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