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