LTC Slave, add support for variable framerates
[ardour.git] / libs / surfaces / mackie / mackie_control_protocol.cc
1 /*
2         Copyright (C) 2006,2007 John Anderson
3         Copyright (C) 2012 Paul Davis
4
5         This program is free software; you can redistribute it and/or modify
6         it under the terms of the GNU General Public License as published by
7         the Free Software Foundation; either version 2 of the License, or
8         (at your option) any later version.
9
10         This program is distributed in the hope that it will be useful,
11         but WITHOUT ANY WARRANTY; without even the implied warranty of
12         MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13         GNU General Public License for more details.
14
15         You should have received a copy of the GNU General Public License
16         along with this program; if not, write to the Free Software
17         Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
18 */
19
20 #include <fcntl.h>
21 #include <iostream>
22 #include <algorithm>
23 #include <cmath>
24 #include <sstream>
25 #include <vector>
26 #include <iomanip>
27
28 #include <inttypes.h>
29 #include <float.h>
30 #include <sys/time.h>
31 #include <errno.h>
32 #include <poll.h>
33
34 #include <boost/shared_array.hpp>
35
36 #include "midi++/types.h"
37 #include "midi++/port.h"
38 #include "midi++/ipmidi_port.h"
39 #include "pbd/pthread_utils.h"
40 #include "pbd/error.h"
41 #include "pbd/memento_command.h"
42 #include "pbd/convert.h"
43
44 #include "ardour/automation_control.h"
45 #include "ardour/dB.h"
46 #include "ardour/debug.h"
47 #include "ardour/location.h"
48 #include "ardour/meter.h"
49 #include "ardour/panner.h"
50 #include "ardour/panner_shell.h"
51 #include "ardour/route.h"
52 #include "ardour/session.h"
53 #include "ardour/tempo.h"
54 #include "ardour/track.h"
55 #include "ardour/types.h"
56 #include "ardour/audioengine.h"
57
58 #include "mackie_control_protocol.h"
59
60 #include "midi_byte_array.h"
61 #include "mackie_control_exception.h"
62 #include "device_profile.h"
63 #include "surface_port.h"
64 #include "surface.h"
65 #include "strip.h"
66 #include "control_group.h"
67 #include "meter.h"
68 #include "button.h"
69 #include "fader.h"
70 #include "pot.h"
71
72 using namespace ARDOUR;
73 using namespace std;
74 using namespace Mackie;
75 using namespace PBD;
76 using namespace Glib;
77
78 #include "i18n.h"
79
80 #include "pbd/abstract_ui.cc" // instantiate template
81
82 const int MackieControlProtocol::MODIFIER_OPTION = 0x1;
83 const int MackieControlProtocol::MODIFIER_CONTROL = 0x2;
84 const int MackieControlProtocol::MODIFIER_SHIFT = 0x4;
85 const int MackieControlProtocol::MODIFIER_CMDALT = 0x8;
86
87 MackieControlProtocol* MackieControlProtocol::_instance = 0;
88
89 bool MackieControlProtocol::probe()
90 {
91         return true;
92 }
93
94 MackieControlProtocol::MackieControlProtocol (Session& session)
95         : ControlProtocol (session, X_("Mackie"))
96         , AbstractUI<MackieControlUIRequest> ("mackie")
97         , _current_initial_bank (0)
98         , _timecode_type (ARDOUR::AnyTime::BBT)
99         , _input_bundle (new ARDOUR::Bundle (_("Mackie Control In"), true))
100         , _output_bundle (new ARDOUR::Bundle (_("Mackie Control Out"), false))
101         , _gui (0)
102         , _zoom_mode (false)
103         , _scrub_mode (false)
104         , _flip_mode (false)
105         , _view_mode (Mixer)
106         , _current_selected_track (-1)
107         , _modifier_state (0)
108         , _ipmidi_base (MIDI::IPMIDIPort::lowest_ipmidi_port_default)
109         , needs_ipmidi_restart (false)
110         , _metering_active (true)
111         , _initialized (false)
112 {
113         DEBUG_TRACE (DEBUG::MackieControl, "MackieControlProtocol::MackieControlProtocol\n");
114
115         DeviceInfo::reload_device_info ();
116         DeviceProfile::reload_device_profiles ();
117
118         TrackSelectionChanged.connect (gui_connections, MISSING_INVALIDATOR, boost::bind (&MackieControlProtocol::gui_track_selection_changed, this, _1, true), this);
119
120         _instance = this;
121
122         build_button_map ();
123 }
124
125 MackieControlProtocol::~MackieControlProtocol()
126 {
127         DEBUG_TRACE (DEBUG::MackieControl, "MackieControlProtocol::~MackieControlProtocol init\n");
128         
129         DEBUG_TRACE (DEBUG::MackieControl, "MackieControlProtocol::~MackieControlProtocol drop_connections ()\n");
130         drop_connections ();
131
132         DEBUG_TRACE (DEBUG::MackieControl, "MackieControlProtocol::~MackieControlProtocol tear_down_gui ()\n");
133         tear_down_gui ();
134
135         _active = false;
136
137         /* stop event loop */
138         DEBUG_TRACE (DEBUG::MackieControl, "MackieControlProtocol::~MackieControlProtocol BaseUI::quit ()\n");
139         BaseUI::quit ();
140
141         try {
142                 DEBUG_TRACE (DEBUG::MackieControl, "MackieControlProtocol::~MackieControlProtocol close()\n");
143                 close();
144         }
145         catch (exception & e) {
146                 cout << "~MackieControlProtocol caught " << e.what() << endl;
147         }
148         catch (...) {
149                 cout << "~MackieControlProtocol caught unknown" << endl;
150         }
151
152         _instance = 0;
153
154         DEBUG_TRACE (DEBUG::MackieControl, "MackieControlProtocol::~MackieControlProtocol done\n");
155 }
156
157 void
158 MackieControlProtocol::thread_init ()
159 {
160         struct sched_param rtparam;
161
162         pthread_set_name (X_("MackieControl"));
163
164         PBD::notify_gui_about_thread_creation (X_("gui"), pthread_self(), X_("MackieControl"), 2048);
165         ARDOUR::SessionEvent::create_per_thread_pool (X_("MackieControl"), 128);
166
167         memset (&rtparam, 0, sizeof (rtparam));
168         rtparam.sched_priority = 9; /* XXX should be relative to audio (JACK) thread */
169
170         if (pthread_setschedparam (pthread_self(), SCHED_FIFO, &rtparam) != 0) {
171                 // do we care? not particularly.
172         }
173 }
174
175 void
176 MackieControlProtocol::midi_connectivity_established ()
177 {
178         for (Surfaces::const_iterator si = surfaces.begin(); si != surfaces.end(); ++si) {
179                 (*si)->say_hello ();
180         }
181 }
182
183 // go to the previous track.
184 // Assume that get_sorted_routes().size() > route_table.size()
185 void 
186 MackieControlProtocol::prev_track()
187 {
188         if (_current_initial_bank >= 1) {
189                 switch_banks (_current_initial_bank - 1);
190         }
191 }
192
193 // go to the next track.
194 // Assume that get_sorted_routes().size() > route_table.size()
195 void 
196 MackieControlProtocol::next_track()
197 {
198         Sorted sorted = get_sorted_routes();
199         if (_current_initial_bank + n_strips() < sorted.size()) {
200                 switch_banks (_current_initial_bank + 1);
201         }
202 }
203
204 bool
205 MackieControlProtocol::route_is_locked_to_strip (boost::shared_ptr<Route> r) const
206 {
207         for (Surfaces::const_iterator si = surfaces.begin(); si != surfaces.end(); ++si) {
208                 if ((*si)->route_is_locked_to_strip (r)) {
209                         return true;
210                 }
211         }
212         return false;
213 }
214
215 // predicate for sort call in get_sorted_routes
216 struct RouteByRemoteId
217 {
218         bool operator () (const boost::shared_ptr<Route> & a, const boost::shared_ptr<Route> & b) const
219         {
220                 return a->remote_control_id() < b->remote_control_id();
221         }
222
223         bool operator () (const Route & a, const Route & b) const
224         {
225                 return a.remote_control_id() < b.remote_control_id();
226         }
227
228         bool operator () (const Route * a, const Route * b) const
229         {
230                 return a->remote_control_id() < b->remote_control_id();
231         }
232 };
233
234 MackieControlProtocol::Sorted 
235 MackieControlProtocol::get_sorted_routes()
236 {
237         Sorted sorted;
238
239         // fetch all routes
240         boost::shared_ptr<RouteList> routes = session->get_routes();
241         set<uint32_t> remote_ids;
242
243         // routes with remote_id 0 should never be added
244         // TODO verify this with ardour devs
245         // remote_ids.insert (0);
246
247         // sort in remote_id order, and exclude master, control and hidden routes
248         // and any routes that are already set.
249
250         for (RouteList::iterator it = routes->begin(); it != routes->end(); ++it) {
251
252                 boost::shared_ptr<Route> route = *it;
253
254                 if (remote_ids.find (route->remote_control_id()) != remote_ids.end()) {
255                         continue;
256                 }
257
258                 if (route->is_hidden() || route->is_master() || route->is_monitor()) {
259                         continue;
260                 }
261
262                 /* don't include locked routes */
263
264                 if (route_is_locked_to_strip(route)) {
265                         continue;
266                 }
267
268                 switch (_view_mode) {
269                 case Mixer:
270                         break;
271                 case AudioTracks:
272                         break;
273                 case Busses:
274                         break;
275                 case MidiTracks:
276                         break;
277                 case Dynamics:
278                         break;
279                 case EQ:
280                         break;
281                 case Loop:
282                         break;
283                 case Sends:
284                         break;
285                 case Plugins:
286                         break;
287                 }
288
289                 sorted.push_back (*it);
290                 remote_ids.insert (route->remote_control_id());
291         }
292
293         sort (sorted.begin(), sorted.end(), RouteByRemoteId());
294         return sorted;
295 }
296
297 void 
298 MackieControlProtocol::refresh_current_bank()
299 {
300         switch_banks (_current_initial_bank, true);
301 }
302
303 uint32_t
304 MackieControlProtocol::n_strips (bool with_locked_strips) const
305 {
306         uint32_t strip_count = 0;
307
308         for (Surfaces::const_iterator si = surfaces.begin(); si != surfaces.end(); ++si) {
309                 strip_count += (*si)->n_strips (with_locked_strips);
310         }
311
312         return strip_count;
313 }
314
315 void 
316 MackieControlProtocol::switch_banks (uint32_t initial, bool force)
317 {
318         DEBUG_TRACE (DEBUG::MackieControl, string_compose ("switch banking to start at %1 force ? %2 current = %3\n", initial, force, _current_initial_bank));
319
320         if (initial == _current_initial_bank && !force) {
321                 return;
322         }
323
324         Sorted sorted = get_sorted_routes();
325         uint32_t strip_cnt = n_strips (false); // do not include locked strips
326                                                // in this count
327
328         if (sorted.size() <= strip_cnt && _current_initial_bank == 0 && !force) {
329                 /* no banking - not enough routes to fill all strips and we're
330                  * not at the first one.
331                  */
332                 return;
333         }
334
335         _current_initial_bank = initial;
336         _current_selected_track = -1;
337
338         // Map current bank of routes onto each surface(+strip)
339
340         if (_current_initial_bank <= sorted.size()) {
341
342                 DEBUG_TRACE (DEBUG::MackieControl, string_compose ("switch to %1, %2, available routes %3\n", _current_initial_bank, strip_cnt, sorted.size()));
343
344                 // link routes to strips
345
346                 Sorted::iterator r = sorted.begin() + _current_initial_bank;
347                 
348                 for (Surfaces::iterator si = surfaces.begin(); si != surfaces.end(); ++si) {
349                         vector<boost::shared_ptr<Route> > routes;
350                         uint32_t added = 0;
351
352                         DEBUG_TRACE (DEBUG::MackieControl, string_compose ("surface has %1 unlockedstrips\n", (*si)->n_strips (false)));
353
354                         for (; r != sorted.end() && added < (*si)->n_strips (false); ++r, ++added) {
355                                 routes.push_back (*r);
356                         }
357
358                         DEBUG_TRACE (DEBUG::MackieControl, string_compose ("give surface %1 routes\n", routes.size()));
359
360                         (*si)->map_routes (routes);
361                 }
362         }
363
364         /* reset this to get the right display of view mode after the switch */
365         set_view_mode (_view_mode);
366
367         /* make sure selection is correct */
368         
369         _gui_track_selection_changed (&_last_selected_routes, false);
370         
371         /* current bank has not been saved */
372         session->set_dirty();
373 }
374
375 int 
376 MackieControlProtocol::set_active (bool yn)
377 {
378         DEBUG_TRACE (DEBUG::MackieControl, string_compose("MackieControlProtocol::set_active init with yn: '%1'\n", yn));
379
380         if (yn == _active) {
381                 return 0;
382         }
383
384         if (yn) {
385                 
386                 /* start event loop */
387                 
388                 BaseUI::run ();
389                 
390                 create_surfaces ();
391                 connect_session_signals ();
392                 _active = true;
393                 update_surfaces ();
394                 
395                 /* set up periodic task for metering and automation
396                  */
397                 
398                 Glib::RefPtr<Glib::TimeoutSource> periodic_timeout = Glib::TimeoutSource::create (100); // milliseconds
399                 periodic_connection = periodic_timeout->connect (sigc::mem_fun (*this, &MackieControlProtocol::periodic));
400                 periodic_timeout->attach (main_loop()->get_context());
401                 
402         } else {
403
404                 BaseUI::quit ();
405                 close ();
406                 _active = false;
407
408         }
409
410         DEBUG_TRACE (DEBUG::MackieControl, string_compose("MackieControlProtocol::set_active done with yn: '%1'\n", yn));
411
412         return 0;
413 }
414
415 bool
416 MackieControlProtocol::periodic ()
417 {
418         if (!_active) {
419                 return false;
420         }
421
422         if (needs_ipmidi_restart) {
423                 ipmidi_restart ();
424                 return true;
425         }
426         
427         if (!_initialized) {
428                 initialize();
429         }
430
431         struct timeval now;
432         uint64_t now_usecs;
433         gettimeofday (&now, 0);
434
435         now_usecs = (now.tv_sec * 1000000) + now.tv_usec;
436
437         for (Surfaces::iterator s = surfaces.begin(); s != surfaces.end(); ++s) {
438                 (*s)->periodic (now_usecs);
439         }
440
441         update_timecode_display ();
442         
443         return true;
444 }
445
446 void 
447 MackieControlProtocol::update_timecode_beats_led()
448 {
449         if (!_device_info.has_timecode_display()) {
450                 return;
451         }
452
453         DEBUG_TRACE (DEBUG::MackieControl, string_compose("MackieControlProtocol::update_timecode_beats_led(): %1\n", _timecode_type));
454         switch (_timecode_type) {
455                 case ARDOUR::AnyTime::BBT:
456                         update_global_led (Led::Beats, on);
457                         update_global_led (Led::Timecode, off);
458                         break;
459                 case ARDOUR::AnyTime::Timecode:
460                         update_global_led (Led::Timecode, on);
461                         update_global_led (Led::Beats, off);
462                         break;
463                 default:
464                         ostringstream os;
465                         os << "Unknown Anytime::Type " << _timecode_type;
466                         throw runtime_error (os.str());
467         }
468 }
469
470 void 
471 MackieControlProtocol::update_global_button (int id, LedState ls)
472 {
473         if (!_device_info.has_global_controls()) {
474                 return;
475         }
476
477         boost::shared_ptr<Surface> surface = surfaces.front();
478
479         map<int,Control*>::iterator x = surface->controls_by_device_independent_id.find (id);
480         if (x != surface->controls_by_device_independent_id.end()) {
481                 Button * button = dynamic_cast<Button*> (x->second);
482                 surface->write (button->set_state (ls));
483         } else {
484                 DEBUG_TRACE (DEBUG::MackieControl, string_compose ("Button %1 not found\n", id));
485         }
486 }
487
488 void 
489 MackieControlProtocol::update_global_led (int id, LedState ls)
490 {
491         if (!_device_info.has_global_controls()) {
492                 return;
493         }
494
495         boost::shared_ptr<Surface> surface = surfaces.front();
496
497         map<int,Control*>::iterator x = surface->controls_by_device_independent_id.find (id);
498
499         if (x != surface->controls_by_device_independent_id.end()) {
500                 Led * led = dynamic_cast<Led*> (x->second);
501                 DEBUG_TRACE (DEBUG::MackieControl, "Writing LedState\n");
502                 surface->write (led->set_state (ls));
503         } else {
504                 DEBUG_TRACE (DEBUG::MackieControl, string_compose ("Led %1 not found\n", id));
505         }
506 }
507
508 // send messages to surface to set controls to correct values
509 void 
510 MackieControlProtocol::update_surfaces()
511 {
512         DEBUG_TRACE (DEBUG::MackieControl, "MackieControlProtocol::update_surfaces() init\n");
513         if (!_active) {
514                 return;
515         }
516
517         // do the initial bank switch to connect signals
518         // _current_initial_bank is initialised by set_state
519         switch_banks (_current_initial_bank, true);
520         
521         DEBUG_TRACE (DEBUG::MackieControl, "MackieControlProtocol::update_surfaces() finished\n");
522 }
523
524 void
525 MackieControlProtocol::initialize()
526 {
527         if (!surfaces.front()->active ()) {
528                 return;
529         }
530
531         // sometimes the jog wheel is a pot
532         if (_device_info.has_jog_wheel()) {
533                 surfaces.front()->blank_jog_ring ();
534         }
535         
536         // update global buttons and displays
537
538         notify_record_state_changed();
539         notify_transport_state_changed();
540         update_timecode_beats_led();
541         
542         _initialized = true;
543 }
544
545 void 
546 MackieControlProtocol::connect_session_signals()
547 {
548         // receive routes added
549         session->RouteAdded.connect(session_connections, MISSING_INVALIDATOR, boost::bind (&MackieControlProtocol::notify_route_added, this, _1), this);
550         // receive record state toggled
551         session->RecordStateChanged.connect(session_connections, MISSING_INVALIDATOR, boost::bind (&MackieControlProtocol::notify_record_state_changed, this), this);
552         // receive transport state changed
553         session->TransportStateChange.connect(session_connections, MISSING_INVALIDATOR, boost::bind (&MackieControlProtocol::notify_transport_state_changed, this), this);
554         session->TransportLooped.connect (session_connections, MISSING_INVALIDATOR, boost::bind (&MackieControlProtocol::notify_loop_state_changed, this), this);
555         // receive punch-in and punch-out
556         Config->ParameterChanged.connect(session_connections, MISSING_INVALIDATOR, boost::bind (&MackieControlProtocol::notify_parameter_changed, this, _1), this);
557         session->config.ParameterChanged.connect (session_connections, MISSING_INVALIDATOR, boost::bind (&MackieControlProtocol::notify_parameter_changed, this, _1), this);
558         // receive rude solo changed
559         session->SoloActive.connect(session_connections, MISSING_INVALIDATOR, boost::bind (&MackieControlProtocol::notify_solo_active_changed, this, _1), this);
560
561         // make sure remote id changed signals reach here
562         // see also notify_route_added
563         Sorted sorted = get_sorted_routes();
564
565         for (Sorted::iterator it = sorted.begin(); it != sorted.end(); ++it) {
566                 (*it)->RemoteControlIDChanged.connect (route_connections, MISSING_INVALIDATOR, boost::bind (&MackieControlProtocol::notify_remote_id_changed, this), this);
567         }
568 }
569
570 void
571 MackieControlProtocol::set_profile (const string& profile_name)
572 {
573         if (profile_name == "default") {
574                 /* reset to default */
575                 _device_profile = DeviceProfile (profile_name);
576         }
577
578         map<string,DeviceProfile>::iterator d = DeviceProfile::device_profiles.find (profile_name);
579
580         if (d == DeviceProfile::device_profiles.end()) {
581                 return;
582         }
583         
584         _device_profile = d->second;
585 }       
586
587 void
588 MackieControlProtocol::set_device (const string& device_name, bool allow_activation)
589 {
590         map<string,DeviceInfo>::iterator d = DeviceInfo::device_info.find (device_name);
591
592         if (d == DeviceInfo::device_info.end()) {
593                 return;
594         }
595         
596         if (_active) {
597                 clear_ports ();
598                 surfaces.clear ();      
599         }
600
601         _device_info = d->second;
602
603         if (allow_activation) {
604                 set_active (true);
605         } else {
606                 if (_active) {
607                         create_surfaces ();
608                         switch_banks (0, true);
609                 }
610         }
611 }
612
613 void 
614 MackieControlProtocol::create_surfaces ()
615 {
616         string device_name;
617         surface_type_t stype = mcu;
618         char buf[128];
619
620         if (_device_info.extenders() == 0) {
621                 device_name = X_("mackie control");
622         } else {
623                 device_name = X_("mackie control #1");
624         }
625
626         DEBUG_TRACE (DEBUG::MackieControl, string_compose ("Create %1 surfaces\n", 1 + _device_info.extenders()));
627
628         for (uint32_t n = 0; n < 1 + _device_info.extenders(); ++n) {
629
630                 boost::shared_ptr<Surface> surface (new Surface (*this, device_name, n, stype));
631                 surfaces.push_back (surface);
632
633                 /* next device will be an extender */
634                 
635                 if (_device_info.extenders() < 2) {
636                         device_name = X_("mackie control #2");
637                 } else {
638                         snprintf (buf, sizeof (buf), X_("mackie control #%d"), n+2);
639                         device_name = buf;
640                 }
641                 stype = ext;
642
643                 if (!_device_info.uses_ipmidi()) {
644                         _input_bundle->add_channel (
645                                 surface->port().input_port().name(),
646                                 ARDOUR::DataType::MIDI,
647                                 session->engine().make_port_name_non_relative (surface->port().input_port().name())
648                                 );
649                         
650                         _output_bundle->add_channel (
651                                 surface->port().output_port().name(),
652                                 ARDOUR::DataType::MIDI,
653                                 session->engine().make_port_name_non_relative (surface->port().output_port().name())
654                                 );
655                 }
656
657                 int fd;
658                 MIDI::Port& input_port (surface->port().input_port());
659
660                 if ((fd = input_port.selectable ()) >= 0) {
661                         Glib::RefPtr<IOSource> psrc = IOSource::create (fd, IO_IN|IO_HUP|IO_ERR);
662
663                         psrc->connect (sigc::bind (sigc::mem_fun (this, &MackieControlProtocol::midi_input_handler), &input_port));
664                         psrc->attach (main_loop()->get_context());
665                         
666                         // glibmm hack: for now, store only the GSource*
667
668                         port_sources.push_back (psrc->gobj());
669                         g_source_ref (psrc->gobj());
670                 }
671         }
672 }
673
674 void 
675 MackieControlProtocol::close()
676 {
677         clear_ports ();
678
679         port_connections.drop_connections ();
680         session_connections.drop_connections ();
681         route_connections.drop_connections ();
682         periodic_connection.disconnect ();
683
684         surfaces.clear ();
685 }
686
687 XMLNode& 
688 MackieControlProtocol::get_state()
689 {
690         DEBUG_TRACE (DEBUG::MackieControl, "MackieControlProtocol::get_state init\n");
691         char buf[16];
692
693         // add name of protocol
694         XMLNode* node = new XMLNode (X_("Protocol"));
695         node->add_property (X_("name"), ARDOUR::ControlProtocol::_name);
696
697         // add current bank
698         snprintf (buf, sizeof (buf), "%d", _current_initial_bank);
699         node->add_property (X_("bank"), buf);
700
701         // ipMIDI base port (possibly not used)
702         snprintf (buf, sizeof (buf), "%d", _ipmidi_base);
703         node->add_property (X_("ipmidi-base"), buf);
704
705         node->add_property (X_("device-profile"), _device_profile.name());
706         node->add_property (X_("device-name"), _device_info.name());
707
708         DEBUG_TRACE (DEBUG::MackieControl, "MackieControlProtocol::get_state done\n");
709
710         return *node;
711 }
712
713 int 
714 MackieControlProtocol::set_state (const XMLNode & node, int /*version*/)
715 {
716         DEBUG_TRACE (DEBUG::MackieControl, string_compose ("MackieControlProtocol::set_state: active %1\n", _active));
717
718         int retval = 0;
719         const XMLProperty* prop;
720         uint32_t bank = 0;
721         bool active = _active;
722
723         if ((prop = node.property (X_("ipmidi-base"))) != 0) {
724                 set_ipmidi_base (atoi (prop->value()));
725         }
726
727         // fetch current bank
728         if ((prop = node.property (X_("bank"))) != 0) {
729                 bank = atoi (prop->value());
730         }
731         
732         if ((prop = node.property (X_("active"))) != 0) {
733                 active = string_is_affirmative (prop->value());
734         }
735
736         if ((prop = node.property (X_("device-name"))) != 0) {
737                 set_device (prop->value(), false);
738         }
739
740         if ((prop = node.property (X_("device-profile"))) != 0) {
741                 set_profile (prop->value());
742         }
743
744         set_active (active);
745
746         if (_active) {
747                 switch_banks (bank, true);
748         }
749
750         DEBUG_TRACE (DEBUG::MackieControl, "MackieControlProtocol::set_state done\n");
751
752         return retval;
753 }
754
755 string 
756 MackieControlProtocol::format_bbt_timecode (framepos_t now_frame)
757 {
758         Timecode::BBT_Time bbt_time;
759
760         session->bbt_time (now_frame, bbt_time);
761
762         // The Mackie protocol spec is built around a BBT time display of
763         //
764         // digits:     888/88/88/888
765         // semantics:  BBB/bb/ss/ttt
766         //
767         // The third field is "subdivisions" which is a concept found in Logic
768         // but not present in Ardour. Instead Ardour displays a 4 digit tick
769         // count, which we need to spread across the 5 digits of ss/ttt.
770
771         ostringstream os;
772
773         os << setw(3) << setfill('0') << bbt_time.bars;
774         os << setw(2) << setfill('0') << bbt_time.beats;
775         os << ' ';
776         os << setw(1) << setfill('0') << bbt_time.ticks / 1000;
777         os << setw(3) << setfill('0') << bbt_time.ticks % 1000;
778
779         return os.str();
780 }
781
782 string 
783 MackieControlProtocol::format_timecode_timecode (framepos_t now_frame)
784 {
785         Timecode::Time timecode;
786         session->timecode_time (now_frame, timecode);
787
788         // According to the Logic docs
789         // digits: 888/88/88/888
790         // Timecode mode: Hours/Minutes/Seconds/Frames
791         ostringstream os;
792         os << setw(2) << setfill('0') << timecode.hours;
793         os << ' ';
794         os << setw(2) << setfill('0') << timecode.minutes;
795         os << setw(2) << setfill('0') << timecode.seconds;
796         os << ' ';
797         os << setw(2) << setfill('0') << timecode.frames;
798
799         return os.str();
800 }
801
802 void 
803 MackieControlProtocol::update_timecode_display()
804 {
805         if (surfaces.empty()) {
806                 return;
807         }
808
809         boost::shared_ptr<Surface> surface = surfaces.front();
810
811         if (surface->type() != mcu || !_device_info.has_timecode_display() || !surface->active ()) {
812                 return;
813         }
814
815         // do assignment here so current_frame is fixed
816         framepos_t current_frame = session->transport_frame();
817         string timecode;
818
819         switch (_timecode_type) {
820         case ARDOUR::AnyTime::BBT:
821                 timecode = format_bbt_timecode (current_frame);
822                 break;
823         case ARDOUR::AnyTime::Timecode:
824                 timecode = format_timecode_timecode (current_frame);
825                 break;
826         default:
827                 return;
828         }
829         
830         // only write the timecode string to the MCU if it's changed
831         // since last time. This is to reduce midi bandwidth used.
832         if (timecode != _timecode_last) {
833                 surface->display_timecode (timecode, _timecode_last);
834                 _timecode_last = timecode;
835         }
836 }
837
838 ///////////////////////////////////////////
839 // Session signals
840 ///////////////////////////////////////////
841
842 void MackieControlProtocol::notify_parameter_changed (std::string const & p)
843 {
844         if (p == "punch-in") {
845                 update_global_button (Button::PunchIn, session->config.get_punch_in());
846         } else if (p == "punch-out") {
847                 update_global_button (Button::PunchOut, session->config.get_punch_out());
848         } else if (p == "clicking") {
849                 // update_global_button (Button::RelayClick, Config->get_clicking());
850         } else {
851                 DEBUG_TRACE (DEBUG::MackieControl, string_compose ("parameter changed: %1\n", p));
852         }
853 }
854
855 // RouteList is the set of routes that have just been added
856 void 
857 MackieControlProtocol::notify_route_added (ARDOUR::RouteList & rl)
858 {
859         // currently assigned banks are less than the full set of
860         // strips, so activate the new strip now.
861
862         refresh_current_bank();
863
864         // otherwise route added, but current bank needs no updating
865
866         // make sure remote id changes in the new route are handled
867         typedef ARDOUR::RouteList ARS;
868
869         for (ARS::iterator it = rl.begin(); it != rl.end(); ++it) {
870                 (*it)->RemoteControlIDChanged.connect (route_connections, MISSING_INVALIDATOR, boost::bind (&MackieControlProtocol::notify_remote_id_changed, this), this);
871         }
872 }
873
874 void 
875 MackieControlProtocol::notify_solo_active_changed (bool active)
876 {
877         boost::shared_ptr<Surface> surface = surfaces.front();
878         
879         map<int,Control*>::iterator x = surface->controls_by_device_independent_id.find (Led::RudeSolo);
880         if (x != surface->controls_by_device_independent_id.end()) {
881                 Led* rude_solo = dynamic_cast<Led*> (x->second);
882                 if (rude_solo) {
883                         surface->write (rude_solo->set_state (active ? flashing : off));
884                 }
885         }
886 }
887
888 void 
889 MackieControlProtocol::notify_remote_id_changed()
890 {
891         Sorted sorted = get_sorted_routes();
892         uint32_t sz = n_strips();
893
894         // if a remote id has been moved off the end, we need to shift
895         // the current bank backwards.
896
897         if (sorted.size() - _current_initial_bank < sz) {
898                 // but don't shift backwards past the zeroth channel
899                 switch_banks (max((Sorted::size_type) 0, sorted.size() - sz));
900         } else {
901                 // Otherwise just refresh the current bank
902                 refresh_current_bank();
903         }
904 }
905
906 ///////////////////////////////////////////
907 // Transport signals
908 ///////////////////////////////////////////
909
910 void 
911 MackieControlProtocol::notify_loop_state_changed()
912 {
913         update_global_button (Button::Loop, session->get_play_loop());
914 }
915
916 void 
917 MackieControlProtocol::notify_transport_state_changed()
918 {
919         if (!_device_info.has_global_controls()) {
920                 return;
921         }
922
923         // switch various play and stop buttons on / off
924         update_global_button (Button::Loop, session->get_play_loop());
925         update_global_button (Button::Play, session->transport_speed() == 1.0);
926         update_global_button (Button::Stop, session->transport_stopped ());
927         update_global_button (Button::Rewind, session->transport_speed() < 0.0);
928         update_global_button (Button::Ffwd, session->transport_speed() > 1.0);
929
930         notify_metering_state_changed ();
931 }
932
933 void 
934 MackieControlProtocol::notify_metering_state_changed()
935 {
936         for (Surfaces::iterator s = surfaces.begin(); s != surfaces.end(); ++s) {
937                 (*s)->notify_metering_state_changed ();
938         }       
939 }
940
941 void
942 MackieControlProtocol::notify_record_state_changed ()
943 {
944         if (!_device_info.has_global_controls()) {
945                 return;
946         }
947         boost::shared_ptr<Surface> surface = surfaces.front();
948
949         /* rec is a tristate */
950
951         map<int,Control*>::iterator x = surface->controls_by_device_independent_id.find (Button::Record);
952         if (x != surface->controls_by_device_independent_id.end()) {
953                 Button * rec = dynamic_cast<Button*> (x->second);
954                 if (rec) {
955                         LedState ls;
956                         
957                         switch (session->record_status()) {
958                         case Session::Disabled:
959                                 DEBUG_TRACE (DEBUG::MackieControl, "record state changed to disabled, LED off\n");
960                                 ls = off;
961                                 break;
962                         case Session::Recording:
963                                 DEBUG_TRACE (DEBUG::MackieControl, "record state changed to recording, LED on\n");
964                                 ls = on;
965                                 break;
966                         case Session::Enabled:
967                                 DEBUG_TRACE (DEBUG::MackieControl, "record state changed to enabled, LED flashing\n");
968                                 ls = flashing;
969                                 break;
970                         }
971
972                         surface->write (rec->set_state (ls));
973                 }
974         }
975 }
976
977 list<boost::shared_ptr<ARDOUR::Bundle> >
978 MackieControlProtocol::bundles ()
979 {
980         list<boost::shared_ptr<ARDOUR::Bundle> > b;
981         b.push_back (_input_bundle);
982         b.push_back (_output_bundle);
983         return b;
984 }
985
986 void
987 MackieControlProtocol::do_request (MackieControlUIRequest* req)
988 {
989         if (req->type == CallSlot) {
990
991                 call_slot (MISSING_INVALIDATOR, req->the_slot);
992
993         } else if (req->type == Quit) {
994
995                 stop ();
996         }
997 }
998
999 int
1000 MackieControlProtocol::stop ()
1001 {
1002         BaseUI::quit ();
1003
1004         return 0;
1005 }
1006
1007 void 
1008 MackieControlProtocol::update_led (Surface& surface, Button& button, Mackie::LedState ls)
1009 {
1010         if (ls != none) {
1011                 surface.port().write (button.set_state (ls));
1012         }
1013 }
1014
1015 void
1016 MackieControlProtocol::build_button_map ()
1017 {
1018         /* this maps our device-independent button codes to the methods that handle them.
1019          */
1020
1021 #define DEFINE_BUTTON_HANDLER(b,p,r) button_map.insert (pair<Button::ID,ButtonHandlers> ((b), ButtonHandlers ((p),(r))));
1022
1023         DEFINE_BUTTON_HANDLER (Button::IO, &MackieControlProtocol::io_press, &MackieControlProtocol::io_release);
1024         DEFINE_BUTTON_HANDLER (Button::Sends, &MackieControlProtocol::sends_press, &MackieControlProtocol::sends_release);
1025         DEFINE_BUTTON_HANDLER (Button::Pan, &MackieControlProtocol::pan_press, &MackieControlProtocol::pan_release);
1026         DEFINE_BUTTON_HANDLER (Button::Plugin, &MackieControlProtocol::plugin_press, &MackieControlProtocol::plugin_release);
1027         DEFINE_BUTTON_HANDLER (Button::Eq, &MackieControlProtocol::eq_press, &MackieControlProtocol::eq_release);
1028         DEFINE_BUTTON_HANDLER (Button::Dyn, &MackieControlProtocol::dyn_press, &MackieControlProtocol::dyn_release);
1029         DEFINE_BUTTON_HANDLER (Button::Left, &MackieControlProtocol::left_press, &MackieControlProtocol::left_release);
1030         DEFINE_BUTTON_HANDLER (Button::Right, &MackieControlProtocol::right_press, &MackieControlProtocol::right_release);
1031         DEFINE_BUTTON_HANDLER (Button::ChannelLeft, &MackieControlProtocol::channel_left_press, &MackieControlProtocol::channel_left_release);
1032         DEFINE_BUTTON_HANDLER (Button::ChannelRight, &MackieControlProtocol::channel_right_press, &MackieControlProtocol::channel_right_release);
1033         DEFINE_BUTTON_HANDLER (Button::Flip, &MackieControlProtocol::flip_press, &MackieControlProtocol::flip_release);
1034         DEFINE_BUTTON_HANDLER (Button::Edit, &MackieControlProtocol::edit_press, &MackieControlProtocol::edit_release);
1035         DEFINE_BUTTON_HANDLER (Button::NameValue, &MackieControlProtocol::name_value_press, &MackieControlProtocol::name_value_release);
1036         DEFINE_BUTTON_HANDLER (Button::TimecodeBeats, &MackieControlProtocol::timecode_beats_press, &MackieControlProtocol::timecode_beats_release);
1037         DEFINE_BUTTON_HANDLER (Button::F1, &MackieControlProtocol::F1_press, &MackieControlProtocol::F1_release);
1038         DEFINE_BUTTON_HANDLER (Button::F2, &MackieControlProtocol::F2_press, &MackieControlProtocol::F2_release);
1039         DEFINE_BUTTON_HANDLER (Button::F3, &MackieControlProtocol::F3_press, &MackieControlProtocol::F3_release);
1040         DEFINE_BUTTON_HANDLER (Button::F4, &MackieControlProtocol::F4_press, &MackieControlProtocol::F4_release);
1041         DEFINE_BUTTON_HANDLER (Button::F5, &MackieControlProtocol::F5_press, &MackieControlProtocol::F5_release);
1042         DEFINE_BUTTON_HANDLER (Button::F6, &MackieControlProtocol::F6_press, &MackieControlProtocol::F6_release);
1043         DEFINE_BUTTON_HANDLER (Button::F7, &MackieControlProtocol::F7_press, &MackieControlProtocol::F7_release);
1044         DEFINE_BUTTON_HANDLER (Button::F8, &MackieControlProtocol::F8_press, &MackieControlProtocol::F8_release);
1045         DEFINE_BUTTON_HANDLER (Button::F9, &MackieControlProtocol::F9_press, &MackieControlProtocol::F9_release);
1046         DEFINE_BUTTON_HANDLER (Button::F10, &MackieControlProtocol::F10_press, &MackieControlProtocol::F10_release);
1047         DEFINE_BUTTON_HANDLER (Button::F11, &MackieControlProtocol::F11_press, &MackieControlProtocol::F11_release);
1048         DEFINE_BUTTON_HANDLER (Button::F12, &MackieControlProtocol::F12_press, &MackieControlProtocol::F12_release);
1049         DEFINE_BUTTON_HANDLER (Button::F13, &MackieControlProtocol::F13_press, &MackieControlProtocol::F13_release);
1050         DEFINE_BUTTON_HANDLER (Button::F14, &MackieControlProtocol::F14_press, &MackieControlProtocol::F14_release);
1051         DEFINE_BUTTON_HANDLER (Button::F15, &MackieControlProtocol::F15_press, &MackieControlProtocol::F15_release);
1052         DEFINE_BUTTON_HANDLER (Button::F16, &MackieControlProtocol::F16_press, &MackieControlProtocol::F16_release);
1053         DEFINE_BUTTON_HANDLER (Button::Shift, &MackieControlProtocol::shift_press, &MackieControlProtocol::shift_release);
1054         DEFINE_BUTTON_HANDLER (Button::Option, &MackieControlProtocol::option_press, &MackieControlProtocol::option_release);
1055         DEFINE_BUTTON_HANDLER (Button::Ctrl, &MackieControlProtocol::control_press, &MackieControlProtocol::control_release);
1056         DEFINE_BUTTON_HANDLER (Button::CmdAlt, &MackieControlProtocol::cmd_alt_press, &MackieControlProtocol::cmd_alt_release);
1057         DEFINE_BUTTON_HANDLER (Button::On, &MackieControlProtocol::on_press, &MackieControlProtocol::on_release);
1058         DEFINE_BUTTON_HANDLER (Button::RecReady, &MackieControlProtocol::rec_ready_press, &MackieControlProtocol::rec_ready_release);
1059         DEFINE_BUTTON_HANDLER (Button::Undo, &MackieControlProtocol::undo_press, &MackieControlProtocol::undo_release);
1060         DEFINE_BUTTON_HANDLER (Button::Save, &MackieControlProtocol::save_press, &MackieControlProtocol::save_release);
1061         DEFINE_BUTTON_HANDLER (Button::Touch, &MackieControlProtocol::touch_press, &MackieControlProtocol::touch_release);
1062         DEFINE_BUTTON_HANDLER (Button::Redo, &MackieControlProtocol::redo_press, &MackieControlProtocol::redo_release);
1063         DEFINE_BUTTON_HANDLER (Button::Marker, &MackieControlProtocol::marker_press, &MackieControlProtocol::marker_release);
1064         DEFINE_BUTTON_HANDLER (Button::Enter, &MackieControlProtocol::enter_press, &MackieControlProtocol::enter_release);
1065         DEFINE_BUTTON_HANDLER (Button::Cancel, &MackieControlProtocol::cancel_press, &MackieControlProtocol::cancel_release);
1066         DEFINE_BUTTON_HANDLER (Button::Mixer, &MackieControlProtocol::mixer_press, &MackieControlProtocol::mixer_release);
1067         DEFINE_BUTTON_HANDLER (Button::FrmLeft, &MackieControlProtocol::frm_left_press, &MackieControlProtocol::frm_left_release);
1068         DEFINE_BUTTON_HANDLER (Button::FrmRight, &MackieControlProtocol::frm_right_press, &MackieControlProtocol::frm_right_release);
1069         DEFINE_BUTTON_HANDLER (Button::Loop, &MackieControlProtocol::loop_press, &MackieControlProtocol::loop_release);
1070         DEFINE_BUTTON_HANDLER (Button::PunchIn, &MackieControlProtocol::punch_in_press, &MackieControlProtocol::punch_in_release);
1071         DEFINE_BUTTON_HANDLER (Button::PunchOut, &MackieControlProtocol::punch_out_press, &MackieControlProtocol::punch_out_release);
1072         DEFINE_BUTTON_HANDLER (Button::Home, &MackieControlProtocol::home_press, &MackieControlProtocol::home_release);
1073         DEFINE_BUTTON_HANDLER (Button::End, &MackieControlProtocol::end_press, &MackieControlProtocol::end_release);
1074         DEFINE_BUTTON_HANDLER (Button::Rewind, &MackieControlProtocol::rewind_press, &MackieControlProtocol::rewind_release);
1075         DEFINE_BUTTON_HANDLER (Button::Ffwd, &MackieControlProtocol::ffwd_press, &MackieControlProtocol::ffwd_release);
1076         DEFINE_BUTTON_HANDLER (Button::Stop, &MackieControlProtocol::stop_press, &MackieControlProtocol::stop_release);
1077         DEFINE_BUTTON_HANDLER (Button::Play, &MackieControlProtocol::play_press, &MackieControlProtocol::play_release);
1078         DEFINE_BUTTON_HANDLER (Button::Record, &MackieControlProtocol::record_press, &MackieControlProtocol::record_release);
1079         DEFINE_BUTTON_HANDLER (Button::CursorUp, &MackieControlProtocol::cursor_up_press, &MackieControlProtocol::cursor_up_release);
1080         DEFINE_BUTTON_HANDLER (Button::CursorDown, &MackieControlProtocol::cursor_down_press, &MackieControlProtocol::cursor_down_release);
1081         DEFINE_BUTTON_HANDLER (Button::CursorLeft, &MackieControlProtocol::cursor_left_press, &MackieControlProtocol::cursor_left_release);
1082         DEFINE_BUTTON_HANDLER (Button::CursorRight, &MackieControlProtocol::cursor_right_press, &MackieControlProtocol::cursor_right_release);
1083         DEFINE_BUTTON_HANDLER (Button::Zoom, &MackieControlProtocol::zoom_press, &MackieControlProtocol::zoom_release);
1084         DEFINE_BUTTON_HANDLER (Button::Scrub, &MackieControlProtocol::scrub_press, &MackieControlProtocol::scrub_release);
1085         DEFINE_BUTTON_HANDLER (Button::UserA, &MackieControlProtocol::user_a_press, &MackieControlProtocol::user_a_release);
1086         DEFINE_BUTTON_HANDLER (Button::UserB, &MackieControlProtocol::user_b_press, &MackieControlProtocol::user_b_release);
1087         DEFINE_BUTTON_HANDLER (Button::MasterFaderTouch, &MackieControlProtocol::master_fader_touch_press, &MackieControlProtocol::master_fader_touch_release);
1088
1089         DEFINE_BUTTON_HANDLER (Button::Snapshot, &MackieControlProtocol::snapshot_press, &MackieControlProtocol::snapshot_release);
1090         DEFINE_BUTTON_HANDLER (Button::Read, &MackieControlProtocol::read_press, &MackieControlProtocol::read_release);
1091         DEFINE_BUTTON_HANDLER (Button::Write, &MackieControlProtocol::write_press, &MackieControlProtocol::write_release);
1092         DEFINE_BUTTON_HANDLER (Button::FdrGroup, &MackieControlProtocol::fdrgroup_press, &MackieControlProtocol::fdrgroup_release);
1093         DEFINE_BUTTON_HANDLER (Button::ClearSolo, &MackieControlProtocol::clearsolo_press, &MackieControlProtocol::clearsolo_release);
1094         DEFINE_BUTTON_HANDLER (Button::Track, &MackieControlProtocol::track_press, &MackieControlProtocol::track_release);
1095         DEFINE_BUTTON_HANDLER (Button::Send, &MackieControlProtocol::send_press, &MackieControlProtocol::send_release);
1096         DEFINE_BUTTON_HANDLER (Button::MidiTracks, &MackieControlProtocol::miditracks_press, &MackieControlProtocol::miditracks_release);
1097         DEFINE_BUTTON_HANDLER (Button::Inputs, &MackieControlProtocol::inputs_press, &MackieControlProtocol::inputs_release);
1098         DEFINE_BUTTON_HANDLER (Button::AudioTracks, &MackieControlProtocol::audiotracks_press, &MackieControlProtocol::audiotracks_release);
1099         DEFINE_BUTTON_HANDLER (Button::AudioInstruments, &MackieControlProtocol::audioinstruments_press, &MackieControlProtocol::audioinstruments_release);
1100         DEFINE_BUTTON_HANDLER (Button::Aux, &MackieControlProtocol::aux_press, &MackieControlProtocol::aux_release);
1101         DEFINE_BUTTON_HANDLER (Button::Busses, &MackieControlProtocol::busses_press, &MackieControlProtocol::busses_release);
1102         DEFINE_BUTTON_HANDLER (Button::Outputs, &MackieControlProtocol::outputs_press, &MackieControlProtocol::outputs_release);
1103         DEFINE_BUTTON_HANDLER (Button::User, &MackieControlProtocol::user_press, &MackieControlProtocol::user_release);
1104         DEFINE_BUTTON_HANDLER (Button::Trim, &MackieControlProtocol::trim_press, &MackieControlProtocol::trim_release);
1105         DEFINE_BUTTON_HANDLER (Button::Latch, &MackieControlProtocol::latch_press, &MackieControlProtocol::latch_release);
1106         DEFINE_BUTTON_HANDLER (Button::Grp, &MackieControlProtocol::grp_press, &MackieControlProtocol::grp_release);
1107         DEFINE_BUTTON_HANDLER (Button::Nudge, &MackieControlProtocol::nudge_press, &MackieControlProtocol::nudge_release);
1108         DEFINE_BUTTON_HANDLER (Button::Drop, &MackieControlProtocol::drop_press, &MackieControlProtocol::drop_release);
1109         DEFINE_BUTTON_HANDLER (Button::Replace, &MackieControlProtocol::replace_press, &MackieControlProtocol::replace_release);
1110         DEFINE_BUTTON_HANDLER (Button::Click, &MackieControlProtocol::click_press, &MackieControlProtocol::click_release);
1111         DEFINE_BUTTON_HANDLER (Button::View, &MackieControlProtocol::view_press, &MackieControlProtocol::view_release);
1112 }
1113
1114 void 
1115 MackieControlProtocol::handle_button_event (Surface& surface, Button& button, ButtonState bs)
1116 {
1117         if  (bs != press && bs != release) {
1118                 update_led (surface, button, none);
1119                 return;
1120         }
1121         
1122         DEBUG_TRACE (DEBUG::MackieControl, string_compose ("Handling %1 for button %2 (%3)\n", (bs == press ? "press" : "release"), button.id(),
1123                                                            Button::id_to_name (button.bid())));
1124
1125         /* check profile first */
1126         
1127         string action = _device_profile.get_button_action (button.bid(), _modifier_state);
1128         
1129         DEBUG_TRACE (DEBUG::MackieControl, string_compose ("Looked up action for button %1 with modifier %2, got [%3]\n",
1130                                                            button.bid(), _modifier_state, action));
1131
1132         if (!action.empty()) {
1133                 /* if there is a bound action for this button, and this is a press event,
1134                    carry out the action. If its a release event, do nothing since we 
1135                    don't bind to them at all but don't want any other handling to 
1136                    occur either.
1137                 */
1138                 if (bs == press) {
1139                         DEBUG_TRACE (DEBUG::MackieControl, string_compose ("executing action %1\n", action));
1140                         access_action (action);
1141                 }
1142                 return;
1143         }
1144
1145         /* lookup using the device-INDEPENDENT button ID */
1146
1147         ButtonMap::iterator b = button_map.find (button.bid());
1148
1149         if (b != button_map.end()) {
1150
1151                 ButtonHandlers& bh (b->second);
1152
1153                 switch  (bs) {
1154                 case press: 
1155                         surface.write (button.set_state ((this->*(bh.press)) (button)));
1156                         break;
1157                 case release: 
1158                         surface.write (button.set_state ((this->*(bh.release)) (button)));
1159                         break;
1160                 default:
1161                         break;
1162                 }
1163         } else {
1164                 DEBUG_TRACE (DEBUG::MackieControl, string_compose ("no button handlers for button ID %1 (device ID %2)\n", 
1165                                                                    button.bid(), button.id()));
1166                 error << string_compose ("no button handlers for button ID %1 (device ID %2)\n", 
1167                                          button.bid(), button.id()) << endmsg;
1168         }
1169 }
1170
1171 bool
1172 MackieControlProtocol::midi_input_handler (IOCondition ioc, MIDI::Port* port)
1173 {
1174         DEBUG_TRACE (DEBUG::MackieControl, string_compose ("something happend on  %1\n", port->name()));
1175
1176         if (ioc & ~IO_IN) {
1177                 return false;
1178         }
1179
1180         if (ioc & IO_IN) {
1181
1182                 /* Devices using regular JACK MIDI ports will need to have
1183                    the x-thread FIFO drained to avoid burning endless CPU.
1184
1185                    Devices using ipMIDI have port->selectable() as the same
1186                    file descriptor that data arrives on, so doing this
1187                    for them will simply throw all incoming data away.
1188                 */
1189
1190                 if (!_device_info.uses_ipmidi()) {
1191                         CrossThreadChannel::drain (port->selectable());
1192                 }
1193
1194                 DEBUG_TRACE (DEBUG::MackieControl, string_compose ("data available on %1\n", port->name()));
1195                 framepos_t now = session->engine().frame_time();
1196                 port->parse (now);
1197         }
1198
1199         return true;
1200 }
1201
1202 void
1203 MackieControlProtocol::clear_ports ()
1204 {
1205         _input_bundle->remove_channels ();
1206         _output_bundle->remove_channels ();
1207
1208         for (PortSources::iterator i = port_sources.begin(); i != port_sources.end(); ++i) {
1209                 g_source_destroy (*i);
1210                 g_source_unref (*i);
1211         }
1212
1213         port_sources.clear ();
1214 }
1215
1216 void
1217 MackieControlProtocol::set_view_mode (ViewMode m)
1218 {
1219         _view_mode = m;
1220
1221         for (Surfaces::iterator s = surfaces.begin(); s != surfaces.end(); ++s) {
1222                 (*s)->update_view_mode_display ();
1223         }
1224         
1225 }
1226
1227 void
1228 MackieControlProtocol::set_flip_mode (bool yn)
1229 {
1230         _flip_mode = yn;
1231         
1232         for (Surfaces::iterator s = surfaces.begin(); s != surfaces.end(); ++s) {
1233                 (*s)->update_flip_mode_display ();
1234         }
1235 }
1236         
1237 void
1238 MackieControlProtocol::set_master_on_surface_strip (uint32_t surface, uint32_t strip_number)
1239 {
1240         force_special_route_to_strip (session->master_out(), surface, strip_number);
1241 }
1242
1243 void
1244 MackieControlProtocol::set_monitor_on_surface_strip (uint32_t surface, uint32_t strip_number)
1245 {
1246         force_special_route_to_strip (session->monitor_out(), surface, strip_number);
1247 }
1248
1249 void
1250 MackieControlProtocol::force_special_route_to_strip (boost::shared_ptr<Route> r, uint32_t surface, uint32_t strip_number)
1251 {
1252         if (!r) {
1253                 return;
1254         }
1255
1256         for (Surfaces::iterator s = surfaces.begin(); s != surfaces.end(); ++s) {
1257                 if ((*s)->number() == surface) {
1258                         Strip* strip = (*s)->nth_strip (strip_number);
1259                         if (strip) {
1260                                 strip->set_route (session->master_out());
1261                                 strip->lock_controls ();
1262                         }
1263                 }
1264         }
1265 }
1266
1267 void
1268 MackieControlProtocol::gui_track_selection_changed (ARDOUR::RouteNotificationListPtr rl, bool save_list)
1269 {
1270         _gui_track_selection_changed (rl.get(), save_list);
1271 }
1272
1273 void
1274 MackieControlProtocol::_gui_track_selection_changed (ARDOUR::RouteNotificationList* rl, bool save_list)
1275 {
1276
1277         /* We need to keep a list of the most recently selected routes around,
1278            but we are not allowed to keep shared_ptr<Route> unless we want to
1279            handle the complexities of route deletion. So instead, the GUI sends
1280            us a notification using weak_ptr<Route>, which we keep a copy
1281            of. For efficiency's sake, however, we convert the weak_ptr's into
1282            shared_ptr<Route> before passing them to however many surfaces (and
1283            thus strips) that we have.
1284         */
1285
1286         StrongRouteNotificationList srl;
1287
1288         for (ARDOUR::RouteNotificationList::const_iterator i = rl->begin(); i != rl->end(); ++i) {
1289                 boost::shared_ptr<ARDOUR::Route> r = (*i).lock();
1290                 if (r) {
1291                         srl.push_back (r);
1292                 }
1293         }
1294
1295         for (Surfaces::iterator s = surfaces.begin(); s != surfaces.end(); ++s) {
1296                 (*s)->gui_selection_changed (srl);
1297         }
1298         
1299         if (save_list) {
1300                 _last_selected_routes = *rl;
1301         }
1302 }
1303
1304 framepos_t
1305 MackieControlProtocol::transport_frame() const
1306 {
1307         return session->transport_frame();
1308 }
1309
1310 void
1311 MackieControlProtocol::add_down_select_button (int surface, int strip)
1312 {
1313         _down_select_buttons.insert ((surface<<8)|(strip&0xf));
1314 }
1315
1316 void
1317 MackieControlProtocol::remove_down_select_button (int surface, int strip)
1318 {
1319         DownButtonList::iterator x = find (_down_select_buttons.begin(), _down_select_buttons.end(), (surface<<8)|(strip&0xf));
1320         DEBUG_TRACE (DEBUG::MackieControl, string_compose ("removing surface %1 strip %2 from down select buttons\n", surface, strip));
1321         if (x != _down_select_buttons.end()) {
1322                 _down_select_buttons.erase (x);
1323         } else {
1324                 DEBUG_TRACE (DEBUG::MackieControl, string_compose ("surface %1 strip %2 not found in down select buttons\n",
1325                                                                    surface, strip));
1326         }
1327 }
1328
1329 void
1330 MackieControlProtocol::select_range ()
1331 {
1332         RouteList routes;
1333
1334         pull_route_range (_down_select_buttons, routes);
1335
1336         DEBUG_TRACE (DEBUG::MackieControl, string_compose ("select range: found %1 routes\n", routes.size()));
1337
1338         if (!routes.empty()) {
1339                 for (RouteList::iterator r = routes.begin(); r != routes.end(); ++r) {
1340
1341                         if (_modifier_state == MODIFIER_CONTROL) {
1342                                 ToggleRouteSelection ((*r)->remote_control_id ());
1343                         } else {
1344                                 if (r == routes.begin()) {
1345                                         SetRouteSelection ((*r)->remote_control_id());
1346                                 } else {
1347                                         AddRouteToSelection ((*r)->remote_control_id());
1348                                 }
1349                         }
1350                 }
1351         }
1352 }
1353
1354 void
1355 MackieControlProtocol::add_down_button (AutomationType a, int surface, int strip)
1356 {
1357         DownButtonMap::iterator m = _down_buttons.find (a);
1358
1359         if (m == _down_buttons.end()) {
1360                 _down_buttons[a] = DownButtonList();
1361         }
1362
1363         _down_buttons[a].insert ((surface<<8)|(strip&0xf));
1364 }
1365
1366 void
1367 MackieControlProtocol::remove_down_button (AutomationType a, int surface, int strip)
1368 {
1369         DownButtonMap::iterator m = _down_buttons.find (a);
1370
1371         DEBUG_TRACE (DEBUG::MackieControl, string_compose ("removing surface %1 strip %2 from down buttons for %3\n", surface, strip, (int) a));
1372
1373         if (m == _down_buttons.end()) {
1374                 return;
1375         }
1376
1377         DownButtonList& l (m->second);
1378         DownButtonList::iterator x = find (l.begin(), l.end(), (surface<<8)|(strip&0xf));
1379
1380         if (x != l.end()) {
1381                 l.erase (x);
1382         } else {
1383                 DEBUG_TRACE (DEBUG::MackieControl, string_compose ("surface %1 strip %2 not found in down buttons for %3\n",
1384                                                                    surface, strip, (int) a));
1385         }
1386 }
1387
1388 MackieControlProtocol::ControlList
1389 MackieControlProtocol::down_controls (AutomationType p)
1390 {
1391         ControlList controls;
1392         RouteList routes;
1393
1394         DownButtonMap::iterator m = _down_buttons.find (p);
1395
1396         if (m == _down_buttons.end()) {
1397                 return controls;
1398         }
1399         
1400         DEBUG_TRACE (DEBUG::MackieControl, string_compose ("looking for down buttons for %1, got %2\n",
1401                                                            p, m->second.size()));
1402
1403         pull_route_range (m->second, routes);
1404         
1405         switch (p) {
1406         case GainAutomation:
1407                 for (RouteList::iterator r = routes.begin(); r != routes.end(); ++r) {
1408                         controls.push_back ((*r)->gain_control());
1409                 }
1410                 break;
1411         case SoloAutomation:
1412                 for (RouteList::iterator r = routes.begin(); r != routes.end(); ++r) {
1413                         controls.push_back ((*r)->solo_control());
1414                 }
1415                 break;
1416         case MuteAutomation:
1417                 for (RouteList::iterator r = routes.begin(); r != routes.end(); ++r) {
1418                         controls.push_back ((*r)->mute_control());
1419                 }
1420                 break;
1421         case RecEnableAutomation:
1422                 for (RouteList::iterator r = routes.begin(); r != routes.end(); ++r) {
1423                         boost::shared_ptr<Track> trk = boost::dynamic_pointer_cast<Track> (*r);
1424                         if (trk) {
1425                                 controls.push_back (trk->rec_enable_control());
1426                         }
1427                 }
1428                 break;
1429         default:
1430                 break;
1431         }
1432
1433         return controls;
1434
1435 }
1436         
1437 struct ButtonRangeSorter {
1438     bool operator() (const uint32_t& a, const uint32_t& b) {
1439             return (a>>8) < (b>>8) // a.surface < b.surface
1440                     ||
1441                     ((a>>8) == (b>>8) && (a&0xf) < (b&0xf)); // a.surface == b.surface && a.strip < b.strip
1442     }
1443 };
1444
1445 void
1446 MackieControlProtocol::pull_route_range (DownButtonList& down, RouteList& selected)
1447 {
1448         ButtonRangeSorter cmp;
1449
1450         if (down.empty()) {
1451                 return;
1452         }
1453
1454         list<uint32_t> ldown;
1455         ldown.insert (ldown.end(), down.begin(), down.end());
1456         ldown.sort (cmp);
1457
1458         uint32_t first = ldown.front();
1459         uint32_t last = ldown.back ();
1460         
1461         uint32_t first_surface = first>>8;
1462         uint32_t first_strip = first&0xf;
1463
1464         uint32_t last_surface = last>>8;
1465         uint32_t last_strip = last&0xf;
1466
1467         DEBUG_TRACE (DEBUG::MackieControl, string_compose ("PRR %5 in list %1.%2 - %3.%4\n", first_surface, first_strip, last_surface, last_strip,
1468                                                            down.size()));
1469         
1470         for (Surfaces::const_iterator s = surfaces.begin(); s != surfaces.end(); ++s) {
1471                 
1472                 if ((*s)->number() >= first_surface && (*s)->number() <= last_surface) {
1473
1474                         uint32_t fs;
1475                         uint32_t ls;
1476
1477                         if ((*s)->number() == first_surface) {
1478                                 fs = first_strip;
1479                         } else {
1480                                 fs = 0;
1481                         }
1482
1483                         if ((*s)->number() == last_surface) {
1484                                 ls = last_strip;
1485                                 ls += 1;
1486                         } else {
1487                                 ls = (*s)->n_strips ();
1488                         }
1489
1490                         DEBUG_TRACE (DEBUG::MackieControl, string_compose ("adding strips for surface %1 (%2 .. %3)\n",
1491                                                                            (*s)->number(), fs, ls));
1492
1493                         for (uint32_t n = fs; n < ls; ++n) {
1494                                 boost::shared_ptr<Route> r = (*s)->nth_strip (n)->route();
1495                                 if (r) {
1496                                         selected.push_back (r);
1497                                 }
1498                         }
1499                 }
1500         }
1501 }
1502
1503 void
1504 MackieControlProtocol::set_ipmidi_base (int16_t portnum)
1505 {
1506         /* this will not be saved without a session save, so .. */
1507
1508         session->set_dirty ();
1509
1510         _ipmidi_base = portnum;
1511
1512         /* if the current device uses ipMIDI we need
1513            to restart.
1514         */
1515
1516         if (_active && _device_info.uses_ipmidi()) {
1517                 needs_ipmidi_restart = true;
1518         }
1519 }
1520
1521 void
1522 MackieControlProtocol::ipmidi_restart ()
1523 {
1524         clear_ports ();
1525         surfaces.clear ();      
1526         create_surfaces ();
1527         switch_banks (_current_initial_bank, true);
1528         needs_ipmidi_restart = false;
1529 }