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