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