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