handle deletion of UI objects between the time that a callback is queued with the...
[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 <iostream>
20 #include <algorithm>
21 #include <cmath>
22 #include <sstream>
23 #include <vector>
24 #include <iomanip>
25
26 #define __STDC_FORMAT_MACROS
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 "midi++/manager.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/dB.h"
44 #include "ardour/debug.h"
45 #include "ardour/location.h"
46 #include "ardour/midi_ui.h"
47 #include "ardour/panner.h"
48 #include "ardour/route.h"
49 #include "ardour/session.h"
50 #include "ardour/tempo.h"
51 #include "ardour/types.h"
52
53 #include "mackie_control_protocol.h"
54
55 #include "midi_byte_array.h"
56 #include "mackie_control_exception.h"
57 #include "route_signal.h"
58 #include "mackie_midi_builder.h"
59 #include "surface_port.h"
60 #include "surface.h"
61 #include "bcf_surface.h"
62 #include "mackie_surface.h"
63
64 using namespace ARDOUR;
65 using namespace std;
66 using namespace Mackie;
67 using namespace PBD;
68
69 using boost::shared_ptr;
70
71 #include "i18n.h"
72
73 MackieMidiBuilder builder;
74
75 #define midi_ui_context() MidiControlUI::instance() /* a UICallback-derived object that specifies the event loop for signal handling */
76 #define ui_bind(f, ...) boost::protect (boost::bind (f, __VA_ARGS__))
77
78 MackieControlProtocol::MackieControlProtocol (Session& session)
79         : ControlProtocol (session, X_("Mackie"), MidiControlUI::instance())
80         , _current_initial_bank (0)
81         , _surface (0)
82         , _jog_wheel (*this)
83         , _timecode_type (ARDOUR::AnyTime::BBT)
84 {
85         DEBUG_TRACE (DEBUG::MackieControl, "MackieControlProtocol::MackieControlProtocol\n");
86 }
87
88 MackieControlProtocol::~MackieControlProtocol()
89 {
90         DEBUG_TRACE (DEBUG::MackieControl, "MackieControlProtocol::~MackieControlProtocol\n");
91
92         try {
93                 close();
94         }
95         catch (exception & e) {
96                 cout << "~MackieControlProtocol caught " << e.what() << endl;
97         }
98         catch (...) {
99                 cout << "~MackieControlProtocol caught unknown" << endl;
100         }
101
102         DEBUG_TRACE (DEBUG::MackieControl, "finished ~MackieControlProtocol::MackieControlProtocol\n");
103 }
104
105 Mackie::Surface& 
106 MackieControlProtocol::surface()
107 {
108         if (_surface == 0) {
109                 throw MackieControlException ("_surface is 0 in MackieControlProtocol::surface");
110         }
111         return *_surface;
112 }
113
114 const Mackie::SurfacePort& 
115 MackieControlProtocol::mcu_port() const
116 {
117         if (_ports.size() < 1) {
118                 return _dummy_port;
119         } else {
120                 return dynamic_cast<const MackiePort &> (*_ports[0]);
121         }
122 }
123
124 Mackie::SurfacePort& 
125 MackieControlProtocol::mcu_port()
126 {
127         if (_ports.size() < 1) {
128                 return _dummy_port;
129         } else {
130                 return dynamic_cast<MackiePort &> (*_ports[0]);
131         }
132 }
133
134 // go to the previous track.
135 // Assume that get_sorted_routes().size() > route_table.size()
136 void 
137 MackieControlProtocol::prev_track()
138 {
139         if (_current_initial_bank >= 1) {
140                 session->set_dirty();
141                 switch_banks (_current_initial_bank - 1);
142         }
143 }
144
145 // go to the next track.
146 // Assume that get_sorted_routes().size() > route_table.size()
147 void 
148 MackieControlProtocol::next_track()
149 {
150         Sorted sorted = get_sorted_routes();
151         if (_current_initial_bank + route_table.size() < sorted.size())
152         {
153                 session->set_dirty();
154                 switch_banks (_current_initial_bank + 1);
155         }
156 }
157
158 void 
159 MackieControlProtocol::clear_route_signals()
160 {
161         for (RouteSignals::iterator it = route_signals.begin(); it != route_signals.end(); ++it) {
162                 delete *it;
163         }
164         route_signals.clear();
165 }
166
167 // return the port for a given id - 0 based
168 // throws an exception if no port found
169 MackiePort& 
170 MackieControlProtocol::port_for_id (uint32_t index)
171 {
172         uint32_t current_max = 0;
173         for (MackiePorts::iterator it = _ports.begin(); it != _ports.end(); ++it) {
174                 current_max += (*it)->strips();
175                 if (index < current_max) return **it;
176         }
177
178         // oops - no matching port
179         ostringstream os;
180         os << "No port for index " << index;
181         throw MackieControlException (os.str());
182 }
183
184 // predicate for sort call in get_sorted_routes
185 struct RouteByRemoteId
186 {
187         bool operator () (const shared_ptr<Route> & a, const 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         for (RouteList::iterator it = routes->begin(); it != routes->end(); ++it)
219         {
220                 Route & route = **it;
221                 if (
222                                 route.active()
223                                 && !route.is_master()
224                                 && !route.is_hidden()
225                                 && !route.is_monitor()
226                                 && remote_ids.find (route.remote_control_id()) == remote_ids.end()
227                 )
228                 {
229                         sorted.push_back (*it);
230                         remote_ids.insert (route.remote_control_id());
231                 }
232         }
233         sort (sorted.begin(), sorted.end(), RouteByRemoteId());
234         return sorted;
235 }
236
237 void 
238 MackieControlProtocol::refresh_current_bank()
239 {
240         switch_banks (_current_initial_bank);
241 }
242
243 void 
244 MackieControlProtocol::switch_banks (int initial)
245 {
246         // DON'T prevent bank switch if initial == _current_initial_bank
247         // because then this method can't be used as a refresh
248
249         // sanity checking
250         Sorted sorted = get_sorted_routes();
251         int delta = sorted.size() - route_table.size();
252         if (initial < 0 || (delta > 0 && initial > delta))
253         {
254                 DEBUG_TRACE (DEBUG::MackieControl, string_compose ("not switching to %1\n", initial));
255                 return;
256         }
257         _current_initial_bank = initial;
258
259         // first clear the signals from old routes
260         // taken care of by the RouteSignal destructors
261         clear_route_signals();
262
263         // now set the signals for new routes
264         if (_current_initial_bank <= sorted.size())
265         {
266                 // fetch the bank start and end to switch to
267                 uint32_t end_pos = min (route_table.size(), sorted.size());
268                 Sorted::iterator it = sorted.begin() + _current_initial_bank;
269                 Sorted::iterator end = sorted.begin() + _current_initial_bank + end_pos;
270
271                 DEBUG_TRACE (DEBUG::MackieControl, string_compose ("switch to %1, %2\n", _current_initial_bank, end_pos));
272
273                 // link routes to strips
274                 uint32_t i = 0;
275                 for (; it != end && it != sorted.end(); ++it, ++i)
276                 {
277                         boost::shared_ptr<Route> route = *it;
278                         Strip & strip = *surface().strips[i];
279
280                         DEBUG_TRACE (DEBUG::MackieControl, string_compose ("remote id %1 connecting %2 to %3 with port %4\n", 
281                                                                            route->remote_control_id(), route->name(), strip.name(), port_for_id(i)));
282                         route_table[i] = route;
283                         RouteSignal * rs = new RouteSignal (route, *this, strip, port_for_id(i));
284                         route_signals.push_back (rs);
285                         // update strip from route
286                         rs->notify_all();
287                 }
288
289                 // create dead strips if there aren't enough routes to
290                 // fill a bank
291                 for (; i < route_table.size(); ++i)
292                 {
293                         Strip & strip = *surface().strips[i];
294                         // send zero for this strip
295                         MackiePort & port = port_for_id(i);
296                         port.write (builder.zero_strip (port, strip));
297                 }
298         }
299
300         // display the current start bank.
301         surface().display_bank_start (mcu_port(), builder, _current_initial_bank);
302 }
303
304 void 
305 MackieControlProtocol::zero_all()
306 {
307         // TODO turn off Timecode displays
308
309         // zero all strips
310         for (Surface::Strips::iterator it = surface().strips.begin(); it != surface().strips.end(); ++it)
311         {
312                 MackiePort & port = port_for_id ((*it)->index());
313                 port.write (builder.zero_strip (port, **it));
314         }
315
316         // and the master strip
317         mcu_port().write (builder.zero_strip (dynamic_cast<MackiePort&> (mcu_port()), master_strip()));
318
319         // turn off global buttons and leds
320         // global buttons are only ever on mcu_port, so we don't have
321         // to figure out which port.
322         for (Surface::Controls::iterator it = surface().controls.begin(); it != surface().controls.end(); ++it)
323         {
324                 Control & control = **it;
325                 if (!control.group().is_strip() && control.accepts_feedback())
326                 {
327                         mcu_port().write (builder.zero_control (control));
328                 }
329         }
330
331         // any hardware-specific stuff
332         surface().zero_all (mcu_port(), builder);
333 }
334
335 int 
336 MackieControlProtocol::set_active (bool yn)
337 {
338         if (yn != _active)
339         {
340                 try
341                 {
342                         // the reason for the locking and unlocking is that
343                         // glibmm can't do a condition wait on a RecMutex
344                         if (yn)
345                         {
346                                 // TODO what happens if this fails half way?
347
348                                 // create MackiePorts
349                                 {
350                                         Glib::Mutex::Lock lock (update_mutex);
351                                         create_ports();
352                                 }
353
354                                 // now initialise MackiePorts - ie exchange sysex messages
355                                 for (MackiePorts::iterator it = _ports.begin(); it != _ports.end(); ++it) {
356                                         (*it)->open();
357                                 }
358
359                                 // wait until all ports are active
360                                 // TODO a more sophisticated approach would
361                                 // allow things to start up with only an MCU, even if
362                                 // extenders were specified but not responding.
363                                 for (MackiePorts::iterator it = _ports.begin(); it != _ports.end(); ++it) {
364                                         (*it)->wait_for_init();
365                                 }
366
367                                 // create surface object. This depends on the ports being
368                                 // correctly initialised
369                                 initialize_surface();
370                                 connect_session_signals();
371
372                                 // yeehah!
373                                 _active = true;
374
375                                 // send current control positions to surface
376                                 // must come after _active = true otherwise it won't run
377                                 update_surface();
378                         } else {
379                                 close();
380                                 _active = false;
381                         }
382                 }
383
384                 catch (exception & e) {
385                         DEBUG_TRACE (DEBUG::MackieControl, string_compose ("set_active to false because exception caught: %1\n", e.what()));
386                         _active = false;
387                         throw;
388                 }
389         }
390
391         return 0;
392 }
393
394 bool 
395 MackieControlProtocol::handle_strip_button (Control & control, ButtonState bs, boost::shared_ptr<Route> route)
396 {
397         bool state = false;
398
399         if (bs == press)
400         {
401                 if (control.name() == "recenable")
402                 {
403                         state = !route->record_enabled();
404                         route->set_record_enable (state, this);
405                 }
406                 else if (control.name() == "mute")
407                 {
408                         state = !route->muted();
409                         route->set_mute (state, this);
410                 }
411                 else if (control.name() == "solo")
412                 {
413                         state = !route->soloed();
414                         route->set_solo (state, this);
415                 }
416                 else if (control.name() == "select")
417                 {
418                         // TODO make the track selected. Whatever that means.
419                         //state = default_button_press (dynamic_cast<Button&> (control));
420                 }
421                 else if (control.name() == "vselect")
422                 {
423                         // TODO could be used to select different things to apply the pot to?
424                         //state = default_button_press (dynamic_cast<Button&> (control));
425                 }
426         }
427
428         if (control.name() == "fader_touch")
429         {
430                 state = bs == press;
431                 control.strip().gain().in_use (state);
432         }
433
434         return state;
435 }
436
437 void 
438 MackieControlProtocol::update_led (Mackie::Button & button, Mackie::LedState ls)
439 {
440         if (ls != none)
441         {
442                 SurfacePort * port = 0;
443                 if (button.group().is_strip())
444                 {
445                         if (button.group().is_master())
446                         {
447                                 port = &mcu_port();
448                         }
449                         else
450                         {
451                                 port = &port_for_id (dynamic_cast<const Strip&> (button.group()).index());
452                         }
453                 }
454                 else
455                 {
456                         port = &mcu_port();
457                 }
458                 port->write (builder.build_led (button, ls));
459         }
460 }
461
462 void 
463 MackieControlProtocol::update_timecode_beats_led()
464 {
465         switch (_timecode_type)
466         {
467                 case ARDOUR::AnyTime::BBT:
468                         update_global_led ("beats", on);
469                         update_global_led ("timecode", off);
470                         break;
471                 case ARDOUR::AnyTime::Timecode:
472                         update_global_led ("timecode", on);
473                         update_global_led ("beats", off);
474                         break;
475                 default:
476                         ostringstream os;
477                         os << "Unknown Anytime::Type " << _timecode_type;
478                         throw runtime_error (os.str());
479         }
480 }
481
482 void 
483 MackieControlProtocol::update_global_button (const string & name, LedState ls)
484 {
485         if (surface().controls_by_name.find (name) != surface().controls_by_name.end())
486         {
487                 Button * button = dynamic_cast<Button*> (surface().controls_by_name[name]);
488                 mcu_port().write (builder.build_led (button->led(), ls));
489         }
490         else
491         {
492                 DEBUG_TRACE (DEBUG::MackieControl, string_compose ("Button %1 not found\n", name));
493         }
494 }
495
496 void 
497 MackieControlProtocol::update_global_led (const string & name, LedState ls)
498 {
499         if (surface().controls_by_name.find (name) != surface().controls_by_name.end())
500         {
501                 Led * led = dynamic_cast<Led*> (surface().controls_by_name[name]);
502                 mcu_port().write (builder.build_led (*led, ls));
503         }
504         else
505         {
506                 DEBUG_TRACE (DEBUG::MackieControl, string_compose ("Led %1 not found\n", name));
507         }
508 }
509
510 // send messages to surface to set controls to correct values
511 void 
512 MackieControlProtocol::update_surface()
513 {
514         if (_active)
515         {
516                 // do the initial bank switch to connect signals
517                 // _current_initial_bank is initialised by set_state
518                 switch_banks (_current_initial_bank);
519
520                 // create a RouteSignal for the master route
521
522  boost::shared_ptr<Route> mr = master_route ();
523  if (mr) {
524  master_route_signal = shared_ptr<RouteSignal> (new RouteSignal (mr, *this, master_strip(), mcu_port()));
525  // update strip from route
526  master_route_signal->notify_all();
527  }
528
529                 // sometimes the jog wheel is a pot
530                 surface().blank_jog_ring (mcu_port(), builder);
531
532                 // update global buttons and displays
533                 notify_record_state_changed();
534                 notify_transport_state_changed();
535                 update_timecode_beats_led();
536         }
537 }
538
539 void 
540 MackieControlProtocol::connect_session_signals()
541 {
542         // receive routes added
543         session->RouteAdded.connect(session_connections, MISSING_INVALIDATOR, ui_bind (&MackieControlProtocol::notify_route_added, this, _1), midi_ui_context());
544         // receive record state toggled
545         session->RecordStateChanged.connect(session_connections, MISSING_INVALIDATOR, ui_bind (&MackieControlProtocol::notify_record_state_changed, this), midi_ui_context());
546         // receive transport state changed
547         session->TransportStateChange.connect(session_connections, MISSING_INVALIDATOR, ui_bind (&MackieControlProtocol::notify_transport_state_changed, this), midi_ui_context());
548         // receive punch-in and punch-out
549         Config->ParameterChanged.connect(session_connections, MISSING_INVALIDATOR, ui_bind (&MackieControlProtocol::notify_parameter_changed, this, _1), midi_ui_context());
550         session->config.ParameterChanged.connect (session_connections, MISSING_INVALIDATOR, ui_bind (&MackieControlProtocol::notify_parameter_changed, this, _1), midi_ui_context());
551         // receive rude solo changed
552         session->SoloActive.connect(session_connections, MISSING_INVALIDATOR, ui_bind (&MackieControlProtocol::notify_solo_active_changed, this, _1), midi_ui_context());
553
554         // make sure remote id changed signals reach here
555         // see also notify_route_added
556         Sorted sorted = get_sorted_routes();
557
558         for (Sorted::iterator it = sorted.begin(); it != sorted.end(); ++it) {
559                 (*it)->RemoteControlIDChanged.connect (route_connections, MISSING_INVALIDATOR, ui_bind(&MackieControlProtocol::notify_remote_id_changed, this), midi_ui_context());
560         }
561 }
562
563 void 
564 MackieControlProtocol::add_port (MIDI::Port & midi_port, int number)
565 {
566         DEBUG_TRACE (DEBUG::MackieControl, string_compose ("add port %1,%2,%3\n", midi_port.name(), midi_port.device(), midi_port.type()));
567
568         if (string (midi_port.device()) == string ("ardour") && midi_port.type() == MIDI::Port::ALSA_Sequencer) {
569                 throw MackieControlException ("The Mackie MCU driver will not use a port with device=ardour");
570         } else if (midi_port.type() == MIDI::Port::ALSA_Sequencer) {
571                 throw MackieControlException ("alsa/sequencer ports don't work with the Mackie MCU driver right now");
572         } else {
573                 MackiePort * sport = new MackiePort (*this, midi_port, number);
574                 _ports.push_back (sport);
575                 
576                 sport->init_event.connect_same_thread (port_connections, boost::bind (&MackieControlProtocol::handle_port_init, this, sport));
577                 sport->active_event.connect_same_thread (port_connections, boost::bind (&MackieControlProtocol::handle_port_active, this, sport));
578                 sport->inactive_event.connect_same_thread (port_connections, boost::bind (&MackieControlProtocol::handle_port_inactive, this, sport));
579         }
580 }
581
582 void 
583 MackieControlProtocol::create_ports()
584 {
585         MIDI::Manager * mm = MIDI::Manager::instance();
586         MIDI::Port * midi_port = mm->port (default_port_name);
587
588         // open main port               
589
590         if (midi_port == 0) {
591                 ostringstream os;
592                 os << string_compose (_("no MIDI port named \"%1\" exists - Mackie control disabled"), default_port_name);
593                 error << os.str() << endmsg;
594                 throw MackieControlException (os.str());
595         }
596
597         add_port (*midi_port, 0);
598
599         // open extender ports. Up to 9. Should be enough.
600         // could also use mm->get_midi_ports()
601
602         string ext_port_base = "mcu_xt_";
603
604         for (int index = 1; index <= 9; ++index) {
605                 ostringstream os;
606                 os << ext_port_base << index;
607                 MIDI::Port * midi_port = mm->port (os.str());
608                 if (midi_port != 0) {
609                         add_port (*midi_port, index);
610                 }
611         }
612 }
613
614 shared_ptr<Route> 
615 MackieControlProtocol::master_route()
616 {
617         return session->master_out ();
618 }
619
620 Strip& 
621 MackieControlProtocol::master_strip()
622 {
623         return dynamic_cast<Strip&> (*surface().groups["master"]);
624 }
625
626 void 
627 MackieControlProtocol::initialize_surface()
628 {
629         // set up the route table
630         int strips = 0;
631         for (MackiePorts::iterator it = _ports.begin(); it != _ports.end(); ++it) {
632                 strips += (*it)->strips();
633         }
634
635         set_route_table_size (strips);
636
637         // TODO same as code in mackie_port.cc
638         string emulation = ARDOUR::Config->get_mackie_emulation();
639         if (emulation == "bcf")
640         {
641                 _surface = new BcfSurface (strips);
642         }
643         else if (emulation == "mcu")
644         {
645                 _surface = new MackieSurface (strips);
646         }
647         else
648         {
649                 ostringstream os;
650                 os << "no Surface class found for emulation: " << emulation;
651                 throw MackieControlException (os.str());
652         }
653
654         _surface->init();
655
656         // Connect events. Must be after route table otherwise there will be trouble
657
658         for (MackiePorts::iterator it = _ports.begin(); it != _ports.end(); ++it) {
659                 (*it)->control_event.connect_same_thread (port_connections, boost::bind (&MackieControlProtocol::handle_control_event, this, _1, _2, _3));
660         }
661 }
662
663 void 
664 MackieControlProtocol::close()
665 {
666
667         // must be before other shutdown otherwise polling loop
668         // calls methods on objects that are deleted
669
670         port_connections.drop_connections ();
671         session_connections.drop_connections ();
672         route_connections.drop_connections ();
673
674         if (_surface != 0) {
675                 // These will fail if the port has gone away.
676                 // So catch the exception and do the rest of the
677                 // close afterwards
678                 // because the bcf doesn't respond to the next 3 sysex messages
679                 try {
680                         zero_all();
681                 }
682
683                 catch (exception & e) {
684                         DEBUG_TRACE (DEBUG::MackieControl, string_compose ("MackieControlProtocol::close caught exception: %1\n", e.what()));
685                 }
686
687                 for (MackiePorts::iterator it = _ports.begin(); it != _ports.end(); ++it) {
688                         try {
689                                 MackiePort & port = **it;
690                                 // faders to minimum
691                                 port.write_sysex (0x61);
692                                 // All LEDs off
693                                 port.write_sysex (0x62);
694                                 // Reset (reboot into offline mode)
695                                 port.write_sysex (0x63);
696                         }
697                         catch (exception & e) {
698                                 DEBUG_TRACE (DEBUG::MackieControl, string_compose ("MackieControlProtocol::close caught exception: %1\n", e.what()));
699                         }
700                 }
701
702                 // disconnect routes from strips
703                 clear_route_signals();
704                 delete _surface;
705                 _surface = 0;
706         }
707
708         // shut down MackiePorts
709         for (MackiePorts::iterator it = _ports.begin(); it != _ports.end(); ++it) {
710                 delete *it;
711         }
712
713         _ports.clear();
714 }
715
716 XMLNode& 
717 MackieControlProtocol::get_state()
718 {
719         DEBUG_TRACE (DEBUG::MackieControl, "MackieControlProtocol::get_state\n");
720
721         // add name of protocol
722         XMLNode* node = new XMLNode (X_("Protocol"));
723         node->add_property (X_("name"), _name);
724
725         // add current bank
726         ostringstream os;
727         os << _current_initial_bank;
728         node->add_property (X_("bank"), os.str());
729
730         return *node;
731 }
732
733 int 
734 MackieControlProtocol::set_state (const XMLNode & node, int /*version*/)
735 {
736         DEBUG_TRACE (DEBUG::MackieControl, string_compose ("MackieControlProtocol::set_state: active %1\n", _active));
737
738         int retval = 0;
739
740         // fetch current bank
741
742         if (node.property (X_("bank")) != 0) {
743                 string bank = node.property (X_("bank"))->value();
744                 try {
745                         set_active (true);
746                         uint32_t new_bank = atoi (bank.c_str());
747                         if (_current_initial_bank != new_bank) {
748                                 switch_banks (new_bank);
749                         }
750                 }
751                 catch (exception & e) {
752                         DEBUG_TRACE (DEBUG::MackieControl, string_compose ("exception in MackieControlProtocol::set_state: %1\n", e.what()));
753                         return -1;
754                 }
755         }
756
757         return retval;
758 }
759
760 void 
761 MackieControlProtocol::handle_control_event (SurfacePort & port, Control & control, const ControlState & state)
762 {
763         // find the route for the control, if there is one
764         boost::shared_ptr<Route> route;
765         if (control.group().is_strip()) {
766                 if (control.group().is_master()) {
767                         route = master_route();
768                 } else {
769                         uint32_t index = control.ordinal() - 1 + (port.number() * port.strips());
770                         if (index < route_table.size())
771                                 route = route_table[index];
772                         else
773                                 cerr << "Warning: index is " << index << " which is not in the route table, size: " << route_table.size() << endl;
774                 }
775         }
776
777         // This handles control element events from the surface
778         // the state of the controls on the surface is usually updated
779         // from UI events.
780         switch (control.type()) {
781                 case Control::type_fader:
782                         // find the route in the route table for the id
783                         // if the route isn't available, skip it
784                         // at which point the fader should just reset itself
785                         if (route != 0)
786                         {
787                                 route->gain_control()->set_value (state.pos);
788
789                                 // must echo bytes back to slider now, because
790                                 // the notifier only works if the fader is not being
791                                 // touched. Which it is if we're getting input.
792                                 port.write (builder.build_fader ((Fader&)control, state.pos));
793                         }
794                         break;
795
796                 case Control::type_button:
797                         if (control.group().is_strip()) {
798                                 // strips
799                                 if (route != 0) {
800                                         handle_strip_button (control, state.button_state, route);
801                                 } else {
802                                         // no route so always switch the light off
803                                         // because no signals will be emitted by a non-route
804                                         port.write (builder.build_led (control.led(), off));
805                                 }
806                         } else if (control.group().is_master()) {
807                                 // master fader touch
808                                 if (route != 0) {
809                                         handle_strip_button (control, state.button_state, route);
810                                 }
811                         } else {
812                                 // handle all non-strip buttons
813                                 surface().handle_button (*this, state.button_state, dynamic_cast<Button&> (control));
814                         }
815                         break;
816
817                 // pot (jog wheel, external control)
818                 case Control::type_pot:
819                         if (control.group().is_strip()) {
820                                 if (route != 0 && route->panner())
821                                 {
822                                         // pan for mono input routes, or stereo linked panners
823                                         if (route->panner()->npanners() == 1 || (route->panner()->npanners() == 2 && route->panner()->linked()))
824                                         {
825                                                 // assume pan for now
826                                                 float xpos;
827                                                 route->panner()->streampanner (0).get_effective_position (xpos);
828
829                                                 // calculate new value, and trim
830                                                 xpos += state.delta * state.sign;
831                                                 if (xpos > 1.0)
832                                                         xpos = 1.0;
833                                                 else if (xpos < 0.0)
834                                                         xpos = 0.0;
835
836                                                 route->panner()->streampanner (0).set_position (xpos);
837                                         }
838                                 }
839                                 else
840                                 {
841                                         // it's a pot for an umnapped route, so turn all the lights off
842                                         port.write (builder.build_led_ring (dynamic_cast<Pot &> (control), off));
843                                 }
844                         }
845                         else
846                         {
847                                 if (control.is_jog())
848                                 {
849                                         _jog_wheel.jog_event (port, control, state);
850                                 }
851                                 else
852                                 {
853                                         cout << "external controller" << state.ticks * state.sign << endl;
854                                 }
855                         }
856                         break;
857
858                 default:
859                         cout << "Control::type not handled: " << control.type() << endl;
860         }
861 }
862
863 /////////////////////////////////////////////////
864 // handlers for Route signals
865 // TODO should these be part of RouteSignal?
866 // They started off as signal/slot handlers for signals
867 // from Route, but they're also used in polling for automation
868 /////////////////////////////////////////////////
869
870 void 
871 MackieControlProtocol::notify_solo_changed (RouteSignal * route_signal)
872 {
873         try
874         {
875                 Button & button = route_signal->strip().solo();
876                 route_signal->port().write (builder.build_led (button, route_signal->route()->soloed()));
877         }
878         catch (exception & e)
879         {
880                 cout << e.what() << endl;
881         }
882 }
883
884 void 
885 MackieControlProtocol::notify_mute_changed (RouteSignal * route_signal)
886 {
887         try
888         {
889                 Button & button = route_signal->strip().mute();
890                 route_signal->port().write (builder.build_led (button, route_signal->route()->muted()));
891         }
892         catch (exception & e)
893         {
894                 cout << e.what() << endl;
895         }
896 }
897
898 void 
899 MackieControlProtocol::notify_record_enable_changed (RouteSignal * route_signal)
900 {
901         try
902         {
903                 Button & button = route_signal->strip().recenable();
904                 route_signal->port().write (builder.build_led (button, route_signal->route()->record_enabled()));
905         }
906         catch (exception & e)
907         {
908                 cout << e.what() << endl;
909         }
910 }
911
912 void MackieControlProtocol::notify_active_changed (RouteSignal *)
913 {
914         try
915         {
916                 DEBUG_TRACE (DEBUG::MackieControl, "MackieControlProtocol::notify_active_changed\n");
917                 refresh_current_bank();
918         }
919         catch (exception & e)
920         {
921                 cout << e.what() << endl;
922         }
923 }
924
925 void 
926 MackieControlProtocol::notify_gain_changed (RouteSignal * route_signal, bool force_update)
927 {
928         try
929         {
930                 Fader & fader = route_signal->strip().gain();
931                 if (!fader.in_use())
932                 {
933                         float gain_value = route_signal->route()->gain_control()->get_value();
934                         // check that something has actually changed
935                         if (force_update || gain_value != route_signal->last_gain_written())
936                         {
937                                 route_signal->port().write (builder.build_fader (fader, gain_value));
938                                 route_signal->last_gain_written (gain_value);
939                         }
940                 }
941         }
942         catch (exception & e)
943         {
944                 cout << e.what() << endl;
945         }
946 }
947
948 void 
949 MackieControlProtocol::notify_property_changed (const PropertyChange& what_changed, RouteSignal * route_signal)
950 {
951         if (!what_changed.contains (Properties::name)) {
952                 return;
953         }
954
955         try
956         {
957                 Strip & strip = route_signal->strip();
958                 if (!strip.is_master())
959                 {
960                         string line1;
961                         string fullname = route_signal->route()->name();
962
963                         if (fullname.length() <= 6)
964                         {
965                                 line1 = fullname;
966                         }
967                         else
968                         {
969                                 line1 = PBD::short_version (fullname, 6);
970                         }
971
972                         SurfacePort & port = route_signal->port();
973                         port.write (builder.strip_display (port, strip, 0, line1));
974                         port.write (builder.strip_display_blank (port, strip, 1));
975                 }
976         }
977         catch (exception & e)
978         {
979                 cout << e.what() << endl;
980         }
981 }
982
983 void 
984 MackieControlProtocol::notify_panner_changed (RouteSignal * route_signal, bool force_update)
985 {
986         try
987         {
988                 Pot & pot = route_signal->strip().vpot();
989                 boost::shared_ptr<Panner> panner = route_signal->route()->panner();
990                 if ((panner && panner->npanners() == 1) || (panner->npanners() == 2 && panner->linked()))
991                 {
992                         float pos;
993                         route_signal->route()->panner()->streampanner(0).get_effective_position (pos);
994
995                         // cache the MidiByteArray here, because the mackie led control is much lower
996                         // resolution than the panner control. So we save lots of byte
997                         // sends in spite of more work on the comparison
998                         MidiByteArray bytes = builder.build_led_ring (pot, ControlState (on, pos), MackieMidiBuilder::midi_pot_mode_dot);
999                         // check that something has actually changed
1000                         if (force_update || bytes != route_signal->last_pan_written())
1001                         {
1002                                 route_signal->port().write (bytes);
1003                                 route_signal->last_pan_written (bytes);
1004                         }
1005                 }
1006                 else
1007                 {
1008                         route_signal->port().write (builder.zero_control (pot));
1009                 }
1010         }
1011         catch (exception & e)
1012         {
1013                 cout << e.what() << endl;
1014         }
1015 }
1016
1017 // TODO handle plugin automation polling
1018 void 
1019 MackieControlProtocol::update_automation (RouteSignal & rs)
1020 {
1021         ARDOUR::AutoState gain_state = rs.route()->gain_control()->automation_state();
1022
1023         if (gain_state == Touch || gain_state == Play)
1024         {
1025                 notify_gain_changed (&rs, false);
1026         }
1027
1028         if (rs.route()->panner()) {
1029                 ARDOUR::AutoState panner_state = rs.route()->panner()->automation_state();
1030                 if (panner_state == Touch || panner_state == Play)
1031                 {
1032                         notify_panner_changed (&rs, false);
1033                 }
1034         }
1035 }
1036
1037 string 
1038 MackieControlProtocol::format_bbt_timecode (nframes_t now_frame)
1039 {
1040         BBT_Time bbt_time;
1041         session->bbt_time (now_frame, bbt_time);
1042
1043         // According to the Logic docs
1044         // digits: 888/88/88/888
1045         // BBT mode: Bars/Beats/Subdivisions/Ticks
1046         ostringstream os;
1047         os << setw(3) << setfill('0') << bbt_time.bars;
1048         os << setw(2) << setfill('0') << bbt_time.beats;
1049
1050         // figure out subdivisions per beat
1051         const Meter & meter = session->tempo_map().meter_at (now_frame);
1052         int subdiv = 2;
1053         if (meter.note_divisor() == 8 && (meter.beats_per_bar() == 12.0 || meter.beats_per_bar() == 9.0 || meter.beats_per_bar() == 6.0))
1054         {
1055                 subdiv = 3;
1056         }
1057
1058         uint32_t subdivisions = bbt_time.ticks / uint32_t (Meter::ticks_per_beat / subdiv);
1059         uint32_t ticks = bbt_time.ticks % uint32_t (Meter::ticks_per_beat / subdiv);
1060
1061         os << setw(2) << setfill('0') << subdivisions + 1;
1062         os << setw(3) << setfill('0') << ticks;
1063
1064         return os.str();
1065 }
1066
1067 string 
1068 MackieControlProtocol::format_timecode_timecode (nframes_t now_frame)
1069 {
1070         Timecode::Time timecode;
1071         session->timecode_time (now_frame, timecode);
1072
1073         // According to the Logic docs
1074         // digits: 888/88/88/888
1075         // Timecode mode: Hours/Minutes/Seconds/Frames
1076         ostringstream os;
1077         os << setw(3) << setfill('0') << timecode.hours;
1078         os << setw(2) << setfill('0') << timecode.minutes;
1079         os << setw(2) << setfill('0') << timecode.seconds;
1080         os << setw(3) << setfill('0') << timecode.frames;
1081
1082         return os.str();
1083 }
1084
1085 void 
1086 MackieControlProtocol::update_timecode_display()
1087 {
1088         if (surface().has_timecode_display())
1089         {
1090                 // do assignment here so current_frame is fixed
1091                 nframes_t current_frame = session->transport_frame();
1092                 string timecode;
1093
1094                 switch (_timecode_type)
1095                 {
1096                         case ARDOUR::AnyTime::BBT:
1097                                 timecode = format_bbt_timecode (current_frame);
1098                                 break;
1099                         case ARDOUR::AnyTime::Timecode:
1100                                 timecode = format_timecode_timecode (current_frame);
1101                                 break;
1102                         default:
1103                                 ostringstream os;
1104                                 os << "Unknown timecode: " << _timecode_type;
1105                                 throw runtime_error (os.str());
1106                 }
1107
1108                 // only write the timecode string to the MCU if it's changed
1109                 // since last time. This is to reduce midi bandwidth used.
1110                 if (timecode != _timecode_last)
1111                 {
1112                         surface().display_timecode (mcu_port(), builder, timecode, _timecode_last);
1113                         _timecode_last = timecode;
1114                 }
1115         }
1116 }
1117
1118 void 
1119 MackieControlProtocol::poll_session_data()
1120 {
1121         // XXX need to attach this to a timer in the MIDI UI event loop (20msec)
1122
1123         if (_active) {
1124                 // do all currently mapped routes
1125                 for (RouteSignals::iterator it = route_signals.begin(); it != route_signals.end(); ++it) {
1126                         update_automation (**it);
1127                 }
1128
1129                 // and the master strip
1130                 if (master_route_signal != 0) {
1131                         update_automation (*master_route_signal);
1132                 }
1133
1134                 update_timecode_display();
1135         }
1136 }
1137
1138 /////////////////////////////////////
1139 // Transport Buttons
1140 /////////////////////////////////////
1141
1142 LedState 
1143 MackieControlProtocol::frm_left_press (Button &)
1144 {
1145         // can use first_mark_before/after as well
1146         unsigned long elapsed = _frm_left_last.restart();
1147
1148         Location * loc = session->locations()->first_location_before (
1149                 session->transport_frame()
1150         );
1151
1152         // allow a quick double to go past a previous mark
1153         if (session->transport_rolling() && elapsed < 500 && loc != 0)
1154         {
1155                 Location * loc_two_back = session->locations()->first_location_before (loc->start());
1156                 if (loc_two_back != 0)
1157                 {
1158                         loc = loc_two_back;
1159                 }
1160         }
1161
1162         // move to the location, if it's valid
1163         if (loc != 0)
1164         {
1165                 session->request_locate (loc->start(), session->transport_rolling());
1166         }
1167
1168         return on;
1169 }
1170
1171 LedState 
1172 MackieControlProtocol::frm_left_release (Button &)
1173 {
1174         return off;
1175 }
1176
1177 LedState 
1178 MackieControlProtocol::frm_right_press (Button &)
1179 {
1180         // can use first_mark_before/after as well
1181         Location * loc = session->locations()->first_location_after (
1182                 session->transport_frame()
1183         );
1184         if (loc != 0) session->request_locate (loc->start(), session->transport_rolling());
1185         return on;
1186 }
1187
1188 LedState 
1189 MackieControlProtocol::frm_right_release (Button &)
1190 {
1191         return off;
1192 }
1193
1194 LedState 
1195 MackieControlProtocol::stop_press (Button &)
1196 {
1197         session->request_stop();
1198         return on;
1199 }
1200
1201 LedState 
1202 MackieControlProtocol::stop_release (Button &)
1203 {
1204         return session->transport_stopped();
1205 }
1206
1207 LedState 
1208 MackieControlProtocol::play_press (Button &)
1209 {
1210         session->request_transport_speed (1.0);
1211         return on;
1212 }
1213
1214 LedState 
1215 MackieControlProtocol::play_release (Button &)
1216 {
1217         return session->transport_rolling();
1218 }
1219
1220 LedState 
1221 MackieControlProtocol::record_press (Button &)
1222 {
1223         if (session->get_record_enabled()) {
1224                 session->disable_record (false);
1225         } else {
1226                 session->maybe_enable_record();
1227         }
1228         return on;
1229 }
1230
1231 LedState 
1232 MackieControlProtocol::record_release (Button &)
1233 {
1234         if (session->get_record_enabled()) {
1235                 if (session->transport_rolling()) {
1236                         return on;
1237                 } else {
1238                         return flashing;
1239                 }
1240         } else {
1241                 return off;
1242         }
1243 }
1244
1245 LedState 
1246 MackieControlProtocol::rewind_press (Button &)
1247 {
1248         _jog_wheel.push (JogWheel::speed);
1249         _jog_wheel.transport_direction (-1);
1250         session->request_transport_speed (-_jog_wheel.transport_speed());
1251         return on;
1252 }
1253
1254 LedState 
1255 MackieControlProtocol::rewind_release (Button &)
1256 {
1257         _jog_wheel.pop();
1258         _jog_wheel.transport_direction (0);
1259         if (_transport_previously_rolling)
1260                 session->request_transport_speed (1.0);
1261         else
1262                 session->request_stop();
1263         return off;
1264 }
1265
1266 LedState 
1267 MackieControlProtocol::ffwd_press (Button &)
1268 {
1269         _jog_wheel.push (JogWheel::speed);
1270         _jog_wheel.transport_direction (1);
1271         session->request_transport_speed (_jog_wheel.transport_speed());
1272         return on;
1273 }
1274
1275 LedState 
1276 MackieControlProtocol::ffwd_release (Button &)
1277 {
1278         _jog_wheel.pop();
1279         _jog_wheel.transport_direction (0);
1280         if (_transport_previously_rolling)
1281                 session->request_transport_speed (1.0);
1282         else
1283                 session->request_stop();
1284         return off;
1285 }
1286
1287 LedState 
1288 MackieControlProtocol::loop_press (Button &)
1289 {
1290         session->request_play_loop (!session->get_play_loop());
1291         return on;
1292 }
1293
1294 LedState 
1295 MackieControlProtocol::loop_release (Button &)
1296 {
1297         return session->get_play_loop();
1298 }
1299
1300 LedState 
1301 MackieControlProtocol::punch_in_press (Button &)
1302 {
1303         bool state = !session->config.get_punch_in();
1304         session->config.set_punch_in (state);
1305         return state;
1306 }
1307
1308 LedState 
1309 MackieControlProtocol::punch_in_release (Button &)
1310 {
1311         return session->config.get_punch_in();
1312 }
1313
1314 LedState 
1315 MackieControlProtocol::punch_out_press (Button &)
1316 {
1317         bool state = !session->config.get_punch_out();
1318         session->config.set_punch_out (state);
1319         return state;
1320 }
1321
1322 LedState 
1323 MackieControlProtocol::punch_out_release (Button &)
1324 {
1325         return session->config.get_punch_out();
1326 }
1327
1328 LedState 
1329 MackieControlProtocol::home_press (Button &)
1330 {
1331         session->goto_start();
1332         return on;
1333 }
1334
1335 LedState 
1336 MackieControlProtocol::home_release (Button &)
1337 {
1338         return off;
1339 }
1340
1341 LedState 
1342 MackieControlProtocol::end_press (Button &)
1343 {
1344         session->goto_end();
1345         return on;
1346 }
1347
1348 LedState 
1349 MackieControlProtocol::end_release (Button &)
1350 {
1351         return off;
1352 }
1353
1354 LedState 
1355 MackieControlProtocol::clicking_press (Button &)
1356 {
1357         bool state = !Config->get_clicking();
1358         Config->set_clicking (state);
1359         return state;
1360 }
1361
1362 LedState 
1363 MackieControlProtocol::clicking_release (Button &)
1364 {
1365         return Config->get_clicking();
1366 }
1367
1368 LedState MackieControlProtocol::global_solo_press (Button &)
1369 {
1370         bool state = !session->soloing();
1371         session->set_solo (session->get_routes(), state);
1372         return state;
1373 }
1374
1375 LedState MackieControlProtocol::global_solo_release (Button &)
1376 {
1377         return session->soloing();
1378 }
1379
1380 ///////////////////////////////////////////
1381 // Session signals
1382 ///////////////////////////////////////////
1383
1384 void MackieControlProtocol::notify_parameter_changed (std::string const & p)
1385 {
1386         if (p == "punch-in")
1387         {
1388                 update_global_button ("punch_in", session->config.get_punch_in());
1389         }
1390         else if (p == "punch-out")
1391         {
1392                 update_global_button ("punch_out", session->config.get_punch_out());
1393         }
1394         else if (p == "clicking")
1395         {
1396                 update_global_button ("clicking", Config->get_clicking());
1397         }
1398         else
1399         {
1400                 DEBUG_TRACE (DEBUG::MackieControl, string_compose ("parameter changed: %1\n", p));
1401         }
1402 }
1403
1404 // RouteList is the set of routes that have just been added
1405 void 
1406 MackieControlProtocol::notify_route_added (ARDOUR::RouteList & rl)
1407 {
1408         // currently assigned banks are less than the full set of
1409         // strips, so activate the new strip now.
1410         if (route_signals.size() < route_table.size())
1411         {
1412                 refresh_current_bank();
1413         }
1414         // otherwise route added, but current bank needs no updating
1415
1416         // make sure remote id changes in the new route are handled
1417         typedef ARDOUR::RouteList ARS;
1418
1419         for (ARS::iterator it = rl.begin(); it != rl.end(); ++it) {
1420                 (*it)->RemoteControlIDChanged.connect (route_connections, MISSING_INVALIDATOR, ui_bind (&MackieControlProtocol::notify_remote_id_changed, this), midi_ui_context());
1421         }
1422 }
1423
1424 void 
1425 MackieControlProtocol::notify_solo_active_changed (bool active)
1426 {
1427         Button * rude_solo = reinterpret_cast<Button*> (surface().controls_by_name["solo"]);
1428         mcu_port().write (builder.build_led (*rude_solo, active ? flashing : off));
1429 }
1430
1431 void 
1432 MackieControlProtocol::notify_remote_id_changed()
1433 {
1434         Sorted sorted = get_sorted_routes();
1435
1436         // if a remote id has been moved off the end, we need to shift
1437         // the current bank backwards.
1438         if (sorted.size() - _current_initial_bank < route_signals.size())
1439         {
1440                 // but don't shift backwards past the zeroth channel
1441                 switch_banks (max((Sorted::size_type) 0, sorted.size() - route_signals.size()));
1442         }
1443         // Otherwise just refresh the current bank
1444         else
1445         {
1446                 refresh_current_bank();
1447         }
1448 }
1449
1450 ///////////////////////////////////////////
1451 // Transport signals
1452 ///////////////////////////////////////////
1453
1454 void 
1455 MackieControlProtocol::notify_record_state_changed()
1456 {
1457         // switch rec button on / off / flashing
1458         Button * rec = reinterpret_cast<Button*> (surface().controls_by_name["record"]);
1459         mcu_port().write (builder.build_led (*rec, record_release (*rec)));
1460 }
1461
1462 void 
1463 MackieControlProtocol::notify_transport_state_changed()
1464 {
1465         // switch various play and stop buttons on / off
1466         update_global_button ("play", session->transport_rolling());
1467         update_global_button ("stop", !session->transport_rolling());
1468         update_global_button ("loop", session->get_play_loop());
1469
1470         _transport_previously_rolling = session->transport_rolling();
1471
1472         // rec is special because it's tristate
1473         Button * rec = reinterpret_cast<Button*> (surface().controls_by_name["record"]);
1474         mcu_port().write (builder.build_led (*rec, record_release (*rec)));
1475 }
1476
1477 /////////////////////////////////////
1478 // Bank Switching
1479 /////////////////////////////////////
1480 LedState 
1481 MackieControlProtocol::left_press (Button &)
1482 {
1483         Sorted sorted = get_sorted_routes();
1484         if (sorted.size() > route_table.size())
1485         {
1486                 int new_initial = _current_initial_bank - route_table.size();
1487                 if (new_initial < 0) new_initial = 0;
1488                 if (new_initial != int (_current_initial_bank))
1489                 {
1490                         session->set_dirty();
1491                         switch_banks (new_initial);
1492                 }
1493
1494                 return on;
1495         }
1496         else
1497         {
1498                 return flashing;
1499         }
1500 }
1501
1502 LedState 
1503 MackieControlProtocol::left_release (Button &)
1504 {
1505         return off;
1506 }
1507
1508 LedState 
1509 MackieControlProtocol::right_press (Button &)
1510 {
1511         Sorted sorted = get_sorted_routes();
1512         if (sorted.size() > route_table.size()) {
1513                 uint32_t delta = sorted.size() - (route_table.size() + _current_initial_bank);
1514                 if (delta > route_table.size()) delta = route_table.size();
1515                 if (delta > 0) {
1516                         session->set_dirty();
1517                         switch_banks (_current_initial_bank + delta);
1518                 }
1519
1520                 return on;
1521         } else {
1522                 return flashing;
1523         }
1524 }
1525
1526 LedState 
1527 MackieControlProtocol::right_release (Button &)
1528 {
1529         return off;
1530 }
1531
1532 LedState 
1533 MackieControlProtocol::channel_left_press (Button &)
1534 {
1535         Sorted sorted = get_sorted_routes();
1536         if (sorted.size() > route_table.size())
1537         {
1538                 prev_track();
1539                 return on;
1540         }
1541         else
1542         {
1543                 return flashing;
1544         }
1545 }
1546
1547 LedState 
1548 MackieControlProtocol::channel_left_release (Button &)
1549 {
1550         return off;
1551 }
1552
1553 LedState 
1554 MackieControlProtocol::channel_right_press (Button &)
1555 {
1556         Sorted sorted = get_sorted_routes();
1557         if (sorted.size() > route_table.size())
1558         {
1559                 next_track();
1560                 return on;
1561         }
1562         else
1563         {
1564                 return flashing;
1565         }
1566 }
1567
1568 LedState 
1569 MackieControlProtocol::channel_right_release (Button &)
1570 {
1571         return off;
1572 }
1573
1574 /////////////////////////////////////
1575 // Functions
1576 /////////////////////////////////////
1577 LedState 
1578 MackieControlProtocol::marker_press (Button &)
1579 {
1580         // cut'n'paste from LocationUI::add_new_location()
1581         string markername;
1582         nframes_t where = session->audible_frame();
1583         session->locations()->next_available_name(markername,"mcu");
1584         Location *location = new Location (where, where, markername, Location::IsMark);
1585         session->begin_reversible_command (_("add marker"));
1586         XMLNode &before = session->locations()->get_state();
1587         session->locations()->add (location, true);
1588         XMLNode &after = session->locations()->get_state();
1589         session->add_command (new MementoCommand<Locations>(*(session->locations()), &before, &after));
1590         session->commit_reversible_command ();
1591         return on;
1592 }
1593
1594 LedState 
1595 MackieControlProtocol::marker_release (Button &)
1596 {
1597         return off;
1598 }
1599
1600 void 
1601 jog_wheel_state_display (JogWheel::State state, SurfacePort & port)
1602 {
1603         switch (state)
1604         {
1605                 case JogWheel::zoom: port.write (builder.two_char_display ("Zm")); break;
1606                 case JogWheel::scroll: port.write (builder.two_char_display ("Sc")); break;
1607                 case JogWheel::scrub: port.write (builder.two_char_display ("Sb")); break;
1608                 case JogWheel::shuttle: port.write (builder.two_char_display ("Sh")); break;
1609                 case JogWheel::speed: port.write (builder.two_char_display ("Sp")); break;
1610                 case JogWheel::select: port.write (builder.two_char_display ("Se")); break;
1611         }
1612 }
1613
1614 Mackie::LedState 
1615 MackieControlProtocol::zoom_press (Mackie::Button &)
1616 {
1617         _jog_wheel.zoom_state_toggle();
1618         update_global_button ("scrub", _jog_wheel.jog_wheel_state() == JogWheel::scrub);
1619         jog_wheel_state_display (_jog_wheel.jog_wheel_state(), mcu_port());
1620         return _jog_wheel.jog_wheel_state() == JogWheel::zoom;
1621 }
1622
1623 Mackie::LedState 
1624 MackieControlProtocol::zoom_release (Mackie::Button &)
1625 {
1626         return _jog_wheel.jog_wheel_state() == JogWheel::zoom;
1627 }
1628
1629 Mackie::LedState 
1630 MackieControlProtocol::scrub_press (Mackie::Button &)
1631 {
1632         _jog_wheel.scrub_state_cycle();
1633         update_global_button ("zoom", _jog_wheel.jog_wheel_state() == JogWheel::zoom);
1634         jog_wheel_state_display (_jog_wheel.jog_wheel_state(), mcu_port());
1635         return
1636                 _jog_wheel.jog_wheel_state() == JogWheel::scrub
1637                 ||
1638                 _jog_wheel.jog_wheel_state() == JogWheel::shuttle
1639         ;
1640 }
1641
1642 Mackie::LedState 
1643 MackieControlProtocol::scrub_release (Mackie::Button &)
1644 {
1645         return
1646                 _jog_wheel.jog_wheel_state() == JogWheel::scrub
1647                 ||
1648                 _jog_wheel.jog_wheel_state() == JogWheel::shuttle
1649         ;
1650 }
1651
1652 LedState 
1653 MackieControlProtocol::drop_press (Button &)
1654 {
1655         session->remove_last_capture();
1656         return on;
1657 }
1658
1659 LedState 
1660 MackieControlProtocol::drop_release (Button &)
1661 {
1662         return off;
1663 }
1664
1665 LedState 
1666 MackieControlProtocol::save_press (Button &)
1667 {
1668         session->save_state ("");
1669         return on;
1670 }
1671
1672 LedState 
1673 MackieControlProtocol::save_release (Button &)
1674 {
1675         return off;
1676 }
1677
1678 LedState 
1679 MackieControlProtocol::timecode_beats_press (Button &)
1680 {
1681         switch (_timecode_type)
1682         {
1683                 case ARDOUR::AnyTime::BBT:
1684                         _timecode_type = ARDOUR::AnyTime::Timecode;
1685                         break;
1686                 case ARDOUR::AnyTime::Timecode:
1687                         _timecode_type = ARDOUR::AnyTime::BBT;
1688                         break;
1689                 default:
1690                         ostringstream os;
1691                         os << "Unknown Anytime::Type " << _timecode_type;
1692                         throw runtime_error (os.str());
1693         }
1694         update_timecode_beats_led();
1695         return on;
1696 }
1697
1698 LedState 
1699 MackieControlProtocol::timecode_beats_release (Button &)
1700 {
1701         return off;
1702 }
1703