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