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