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