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