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