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