89719d03e9c9722fee1b761e4a14bbeeaa193712
[ardour.git] / libs / surfaces / mackie / mackie_control_protocol.cc
1 /*
2         Copyright (C) 2006,2007 John Anderson
3         Copyright (C) 2012 Paul Davis
4
5         This program is free software; you can redistribute it and/or modify
6         it under the terms of the GNU General Public License as published by
7         the Free Software Foundation; either version 2 of the License, or
8         (at your option) any later version.
9
10         This program is distributed in the hope that it will be useful,
11         but WITHOUT ANY WARRANTY; without even the implied warranty of
12         MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13         GNU General Public License for more details.
14
15         You should have received a copy of the GNU General Public License
16         along with this program; if not, write to the Free Software
17         Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
18 */
19
20 #include <fcntl.h>
21 #include <iostream>
22 #include <algorithm>
23 #include <cmath>
24 #include <sstream>
25 #include <vector>
26 #include <iomanip>
27
28 #include <inttypes.h>
29 #include <float.h>
30 #include <sys/time.h>
31 #include <errno.h>
32
33 #include <boost/shared_array.hpp>
34 #include <glibmm/miscutils.h>
35
36 #include "midi++/types.h"
37 #include "midi++/port.h"
38 #include "midi++/ipmidi_port.h"
39 #include "pbd/pthread_utils.h"
40 #include "pbd/error.h"
41 #include "pbd/memento_command.h"
42 #include "pbd/convert.h"
43
44 #include "ardour/audio_track.h"
45 #include "ardour/automation_control.h"
46 #include "ardour/async_midi_port.h"
47 #include "ardour/dB.h"
48 #include "ardour/debug.h"
49 #include "ardour/location.h"
50 #include "ardour/meter.h"
51 #include "ardour/midi_track.h"
52 #include "ardour/panner.h"
53 #include "ardour/panner_shell.h"
54 #include "ardour/profile.h"
55 #include "ardour/record_enable_control.h"
56 #include "ardour/route.h"
57 #include "ardour/route_group.h"
58 #include "ardour/session.h"
59 #include "ardour/tempo.h"
60 #include "ardour/track.h"
61 #include "ardour/types.h"
62 #include "ardour/audioengine.h"
63 #include "ardour/vca_manager.h"
64
65 #include "mackie_control_protocol.h"
66
67 #include "midi_byte_array.h"
68 #include "mackie_control_exception.h"
69 #include "device_profile.h"
70 #include "surface_port.h"
71 #include "surface.h"
72 #include "strip.h"
73 #include "control_group.h"
74 #include "meter.h"
75 #include "button.h"
76 #include "fader.h"
77 #include "pot.h"
78
79 using namespace ARDOUR;
80 using namespace std;
81 using namespace PBD;
82 using namespace Glib;
83 using namespace ArdourSurface;
84 using namespace Mackie;
85
86 #include "i18n.h"
87
88 #include "pbd/abstract_ui.cc" // instantiate template
89
90 const int MackieControlProtocol::MODIFIER_OPTION = 0x1;
91 const int MackieControlProtocol::MODIFIER_CONTROL = 0x2;
92 const int MackieControlProtocol::MODIFIER_SHIFT = 0x4;
93 const int MackieControlProtocol::MODIFIER_CMDALT = 0x8;
94 const int MackieControlProtocol::MODIFIER_ZOOM = 0x10;
95 const int MackieControlProtocol::MODIFIER_SCRUB = 0x20;
96 const int MackieControlProtocol::MODIFIER_MARKER = 0x40;
97 const int MackieControlProtocol::MODIFIER_NUDGE = 0x80;
98 const int MackieControlProtocol::MAIN_MODIFIER_MASK = (MackieControlProtocol::MODIFIER_OPTION|
99                                                        MackieControlProtocol::MODIFIER_CONTROL|
100                                                        MackieControlProtocol::MODIFIER_SHIFT|
101                                                        MackieControlProtocol::MODIFIER_CMDALT);
102
103 MackieControlProtocol* MackieControlProtocol::_instance = 0;
104
105 bool MackieControlProtocol::probe()
106 {
107         return true;
108 }
109
110 MackieControlProtocol::MackieControlProtocol (Session& session)
111         : ControlProtocol (session, X_("Mackie"))
112         , AbstractUI<MackieControlUIRequest> (name())
113         , _current_initial_bank (0)
114         , _frame_last (0)
115         , _timecode_type (ARDOUR::AnyTime::BBT)
116         , _gui (0)
117         , _scrub_mode (false)
118         , _flip_mode (Normal)
119         , _view_mode (Mixer)
120         , _subview_mode (None)
121         , _current_selected_track (-1)
122         , _modifier_state (0)
123         , _ipmidi_base (MIDI::IPMIDIPort::lowest_ipmidi_port_default)
124         , needs_ipmidi_restart (false)
125         , _metering_active (true)
126         , _initialized (false)
127         , configuration_state (0)
128         , state_version (0)
129         , marker_modifier_consumed_by_button (false)
130         , nudge_modifier_consumed_by_button (false)
131 {
132         DEBUG_TRACE (DEBUG::MackieControl, "MackieControlProtocol::MackieControlProtocol\n");
133
134         DeviceInfo::reload_device_info ();
135         DeviceProfile::reload_device_profiles ();
136
137         for (int i = 0; i < 9; i++) {
138                 _last_bank[i] = 0;
139         }
140
141         StripableSelectionChanged.connect (gui_connections, MISSING_INVALIDATOR, boost::bind (&MackieControlProtocol::gui_track_selection_changed, this, _1, true), this);
142         PresentationInfo::Change.connect (gui_connections, MISSING_INVALIDATOR, boost::bind (&MackieControlProtocol::notify_presentation_info_changed, this), this);
143
144         _instance = this;
145
146         build_button_map ();
147 }
148
149 MackieControlProtocol::~MackieControlProtocol()
150 {
151         DEBUG_TRACE (DEBUG::MackieControl, "MackieControlProtocol::~MackieControlProtocol init\n");
152
153         for (Surfaces::const_iterator si = surfaces.begin(); si != surfaces.end(); ++si) {
154                 (*si)->reset ();
155         }
156
157         DEBUG_TRACE (DEBUG::MackieControl, "MackieControlProtocol::~MackieControlProtocol drop_connections ()\n");
158         drop_connections ();
159
160         DEBUG_TRACE (DEBUG::MackieControl, "MackieControlProtocol::~MackieControlProtocol tear_down_gui ()\n");
161         tear_down_gui ();
162
163         delete configuration_state;
164
165         /* stop event loop */
166         DEBUG_TRACE (DEBUG::MackieControl, "MackieControlProtocol::~MackieControlProtocol BaseUI::quit ()\n");
167         BaseUI::quit ();
168
169         try {
170                 DEBUG_TRACE (DEBUG::MackieControl, "MackieControlProtocol::~MackieControlProtocol close()\n");
171                 close();
172         }
173         catch (exception & e) {
174                 cout << "~MackieControlProtocol caught " << e.what() << endl;
175         }
176         catch (...) {
177                 cout << "~MackieControlProtocol caught unknown" << endl;
178         }
179
180         _instance = 0;
181
182         DEBUG_TRACE (DEBUG::MackieControl, "MackieControlProtocol::~MackieControlProtocol done\n");
183 }
184
185 void
186 MackieControlProtocol::thread_init ()
187 {
188         struct sched_param rtparam;
189
190         pthread_set_name (event_loop_name().c_str());
191
192         PBD::notify_event_loops_about_thread_creation (pthread_self(), event_loop_name(), 2048);
193         ARDOUR::SessionEvent::create_per_thread_pool (event_loop_name(), 128);
194
195         memset (&rtparam, 0, sizeof (rtparam));
196         rtparam.sched_priority = 9; /* XXX should be relative to audio (JACK) thread */
197
198         if (pthread_setschedparam (pthread_self(), SCHED_FIFO, &rtparam) != 0) {
199                 // do we care? not particularly.
200         }
201 }
202
203 void
204 MackieControlProtocol::ping_devices ()
205 {
206         /* should not be called if surfaces are not connected, but will not
207          * malfunction if it is.
208          */
209
210         for (Surfaces::const_iterator si = surfaces.begin(); si != surfaces.end(); ++si) {
211                 (*si)->connected ();
212         }
213 }
214
215 // go to the previous track.
216 void
217 MackieControlProtocol::prev_track()
218 {
219         if (_current_initial_bank >= 1) {
220                 switch_banks (_current_initial_bank - 1);
221         }
222 }
223
224 // go to the next track.
225 void
226 MackieControlProtocol::next_track()
227 {
228         Sorted sorted = get_sorted_stripables();
229         if (_current_initial_bank + n_strips() < sorted.size()) {
230                 switch_banks (_current_initial_bank + 1);
231         }
232 }
233
234 bool
235 MackieControlProtocol::stripable_is_locked_to_strip (boost::shared_ptr<Stripable> r) const
236 {
237         for (Surfaces::const_iterator si = surfaces.begin(); si != surfaces.end(); ++si) {
238                 if ((*si)->stripable_is_locked_to_strip (r)) {
239                         return true;
240                 }
241         }
242         return false;
243 }
244
245 // predicate for sort call in get_sorted_stripables
246 struct StripableByPresentationOrder
247 {
248         bool operator () (const boost::shared_ptr<Stripable> & a, const boost::shared_ptr<Stripable> & b) const
249         {
250                 return a->presentation_info() < b->presentation_info();
251         }
252
253         bool operator () (const Stripable & a, const Stripable & b) const
254         {
255                 return a.presentation_info() < b.presentation_info();
256         }
257
258         bool operator () (const Stripable * a, const Stripable * b) const
259         {
260                 return a->presentation_info() < b->presentation_info();
261         }
262 };
263
264 MackieControlProtocol::Sorted
265 MackieControlProtocol::get_sorted_stripables()
266 {
267         Sorted sorted;
268
269         // fetch all stripables
270         StripableList stripables;
271
272         session->get_stripables (stripables);
273
274         // sort in presentation order, and exclude master, control and hidden stripables
275         // and any stripables that are already set.
276
277         for (StripableList::iterator it = stripables.begin(); it != stripables.end(); ++it) {
278
279                 boost::shared_ptr<Stripable> s = *it;
280
281                 if (s->presentation_info().special()) {
282                         continue;
283                 }
284
285                 /* don't include locked routes */
286
287                 if (stripable_is_locked_to_strip (s)) {
288                         continue;
289                 }
290
291                 switch (_view_mode) {
292                 case Mixer:
293                         if (!is_hidden (s)) {
294                                 sorted.push_back (s);
295                         }
296                         break;
297                 case AudioTracks:
298                         if (is_audio_track(s) && !is_hidden(s)) {
299                                 sorted.push_back (s);
300                         }
301                         break;
302                 case Busses:
303                         if (Profile->get_mixbus()) {
304 #ifdef MIXBUS
305                                 if (s->mixbus()) {
306                                         sorted.push_back (s);
307                                 }
308 #endif
309                         } else {
310                                 if (!is_track(s) && !is_hidden(s)) {
311                                         sorted.push_back (s);
312                                 }
313                         }
314                         break;
315                 case MidiTracks:
316                         if (is_midi_track(s) && !is_hidden(s)) {
317                                 sorted.push_back (s);
318                         }
319                         break;
320                 case Plugins:
321                         break;
322                 case Auxes: // in ardour, for now aux and buss are same. for mixbus, "Busses" are mixbuses, "Auxes" are ardour buses
323 #ifdef MIXBUS
324                         if (!s->mixbus() && !is_track() && !is_hidden(s))
325 #else
326                         if (!is_track(s) && !is_hidden(s))
327 #endif
328                         {
329                                 sorted.push_back (s);
330                         }
331                         break;
332                 case Hidden: // Show all the tracks we have hidden
333                         if (is_hidden(s)) {
334                                 // maybe separate groups
335                                 sorted.push_back (s);
336                         }
337                         break;
338                 case Selected: // For example: a group (this is USER)
339                         if (selected(s) && !is_hidden(s)) {
340                                 sorted.push_back (s);
341                         }
342                         break;
343                 }
344         }
345
346         sort (sorted.begin(), sorted.end(), StripableByPresentationOrder());
347         return sorted;
348 }
349
350 void
351 MackieControlProtocol::refresh_current_bank()
352 {
353         switch_banks (_current_initial_bank, true);
354 }
355
356 uint32_t
357 MackieControlProtocol::n_strips (bool with_locked_strips) const
358 {
359         uint32_t strip_count = 0;
360
361         for (Surfaces::const_iterator si = surfaces.begin(); si != surfaces.end(); ++si) {
362                 strip_count += (*si)->n_strips (with_locked_strips);
363         }
364
365         return strip_count;
366 }
367
368 int
369 MackieControlProtocol::switch_banks (uint32_t initial, bool force)
370 {
371         DEBUG_TRACE (DEBUG::MackieControl, string_compose ("switch banking to start at %1 force ? %2 current = %3\n", initial, force, _current_initial_bank));
372
373         if (initial == _current_initial_bank && !force) {
374                 /* everything is as it should be */
375                 return 0;
376         }
377
378         Sorted sorted = get_sorted_stripables();
379         uint32_t strip_cnt = n_strips (false); // do not include locked strips
380                                                // in this count
381
382         if (initial >= sorted.size() && !force) {
383                 DEBUG_TRACE (DEBUG::MackieControl, string_compose ("bank target %1 exceeds route range %2\n",
384                                                                    _current_initial_bank, sorted.size()));
385                 /* too high, we can't get there */
386                 return -1;
387         }
388
389         if (sorted.size() <= strip_cnt && _current_initial_bank == 0 && !force) {
390                 /* no banking - not enough stripables to fill all strips and we're
391                  * not at the first one.
392                  */
393                 DEBUG_TRACE (DEBUG::MackieControl, string_compose ("less routes (%1) than strips (%2) and we're at the end already (%3)\n",
394                                                                    sorted.size(), strip_cnt, _current_initial_bank));
395                 return -1;
396         }
397
398         _current_initial_bank = initial;
399         _current_selected_track = -1;
400
401         // Map current bank of stripables onto each surface(+strip)
402
403         if (_current_initial_bank < sorted.size()) {
404
405                 DEBUG_TRACE (DEBUG::MackieControl, string_compose ("switch to %1, %2, available stripables %3 on %4 surfaces\n",
406                                                                    _current_initial_bank, strip_cnt, sorted.size(),
407                                                                    surfaces.size()));
408
409                 // link stripables to strips
410
411                 Sorted::iterator r = sorted.begin() + _current_initial_bank;
412
413                 for (Surfaces::iterator si = surfaces.begin(); si != surfaces.end(); ++si) {
414                         vector<boost::shared_ptr<Stripable> > stripables;
415                         uint32_t added = 0;
416
417                         DEBUG_TRACE (DEBUG::MackieControl, string_compose ("surface has %1 unlocked strips\n", (*si)->n_strips (false)));
418
419                         for (; r != sorted.end() && added < (*si)->n_strips (false); ++r, ++added) {
420                                 stripables.push_back (*r);
421                         }
422
423                         DEBUG_TRACE (DEBUG::MackieControl, string_compose ("give surface %1 stripables\n", stripables.size()));
424
425                         (*si)->map_stripables (stripables);
426                 }
427
428         } else {
429                 /* all strips need to be reset */
430                 DEBUG_TRACE (DEBUG::MackieControl, string_compose ("clear all strips, bank target %1  is outside route range %2\n",
431                                                                    _current_initial_bank, sorted.size()));
432                 for (Surfaces::iterator si = surfaces.begin(); si != surfaces.end(); ++si) {
433                         vector<boost::shared_ptr<Stripable> > stripables;
434                         /* pass in an empty stripables list, so that all strips will be reset */
435                         (*si)->map_stripables (stripables);
436                 }
437                 return -1;
438         }
439
440         /* make sure selection is correct */
441
442         _gui_track_selection_changed (&_last_selected_stripables, false, false);
443
444         /* current bank has not been saved */
445         session->set_dirty();
446
447         return 0;
448 }
449
450 int
451 MackieControlProtocol::set_active (bool yn)
452 {
453         DEBUG_TRACE (DEBUG::MackieControl, string_compose("MackieControlProtocol::set_active init with yn: '%1'\n", yn));
454
455         if (yn == active()) {
456                 return 0;
457         }
458
459         if (yn) {
460
461                 /* start event loop */
462
463                 BaseUI::run ();
464
465                 connect_session_signals ();
466
467                 if (!_device_info.name().empty()) {
468                         set_device (_device_info.name(), true);
469                 }
470
471                 /* set up periodic task for timecode display and metering and automation
472                  */
473
474                 Glib::RefPtr<Glib::TimeoutSource> periodic_timeout = Glib::TimeoutSource::create (100); // milliseconds
475                 periodic_connection = periodic_timeout->connect (sigc::mem_fun (*this, &MackieControlProtocol::periodic));
476                 periodic_timeout->attach (main_loop()->get_context());
477
478                 /* periodic task used to update strip displays */
479
480                 Glib::RefPtr<Glib::TimeoutSource> redisplay_timeout = Glib::TimeoutSource::create (10); // milliseconds
481                 redisplay_connection = redisplay_timeout->connect (sigc::mem_fun (*this, &MackieControlProtocol::redisplay));
482                 redisplay_timeout->attach (main_loop()->get_context());
483
484         } else {
485
486                 BaseUI::quit ();
487                 close ();
488
489         }
490
491         ControlProtocol::set_active (yn);
492
493         DEBUG_TRACE (DEBUG::MackieControl, string_compose("MackieControlProtocol::set_active done with yn: '%1'\n", yn));
494
495         return 0;
496 }
497
498 bool
499 MackieControlProtocol::hui_heartbeat ()
500 {
501         Glib::Threads::Mutex::Lock lm (surfaces_lock);
502
503         for (Surfaces::iterator s = surfaces.begin(); s != surfaces.end(); ++s) {
504                 (*s)->hui_heartbeat ();
505         }
506
507         return true;
508 }
509
510 bool
511 MackieControlProtocol::periodic ()
512 {
513         if (!active()) {
514                 return false;
515         }
516
517         if (!_initialized) {
518                 /* wait for higher-frequency redisplay() callback to initialize
519                  * us
520                  */
521                 return true;
522         }
523
524         update_timecode_display ();
525
526         ARDOUR::microseconds_t now_usecs = ARDOUR::get_microseconds ();
527
528         {
529                 Glib::Threads::Mutex::Lock lm (surfaces_lock);
530
531                 for (Surfaces::iterator s = surfaces.begin(); s != surfaces.end(); ++s) {
532                         (*s)->periodic (now_usecs);
533                 }
534         }
535
536         return true;
537 }
538
539 bool
540 MackieControlProtocol::redisplay ()
541 {
542         if (!active()) {
543                 return false;
544         }
545
546         if (needs_ipmidi_restart) {
547                 ipmidi_restart ();
548                 return true;
549         }
550
551         if (!_initialized) {
552                 initialize();
553         }
554
555         ARDOUR::microseconds_t now = ARDOUR::get_microseconds ();
556
557         {
558                 Glib::Threads::Mutex::Lock lm (surfaces_lock);
559
560                 for (Surfaces::iterator s = surfaces.begin(); s != surfaces.end(); ++s) {
561                         (*s)->redisplay (now, false);
562                 }
563         }
564
565         return true;
566 }
567
568 void
569 MackieControlProtocol::update_timecode_beats_led()
570 {
571         if (!_device_info.has_timecode_display()) {
572                 return;
573         }
574
575         DEBUG_TRACE (DEBUG::MackieControl, string_compose("MackieControlProtocol::update_timecode_beats_led(): %1\n", _timecode_type));
576         switch (_timecode_type) {
577                 case ARDOUR::AnyTime::BBT:
578                         update_global_led (Led::Beats, on);
579                         update_global_led (Led::Timecode, off);
580                         break;
581                 case ARDOUR::AnyTime::Timecode:
582                         update_global_led (Led::Timecode, on);
583                         update_global_led (Led::Beats, off);
584                         break;
585                 default:
586                         ostringstream os;
587                         os << "Unknown Anytime::Type " << _timecode_type;
588                         throw runtime_error (os.str());
589         }
590 }
591
592 void
593 MackieControlProtocol::update_global_button (int id, LedState ls)
594 {
595         boost::shared_ptr<Surface> surface;
596
597         {
598                 Glib::Threads::Mutex::Lock lm (surfaces_lock);
599
600                 if (surfaces.empty()) {
601                         return;
602                 }
603
604                 if (!_device_info.has_global_controls()) {
605                         return;
606                 }
607                 // surface needs to be master surface
608                 surface = _master_surface;
609         }
610
611         map<int,Control*>::iterator x = surface->controls_by_device_independent_id.find (id);
612         if (x != surface->controls_by_device_independent_id.end()) {
613                 Button * button = dynamic_cast<Button*> (x->second);
614                 surface->write (button->set_state (ls));
615         } else {
616                 DEBUG_TRACE (DEBUG::MackieControl, string_compose ("Button %1 not found\n", id));
617         }
618 }
619
620 void
621 MackieControlProtocol::update_global_led (int id, LedState ls)
622 {
623         Glib::Threads::Mutex::Lock lm (surfaces_lock);
624
625         if (surfaces.empty()) {
626                 return;
627         }
628
629         if (!_device_info.has_global_controls()) {
630                 return;
631         }
632         boost::shared_ptr<Surface> surface = _master_surface;
633
634         map<int,Control*>::iterator x = surface->controls_by_device_independent_id.find (id);
635
636         if (x != surface->controls_by_device_independent_id.end()) {
637                 Led * led = dynamic_cast<Led*> (x->second);
638                 DEBUG_TRACE (DEBUG::MackieControl, "Writing LedState\n");
639                 surface->write (led->set_state (ls));
640         } else {
641                 DEBUG_TRACE (DEBUG::MackieControl, string_compose ("Led %1 not found\n", id));
642         }
643 }
644
645 void
646 MackieControlProtocol::device_ready ()
647 {
648         DEBUG_TRACE (DEBUG::MackieControl, string_compose ("device ready init (active=%1)\n", active()));
649         update_surfaces ();
650         set_subview_mode (MackieControlProtocol::None, boost::shared_ptr<Stripable>());
651         set_flip_mode (Normal);
652 }
653
654 // send messages to surface to set controls to correct values
655 void
656 MackieControlProtocol::update_surfaces()
657 {
658         DEBUG_TRACE (DEBUG::MackieControl, string_compose ("MackieControlProtocol::update_surfaces() init (active=%1)\n", active()));
659         if (!active()) {
660                 return;
661         }
662
663         // do the initial bank switch to connect signals
664         // _current_initial_bank is initialised by set_state
665         (void) switch_banks (_current_initial_bank, true);
666
667         DEBUG_TRACE (DEBUG::MackieControl, "MackieControlProtocol::update_surfaces() finished\n");
668 }
669
670 void
671 MackieControlProtocol::initialize()
672 {
673         {
674                 Glib::Threads::Mutex::Lock lm (surfaces_lock);
675
676                 if (surfaces.empty()) {
677                         return;
678                 }
679
680                 if (!_master_surface->active ()) {
681                         return;
682                 }
683
684                 // sometimes the jog wheel is a pot
685                 if (_device_info.has_jog_wheel()) {
686                         _master_surface->blank_jog_ring ();
687                 }
688         }
689
690         // update global buttons and displays
691
692         notify_record_state_changed();
693         notify_transport_state_changed();
694         update_timecode_beats_led();
695
696         _initialized = true;
697 }
698
699 void
700 MackieControlProtocol::connect_session_signals()
701 {
702         // receive routes added
703         session->RouteAdded.connect(session_connections, MISSING_INVALIDATOR, boost::bind (&MackieControlProtocol::notify_routes_added, this, _1), this);
704         // receive VCAs added
705         session->vca_manager().VCAAdded.connect(session_connections, MISSING_INVALIDATOR, boost::bind (&MackieControlProtocol::notify_vca_added, this, _1), this);
706
707         // receive record state toggled
708         session->RecordStateChanged.connect(session_connections, MISSING_INVALIDATOR, boost::bind (&MackieControlProtocol::notify_record_state_changed, this), this);
709         // receive transport state changed
710         session->TransportStateChange.connect(session_connections, MISSING_INVALIDATOR, boost::bind (&MackieControlProtocol::notify_transport_state_changed, this), this);
711         session->TransportLooped.connect (session_connections, MISSING_INVALIDATOR, boost::bind (&MackieControlProtocol::notify_loop_state_changed, this), this);
712         // receive punch-in and punch-out
713         Config->ParameterChanged.connect(session_connections, MISSING_INVALIDATOR, boost::bind (&MackieControlProtocol::notify_parameter_changed, this, _1), this);
714         session->config.ParameterChanged.connect (session_connections, MISSING_INVALIDATOR, boost::bind (&MackieControlProtocol::notify_parameter_changed, this, _1), this);
715         // receive rude solo changed
716         session->SoloActive.connect(session_connections, MISSING_INVALIDATOR, boost::bind (&MackieControlProtocol::notify_solo_active_changed, this, _1), this);
717
718         // make sure remote id changed signals reach here
719         // see also notify_stripable_added
720         Sorted sorted = get_sorted_stripables();
721 }
722
723 void
724 MackieControlProtocol::set_profile (const string& profile_name)
725 {
726         map<string,DeviceProfile>::iterator d = DeviceProfile::device_profiles.find (profile_name);
727
728         if (d == DeviceProfile::device_profiles.end()) {
729                 _device_profile = DeviceProfile (profile_name);
730                 return;
731         }
732
733         _device_profile = d->second;
734 }
735
736 int
737 MackieControlProtocol::set_device_info (const string& device_name)
738 {
739         map<string,DeviceInfo>::iterator d = DeviceInfo::device_info.find (device_name);
740
741         DEBUG_TRACE (DEBUG::MackieControl, string_compose ("new device chosen %1\n", device_name));
742
743         if (d == DeviceInfo::device_info.end()) {
744                 return -1;
745         }
746
747         _device_info = d->second;
748
749         return 0;
750 }
751
752 int
753 MackieControlProtocol::set_device (const string& device_name, bool force)
754 {
755         if (device_name == device_info().name() && !force) {
756                 /* already using that device, nothing to do */
757                 return 0;
758         }
759         /* get state from the current setup, and make sure it is stored in
760            the configuration_states node so that if we switch back to this device,
761            we will have its state available.
762         */
763
764         {
765                 Glib::Threads::Mutex::Lock lm (surfaces_lock);
766                 if (!surfaces.empty()) {
767                         update_configuration_state ();
768                 }
769         }
770
771         if (set_device_info (device_name)) {
772                 return -1;
773         }
774
775         clear_surfaces ();
776         port_connection.disconnect ();
777         hui_connection.disconnect ();
778
779         if (_device_info.device_type() == DeviceInfo::HUI) {
780                 Glib::RefPtr<Glib::TimeoutSource> hui_timeout = Glib::TimeoutSource::create (1000); // milliseconds
781                 hui_connection = hui_timeout->connect (sigc::mem_fun (*this, &MackieControlProtocol::hui_heartbeat));
782                 hui_timeout->attach (main_loop()->get_context());
783         }
784
785         if (!_device_info.uses_ipmidi()) {
786                 /* notice that the handler for this will execute in our event
787                    loop, not in the thread where the
788                    PortConnectedOrDisconnected signal is emitted.
789                 */
790                 ARDOUR::AudioEngine::instance()->PortConnectedOrDisconnected.connect (port_connection, MISSING_INVALIDATOR, boost::bind (&MackieControlProtocol::connection_handler, this, _1, _2, _3, _4, _5), this);
791         }
792
793         if (create_surfaces ()) {
794                 return -1;
795         }
796
797         DeviceChanged ();
798
799         return 0;
800 }
801
802 gboolean
803 ArdourSurface::ipmidi_input_handler (GIOChannel*, GIOCondition condition, void *data)
804 {
805         ArdourSurface::MackieControlProtocol::ipMIDIHandler* ipm = static_cast<ArdourSurface::MackieControlProtocol::ipMIDIHandler*>(data);
806         return ipm->mcp->midi_input_handler (Glib::IOCondition (condition), ipm->port);
807 }
808
809 int
810 MackieControlProtocol::create_surfaces ()
811 {
812         string device_name;
813         surface_type_t stype = mcu; // type not yet determined
814
815         DEBUG_TRACE (DEBUG::MackieControl, string_compose ("Create %1 surfaces for %2\n", 1 + _device_info.extenders(), _device_info.name()));
816
817         if (!_device_info.uses_ipmidi()) {
818                 _input_bundle.reset (new ARDOUR::Bundle (_("Mackie Control In"), true));
819                 _output_bundle.reset (new ARDOUR::Bundle (_("Mackie Control Out"), false));
820         } else {
821                 _input_bundle.reset ();
822                 _output_bundle.reset ();
823
824         }
825         for (uint32_t n = 0; n < 1 + _device_info.extenders(); ++n) {
826                 bool is_master = false;
827
828                 if (n == _device_info.master_position()) {
829                         is_master = true;
830                         if (_device_info.extenders() == 0) {
831                                 device_name = _device_info.name();
832                         } else {
833                                 device_name = X_("mackie control");
834                         }
835
836                 }
837
838                 if (!is_master) {
839                         device_name = string_compose (X_("mackie control ext %1"), n+1);
840                 }
841
842                 DEBUG_TRACE (DEBUG::MackieControl, string_compose ("Port Name for surface %1 is %2\n", n, device_name));
843
844                 boost::shared_ptr<Surface> surface;
845
846                 if (is_master) {
847                         stype = mcu;
848                 } else {
849                         stype = ext;
850                 }
851                 try {
852                         surface.reset (new Surface (*this, device_name, n, stype));
853                 } catch (...) {
854                         return -1;
855                 }
856
857                 if (is_master) {
858                         _master_surface = surface;
859                 }
860
861                 if (configuration_state) {
862                         XMLNode* this_device = 0;
863                         XMLNodeList const& devices = configuration_state->children();
864                         for (XMLNodeList::const_iterator d = devices.begin(); d != devices.end(); ++d) {
865                                 XMLProperty const * prop = (*d)->property (X_("name"));
866                                 if (prop && prop->value() == _device_info.name()) {
867                                         this_device = *d;
868                                         break;
869                                 }
870                         }
871                         if (this_device) {
872                                 XMLNode* snode = this_device->child (X_("Surfaces"));
873                                 if (snode) {
874                                         surface->set_state (*snode, state_version);
875                                 }
876                         }
877                 }
878
879                 {
880                         Glib::Threads::Mutex::Lock lm (surfaces_lock);
881                         surfaces.push_back (surface);
882                 }
883
884                 if (!_device_info.uses_ipmidi()) {
885
886                         _input_bundle->add_channel (
887                                 surface->port().input_port().name(),
888                                 ARDOUR::DataType::MIDI,
889                                 session->engine().make_port_name_non_relative (surface->port().input_port().name())
890                                 );
891
892                         _output_bundle->add_channel (
893                                 surface->port().output_port().name(),
894                                 ARDOUR::DataType::MIDI,
895                                 session->engine().make_port_name_non_relative (surface->port().output_port().name())
896                                 );
897                 }
898
899                 MIDI::Port& input_port (surface->port().input_port());
900                 AsyncMIDIPort* asp = dynamic_cast<AsyncMIDIPort*> (&input_port);
901
902                 if (asp) {
903
904                         /* async MIDI port */
905
906                         asp->xthread().set_receive_handler (sigc::bind (sigc::mem_fun (this, &MackieControlProtocol::midi_input_handler), &input_port));
907                         asp->xthread().attach (main_loop()->get_context());
908
909                 } else {
910
911                         /* ipMIDI port, no IOSource method at this time */
912
913                         int fd;
914
915                         if ((fd = input_port.selectable ()) >= 0) {
916
917                                 GIOChannel* ioc = g_io_channel_unix_new (fd);
918                                 surface->input_source = g_io_create_watch (ioc, GIOCondition (G_IO_IN|G_IO_HUP|G_IO_ERR));
919
920                                 /* make surface's input source now hold the
921                                  * only reference on the IO channel
922                                  */
923                                 g_io_channel_unref (ioc);
924
925                                 /* hack up an object so that in the callback from the event loop
926                                    we have both the MackieControlProtocol and the input port.
927
928                                    If we were using C++ for this stuff we wouldn't need this
929                                    but a nasty, not-fixable bug in the binding between C
930                                    and C++ makes it necessary to avoid C++ for the IO
931                                    callback setup.
932                                 */
933
934                                 ipMIDIHandler* ipm = new ipMIDIHandler (); /* we will leak this sizeof(pointer)*2 sized object */
935                                 ipm->mcp = this;
936                                 ipm->port = &input_port;
937
938                                 g_source_set_callback (surface->input_source, (GSourceFunc) ipmidi_input_handler, ipm, NULL);
939                                 g_source_attach (surface->input_source, main_loop()->get_context()->gobj());
940                         }
941                 }
942         }
943
944         if (!_device_info.uses_ipmidi()) {
945                 Glib::Threads::Mutex::Lock lm (surfaces_lock);
946                 for (Surfaces::iterator s = surfaces.begin(); s != surfaces.end(); ++s) {
947                         (*s)->port().reconnect ();
948                 }
949         }
950
951         session->BundleAddedOrRemoved ();
952
953         assert (_master_surface);
954
955         return 0;
956 }
957
958 void
959 MackieControlProtocol::close()
960 {
961         port_connection.disconnect ();
962         session_connections.drop_connections ();
963         stripable_connections.drop_connections ();
964         periodic_connection.disconnect ();
965
966         clear_surfaces();
967 }
968
969 /** Ensure that the configuration_state XML node contains an up-to-date
970  *  copy of the state node the current device. If configuration_state already
971  *  contains a state node for the device, it will deleted and replaced.
972  */
973 void
974 MackieControlProtocol::update_configuration_state ()
975 {
976         /* CALLER MUST HOLD SURFACES LOCK */
977
978         if (!configuration_state) {
979                 configuration_state = new XMLNode (X_("Configurations"));
980         }
981
982         XMLNode* devnode = new XMLNode (X_("Configuration"));
983         devnode->add_property (X_("name"), _device_info.name());
984
985         configuration_state->remove_nodes_and_delete (X_("name"), _device_info.name());
986         configuration_state->add_child_nocopy (*devnode);
987
988         XMLNode* snode = new XMLNode (X_("Surfaces"));
989
990         for (Surfaces::iterator s = surfaces.begin(); s != surfaces.end(); ++s) {
991                 snode->add_child_nocopy ((*s)->get_state());
992         }
993
994         devnode->add_child_nocopy (*snode);
995 }
996
997 XMLNode&
998 MackieControlProtocol::get_state()
999 {
1000         XMLNode& node (ControlProtocol::get_state());
1001
1002         DEBUG_TRACE (DEBUG::MackieControl, "MackieControlProtocol::get_state init\n");
1003         char buf[16];
1004
1005         // add current bank
1006         snprintf (buf, sizeof (buf), "%d", _current_initial_bank);
1007         node.add_property (X_("bank"), buf);
1008
1009         // ipMIDI base port (possibly not used)
1010         snprintf (buf, sizeof (buf), "%d", _ipmidi_base);
1011         node.add_property (X_("ipmidi-base"), buf);
1012
1013         node.add_property (X_("device-profile"), _device_profile.name());
1014         node.add_property (X_("device-name"), _device_info.name());
1015
1016         {
1017                 Glib::Threads::Mutex::Lock lm (surfaces_lock);
1018                 update_configuration_state ();
1019         }
1020
1021         /* force a copy of the _surfaces_state node, because we want to retain ownership */
1022         node.add_child_copy (*configuration_state);
1023
1024         DEBUG_TRACE (DEBUG::MackieControl, "MackieControlProtocol::get_state done\n");
1025
1026         return node;
1027 }
1028
1029 bool
1030 MackieControlProtocol::profile_exists (string const & name) const
1031 {
1032         return DeviceProfile::device_profiles.find (name) != DeviceProfile::device_profiles.end();
1033 }
1034
1035 int
1036 MackieControlProtocol::set_state (const XMLNode & node, int version)
1037 {
1038         DEBUG_TRACE (DEBUG::MackieControl, string_compose ("MackieControlProtocol::set_state: active %1\n", active()));
1039
1040         int retval = 0;
1041         const XMLProperty* prop;
1042         uint32_t bank = 0;
1043
1044         if (ControlProtocol::set_state (node, version)) {
1045                 return -1;
1046         }
1047
1048         if ((prop = node.property (X_("ipmidi-base"))) != 0) {
1049                 set_ipmidi_base (atoi (prop->value()));
1050         }
1051
1052         // fetch current bank
1053         if ((prop = node.property (X_("bank"))) != 0) {
1054                 bank = atoi (prop->value());
1055         }
1056
1057         if ((prop = node.property (X_("device-name"))) != 0) {
1058                 set_device_info (prop->value());
1059         }
1060
1061         if ((prop = node.property (X_("device-profile"))) != 0) {
1062                 if (prop->value().empty()) {
1063                         string default_profile_name;
1064
1065                         /* start by looking for a user-edited profile for the current device name */
1066
1067                         default_profile_name = DeviceProfile::name_when_edited (_device_info.name());
1068
1069                         if (!profile_exists (default_profile_name)) {
1070
1071                                 /* no user-edited profile for this device name, so try the user-edited default profile */
1072
1073                                 default_profile_name = DeviceProfile::name_when_edited (DeviceProfile::default_profile_name);
1074
1075                                 if (!profile_exists (default_profile_name)) {
1076
1077                                         /* no user-edited version, so just try the device name */
1078
1079                                         default_profile_name = _device_info.name();
1080
1081                                         if (!profile_exists (default_profile_name)) {
1082
1083                                                 /* no generic device specific profile, just try the fixed default */
1084                                                 default_profile_name = DeviceProfile::default_profile_name;
1085                                         }
1086                                 }
1087                         }
1088
1089                         set_profile (default_profile_name);
1090
1091                 } else {
1092                         if (profile_exists (prop->value())) {
1093                                 set_profile (prop->value());
1094                         } else {
1095                                 set_profile (DeviceProfile::default_profile_name);
1096                         }
1097                 }
1098         }
1099
1100         XMLNode* dnode = node.child (X_("Configurations"));
1101
1102         delete configuration_state;
1103         configuration_state = 0;
1104
1105         if (dnode) {
1106                 configuration_state = new XMLNode (*dnode);
1107                 state_version = version;
1108         }
1109
1110         (void) switch_banks (bank, true);
1111
1112         DEBUG_TRACE (DEBUG::MackieControl, "MackieControlProtocol::set_state done\n");
1113
1114         return retval;
1115 }
1116
1117 string
1118 MackieControlProtocol::format_bbt_timecode (framepos_t now_frame)
1119 {
1120         Timecode::BBT_Time bbt_time;
1121
1122         session->bbt_time (now_frame, bbt_time);
1123
1124         // The Mackie protocol spec is built around a BBT time display of
1125         //
1126         // digits:     888/88/88/888
1127         // semantics:  BBB/bb/ss/ttt
1128         //
1129         // The third field is "subdivisions" which is a concept found in Logic
1130         // but not present in Ardour. Instead Ardour displays a 4 digit tick
1131         // count, which we need to spread across the 5 digits of ss/ttt.
1132
1133         ostringstream os;
1134
1135         os << setw(3) << setfill('0') << bbt_time.bars;
1136         os << setw(2) << setfill('0') << bbt_time.beats;
1137         os << ' ';
1138         os << setw(1) << setfill('0') << bbt_time.ticks / 1000;
1139         os << setw(3) << setfill('0') << bbt_time.ticks % 1000;
1140
1141         return os.str();
1142 }
1143
1144 string
1145 MackieControlProtocol::format_timecode_timecode (framepos_t now_frame)
1146 {
1147         Timecode::Time timecode;
1148         session->timecode_time (now_frame, timecode);
1149
1150         // According to the Logic docs
1151         // digits: 888/88/88/888
1152         // Timecode mode: Hours/Minutes/Seconds/Frames
1153         ostringstream os;
1154         os << setw(2) << setfill('0') << timecode.hours;
1155         os << ' ';
1156         os << setw(2) << setfill('0') << timecode.minutes;
1157         os << setw(2) << setfill('0') << timecode.seconds;
1158         os << ' ';
1159         os << setw(2) << setfill('0') << timecode.frames;
1160
1161         return os.str();
1162 }
1163
1164 void
1165 MackieControlProtocol::update_timecode_display()
1166 {
1167         Glib::Threads::Mutex::Lock lm (surfaces_lock);
1168
1169         if (surfaces.empty()) {
1170                 return;
1171         }
1172
1173         boost::shared_ptr<Surface> surface = _master_surface;
1174
1175         if (surface->type() != mcu || !_device_info.has_timecode_display() || !surface->active ()) {
1176                 return;
1177         }
1178
1179         // do assignment here so current_frame is fixed
1180         framepos_t current_frame = session->transport_frame();
1181         string timecode;
1182         // For large jumps in play head possition do full reset
1183         int moved = (current_frame - _frame_last) / session->frame_rate ();
1184         if (moved) {
1185                 DEBUG_TRACE (DEBUG::MackieControl, "Timecode reset\n");
1186                 _timecode_last = string (10, ' ');
1187         }
1188         _frame_last = current_frame;
1189
1190         switch (_timecode_type) {
1191         case ARDOUR::AnyTime::BBT:
1192                 timecode = format_bbt_timecode (current_frame);
1193                 break;
1194         case ARDOUR::AnyTime::Timecode:
1195                 timecode = format_timecode_timecode (current_frame);
1196                 break;
1197         default:
1198                 return;
1199         }
1200
1201         // only write the timecode string to the MCU if it's changed
1202         // since last time. This is to reduce midi bandwidth used.
1203         if (timecode != _timecode_last) {
1204                 surface->display_timecode (timecode, _timecode_last);
1205                 _timecode_last = timecode;
1206         }
1207 }
1208
1209 ///////////////////////////////////////////
1210 // Session signals
1211 ///////////////////////////////////////////
1212
1213 void MackieControlProtocol::notify_parameter_changed (std::string const & p)
1214 {
1215         if (p == "punch-in") {
1216                 update_global_button (Button::Drop, session->config.get_punch_in() ? flashing : off);
1217         } else if (p == "punch-out") {
1218                 update_global_button (Button::Replace, session->config.get_punch_out() ? flashing : off);
1219         } else if (p == "clicking") {
1220                 update_global_button (Button::Click, Config->get_clicking());
1221         } else if (p == "follow-edits") {
1222                 /* we can't respond to this at present, because "follow-edits"
1223                  * is  a property of the (G)UI configuration object, to which we
1224                  * have no access. For now, this means that the lit state of
1225                  * this button (if there is one) won't reflect the setting.
1226                  */
1227
1228                 //update_global_button (Button::Enter, session->config.get_follow_edits() ? on : off);
1229         } else if (p == "external-sync") {
1230                 update_global_button (Button::Cancel, session->config.get_external_sync() ? on : off);
1231         } else {
1232                 DEBUG_TRACE (DEBUG::MackieControl, string_compose ("parameter changed: %1\n", p));
1233         }
1234 }
1235
1236 void
1237 MackieControlProtocol::notify_stripable_removed ()
1238 {
1239         Glib::Threads::Mutex::Lock lm (surfaces_lock);
1240         for (Surfaces::iterator s = surfaces.begin(); s != surfaces.end(); ++s) {
1241                 (*s)->master_monitor_may_have_changed ();
1242         }
1243 }
1244
1245 void
1246 MackieControlProtocol::notify_vca_added (ARDOUR::VCAList& vl)
1247 {
1248         refresh_current_bank ();
1249 }
1250
1251 // RouteList is the set of Routes that have just been added
1252 void
1253 MackieControlProtocol::notify_routes_added (ARDOUR::RouteList & rl)
1254 {
1255         {
1256                 Glib::Threads::Mutex::Lock lm (surfaces_lock);
1257
1258                 if (surfaces.empty()) {
1259                         return;
1260                 }
1261         }
1262
1263         /* special case: single route, and it is the monitor or master out */
1264
1265         if (rl.size() == 1 && (rl.front()->is_monitor() || rl.front()->is_master())) {
1266                 Glib::Threads::Mutex::Lock lm (surfaces_lock);
1267                 for (Surfaces::iterator s = surfaces.begin(); s != surfaces.end(); ++s) {
1268                         (*s)->master_monitor_may_have_changed ();
1269                 }
1270         }
1271
1272         // currently assigned banks are less than the full set of
1273         // strips, so activate the new strip now.
1274
1275         refresh_current_bank();
1276
1277         // otherwise route added, but current bank needs no updating
1278 }
1279
1280 void
1281 MackieControlProtocol::notify_solo_active_changed (bool active)
1282 {
1283         boost::shared_ptr<Surface> surface;
1284
1285         {
1286                 Glib::Threads::Mutex::Lock lm (surfaces_lock);
1287
1288                 if (surfaces.empty()) {
1289                         return;
1290                 }
1291
1292                 surface = _master_surface;
1293         }
1294
1295         map<int,Control*>::iterator x = surface->controls_by_device_independent_id.find (Led::RudeSolo);
1296         if (x != surface->controls_by_device_independent_id.end()) {
1297                 Led* rude_solo = dynamic_cast<Led*> (x->second);
1298                 if (rude_solo) {
1299                         surface->write (rude_solo->set_state (active ? flashing : off));
1300                 }
1301         }
1302 }
1303
1304 void
1305 MackieControlProtocol::notify_presentation_info_changed ()
1306 {
1307         {
1308                 Glib::Threads::Mutex::Lock lm (surfaces_lock);
1309
1310                 if (surfaces.empty()) {
1311                         return;
1312                 }
1313         }
1314
1315         Sorted sorted = get_sorted_stripables();
1316         uint32_t sz = n_strips();
1317
1318         // if a remote id has been moved off the end, we need to shift
1319         // the current bank backwards.
1320
1321         if (sorted.size() - _current_initial_bank < sz) {
1322                 // but don't shift backwards past the zeroth channel
1323                 if (sorted.size() < sz) {  // avoid unsigned math mistake below
1324                         (void) switch_banks(0, true);
1325                 } else {
1326                         (void) switch_banks (max((Sorted::size_type) 0, sorted.size() - sz), true);
1327                 }
1328         } else {
1329                 // Otherwise just refresh the current bank
1330                 refresh_current_bank();
1331         }
1332 }
1333
1334 ///////////////////////////////////////////
1335 // Transport signals
1336 ///////////////////////////////////////////
1337
1338 void
1339 MackieControlProtocol::notify_loop_state_changed()
1340 {
1341         update_global_button (Button::Loop, session->get_play_loop());
1342 }
1343
1344 void
1345 MackieControlProtocol::notify_transport_state_changed()
1346 {
1347         if (!_device_info.has_global_controls()) {
1348                 return;
1349         }
1350
1351         // switch various play and stop buttons on / off
1352         update_global_button (Button::Loop, session->get_play_loop());
1353         update_global_button (Button::Play, session->transport_speed() == 1.0);
1354         update_global_button (Button::Stop, session->transport_stopped ());
1355         update_global_button (Button::Rewind, session->transport_speed() < 0.0);
1356         update_global_button (Button::Ffwd, session->transport_speed() > 1.0);
1357
1358         // sometimes a return to start leaves time code at old time
1359         _timecode_last = string (10, ' ');
1360
1361         notify_metering_state_changed ();
1362 }
1363
1364 void
1365 MackieControlProtocol::notify_metering_state_changed()
1366 {
1367         Glib::Threads::Mutex::Lock lm (surfaces_lock);
1368
1369         for (Surfaces::iterator s = surfaces.begin(); s != surfaces.end(); ++s) {
1370                 (*s)->notify_metering_state_changed ();
1371         }
1372 }
1373
1374 void
1375 MackieControlProtocol::notify_record_state_changed ()
1376 {
1377         if (!_device_info.has_global_controls()) {
1378                 return;
1379         }
1380
1381         boost::shared_ptr<Surface> surface;
1382
1383         {
1384                 Glib::Threads::Mutex::Lock lm (surfaces_lock);
1385                 if (surfaces.empty()) {
1386                         return;
1387                 }
1388                 surface = _master_surface;
1389         }
1390
1391         /* rec is a tristate */
1392
1393         map<int,Control*>::iterator x = surface->controls_by_device_independent_id.find (Button::Record);
1394         if (x != surface->controls_by_device_independent_id.end()) {
1395                 Button * rec = dynamic_cast<Button*> (x->second);
1396                 if (rec) {
1397                         LedState ls;
1398
1399                         switch (session->record_status()) {
1400                         case Session::Disabled:
1401                                 DEBUG_TRACE (DEBUG::MackieControl, "record state changed to disabled, LED off\n");
1402                                 ls = off;
1403                                 break;
1404                         case Session::Recording:
1405                                 DEBUG_TRACE (DEBUG::MackieControl, "record state changed to recording, LED on\n");
1406                                 ls = on;
1407                                 break;
1408                         case Session::Enabled:
1409                                 DEBUG_TRACE (DEBUG::MackieControl, "record state changed to enabled, LED flashing\n");
1410                                 ls = flashing;
1411                                 break;
1412                         }
1413
1414                         surface->write (rec->set_state (ls));
1415                 }
1416         }
1417 }
1418
1419 list<boost::shared_ptr<ARDOUR::Bundle> >
1420 MackieControlProtocol::bundles ()
1421 {
1422         list<boost::shared_ptr<ARDOUR::Bundle> > b;
1423
1424         if (_input_bundle) {
1425                 b.push_back (_input_bundle);
1426                 b.push_back (_output_bundle);
1427         }
1428
1429         return b;
1430 }
1431
1432 void
1433 MackieControlProtocol::do_request (MackieControlUIRequest* req)
1434 {
1435         DEBUG_TRACE (DEBUG::MackieControl, string_compose ("doing request type %1\n", req->type));
1436         if (req->type == CallSlot) {
1437
1438                 call_slot (MISSING_INVALIDATOR, req->the_slot);
1439
1440         } else if (req->type == Quit) {
1441
1442                 stop ();
1443         }
1444 }
1445
1446 int
1447 MackieControlProtocol::stop ()
1448 {
1449         BaseUI::quit ();
1450
1451         return 0;
1452 }
1453
1454 void
1455 MackieControlProtocol::update_led (Surface& surface, Button& button, Mackie::LedState ls)
1456 {
1457         if (ls != none) {
1458                 surface.port().write (button.set_state (ls));
1459         }
1460 }
1461
1462 void
1463 MackieControlProtocol::build_button_map ()
1464 {
1465         /* this maps our device-independent button codes to the methods that handle them.
1466          */
1467
1468 #define DEFINE_BUTTON_HANDLER(b,p,r) button_map.insert (pair<Button::ID,ButtonHandlers> ((b), ButtonHandlers ((p),(r))));
1469
1470         DEFINE_BUTTON_HANDLER (Button::Track, &MackieControlProtocol::track_press, &MackieControlProtocol::track_release);
1471         DEFINE_BUTTON_HANDLER (Button::Send, &MackieControlProtocol::send_press, &MackieControlProtocol::send_release);
1472         DEFINE_BUTTON_HANDLER (Button::Pan, &MackieControlProtocol::pan_press, &MackieControlProtocol::pan_release);
1473         DEFINE_BUTTON_HANDLER (Button::Plugin, &MackieControlProtocol::plugin_press, &MackieControlProtocol::plugin_release);
1474         DEFINE_BUTTON_HANDLER (Button::Eq, &MackieControlProtocol::eq_press, &MackieControlProtocol::eq_release);
1475         DEFINE_BUTTON_HANDLER (Button::Dyn, &MackieControlProtocol::dyn_press, &MackieControlProtocol::dyn_release);
1476         DEFINE_BUTTON_HANDLER (Button::Left, &MackieControlProtocol::left_press, &MackieControlProtocol::left_release);
1477         DEFINE_BUTTON_HANDLER (Button::Right, &MackieControlProtocol::right_press, &MackieControlProtocol::right_release);
1478         DEFINE_BUTTON_HANDLER (Button::ChannelLeft, &MackieControlProtocol::channel_left_press, &MackieControlProtocol::channel_left_release);
1479         DEFINE_BUTTON_HANDLER (Button::ChannelRight, &MackieControlProtocol::channel_right_press, &MackieControlProtocol::channel_right_release);
1480         DEFINE_BUTTON_HANDLER (Button::Flip, &MackieControlProtocol::flip_press, &MackieControlProtocol::flip_release);
1481         DEFINE_BUTTON_HANDLER (Button::View, &MackieControlProtocol::view_press, &MackieControlProtocol::view_release);
1482         DEFINE_BUTTON_HANDLER (Button::NameValue, &MackieControlProtocol::name_value_press, &MackieControlProtocol::name_value_release);
1483         DEFINE_BUTTON_HANDLER (Button::TimecodeBeats, &MackieControlProtocol::timecode_beats_press, &MackieControlProtocol::timecode_beats_release);
1484         DEFINE_BUTTON_HANDLER (Button::F1, &MackieControlProtocol::F1_press, &MackieControlProtocol::F1_release);
1485         DEFINE_BUTTON_HANDLER (Button::F2, &MackieControlProtocol::F2_press, &MackieControlProtocol::F2_release);
1486         DEFINE_BUTTON_HANDLER (Button::F3, &MackieControlProtocol::F3_press, &MackieControlProtocol::F3_release);
1487         DEFINE_BUTTON_HANDLER (Button::F4, &MackieControlProtocol::F4_press, &MackieControlProtocol::F4_release);
1488         DEFINE_BUTTON_HANDLER (Button::F5, &MackieControlProtocol::F5_press, &MackieControlProtocol::F5_release);
1489         DEFINE_BUTTON_HANDLER (Button::F6, &MackieControlProtocol::F6_press, &MackieControlProtocol::F6_release);
1490         DEFINE_BUTTON_HANDLER (Button::F7, &MackieControlProtocol::F7_press, &MackieControlProtocol::F7_release);
1491         DEFINE_BUTTON_HANDLER (Button::F8, &MackieControlProtocol::F8_press, &MackieControlProtocol::F8_release);
1492         DEFINE_BUTTON_HANDLER (Button::MidiTracks, &MackieControlProtocol::miditracks_press, &MackieControlProtocol::miditracks_release);
1493         DEFINE_BUTTON_HANDLER (Button::Inputs, &MackieControlProtocol::inputs_press, &MackieControlProtocol::inputs_release);
1494         DEFINE_BUTTON_HANDLER (Button::AudioTracks, &MackieControlProtocol::audiotracks_press, &MackieControlProtocol::audiotracks_release);
1495         DEFINE_BUTTON_HANDLER (Button::AudioInstruments, &MackieControlProtocol::audioinstruments_press, &MackieControlProtocol::audioinstruments_release);
1496         DEFINE_BUTTON_HANDLER (Button::Aux, &MackieControlProtocol::aux_press, &MackieControlProtocol::aux_release);
1497         DEFINE_BUTTON_HANDLER (Button::Busses, &MackieControlProtocol::busses_press, &MackieControlProtocol::busses_release);
1498         DEFINE_BUTTON_HANDLER (Button::Outputs, &MackieControlProtocol::outputs_press, &MackieControlProtocol::outputs_release);
1499         DEFINE_BUTTON_HANDLER (Button::User, &MackieControlProtocol::user_press, &MackieControlProtocol::user_release);
1500         DEFINE_BUTTON_HANDLER (Button::Shift, &MackieControlProtocol::shift_press, &MackieControlProtocol::shift_release);
1501         DEFINE_BUTTON_HANDLER (Button::Option, &MackieControlProtocol::option_press, &MackieControlProtocol::option_release);
1502         DEFINE_BUTTON_HANDLER (Button::Ctrl, &MackieControlProtocol::control_press, &MackieControlProtocol::control_release);
1503         DEFINE_BUTTON_HANDLER (Button::CmdAlt, &MackieControlProtocol::cmd_alt_press, &MackieControlProtocol::cmd_alt_release);
1504         DEFINE_BUTTON_HANDLER (Button::Read, &MackieControlProtocol::read_press, &MackieControlProtocol::read_release);
1505         DEFINE_BUTTON_HANDLER (Button::Write, &MackieControlProtocol::write_press, &MackieControlProtocol::write_release);
1506         DEFINE_BUTTON_HANDLER (Button::Trim, &MackieControlProtocol::trim_press, &MackieControlProtocol::trim_release);
1507         DEFINE_BUTTON_HANDLER (Button::Touch, &MackieControlProtocol::touch_press, &MackieControlProtocol::touch_release);
1508         DEFINE_BUTTON_HANDLER (Button::Latch, &MackieControlProtocol::latch_press, &MackieControlProtocol::latch_release);
1509         DEFINE_BUTTON_HANDLER (Button::Grp, &MackieControlProtocol::grp_press, &MackieControlProtocol::grp_release);
1510         DEFINE_BUTTON_HANDLER (Button::Save, &MackieControlProtocol::save_press, &MackieControlProtocol::save_release);
1511         DEFINE_BUTTON_HANDLER (Button::Undo, &MackieControlProtocol::undo_press, &MackieControlProtocol::undo_release);
1512         DEFINE_BUTTON_HANDLER (Button::Cancel, &MackieControlProtocol::cancel_press, &MackieControlProtocol::cancel_release);
1513         DEFINE_BUTTON_HANDLER (Button::Enter, &MackieControlProtocol::enter_press, &MackieControlProtocol::enter_release);
1514         DEFINE_BUTTON_HANDLER (Button::Marker, &MackieControlProtocol::marker_press, &MackieControlProtocol::marker_release);
1515         DEFINE_BUTTON_HANDLER (Button::Nudge, &MackieControlProtocol::nudge_press, &MackieControlProtocol::nudge_release);
1516         DEFINE_BUTTON_HANDLER (Button::Loop, &MackieControlProtocol::loop_press, &MackieControlProtocol::loop_release);
1517         DEFINE_BUTTON_HANDLER (Button::Drop, &MackieControlProtocol::drop_press, &MackieControlProtocol::drop_release);
1518         DEFINE_BUTTON_HANDLER (Button::Replace, &MackieControlProtocol::replace_press, &MackieControlProtocol::replace_release);
1519         DEFINE_BUTTON_HANDLER (Button::Click, &MackieControlProtocol::click_press, &MackieControlProtocol::click_release);
1520         DEFINE_BUTTON_HANDLER (Button::ClearSolo, &MackieControlProtocol::clearsolo_press, &MackieControlProtocol::clearsolo_release);
1521         DEFINE_BUTTON_HANDLER (Button::Rewind, &MackieControlProtocol::rewind_press, &MackieControlProtocol::rewind_release);
1522         DEFINE_BUTTON_HANDLER (Button::Ffwd, &MackieControlProtocol::ffwd_press, &MackieControlProtocol::ffwd_release);
1523         DEFINE_BUTTON_HANDLER (Button::Stop, &MackieControlProtocol::stop_press, &MackieControlProtocol::stop_release);
1524         DEFINE_BUTTON_HANDLER (Button::Play, &MackieControlProtocol::play_press, &MackieControlProtocol::play_release);
1525         DEFINE_BUTTON_HANDLER (Button::Record, &MackieControlProtocol::record_press, &MackieControlProtocol::record_release);
1526         DEFINE_BUTTON_HANDLER (Button::CursorUp, &MackieControlProtocol::cursor_up_press, &MackieControlProtocol::cursor_up_release);
1527         DEFINE_BUTTON_HANDLER (Button::CursorDown, &MackieControlProtocol::cursor_down_press, &MackieControlProtocol::cursor_down_release);
1528         DEFINE_BUTTON_HANDLER (Button::CursorLeft, &MackieControlProtocol::cursor_left_press, &MackieControlProtocol::cursor_left_release);
1529         DEFINE_BUTTON_HANDLER (Button::CursorRight, &MackieControlProtocol::cursor_right_press, &MackieControlProtocol::cursor_right_release);
1530         DEFINE_BUTTON_HANDLER (Button::Zoom, &MackieControlProtocol::zoom_press, &MackieControlProtocol::zoom_release);
1531         DEFINE_BUTTON_HANDLER (Button::Scrub, &MackieControlProtocol::scrub_press, &MackieControlProtocol::scrub_release);
1532         DEFINE_BUTTON_HANDLER (Button::UserA, &MackieControlProtocol::user_a_press, &MackieControlProtocol::user_a_release);
1533         DEFINE_BUTTON_HANDLER (Button::UserB, &MackieControlProtocol::user_b_press, &MackieControlProtocol::user_b_release);
1534         DEFINE_BUTTON_HANDLER (Button::MasterFaderTouch, &MackieControlProtocol::master_fader_touch_press, &MackieControlProtocol::master_fader_touch_release);
1535 }
1536
1537 void
1538 MackieControlProtocol::handle_button_event (Surface& surface, Button& button, ButtonState bs)
1539 {
1540         Button::ID button_id = button.bid();
1541
1542         if  (bs != press && bs != release) {
1543                 update_led (surface, button, none);
1544                 return;
1545         }
1546
1547         if ((button_id != Button::Marker) && (modifier_state() & MODIFIER_MARKER)) {
1548                 marker_modifier_consumed_by_button = true;
1549         }
1550
1551         if ((button_id != Button::Nudge) && (modifier_state() & MODIFIER_NUDGE)) {
1552                 nudge_modifier_consumed_by_button = true;
1553         }
1554
1555         DEBUG_TRACE (DEBUG::MackieControl, string_compose ("Handling %1 for button %2 (%3)\n", (bs == press ? "press" : "release"), button.id(),
1556                                                            Button::id_to_name (button.bid())));
1557
1558         /* check profile first */
1559
1560         string action = _device_profile.get_button_action (button.bid(), _modifier_state);
1561
1562         if (!action.empty()) {
1563
1564                 if (action.find ('/') != string::npos) { /* good chance that this is really an action */
1565
1566                         DEBUG_TRACE (DEBUG::MackieControl, string_compose ("Looked up action for button %1 with modifier %2, got [%3]\n",
1567                                                                            button.bid(), _modifier_state, action));
1568
1569                         /* if there is a bound action for this button, and this is a press event,
1570                            carry out the action. If its a release event, do nothing since we
1571                            don't bind to them at all but don't want any other handling to
1572                            occur either.
1573                         */
1574                         if (bs == press) {
1575                                 DEBUG_TRACE (DEBUG::MackieControl, string_compose ("executing action %1\n", action));
1576                                 access_action (action);
1577                         }
1578
1579                         return;
1580
1581                 } else {
1582
1583                         /* "action" is more likely to be a button name. We use this to
1584                          * allow remapping buttons to different (builtin) functionality
1585                          * associated with an existing button. This is similar to the
1586                          * way that (for example) Nuendo moves the "Shift" function to
1587                          * the "Enter" key of the MCU Pro.
1588                          */
1589
1590                         int bid = Button::name_to_id (action);
1591
1592                         if (bid < 0) {
1593                                 DEBUG_TRACE (DEBUG::MackieControl, string_compose ("apparent button name %1 not found\n", action));
1594                                 return;
1595                         }
1596
1597                         button_id = (Button::ID) bid;
1598                         DEBUG_TRACE (DEBUG::MackieControl, string_compose ("handling button %1 as if it was %2 (%3)\n", Button::id_to_name (button.bid()), button_id, Button::id_to_name (button_id)));
1599                 }
1600         }
1601
1602         /* lookup using the device-INDEPENDENT button ID */
1603
1604         ButtonMap::iterator b = button_map.find (button_id);
1605
1606         if (b != button_map.end()) {
1607
1608                 ButtonHandlers& bh (b->second);
1609
1610                 switch  (bs) {
1611                 case press:
1612                         surface.write (button.set_state ((this->*(bh.press)) (button)));
1613                         break;
1614                 case release:
1615                         surface.write (button.set_state ((this->*(bh.release)) (button)));
1616                         break;
1617                 default:
1618                         break;
1619                 }
1620         } else {
1621                 DEBUG_TRACE (DEBUG::MackieControl, string_compose ("no button handlers for button ID %1 (device ID %2)\n",
1622                                                                    button.bid(), button.id()));
1623                 error << string_compose ("no button handlers for button ID %1 (device ID %2)\n",
1624                                          button.bid(), button.id()) << endmsg;
1625         }
1626 }
1627
1628 bool
1629 MackieControlProtocol::midi_input_handler (IOCondition ioc, MIDI::Port* port)
1630 {
1631         if (ioc & ~IO_IN) {
1632                 DEBUG_TRACE (DEBUG::MackieControl, "MIDI port closed\n");
1633                 return false;
1634         }
1635
1636         if (ioc & IO_IN) {
1637
1638                 DEBUG_TRACE (DEBUG::MackieControl, string_compose ("something happend on  %1\n", port->name()));
1639
1640                 /* Devices using regular JACK MIDI ports will need to have
1641                    the x-thread FIFO drained to avoid burning endless CPU.
1642
1643                    Devices using ipMIDI have port->selectable() as the same
1644                    file descriptor that data arrives on, so doing this
1645                    for them will simply throw all incoming data away.
1646                 */
1647
1648                 if (!_device_info.uses_ipmidi()) {
1649                         AsyncMIDIPort* asp = dynamic_cast<AsyncMIDIPort*>(port);
1650                         if (asp) {
1651                                 asp->clear ();
1652                         }
1653                 }
1654
1655                 DEBUG_TRACE (DEBUG::MackieControl, string_compose ("data available on %1\n", port->name()));
1656                 framepos_t now = session->engine().sample_time();
1657                 port->parse (now);
1658         }
1659
1660         return true;
1661 }
1662
1663 void
1664 MackieControlProtocol::clear_ports ()
1665 {
1666         if (_input_bundle) {
1667                 _input_bundle->remove_channels ();
1668                 _output_bundle->remove_channels ();
1669         }
1670 }
1671
1672 void
1673 MackieControlProtocol::notify_subview_stripable_deleted ()
1674 {
1675         /* return to global/mixer view */
1676         _subview_stripable.reset ();
1677         set_view_mode (Mixer);
1678 }
1679
1680 bool
1681 MackieControlProtocol::subview_mode_would_be_ok (SubViewMode mode, boost::shared_ptr<Stripable> r)
1682 {
1683         switch (mode) {
1684         case None:
1685                 return true;
1686                 break;
1687
1688         case Sends:
1689                 if (r && r->send_level_controllable (0)) {
1690                         return true;
1691                 }
1692                 break;
1693
1694         case EQ:
1695                 if (r && r->eq_band_cnt() > 0) {
1696                         return true;
1697                 }
1698                 break;
1699
1700         case Dynamics:
1701                 if (r && r->comp_enable_controllable()) {
1702                         return true;
1703                 }
1704                 break;
1705
1706         case TrackView:
1707                 if (r) {
1708                         return true;
1709                 }
1710         }
1711
1712         return false;
1713 }
1714
1715 bool
1716 MackieControlProtocol::redisplay_subview_mode ()
1717 {
1718         Surfaces copy; /* can't hold surfaces lock while calling Strip::subview_mode_changed */
1719
1720         {
1721                 Glib::Threads::Mutex::Lock lm (surfaces_lock);
1722                 copy = surfaces;
1723         }
1724
1725         for (Surfaces::iterator s = copy.begin(); s != copy.end(); ++s) {
1726                 (*s)->subview_mode_changed ();
1727         }
1728
1729         /* don't call this again from a timeout */
1730         return false;
1731 }
1732
1733 int
1734 MackieControlProtocol::set_subview_mode (SubViewMode sm, boost::shared_ptr<Stripable> r)
1735 {
1736         if (_flip_mode != Normal) {
1737                 set_flip_mode (Normal);
1738         }
1739
1740         if (!subview_mode_would_be_ok (sm, r)) {
1741
1742                 if (r) {
1743
1744                         Glib::Threads::Mutex::Lock lm (surfaces_lock);
1745
1746                         if (!surfaces.empty()) {
1747
1748                                 string msg;
1749
1750                                 switch (sm) {
1751                                 case Sends:
1752                                         msg = _("no sends for selected track/bus");
1753                                         break;
1754                                 case EQ:
1755                                         msg = _("no EQ in the track/bus");
1756                                         break;
1757                                 case Dynamics:
1758                                         msg = _("no dynamics in selected track/bus");
1759                                         break;
1760                                 case TrackView:
1761                                         msg = _("no track view possible");
1762                                 default:
1763                                         break;
1764                                 }
1765                                 if (!msg.empty()) {
1766                                         surfaces.front()->display_message_for (msg, 1000);
1767                                         if (_subview_mode != None) {
1768                                                 /* redisplay current subview mode after
1769                                                    that message goes away.
1770                                                 */
1771                                                 Glib::RefPtr<Glib::TimeoutSource> redisplay_timeout = Glib::TimeoutSource::create (1000); // milliseconds
1772                                                 redisplay_timeout->connect (sigc::mem_fun (*this, &MackieControlProtocol::redisplay_subview_mode));
1773                                                 redisplay_timeout->attach (main_loop()->get_context());
1774                                         }
1775                                 }
1776                         }
1777                 }
1778
1779                 return -1;
1780         }
1781
1782         boost::shared_ptr<Stripable> old_stripable = _subview_stripable;
1783
1784         _subview_mode = sm;
1785         _subview_stripable = r;
1786
1787         if (_subview_stripable != old_stripable) {
1788                 subview_stripable_connections.drop_connections ();
1789
1790                 /* Catch the current subview stripable going away */
1791                 if (_subview_stripable) {
1792                         _subview_stripable->DropReferences.connect (subview_stripable_connections, MISSING_INVALIDATOR,
1793                                                                     boost::bind (&MackieControlProtocol::notify_subview_stripable_deleted, this),
1794                                                                     this);
1795                 }
1796         }
1797
1798         redisplay_subview_mode ();
1799
1800         /* turn buttons related to vpot mode on or off as required */
1801
1802         switch (_subview_mode) {
1803         case MackieControlProtocol::None:
1804                 update_global_button (Button::Send, off);
1805                 update_global_button (Button::Plugin, off);
1806                 update_global_button (Button::Eq, off);
1807                 update_global_button (Button::Dyn, off);
1808                 update_global_button (Button::Track, off);
1809                 update_global_button (Button::Pan, on);
1810                 break;
1811         case MackieControlProtocol::EQ:
1812                 update_global_button (Button::Send, off);
1813                 update_global_button (Button::Plugin, off);
1814                 update_global_button (Button::Eq, on);
1815                 update_global_button (Button::Dyn, off);
1816                 update_global_button (Button::Track, off);
1817                 update_global_button (Button::Pan, off);
1818                 break;
1819         case MackieControlProtocol::Dynamics:
1820                 update_global_button (Button::Send, off);
1821                 update_global_button (Button::Plugin, off);
1822                 update_global_button (Button::Eq, off);
1823                 update_global_button (Button::Dyn, on);
1824                 update_global_button (Button::Track, off);
1825                 update_global_button (Button::Pan, off);
1826                 break;
1827         case MackieControlProtocol::Sends:
1828                 update_global_button (Button::Send, on);
1829                 update_global_button (Button::Plugin, off);
1830                 update_global_button (Button::Eq, off);
1831                 update_global_button (Button::Dyn, off);
1832                 update_global_button (Button::Track, off);
1833                 update_global_button (Button::Pan, off);
1834                 break;
1835         case MackieControlProtocol::TrackView:
1836                 update_global_button (Button::Send, off);
1837                 update_global_button (Button::Plugin, off);
1838                 update_global_button (Button::Eq, off);
1839                 update_global_button (Button::Dyn, off);
1840                 update_global_button (Button::Track, on);
1841                 update_global_button (Button::Pan, off);
1842                 break;
1843         }
1844
1845         return 0;
1846 }
1847
1848 void
1849 MackieControlProtocol::set_view_mode (ViewMode m)
1850 {
1851         if (_flip_mode != Normal) {
1852                 set_flip_mode (Normal);
1853         }
1854         ViewMode old_view_mode = _view_mode;
1855
1856         _view_mode = m;
1857         _last_bank[old_view_mode] = _current_initial_bank;
1858
1859         if (switch_banks(_last_bank[m], true)) {
1860                 _view_mode = old_view_mode;
1861                 return;
1862         }
1863
1864         /* leave subview mode, whatever it was */
1865         set_subview_mode (None, boost::shared_ptr<Stripable>());
1866         display_view_mode ();
1867 }
1868
1869 void
1870 MackieControlProtocol::display_view_mode ()
1871 {
1872         Glib::Threads::Mutex::Lock lm (surfaces_lock);
1873
1874         for (Surfaces::iterator s = surfaces.begin(); s != surfaces.end(); ++s) {
1875                 (*s)->update_view_mode_display (true);
1876         }
1877 }
1878
1879 void
1880 MackieControlProtocol::set_flip_mode (FlipMode fm)
1881 {
1882         if (fm == Normal) {
1883                 update_global_button (Button::Flip, off);
1884         } else {
1885                 update_global_button (Button::Flip, on);
1886         }
1887
1888         Glib::Threads::Mutex::Lock lm (surfaces_lock);
1889
1890         _flip_mode = fm;
1891
1892         for (Surfaces::iterator s = surfaces.begin(); s != surfaces.end(); ++s) {
1893                 (*s)->update_flip_mode_display ();
1894         }
1895 }
1896
1897 void
1898 MackieControlProtocol::set_master_on_surface_strip (uint32_t surface, uint32_t strip_number)
1899 {
1900         force_special_stripable_to_strip (session->master_out(), surface, strip_number);
1901 }
1902
1903 void
1904 MackieControlProtocol::set_monitor_on_surface_strip (uint32_t surface, uint32_t strip_number)
1905 {
1906         force_special_stripable_to_strip (session->monitor_out(), surface, strip_number);
1907 }
1908
1909 void
1910 MackieControlProtocol::force_special_stripable_to_strip (boost::shared_ptr<Stripable> r, uint32_t surface, uint32_t strip_number)
1911 {
1912         if (!r) {
1913                 return;
1914         }
1915
1916         Glib::Threads::Mutex::Lock lm (surfaces_lock);
1917
1918         for (Surfaces::iterator s = surfaces.begin(); s != surfaces.end(); ++s) {
1919                 if ((*s)->number() == surface) {
1920                         Strip* strip = (*s)->nth_strip (strip_number);
1921                         if (strip) {
1922                                 strip->set_stripable (session->master_out());
1923                                 strip->lock_controls ();
1924                         }
1925                 }
1926         }
1927 }
1928
1929 void
1930 MackieControlProtocol::gui_track_selection_changed (ARDOUR::StripableNotificationListPtr rl, bool save_list)
1931 {
1932         _gui_track_selection_changed (rl.get(), save_list, true);
1933 }
1934
1935 void
1936 MackieControlProtocol::_gui_track_selection_changed (ARDOUR::StripableNotificationList* rl, bool save_list, bool gui_selection_did_change)
1937 {
1938         /* We need to keep a list of the most recently selected routes around,
1939            but we are not allowed to keep shared_ptr<Stripable> unless we want to
1940            handle the complexities of route deletion. So instead, the GUI sends
1941            us a notification using weak_ptr<Stripable>, which we keep a copy
1942            of. For efficiency's sake, however, we convert the weak_ptr's into
1943            shared_ptr<Stripable> before passing them to however many surfaces (and
1944            thus strips) that we have.
1945         */
1946
1947         StrongStripableNotificationList srl;
1948
1949         for (ARDOUR::StripableNotificationList::const_iterator i = rl->begin(); i != rl->end(); ++i) {
1950                 boost::shared_ptr<ARDOUR::Stripable> r = (*i).lock();
1951                 if (r) {
1952                         srl.push_back (r);
1953                 }
1954         }
1955
1956         {
1957                 Glib::Threads::Mutex::Lock lm (surfaces_lock);
1958
1959                 for (Surfaces::iterator s = surfaces.begin(); s != surfaces.end(); ++s) {
1960                         (*s)->gui_selection_changed (srl);
1961                 }
1962         }
1963
1964         if (save_list) {
1965                 _last_selected_stripables = *rl;
1966         }
1967
1968         if (gui_selection_did_change) {
1969
1970                 check_fader_automation_state ();
1971
1972                 /* note: this method is also called when we switch banks.
1973                  * But ... we don't allow bank switching when in subview mode.
1974                  *
1975                  * so .. we only have to care about subview mode if the
1976                  * GUI selection has changed.
1977                  *
1978                  * It is possible that first_selected_stripable() may return null if we
1979                  * are no longer displaying/mapping that route. In that case,
1980                  * we will exit subview mode. If first_selected_stripable() is
1981                  * null, and subview mode is not None, then the first call to
1982                  * set_subview_mode() will fail, and we will reset to None.
1983                  */
1984
1985                 if (set_subview_mode (_subview_mode, first_selected_stripable())) {
1986                         set_subview_mode (None, boost::shared_ptr<Stripable>());
1987                 }
1988         }
1989 }
1990
1991 void
1992 MackieControlProtocol::check_fader_automation_state ()
1993 {
1994         fader_automation_connections.drop_connections ();
1995
1996         boost::shared_ptr<Stripable> r = first_selected_stripable ();
1997
1998         if (!r) {
1999                 update_global_button (Button::Read, off);
2000                 update_global_button (Button::Write, off);
2001                 update_global_button (Button::Touch, off);
2002                 update_global_button (Button::Trim, off);
2003                 update_global_button (Button::Latch, off);
2004                 update_global_button (Button::Grp, on);
2005                 return;
2006         }
2007
2008         r->gain_control()->alist()->automation_state_changed.connect (fader_automation_connections,
2009                                                                       MISSING_INVALIDATOR,
2010                                                                       boost::bind (&MackieControlProtocol::update_fader_automation_state, this),
2011                                                                       this);
2012
2013         update_fader_automation_state ();
2014 }
2015
2016 void
2017 MackieControlProtocol::update_fader_automation_state ()
2018 {
2019         boost::shared_ptr<Stripable> r = first_selected_stripable ();
2020
2021         if (!r) {
2022                 update_global_button (Button::Read, off);
2023                 update_global_button (Button::Write, off);
2024                 update_global_button (Button::Touch, off);
2025                 update_global_button (Button::Trim, off);
2026                 update_global_button (Button::Latch, off);
2027                 update_global_button (Button::Grp, on);
2028                 return;
2029         }
2030
2031         switch (r->gain_control()->automation_state()) {
2032         case Off:
2033                 update_global_button (Button::Read, off);
2034                 update_global_button (Button::Write, off);
2035                 update_global_button (Button::Touch, off);
2036                 update_global_button (Button::Trim, off);
2037                 update_global_button (Button::Latch, off);
2038                 update_global_button (Button::Grp, on);
2039                 break;
2040         case Play:
2041                 update_global_button (Button::Read, on);
2042                 update_global_button (Button::Write, off);
2043                 update_global_button (Button::Touch, off);
2044                 update_global_button (Button::Trim, off);
2045                 update_global_button (Button::Latch, off);
2046                 update_global_button (Button::Grp, off);
2047                 break;
2048         case Write:
2049                 update_global_button (Button::Read, off);
2050                 update_global_button (Button::Write, on);
2051                 update_global_button (Button::Touch, off);
2052                 update_global_button (Button::Trim, off);
2053                 update_global_button (Button::Latch, off);
2054                 update_global_button (Button::Grp, off);
2055                 break;
2056         case Touch:
2057                 update_global_button (Button::Read, off);
2058                 update_global_button (Button::Write, off);
2059                 update_global_button (Button::Touch, on);
2060                 update_global_button (Button::Trim, off);
2061                 update_global_button (Button::Latch, off);
2062                 update_global_button (Button::Grp, off);
2063                 break;
2064         }
2065 }
2066
2067 framepos_t
2068 MackieControlProtocol::transport_frame() const
2069 {
2070         return session->transport_frame();
2071 }
2072
2073 void
2074 MackieControlProtocol::add_down_select_button (int surface, int strip)
2075 {
2076         _down_select_buttons.insert ((surface<<8)|(strip&0xf));
2077 }
2078
2079 void
2080 MackieControlProtocol::remove_down_select_button (int surface, int strip)
2081 {
2082         DownButtonList::iterator x = find (_down_select_buttons.begin(), _down_select_buttons.end(), (uint32_t) (surface<<8)|(strip&0xf));
2083         DEBUG_TRACE (DEBUG::MackieControl, string_compose ("removing surface %1 strip %2 from down select buttons\n", surface, strip));
2084         if (x != _down_select_buttons.end()) {
2085                 _down_select_buttons.erase (x);
2086         } else {
2087                 DEBUG_TRACE (DEBUG::MackieControl, string_compose ("surface %1 strip %2 not found in down select buttons\n",
2088                                                                    surface, strip));
2089         }
2090 }
2091
2092 void
2093 MackieControlProtocol::select_range ()
2094 {
2095         StripableList stripables;
2096
2097         pull_stripable_range (_down_select_buttons, stripables);
2098
2099         DEBUG_TRACE (DEBUG::MackieControl, string_compose ("select range: found %1 stripables\n", stripables.size()));
2100
2101         if (stripables.empty()) {
2102                 return;
2103         }
2104
2105         for (StripableList::iterator s = stripables.begin(); s != stripables.end(); ++s) {
2106
2107                 if (main_modifier_state() == MODIFIER_SHIFT) {
2108                         /* XXX can only use order part of PresentationInfo at present */
2109                         ToggleStripableSelection ((*s)->presentation_info ().order());
2110                 } else {
2111                         if (s == stripables.begin()) {
2112                                 /* XXX can only use order part of PresentationInfo at present */
2113                                 SetStripableSelection ((*s)->presentation_info().order());
2114                         } else {
2115                                 /* XXX can only use order part of PresentationInfo at present */
2116                                 AddStripableToSelection ((*s)->presentation_info().order());
2117                         }
2118                 }
2119         }
2120 }
2121
2122 void
2123 MackieControlProtocol::add_down_button (AutomationType a, int surface, int strip)
2124 {
2125         DownButtonMap::iterator m = _down_buttons.find (a);
2126
2127         if (m == _down_buttons.end()) {
2128                 _down_buttons[a] = DownButtonList();
2129         }
2130
2131         _down_buttons[a].insert ((surface<<8)|(strip&0xf));
2132 }
2133
2134 void
2135 MackieControlProtocol::remove_down_button (AutomationType a, int surface, int strip)
2136 {
2137         DownButtonMap::iterator m = _down_buttons.find (a);
2138
2139         DEBUG_TRACE (DEBUG::MackieControl, string_compose ("removing surface %1 strip %2 from down buttons for %3\n", surface, strip, (int) a));
2140
2141         if (m == _down_buttons.end()) {
2142                 return;
2143         }
2144
2145         DownButtonList& l (m->second);
2146         DownButtonList::iterator x = find (l.begin(), l.end(), (surface<<8)|(strip&0xf));
2147
2148         if (x != l.end()) {
2149                 l.erase (x);
2150         } else {
2151                 DEBUG_TRACE (DEBUG::MackieControl, string_compose ("surface %1 strip %2 not found in down buttons for %3\n",
2152                                                                    surface, strip, (int) a));
2153         }
2154 }
2155
2156 MackieControlProtocol::ControlList
2157 MackieControlProtocol::down_controls (AutomationType p)
2158 {
2159         ControlList controls;
2160         StripableList stripables;
2161
2162         DownButtonMap::iterator m = _down_buttons.find (p);
2163
2164         if (m == _down_buttons.end()) {
2165                 return controls;
2166         }
2167
2168         DEBUG_TRACE (DEBUG::MackieControl, string_compose ("looking for down buttons for %1, got %2\n",
2169                                                            p, m->second.size()));
2170
2171         pull_stripable_range (m->second, stripables);
2172
2173         switch (p) {
2174         case GainAutomation:
2175                 for (StripableList::iterator s = stripables.begin(); s != stripables.end(); ++s) {
2176                         controls.push_back ((*s)->gain_control());
2177                 }
2178                 break;
2179         case SoloAutomation:
2180                 for (StripableList::iterator s = stripables.begin(); s != stripables.end(); ++s) {
2181                         controls.push_back ((*s)->solo_control());
2182                 }
2183                 break;
2184         case MuteAutomation:
2185                 for (StripableList::iterator s = stripables.begin(); s != stripables.end(); ++s) {
2186                         controls.push_back ((*s)->mute_control());
2187                 }
2188                 break;
2189         case RecEnableAutomation:
2190                 for (StripableList::iterator s = stripables.begin(); s != stripables.end(); ++s) {
2191                         boost::shared_ptr<AutomationControl> ac = (*s)->rec_enable_control();
2192                         if (ac) {
2193                                 controls.push_back (ac);
2194                         }
2195                 }
2196                 break;
2197         default:
2198                 break;
2199         }
2200
2201         return controls;
2202
2203 }
2204
2205 struct ButtonRangeSorter {
2206     bool operator() (const uint32_t& a, const uint32_t& b) {
2207             return (a>>8) < (b>>8) // a.surface < b.surface
2208                     ||
2209                     ((a>>8) == (b>>8) && (a&0xf) < (b&0xf)); // a.surface == b.surface && a.strip < b.strip
2210     }
2211 };
2212
2213 void
2214 MackieControlProtocol::pull_stripable_range (DownButtonList& down, StripableList& selected)
2215 {
2216         ButtonRangeSorter cmp;
2217
2218         if (down.empty()) {
2219                 return;
2220         }
2221
2222         list<uint32_t> ldown;
2223         ldown.insert (ldown.end(), down.begin(), down.end());
2224         ldown.sort (cmp);
2225
2226         uint32_t first = ldown.front();
2227         uint32_t last = ldown.back ();
2228
2229         uint32_t first_surface = first>>8;
2230         uint32_t first_strip = first&0xf;
2231
2232         uint32_t last_surface = last>>8;
2233         uint32_t last_strip = last&0xf;
2234
2235         DEBUG_TRACE (DEBUG::MackieControl, string_compose ("PRR %5 in list %1.%2 - %3.%4\n", first_surface, first_strip, last_surface, last_strip,
2236                                                            down.size()));
2237
2238         Glib::Threads::Mutex::Lock lm (surfaces_lock);
2239
2240         for (Surfaces::const_iterator s = surfaces.begin(); s != surfaces.end(); ++s) {
2241
2242                 if ((*s)->number() >= first_surface && (*s)->number() <= last_surface) {
2243
2244                         uint32_t fs;
2245                         uint32_t ls;
2246
2247                         if ((*s)->number() == first_surface) {
2248                                 fs = first_strip;
2249                         } else {
2250                                 fs = 0;
2251                         }
2252
2253                         if ((*s)->number() == last_surface) {
2254                                 ls = last_strip;
2255                                 ls += 1;
2256                         } else {
2257                                 ls = (*s)->n_strips ();
2258                         }
2259
2260                         DEBUG_TRACE (DEBUG::MackieControl, string_compose ("adding strips for surface %1 (%2 .. %3)\n",
2261                                                                            (*s)->number(), fs, ls));
2262
2263                         for (uint32_t n = fs; n < ls; ++n) {
2264                                 boost::shared_ptr<Stripable> r = (*s)->nth_strip (n)->stripable();
2265                                 if (r) {
2266                                         selected.push_back (r);
2267                                 }
2268                         }
2269                 }
2270         }
2271 }
2272
2273 void
2274 MackieControlProtocol::set_ipmidi_base (int16_t portnum)
2275 {
2276         /* this will not be saved without a session save, so .. */
2277
2278         session->set_dirty ();
2279
2280         _ipmidi_base = portnum;
2281
2282         /* if the current device uses ipMIDI we need
2283            to restart.
2284         */
2285
2286         if (active() && _device_info.uses_ipmidi()) {
2287                 needs_ipmidi_restart = true;
2288         }
2289 }
2290
2291 int
2292 MackieControlProtocol::ipmidi_restart ()
2293 {
2294         clear_surfaces ();
2295         if (create_surfaces ()) {
2296                 return -1;
2297         }
2298         (void) switch_banks (_current_initial_bank, true);
2299         needs_ipmidi_restart = false;
2300         return 0;
2301 }
2302
2303 void
2304 MackieControlProtocol::clear_surfaces ()
2305 {
2306         clear_ports ();
2307
2308         {
2309                 Glib::Threads::Mutex::Lock lm (surfaces_lock);
2310                 _master_surface.reset ();
2311                 surfaces.clear ();
2312         }
2313 }
2314
2315 void
2316 MackieControlProtocol::set_touch_sensitivity (int sensitivity)
2317 {
2318         sensitivity = min (9, sensitivity);
2319         sensitivity = max (0, sensitivity);
2320
2321         Glib::Threads::Mutex::Lock lm (surfaces_lock);
2322
2323         for (Surfaces::const_iterator s = surfaces.begin(); s != surfaces.end(); ++s) {
2324                 (*s)->set_touch_sensitivity (sensitivity);
2325         }
2326 }
2327
2328 void
2329 MackieControlProtocol::recalibrate_faders ()
2330 {
2331         Glib::Threads::Mutex::Lock lm (surfaces_lock);
2332
2333         for (Surfaces::const_iterator s = surfaces.begin(); s != surfaces.end(); ++s) {
2334                 (*s)->recalibrate_faders ();
2335         }
2336 }
2337
2338 void
2339 MackieControlProtocol::toggle_backlight ()
2340 {
2341         Glib::Threads::Mutex::Lock lm (surfaces_lock);
2342
2343         for (Surfaces::const_iterator s = surfaces.begin(); s != surfaces.end(); ++s) {
2344                 (*s)->toggle_backlight ();
2345         }
2346 }
2347
2348 boost::shared_ptr<Surface>
2349 MackieControlProtocol::get_surface_by_raw_pointer (void* ptr) const
2350 {
2351         Glib::Threads::Mutex::Lock lm (surfaces_lock);
2352
2353         for (Surfaces::const_iterator s = surfaces.begin(); s != surfaces.end(); ++s) {
2354                 if ((*s).get() == (Surface*) ptr) {
2355                         return *s;
2356                 }
2357         }
2358
2359         return boost::shared_ptr<Surface> ();
2360 }
2361
2362 boost::shared_ptr<Surface>
2363 MackieControlProtocol::nth_surface (uint32_t n) const
2364 {
2365         Glib::Threads::Mutex::Lock lm (surfaces_lock);
2366
2367         for (Surfaces::const_iterator s = surfaces.begin(); s != surfaces.end(); ++s, --n) {
2368                 if (n == 0) {
2369                         return *s;
2370                 }
2371         }
2372
2373         return boost::shared_ptr<Surface> ();
2374 }
2375
2376 void
2377 MackieControlProtocol::connection_handler (boost::weak_ptr<ARDOUR::Port> wp1, std::string name1, boost::weak_ptr<ARDOUR::Port> wp2, std::string name2, bool yn)
2378 {
2379         Surfaces scopy;
2380         {
2381                 Glib::Threads::Mutex::Lock lm (surfaces_lock);
2382                 scopy = surfaces;
2383         }
2384
2385         for (Surfaces::const_iterator s = scopy.begin(); s != scopy.end(); ++s) {
2386                 if ((*s)->connection_handler (wp1, name1, wp2, name2, yn)) {
2387                         ConnectionChange (*s);
2388                         break;
2389                 }
2390         }
2391 }
2392
2393 bool
2394 MackieControlProtocol::is_track (boost::shared_ptr<Stripable> r) const
2395 {
2396         return boost::dynamic_pointer_cast<Track>(r) != 0;
2397 }
2398
2399 bool
2400 MackieControlProtocol::is_audio_track (boost::shared_ptr<Stripable> r) const
2401 {
2402         return boost::dynamic_pointer_cast<AudioTrack>(r) != 0;
2403 }
2404
2405 bool
2406 MackieControlProtocol::is_midi_track (boost::shared_ptr<Stripable> r) const
2407 {
2408         return boost::dynamic_pointer_cast<MidiTrack>(r) != 0;
2409 }
2410
2411 bool
2412 MackieControlProtocol::selected (boost::shared_ptr<Stripable> r) const
2413 {
2414         const StripableNotificationList* rl = &_last_selected_stripables;
2415
2416         for (ARDOUR::StripableNotificationList::const_iterator i = rl->begin(); i != rl->end(); ++i) {
2417                 boost::shared_ptr<ARDOUR::Stripable> rt = (*i).lock();
2418                 if (rt == r) {
2419                         return true;
2420                 }
2421         }
2422         return false;
2423 }
2424
2425 bool
2426 MackieControlProtocol::is_hidden (boost::shared_ptr<Stripable> r) const
2427 {
2428         if (!r) {
2429                 return false;
2430         }
2431         return (r->presentation_info().flags() & PresentationInfo::Hidden);
2432 }
2433
2434 bool
2435 MackieControlProtocol::is_mapped (boost::shared_ptr<Stripable> r) const
2436 {
2437         Glib::Threads::Mutex::Lock lm (surfaces_lock);
2438
2439         for (Surfaces::const_iterator s = surfaces.begin(); s != surfaces.end(); ++s) {
2440                 if ((*s)->stripable_is_mapped (r)) {
2441                         return true;
2442                 }
2443         }
2444
2445         return false;
2446 }
2447
2448 boost::shared_ptr<Stripable>
2449 MackieControlProtocol::first_selected_stripable () const
2450 {
2451         if (_last_selected_stripables.empty()) {
2452                 return boost::shared_ptr<Stripable>();
2453         }
2454
2455         boost::shared_ptr<Stripable> r = _last_selected_stripables.front().lock();
2456
2457         if (r) {
2458                 /* check it is on one of our surfaces */
2459
2460                 if (is_mapped (r)) {
2461                         return r;
2462                 }
2463
2464                 /* stripable is not mapped. thus, the currently selected stripable is
2465                  * not on the surfaces, and so from our perspective, there is
2466                  * no currently selected stripable.
2467                  */
2468
2469                 r.reset ();
2470         }
2471
2472         return r; /* may be null */
2473 }
2474
2475 boost::shared_ptr<Stripable>
2476 MackieControlProtocol::subview_stripable () const
2477 {
2478         return _subview_stripable;
2479 }
2480
2481 uint32_t
2482 MackieControlProtocol::global_index (Strip& strip)
2483 {
2484         Glib::Threads::Mutex::Lock lm (surfaces_lock);
2485         uint32_t global = 0;
2486
2487         for (Surfaces::const_iterator s = surfaces.begin(); s != surfaces.end(); ++s) {
2488                 if ((*s).get() == strip.surface()) {
2489                         return global + strip.index();
2490                 }
2491                 global += (*s)->n_strips ();
2492         }
2493
2494         return global;
2495 }
2496
2497 void*
2498 MackieControlProtocol::request_factory (uint32_t num_requests)
2499 {
2500         /* AbstractUI<T>::request_buffer_factory() is a template method only
2501            instantiated in this source module. To provide something visible for
2502            use in the interface/descriptor, we have this static method that is
2503            template-free.
2504         */
2505         return request_buffer_factory (num_requests);
2506 }
2507
2508 void
2509 MackieControlProtocol::set_automation_state (AutoState as)
2510 {
2511         boost::shared_ptr<Stripable> r = first_selected_stripable ();
2512
2513         if (!r) {
2514                 return;
2515         }
2516
2517         boost::shared_ptr<AutomationControl> ac = r->gain_control();
2518
2519         if (!ac) {
2520                 return;
2521         }
2522
2523         ac->set_automation_state (as);
2524 }