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