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