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