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