MCP: rename raw_id() to id(); add missign modifier_state() function
[ardour.git] / libs / surfaces / mackie / mackie_control_protocol.cc
1 /*
2         Copyright (C) 2006,2007 John Anderson
3
4         This program is free software; you can redistribute it and/or modify
5         it under the terms of the GNU General Public License as published by
6         the Free Software Foundation; either version 2 of the License, or
7         (at your option) any later version.
8
9         This program is distributed in the hope that it will be useful,
10         but WITHOUT ANY WARRANTY; without even the implied warranty of
11         MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12         GNU General Public License for more details.
13
14         You should have received a copy of the GNU General Public License
15         along with this program; if not, write to the Free Software
16         Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
17 */
18
19 #include <fcntl.h>
20 #include <iostream>
21 #include <algorithm>
22 #include <cmath>
23 #include <sstream>
24 #include <vector>
25 #include <iomanip>
26
27 #include <inttypes.h>
28 #include <float.h>
29 #include <sys/time.h>
30 #include <errno.h>
31 #include <poll.h>
32
33 #include <boost/shared_array.hpp>
34
35 #include "midi++/types.h"
36 #include "midi++/port.h"
37 #include "pbd/pthread_utils.h"
38 #include "pbd/error.h"
39 #include "pbd/memento_command.h"
40 #include "pbd/convert.h"
41
42 #include "ardour/dB.h"
43 #include "ardour/debug.h"
44 #include "ardour/location.h"
45 #include "ardour/meter.h"
46 #include "ardour/panner.h"
47 #include "ardour/panner_shell.h"
48 #include "ardour/route.h"
49 #include "ardour/session.h"
50 #include "ardour/tempo.h"
51 #include "ardour/types.h"
52 #include "ardour/audioengine.h"
53
54 #include "mackie_control_protocol.h"
55
56 #include "midi_byte_array.h"
57 #include "mackie_control_exception.h"
58 #include "surface_port.h"
59 #include "surface.h"
60
61 #include "strip.h"
62 #include "control_group.h"
63 #include "meter.h"
64 #include "button.h"
65 #include "fader.h"
66 #include "pot.h"
67
68 using namespace ARDOUR;
69 using namespace std;
70 using namespace Mackie;
71 using namespace PBD;
72 using namespace Glib;
73
74 #include "i18n.h"
75
76 #include "pbd/abstract_ui.cc" // instantiate template
77
78 #define ui_bind(f, ...) boost::protect (boost::bind (f, __VA_ARGS__))
79
80 const int MackieControlProtocol::MODIFIER_OPTION = 0x1;
81 const int MackieControlProtocol::MODIFIER_CONTROL = 0x2;
82 const int MackieControlProtocol::MODIFIER_SHIFT = 0x3;
83 const int MackieControlProtocol::MODIFIER_CMDALT = 0x4;
84
85 MackieControlProtocol* MackieControlProtocol::_instance = 0;
86
87 bool MackieControlProtocol::probe()
88 {
89         return true;
90 }
91
92 MackieControlProtocol::MackieControlProtocol (Session& session)
93         : ControlProtocol (session, X_("Mackie"), this)
94         , AbstractUI<MackieControlUIRequest> ("mackie")
95         , _current_initial_bank (0)
96         , _timecode_type (ARDOUR::AnyTime::BBT)
97         , _input_bundle (new ARDOUR::Bundle (_("Mackie Control In"), true))
98         , _output_bundle (new ARDOUR::Bundle (_("Mackie Control Out"), false))
99         , _gui (0)
100         , _zoom_mode (false)
101         , _scrub_mode (false)
102         , _flip_mode (false)
103         , _current_selected_track (-1)
104 {
105         DEBUG_TRACE (DEBUG::MackieControl, "MackieControlProtocol::MackieControlProtocol\n");
106
107         AudioEngine::instance()->PortConnectedOrDisconnected.connect (
108                 audio_engine_connections, MISSING_INVALIDATOR, ui_bind (&MackieControlProtocol::port_connected_or_disconnected, this, _2, _4, _5),
109                 this
110                 );
111
112         _instance = this;
113
114         build_button_map ();
115 }
116
117 MackieControlProtocol::~MackieControlProtocol()
118 {
119         DEBUG_TRACE (DEBUG::MackieControl, "MackieControlProtocol::~MackieControlProtocol\n");
120
121         _active = false;
122
123         try {
124                 close();
125         }
126         catch (exception & e) {
127                 cout << "~MackieControlProtocol caught " << e.what() << endl;
128         }
129         catch (...) {
130                 cout << "~MackieControlProtocol caught unknown" << endl;
131         }
132
133         DEBUG_TRACE (DEBUG::MackieControl, "finished ~MackieControlProtocol::MackieControlProtocol\n");
134
135         _instance = 0;
136 }
137
138 void
139 MackieControlProtocol::thread_init ()
140 {
141         struct sched_param rtparam;
142
143         pthread_set_name (X_("MackieControl"));
144
145         PBD::notify_gui_about_thread_creation (X_("gui"), pthread_self(), X_("MackieControl"), 2048);
146         ARDOUR::SessionEvent::create_per_thread_pool (X_("MackieControl"), 128);
147
148         memset (&rtparam, 0, sizeof (rtparam));
149         rtparam.sched_priority = 9; /* XXX should be relative to audio (JACK) thread */
150
151         if (pthread_setschedparam (pthread_self(), SCHED_FIFO, &rtparam) != 0) {
152                 // do we care? not particularly.
153         }
154 }
155
156 // go to the previous track.
157 // Assume that get_sorted_routes().size() > route_table.size()
158 void 
159 MackieControlProtocol::prev_track()
160 {
161         if (_current_initial_bank >= 1) {
162                 session->set_dirty();
163                 switch_banks (_current_initial_bank - 1);
164         }
165 }
166
167 // go to the next track.
168 // Assume that get_sorted_routes().size() > route_table.size()
169 void 
170 MackieControlProtocol::next_track()
171 {
172         Sorted sorted = get_sorted_routes();
173         if (_current_initial_bank + n_strips() < sorted.size()) {
174                 session->set_dirty();
175                 switch_banks (_current_initial_bank + 1);
176         }
177 }
178
179 // predicate for sort call in get_sorted_routes
180 struct RouteByRemoteId
181 {
182         bool operator () (const boost::shared_ptr<Route> & a, const boost::shared_ptr<Route> & b) const
183         {
184                 return a->remote_control_id() < b->remote_control_id();
185         }
186
187         bool operator () (const Route & a, const Route & b) const
188         {
189                 return a.remote_control_id() < b.remote_control_id();
190         }
191
192         bool operator () (const Route * a, const Route * b) const
193         {
194                 return a->remote_control_id() < b->remote_control_id();
195         }
196 };
197
198 MackieControlProtocol::Sorted 
199 MackieControlProtocol::get_sorted_routes()
200 {
201         Sorted sorted;
202
203         // fetch all routes
204         boost::shared_ptr<RouteList> routes = session->get_routes();
205         set<uint32_t> remote_ids;
206
207         // routes with remote_id 0 should never be added
208         // TODO verify this with ardour devs
209         // remote_ids.insert (0);
210
211         // sort in remote_id order, and exclude master, control and hidden routes
212         // and any routes that are already set.
213         for (RouteList::iterator it = routes->begin(); it != routes->end(); ++it) {
214                 Route & route = **it;
215                 if (
216                         route.active()
217                         && !route.is_master()
218                         && !route.is_hidden()
219                         && !route.is_monitor()
220                         && remote_ids.find (route.remote_control_id()) == remote_ids.end()
221                         ) {
222                         sorted.push_back (*it);
223                         remote_ids.insert (route.remote_control_id());
224                 }
225         }
226         sort (sorted.begin(), sorted.end(), RouteByRemoteId());
227         return sorted;
228 }
229
230 void 
231 MackieControlProtocol::refresh_current_bank()
232 {
233         switch_banks (_current_initial_bank, true);
234 }
235
236 uint32_t
237 MackieControlProtocol::n_strips() const
238 {
239         uint32_t strip_count = 0;
240
241         for (Surfaces::const_iterator si = surfaces.begin(); si != surfaces.end(); ++si) {
242                 strip_count += (*si)->n_strips ();
243         }
244
245         return strip_count;
246 }
247
248 void 
249 MackieControlProtocol::switch_banks (uint32_t initial, bool force)
250 {
251         DEBUG_TRACE (DEBUG::MackieControl, string_compose ("switch banking to start at %1 force ? %2 current = %3\n", initial, force, _current_initial_bank));
252
253         if (initial == _current_initial_bank && !force) {
254                 DEBUG_TRACE (DEBUG::MackieControl, string_compose ("not switching to %1\n", initial));
255                 return;
256         }
257
258         Sorted sorted = get_sorted_routes();
259         uint32_t strip_cnt = n_strips();
260
261         if (sorted.size() <= strip_cnt && !force) {
262                 /* no banking */
263                 DEBUG_TRACE (DEBUG::MackieControl, string_compose ("not switching to %1\n", initial));
264                 return;
265         }
266
267         uint32_t delta = sorted.size() - strip_cnt;
268
269         if (delta > 0 && initial > delta) {
270                 DEBUG_TRACE (DEBUG::MackieControl, string_compose ("not switching to %1\n", initial));
271                 return;
272         }
273
274         _current_initial_bank = initial;
275         _current_selected_track = -1;
276
277         for (Surfaces::iterator si = surfaces.begin(); si != surfaces.end(); ++si) {
278                 (*si)->drop_routes ();
279         }
280
281         // Map current bank of routes onto each surface(+strip)
282
283         if (_current_initial_bank <= sorted.size()) {
284
285                 DEBUG_TRACE (DEBUG::MackieControl, string_compose ("switch to %1, %2, available routes %3\n", _current_initial_bank, strip_cnt, sorted.size()));
286
287                 // link routes to strips
288
289                 Sorted::iterator r = sorted.begin() + _current_initial_bank;
290                 
291                 for (Surfaces::iterator si = surfaces.begin(); si != surfaces.end(); ++si) {
292                         vector<boost::shared_ptr<Route> > routes;
293                         uint32_t added = 0;
294
295                         DEBUG_TRACE (DEBUG::MackieControl, string_compose ("surface has %1 strips\n", (*si)->n_strips()));
296
297                         for (; r != sorted.end() && added < (*si)->n_strips(); ++r, ++added) {
298                                 routes.push_back (*r);
299                                 cerr << "\t\tadded " << (*r)->name() << endl;
300                         }
301
302                         DEBUG_TRACE (DEBUG::MackieControl, string_compose ("give surface %1 routes\n", routes.size()));
303
304                         (*si)->map_routes (routes);
305                 }
306         }
307
308         // display the current start bank.
309         surfaces.front()->display_bank_start (_current_initial_bank);
310 }
311
312 int 
313 MackieControlProtocol::set_active (bool yn)
314 {
315         if (yn == _active) {
316                 return 0;
317         }
318
319         try
320         {
321                 if (yn) {
322
323                         /* start event loop */
324
325                         BaseUI::run ();
326
327                         create_surfaces ();
328                         connect_session_signals ();
329                         
330                         _active = true;
331                         update_surfaces ();
332
333                         /* set up periodic task for metering and automation
334                          */
335
336                         Glib::RefPtr<Glib::TimeoutSource> periodic_timeout = Glib::TimeoutSource::create (100); // milliseconds
337                         periodic_connection = periodic_timeout->connect (sigc::mem_fun (*this, &MackieControlProtocol::periodic));
338                         periodic_timeout->attach (main_loop()->get_context());
339
340                 } else {
341                         BaseUI::quit ();
342                         close();
343                         _active = false;
344                 }
345         }
346         
347         catch (exception & e) {
348                 DEBUG_TRACE (DEBUG::MackieControl, string_compose ("set_active to false because exception caught: %1\n", e.what()));
349                 _active = false;
350                 throw;
351         }
352
353         return 0;
354 }
355
356 bool
357 MackieControlProtocol::periodic ()
358 {
359         if (!_active) {
360                 return false;
361         }
362
363         for (Surfaces::iterator s = surfaces.begin(); s != surfaces.end(); ++s) {
364                 (*s)->periodic ();
365         }
366         
367         return true;
368 }
369
370
371 void 
372 MackieControlProtocol::update_timecode_beats_led()
373 {
374         switch (_timecode_type) {
375                 case ARDOUR::AnyTime::BBT:
376                         update_global_led ("beats", on);
377                         update_global_led ("timecode", off);
378                         break;
379                 case ARDOUR::AnyTime::Timecode:
380                         update_global_led ("timecode", on);
381                         update_global_led ("beats", off);
382                         break;
383                 default:
384                         ostringstream os;
385                         os << "Unknown Anytime::Type " << _timecode_type;
386                         throw runtime_error (os.str());
387         }
388 }
389
390 void 
391 MackieControlProtocol::update_global_button (const string & name, LedState ls)
392 {
393         boost::shared_ptr<Surface> surface = surfaces.front();
394
395         if (!surface->type() == mcu) {
396                 return;
397         }
398
399         if (surface->controls_by_name.find (name) != surface->controls_by_name.end()) {
400                 Button * button = dynamic_cast<Button*> (surface->controls_by_name[name]);
401                 surface->write (button->led().set_state (ls));
402         } else {
403                 DEBUG_TRACE (DEBUG::MackieControl, string_compose ("Button %1 not found\n", name));
404         }
405 }
406
407 void 
408 MackieControlProtocol::update_global_led (const string & name, LedState ls)
409 {
410         boost::shared_ptr<Surface> surface = surfaces.front();
411
412         if (!surface->type() == mcu) {
413                 return;
414         }
415
416         if (surface->controls_by_name.find (name) != surface->controls_by_name.end()) {
417                 Led * led = dynamic_cast<Led*> (surface->controls_by_name[name]);
418                 surface->write (led->set_state (ls));
419         } else {
420                 DEBUG_TRACE (DEBUG::MackieControl, string_compose ("Led %1 not found\n", name));
421         }
422 }
423
424 // send messages to surface to set controls to correct values
425 void 
426 MackieControlProtocol::update_surfaces()
427 {
428         if (!_active) {
429                 return;
430         }
431
432         // do the initial bank switch to connect signals
433         // _current_initial_bank is initialised by set_state
434         switch_banks (_current_initial_bank, true);
435         
436         // sometimes the jog wheel is a pot
437         surfaces.front()->blank_jog_ring ();
438         
439         // update global buttons and displays
440
441         notify_record_state_changed();
442         notify_transport_state_changed();
443         update_timecode_beats_led();
444 }
445
446 void 
447 MackieControlProtocol::connect_session_signals()
448 {
449         // receive routes added
450         session->RouteAdded.connect(session_connections, MISSING_INVALIDATOR, ui_bind (&MackieControlProtocol::notify_route_added, this, _1), this);
451         // receive record state toggled
452         session->RecordStateChanged.connect(session_connections, MISSING_INVALIDATOR, ui_bind (&MackieControlProtocol::notify_record_state_changed, this), this);
453         // receive transport state changed
454         session->TransportStateChange.connect(session_connections, MISSING_INVALIDATOR, ui_bind (&MackieControlProtocol::notify_transport_state_changed, this), this);
455         session->TransportLooped.connect (session_connections, MISSING_INVALIDATOR, ui_bind (&MackieControlProtocol::notify_loop_state_changed, this), this);
456         // receive punch-in and punch-out
457         Config->ParameterChanged.connect(session_connections, MISSING_INVALIDATOR, ui_bind (&MackieControlProtocol::notify_parameter_changed, this, _1), this);
458         session->config.ParameterChanged.connect (session_connections, MISSING_INVALIDATOR, ui_bind (&MackieControlProtocol::notify_parameter_changed, this, _1), this);
459         // receive rude solo changed
460         session->SoloActive.connect(session_connections, MISSING_INVALIDATOR, ui_bind (&MackieControlProtocol::notify_solo_active_changed, this, _1), this);
461
462         // make sure remote id changed signals reach here
463         // see also notify_route_added
464         Sorted sorted = get_sorted_routes();
465
466         for (Sorted::iterator it = sorted.begin(); it != sorted.end(); ++it) {
467                 (*it)->RemoteControlIDChanged.connect (route_connections, MISSING_INVALIDATOR, ui_bind(&MackieControlProtocol::notify_remote_id_changed, this), this);
468         }
469 }
470
471 void 
472 MackieControlProtocol::create_surfaces ()
473 {
474         string device_name = "mcu";
475         surface_type_t stype = mcu;
476
477         DEBUG_TRACE (DEBUG::MackieControl, string_compose ("Create %1 surfaces\n",
478                                                            1 + ARDOUR::Config->get_mackie_extenders()));
479
480         for (uint32_t n = 0; n < 1 + ARDOUR::Config->get_mackie_extenders(); ++n) {
481
482                 boost::shared_ptr<Surface> surface (new Surface (*this, session->engine().jack(), device_name, n, stype));
483                 surfaces.push_back (surface);
484                 
485                 device_name = "mcu_xt";
486                 stype = ext;
487
488                 _input_bundle->add_channel (
489                         surface->port().input_port().name(),
490                         ARDOUR::DataType::MIDI,
491                         session->engine().make_port_name_non_relative (surface->port().input_port().name())
492                         );
493                 
494                 _output_bundle->add_channel (
495                         surface->port().output_port().name(),
496                         ARDOUR::DataType::MIDI,
497                         session->engine().make_port_name_non_relative (surface->port().output_port().name())
498                         );
499
500                 int fd;
501                 MIDI::Port& input_port (surface->port().input_port());
502                 
503                 if ((fd = input_port.selectable ()) >= 0) {
504                         Glib::RefPtr<IOSource> psrc = IOSource::create (fd, IO_IN|IO_HUP|IO_ERR);
505
506                         psrc->connect (sigc::bind (sigc::mem_fun (this, &MackieControlProtocol::midi_input_handler), &input_port));
507                         psrc->attach (main_loop()->get_context());
508                         
509                         // glibmm hack: for now, store only the GSource*
510
511                         port_sources.push_back (psrc->gobj());
512                         g_source_ref (psrc->gobj());
513                 }
514         }
515 }
516
517 void 
518 MackieControlProtocol::close()
519 {
520         clear_ports ();
521
522         port_connections.drop_connections ();
523         session_connections.drop_connections ();
524         route_connections.drop_connections ();
525         periodic_connection.disconnect ();
526
527         surfaces.clear ();
528 }
529
530 XMLNode& 
531 MackieControlProtocol::get_state()
532 {
533         DEBUG_TRACE (DEBUG::MackieControl, "MackieControlProtocol::get_state\n");
534
535         // add name of protocol
536         XMLNode* node = new XMLNode (X_("Protocol"));
537         node->add_property (X_("name"), ARDOUR::ControlProtocol::_name);
538
539         // add current bank
540         ostringstream os;
541         os << _current_initial_bank;
542         node->add_property (X_("bank"), os.str());
543
544         return *node;
545 }
546
547 int 
548 MackieControlProtocol::set_state (const XMLNode & node, int /*version*/)
549 {
550         DEBUG_TRACE (DEBUG::MackieControl, string_compose ("MackieControlProtocol::set_state: active %1\n", _active));
551
552         int retval = 0;
553
554         // fetch current bank
555
556         if (node.property (X_("bank")) != 0) {
557                 string bank = node.property (X_("bank"))->value();
558                 try {
559                         set_active (true);
560                         uint32_t new_bank = atoi (bank.c_str());
561                         if (_current_initial_bank != new_bank) {
562                                 switch_banks (new_bank);
563                         }
564                 }
565                 catch (exception & e) {
566                         DEBUG_TRACE (DEBUG::MackieControl, string_compose ("exception in MackieControlProtocol::set_state: %1\n", e.what()));
567                         return -1;
568                 }
569         }
570
571         return retval;
572 }
573
574
575 /////////////////////////////////////////////////
576 // handlers for Route signals
577 // TODO should these be part of RouteSignal?
578 // They started off as signal/slot handlers for signals
579 // from Route, but they're also used in polling for automation
580 /////////////////////////////////////////////////
581
582 // TODO handle plugin automation polling
583 string 
584 MackieControlProtocol::format_bbt_timecode (framepos_t now_frame)
585 {
586         Timecode::BBT_Time bbt_time;
587         session->bbt_time (now_frame, bbt_time);
588
589         // According to the Logic docs
590         // digits: 888/88/88/888
591         // BBT mode: Bars/Beats/Subdivisions/Ticks
592         ostringstream os;
593         os << setw(3) << setfill('0') << bbt_time.bars;
594         os << setw(2) << setfill('0') << bbt_time.beats;
595
596         // figure out subdivisions per beat
597         const ARDOUR::Meter & meter = session->tempo_map().meter_at (now_frame);
598         int subdiv = 2;
599         if (meter.note_divisor() == 8 && (meter.divisions_per_bar() == 12.0 || meter.divisions_per_bar() == 9.0 || meter.divisions_per_bar() == 6.0)) {
600                 subdiv = 3;
601         }
602
603         uint32_t subdivisions = bbt_time.ticks / uint32_t (Timecode::BBT_Time::ticks_per_beat / subdiv);
604         uint32_t ticks = bbt_time.ticks % uint32_t (Timecode::BBT_Time::ticks_per_beat / subdiv);
605
606         os << setw(2) << setfill('0') << subdivisions + 1;
607         os << setw(3) << setfill('0') << ticks;
608
609         return os.str();
610 }
611
612 string 
613 MackieControlProtocol::format_timecode_timecode (framepos_t now_frame)
614 {
615         Timecode::Time timecode;
616         session->timecode_time (now_frame, timecode);
617
618         // According to the Logic docs
619         // digits: 888/88/88/888
620         // Timecode mode: Hours/Minutes/Seconds/Frames
621         ostringstream os;
622         os << setw(3) << setfill('0') << timecode.hours;
623         os << setw(2) << setfill('0') << timecode.minutes;
624         os << setw(2) << setfill('0') << timecode.seconds;
625         os << setw(3) << setfill('0') << timecode.frames;
626
627         return os.str();
628 }
629
630 void 
631 MackieControlProtocol::update_timecode_display()
632 {
633         boost::shared_ptr<Surface> surface = surfaces.front();
634
635         if (surface->type() != mcu || !surface->has_timecode_display()) {
636                 return;
637         }
638
639         // do assignment here so current_frame is fixed
640         framepos_t current_frame = session->transport_frame();
641         string timecode;
642
643         switch (_timecode_type) {
644         case ARDOUR::AnyTime::BBT:
645                 timecode = format_bbt_timecode (current_frame);
646                 break;
647         case ARDOUR::AnyTime::Timecode:
648                 timecode = format_timecode_timecode (current_frame);
649                 break;
650         default:
651                 return;
652         }
653         
654         // only write the timecode string to the MCU if it's changed
655         // since last time. This is to reduce midi bandwidth used.
656         if (timecode != _timecode_last) {
657                 surface->display_timecode (timecode, _timecode_last);
658                 _timecode_last = timecode;
659         }
660 }
661
662 ///////////////////////////////////////////
663 // Session signals
664 ///////////////////////////////////////////
665
666 void MackieControlProtocol::notify_parameter_changed (std::string const & p)
667 {
668         if (p == "punch-in") {
669                 update_global_button ("punch_in", session->config.get_punch_in());
670         } else if (p == "punch-out") {
671                 update_global_button ("punch_out", session->config.get_punch_out());
672         } else if (p == "clicking") {
673                 update_global_button ("clicking", Config->get_clicking());
674         } else {
675                 DEBUG_TRACE (DEBUG::MackieControl, string_compose ("parameter changed: %1\n", p));
676         }
677 }
678
679 // RouteList is the set of routes that have just been added
680 void 
681 MackieControlProtocol::notify_route_added (ARDOUR::RouteList & rl)
682 {
683         // currently assigned banks are less than the full set of
684         // strips, so activate the new strip now.
685
686         refresh_current_bank();
687
688         // otherwise route added, but current bank needs no updating
689
690         // make sure remote id changes in the new route are handled
691         typedef ARDOUR::RouteList ARS;
692
693         for (ARS::iterator it = rl.begin(); it != rl.end(); ++it) {
694                 (*it)->RemoteControlIDChanged.connect (route_connections, MISSING_INVALIDATOR, ui_bind (&MackieControlProtocol::notify_remote_id_changed, this), this);
695         }
696 }
697
698 void 
699 MackieControlProtocol::notify_solo_active_changed (bool active)
700 {
701         boost::shared_ptr<Surface> surface = surfaces.front();
702         
703         Led* rude_solo = dynamic_cast<Led*> (surface->controls_by_name["solo"]);
704
705         if (rude_solo) {
706                 surface->write (rude_solo->set_state (active ? flashing : off));
707         }
708 }
709
710 void 
711 MackieControlProtocol::notify_remote_id_changed()
712 {
713         Sorted sorted = get_sorted_routes();
714         uint32_t sz = n_strips();
715
716         // if a remote id has been moved off the end, we need to shift
717         // the current bank backwards.
718
719         if (sorted.size() - _current_initial_bank < sz) {
720                 // but don't shift backwards past the zeroth channel
721                 switch_banks (max((Sorted::size_type) 0, sorted.size() - sz));
722         } else {
723                 // Otherwise just refresh the current bank
724                 refresh_current_bank();
725         }
726 }
727
728 ///////////////////////////////////////////
729 // Transport signals
730 ///////////////////////////////////////////
731
732 void 
733 MackieControlProtocol::notify_loop_state_changed()
734 {
735         update_global_button ("loop", session->get_play_loop());
736 }
737
738 void 
739 MackieControlProtocol::notify_transport_state_changed()
740 {
741         // switch various play and stop buttons on / off
742         update_global_button ("play", session->transport_rolling());
743         update_global_button ("stop", !session->transport_rolling());
744         update_global_button ("rewind", session->transport_speed() < 0.0);
745         update_global_button ("ffwd", session->transport_speed() > 1.0);
746
747         _transport_previously_rolling = session->transport_rolling();
748 }
749
750 void
751 MackieControlProtocol::notify_record_state_changed ()
752 {
753         /* rec is a tristate */
754
755
756         Button * rec = reinterpret_cast<Button*> (surfaces.front()->controls_by_name["record"]);
757         if (rec) {
758                 LedState ls;
759
760                 switch (session->record_status()) {
761                 case Session::Disabled:
762                         DEBUG_TRACE (DEBUG::MackieControl, "record state changed to disabled, LED off\n");
763                         ls = off;
764                         break;
765                 case Session::Recording:
766                         DEBUG_TRACE (DEBUG::MackieControl, "record state changed to recording, LED on\n");
767                         ls = on;
768                         break;
769                 case Session::Enabled:
770                         DEBUG_TRACE (DEBUG::MackieControl, "record state changed to enabled, LED flashing\n");
771                         ls = flashing;
772                         break;
773                 }
774
775                 surfaces.front()->write (rec->led().set_state (ls));
776         } else {
777                 DEBUG_TRACE (DEBUG::MackieControl, "record button control not found\n");
778         }
779 }
780
781 list<boost::shared_ptr<ARDOUR::Bundle> >
782 MackieControlProtocol::bundles ()
783 {
784         list<boost::shared_ptr<ARDOUR::Bundle> > b;
785         b.push_back (_input_bundle);
786         b.push_back (_output_bundle);
787         return b;
788 }
789
790 void
791 MackieControlProtocol::port_connected_or_disconnected (string a, string b, bool connected)
792 {
793         /* If something is connected to one of our output ports, send MIDI to update the surface
794            to whatever state it should have.
795         */
796
797         if (!connected) {
798                 return;
799         }
800
801         for (Surfaces::iterator s = surfaces.begin(); s != surfaces.end(); ++s) {
802                 string const n = AudioEngine::instance()->make_port_name_non_relative ((*s)->port().output_port().name ());
803                 if (a == n || b == n) {
804                         update_surfaces ();
805                         return;
806                 }
807         }
808 }
809
810 void
811 MackieControlProtocol::do_request (MackieControlUIRequest* req)
812 {
813         if (req->type == CallSlot) {
814
815                 call_slot (MISSING_INVALIDATOR, req->the_slot);
816
817         } else if (req->type == Quit) {
818
819                 stop ();
820         }
821 }
822
823 int
824 MackieControlProtocol::stop ()
825 {
826         BaseUI::quit ();
827
828         return 0;
829 }
830
831 /** Add a timeout so that a control's in_use flag will be reset some time in the future.
832  *  @param in_use_control the control whose in_use flag to reset.
833  *  @param touch_control a touch control to emit an event for, or 0.
834  */
835 void
836 MackieControlProtocol::add_in_use_timeout (Surface& surface, Control& in_use_control, Control* touch_control)
837 {
838         Glib::RefPtr<Glib::TimeoutSource> timeout (Glib::TimeoutSource::create (250)); // milliseconds
839
840         in_use_control.in_use_connection.disconnect ();
841         in_use_control.in_use_connection = timeout->connect (
842                 sigc::bind (sigc::mem_fun (*this, &MackieControlProtocol::control_in_use_timeout), &surface, &in_use_control, touch_control));
843         in_use_control.in_use_touch_control = touch_control;
844         
845         timeout->attach (main_loop()->get_context());
846
847         DEBUG_TRACE (DEBUG::MackieControl, string_compose ("timeout queued for surface %1, control %2 touch control %3\n",
848                                                            surface.number(), &in_use_control, touch_control));}
849
850 /** Handle timeouts to reset in_use for controls that can't
851  *  do this by themselves (e.g. pots, and faders without touch support).
852  *  @param in_use_control the control whose in_use flag to reset.
853  *  @param touch_control a touch control to emit an event for, or 0.
854  */
855 bool
856 MackieControlProtocol::control_in_use_timeout (Surface* surface, Control* in_use_control, Control* touch_control)
857 {
858         DEBUG_TRACE (DEBUG::MackieControl, string_compose ("timeout elapsed for surface %1, control %2 touch control %3\n",
859                                                            surface->number(), in_use_control, touch_control));
860
861         in_use_control->set_in_use (false);
862
863         if (touch_control) {
864                 /* figure out what to do here */
865         }
866         
867         // only call this method once from the timer
868         return false;
869 }
870
871 void 
872 MackieControlProtocol::update_led (Surface& surface, Button& button, Mackie::LedState ls)
873 {
874         if (ls != none) {
875                 surface.port().write (button.led().set_state (ls));
876         }
877 }
878
879 void
880 MackieControlProtocol::build_button_map ()
881 {
882 #define DEFINE_BUTTON_HANDLER(b,p,r) button_map.insert (pair<int,ButtonHandlers> ((b), ButtonHandlers ((p),(r))));
883
884         DEFINE_BUTTON_HANDLER (Button::Io, &MackieControlProtocol::io_press, &MackieControlProtocol::io_release);
885         DEFINE_BUTTON_HANDLER (Button::Sends, &MackieControlProtocol::sends_press, &MackieControlProtocol::sends_release);
886         DEFINE_BUTTON_HANDLER (Button::Pan, &MackieControlProtocol::pan_press, &MackieControlProtocol::pan_release);
887         DEFINE_BUTTON_HANDLER (Button::Plugin, &MackieControlProtocol::plugin_press, &MackieControlProtocol::plugin_release);
888         DEFINE_BUTTON_HANDLER (Button::Eq, &MackieControlProtocol::eq_press, &MackieControlProtocol::eq_release);
889         DEFINE_BUTTON_HANDLER (Button::Dyn, &MackieControlProtocol::dyn_press, &MackieControlProtocol::dyn_release);
890         DEFINE_BUTTON_HANDLER (Button::Left, &MackieControlProtocol::left_press, &MackieControlProtocol::left_release);
891         DEFINE_BUTTON_HANDLER (Button::Right, &MackieControlProtocol::right_press, &MackieControlProtocol::right_release);
892         DEFINE_BUTTON_HANDLER (Button::ChannelLeft, &MackieControlProtocol::channel_left_press, &MackieControlProtocol::channel_left_release);
893         DEFINE_BUTTON_HANDLER (Button::ChannelRight, &MackieControlProtocol::channel_right_press, &MackieControlProtocol::channel_right_release);
894         DEFINE_BUTTON_HANDLER (Button::Flip, &MackieControlProtocol::flip_press, &MackieControlProtocol::flip_release);
895         DEFINE_BUTTON_HANDLER (Button::Edit, &MackieControlProtocol::edit_press, &MackieControlProtocol::edit_release);
896         DEFINE_BUTTON_HANDLER (Button::NameValue, &MackieControlProtocol::name_value_press, &MackieControlProtocol::name_value_release);
897         DEFINE_BUTTON_HANDLER (Button::TimecodeBeats, &MackieControlProtocol::timecode_beats_press, &MackieControlProtocol::timecode_beats_release);
898         DEFINE_BUTTON_HANDLER (Button::F1, &MackieControlProtocol::F1_press, &MackieControlProtocol::F1_release);
899         DEFINE_BUTTON_HANDLER (Button::F2, &MackieControlProtocol::F2_press, &MackieControlProtocol::F2_release);
900         DEFINE_BUTTON_HANDLER (Button::F3, &MackieControlProtocol::F3_press, &MackieControlProtocol::F3_release);
901         DEFINE_BUTTON_HANDLER (Button::F4, &MackieControlProtocol::F4_press, &MackieControlProtocol::F4_release);
902         DEFINE_BUTTON_HANDLER (Button::F5, &MackieControlProtocol::F5_press, &MackieControlProtocol::F5_release);
903         DEFINE_BUTTON_HANDLER (Button::F6, &MackieControlProtocol::F6_press, &MackieControlProtocol::F6_release);
904         DEFINE_BUTTON_HANDLER (Button::F7, &MackieControlProtocol::F7_press, &MackieControlProtocol::F7_release);
905         DEFINE_BUTTON_HANDLER (Button::F8, &MackieControlProtocol::F8_press, &MackieControlProtocol::F8_release);
906         DEFINE_BUTTON_HANDLER (Button::F9, &MackieControlProtocol::F9_press, &MackieControlProtocol::F9_release);
907         DEFINE_BUTTON_HANDLER (Button::F10, &MackieControlProtocol::F10_press, &MackieControlProtocol::F10_release);
908         DEFINE_BUTTON_HANDLER (Button::F11, &MackieControlProtocol::F11_press, &MackieControlProtocol::F11_release);
909         DEFINE_BUTTON_HANDLER (Button::F12, &MackieControlProtocol::F12_press, &MackieControlProtocol::F12_release);
910         DEFINE_BUTTON_HANDLER (Button::F13, &MackieControlProtocol::F13_press, &MackieControlProtocol::F13_release);
911         DEFINE_BUTTON_HANDLER (Button::F14, &MackieControlProtocol::F14_press, &MackieControlProtocol::F14_release);
912         DEFINE_BUTTON_HANDLER (Button::F15, &MackieControlProtocol::F15_press, &MackieControlProtocol::F15_release);
913         DEFINE_BUTTON_HANDLER (Button::F16, &MackieControlProtocol::F16_press, &MackieControlProtocol::F16_release);
914         DEFINE_BUTTON_HANDLER (Button::Shift, &MackieControlProtocol::shift_press, &MackieControlProtocol::shift_release);
915         DEFINE_BUTTON_HANDLER (Button::Option, &MackieControlProtocol::option_press, &MackieControlProtocol::option_release);
916         DEFINE_BUTTON_HANDLER (Button::Ctrl, &MackieControlProtocol::control_press, &MackieControlProtocol::control_release);
917         DEFINE_BUTTON_HANDLER (Button::CmdAlt, &MackieControlProtocol::cmd_alt_press, &MackieControlProtocol::cmd_alt_release);
918         DEFINE_BUTTON_HANDLER (Button::On, &MackieControlProtocol::on_press, &MackieControlProtocol::on_release);
919         DEFINE_BUTTON_HANDLER (Button::RecReady, &MackieControlProtocol::rec_ready_press, &MackieControlProtocol::rec_ready_release);
920         DEFINE_BUTTON_HANDLER (Button::Undo, &MackieControlProtocol::undo_press, &MackieControlProtocol::undo_release);
921         DEFINE_BUTTON_HANDLER (Button::Save, &MackieControlProtocol::save_press, &MackieControlProtocol::save_release);
922         DEFINE_BUTTON_HANDLER (Button::Touch, &MackieControlProtocol::touch_press, &MackieControlProtocol::touch_release);
923         DEFINE_BUTTON_HANDLER (Button::Redo, &MackieControlProtocol::redo_press, &MackieControlProtocol::redo_release);
924         DEFINE_BUTTON_HANDLER (Button::Marker, &MackieControlProtocol::marker_press, &MackieControlProtocol::marker_release);
925         DEFINE_BUTTON_HANDLER (Button::Enter, &MackieControlProtocol::enter_press, &MackieControlProtocol::enter_release);
926         DEFINE_BUTTON_HANDLER (Button::Cancel, &MackieControlProtocol::cancel_press, &MackieControlProtocol::cancel_release);
927         DEFINE_BUTTON_HANDLER (Button::Mixer, &MackieControlProtocol::mixer_press, &MackieControlProtocol::mixer_release);
928         DEFINE_BUTTON_HANDLER (Button::FrmLeft, &MackieControlProtocol::frm_left_press, &MackieControlProtocol::frm_left_release);
929         DEFINE_BUTTON_HANDLER (Button::FrmRight, &MackieControlProtocol::frm_right_press, &MackieControlProtocol::frm_right_release);
930         DEFINE_BUTTON_HANDLER (Button::Loop, &MackieControlProtocol::loop_press, &MackieControlProtocol::loop_release);
931         DEFINE_BUTTON_HANDLER (Button::PunchIn, &MackieControlProtocol::punch_in_press, &MackieControlProtocol::punch_in_release);
932         DEFINE_BUTTON_HANDLER (Button::PunchOut, &MackieControlProtocol::punch_out_press, &MackieControlProtocol::punch_out_release);
933         DEFINE_BUTTON_HANDLER (Button::Home, &MackieControlProtocol::home_press, &MackieControlProtocol::home_release);
934         DEFINE_BUTTON_HANDLER (Button::End, &MackieControlProtocol::end_press, &MackieControlProtocol::end_release);
935         DEFINE_BUTTON_HANDLER (Button::Rewind, &MackieControlProtocol::rewind_press, &MackieControlProtocol::rewind_release);
936         DEFINE_BUTTON_HANDLER (Button::Ffwd, &MackieControlProtocol::ffwd_press, &MackieControlProtocol::ffwd_release);
937         DEFINE_BUTTON_HANDLER (Button::Stop, &MackieControlProtocol::stop_press, &MackieControlProtocol::stop_release);
938         DEFINE_BUTTON_HANDLER (Button::Play, &MackieControlProtocol::play_press, &MackieControlProtocol::play_release);
939         DEFINE_BUTTON_HANDLER (Button::Record, &MackieControlProtocol::record_press, &MackieControlProtocol::record_release);
940         DEFINE_BUTTON_HANDLER (Button::CursorUp, &MackieControlProtocol::cursor_up_press, &MackieControlProtocol::cursor_up_release);
941         DEFINE_BUTTON_HANDLER (Button::CursorDown, &MackieControlProtocol::cursor_down_press, &MackieControlProtocol::cursor_down_release);
942         DEFINE_BUTTON_HANDLER (Button::CursorLeft, &MackieControlProtocol::cursor_left_press, &MackieControlProtocol::cursor_left_release);
943         DEFINE_BUTTON_HANDLER (Button::CursorRight, &MackieControlProtocol::cursor_right_press, &MackieControlProtocol::cursor_right_release);
944         DEFINE_BUTTON_HANDLER (Button::Zoom, &MackieControlProtocol::zoom_press, &MackieControlProtocol::zoom_release);
945         DEFINE_BUTTON_HANDLER (Button::Scrub, &MackieControlProtocol::scrub_press, &MackieControlProtocol::scrub_release);
946         DEFINE_BUTTON_HANDLER (Button::UserA, &MackieControlProtocol::user_a_press, &MackieControlProtocol::user_a_release);
947         DEFINE_BUTTON_HANDLER (Button::UserB, &MackieControlProtocol::user_b_press, &MackieControlProtocol::user_b_release);
948 }
949
950 void 
951 MackieControlProtocol::handle_button_event (Surface& surface, Button& button, ButtonState bs)
952 {
953         if  (bs != press && bs != release) {
954                 update_led (surface, button, none);
955                 return;
956         }
957         
958         DEBUG_TRACE (DEBUG::MackieControl, string_compose ("Handling %1 for button %2\n", (bs == press ? "press" : "release"), button.id()));
959
960         ButtonMap::iterator b = button_map.find (button.id());
961
962         if (b != button_map.end()) {
963
964                 ButtonHandlers& bh (b->second);
965
966                 switch  (bs) {
967                 case press: 
968                         surface.write (button.led().set_state ((this->*(bh.press)) (button)));
969                 case release: 
970                         surface.write (button.led().set_state ((this->*(bh.release)) (button)));
971                         break;
972                 default:
973                         break;
974                 }
975         }
976 }
977
978 void
979 MackieControlProtocol::select_track (boost::shared_ptr<Route> r)
980 {
981         if (_modifier_state == MODIFIER_SHIFT) {
982                 r->gain_control()->set_value (0.0);
983         } else {
984                 if (_current_selected_track > 0 && r->remote_control_id() == (uint32_t) _current_selected_track) {
985                         UnselectTrack (); /* EMIT SIGNAL */
986                         _current_selected_track = -1;
987                 } else {
988                         SelectByRID (r->remote_control_id()); /* EMIT SIGNAL */
989                         _current_selected_track = r->remote_control_id();;
990                 }
991         }
992 }
993
994 bool
995 MackieControlProtocol::midi_input_handler (IOCondition ioc, MIDI::Port* port)
996 {
997         DEBUG_TRACE (DEBUG::MidiIO, string_compose ("something happend on  %1\n", port->name()));
998
999         if (ioc & ~IO_IN) {
1000                 return false;
1001         }
1002
1003         if (ioc & IO_IN) {
1004
1005                 CrossThreadChannel::drain (port->selectable());
1006
1007                 DEBUG_TRACE (DEBUG::MidiIO, string_compose ("data available on %1\n", port->name()));
1008                 framepos_t now = session->engine().frame_time();
1009                 port->parse (now);
1010         }
1011
1012         return true;
1013 }
1014
1015 void
1016 MackieControlProtocol::clear_ports ()
1017 {
1018         for (PortSources::iterator i = port_sources.begin(); i != port_sources.end(); ++i) {
1019                 g_source_destroy (*i);
1020                 g_source_unref (*i);
1021         }
1022
1023         port_sources.clear ();
1024 }
1025