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