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