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