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