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