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