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