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