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