Made master fader touch and jog go to _master_surface instead of first surface.
[ardour.git] / libs / surfaces / mackie / mackie_control_protocol.cc
1 /*
2         Copyright (C) 2006,2007 John Anderson
3         Copyright (C) 2012 Paul Davis
4
5         This program is free software; you can redistribute it and/or modify
6         it under the terms of the GNU General Public License as published by
7         the Free Software Foundation; either version 2 of the License, or
8         (at your option) any later version.
9
10         This program is distributed in the hope that it will be useful,
11         but WITHOUT ANY WARRANTY; without even the implied warranty of
12         MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13         GNU General Public License for more details.
14
15         You should have received a copy of the GNU General Public License
16         along with this program; if not, write to the Free Software
17         Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
18 */
19
20 #include <fcntl.h>
21 #include <iostream>
22 #include <algorithm>
23 #include <cmath>
24 #include <sstream>
25 #include <vector>
26 #include <iomanip>
27
28 #include <inttypes.h>
29 #include <float.h>
30 #include <sys/time.h>
31 #include <errno.h>
32
33 #include <boost/shared_array.hpp>
34
35 #include "midi++/types.h"
36 #include "midi++/port.h"
37 #include "midi++/ipmidi_port.h"
38 #include "pbd/pthread_utils.h"
39 #include "pbd/error.h"
40 #include "pbd/memento_command.h"
41 #include "pbd/convert.h"
42
43 #include "ardour/automation_control.h"
44 #include "ardour/async_midi_port.h"
45 #include "ardour/dB.h"
46 #include "ardour/debug.h"
47 #include "ardour/location.h"
48 #include "ardour/meter.h"
49 #include "ardour/panner.h"
50 #include "ardour/panner_shell.h"
51 #include "ardour/route.h"
52 #include "ardour/session.h"
53 #include "ardour/tempo.h"
54 #include "ardour/track.h"
55 #include "ardour/types.h"
56 #include "ardour/audioengine.h"
57
58 #include "mackie_control_protocol.h"
59
60 #include "midi_byte_array.h"
61 #include "mackie_control_exception.h"
62 #include "device_profile.h"
63 #include "surface_port.h"
64 #include "surface.h"
65 #include "strip.h"
66 #include "control_group.h"
67 #include "meter.h"
68 #include "button.h"
69 #include "fader.h"
70 #include "pot.h"
71
72 using namespace ARDOUR;
73 using namespace std;
74 using namespace PBD;
75 using namespace Glib;
76 using namespace ArdourSurface;
77 using namespace Mackie;
78
79 #include "i18n.h"
80
81 #include "pbd/abstract_ui.cc" // instantiate template
82
83 const int MackieControlProtocol::MODIFIER_OPTION = 0x1;
84 const int MackieControlProtocol::MODIFIER_CONTROL = 0x2;
85 const int MackieControlProtocol::MODIFIER_SHIFT = 0x4;
86 const int MackieControlProtocol::MODIFIER_CMDALT = 0x8;
87
88 MackieControlProtocol* MackieControlProtocol::_instance = 0;
89
90 bool MackieControlProtocol::probe()
91 {
92         return true;
93 }
94
95 MackieControlProtocol::MackieControlProtocol (Session& session)
96         : ControlProtocol (session, X_("Mackie"))
97         , AbstractUI<MackieControlUIRequest> ("mackie")
98         , _current_initial_bank (0)
99         , _timecode_type (ARDOUR::AnyTime::BBT)
100         , _gui (0)
101         , _zoom_mode (false)
102         , _scrub_mode (false)
103         , _flip_mode (Normal)
104         , _view_mode (Mixer)
105         , _current_selected_track (-1)
106         , _modifier_state (0)
107         , _ipmidi_base (MIDI::IPMIDIPort::lowest_ipmidi_port_default)
108         , needs_ipmidi_restart (false)
109         , _metering_active (true)
110         , _initialized (false)
111         , _surfaces_state (0)
112         , _surfaces_version (0)
113         , _session_load (true)
114 {
115         DEBUG_TRACE (DEBUG::MackieControl, "MackieControlProtocol::MackieControlProtocol\n");
116
117         DeviceInfo::reload_device_info ();
118         DeviceProfile::reload_device_profiles ();
119
120         TrackSelectionChanged.connect (gui_connections, MISSING_INVALIDATOR, boost::bind (&MackieControlProtocol::gui_track_selection_changed, this, _1, true), this);
121
122         _instance = this;
123
124         build_button_map ();
125 }
126
127 MackieControlProtocol::~MackieControlProtocol()
128 {
129         DEBUG_TRACE (DEBUG::MackieControl, "MackieControlProtocol::~MackieControlProtocol init\n");
130         
131         DEBUG_TRACE (DEBUG::MackieControl, "MackieControlProtocol::~MackieControlProtocol drop_connections ()\n");
132         drop_connections ();
133
134         DEBUG_TRACE (DEBUG::MackieControl, "MackieControlProtocol::~MackieControlProtocol tear_down_gui ()\n");
135         tear_down_gui ();
136
137         delete _surfaces_state;
138
139         /* stop event loop */
140         DEBUG_TRACE (DEBUG::MackieControl, "MackieControlProtocol::~MackieControlProtocol BaseUI::quit ()\n");
141         BaseUI::quit ();
142
143         try {
144                 DEBUG_TRACE (DEBUG::MackieControl, "MackieControlProtocol::~MackieControlProtocol close()\n");
145                 close();
146         }
147         catch (exception & e) {
148                 cout << "~MackieControlProtocol caught " << e.what() << endl;
149         }
150         catch (...) {
151                 cout << "~MackieControlProtocol caught unknown" << endl;
152         }
153
154         _instance = 0;
155
156         DEBUG_TRACE (DEBUG::MackieControl, "MackieControlProtocol::~MackieControlProtocol done\n");
157 }
158
159 void
160 MackieControlProtocol::thread_init ()
161 {
162         struct sched_param rtparam;
163
164         pthread_set_name (X_("MackieControl"));
165
166         PBD::notify_gui_about_thread_creation (X_("gui"), pthread_self(), X_("MackieControl"), 2048);
167         ARDOUR::SessionEvent::create_per_thread_pool (X_("MackieControl"), 128);
168
169         memset (&rtparam, 0, sizeof (rtparam));
170         rtparam.sched_priority = 9; /* XXX should be relative to audio (JACK) thread */
171
172         if (pthread_setschedparam (pthread_self(), SCHED_FIFO, &rtparam) != 0) {
173                 // do we care? not particularly.
174         }
175 }
176
177 void
178 MackieControlProtocol::midi_connectivity_established ()
179 {
180         for (Surfaces::const_iterator si = surfaces.begin(); si != surfaces.end(); ++si) {
181                 (*si)->say_hello ();
182         }
183
184         if (_device_info.no_handshake()) {
185                 for (Surfaces::const_iterator si = surfaces.begin(); si != surfaces.end(); ++si) {
186                         (*si)->turn_it_on ();
187                 }
188         }
189 }
190
191 // go to the previous track.
192 // Assume that get_sorted_routes().size() > route_table.size()
193 void 
194 MackieControlProtocol::prev_track()
195 {
196         if (_current_initial_bank >= 1) {
197                 switch_banks (_current_initial_bank - 1);
198         }
199 }
200
201 // go to the next track.
202 // Assume that get_sorted_routes().size() > route_table.size()
203 void 
204 MackieControlProtocol::next_track()
205 {
206         Sorted sorted = get_sorted_routes();
207         if (_current_initial_bank + n_strips() < sorted.size()) {
208                 switch_banks (_current_initial_bank + 1);
209         }
210 }
211
212 bool
213 MackieControlProtocol::route_is_locked_to_strip (boost::shared_ptr<Route> r) const
214 {
215         for (Surfaces::const_iterator si = surfaces.begin(); si != surfaces.end(); ++si) {
216                 if ((*si)->route_is_locked_to_strip (r)) {
217                         return true;
218                 }
219         }
220         return false;
221 }
222
223 // predicate for sort call in get_sorted_routes
224 struct RouteByRemoteId
225 {
226         bool operator () (const boost::shared_ptr<Route> & a, const boost::shared_ptr<Route> & b) const
227         {
228                 return a->remote_control_id() < b->remote_control_id();
229         }
230
231         bool operator () (const Route & a, const Route & b) const
232         {
233                 return a.remote_control_id() < b.remote_control_id();
234         }
235
236         bool operator () (const Route * a, const Route * b) const
237         {
238                 return a->remote_control_id() < b->remote_control_id();
239         }
240 };
241
242 MackieControlProtocol::Sorted 
243 MackieControlProtocol::get_sorted_routes()
244 {
245         Sorted sorted;
246
247         // fetch all routes
248         boost::shared_ptr<RouteList> routes = session->get_routes();
249         set<uint32_t> remote_ids;
250
251         // routes with remote_id 0 should never be added
252         // TODO verify this with ardour devs
253         // remote_ids.insert (0);
254
255         // sort in remote_id order, and exclude master, control and hidden routes
256         // and any routes that are already set.
257
258         for (RouteList::iterator it = routes->begin(); it != routes->end(); ++it) {
259
260                 boost::shared_ptr<Route> route = *it;
261
262                 if (remote_ids.find (route->remote_control_id()) != remote_ids.end()) {
263                         continue;
264                 }
265
266                 if (route->is_auditioner() || route->is_master() || route->is_monitor()) {
267                         continue;
268                 }
269
270                 /* don't include locked routes */
271
272                 if (route_is_locked_to_strip(route)) {
273                         continue;
274                 }
275                 /* This next section which is not used yet, looks wrong to me
276                         The first four belong here but the bottom five are not a selection
277                         of routes and belong elsewhere as they are v-pot modes.
278                 */
279                 switch (_view_mode) {
280                 case Mixer:
281                         break;
282                 case AudioTracks:
283                         break;
284                 case Busses:
285                         break;
286                 case MidiTracks:
287                         break;
288                 case Dynamics:
289                         break;
290                 case EQ:
291                         break;
292                 case Loop:
293                         break;
294                 case Sends:
295                         break;
296                 case Plugins:
297                         break;
298                 }
299
300                 sorted.push_back (*it);
301                 remote_ids.insert (route->remote_control_id());
302         }
303
304         sort (sorted.begin(), sorted.end(), RouteByRemoteId());
305         return sorted;
306 }
307
308 void 
309 MackieControlProtocol::refresh_current_bank()
310 {
311         switch_banks (_current_initial_bank, true);
312 }
313
314 uint32_t
315 MackieControlProtocol::n_strips (bool with_locked_strips) const
316 {
317         uint32_t strip_count = 0;
318
319         for (Surfaces::const_iterator si = surfaces.begin(); si != surfaces.end(); ++si) {
320                 strip_count += (*si)->n_strips (with_locked_strips);
321         }
322
323         return strip_count;
324 }
325
326 void 
327 MackieControlProtocol::switch_banks (uint32_t initial, bool force)
328 {
329         DEBUG_TRACE (DEBUG::MackieControl, string_compose ("switch banking to start at %1 force ? %2 current = %3\n", initial, force, _current_initial_bank));
330
331         if (initial == _current_initial_bank && !force) {
332                 return;
333         }
334
335         Sorted sorted = get_sorted_routes();
336         uint32_t strip_cnt = n_strips (false); // do not include locked strips
337                                                // in this count
338
339         if (sorted.size() <= strip_cnt && _current_initial_bank == 0 && !force) {
340                 /* no banking - not enough routes to fill all strips and we're
341                  * not at the first one.
342                  */
343                 return;
344         }
345
346         _current_initial_bank = initial;
347         _current_selected_track = -1;
348
349         // Map current bank of routes onto each surface(+strip)
350
351         if (_current_initial_bank <= sorted.size()) {
352
353                 DEBUG_TRACE (DEBUG::MackieControl, string_compose ("switch to %1, %2, available routes %3 on %4 surfaces\n", 
354                                                                    _current_initial_bank, strip_cnt, sorted.size(),
355                                                                    surfaces.size()));
356
357                 // link routes to strips
358
359                 Sorted::iterator r = sorted.begin() + _current_initial_bank;
360                 
361                 for (Surfaces::iterator si = surfaces.begin(); si != surfaces.end(); ++si) {
362                         vector<boost::shared_ptr<Route> > routes;
363                         uint32_t added = 0;
364
365                         DEBUG_TRACE (DEBUG::MackieControl, string_compose ("surface has %1 unlockedstrips\n", (*si)->n_strips (false)));
366
367                         for (; r != sorted.end() && added < (*si)->n_strips (false); ++r, ++added) {
368                                 routes.push_back (*r);
369                         }
370
371                         DEBUG_TRACE (DEBUG::MackieControl, string_compose ("give surface %1 routes\n", routes.size()));
372
373                         (*si)->map_routes (routes);
374                 }
375         }
376
377         /* reset this to get the right display of view mode after the switch */
378         set_view_mode (_view_mode);
379
380         /* make sure selection is correct */
381         
382         _gui_track_selection_changed (&_last_selected_routes, false);
383         
384         /* current bank has not been saved */
385         session->set_dirty();
386 }
387
388 int 
389 MackieControlProtocol::set_active (bool yn)
390 {
391         DEBUG_TRACE (DEBUG::MackieControl, string_compose("MackieControlProtocol::set_active init with yn: '%1'\n", yn));
392
393         if (yn == active()) {
394                 return 0;
395         }
396
397         if (yn) {
398                 
399                 /* start event loop */
400                 
401                 BaseUI::run ();
402                 
403                 if (create_surfaces ()) {
404                         return -1;
405                 }
406                 connect_session_signals ();
407                 update_surfaces ();
408                 
409                 /* set up periodic task for metering and automation
410                  */
411                 
412                 Glib::RefPtr<Glib::TimeoutSource> periodic_timeout = Glib::TimeoutSource::create (100); // milliseconds
413                 periodic_connection = periodic_timeout->connect (sigc::mem_fun (*this, &MackieControlProtocol::periodic));
414                 periodic_timeout->attach (main_loop()->get_context());
415                 
416         } else {
417
418                 BaseUI::quit ();
419                 close ();
420
421         }
422
423         ControlProtocol::set_active (yn);
424
425         DEBUG_TRACE (DEBUG::MackieControl, string_compose("MackieControlProtocol::set_active done with yn: '%1'\n", yn));
426
427         return 0;
428 }
429
430 bool
431 MackieControlProtocol::periodic ()
432 {
433         if (!active()) {
434                 return false;
435         }
436
437         if (needs_ipmidi_restart) {
438                 ipmidi_restart ();
439                 return true;
440         }
441         
442         if (!_initialized) {
443                 initialize();
444         }
445
446         struct timeval now;
447         uint64_t now_usecs;
448         gettimeofday (&now, 0);
449
450         now_usecs = (now.tv_sec * 1000000) + now.tv_usec;
451
452         {
453                 Glib::Threads::Mutex::Lock lm (surfaces_lock);
454
455                 for (Surfaces::iterator s = surfaces.begin(); s != surfaces.end(); ++s) {
456                         (*s)->periodic (now_usecs);
457                 }
458         }
459
460         update_timecode_display ();
461         
462         return true;
463 }
464
465 void 
466 MackieControlProtocol::update_timecode_beats_led()
467 {
468         if (!_device_info.has_timecode_display()) {
469                 return;
470         }
471
472         DEBUG_TRACE (DEBUG::MackieControl, string_compose("MackieControlProtocol::update_timecode_beats_led(): %1\n", _timecode_type));
473         switch (_timecode_type) {
474                 case ARDOUR::AnyTime::BBT:
475                         update_global_led (Led::Beats, on);
476                         update_global_led (Led::Timecode, off);
477                         break;
478                 case ARDOUR::AnyTime::Timecode:
479                         update_global_led (Led::Timecode, on);
480                         update_global_led (Led::Beats, off);
481                         break;
482                 default:
483                         ostringstream os;
484                         os << "Unknown Anytime::Type " << _timecode_type;
485                         throw runtime_error (os.str());
486         }
487 }
488
489 void 
490 MackieControlProtocol::update_global_button (int id, LedState ls)
491 {
492         Glib::Threads::Mutex::Lock lm (surfaces_lock);
493
494         if (!_device_info.has_global_controls()) {
495                 return;
496         }
497         // surface needs to be master surface
498         boost::shared_ptr<Surface> surface = _master_surface;
499
500         map<int,Control*>::iterator x = surface->controls_by_device_independent_id.find (id);
501         if (x != surface->controls_by_device_independent_id.end()) {
502                 Button * button = dynamic_cast<Button*> (x->second);
503                 surface->write (button->set_state (ls));
504         } else {
505                 DEBUG_TRACE (DEBUG::MackieControl, string_compose ("Button %1 not found\n", id));
506         }
507 }
508
509 void 
510 MackieControlProtocol::update_global_led (int id, LedState ls)
511 {
512         Glib::Threads::Mutex::Lock lm (surfaces_lock);
513
514         if (!_device_info.has_global_controls()) {
515                 return;
516         }
517         boost::shared_ptr<Surface> surface = _master_surface;
518
519         map<int,Control*>::iterator x = surface->controls_by_device_independent_id.find (id);
520
521         if (x != surface->controls_by_device_independent_id.end()) {
522                 Led * led = dynamic_cast<Led*> (x->second);
523                 DEBUG_TRACE (DEBUG::MackieControl, "Writing LedState\n");
524                 surface->write (led->set_state (ls));
525         } else {
526                 DEBUG_TRACE (DEBUG::MackieControl, string_compose ("Led %1 not found\n", id));
527         }
528 }
529
530 void
531 MackieControlProtocol::device_ready ()
532 {
533         /* this is not required to be called, but for devices which do
534          * handshaking, it can be called once the device has verified the
535          * connection.
536          */
537          
538         DEBUG_TRACE (DEBUG::MackieControl, string_compose ("device ready init (active=%1)\n", active()));
539         update_surfaces ();
540 }
541
542 // send messages to surface to set controls to correct values
543 void 
544 MackieControlProtocol::update_surfaces()
545 {
546         DEBUG_TRACE (DEBUG::MackieControl, string_compose ("MackieControlProtocol::update_surfaces() init (active=%1)\n", active()));
547         if (!active()) {
548                 return;
549         }
550
551         // do the initial bank switch to connect signals
552         // _current_initial_bank is initialised by set_state
553         switch_banks (_current_initial_bank, true);
554         
555         DEBUG_TRACE (DEBUG::MackieControl, "MackieControlProtocol::update_surfaces() finished\n");
556 }
557
558 void
559 MackieControlProtocol::initialize()
560 {
561         {
562                 Glib::Threads::Mutex::Lock lm (surfaces_lock);
563                 
564                 if (surfaces.empty()) {
565                         return;
566                 }
567                 
568                 if (!_master_surface->active ()) {
569                         return;
570                 }
571                 
572                 // sometimes the jog wheel is a pot
573                 if (_device_info.has_jog_wheel()) {
574                         _master_surface->blank_jog_ring ();
575                 }
576         }
577
578         // update global buttons and displays
579
580         notify_record_state_changed();
581         notify_transport_state_changed();
582         update_timecode_beats_led();
583         
584         _initialized = true;
585 }
586
587 void 
588 MackieControlProtocol::connect_session_signals()
589 {
590         // receive routes added
591         session->RouteAdded.connect(session_connections, MISSING_INVALIDATOR, boost::bind (&MackieControlProtocol::notify_route_added, this, _1), this);
592         // receive record state toggled
593         session->RecordStateChanged.connect(session_connections, MISSING_INVALIDATOR, boost::bind (&MackieControlProtocol::notify_record_state_changed, this), this);
594         // receive transport state changed
595         session->TransportStateChange.connect(session_connections, MISSING_INVALIDATOR, boost::bind (&MackieControlProtocol::notify_transport_state_changed, this), this);
596         session->TransportLooped.connect (session_connections, MISSING_INVALIDATOR, boost::bind (&MackieControlProtocol::notify_loop_state_changed, this), this);
597         // receive punch-in and punch-out
598         Config->ParameterChanged.connect(session_connections, MISSING_INVALIDATOR, boost::bind (&MackieControlProtocol::notify_parameter_changed, this, _1), this);
599         session->config.ParameterChanged.connect (session_connections, MISSING_INVALIDATOR, boost::bind (&MackieControlProtocol::notify_parameter_changed, this, _1), this);
600         // receive rude solo changed
601         session->SoloActive.connect(session_connections, MISSING_INVALIDATOR, boost::bind (&MackieControlProtocol::notify_solo_active_changed, this, _1), this);
602
603         // make sure remote id changed signals reach here
604         // see also notify_route_added
605         Sorted sorted = get_sorted_routes();
606
607         for (Sorted::iterator it = sorted.begin(); it != sorted.end(); ++it) {
608                 (*it)->RemoteControlIDChanged.connect (route_connections, MISSING_INVALIDATOR, boost::bind (&MackieControlProtocol::notify_remote_id_changed, this), this);
609         }
610 }
611
612 void
613 MackieControlProtocol::set_profile (const string& profile_name)
614 {
615         if (profile_name == "default") {
616                 /* reset to default */
617                 _device_profile = DeviceProfile (profile_name);
618         }
619
620         map<string,DeviceProfile>::iterator d = DeviceProfile::device_profiles.find (profile_name);
621
622         if (d == DeviceProfile::device_profiles.end()) {
623                 return;
624         }
625         
626         _device_profile = d->second;
627 }       
628
629 int
630 MackieControlProtocol::set_device_info (const string& device_name)
631 {
632         map<string,DeviceInfo>::iterator d = DeviceInfo::device_info.find (device_name);
633
634         DEBUG_TRACE (DEBUG::MackieControl, string_compose ("new device chosen %1\n", device_name));
635
636         if (d == DeviceInfo::device_info.end()) {
637                 return -1;
638         }
639         
640         _device_info = d->second;
641
642         return 0;
643 }
644
645 int
646 MackieControlProtocol::set_device (const string& device_name)
647 {
648         if (set_device_info (device_name)) {
649                 return -1;
650         }
651
652         clear_surfaces ();
653
654         if (create_surfaces ()) {
655                 return -1;
656         }
657
658         switch_banks (0, true);
659
660         return 0;
661 }
662
663 gboolean 
664 ArdourSurface::ipmidi_input_handler (GIOChannel*, GIOCondition condition, void *data)
665 {
666         ArdourSurface::MackieControlProtocol::ipMIDIHandler* ipm = static_cast<ArdourSurface::MackieControlProtocol::ipMIDIHandler*>(data);
667         return ipm->mcp->midi_input_handler (Glib::IOCondition (condition), ipm->port);
668 }
669
670 int
671 MackieControlProtocol::create_surfaces ()
672 {
673         string device_name;
674         surface_type_t stype = mcu; // type not yet determined
675         char buf[128];
676
677         if (_device_info.extenders() == 0) {
678                 device_name = X_("mackie control");
679         } else {
680                 device_name = X_("mackie control #1");
681         }
682
683         DEBUG_TRACE (DEBUG::MackieControl, string_compose ("Create %1 surfaces\n", 1 + _device_info.extenders()));
684
685         for (uint32_t n = 0; n < 1 + _device_info.extenders(); ++n) {
686
687                 boost::shared_ptr<Surface> surface;
688
689                 if (n == _device_info.master_position()) {
690                         stype = mcu;
691                 } else {
692                         stype = ext;
693                 }
694                 try {
695                         surface.reset (new Surface (*this, device_name, n, stype));
696                 } catch (...) {
697                         return -1;
698                 }
699
700                 if (n == _device_info.master_position()) {
701                         _master_surface = surface;
702                 }
703
704                 if (_surfaces_state) {
705                         surface->set_state (*_surfaces_state, _surfaces_version);
706                 }
707
708                 {
709                         Glib::Threads::Mutex::Lock lm (surfaces_lock);
710                         surfaces.push_back (surface);
711                 }
712                 
713                 if (_device_info.extenders() < 2) {
714                         device_name = X_("mackie control #2");
715                 } else {
716                         snprintf (buf, sizeof (buf), X_("mackie control #%d"), n+2);
717                         device_name = buf;
718                 }
719
720                 if (!_device_info.uses_ipmidi()) {
721
722                         _input_bundle.reset (new ARDOUR::Bundle (_("Mackie Control In"), true));
723                         _output_bundle.reset (new ARDOUR::Bundle (_("Mackie Control Out"), false));
724
725                         _input_bundle->add_channel (
726                                 surface->port().input_port().name(),
727                                 ARDOUR::DataType::MIDI,
728                                 session->engine().make_port_name_non_relative (surface->port().input_port().name())
729                                 );
730                         
731                         _output_bundle->add_channel (
732                                 surface->port().output_port().name(),
733                                 ARDOUR::DataType::MIDI,
734                                 session->engine().make_port_name_non_relative (surface->port().output_port().name())
735                                 );
736
737                         session->BundleAddedOrRemoved ();
738
739                 } else {
740                         _input_bundle.reset ((ARDOUR::Bundle*) 0);
741                         _output_bundle.reset ((ARDOUR::Bundle*) 0);
742
743                         session->BundleAddedOrRemoved ();
744                 }
745
746                 MIDI::Port& input_port (surface->port().input_port());
747                 AsyncMIDIPort* asp = dynamic_cast<AsyncMIDIPort*> (&input_port);
748
749                 if (asp) {
750
751                         /* async MIDI port */
752
753                         asp->xthread().set_receive_handler (sigc::bind (sigc::mem_fun (this, &MackieControlProtocol::midi_input_handler), &input_port));
754                         asp->xthread().attach (main_loop()->get_context());
755
756                 } else {
757
758                         /* ipMIDI port, no IOSource method at this time */
759
760                         int fd;
761
762                         if ((fd = input_port.selectable ()) >= 0) {
763
764                                 GIOChannel* ioc = g_io_channel_unix_new (fd);
765                                 GSource* gsrc = g_io_create_watch (ioc, GIOCondition (G_IO_IN|G_IO_HUP|G_IO_ERR));
766                                 
767                                 /* hack up an object so that in the callback from the event loop
768                                    we have both the MackieControlProtocol and the input port.
769                                    
770                                    If we were using C++ for this stuff we wouldn't need this
771                                    but a nasty, not-fixable bug in the binding between C 
772                                    and C++ makes it necessary to avoid C++ for the IO
773                                    callback setup.
774                                 */
775
776                                 ipMIDIHandler* ipm = new ipMIDIHandler (); /* we will leak this sizeof(pointer)*2 sized object */
777                                 ipm->mcp = this;
778                                 ipm->port = &input_port;
779
780                                 g_source_set_callback (gsrc, (GSourceFunc) ipmidi_input_handler, ipm, NULL);
781                                 g_source_attach (gsrc, main_loop()->get_context()->gobj());
782                         }
783                 }
784         }
785
786         return 0;
787 }
788
789 void 
790 MackieControlProtocol::close()
791 {
792         session_connections.drop_connections ();
793         route_connections.drop_connections ();
794         periodic_connection.disconnect ();
795
796         clear_surfaces();
797 }
798
799 XMLNode& 
800 MackieControlProtocol::get_state()
801 {
802         XMLNode& node (ControlProtocol::get_state());
803
804         DEBUG_TRACE (DEBUG::MackieControl, "MackieControlProtocol::get_state init\n");
805         char buf[16];
806
807         // add current bank
808         snprintf (buf, sizeof (buf), "%d", _current_initial_bank);
809         node.add_property (X_("bank"), buf);
810
811         // ipMIDI base port (possibly not used)
812         snprintf (buf, sizeof (buf), "%d", _ipmidi_base);
813         node.add_property (X_("ipmidi-base"), buf);
814
815         node.add_property (X_("device-profile"), _device_profile.name());
816         node.add_property (X_("device-name"), _device_info.name());
817
818         XMLNode* snode = new XMLNode (X_("Surfaces"));
819         for (Surfaces::iterator s = surfaces.begin(); s != surfaces.end(); ++s) {
820                 snode->add_child_nocopy ((*s)->get_state());
821         }
822
823         node.add_child_nocopy (*snode);
824
825         DEBUG_TRACE (DEBUG::MackieControl, "MackieControlProtocol::get_state done\n");
826
827         return node;
828 }
829
830 int 
831 MackieControlProtocol::set_state (const XMLNode & node, int version)
832 {
833         DEBUG_TRACE (DEBUG::MackieControl, string_compose ("MackieControlProtocol::set_state: active %1\n", active()));
834
835         int retval = 0;
836         const XMLProperty* prop;
837         uint32_t bank = 0;
838
839         if (ControlProtocol::set_state (node, version)) {
840                 return -1;
841         }
842         
843         if ((prop = node.property (X_("ipmidi-base"))) != 0) {
844                 set_ipmidi_base (atoi (prop->value()));
845         }
846
847         // fetch current bank
848         if ((prop = node.property (X_("bank"))) != 0) {
849                 bank = atoi (prop->value());
850         }
851         
852         if ((prop = node.property (X_("device-name"))) != 0) {
853                 set_device_info (prop->value());
854         }
855
856         if ((prop = node.property (X_("device-profile"))) != 0) {
857                 set_profile (prop->value());
858         }
859         
860         XMLNode* snode = node.child (X_("Surfaces"));
861         
862         delete _surfaces_state;
863         _surfaces_state = 0;
864
865         if (snode) {
866                 _surfaces_state = new XMLNode (*snode);
867                 _surfaces_version = version;
868         }
869
870         switch_banks (bank, true);
871         
872         DEBUG_TRACE (DEBUG::MackieControl, "MackieControlProtocol::set_state done\n");
873
874         return retval;
875 }
876
877 string 
878 MackieControlProtocol::format_bbt_timecode (framepos_t now_frame)
879 {
880         Timecode::BBT_Time bbt_time;
881
882         session->bbt_time (now_frame, bbt_time);
883
884         // The Mackie protocol spec is built around a BBT time display of
885         //
886         // digits:     888/88/88/888
887         // semantics:  BBB/bb/ss/ttt
888         //
889         // The third field is "subdivisions" which is a concept found in Logic
890         // but not present in Ardour. Instead Ardour displays a 4 digit tick
891         // count, which we need to spread across the 5 digits of ss/ttt.
892
893         ostringstream os;
894
895         os << setw(3) << setfill('0') << bbt_time.bars;
896         os << setw(2) << setfill('0') << bbt_time.beats;
897         os << ' ';
898         os << setw(1) << setfill('0') << bbt_time.ticks / 1000;
899         os << setw(3) << setfill('0') << bbt_time.ticks % 1000;
900
901         return os.str();
902 }
903
904 string 
905 MackieControlProtocol::format_timecode_timecode (framepos_t now_frame)
906 {
907         Timecode::Time timecode;
908         session->timecode_time (now_frame, timecode);
909
910         // According to the Logic docs
911         // digits: 888/88/88/888
912         // Timecode mode: Hours/Minutes/Seconds/Frames
913         ostringstream os;
914         os << setw(2) << setfill('0') << timecode.hours;
915         os << ' ';
916         os << setw(2) << setfill('0') << timecode.minutes;
917         os << setw(2) << setfill('0') << timecode.seconds;
918         os << ' ';
919         os << setw(2) << setfill('0') << timecode.frames;
920
921         return os.str();
922 }
923
924 void 
925 MackieControlProtocol::update_timecode_display()
926 {
927         Glib::Threads::Mutex::Lock lm (surfaces_lock);
928
929         if (surfaces.empty()) {
930                 return;
931         }
932
933         boost::shared_ptr<Surface> surface = _master_surface;
934
935         if (surface->type() != mcu || !_device_info.has_timecode_display() || !surface->active ()) {
936                 return;
937         }
938
939         // do assignment here so current_frame is fixed
940         framepos_t current_frame = session->transport_frame();
941         string timecode;
942
943         switch (_timecode_type) {
944         case ARDOUR::AnyTime::BBT:
945                 timecode = format_bbt_timecode (current_frame);
946                 break;
947         case ARDOUR::AnyTime::Timecode:
948                 timecode = format_timecode_timecode (current_frame);
949                 break;
950         default:
951                 return;
952         }
953         
954         // only write the timecode string to the MCU if it's changed
955         // since last time. This is to reduce midi bandwidth used.
956         if (timecode != _timecode_last) {
957                 surface->display_timecode (timecode, _timecode_last);
958                 _timecode_last = timecode;
959         }
960 }
961
962 ///////////////////////////////////////////
963 // Session signals
964 ///////////////////////////////////////////
965
966 void MackieControlProtocol::notify_parameter_changed (std::string const & p)
967 {
968         if (p == "punch-in") {
969                 // no such button right now
970                 // update_global_button (Button::PunchIn, session->config.get_punch_in());
971         } else if (p == "punch-out") {
972                 // no such button right now
973                 // update_global_button (Button::PunchOut, session->config.get_punch_out());
974         } else if (p == "clicking") {
975                 // update_global_button (Button::RelayClick, Config->get_clicking());
976         } else {
977                 DEBUG_TRACE (DEBUG::MackieControl, string_compose ("parameter changed: %1\n", p));
978         }
979 }
980
981 // RouteList is the set of routes that have just been added
982 void 
983 MackieControlProtocol::notify_route_added (ARDOUR::RouteList & rl)
984 {
985         // currently assigned banks are less than the full set of
986         // strips, so activate the new strip now.
987
988         refresh_current_bank();
989
990         // otherwise route added, but current bank needs no updating
991
992         // make sure remote id changes in the new route are handled
993         typedef ARDOUR::RouteList ARS;
994
995         for (ARS::iterator it = rl.begin(); it != rl.end(); ++it) {
996                 (*it)->RemoteControlIDChanged.connect (route_connections, MISSING_INVALIDATOR, boost::bind (&MackieControlProtocol::notify_remote_id_changed, this), this);
997         }
998 }
999
1000 void 
1001 MackieControlProtocol::notify_solo_active_changed (bool active)
1002 {
1003         boost::shared_ptr<Surface> surface;
1004
1005         {
1006                 Glib::Threads::Mutex::Lock lm (surfaces_lock);
1007                 surface = _master_surface;
1008         }
1009         
1010         map<int,Control*>::iterator x = surface->controls_by_device_independent_id.find (Led::RudeSolo);
1011         if (x != surface->controls_by_device_independent_id.end()) {
1012                 Led* rude_solo = dynamic_cast<Led*> (x->second);
1013                 if (rude_solo) {
1014                         surface->write (rude_solo->set_state (active ? flashing : off));
1015                 }
1016         }
1017 }
1018
1019 void 
1020 MackieControlProtocol::notify_remote_id_changed()
1021 {
1022         Sorted sorted = get_sorted_routes();
1023         uint32_t sz = n_strips();
1024
1025         // if a remote id has been moved off the end, we need to shift
1026         // the current bank backwards.
1027
1028         if (sorted.size() - _current_initial_bank < sz) {
1029                 // but don't shift backwards past the zeroth channel
1030                 switch_banks (max((Sorted::size_type) 0, sorted.size() - sz));
1031         } else {
1032                 // Otherwise just refresh the current bank
1033                 refresh_current_bank();
1034         }
1035 }
1036
1037 ///////////////////////////////////////////
1038 // Transport signals
1039 ///////////////////////////////////////////
1040
1041 void 
1042 MackieControlProtocol::notify_loop_state_changed()
1043 {
1044         update_global_button (Button::Loop, session->get_play_loop());
1045 }
1046
1047 void 
1048 MackieControlProtocol::notify_transport_state_changed()
1049 {
1050         if (!_device_info.has_global_controls()) {
1051                 return;
1052         }
1053
1054         // switch various play and stop buttons on / off
1055         update_global_button (Button::Loop, session->get_play_loop());
1056         update_global_button (Button::Play, session->transport_speed() == 1.0);
1057         update_global_button (Button::Stop, session->transport_stopped ());
1058         update_global_button (Button::Rewind, session->transport_speed() < 0.0);
1059         update_global_button (Button::Ffwd, session->transport_speed() > 1.0);
1060
1061         notify_metering_state_changed ();
1062 }
1063
1064 void 
1065 MackieControlProtocol::notify_metering_state_changed()
1066 {
1067         Glib::Threads::Mutex::Lock lm (surfaces_lock);
1068
1069         for (Surfaces::iterator s = surfaces.begin(); s != surfaces.end(); ++s) {
1070                 (*s)->notify_metering_state_changed ();
1071         }       
1072 }
1073
1074 void
1075 MackieControlProtocol::notify_record_state_changed ()
1076 {
1077         if (!_device_info.has_global_controls()) {
1078                 return;
1079         }
1080
1081         boost::shared_ptr<Surface> surface;
1082
1083         {
1084                 Glib::Threads::Mutex::Lock lm (surfaces_lock);
1085                 surface = _master_surface;
1086         }
1087                 
1088         /* rec is a tristate */
1089
1090         map<int,Control*>::iterator x = surface->controls_by_device_independent_id.find (Button::Record);
1091         if (x != surface->controls_by_device_independent_id.end()) {
1092                 Button * rec = dynamic_cast<Button*> (x->second);
1093                 if (rec) {
1094                         LedState ls;
1095                         
1096                         switch (session->record_status()) {
1097                         case Session::Disabled:
1098                                 DEBUG_TRACE (DEBUG::MackieControl, "record state changed to disabled, LED off\n");
1099                                 ls = off;
1100                                 break;
1101                         case Session::Recording:
1102                                 DEBUG_TRACE (DEBUG::MackieControl, "record state changed to recording, LED on\n");
1103                                 ls = on;
1104                                 break;
1105                         case Session::Enabled:
1106                                 DEBUG_TRACE (DEBUG::MackieControl, "record state changed to enabled, LED flashing\n");
1107                                 ls = flashing;
1108                                 break;
1109                         }
1110
1111                         surface->write (rec->set_state (ls));
1112                 }
1113         }
1114 }
1115
1116 list<boost::shared_ptr<ARDOUR::Bundle> >
1117 MackieControlProtocol::bundles ()
1118 {
1119         list<boost::shared_ptr<ARDOUR::Bundle> > b;
1120
1121         if (_input_bundle) {
1122                 b.push_back (_input_bundle);
1123                 b.push_back (_output_bundle);
1124         }
1125
1126         return b;
1127 }
1128
1129 void
1130 MackieControlProtocol::do_request (MackieControlUIRequest* req)
1131 {
1132         if (req->type == CallSlot) {
1133
1134                 call_slot (MISSING_INVALIDATOR, req->the_slot);
1135
1136         } else if (req->type == Quit) {
1137
1138                 stop ();
1139         }
1140 }
1141
1142 int
1143 MackieControlProtocol::stop ()
1144 {
1145         BaseUI::quit ();
1146
1147         return 0;
1148 }
1149
1150 void 
1151 MackieControlProtocol::update_led (Surface& surface, Button& button, Mackie::LedState ls)
1152 {
1153         if (ls != none) {
1154                 surface.port().write (button.set_state (ls));
1155         }
1156 }
1157
1158 void
1159 MackieControlProtocol::build_button_map ()
1160 {
1161         /* this maps our device-independent button codes to the methods that handle them.
1162          */
1163
1164 #define DEFINE_BUTTON_HANDLER(b,p,r) button_map.insert (pair<Button::ID,ButtonHandlers> ((b), ButtonHandlers ((p),(r))));
1165
1166         DEFINE_BUTTON_HANDLER (Button::Track, &MackieControlProtocol::track_press, &MackieControlProtocol::track_release);
1167         DEFINE_BUTTON_HANDLER (Button::Send, &MackieControlProtocol::send_press, &MackieControlProtocol::send_release);
1168         DEFINE_BUTTON_HANDLER (Button::Pan, &MackieControlProtocol::pan_press, &MackieControlProtocol::pan_release);
1169         DEFINE_BUTTON_HANDLER (Button::Plugin, &MackieControlProtocol::plugin_press, &MackieControlProtocol::plugin_release);
1170         DEFINE_BUTTON_HANDLER (Button::Eq, &MackieControlProtocol::eq_press, &MackieControlProtocol::eq_release);
1171         DEFINE_BUTTON_HANDLER (Button::Dyn, &MackieControlProtocol::dyn_press, &MackieControlProtocol::dyn_release);
1172         DEFINE_BUTTON_HANDLER (Button::Left, &MackieControlProtocol::left_press, &MackieControlProtocol::left_release);
1173         DEFINE_BUTTON_HANDLER (Button::Right, &MackieControlProtocol::right_press, &MackieControlProtocol::right_release);
1174         DEFINE_BUTTON_HANDLER (Button::ChannelLeft, &MackieControlProtocol::channel_left_press, &MackieControlProtocol::channel_left_release);
1175         DEFINE_BUTTON_HANDLER (Button::ChannelRight, &MackieControlProtocol::channel_right_press, &MackieControlProtocol::channel_right_release);
1176         DEFINE_BUTTON_HANDLER (Button::Flip, &MackieControlProtocol::flip_press, &MackieControlProtocol::flip_release);
1177         DEFINE_BUTTON_HANDLER (Button::View, &MackieControlProtocol::view_press, &MackieControlProtocol::view_release);
1178         DEFINE_BUTTON_HANDLER (Button::NameValue, &MackieControlProtocol::name_value_press, &MackieControlProtocol::name_value_release);
1179         DEFINE_BUTTON_HANDLER (Button::TimecodeBeats, &MackieControlProtocol::timecode_beats_press, &MackieControlProtocol::timecode_beats_release);
1180         DEFINE_BUTTON_HANDLER (Button::F1, &MackieControlProtocol::F1_press, &MackieControlProtocol::F1_release);
1181         DEFINE_BUTTON_HANDLER (Button::F2, &MackieControlProtocol::F2_press, &MackieControlProtocol::F2_release);
1182         DEFINE_BUTTON_HANDLER (Button::F3, &MackieControlProtocol::F3_press, &MackieControlProtocol::F3_release);
1183         DEFINE_BUTTON_HANDLER (Button::F4, &MackieControlProtocol::F4_press, &MackieControlProtocol::F4_release);
1184         DEFINE_BUTTON_HANDLER (Button::F5, &MackieControlProtocol::F5_press, &MackieControlProtocol::F5_release);
1185         DEFINE_BUTTON_HANDLER (Button::F6, &MackieControlProtocol::F6_press, &MackieControlProtocol::F6_release);
1186         DEFINE_BUTTON_HANDLER (Button::F7, &MackieControlProtocol::F7_press, &MackieControlProtocol::F7_release);
1187         DEFINE_BUTTON_HANDLER (Button::F8, &MackieControlProtocol::F8_press, &MackieControlProtocol::F8_release);
1188         DEFINE_BUTTON_HANDLER (Button::MidiTracks, &MackieControlProtocol::miditracks_press, &MackieControlProtocol::miditracks_release);
1189         DEFINE_BUTTON_HANDLER (Button::Inputs, &MackieControlProtocol::inputs_press, &MackieControlProtocol::inputs_release);
1190         DEFINE_BUTTON_HANDLER (Button::AudioTracks, &MackieControlProtocol::audiotracks_press, &MackieControlProtocol::audiotracks_release);
1191         DEFINE_BUTTON_HANDLER (Button::AudioInstruments, &MackieControlProtocol::audioinstruments_press, &MackieControlProtocol::audioinstruments_release);
1192         DEFINE_BUTTON_HANDLER (Button::Aux, &MackieControlProtocol::aux_press, &MackieControlProtocol::aux_release);
1193         DEFINE_BUTTON_HANDLER (Button::Busses, &MackieControlProtocol::busses_press, &MackieControlProtocol::busses_release);
1194         DEFINE_BUTTON_HANDLER (Button::Outputs, &MackieControlProtocol::outputs_press, &MackieControlProtocol::outputs_release);
1195         DEFINE_BUTTON_HANDLER (Button::User, &MackieControlProtocol::user_press, &MackieControlProtocol::user_release);
1196         DEFINE_BUTTON_HANDLER (Button::Shift, &MackieControlProtocol::shift_press, &MackieControlProtocol::shift_release);
1197         DEFINE_BUTTON_HANDLER (Button::Option, &MackieControlProtocol::option_press, &MackieControlProtocol::option_release);
1198         DEFINE_BUTTON_HANDLER (Button::Ctrl, &MackieControlProtocol::control_press, &MackieControlProtocol::control_release);
1199         DEFINE_BUTTON_HANDLER (Button::CmdAlt, &MackieControlProtocol::cmd_alt_press, &MackieControlProtocol::cmd_alt_release);
1200         DEFINE_BUTTON_HANDLER (Button::Read, &MackieControlProtocol::read_press, &MackieControlProtocol::read_release);
1201         DEFINE_BUTTON_HANDLER (Button::Write, &MackieControlProtocol::write_press, &MackieControlProtocol::write_release);
1202         DEFINE_BUTTON_HANDLER (Button::Trim, &MackieControlProtocol::trim_press, &MackieControlProtocol::trim_release);
1203         DEFINE_BUTTON_HANDLER (Button::Touch, &MackieControlProtocol::touch_press, &MackieControlProtocol::touch_release);
1204         DEFINE_BUTTON_HANDLER (Button::Latch, &MackieControlProtocol::latch_press, &MackieControlProtocol::latch_release);
1205         DEFINE_BUTTON_HANDLER (Button::Grp, &MackieControlProtocol::grp_press, &MackieControlProtocol::grp_release);
1206         DEFINE_BUTTON_HANDLER (Button::Save, &MackieControlProtocol::save_press, &MackieControlProtocol::save_release);
1207         DEFINE_BUTTON_HANDLER (Button::Undo, &MackieControlProtocol::undo_press, &MackieControlProtocol::undo_release);
1208         DEFINE_BUTTON_HANDLER (Button::Cancel, &MackieControlProtocol::cancel_press, &MackieControlProtocol::cancel_release);
1209         DEFINE_BUTTON_HANDLER (Button::Enter, &MackieControlProtocol::enter_press, &MackieControlProtocol::enter_release);
1210         DEFINE_BUTTON_HANDLER (Button::Marker, &MackieControlProtocol::marker_press, &MackieControlProtocol::marker_release);
1211         DEFINE_BUTTON_HANDLER (Button::Nudge, &MackieControlProtocol::nudge_press, &MackieControlProtocol::nudge_release);
1212         DEFINE_BUTTON_HANDLER (Button::Loop, &MackieControlProtocol::loop_press, &MackieControlProtocol::loop_release);
1213         DEFINE_BUTTON_HANDLER (Button::Drop, &MackieControlProtocol::drop_press, &MackieControlProtocol::drop_release);
1214         DEFINE_BUTTON_HANDLER (Button::Replace, &MackieControlProtocol::replace_press, &MackieControlProtocol::replace_release);
1215         DEFINE_BUTTON_HANDLER (Button::Click, &MackieControlProtocol::click_press, &MackieControlProtocol::click_release);
1216         DEFINE_BUTTON_HANDLER (Button::ClearSolo, &MackieControlProtocol::clearsolo_press, &MackieControlProtocol::clearsolo_release);
1217         DEFINE_BUTTON_HANDLER (Button::Rewind, &MackieControlProtocol::rewind_press, &MackieControlProtocol::rewind_release);
1218         DEFINE_BUTTON_HANDLER (Button::Ffwd, &MackieControlProtocol::ffwd_press, &MackieControlProtocol::ffwd_release);
1219         DEFINE_BUTTON_HANDLER (Button::Stop, &MackieControlProtocol::stop_press, &MackieControlProtocol::stop_release);
1220         DEFINE_BUTTON_HANDLER (Button::Play, &MackieControlProtocol::play_press, &MackieControlProtocol::play_release);
1221         DEFINE_BUTTON_HANDLER (Button::Record, &MackieControlProtocol::record_press, &MackieControlProtocol::record_release);
1222         DEFINE_BUTTON_HANDLER (Button::CursorUp, &MackieControlProtocol::cursor_up_press, &MackieControlProtocol::cursor_up_release);
1223         DEFINE_BUTTON_HANDLER (Button::CursorDown, &MackieControlProtocol::cursor_down_press, &MackieControlProtocol::cursor_down_release);
1224         DEFINE_BUTTON_HANDLER (Button::CursorLeft, &MackieControlProtocol::cursor_left_press, &MackieControlProtocol::cursor_left_release);
1225         DEFINE_BUTTON_HANDLER (Button::CursorRight, &MackieControlProtocol::cursor_right_press, &MackieControlProtocol::cursor_right_release);
1226         DEFINE_BUTTON_HANDLER (Button::Zoom, &MackieControlProtocol::zoom_press, &MackieControlProtocol::zoom_release);
1227         DEFINE_BUTTON_HANDLER (Button::Scrub, &MackieControlProtocol::scrub_press, &MackieControlProtocol::scrub_release);
1228         DEFINE_BUTTON_HANDLER (Button::UserA, &MackieControlProtocol::user_a_press, &MackieControlProtocol::user_a_release);
1229         DEFINE_BUTTON_HANDLER (Button::UserB, &MackieControlProtocol::user_b_press, &MackieControlProtocol::user_b_release);
1230         DEFINE_BUTTON_HANDLER (Button::MasterFaderTouch, &MackieControlProtocol::master_fader_touch_press, &MackieControlProtocol::master_fader_touch_release);
1231
1232 }
1233
1234 void 
1235 MackieControlProtocol::handle_button_event (Surface& surface, Button& button, ButtonState bs)
1236 {
1237         if  (bs != press && bs != release) {
1238                 update_led (surface, button, none);
1239                 return;
1240         }
1241         
1242         DEBUG_TRACE (DEBUG::MackieControl, string_compose ("Handling %1 for button %2 (%3)\n", (bs == press ? "press" : "release"), button.id(),
1243                                                            Button::id_to_name (button.bid())));
1244
1245         /* check profile first */
1246         
1247         string action = _device_profile.get_button_action (button.bid(), _modifier_state);
1248         
1249         DEBUG_TRACE (DEBUG::MackieControl, string_compose ("Looked up action for button %1 with modifier %2, got [%3]\n",
1250                                                            button.bid(), _modifier_state, action));
1251
1252         if (!action.empty()) {
1253                 /* if there is a bound action for this button, and this is a press event,
1254                    carry out the action. If its a release event, do nothing since we 
1255                    don't bind to them at all but don't want any other handling to 
1256                    occur either.
1257                 */
1258                 if (bs == press) {
1259                         DEBUG_TRACE (DEBUG::MackieControl, string_compose ("executing action %1\n", action));
1260                         access_action (action);
1261                 }
1262                 return;
1263         }
1264
1265         /* lookup using the device-INDEPENDENT button ID */
1266
1267         ButtonMap::iterator b = button_map.find (button.bid());
1268
1269         if (b != button_map.end()) {
1270
1271                 ButtonHandlers& bh (b->second);
1272
1273                 switch  (bs) {
1274                 case press: 
1275                         surface.write (button.set_state ((this->*(bh.press)) (button)));
1276                         break;
1277                 case release: 
1278                         surface.write (button.set_state ((this->*(bh.release)) (button)));
1279                         break;
1280                 default:
1281                         break;
1282                 }
1283         } else {
1284                 DEBUG_TRACE (DEBUG::MackieControl, string_compose ("no button handlers for button ID %1 (device ID %2)\n", 
1285                                                                    button.bid(), button.id()));
1286                 error << string_compose ("no button handlers for button ID %1 (device ID %2)\n", 
1287                                          button.bid(), button.id()) << endmsg;
1288         }
1289 }
1290
1291 bool
1292 MackieControlProtocol::midi_input_handler (IOCondition ioc, MIDI::Port* port)
1293 {
1294         DEBUG_TRACE (DEBUG::MackieControl, string_compose ("something happend on  %1\n", port->name()));
1295
1296         if (ioc & ~IO_IN) {
1297                 return false;
1298         }
1299
1300         if (ioc & IO_IN) {
1301
1302                 /* Devices using regular JACK MIDI ports will need to have
1303                    the x-thread FIFO drained to avoid burning endless CPU.
1304
1305                    Devices using ipMIDI have port->selectable() as the same
1306                    file descriptor that data arrives on, so doing this
1307                    for them will simply throw all incoming data away.
1308                 */
1309
1310                 if (!_device_info.uses_ipmidi()) {
1311                         AsyncMIDIPort* asp = dynamic_cast<AsyncMIDIPort*>(port);
1312                         if (asp) {
1313                                 asp->clear ();
1314                         }
1315                 }
1316
1317                 DEBUG_TRACE (DEBUG::MackieControl, string_compose ("data available on %1\n", port->name()));
1318                 framepos_t now = session->engine().sample_time();
1319                 port->parse (now);
1320         }
1321
1322         return true;
1323 }
1324
1325 void
1326 MackieControlProtocol::clear_ports ()
1327 {
1328         if (_input_bundle) {
1329                 _input_bundle->remove_channels ();
1330                 _output_bundle->remove_channels ();
1331         }
1332 }
1333
1334 void
1335 MackieControlProtocol::set_view_mode (ViewMode m)
1336 {
1337         Glib::Threads::Mutex::Lock lm (surfaces_lock);
1338
1339         _view_mode = m;
1340
1341         for (Surfaces::iterator s = surfaces.begin(); s != surfaces.end(); ++s) {
1342                 (*s)->update_view_mode_display ();
1343         }
1344         
1345 }
1346
1347 void
1348 MackieControlProtocol::set_flip_mode (FlipMode fm)
1349 {
1350         Glib::Threads::Mutex::Lock lm (surfaces_lock);
1351
1352         _flip_mode = fm;
1353         
1354         for (Surfaces::iterator s = surfaces.begin(); s != surfaces.end(); ++s) {
1355                 (*s)->update_flip_mode_display ();
1356         }
1357 }
1358         
1359 void
1360 MackieControlProtocol::set_master_on_surface_strip (uint32_t surface, uint32_t strip_number)
1361 {
1362         force_special_route_to_strip (session->master_out(), surface, strip_number);
1363 }
1364
1365 void
1366 MackieControlProtocol::set_monitor_on_surface_strip (uint32_t surface, uint32_t strip_number)
1367 {
1368         force_special_route_to_strip (session->monitor_out(), surface, strip_number);
1369 }
1370
1371 void
1372 MackieControlProtocol::force_special_route_to_strip (boost::shared_ptr<Route> r, uint32_t surface, uint32_t strip_number)
1373 {
1374         if (!r) {
1375                 return;
1376         }
1377
1378         Glib::Threads::Mutex::Lock lm (surfaces_lock);
1379
1380         for (Surfaces::iterator s = surfaces.begin(); s != surfaces.end(); ++s) {
1381                 if ((*s)->number() == surface) {
1382                         Strip* strip = (*s)->nth_strip (strip_number);
1383                         if (strip) {
1384                                 strip->set_route (session->master_out());
1385                                 strip->lock_controls ();
1386                         }
1387                 }
1388         }
1389 }
1390
1391 void
1392 MackieControlProtocol::gui_track_selection_changed (ARDOUR::RouteNotificationListPtr rl, bool save_list)
1393 {
1394         _gui_track_selection_changed (rl.get(), save_list);
1395 }
1396
1397 void
1398 MackieControlProtocol::_gui_track_selection_changed (ARDOUR::RouteNotificationList* rl, bool save_list)
1399 {
1400         /* We need to keep a list of the most recently selected routes around,
1401            but we are not allowed to keep shared_ptr<Route> unless we want to
1402            handle the complexities of route deletion. So instead, the GUI sends
1403            us a notification using weak_ptr<Route>, which we keep a copy
1404            of. For efficiency's sake, however, we convert the weak_ptr's into
1405            shared_ptr<Route> before passing them to however many surfaces (and
1406            thus strips) that we have.
1407         */
1408
1409         StrongRouteNotificationList srl;
1410
1411         for (ARDOUR::RouteNotificationList::const_iterator i = rl->begin(); i != rl->end(); ++i) {
1412                 boost::shared_ptr<ARDOUR::Route> r = (*i).lock();
1413                 if (r) {
1414                         srl.push_back (r);
1415                 }
1416         }
1417
1418         {
1419                 Glib::Threads::Mutex::Lock lm (surfaces_lock);
1420                 
1421                 for (Surfaces::iterator s = surfaces.begin(); s != surfaces.end(); ++s) {
1422                         (*s)->gui_selection_changed (srl);
1423                 }
1424         }
1425         
1426         if (save_list) {
1427                 _last_selected_routes = *rl;
1428         }
1429 }
1430
1431 framepos_t
1432 MackieControlProtocol::transport_frame() const
1433 {
1434         return session->transport_frame();
1435 }
1436
1437 void
1438 MackieControlProtocol::add_down_select_button (int surface, int strip)
1439 {
1440         _down_select_buttons.insert ((surface<<8)|(strip&0xf));
1441 }
1442
1443 void
1444 MackieControlProtocol::remove_down_select_button (int surface, int strip)
1445 {
1446         DownButtonList::iterator x = find (_down_select_buttons.begin(), _down_select_buttons.end(), (uint32_t) (surface<<8)|(strip&0xf));
1447         DEBUG_TRACE (DEBUG::MackieControl, string_compose ("removing surface %1 strip %2 from down select buttons\n", surface, strip));
1448         if (x != _down_select_buttons.end()) {
1449                 _down_select_buttons.erase (x);
1450         } else {
1451                 DEBUG_TRACE (DEBUG::MackieControl, string_compose ("surface %1 strip %2 not found in down select buttons\n",
1452                                                                    surface, strip));
1453         }
1454 }
1455
1456 void
1457 MackieControlProtocol::select_range ()
1458 {
1459         RouteList routes;
1460
1461         pull_route_range (_down_select_buttons, routes);
1462
1463         DEBUG_TRACE (DEBUG::MackieControl, string_compose ("select range: found %1 routes\n", routes.size()));
1464
1465         if (!routes.empty()) {
1466                 for (RouteList::iterator r = routes.begin(); r != routes.end(); ++r) {
1467
1468                         if (_modifier_state == MODIFIER_CONTROL) {
1469                                 ToggleRouteSelection ((*r)->remote_control_id ());
1470                         } else {
1471                                 if (r == routes.begin()) {
1472                                         SetRouteSelection ((*r)->remote_control_id());
1473                                 } else {
1474                                         AddRouteToSelection ((*r)->remote_control_id());
1475                                 }
1476                         }
1477                 }
1478         }
1479 }
1480
1481 void
1482 MackieControlProtocol::add_down_button (AutomationType a, int surface, int strip)
1483 {
1484         DownButtonMap::iterator m = _down_buttons.find (a);
1485
1486         if (m == _down_buttons.end()) {
1487                 _down_buttons[a] = DownButtonList();
1488         }
1489
1490         _down_buttons[a].insert ((surface<<8)|(strip&0xf));
1491 }
1492
1493 void
1494 MackieControlProtocol::remove_down_button (AutomationType a, int surface, int strip)
1495 {
1496         DownButtonMap::iterator m = _down_buttons.find (a);
1497
1498         DEBUG_TRACE (DEBUG::MackieControl, string_compose ("removing surface %1 strip %2 from down buttons for %3\n", surface, strip, (int) a));
1499
1500         if (m == _down_buttons.end()) {
1501                 return;
1502         }
1503
1504         DownButtonList& l (m->second);
1505         DownButtonList::iterator x = find (l.begin(), l.end(), (surface<<8)|(strip&0xf));
1506
1507         if (x != l.end()) {
1508                 l.erase (x);
1509         } else {
1510                 DEBUG_TRACE (DEBUG::MackieControl, string_compose ("surface %1 strip %2 not found in down buttons for %3\n",
1511                                                                    surface, strip, (int) a));
1512         }
1513 }
1514
1515 MackieControlProtocol::ControlList
1516 MackieControlProtocol::down_controls (AutomationType p)
1517 {
1518         ControlList controls;
1519         RouteList routes;
1520
1521         DownButtonMap::iterator m = _down_buttons.find (p);
1522
1523         if (m == _down_buttons.end()) {
1524                 return controls;
1525         }
1526         
1527         DEBUG_TRACE (DEBUG::MackieControl, string_compose ("looking for down buttons for %1, got %2\n",
1528                                                            p, m->second.size()));
1529
1530         pull_route_range (m->second, routes);
1531         
1532         switch (p) {
1533         case GainAutomation:
1534                 for (RouteList::iterator r = routes.begin(); r != routes.end(); ++r) {
1535                         controls.push_back ((*r)->gain_control());
1536                 }
1537                 break;
1538         case SoloAutomation:
1539                 for (RouteList::iterator r = routes.begin(); r != routes.end(); ++r) {
1540                         controls.push_back ((*r)->solo_control());
1541                 }
1542                 break;
1543         case MuteAutomation:
1544                 for (RouteList::iterator r = routes.begin(); r != routes.end(); ++r) {
1545                         controls.push_back ((*r)->mute_control());
1546                 }
1547                 break;
1548         case RecEnableAutomation:
1549                 for (RouteList::iterator r = routes.begin(); r != routes.end(); ++r) {
1550                         boost::shared_ptr<Track> trk = boost::dynamic_pointer_cast<Track> (*r);
1551                         if (trk) {
1552                                 controls.push_back (trk->rec_enable_control());
1553                         }
1554                 }
1555                 break;
1556         default:
1557                 break;
1558         }
1559
1560         return controls;
1561
1562 }
1563         
1564 struct ButtonRangeSorter {
1565     bool operator() (const uint32_t& a, const uint32_t& b) {
1566             return (a>>8) < (b>>8) // a.surface < b.surface
1567                     ||
1568                     ((a>>8) == (b>>8) && (a&0xf) < (b&0xf)); // a.surface == b.surface && a.strip < b.strip
1569     }
1570 };
1571
1572 void
1573 MackieControlProtocol::pull_route_range (DownButtonList& down, RouteList& selected)
1574 {
1575         ButtonRangeSorter cmp;
1576
1577         if (down.empty()) {
1578                 return;
1579         }
1580
1581         list<uint32_t> ldown;
1582         ldown.insert (ldown.end(), down.begin(), down.end());
1583         ldown.sort (cmp);
1584
1585         uint32_t first = ldown.front();
1586         uint32_t last = ldown.back ();
1587         
1588         uint32_t first_surface = first>>8;
1589         uint32_t first_strip = first&0xf;
1590
1591         uint32_t last_surface = last>>8;
1592         uint32_t last_strip = last&0xf;
1593
1594         DEBUG_TRACE (DEBUG::MackieControl, string_compose ("PRR %5 in list %1.%2 - %3.%4\n", first_surface, first_strip, last_surface, last_strip,
1595                                                            down.size()));
1596         
1597         Glib::Threads::Mutex::Lock lm (surfaces_lock);
1598
1599         for (Surfaces::const_iterator s = surfaces.begin(); s != surfaces.end(); ++s) {
1600                 
1601                 if ((*s)->number() >= first_surface && (*s)->number() <= last_surface) {
1602
1603                         uint32_t fs;
1604                         uint32_t ls;
1605
1606                         if ((*s)->number() == first_surface) {
1607                                 fs = first_strip;
1608                         } else {
1609                                 fs = 0;
1610                         }
1611
1612                         if ((*s)->number() == last_surface) {
1613                                 ls = last_strip;
1614                                 ls += 1;
1615                         } else {
1616                                 ls = (*s)->n_strips ();
1617                         }
1618
1619                         DEBUG_TRACE (DEBUG::MackieControl, string_compose ("adding strips for surface %1 (%2 .. %3)\n",
1620                                                                            (*s)->number(), fs, ls));
1621
1622                         for (uint32_t n = fs; n < ls; ++n) {
1623                                 boost::shared_ptr<Route> r = (*s)->nth_strip (n)->route();
1624                                 if (r) {
1625                                         selected.push_back (r);
1626                                 }
1627                         }
1628                 }
1629         }
1630 }
1631
1632 void
1633 MackieControlProtocol::set_ipmidi_base (int16_t portnum)
1634 {
1635         /* this will not be saved without a session save, so .. */
1636
1637         session->set_dirty ();
1638
1639         _ipmidi_base = portnum;
1640
1641         /* if the current device uses ipMIDI we need
1642            to restart.
1643         */
1644
1645         if (active() && _device_info.uses_ipmidi()) {
1646                 needs_ipmidi_restart = true;
1647         }
1648 }
1649
1650 int
1651 MackieControlProtocol::ipmidi_restart ()
1652 {
1653         clear_surfaces ();
1654         if (create_surfaces ()) {
1655                 return -1;
1656         }
1657         switch_banks (_current_initial_bank, true);
1658         needs_ipmidi_restart = false;
1659         return 0;
1660 }
1661
1662 void
1663 MackieControlProtocol::clear_surfaces ()
1664 {
1665         clear_ports ();
1666         Glib::Threads::Mutex::Lock lm (surfaces_lock);
1667         surfaces.clear ();      
1668 }