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