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