MCP: rename ports again, remove ports from MCP bundles, wakeup devices
[ardour.git] / libs / surfaces / mackie / mackie_control_protocol.cc
1 /*
2         Copyright (C) 2006,2007 John Anderson
3
4         This program is free software; you can redistribute it and/or modify
5         it under the terms of the GNU General Public License as published by
6         the Free Software Foundation; either version 2 of the License, or
7         (at your option) any later version.
8
9         This program is distributed in the hope that it will be useful,
10         but WITHOUT ANY WARRANTY; without even the implied warranty of
11         MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12         GNU General Public License for more details.
13
14         You should have received a copy of the GNU General Public License
15         along with this program; if not, write to the Free Software
16         Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
17 */
18
19 #include <fcntl.h>
20 #include <iostream>
21 #include <algorithm>
22 #include <cmath>
23 #include <sstream>
24 #include <vector>
25 #include <iomanip>
26
27 #include <inttypes.h>
28 #include <float.h>
29 #include <sys/time.h>
30 #include <errno.h>
31 #include <poll.h>
32
33 #include <boost/shared_array.hpp>
34
35 #include "midi++/types.h"
36 #include "midi++/port.h"
37 #include "pbd/pthread_utils.h"
38 #include "pbd/error.h"
39 #include "pbd/memento_command.h"
40 #include "pbd/convert.h"
41
42 #include "ardour/dB.h"
43 #include "ardour/debug.h"
44 #include "ardour/location.h"
45 #include "ardour/meter.h"
46 #include "ardour/panner.h"
47 #include "ardour/panner_shell.h"
48 #include "ardour/route.h"
49 #include "ardour/session.h"
50 #include "ardour/tempo.h"
51 #include "ardour/types.h"
52 #include "ardour/audioengine.h"
53
54 #include "mackie_control_protocol.h"
55
56 #include "midi_byte_array.h"
57 #include "mackie_control_exception.h"
58 #include "surface_port.h"
59 #include "surface.h"
60 #include "strip.h"
61 #include "control_group.h"
62 #include "meter.h"
63 #include "button.h"
64 #include "fader.h"
65 #include "pot.h"
66
67 using namespace ARDOUR;
68 using namespace std;
69 using namespace Mackie;
70 using namespace PBD;
71 using namespace Glib;
72
73 #include "i18n.h"
74
75 #include "pbd/abstract_ui.cc" // instantiate template
76
77 #define ui_bind(f, ...) boost::protect (boost::bind (f, __VA_ARGS__))
78
79 const int MackieControlProtocol::MODIFIER_OPTION = 0x1;
80 const int MackieControlProtocol::MODIFIER_CONTROL = 0x2;
81 const int MackieControlProtocol::MODIFIER_SHIFT = 0x3;
82 const int MackieControlProtocol::MODIFIER_CMDALT = 0x4;
83
84 MackieControlProtocol* MackieControlProtocol::_instance = 0;
85
86 bool MackieControlProtocol::probe()
87 {
88         return true;
89 }
90
91 MackieControlProtocol::MackieControlProtocol (Session& session)
92         : ControlProtocol (session, X_("Mackie"), this)
93         , AbstractUI<MackieControlUIRequest> ("mackie")
94         , _current_initial_bank (0)
95         , _timecode_type (ARDOUR::AnyTime::BBT)
96         , _input_bundle (new ARDOUR::Bundle (_("Mackie Control In"), true))
97         , _output_bundle (new ARDOUR::Bundle (_("Mackie Control Out"), false))
98         , _gui (0)
99         , _zoom_mode (false)
100         , _scrub_mode (false)
101         , _flip_mode (Normal)
102         , _view_mode (Global)
103         , _current_selected_track (-1)
104 {
105         DEBUG_TRACE (DEBUG::MackieControl, "MackieControlProtocol::MackieControlProtocol\n");
106
107         DeviceInfo::reload_device_info ();
108
109         AudioEngine::instance()->PortConnectedOrDisconnected.connect (
110                 audio_engine_connections, MISSING_INVALIDATOR, ui_bind (&MackieControlProtocol::port_connected_or_disconnected, this, _2, _4, _5),
111                 this
112                 );
113
114         TrackSelectionChanged.connect (gui_connections, MISSING_INVALIDATOR, ui_bind (&MackieControlProtocol::gui_track_selection_changed, this, _1), this);
115
116         _instance = this;
117
118         build_button_map ();
119 }
120
121 MackieControlProtocol::~MackieControlProtocol()
122 {
123         DEBUG_TRACE (DEBUG::MackieControl, "MackieControlProtocol::~MackieControlProtocol\n");
124
125         _active = false;
126
127         try {
128                 close();
129         }
130         catch (exception & e) {
131                 cout << "~MackieControlProtocol caught " << e.what() << endl;
132         }
133         catch (...) {
134                 cout << "~MackieControlProtocol caught unknown" << endl;
135         }
136
137         DEBUG_TRACE (DEBUG::MackieControl, "finished ~MackieControlProtocol::MackieControlProtocol\n");
138
139         _instance = 0;
140 }
141
142 void
143 MackieControlProtocol::thread_init ()
144 {
145         struct sched_param rtparam;
146
147         pthread_set_name (X_("MackieControl"));
148
149         PBD::notify_gui_about_thread_creation (X_("gui"), pthread_self(), X_("MackieControl"), 2048);
150         ARDOUR::SessionEvent::create_per_thread_pool (X_("MackieControl"), 128);
151
152         memset (&rtparam, 0, sizeof (rtparam));
153         rtparam.sched_priority = 9; /* XXX should be relative to audio (JACK) thread */
154
155         if (pthread_setschedparam (pthread_self(), SCHED_FIFO, &rtparam) != 0) {
156                 // do we care? not particularly.
157         }
158 }
159
160 // go to the previous track.
161 // Assume that get_sorted_routes().size() > route_table.size()
162 void 
163 MackieControlProtocol::prev_track()
164 {
165         if (_current_initial_bank >= 1) {
166                 switch_banks (_current_initial_bank - 1);
167         }
168 }
169
170 // go to the next track.
171 // Assume that get_sorted_routes().size() > route_table.size()
172 void 
173 MackieControlProtocol::next_track()
174 {
175         Sorted sorted = get_sorted_routes();
176         if (_current_initial_bank + n_strips() < sorted.size()) {
177                 switch_banks (_current_initial_bank + 1);
178         }
179 }
180
181 // predicate for sort call in get_sorted_routes
182 struct RouteByRemoteId
183 {
184         bool operator () (const boost::shared_ptr<Route> & a, const boost::shared_ptr<Route> & b) const
185         {
186                 return a->remote_control_id() < b->remote_control_id();
187         }
188
189         bool operator () (const Route & a, const Route & b) const
190         {
191                 return a.remote_control_id() < b.remote_control_id();
192         }
193
194         bool operator () (const Route * a, const Route * b) const
195         {
196                 return a->remote_control_id() < b->remote_control_id();
197         }
198 };
199
200 MackieControlProtocol::Sorted 
201 MackieControlProtocol::get_sorted_routes()
202 {
203         Sorted sorted;
204
205         // fetch all routes
206         boost::shared_ptr<RouteList> routes = session->get_routes();
207         set<uint32_t> remote_ids;
208
209         // routes with remote_id 0 should never be added
210         // TODO verify this with ardour devs
211         // remote_ids.insert (0);
212
213         // sort in remote_id order, and exclude master, control and hidden routes
214         // and any routes that are already set.
215
216         for (RouteList::iterator it = routes->begin(); it != routes->end(); ++it) {
217
218                 Route & route = **it;
219
220                 if (remote_ids.find (route.remote_control_id()) != remote_ids.end()) {
221                         continue;
222                 }
223
224                 if (route.is_hidden() || route.is_master() || route.is_monitor()) {
225                         continue;
226                 }
227
228                 switch (_view_mode) {
229                 case Global:
230                         break;
231                 case AudioTracks:
232                         break;
233                 case Busses:
234                         break;
235                 case MidiTracks:
236                         break;
237                 case Dynamics:
238                         break;
239                 case EQ:
240                         break;
241                 case Loop:
242                         break;
243                 case Sends:
244                         break;
245                 case Plugins:
246                         break;
247                 }
248
249                 sorted.push_back (*it);
250                 remote_ids.insert (route.remote_control_id());
251         }
252
253         sort (sorted.begin(), sorted.end(), RouteByRemoteId());
254         return sorted;
255 }
256
257 void 
258 MackieControlProtocol::refresh_current_bank()
259 {
260         switch_banks (_current_initial_bank, true);
261 }
262
263 uint32_t
264 MackieControlProtocol::n_strips() const
265 {
266         uint32_t strip_count = 0;
267
268         for (Surfaces::const_iterator si = surfaces.begin(); si != surfaces.end(); ++si) {
269                 strip_count += (*si)->n_strips ();
270         }
271
272         return strip_count;
273 }
274
275 void 
276 MackieControlProtocol::switch_banks (uint32_t initial, bool force)
277 {
278         DEBUG_TRACE (DEBUG::MackieControl, string_compose ("switch banking to start at %1 force ? %2 current = %3\n", initial, force, _current_initial_bank));
279
280         if (initial == _current_initial_bank && !force) {
281                 return;
282         }
283
284         Sorted sorted = get_sorted_routes();
285         uint32_t strip_cnt = n_strips();
286
287         if (sorted.size() <= strip_cnt && !force) {
288                 /* no banking - not enough routes to fill all strips */
289                 return;
290         }
291
292         uint32_t delta = sorted.size() - strip_cnt;
293
294         if (delta > 0 && initial > delta) {
295                 DEBUG_TRACE (DEBUG::MackieControl, string_compose ("not switching to %1\n", initial));
296                 return;
297         }
298
299         _current_initial_bank = initial;
300         _current_selected_track = -1;
301
302         for (Surfaces::iterator si = surfaces.begin(); si != surfaces.end(); ++si) {
303                 (*si)->drop_routes ();
304         }
305
306         // Map current bank of routes onto each surface(+strip)
307
308         if (_current_initial_bank <= sorted.size()) {
309
310                 DEBUG_TRACE (DEBUG::MackieControl, string_compose ("switch to %1, %2, available routes %3\n", _current_initial_bank, strip_cnt, sorted.size()));
311
312                 // link routes to strips
313
314                 Sorted::iterator r = sorted.begin() + _current_initial_bank;
315                 
316                 for (Surfaces::iterator si = surfaces.begin(); si != surfaces.end(); ++si) {
317                         vector<boost::shared_ptr<Route> > routes;
318                         uint32_t added = 0;
319
320                         DEBUG_TRACE (DEBUG::MackieControl, string_compose ("surface has %1 strips\n", (*si)->n_strips()));
321
322                         for (; r != sorted.end() && added < (*si)->n_strips(); ++r, ++added) {
323                                 routes.push_back (*r);
324                         }
325
326                         DEBUG_TRACE (DEBUG::MackieControl, string_compose ("give surface %1 routes\n", routes.size()));
327
328                         (*si)->map_routes (routes);
329                 }
330         }
331
332         /* reset this to get the right display of view mode after the switch */
333         set_view_mode (_view_mode);
334         
335         /* current bank has not been saved */
336
337         session->set_dirty();
338 }
339
340 int 
341 MackieControlProtocol::set_active (bool yn)
342 {
343         if (yn == _active) {
344                 return 0;
345         }
346
347         try
348         {
349                 if (yn) {
350
351                         /* start event loop */
352
353                         BaseUI::run ();
354
355                         create_surfaces ();
356                         connect_session_signals ();
357                         _active = true;
358                         update_surfaces ();
359
360                         /* set up periodic task for metering and automation
361                          */
362
363                         Glib::RefPtr<Glib::TimeoutSource> periodic_timeout = Glib::TimeoutSource::create (100); // milliseconds
364                         periodic_connection = periodic_timeout->connect (sigc::mem_fun (*this, &MackieControlProtocol::periodic));
365                         periodic_timeout->attach (main_loop()->get_context());
366
367                 } else {
368                         BaseUI::quit ();
369                         close();
370                         _active = false;
371                 }
372         }
373         
374         catch (exception & e) {
375                 DEBUG_TRACE (DEBUG::MackieControl, string_compose ("set_active to false because exception caught: %1\n", e.what()));
376                 _active = false;
377                 throw;
378         }
379
380         return 0;
381 }
382
383 bool
384 MackieControlProtocol::periodic ()
385 {
386         if (!_active) {
387                 return false;
388         }
389
390         for (Surfaces::iterator s = surfaces.begin(); s != surfaces.end(); ++s) {
391                 (*s)->periodic ();
392         }
393         
394         return true;
395 }
396
397
398 void 
399 MackieControlProtocol::update_timecode_beats_led()
400 {
401         switch (_timecode_type) {
402                 case ARDOUR::AnyTime::BBT:
403                         update_global_led ("beats", on);
404                         update_global_led ("timecode", off);
405                         break;
406                 case ARDOUR::AnyTime::Timecode:
407                         update_global_led ("timecode", on);
408                         update_global_led ("beats", off);
409                         break;
410                 default:
411                         ostringstream os;
412                         os << "Unknown Anytime::Type " << _timecode_type;
413                         throw runtime_error (os.str());
414         }
415 }
416
417 void 
418 MackieControlProtocol::update_global_button (const string & name, LedState ls)
419 {
420         boost::shared_ptr<Surface> surface = surfaces.front();
421
422         if (!surface->type() == mcu) {
423                 return;
424         }
425
426         if (surface->controls_by_name.find (name) != surface->controls_by_name.end()) {
427                 Button * button = dynamic_cast<Button*> (surface->controls_by_name[name]);
428                 surface->write (button->set_state (ls));
429         } else {
430                 DEBUG_TRACE (DEBUG::MackieControl, string_compose ("Button %1 not found\n", name));
431         }
432 }
433
434 void 
435 MackieControlProtocol::update_global_led (const string & name, LedState ls)
436 {
437         boost::shared_ptr<Surface> surface = surfaces.front();
438
439         if (!surface->type() == mcu) {
440                 return;
441         }
442
443         if (surface->controls_by_name.find (name) != surface->controls_by_name.end()) {
444                 Led * led = dynamic_cast<Led*> (surface->controls_by_name[name]);
445                 surface->write (led->set_state (ls));
446         } else {
447                 DEBUG_TRACE (DEBUG::MackieControl, string_compose ("Led %1 not found\n", name));
448         }
449 }
450
451 // send messages to surface to set controls to correct values
452 void 
453 MackieControlProtocol::update_surfaces()
454 {
455         if (!_active) {
456                 return;
457         }
458
459         // do the initial bank switch to connect signals
460         // _current_initial_bank is initialised by set_state
461         switch_banks (_current_initial_bank, true);
462         
463         // sometimes the jog wheel is a pot
464         surfaces.front()->blank_jog_ring ();
465         
466         // update global buttons and displays
467
468         notify_record_state_changed();
469         notify_transport_state_changed();
470         update_timecode_beats_led();
471 }
472
473 void 
474 MackieControlProtocol::connect_session_signals()
475 {
476         // receive routes added
477         session->RouteAdded.connect(session_connections, MISSING_INVALIDATOR, ui_bind (&MackieControlProtocol::notify_route_added, this, _1), this);
478         // receive record state toggled
479         session->RecordStateChanged.connect(session_connections, MISSING_INVALIDATOR, ui_bind (&MackieControlProtocol::notify_record_state_changed, this), this);
480         // receive transport state changed
481         session->TransportStateChange.connect(session_connections, MISSING_INVALIDATOR, ui_bind (&MackieControlProtocol::notify_transport_state_changed, this), this);
482         session->TransportLooped.connect (session_connections, MISSING_INVALIDATOR, ui_bind (&MackieControlProtocol::notify_loop_state_changed, this), this);
483         // receive punch-in and punch-out
484         Config->ParameterChanged.connect(session_connections, MISSING_INVALIDATOR, ui_bind (&MackieControlProtocol::notify_parameter_changed, this, _1), this);
485         session->config.ParameterChanged.connect (session_connections, MISSING_INVALIDATOR, ui_bind (&MackieControlProtocol::notify_parameter_changed, this, _1), this);
486         // receive rude solo changed
487         session->SoloActive.connect(session_connections, MISSING_INVALIDATOR, ui_bind (&MackieControlProtocol::notify_solo_active_changed, this, _1), this);
488
489         // make sure remote id changed signals reach here
490         // see also notify_route_added
491         Sorted sorted = get_sorted_routes();
492
493         for (Sorted::iterator it = sorted.begin(); it != sorted.end(); ++it) {
494                 (*it)->RemoteControlIDChanged.connect (route_connections, MISSING_INVALIDATOR, ui_bind(&MackieControlProtocol::notify_remote_id_changed, this), this);
495         }
496 }
497
498 void
499 MackieControlProtocol::set_device (const string& device_name)
500 {
501         map<string,DeviceInfo>::iterator d = DeviceInfo::device_info.find (device_name);
502
503         if (d == DeviceInfo::device_info.end()) {
504                 return;
505         }
506         
507         _device_info = d->second;
508
509         if (_active) {
510                 clear_ports ();
511                 surfaces.clear ();
512                 create_surfaces ();
513                 switch_banks (0, true);
514         }
515 }
516
517 void 
518 MackieControlProtocol::create_surfaces ()
519 {
520         string device_name;
521         surface_type_t stype = mcu;
522         char buf[128];
523
524         if (_device_info.extenders() == 0) {
525                 device_name = X_("mackie control");
526         } else {
527                 device_name = X_("mackie control #1");
528         }
529
530         DEBUG_TRACE (DEBUG::MackieControl, string_compose ("Create %1 surfaces\n", 1 + _device_info.extenders()));
531
532         for (uint32_t n = 0; n < 1 + _device_info.extenders(); ++n) {
533
534                 boost::shared_ptr<Surface> surface (new Surface (*this, device_name, n, stype));
535                 surfaces.push_back (surface);
536
537                 /* next device will be an extender */
538                 
539                 if (_device_info.extenders() < 2) {
540                         device_name = X_("mackie control #2");
541                 } else {
542                         snprintf (buf, sizeof (buf), X_("mackie control #%d"), n+2);
543                         device_name = buf;
544                 }
545                 stype = ext;
546
547                 _input_bundle->add_channel (
548                         surface->port().input_port().name(),
549                         ARDOUR::DataType::MIDI,
550                         session->engine().make_port_name_non_relative (surface->port().input_port().name())
551                         );
552                 
553                 _output_bundle->add_channel (
554                         surface->port().output_port().name(),
555                         ARDOUR::DataType::MIDI,
556                         session->engine().make_port_name_non_relative (surface->port().output_port().name())
557                         );
558
559                 int fd;
560                 MIDI::Port& input_port (surface->port().input_port());
561                 
562                 if ((fd = input_port.selectable ()) >= 0) {
563                         Glib::RefPtr<IOSource> psrc = IOSource::create (fd, IO_IN|IO_HUP|IO_ERR);
564
565                         psrc->connect (sigc::bind (sigc::mem_fun (this, &MackieControlProtocol::midi_input_handler), &input_port));
566                         psrc->attach (main_loop()->get_context());
567                         
568                         // glibmm hack: for now, store only the GSource*
569
570                         port_sources.push_back (psrc->gobj());
571                         g_source_ref (psrc->gobj());
572                 }
573         }
574 }
575
576 void 
577 MackieControlProtocol::close()
578 {
579         clear_ports ();
580
581         port_connections.drop_connections ();
582         session_connections.drop_connections ();
583         route_connections.drop_connections ();
584         periodic_connection.disconnect ();
585
586         surfaces.clear ();
587 }
588
589 XMLNode& 
590 MackieControlProtocol::get_state()
591 {
592         DEBUG_TRACE (DEBUG::MackieControl, "MackieControlProtocol::get_state\n");
593
594         // add name of protocol
595         XMLNode* node = new XMLNode (X_("Protocol"));
596         node->add_property (X_("name"), ARDOUR::ControlProtocol::_name);
597
598         node->add_property (X_("device"), _device_info.name());
599
600         // add current bank
601         ostringstream os;
602         os << _current_initial_bank;
603         node->add_property (X_("bank"), os.str());
604
605         for (uint32_t n = 0; n < 16; ++n) {
606                 ostringstream s;
607                 s << string_compose ("f%1-action", n+1);
608                 node->add_property (s.str().c_str(), f_action (n));
609         }
610
611         return *node;
612 }
613
614 int 
615 MackieControlProtocol::set_state (const XMLNode & node, int /*version*/)
616 {
617         DEBUG_TRACE (DEBUG::MackieControl, string_compose ("MackieControlProtocol::set_state: active %1\n", _active));
618
619         int retval = 0;
620         const XMLProperty* prop;
621
622         // fetch current bank
623         if ((prop = node.property (X_("bank"))) != 0) {
624                 string bank = prop->value();
625                 set_active (true);
626                 uint32_t new_bank = atoi (bank.c_str());
627                 if (_current_initial_bank != new_bank) {
628                         switch_banks (new_bank);
629                 }
630         }
631
632         _f_actions.clear ();
633         _f_actions.resize (16);
634
635         for (uint32_t n = 0; n < 16; ++n) {
636                 string action;
637                 if ((prop = node.property (string_compose ("f%1-action", n+1))) != 0) {
638                         action = prop->value();
639                 }
640
641                 if (action.empty()) {
642                         /* default action if nothing is specified */
643                         action = string_compose ("Editor/goto-visual-state-%1", n+1);
644                 }
645
646                 _f_actions[n] = action;
647         }
648
649         if ((prop = node.property (X_("device"))) != 0) {
650                 set_device (prop->value ());
651         }
652
653         return retval;
654 }
655
656
657 /////////////////////////////////////////////////
658 // handlers for Route signals
659 // TODO should these be part of RouteSignal?
660 // They started off as signal/slot handlers for signals
661 // from Route, but they're also used in polling for automation
662 /////////////////////////////////////////////////
663
664 // TODO handle plugin automation polling
665 string 
666 MackieControlProtocol::format_bbt_timecode (framepos_t now_frame)
667 {
668         Timecode::BBT_Time bbt_time;
669         session->bbt_time (now_frame, bbt_time);
670
671         // According to the Logic docs
672         // digits: 888/88/88/888
673         // BBT mode: Bars/Beats/Subdivisions/Ticks
674         ostringstream os;
675         os << setw(3) << setfill('0') << bbt_time.bars;
676         os << setw(2) << setfill('0') << bbt_time.beats;
677
678         // figure out subdivisions per beat
679         const ARDOUR::Meter & meter = session->tempo_map().meter_at (now_frame);
680         int subdiv = 2;
681         if (meter.note_divisor() == 8 && (meter.divisions_per_bar() == 12.0 || meter.divisions_per_bar() == 9.0 || meter.divisions_per_bar() == 6.0)) {
682                 subdiv = 3;
683         }
684
685         uint32_t subdivisions = bbt_time.ticks / uint32_t (Timecode::BBT_Time::ticks_per_beat / subdiv);
686         uint32_t ticks = bbt_time.ticks % uint32_t (Timecode::BBT_Time::ticks_per_beat / subdiv);
687
688         os << setw(2) << setfill('0') << subdivisions + 1;
689         os << setw(3) << setfill('0') << ticks;
690
691         return os.str();
692 }
693
694 string 
695 MackieControlProtocol::format_timecode_timecode (framepos_t now_frame)
696 {
697         Timecode::Time timecode;
698         session->timecode_time (now_frame, timecode);
699
700         // According to the Logic docs
701         // digits: 888/88/88/888
702         // Timecode mode: Hours/Minutes/Seconds/Frames
703         ostringstream os;
704         os << setw(3) << setfill('0') << timecode.hours;
705         os << setw(2) << setfill('0') << timecode.minutes;
706         os << setw(2) << setfill('0') << timecode.seconds;
707         os << setw(3) << setfill('0') << timecode.frames;
708
709         return os.str();
710 }
711
712 void 
713 MackieControlProtocol::update_timecode_display()
714 {
715         boost::shared_ptr<Surface> surface = surfaces.front();
716
717         if (surface->type() != mcu || !surface->has_timecode_display()) {
718                 return;
719         }
720
721         // do assignment here so current_frame is fixed
722         framepos_t current_frame = session->transport_frame();
723         string timecode;
724
725         switch (_timecode_type) {
726         case ARDOUR::AnyTime::BBT:
727                 timecode = format_bbt_timecode (current_frame);
728                 break;
729         case ARDOUR::AnyTime::Timecode:
730                 timecode = format_timecode_timecode (current_frame);
731                 break;
732         default:
733                 return;
734         }
735         
736         // only write the timecode string to the MCU if it's changed
737         // since last time. This is to reduce midi bandwidth used.
738         if (timecode != _timecode_last) {
739                 surface->display_timecode (timecode, _timecode_last);
740                 _timecode_last = timecode;
741         }
742 }
743
744 ///////////////////////////////////////////
745 // Session signals
746 ///////////////////////////////////////////
747
748 void MackieControlProtocol::notify_parameter_changed (std::string const & p)
749 {
750         if (p == "punch-in") {
751                 update_global_button ("punch_in", session->config.get_punch_in());
752         } else if (p == "punch-out") {
753                 update_global_button ("punch_out", session->config.get_punch_out());
754         } else if (p == "clicking") {
755                 update_global_button ("clicking", Config->get_clicking());
756         } else {
757                 DEBUG_TRACE (DEBUG::MackieControl, string_compose ("parameter changed: %1\n", p));
758         }
759 }
760
761 // RouteList is the set of routes that have just been added
762 void 
763 MackieControlProtocol::notify_route_added (ARDOUR::RouteList & rl)
764 {
765         // currently assigned banks are less than the full set of
766         // strips, so activate the new strip now.
767
768         refresh_current_bank();
769
770         // otherwise route added, but current bank needs no updating
771
772         // make sure remote id changes in the new route are handled
773         typedef ARDOUR::RouteList ARS;
774
775         for (ARS::iterator it = rl.begin(); it != rl.end(); ++it) {
776                 (*it)->RemoteControlIDChanged.connect (route_connections, MISSING_INVALIDATOR, ui_bind (&MackieControlProtocol::notify_remote_id_changed, this), this);
777         }
778 }
779
780 void 
781 MackieControlProtocol::notify_solo_active_changed (bool active)
782 {
783         boost::shared_ptr<Surface> surface = surfaces.front();
784         
785         Led* rude_solo = dynamic_cast<Led*> (surface->controls_by_name["solo"]);
786
787         if (rude_solo) {
788                 surface->write (rude_solo->set_state (active ? flashing : off));
789         }
790 }
791
792 void 
793 MackieControlProtocol::notify_remote_id_changed()
794 {
795         Sorted sorted = get_sorted_routes();
796         uint32_t sz = n_strips();
797
798         // if a remote id has been moved off the end, we need to shift
799         // the current bank backwards.
800
801         if (sorted.size() - _current_initial_bank < sz) {
802                 // but don't shift backwards past the zeroth channel
803                 switch_banks (max((Sorted::size_type) 0, sorted.size() - sz));
804         } else {
805                 // Otherwise just refresh the current bank
806                 refresh_current_bank();
807         }
808 }
809
810 ///////////////////////////////////////////
811 // Transport signals
812 ///////////////////////////////////////////
813
814 void 
815 MackieControlProtocol::notify_loop_state_changed()
816 {
817         update_global_button ("loop", session->get_play_loop());
818 }
819
820 void 
821 MackieControlProtocol::notify_transport_state_changed()
822 {
823         // switch various play and stop buttons on / off
824         update_global_button ("play", session->transport_speed() == 1.0);
825         update_global_button ("stop", !session->transport_rolling());
826         update_global_button ("rewind", session->transport_speed() < 0.0);
827         update_global_button ("ffwd", session->transport_speed() > 1.0);
828
829         _transport_previously_rolling = session->transport_rolling();
830 }
831
832 void
833 MackieControlProtocol::notify_record_state_changed ()
834 {
835         /* rec is a tristate */
836
837
838         Button * rec = reinterpret_cast<Button*> (surfaces.front()->controls_by_name["record"]);
839         if (rec) {
840                 LedState ls;
841
842                 switch (session->record_status()) {
843                 case Session::Disabled:
844                         DEBUG_TRACE (DEBUG::MackieControl, "record state changed to disabled, LED off\n");
845                         ls = off;
846                         break;
847                 case Session::Recording:
848                         DEBUG_TRACE (DEBUG::MackieControl, "record state changed to recording, LED on\n");
849                         ls = on;
850                         break;
851                 case Session::Enabled:
852                         DEBUG_TRACE (DEBUG::MackieControl, "record state changed to enabled, LED flashing\n");
853                         ls = flashing;
854                         break;
855                 }
856
857                 surfaces.front()->write (rec->set_state (ls));
858         } else {
859                 DEBUG_TRACE (DEBUG::MackieControl, "record button control not found\n");
860         }
861 }
862
863 list<boost::shared_ptr<ARDOUR::Bundle> >
864 MackieControlProtocol::bundles ()
865 {
866         list<boost::shared_ptr<ARDOUR::Bundle> > b;
867         b.push_back (_input_bundle);
868         b.push_back (_output_bundle);
869         return b;
870 }
871
872 void
873 MackieControlProtocol::port_connected_or_disconnected (string a, string b, bool connected)
874 {
875         /* If something is connected to one of our output ports, send MIDI to update the surface
876            to whatever state it should have.
877         */
878
879         if (!connected) {
880                 return;
881         }
882
883         for (Surfaces::iterator s = surfaces.begin(); s != surfaces.end(); ++s) {
884                 string const n = AudioEngine::instance()->make_port_name_non_relative ((*s)->port().output_port().name ());
885                 if (a == n || b == n) {
886                         update_surfaces ();
887                         return;
888                 }
889         }
890 }
891
892 void
893 MackieControlProtocol::do_request (MackieControlUIRequest* req)
894 {
895         if (req->type == CallSlot) {
896
897                 call_slot (MISSING_INVALIDATOR, req->the_slot);
898
899         } else if (req->type == Quit) {
900
901                 stop ();
902         }
903 }
904
905 int
906 MackieControlProtocol::stop ()
907 {
908         BaseUI::quit ();
909
910         return 0;
911 }
912
913 /** Add a timeout so that a control's in_use flag will be reset some time in the future.
914  *  @param in_use_control the control whose in_use flag to reset.
915  *  @param touch_control a touch control to emit an event for, or 0.
916  */
917 void
918 MackieControlProtocol::add_in_use_timeout (Surface& surface, Control& in_use_control, Control* touch_control)
919 {
920         Glib::RefPtr<Glib::TimeoutSource> timeout (Glib::TimeoutSource::create (250)); // milliseconds
921
922         in_use_control.in_use_connection.disconnect ();
923         in_use_control.in_use_connection = timeout->connect (
924                 sigc::bind (sigc::mem_fun (*this, &MackieControlProtocol::control_in_use_timeout), &surface, &in_use_control, touch_control));
925         in_use_control.in_use_touch_control = touch_control;
926         
927         timeout->attach (main_loop()->get_context());
928
929         DEBUG_TRACE (DEBUG::MackieControl, string_compose ("timeout queued for surface %1, control %2 touch control %3\n",
930                                                            surface.number(), &in_use_control, touch_control));}
931
932 /** Handle timeouts to reset in_use for controls that can't
933  *  do this by themselves (e.g. pots, and faders without touch support).
934  *  @param in_use_control the control whose in_use flag to reset.
935  *  @param touch_control a touch control to emit an event for, or 0.
936  */
937 bool
938 MackieControlProtocol::control_in_use_timeout (Surface* surface, Control* in_use_control, Control* touch_control)
939 {
940         DEBUG_TRACE (DEBUG::MackieControl, string_compose ("timeout elapsed for surface %1, control %2 touch control %3\n",
941                                                            surface->number(), in_use_control, touch_control));
942
943         in_use_control->set_in_use (false);
944
945         if (touch_control) {
946                 /* figure out what to do here */
947         }
948         
949         // only call this method once from the timer
950         return false;
951 }
952
953 void 
954 MackieControlProtocol::update_led (Surface& surface, Button& button, Mackie::LedState ls)
955 {
956         if (ls != none) {
957                 surface.port().write (button.set_state (ls));
958         }
959 }
960
961 void
962 MackieControlProtocol::build_button_map ()
963 {
964 #define DEFINE_BUTTON_HANDLER(b,p,r) button_map.insert (pair<int,ButtonHandlers> ((b), ButtonHandlers ((p),(r))));
965
966         DEFINE_BUTTON_HANDLER (Button::Io, &MackieControlProtocol::io_press, &MackieControlProtocol::io_release);
967         DEFINE_BUTTON_HANDLER (Button::Sends, &MackieControlProtocol::sends_press, &MackieControlProtocol::sends_release);
968         DEFINE_BUTTON_HANDLER (Button::Pan, &MackieControlProtocol::pan_press, &MackieControlProtocol::pan_release);
969         DEFINE_BUTTON_HANDLER (Button::Plugin, &MackieControlProtocol::plugin_press, &MackieControlProtocol::plugin_release);
970         DEFINE_BUTTON_HANDLER (Button::Eq, &MackieControlProtocol::eq_press, &MackieControlProtocol::eq_release);
971         DEFINE_BUTTON_HANDLER (Button::Dyn, &MackieControlProtocol::dyn_press, &MackieControlProtocol::dyn_release);
972         DEFINE_BUTTON_HANDLER (Button::Left, &MackieControlProtocol::left_press, &MackieControlProtocol::left_release);
973         DEFINE_BUTTON_HANDLER (Button::Right, &MackieControlProtocol::right_press, &MackieControlProtocol::right_release);
974         DEFINE_BUTTON_HANDLER (Button::ChannelLeft, &MackieControlProtocol::channel_left_press, &MackieControlProtocol::channel_left_release);
975         DEFINE_BUTTON_HANDLER (Button::ChannelRight, &MackieControlProtocol::channel_right_press, &MackieControlProtocol::channel_right_release);
976         DEFINE_BUTTON_HANDLER (Button::Flip, &MackieControlProtocol::flip_press, &MackieControlProtocol::flip_release);
977         DEFINE_BUTTON_HANDLER (Button::Edit, &MackieControlProtocol::edit_press, &MackieControlProtocol::edit_release);
978         DEFINE_BUTTON_HANDLER (Button::NameValue, &MackieControlProtocol::name_value_press, &MackieControlProtocol::name_value_release);
979         DEFINE_BUTTON_HANDLER (Button::TimecodeBeats, &MackieControlProtocol::timecode_beats_press, &MackieControlProtocol::timecode_beats_release);
980         DEFINE_BUTTON_HANDLER (Button::F1, &MackieControlProtocol::F1_press, &MackieControlProtocol::F1_release);
981         DEFINE_BUTTON_HANDLER (Button::F2, &MackieControlProtocol::F2_press, &MackieControlProtocol::F2_release);
982         DEFINE_BUTTON_HANDLER (Button::F3, &MackieControlProtocol::F3_press, &MackieControlProtocol::F3_release);
983         DEFINE_BUTTON_HANDLER (Button::F4, &MackieControlProtocol::F4_press, &MackieControlProtocol::F4_release);
984         DEFINE_BUTTON_HANDLER (Button::F5, &MackieControlProtocol::F5_press, &MackieControlProtocol::F5_release);
985         DEFINE_BUTTON_HANDLER (Button::F6, &MackieControlProtocol::F6_press, &MackieControlProtocol::F6_release);
986         DEFINE_BUTTON_HANDLER (Button::F7, &MackieControlProtocol::F7_press, &MackieControlProtocol::F7_release);
987         DEFINE_BUTTON_HANDLER (Button::F8, &MackieControlProtocol::F8_press, &MackieControlProtocol::F8_release);
988         DEFINE_BUTTON_HANDLER (Button::F9, &MackieControlProtocol::F9_press, &MackieControlProtocol::F9_release);
989         DEFINE_BUTTON_HANDLER (Button::F10, &MackieControlProtocol::F10_press, &MackieControlProtocol::F10_release);
990         DEFINE_BUTTON_HANDLER (Button::F11, &MackieControlProtocol::F11_press, &MackieControlProtocol::F11_release);
991         DEFINE_BUTTON_HANDLER (Button::F12, &MackieControlProtocol::F12_press, &MackieControlProtocol::F12_release);
992         DEFINE_BUTTON_HANDLER (Button::F13, &MackieControlProtocol::F13_press, &MackieControlProtocol::F13_release);
993         DEFINE_BUTTON_HANDLER (Button::F14, &MackieControlProtocol::F14_press, &MackieControlProtocol::F14_release);
994         DEFINE_BUTTON_HANDLER (Button::F15, &MackieControlProtocol::F15_press, &MackieControlProtocol::F15_release);
995         DEFINE_BUTTON_HANDLER (Button::F16, &MackieControlProtocol::F16_press, &MackieControlProtocol::F16_release);
996         DEFINE_BUTTON_HANDLER (Button::Shift, &MackieControlProtocol::shift_press, &MackieControlProtocol::shift_release);
997         DEFINE_BUTTON_HANDLER (Button::Option, &MackieControlProtocol::option_press, &MackieControlProtocol::option_release);
998         DEFINE_BUTTON_HANDLER (Button::Ctrl, &MackieControlProtocol::control_press, &MackieControlProtocol::control_release);
999         DEFINE_BUTTON_HANDLER (Button::CmdAlt, &MackieControlProtocol::cmd_alt_press, &MackieControlProtocol::cmd_alt_release);
1000         DEFINE_BUTTON_HANDLER (Button::On, &MackieControlProtocol::on_press, &MackieControlProtocol::on_release);
1001         DEFINE_BUTTON_HANDLER (Button::RecReady, &MackieControlProtocol::rec_ready_press, &MackieControlProtocol::rec_ready_release);
1002         DEFINE_BUTTON_HANDLER (Button::Undo, &MackieControlProtocol::undo_press, &MackieControlProtocol::undo_release);
1003         DEFINE_BUTTON_HANDLER (Button::Save, &MackieControlProtocol::save_press, &MackieControlProtocol::save_release);
1004         DEFINE_BUTTON_HANDLER (Button::Touch, &MackieControlProtocol::touch_press, &MackieControlProtocol::touch_release);
1005         DEFINE_BUTTON_HANDLER (Button::Redo, &MackieControlProtocol::redo_press, &MackieControlProtocol::redo_release);
1006         DEFINE_BUTTON_HANDLER (Button::Marker, &MackieControlProtocol::marker_press, &MackieControlProtocol::marker_release);
1007         DEFINE_BUTTON_HANDLER (Button::Enter, &MackieControlProtocol::enter_press, &MackieControlProtocol::enter_release);
1008         DEFINE_BUTTON_HANDLER (Button::Cancel, &MackieControlProtocol::cancel_press, &MackieControlProtocol::cancel_release);
1009         DEFINE_BUTTON_HANDLER (Button::Mixer, &MackieControlProtocol::mixer_press, &MackieControlProtocol::mixer_release);
1010         DEFINE_BUTTON_HANDLER (Button::FrmLeft, &MackieControlProtocol::frm_left_press, &MackieControlProtocol::frm_left_release);
1011         DEFINE_BUTTON_HANDLER (Button::FrmRight, &MackieControlProtocol::frm_right_press, &MackieControlProtocol::frm_right_release);
1012         DEFINE_BUTTON_HANDLER (Button::Loop, &MackieControlProtocol::loop_press, &MackieControlProtocol::loop_release);
1013         DEFINE_BUTTON_HANDLER (Button::PunchIn, &MackieControlProtocol::punch_in_press, &MackieControlProtocol::punch_in_release);
1014         DEFINE_BUTTON_HANDLER (Button::PunchOut, &MackieControlProtocol::punch_out_press, &MackieControlProtocol::punch_out_release);
1015         DEFINE_BUTTON_HANDLER (Button::Home, &MackieControlProtocol::home_press, &MackieControlProtocol::home_release);
1016         DEFINE_BUTTON_HANDLER (Button::End, &MackieControlProtocol::end_press, &MackieControlProtocol::end_release);
1017         DEFINE_BUTTON_HANDLER (Button::Rewind, &MackieControlProtocol::rewind_press, &MackieControlProtocol::rewind_release);
1018         DEFINE_BUTTON_HANDLER (Button::Ffwd, &MackieControlProtocol::ffwd_press, &MackieControlProtocol::ffwd_release);
1019         DEFINE_BUTTON_HANDLER (Button::Stop, &MackieControlProtocol::stop_press, &MackieControlProtocol::stop_release);
1020         DEFINE_BUTTON_HANDLER (Button::Play, &MackieControlProtocol::play_press, &MackieControlProtocol::play_release);
1021         DEFINE_BUTTON_HANDLER (Button::Record, &MackieControlProtocol::record_press, &MackieControlProtocol::record_release);
1022         DEFINE_BUTTON_HANDLER (Button::CursorUp, &MackieControlProtocol::cursor_up_press, &MackieControlProtocol::cursor_up_release);
1023         DEFINE_BUTTON_HANDLER (Button::CursorDown, &MackieControlProtocol::cursor_down_press, &MackieControlProtocol::cursor_down_release);
1024         DEFINE_BUTTON_HANDLER (Button::CursorLeft, &MackieControlProtocol::cursor_left_press, &MackieControlProtocol::cursor_left_release);
1025         DEFINE_BUTTON_HANDLER (Button::CursorRight, &MackieControlProtocol::cursor_right_press, &MackieControlProtocol::cursor_right_release);
1026         DEFINE_BUTTON_HANDLER (Button::Zoom, &MackieControlProtocol::zoom_press, &MackieControlProtocol::zoom_release);
1027         DEFINE_BUTTON_HANDLER (Button::Scrub, &MackieControlProtocol::scrub_press, &MackieControlProtocol::scrub_release);
1028         DEFINE_BUTTON_HANDLER (Button::UserA, &MackieControlProtocol::user_a_press, &MackieControlProtocol::user_a_release);
1029         DEFINE_BUTTON_HANDLER (Button::UserB, &MackieControlProtocol::user_b_press, &MackieControlProtocol::user_b_release);
1030 }
1031
1032 void 
1033 MackieControlProtocol::handle_button_event (Surface& surface, Button& button, ButtonState bs)
1034 {
1035         if  (bs != press && bs != release) {
1036                 update_led (surface, button, none);
1037                 return;
1038         }
1039         
1040         DEBUG_TRACE (DEBUG::MackieControl, string_compose ("Handling %1 for button %2\n", (bs == press ? "press" : "release"), button.id()));
1041
1042         ButtonMap::iterator b = button_map.find (button.id());
1043
1044         if (b != button_map.end()) {
1045
1046                 ButtonHandlers& bh (b->second);
1047
1048                 switch  (bs) {
1049                 case press: 
1050                         surface.write (button.set_state ((this->*(bh.press)) (button)));
1051                 case release: 
1052                         surface.write (button.set_state ((this->*(bh.release)) (button)));
1053                         break;
1054                 default:
1055                         break;
1056                 }
1057         } else {
1058                 DEBUG_TRACE (DEBUG::MackieControl, string_compose ("no button handlers for ID %1\n", button.id()));
1059         }
1060 }
1061
1062 void
1063 MackieControlProtocol::select_track (boost::shared_ptr<Route> r)
1064 {
1065         if (_modifier_state == MODIFIER_SHIFT) {
1066                 r->gain_control()->set_value (0.0);
1067         } else {
1068                 if (_current_selected_track > 0 && r->remote_control_id() == (uint32_t) _current_selected_track) {
1069                         UnselectTrack (); /* EMIT SIGNAL */
1070                         _current_selected_track = -1;
1071                 } else {
1072                         SelectByRID (r->remote_control_id()); /* EMIT SIGNAL */
1073                         _current_selected_track = r->remote_control_id();;
1074                 }
1075         }
1076 }
1077
1078 bool
1079 MackieControlProtocol::midi_input_handler (IOCondition ioc, MIDI::Port* port)
1080 {
1081         DEBUG_TRACE (DEBUG::MidiIO, string_compose ("something happend on  %1\n", port->name()));
1082
1083         if (ioc & ~IO_IN) {
1084                 return false;
1085         }
1086
1087         if (ioc & IO_IN) {
1088
1089                 CrossThreadChannel::drain (port->selectable());
1090
1091                 DEBUG_TRACE (DEBUG::MidiIO, string_compose ("data available on %1\n", port->name()));
1092                 framepos_t now = session->engine().frame_time();
1093                 port->parse (now);
1094         }
1095
1096         return true;
1097 }
1098
1099 void
1100 MackieControlProtocol::clear_ports ()
1101 {
1102         _input_bundle->remove_channels ();
1103         _output_bundle->remove_channels ();
1104
1105         for (PortSources::iterator i = port_sources.begin(); i != port_sources.end(); ++i) {
1106                 g_source_destroy (*i);
1107                 g_source_unref (*i);
1108         }
1109
1110         port_sources.clear ();
1111 }
1112
1113 string
1114 MackieControlProtocol::f_action (uint32_t fn)
1115 {
1116         if (fn >= _f_actions.size()) {
1117                 return string();
1118         }
1119
1120         return _f_actions[fn];
1121 }
1122
1123 void
1124 MackieControlProtocol::f_press (uint32_t fn)
1125 {
1126         string action = f_action (0);
1127         if (!action.empty()) {
1128                 access_action (action);
1129         }
1130 }
1131
1132 void
1133 MackieControlProtocol::set_view_mode (ViewMode m)
1134 {
1135         _view_mode = m;
1136
1137         for (Surfaces::iterator s = surfaces.begin(); s != surfaces.end(); ++s) {
1138                 (*s)->update_view_mode_display ();
1139         }
1140         
1141 }
1142
1143 void
1144 MackieControlProtocol::set_flip_mode (FlipMode m)
1145 {
1146         _flip_mode = m;
1147         
1148         for (Surfaces::iterator s = surfaces.begin(); s != surfaces.end(); ++s) {
1149                 (*s)->update_flip_mode_display ();
1150         }
1151 }
1152         
1153 void
1154 MackieControlProtocol::set_master_on_surface_strip (uint32_t surface, uint32_t strip_number)
1155 {
1156         force_special_route_to_strip (session->master_out(), surface, strip_number);
1157 }
1158
1159 void
1160 MackieControlProtocol::set_monitor_on_surface_strip (uint32_t surface, uint32_t strip_number)
1161 {
1162         force_special_route_to_strip (session->monitor_out(), surface, strip_number);
1163 }
1164
1165 void
1166 MackieControlProtocol::force_special_route_to_strip (boost::shared_ptr<Route> r, uint32_t surface, uint32_t strip_number)
1167 {
1168         if (!r) {
1169                 return;
1170         }
1171
1172         for (Surfaces::iterator s = surfaces.begin(); s != surfaces.end(); ++s) {
1173                 if ((*s)->number() == surface) {
1174                         Strip* strip = (*s)->nth_strip (strip_number);
1175                         if (strip) {
1176                                 strip->set_route (session->master_out());
1177                                 strip->lock_route ();
1178                         }
1179                 }
1180         }
1181 }
1182
1183 void
1184 MackieControlProtocol::gui_track_selection_changed (ARDOUR::RouteNotificationListPtr rl)
1185 {
1186         for (Surfaces::iterator s = surfaces.begin(); s != surfaces.end(); ++s) {
1187                 (*s)->gui_selection_changed (rl);
1188         }
1189 }