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