Only flip if not already in desired state. Fixes fader jerk on banking.
[ardour.git] / libs / surfaces / mackie / mackie_control_protocol.cc
1 /*
2         Copyright (C) 2006,2007 John Anderson
3         Copyright (C) 2012 Paul Davis
4
5         This program is free software; you can redistribute it and/or modify
6         it under the terms of the GNU General Public License as published by
7         the Free Software Foundation; either version 2 of the License, or
8         (at your option) any later version.
9
10         This program is distributed in the hope that it will be useful,
11         but WITHOUT ANY WARRANTY; without even the implied warranty of
12         MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13         GNU General Public License for more details.
14
15         You should have received a copy of the GNU General Public License
16         along with this program; if not, write to the Free Software
17         Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
18 */
19
20 #include <fcntl.h>
21 #include <iostream>
22 #include <algorithm>
23 #include <cmath>
24 #include <sstream>
25 #include <vector>
26 #include <iomanip>
27
28 #include <inttypes.h>
29 #include <float.h>
30 #include <sys/time.h>
31 #include <errno.h>
32
33 #include <boost/shared_array.hpp>
34
35 #include "midi++/types.h"
36 #include "midi++/port.h"
37 #include "midi++/ipmidi_port.h"
38 #include "pbd/pthread_utils.h"
39 #include "pbd/error.h"
40 #include "pbd/memento_command.h"
41 #include "pbd/convert.h"
42
43 #include "ardour/automation_control.h"
44 #include "ardour/async_midi_port.h"
45 #include "ardour/dB.h"
46 #include "ardour/debug.h"
47 #include "ardour/location.h"
48 #include "ardour/meter.h"
49 #include "ardour/panner.h"
50 #include "ardour/panner_shell.h"
51 #include "ardour/route.h"
52 #include "ardour/session.h"
53 #include "ardour/tempo.h"
54 #include "ardour/track.h"
55 #include "ardour/types.h"
56 #include "ardour/audioengine.h"
57
58 #include "mackie_control_protocol.h"
59
60 #include "midi_byte_array.h"
61 #include "mackie_control_exception.h"
62 #include "device_profile.h"
63 #include "surface_port.h"
64 #include "surface.h"
65 #include "strip.h"
66 #include "control_group.h"
67 #include "meter.h"
68 #include "button.h"
69 #include "fader.h"
70 #include "pot.h"
71
72 using namespace ARDOUR;
73 using namespace std;
74 using namespace PBD;
75 using namespace Glib;
76 using namespace ArdourSurface;
77 using namespace Mackie;
78
79 #include "i18n.h"
80
81 #include "pbd/abstract_ui.cc" // instantiate template
82
83 const int MackieControlProtocol::MODIFIER_OPTION = 0x1;
84 const int MackieControlProtocol::MODIFIER_CONTROL = 0x2;
85 const int MackieControlProtocol::MODIFIER_SHIFT = 0x4;
86 const int MackieControlProtocol::MODIFIER_CMDALT = 0x8;
87 const int MackieControlProtocol::MODIFIER_ZOOM = 0x10;
88 const int MackieControlProtocol::MODIFIER_SCRUB = 0x20;
89 const int MackieControlProtocol::MAIN_MODIFIER_MASK = (MackieControlProtocol::MODIFIER_OPTION|
90                                                        MackieControlProtocol::MODIFIER_CONTROL|
91                                                        MackieControlProtocol::MODIFIER_SHIFT|
92                                                        MackieControlProtocol::MODIFIER_CMDALT);
93
94 MackieControlProtocol* MackieControlProtocol::_instance = 0;
95
96 bool MackieControlProtocol::probe()
97 {
98         return true;
99 }
100
101 MackieControlProtocol::MackieControlProtocol (Session& session)
102         : ControlProtocol (session, X_("Mackie"))
103         , AbstractUI<MackieControlUIRequest> ("mackie")
104         , _current_initial_bank (0)
105         , _timecode_type (ARDOUR::AnyTime::BBT)
106         , _gui (0)
107         , _scrub_mode (false)
108         , _flip_mode (Normal)
109         , _view_mode (Mixer)
110         , _pot_mode (Pan)
111         , _current_selected_track (-1)
112         , _modifier_state (0)
113         , _ipmidi_base (MIDI::IPMIDIPort::lowest_ipmidi_port_default)
114         , needs_ipmidi_restart (false)
115         , _metering_active (true)
116         , _initialized (false)
117         , _surfaces_state (0)
118         , _surfaces_version (0)
119         , _session_load (true)
120 {
121         DEBUG_TRACE (DEBUG::MackieControl, "MackieControlProtocol::MackieControlProtocol\n");
122
123         DeviceInfo::reload_device_info ();
124         DeviceProfile::reload_device_profiles ();
125
126         TrackSelectionChanged.connect (gui_connections, MISSING_INVALIDATOR, boost::bind (&MackieControlProtocol::gui_track_selection_changed, this, _1, true), this);
127
128         _instance = this;
129
130         build_button_map ();
131 }
132
133 MackieControlProtocol::~MackieControlProtocol()
134 {
135         DEBUG_TRACE (DEBUG::MackieControl, "MackieControlProtocol::~MackieControlProtocol init\n");
136
137         for (Surfaces::const_iterator si = surfaces.begin(); si != surfaces.end(); ++si) {
138                 (*si)->reset ();
139         }
140
141         DEBUG_TRACE (DEBUG::MackieControl, "MackieControlProtocol::~MackieControlProtocol drop_connections ()\n");
142         drop_connections ();
143
144         DEBUG_TRACE (DEBUG::MackieControl, "MackieControlProtocol::~MackieControlProtocol tear_down_gui ()\n");
145         tear_down_gui ();
146
147         delete _surfaces_state;
148
149         /* stop event loop */
150         DEBUG_TRACE (DEBUG::MackieControl, "MackieControlProtocol::~MackieControlProtocol BaseUI::quit ()\n");
151         BaseUI::quit ();
152
153         try {
154                 DEBUG_TRACE (DEBUG::MackieControl, "MackieControlProtocol::~MackieControlProtocol close()\n");
155                 close();
156         }
157         catch (exception & e) {
158                 cout << "~MackieControlProtocol caught " << e.what() << endl;
159         }
160         catch (...) {
161                 cout << "~MackieControlProtocol caught unknown" << endl;
162         }
163
164         _instance = 0;
165
166         DEBUG_TRACE (DEBUG::MackieControl, "MackieControlProtocol::~MackieControlProtocol done\n");
167 }
168
169 void
170 MackieControlProtocol::thread_init ()
171 {
172         struct sched_param rtparam;
173
174         pthread_set_name (X_("MackieControl"));
175
176         PBD::notify_gui_about_thread_creation (X_("gui"), pthread_self(), X_("MackieControl"), 2048);
177         ARDOUR::SessionEvent::create_per_thread_pool (X_("MackieControl"), 128);
178
179         memset (&rtparam, 0, sizeof (rtparam));
180         rtparam.sched_priority = 9; /* XXX should be relative to audio (JACK) thread */
181
182         if (pthread_setschedparam (pthread_self(), SCHED_FIFO, &rtparam) != 0) {
183                 // do we care? not particularly.
184         }
185 }
186
187 void
188 MackieControlProtocol::ping_devices ()
189 {
190         /* should not be called if surfaces are not connected, but will not
191          * malfunction if it is.
192          */
193
194         for (Surfaces::const_iterator si = surfaces.begin(); si != surfaces.end(); ++si) {
195                 (*si)->connected ();
196         }
197 }
198
199 // go to the previous track.
200 // Assume that get_sorted_routes().size() > route_table.size()
201 void
202 MackieControlProtocol::prev_track()
203 {
204         if (_current_initial_bank >= 1) {
205                 switch_banks (_current_initial_bank - 1);
206         }
207 }
208
209 // go to the next track.
210 // Assume that get_sorted_routes().size() > route_table.size()
211 void
212 MackieControlProtocol::next_track()
213 {
214         Sorted sorted = get_sorted_routes();
215         if (_current_initial_bank + n_strips() < sorted.size()) {
216                 switch_banks (_current_initial_bank + 1);
217         }
218 }
219
220 bool
221 MackieControlProtocol::route_is_locked_to_strip (boost::shared_ptr<Route> r) const
222 {
223         for (Surfaces::const_iterator si = surfaces.begin(); si != surfaces.end(); ++si) {
224                 if ((*si)->route_is_locked_to_strip (r)) {
225                         return true;
226                 }
227         }
228         return false;
229 }
230
231 // predicate for sort call in get_sorted_routes
232 struct RouteByRemoteId
233 {
234         bool operator () (const boost::shared_ptr<Route> & a, const boost::shared_ptr<Route> & b) const
235         {
236                 return a->remote_control_id() < b->remote_control_id();
237         }
238
239         bool operator () (const Route & a, const Route & b) const
240         {
241                 return a.remote_control_id() < b.remote_control_id();
242         }
243
244         bool operator () (const Route * a, const Route * b) const
245         {
246                 return a->remote_control_id() < b->remote_control_id();
247         }
248 };
249
250 MackieControlProtocol::Sorted
251 MackieControlProtocol::get_sorted_routes()
252 {
253         Sorted sorted;
254
255         // fetch all routes
256         boost::shared_ptr<RouteList> routes = session->get_routes();
257         set<uint32_t> remote_ids;
258
259         // routes with remote_id 0 should never be added
260         // TODO verify this with ardour devs
261         // remote_ids.insert (0);
262
263         // sort in remote_id order, and exclude master, control and hidden routes
264         // and any routes that are already set.
265
266         for (RouteList::iterator it = routes->begin(); it != routes->end(); ++it) {
267
268                 boost::shared_ptr<Route> route = *it;
269
270                 if (remote_ids.find (route->remote_control_id()) != remote_ids.end()) {
271                         continue;
272                 }
273
274                 if (route->is_auditioner() || route->is_master() || route->is_monitor()) {
275                         continue;
276                 }
277
278                 /* don't include locked routes */
279
280                 if (route_is_locked_to_strip(route)) {
281                         continue;
282                 }
283                 /* This next section which is not used yet, looks wrong to me
284                         The first four belong here but the bottom five are not a selection
285                         of routes and belong elsewhere as they are v-pot modes.
286                 */
287                 switch (_view_mode) {
288                 case Mixer:
289                         break;
290                 case AudioTracks:
291                         break;
292                 case Busses:
293                         break;
294                 case MidiTracks:
295                         break;
296                 case Loop:
297                         break;
298                 }
299
300                 sorted.push_back (*it);
301                 remote_ids.insert (route->remote_control_id());
302         }
303
304         sort (sorted.begin(), sorted.end(), RouteByRemoteId());
305         return sorted;
306 }
307
308 void
309 MackieControlProtocol::refresh_current_bank()
310 {
311         switch_banks (_current_initial_bank, true);
312 }
313
314 uint32_t
315 MackieControlProtocol::n_strips (bool with_locked_strips) const
316 {
317         uint32_t strip_count = 0;
318
319         for (Surfaces::const_iterator si = surfaces.begin(); si != surfaces.end(); ++si) {
320                 strip_count += (*si)->n_strips (with_locked_strips);
321         }
322
323         return strip_count;
324 }
325
326 void
327 MackieControlProtocol::switch_banks (uint32_t initial, bool force)
328 {
329         DEBUG_TRACE (DEBUG::MackieControl, string_compose ("switch banking to start at %1 force ? %2 current = %3\n", initial, force, _current_initial_bank));
330
331         if (initial == _current_initial_bank && !force) {
332                 return;
333         }
334
335         Sorted sorted = get_sorted_routes();
336         uint32_t strip_cnt = n_strips (false); // do not include locked strips
337                                                // in this count
338
339         if (sorted.size() <= strip_cnt && _current_initial_bank == 0 && !force) {
340                 /* no banking - not enough routes to fill all strips and we're
341                  * not at the first one.
342                  */
343                 return;
344         }
345         set_flip_mode (Normal);
346         _current_initial_bank = initial;
347         _current_selected_track = -1;
348
349         // Map current bank of routes onto each surface(+strip)
350
351         if (_current_initial_bank <= sorted.size()) {
352
353                 DEBUG_TRACE (DEBUG::MackieControl, string_compose ("switch to %1, %2, available routes %3 on %4 surfaces\n",
354                                                                    _current_initial_bank, strip_cnt, sorted.size(),
355                                                                    surfaces.size()));
356
357                 // link routes to strips
358
359                 Sorted::iterator r = sorted.begin() + _current_initial_bank;
360
361                 for (Surfaces::iterator si = surfaces.begin(); si != surfaces.end(); ++si) {
362                         vector<boost::shared_ptr<Route> > routes;
363                         uint32_t added = 0;
364
365                         DEBUG_TRACE (DEBUG::MackieControl, string_compose ("surface has %1 unlockedstrips\n", (*si)->n_strips (false)));
366
367                         for (; r != sorted.end() && added < (*si)->n_strips (false); ++r, ++added) {
368                                 routes.push_back (*r);
369                         }
370
371                         DEBUG_TRACE (DEBUG::MackieControl, string_compose ("give surface %1 routes\n", routes.size()));
372
373                         (*si)->map_routes (routes);
374                 }
375         }
376
377         /* reset this to get the right display of view mode after the switch */
378         set_view_mode (_view_mode);
379
380         /* make sure selection is correct */
381
382         _gui_track_selection_changed (&_last_selected_routes, false);
383
384         /* current bank has not been saved */
385         session->set_dirty();
386 }
387
388 int
389 MackieControlProtocol::set_active (bool yn)
390 {
391         DEBUG_TRACE (DEBUG::MackieControl, string_compose("MackieControlProtocol::set_active init with yn: '%1'\n", yn));
392
393         if (yn == active()) {
394                 return 0;
395         }
396
397         if (yn) {
398
399                 /* start event loop */
400
401                 BaseUI::run ();
402
403                 connect_session_signals ();
404
405                 if (!_device_info.name().empty()) {
406                         set_device (_device_info.name(), true);
407                 }
408
409                 /* set up periodic task for metering and automation
410                  */
411
412                 Glib::RefPtr<Glib::TimeoutSource> periodic_timeout = Glib::TimeoutSource::create (100); // milliseconds
413                 periodic_connection = periodic_timeout->connect (sigc::mem_fun (*this, &MackieControlProtocol::periodic));
414                 periodic_timeout->attach (main_loop()->get_context());
415
416                 /* a faster periodic task used to display parameter updates */
417
418                 Glib::RefPtr<Glib::TimeoutSource> redisplay_timeout = Glib::TimeoutSource::create (10); // milliseconds
419                 redisplay_connection = redisplay_timeout->connect (sigc::mem_fun (*this, &MackieControlProtocol::redisplay));
420                 redisplay_timeout->attach (main_loop()->get_context());
421
422         } else {
423
424                 BaseUI::quit ();
425                 close ();
426
427         }
428
429         ControlProtocol::set_active (yn);
430
431         DEBUG_TRACE (DEBUG::MackieControl, string_compose("MackieControlProtocol::set_active done with yn: '%1'\n", yn));
432
433         return 0;
434 }
435
436 bool
437 MackieControlProtocol::hui_heartbeat ()
438 {
439         Glib::Threads::Mutex::Lock lm (surfaces_lock);
440
441         for (Surfaces::iterator s = surfaces.begin(); s != surfaces.end(); ++s) {
442                 (*s)->hui_heartbeat ();
443         }
444
445         return true;
446 }
447
448 bool
449 MackieControlProtocol::periodic ()
450 {
451         if (!active()) {
452                 return false;
453         }
454
455         if (needs_ipmidi_restart) {
456                 ipmidi_restart ();
457                 return true;
458         }
459
460         if (!_initialized) {
461                 initialize();
462         }
463
464         ARDOUR::microseconds_t now_usecs = ARDOUR::get_microseconds ();
465
466         {
467                 Glib::Threads::Mutex::Lock lm (surfaces_lock);
468
469                 for (Surfaces::iterator s = surfaces.begin(); s != surfaces.end(); ++s) {
470                         (*s)->periodic (now_usecs);
471                 }
472         }
473
474         update_timecode_display ();
475
476         return true;
477 }
478
479 bool
480 MackieControlProtocol::redisplay ()
481 {
482         if (!active()) {
483                 return false;
484         }
485
486         if (needs_ipmidi_restart) {
487                 ipmidi_restart ();
488                 return true;
489         }
490
491         if (!_initialized) {
492                 initialize();
493         }
494
495         ARDOUR::microseconds_t now = ARDOUR::get_microseconds ();
496
497         {
498                 Glib::Threads::Mutex::Lock lm (surfaces_lock);
499
500                 for (Surfaces::iterator s = surfaces.begin(); s != surfaces.end(); ++s) {
501                         (*s)->redisplay (now);
502                 }
503         }
504
505         return true;
506 }
507
508 void
509 MackieControlProtocol::update_timecode_beats_led()
510 {
511         if (!_device_info.has_timecode_display()) {
512                 return;
513         }
514
515         DEBUG_TRACE (DEBUG::MackieControl, string_compose("MackieControlProtocol::update_timecode_beats_led(): %1\n", _timecode_type));
516         switch (_timecode_type) {
517                 case ARDOUR::AnyTime::BBT:
518                         update_global_led (Led::Beats, on);
519                         update_global_led (Led::Timecode, off);
520                         break;
521                 case ARDOUR::AnyTime::Timecode:
522                         update_global_led (Led::Timecode, on);
523                         update_global_led (Led::Beats, off);
524                         break;
525                 default:
526                         ostringstream os;
527                         os << "Unknown Anytime::Type " << _timecode_type;
528                         throw runtime_error (os.str());
529         }
530 }
531
532 void
533 MackieControlProtocol::update_global_button (int id, LedState ls)
534 {
535         Glib::Threads::Mutex::Lock lm (surfaces_lock);
536
537         if (surfaces.empty()) {
538                 return;
539         }
540
541         if (!_device_info.has_global_controls()) {
542                 return;
543         }
544         // surface needs to be master surface
545         boost::shared_ptr<Surface> surface = _master_surface;
546
547         map<int,Control*>::iterator x = surface->controls_by_device_independent_id.find (id);
548         if (x != surface->controls_by_device_independent_id.end()) {
549                 Button * button = dynamic_cast<Button*> (x->second);
550                 surface->write (button->set_state (ls));
551         } else {
552                 DEBUG_TRACE (DEBUG::MackieControl, string_compose ("Button %1 not found\n", id));
553         }
554 }
555
556 void
557 MackieControlProtocol::update_global_led (int id, LedState ls)
558 {
559         Glib::Threads::Mutex::Lock lm (surfaces_lock);
560
561         if (surfaces.empty()) {
562                 return;
563         }
564
565         if (!_device_info.has_global_controls()) {
566                 return;
567         }
568         boost::shared_ptr<Surface> surface = _master_surface;
569
570         map<int,Control*>::iterator x = surface->controls_by_device_independent_id.find (id);
571
572         if (x != surface->controls_by_device_independent_id.end()) {
573                 Led * led = dynamic_cast<Led*> (x->second);
574                 DEBUG_TRACE (DEBUG::MackieControl, "Writing LedState\n");
575                 surface->write (led->set_state (ls));
576         } else {
577                 DEBUG_TRACE (DEBUG::MackieControl, string_compose ("Led %1 not found\n", id));
578         }
579 }
580
581 void
582 MackieControlProtocol::device_ready ()
583 {
584         /* this is not required to be called, but for devices which do
585          * handshaking, it can be called once the device has verified the
586          * connection.
587          */
588
589         DEBUG_TRACE (DEBUG::MackieControl, string_compose ("device ready init (active=%1)\n", active()));
590         update_surfaces ();
591 }
592
593 // send messages to surface to set controls to correct values
594 void
595 MackieControlProtocol::update_surfaces()
596 {
597         DEBUG_TRACE (DEBUG::MackieControl, string_compose ("MackieControlProtocol::update_surfaces() init (active=%1)\n", active()));
598         if (!active()) {
599                 return;
600         }
601
602         // do the initial bank switch to connect signals
603         // _current_initial_bank is initialised by set_state
604         switch_banks (_current_initial_bank, true);
605
606         DEBUG_TRACE (DEBUG::MackieControl, "MackieControlProtocol::update_surfaces() finished\n");
607 }
608
609 void
610 MackieControlProtocol::initialize()
611 {
612         {
613                 Glib::Threads::Mutex::Lock lm (surfaces_lock);
614
615                 if (surfaces.empty()) {
616                         return;
617                 }
618
619                 if (!_master_surface->active ()) {
620                         return;
621                 }
622
623                 // sometimes the jog wheel is a pot
624                 if (_device_info.has_jog_wheel()) {
625                         _master_surface->blank_jog_ring ();
626                 }
627         }
628
629         // update global buttons and displays
630
631         notify_record_state_changed();
632         notify_transport_state_changed();
633         update_timecode_beats_led();
634
635         _initialized = true;
636 }
637
638 void
639 MackieControlProtocol::connect_session_signals()
640 {
641         // receive routes added
642         session->RouteAdded.connect(session_connections, MISSING_INVALIDATOR, boost::bind (&MackieControlProtocol::notify_route_added, this, _1), this);
643         // receive record state toggled
644         session->RecordStateChanged.connect(session_connections, MISSING_INVALIDATOR, boost::bind (&MackieControlProtocol::notify_record_state_changed, this), this);
645         // receive transport state changed
646         session->TransportStateChange.connect(session_connections, MISSING_INVALIDATOR, boost::bind (&MackieControlProtocol::notify_transport_state_changed, this), this);
647         session->TransportLooped.connect (session_connections, MISSING_INVALIDATOR, boost::bind (&MackieControlProtocol::notify_loop_state_changed, this), this);
648         // receive punch-in and punch-out
649         Config->ParameterChanged.connect(session_connections, MISSING_INVALIDATOR, boost::bind (&MackieControlProtocol::notify_parameter_changed, this, _1), this);
650         session->config.ParameterChanged.connect (session_connections, MISSING_INVALIDATOR, boost::bind (&MackieControlProtocol::notify_parameter_changed, this, _1), this);
651         // receive rude solo changed
652         session->SoloActive.connect(session_connections, MISSING_INVALIDATOR, boost::bind (&MackieControlProtocol::notify_solo_active_changed, this, _1), this);
653
654         // make sure remote id changed signals reach here
655         // see also notify_route_added
656         Sorted sorted = get_sorted_routes();
657
658         for (Sorted::iterator it = sorted.begin(); it != sorted.end(); ++it) {
659                 (*it)->RemoteControlIDChanged.connect (route_connections, MISSING_INVALIDATOR, boost::bind (&MackieControlProtocol::notify_remote_id_changed, this), this);
660         }
661 }
662
663 void
664 MackieControlProtocol::set_profile (const string& profile_name)
665 {
666         if (profile_name == "default") {
667                 /* reset to default */
668                 _device_profile = DeviceProfile (profile_name);
669         }
670
671         map<string,DeviceProfile>::iterator d = DeviceProfile::device_profiles.find (profile_name);
672
673         if (d == DeviceProfile::device_profiles.end()) {
674                 return;
675         }
676
677         _device_profile = d->second;
678 }
679
680 int
681 MackieControlProtocol::set_device_info (const string& device_name)
682 {
683         map<string,DeviceInfo>::iterator d = DeviceInfo::device_info.find (device_name);
684
685         DEBUG_TRACE (DEBUG::MackieControl, string_compose ("new device chosen %1\n", device_name));
686
687         if (d == DeviceInfo::device_info.end()) {
688                 return -1;
689         }
690
691         _device_info = d->second;
692
693         return 0;
694 }
695
696 int
697 MackieControlProtocol::set_device (const string& device_name, bool force)
698 {
699         if (device_name == device_info().name() && !force) {
700                 /* already using that device, nothing to do */
701                 return 0;
702         }
703
704         /* get state from the current setup, and make sure it is stored in
705            the _surface_states node so that if we switch back to this device,
706            we will have its state available.
707         */
708
709         if (!_surfaces_state) {
710                 _surfaces_state = new XMLNode (X_("Surfaces"));
711         }
712
713         {
714                 Glib::Threads::Mutex::Lock lm (surfaces_lock);
715
716                 for (Surfaces::iterator s = surfaces.begin(); s != surfaces.end(); ++s) {
717                         update_surface_state (*s);
718                 }
719         }
720
721         if (set_device_info (device_name)) {
722                 return -1;
723         }
724
725         clear_surfaces ();
726         port_connection.disconnect ();
727         hui_connection.disconnect ();
728
729         if (_device_info.device_type() == DeviceInfo::HUI) {
730                 Glib::RefPtr<Glib::TimeoutSource> hui_timeout = Glib::TimeoutSource::create (1000); // milliseconds
731                 hui_connection = hui_timeout->connect (sigc::mem_fun (*this, &MackieControlProtocol::hui_heartbeat));
732                 hui_timeout->attach (main_loop()->get_context());
733         }
734
735         if (!_device_info.uses_ipmidi()) {
736                 /* notice that the handler for this will execute in our event
737                    loop, not in the thread where the
738                    PortConnectedOrDisconnected signal is emitted.
739                 */
740                 ARDOUR::AudioEngine::instance()->PortConnectedOrDisconnected.connect (port_connection, MISSING_INVALIDATOR, boost::bind (&MackieControlProtocol::connection_handler, this, _1, _2, _3, _4, _5), this);
741         }
742
743         if (create_surfaces ()) {
744                 return -1;
745         }
746
747         DeviceChanged ();
748
749         return 0;
750 }
751
752 gboolean
753 ArdourSurface::ipmidi_input_handler (GIOChannel*, GIOCondition condition, void *data)
754 {
755         ArdourSurface::MackieControlProtocol::ipMIDIHandler* ipm = static_cast<ArdourSurface::MackieControlProtocol::ipMIDIHandler*>(data);
756         return ipm->mcp->midi_input_handler (Glib::IOCondition (condition), ipm->port);
757 }
758
759 int
760 MackieControlProtocol::create_surfaces ()
761 {
762         string device_name;
763         surface_type_t stype = mcu; // type not yet determined
764
765         DEBUG_TRACE (DEBUG::MackieControl, string_compose ("Create %1 surfaces for %2\n", 1 + _device_info.extenders(), _device_info.name()));
766
767         if (!_device_info.uses_ipmidi()) {
768                 _input_bundle.reset (new ARDOUR::Bundle (_("Mackie Control In"), true));
769                 _output_bundle.reset (new ARDOUR::Bundle (_("Mackie Control Out"), false));
770         } else {
771                 _input_bundle.reset ();
772                 _output_bundle.reset ();
773
774         }
775         for (uint32_t n = 0; n < 1 + _device_info.extenders(); ++n) {
776                 bool is_master = false;
777
778                 if (n == _device_info.master_position()) {
779                         is_master = true;
780                         if (_device_info.extenders() == 0) {
781                                 device_name = _device_info.name();
782                         } else {
783                                 device_name = X_("mackie control");
784                         }
785
786                 }
787
788                 if (!is_master) {
789                         device_name = string_compose (X_("mackie control ext %1"), n+1);
790                 }
791         DEBUG_TRACE (DEBUG::MackieControl, string_compose ("Port Name for surface %1 is %2\n", n, device_name));
792
793                 boost::shared_ptr<Surface> surface;
794
795                 if (is_master) {
796                         stype = mcu;
797                 } else {
798                         stype = ext;
799                 }
800                 try {
801                         surface.reset (new Surface (*this, device_name, n, stype));
802                 } catch (...) {
803                         return -1;
804                 }
805
806                 if (is_master) {
807                         _master_surface = surface;
808                 }
809
810                 if (_surfaces_state) {
811                         surface->set_state (*_surfaces_state, _surfaces_version);
812                 }
813
814                 {
815                         Glib::Threads::Mutex::Lock lm (surfaces_lock);
816                         surfaces.push_back (surface);
817                 }
818
819                 if (!_device_info.uses_ipmidi()) {
820
821                         _input_bundle->add_channel (
822                                 surface->port().input_port().name(),
823                                 ARDOUR::DataType::MIDI,
824                                 session->engine().make_port_name_non_relative (surface->port().input_port().name())
825                                 );
826
827                         _output_bundle->add_channel (
828                                 surface->port().output_port().name(),
829                                 ARDOUR::DataType::MIDI,
830                                 session->engine().make_port_name_non_relative (surface->port().output_port().name())
831                                 );
832                 }
833
834                 MIDI::Port& input_port (surface->port().input_port());
835                 AsyncMIDIPort* asp = dynamic_cast<AsyncMIDIPort*> (&input_port);
836
837                 if (asp) {
838
839                         /* async MIDI port */
840
841                         asp->xthread().set_receive_handler (sigc::bind (sigc::mem_fun (this, &MackieControlProtocol::midi_input_handler), &input_port));
842                         asp->xthread().attach (main_loop()->get_context());
843
844                 } else {
845
846                         /* ipMIDI port, no IOSource method at this time */
847
848                         int fd;
849
850                         if ((fd = input_port.selectable ()) >= 0) {
851
852                                 GIOChannel* ioc = g_io_channel_unix_new (fd);
853                                 surface->input_source = g_io_create_watch (ioc, GIOCondition (G_IO_IN|G_IO_HUP|G_IO_ERR));
854
855                                 /* make surface's input source now hold the
856                                  * only reference on the IO channel
857                                  */
858                                 g_io_channel_unref (ioc);
859
860                                 /* hack up an object so that in the callback from the event loop
861                                    we have both the MackieControlProtocol and the input port.
862
863                                    If we were using C++ for this stuff we wouldn't need this
864                                    but a nasty, not-fixable bug in the binding between C
865                                    and C++ makes it necessary to avoid C++ for the IO
866                                    callback setup.
867                                 */
868
869                                 ipMIDIHandler* ipm = new ipMIDIHandler (); /* we will leak this sizeof(pointer)*2 sized object */
870                                 ipm->mcp = this;
871                                 ipm->port = &input_port;
872
873                                 g_source_set_callback (surface->input_source, (GSourceFunc) ipmidi_input_handler, ipm, NULL);
874                                 g_source_attach (surface->input_source, main_loop()->get_context()->gobj());
875                         }
876                 }
877         }
878
879         if (!_device_info.uses_ipmidi()) {
880                 Glib::Threads::Mutex::Lock lm (surfaces_lock);
881                 for (Surfaces::iterator s = surfaces.begin(); s != surfaces.end(); ++s) {
882                         (*s)->port().reconnect ();
883                 }
884         }
885
886         session->BundleAddedOrRemoved ();
887
888         assert (_master_surface);
889
890         return 0;
891 }
892
893 void
894 MackieControlProtocol::close()
895 {
896         port_connection.disconnect ();
897         session_connections.drop_connections ();
898         route_connections.drop_connections ();
899         periodic_connection.disconnect ();
900
901         clear_surfaces();
902 }
903
904 /** Ensure that the _surfaces_state XML node contains an up-to-date
905  *  copy of the state node for @param surface. If _surfaces_state already
906  *  contains a state node for @param surface, it will deleted and replaced.
907  */
908 void
909 MackieControlProtocol::update_surface_state (boost::shared_ptr<Surface> surface)
910 {
911         assert (_surfaces_state);
912         _surfaces_state->remove_nodes_and_delete (X_("name"), surface->name());
913         _surfaces_state->add_child_nocopy (surface->get_state());
914 }
915
916 XMLNode&
917 MackieControlProtocol::get_state()
918 {
919         XMLNode& node (ControlProtocol::get_state());
920
921         DEBUG_TRACE (DEBUG::MackieControl, "MackieControlProtocol::get_state init\n");
922         char buf[16];
923
924         // add current bank
925         snprintf (buf, sizeof (buf), "%d", _current_initial_bank);
926         node.add_property (X_("bank"), buf);
927
928         // ipMIDI base port (possibly not used)
929         snprintf (buf, sizeof (buf), "%d", _ipmidi_base);
930         node.add_property (X_("ipmidi-base"), buf);
931
932         node.add_property (X_("device-profile"), _device_profile.name());
933         node.add_property (X_("device-name"), _device_info.name());
934
935         if (!_surfaces_state) {
936                 _surfaces_state = new XMLNode (X_("Surfaces"));
937         }
938
939         {
940                 Glib::Threads::Mutex::Lock lm (surfaces_lock);
941                 for (Surfaces::iterator s = surfaces.begin(); s != surfaces.end(); ++s) {
942                         update_surface_state (*s);
943                 }
944         }
945
946         /* force a copy of the _surfaces_state node, because we want to retain ownership */
947         node.add_child_copy (*_surfaces_state);
948
949         DEBUG_TRACE (DEBUG::MackieControl, "MackieControlProtocol::get_state done\n");
950
951         return node;
952 }
953
954 int
955 MackieControlProtocol::set_state (const XMLNode & node, int version)
956 {
957         DEBUG_TRACE (DEBUG::MackieControl, string_compose ("MackieControlProtocol::set_state: active %1\n", active()));
958
959         int retval = 0;
960         const XMLProperty* prop;
961         uint32_t bank = 0;
962
963         if (ControlProtocol::set_state (node, version)) {
964                 return -1;
965         }
966
967         if ((prop = node.property (X_("ipmidi-base"))) != 0) {
968                 set_ipmidi_base (atoi (prop->value()));
969         }
970
971         // fetch current bank
972         if ((prop = node.property (X_("bank"))) != 0) {
973                 bank = atoi (prop->value());
974         }
975
976         if ((prop = node.property (X_("device-name"))) != 0) {
977                 set_device_info (prop->value());
978         }
979
980         if ((prop = node.property (X_("device-profile"))) != 0) {
981                 set_profile (prop->value());
982         }
983
984         XMLNode* snode = node.child (X_("Surfaces"));
985
986         delete _surfaces_state;
987         _surfaces_state = 0;
988
989         if (snode) {
990                 _surfaces_state = new XMLNode (*snode);
991                 _surfaces_version = version;
992         }
993
994         switch_banks (bank, true);
995
996         DEBUG_TRACE (DEBUG::MackieControl, "MackieControlProtocol::set_state done\n");
997
998         return retval;
999 }
1000
1001 string
1002 MackieControlProtocol::format_bbt_timecode (framepos_t now_frame)
1003 {
1004         Timecode::BBT_Time bbt_time;
1005
1006         session->bbt_time (now_frame, bbt_time);
1007
1008         // The Mackie protocol spec is built around a BBT time display of
1009         //
1010         // digits:     888/88/88/888
1011         // semantics:  BBB/bb/ss/ttt
1012         //
1013         // The third field is "subdivisions" which is a concept found in Logic
1014         // but not present in Ardour. Instead Ardour displays a 4 digit tick
1015         // count, which we need to spread across the 5 digits of ss/ttt.
1016
1017         ostringstream os;
1018
1019         os << setw(3) << setfill('0') << bbt_time.bars;
1020         os << setw(2) << setfill('0') << bbt_time.beats;
1021         os << ' ';
1022         os << setw(1) << setfill('0') << bbt_time.ticks / 1000;
1023         os << setw(3) << setfill('0') << bbt_time.ticks % 1000;
1024
1025         return os.str();
1026 }
1027
1028 string
1029 MackieControlProtocol::format_timecode_timecode (framepos_t now_frame)
1030 {
1031         Timecode::Time timecode;
1032         session->timecode_time (now_frame, timecode);
1033
1034         // According to the Logic docs
1035         // digits: 888/88/88/888
1036         // Timecode mode: Hours/Minutes/Seconds/Frames
1037         ostringstream os;
1038         os << setw(2) << setfill('0') << timecode.hours;
1039         os << ' ';
1040         os << setw(2) << setfill('0') << timecode.minutes;
1041         os << setw(2) << setfill('0') << timecode.seconds;
1042         os << ' ';
1043         os << setw(2) << setfill('0') << timecode.frames;
1044
1045         return os.str();
1046 }
1047
1048 void
1049 MackieControlProtocol::update_timecode_display()
1050 {
1051         Glib::Threads::Mutex::Lock lm (surfaces_lock);
1052
1053         if (surfaces.empty()) {
1054                 return;
1055         }
1056
1057         boost::shared_ptr<Surface> surface = _master_surface;
1058
1059         if (surface->type() != mcu || !_device_info.has_timecode_display() || !surface->active ()) {
1060                 return;
1061         }
1062
1063         // do assignment here so current_frame is fixed
1064         framepos_t current_frame = session->transport_frame();
1065         string timecode;
1066
1067         switch (_timecode_type) {
1068         case ARDOUR::AnyTime::BBT:
1069                 timecode = format_bbt_timecode (current_frame);
1070                 break;
1071         case ARDOUR::AnyTime::Timecode:
1072                 timecode = format_timecode_timecode (current_frame);
1073                 break;
1074         default:
1075                 return;
1076         }
1077
1078         // only write the timecode string to the MCU if it's changed
1079         // since last time. This is to reduce midi bandwidth used.
1080         if (timecode != _timecode_last) {
1081                 surface->display_timecode (timecode, _timecode_last);
1082                 _timecode_last = timecode;
1083         }
1084 }
1085
1086 ///////////////////////////////////////////
1087 // Session signals
1088 ///////////////////////////////////////////
1089
1090 void MackieControlProtocol::notify_parameter_changed (std::string const & p)
1091 {
1092         if (p == "punch-in") {
1093                 // no such button right now
1094                 // update_global_button (Button::PunchIn, session->config.get_punch_in());
1095         } else if (p == "punch-out") {
1096                 // no such button right now
1097                 // update_global_button (Button::PunchOut, session->config.get_punch_out());
1098         } else if (p == "clicking") {
1099                 update_global_button (Button::Click, Config->get_clicking());
1100         } else {
1101                 DEBUG_TRACE (DEBUG::MackieControl, string_compose ("parameter changed: %1\n", p));
1102         }
1103 }
1104
1105 // RouteList is the set of routes that have just been added
1106 void
1107 MackieControlProtocol::notify_route_added (ARDOUR::RouteList & rl)
1108 {
1109         {
1110                 Glib::Threads::Mutex::Lock lm (surfaces_lock);
1111
1112                 if (surfaces.empty()) {
1113                         return;
1114                 }
1115         }
1116
1117         // currently assigned banks are less than the full set of
1118         // strips, so activate the new strip now.
1119
1120         refresh_current_bank();
1121
1122         // otherwise route added, but current bank needs no updating
1123
1124         // make sure remote id changes in the new route are handled
1125         typedef ARDOUR::RouteList ARS;
1126
1127         for (ARS::iterator it = rl.begin(); it != rl.end(); ++it) {
1128                 (*it)->RemoteControlIDChanged.connect (route_connections, MISSING_INVALIDATOR, boost::bind (&MackieControlProtocol::notify_remote_id_changed, this), this);
1129         }
1130 }
1131
1132 void
1133 MackieControlProtocol::notify_solo_active_changed (bool active)
1134 {
1135         boost::shared_ptr<Surface> surface;
1136
1137         {
1138                 Glib::Threads::Mutex::Lock lm (surfaces_lock);
1139
1140                 if (surfaces.empty()) {
1141                         return;
1142                 }
1143
1144                 surface = _master_surface;
1145         }
1146
1147         map<int,Control*>::iterator x = surface->controls_by_device_independent_id.find (Led::RudeSolo);
1148         if (x != surface->controls_by_device_independent_id.end()) {
1149                 Led* rude_solo = dynamic_cast<Led*> (x->second);
1150                 if (rude_solo) {
1151                         surface->write (rude_solo->set_state (active ? flashing : off));
1152                 }
1153         }
1154 }
1155
1156 void
1157 MackieControlProtocol::notify_remote_id_changed()
1158 {
1159         {
1160                 Glib::Threads::Mutex::Lock lm (surfaces_lock);
1161
1162                 if (surfaces.empty()) {
1163                         return;
1164                 }
1165         }
1166
1167         Sorted sorted = get_sorted_routes();
1168         uint32_t sz = n_strips();
1169
1170         // if a remote id has been moved off the end, we need to shift
1171         // the current bank backwards.
1172
1173         if (sorted.size() - _current_initial_bank < sz) {
1174                 // but don't shift backwards past the zeroth channel
1175                 switch_banks (max((Sorted::size_type) 0, sorted.size() - sz));
1176         } else {
1177                 // Otherwise just refresh the current bank
1178                 refresh_current_bank();
1179         }
1180 }
1181
1182 ///////////////////////////////////////////
1183 // Transport signals
1184 ///////////////////////////////////////////
1185
1186 void
1187 MackieControlProtocol::notify_loop_state_changed()
1188 {
1189         update_global_button (Button::Loop, session->get_play_loop());
1190 }
1191
1192 void
1193 MackieControlProtocol::notify_transport_state_changed()
1194 {
1195         if (!_device_info.has_global_controls()) {
1196                 return;
1197         }
1198
1199         // switch various play and stop buttons on / off
1200         update_global_button (Button::Loop, session->get_play_loop());
1201         update_global_button (Button::Play, session->transport_speed() == 1.0);
1202         update_global_button (Button::Stop, session->transport_stopped ());
1203         update_global_button (Button::Rewind, session->transport_speed() < 0.0);
1204         update_global_button (Button::Ffwd, session->transport_speed() > 1.0);
1205
1206         notify_metering_state_changed ();
1207 }
1208
1209 void
1210 MackieControlProtocol::notify_metering_state_changed()
1211 {
1212         Glib::Threads::Mutex::Lock lm (surfaces_lock);
1213
1214         for (Surfaces::iterator s = surfaces.begin(); s != surfaces.end(); ++s) {
1215                 (*s)->notify_metering_state_changed ();
1216         }
1217 }
1218
1219 void
1220 MackieControlProtocol::notify_record_state_changed ()
1221 {
1222         if (!_device_info.has_global_controls()) {
1223                 return;
1224         }
1225
1226         boost::shared_ptr<Surface> surface;
1227
1228         {
1229                 Glib::Threads::Mutex::Lock lm (surfaces_lock);
1230                 if (surfaces.empty()) {
1231                         return;
1232                 }
1233                 surface = _master_surface;
1234         }
1235
1236         /* rec is a tristate */
1237
1238         map<int,Control*>::iterator x = surface->controls_by_device_independent_id.find (Button::Record);
1239         if (x != surface->controls_by_device_independent_id.end()) {
1240                 Button * rec = dynamic_cast<Button*> (x->second);
1241                 if (rec) {
1242                         LedState ls;
1243
1244                         switch (session->record_status()) {
1245                         case Session::Disabled:
1246                                 DEBUG_TRACE (DEBUG::MackieControl, "record state changed to disabled, LED off\n");
1247                                 ls = off;
1248                                 break;
1249                         case Session::Recording:
1250                                 DEBUG_TRACE (DEBUG::MackieControl, "record state changed to recording, LED on\n");
1251                                 ls = on;
1252                                 break;
1253                         case Session::Enabled:
1254                                 DEBUG_TRACE (DEBUG::MackieControl, "record state changed to enabled, LED flashing\n");
1255                                 ls = flashing;
1256                                 break;
1257                         }
1258
1259                         surface->write (rec->set_state (ls));
1260                 }
1261         }
1262 }
1263
1264 list<boost::shared_ptr<ARDOUR::Bundle> >
1265 MackieControlProtocol::bundles ()
1266 {
1267         list<boost::shared_ptr<ARDOUR::Bundle> > b;
1268
1269         if (_input_bundle) {
1270                 b.push_back (_input_bundle);
1271                 b.push_back (_output_bundle);
1272         }
1273
1274         return b;
1275 }
1276
1277 void
1278 MackieControlProtocol::do_request (MackieControlUIRequest* req)
1279 {
1280         if (req->type == CallSlot) {
1281
1282                 call_slot (MISSING_INVALIDATOR, req->the_slot);
1283
1284         } else if (req->type == Quit) {
1285
1286                 stop ();
1287         }
1288 }
1289
1290 int
1291 MackieControlProtocol::stop ()
1292 {
1293         BaseUI::quit ();
1294
1295         return 0;
1296 }
1297
1298 void
1299 MackieControlProtocol::update_led (Surface& surface, Button& button, Mackie::LedState ls)
1300 {
1301         if (ls != none) {
1302                 surface.port().write (button.set_state (ls));
1303         }
1304 }
1305
1306 void
1307 MackieControlProtocol::build_button_map ()
1308 {
1309         /* this maps our device-independent button codes to the methods that handle them.
1310          */
1311
1312 #define DEFINE_BUTTON_HANDLER(b,p,r) button_map.insert (pair<Button::ID,ButtonHandlers> ((b), ButtonHandlers ((p),(r))));
1313
1314         DEFINE_BUTTON_HANDLER (Button::Track, &MackieControlProtocol::track_press, &MackieControlProtocol::track_release);
1315         DEFINE_BUTTON_HANDLER (Button::Send, &MackieControlProtocol::send_press, &MackieControlProtocol::send_release);
1316         DEFINE_BUTTON_HANDLER (Button::Pan, &MackieControlProtocol::pan_press, &MackieControlProtocol::pan_release);
1317         DEFINE_BUTTON_HANDLER (Button::Plugin, &MackieControlProtocol::plugin_press, &MackieControlProtocol::plugin_release);
1318         DEFINE_BUTTON_HANDLER (Button::Eq, &MackieControlProtocol::eq_press, &MackieControlProtocol::eq_release);
1319         DEFINE_BUTTON_HANDLER (Button::Dyn, &MackieControlProtocol::dyn_press, &MackieControlProtocol::dyn_release);
1320         DEFINE_BUTTON_HANDLER (Button::Left, &MackieControlProtocol::left_press, &MackieControlProtocol::left_release);
1321         DEFINE_BUTTON_HANDLER (Button::Right, &MackieControlProtocol::right_press, &MackieControlProtocol::right_release);
1322         DEFINE_BUTTON_HANDLER (Button::ChannelLeft, &MackieControlProtocol::channel_left_press, &MackieControlProtocol::channel_left_release);
1323         DEFINE_BUTTON_HANDLER (Button::ChannelRight, &MackieControlProtocol::channel_right_press, &MackieControlProtocol::channel_right_release);
1324         DEFINE_BUTTON_HANDLER (Button::Flip, &MackieControlProtocol::flip_press, &MackieControlProtocol::flip_release);
1325         DEFINE_BUTTON_HANDLER (Button::View, &MackieControlProtocol::view_press, &MackieControlProtocol::view_release);
1326         DEFINE_BUTTON_HANDLER (Button::NameValue, &MackieControlProtocol::name_value_press, &MackieControlProtocol::name_value_release);
1327         DEFINE_BUTTON_HANDLER (Button::TimecodeBeats, &MackieControlProtocol::timecode_beats_press, &MackieControlProtocol::timecode_beats_release);
1328         DEFINE_BUTTON_HANDLER (Button::F1, &MackieControlProtocol::F1_press, &MackieControlProtocol::F1_release);
1329         DEFINE_BUTTON_HANDLER (Button::F2, &MackieControlProtocol::F2_press, &MackieControlProtocol::F2_release);
1330         DEFINE_BUTTON_HANDLER (Button::F3, &MackieControlProtocol::F3_press, &MackieControlProtocol::F3_release);
1331         DEFINE_BUTTON_HANDLER (Button::F4, &MackieControlProtocol::F4_press, &MackieControlProtocol::F4_release);
1332         DEFINE_BUTTON_HANDLER (Button::F5, &MackieControlProtocol::F5_press, &MackieControlProtocol::F5_release);
1333         DEFINE_BUTTON_HANDLER (Button::F6, &MackieControlProtocol::F6_press, &MackieControlProtocol::F6_release);
1334         DEFINE_BUTTON_HANDLER (Button::F7, &MackieControlProtocol::F7_press, &MackieControlProtocol::F7_release);
1335         DEFINE_BUTTON_HANDLER (Button::F8, &MackieControlProtocol::F8_press, &MackieControlProtocol::F8_release);
1336         DEFINE_BUTTON_HANDLER (Button::MidiTracks, &MackieControlProtocol::miditracks_press, &MackieControlProtocol::miditracks_release);
1337         DEFINE_BUTTON_HANDLER (Button::Inputs, &MackieControlProtocol::inputs_press, &MackieControlProtocol::inputs_release);
1338         DEFINE_BUTTON_HANDLER (Button::AudioTracks, &MackieControlProtocol::audiotracks_press, &MackieControlProtocol::audiotracks_release);
1339         DEFINE_BUTTON_HANDLER (Button::AudioInstruments, &MackieControlProtocol::audioinstruments_press, &MackieControlProtocol::audioinstruments_release);
1340         DEFINE_BUTTON_HANDLER (Button::Aux, &MackieControlProtocol::aux_press, &MackieControlProtocol::aux_release);
1341         DEFINE_BUTTON_HANDLER (Button::Busses, &MackieControlProtocol::busses_press, &MackieControlProtocol::busses_release);
1342         DEFINE_BUTTON_HANDLER (Button::Outputs, &MackieControlProtocol::outputs_press, &MackieControlProtocol::outputs_release);
1343         DEFINE_BUTTON_HANDLER (Button::User, &MackieControlProtocol::user_press, &MackieControlProtocol::user_release);
1344         DEFINE_BUTTON_HANDLER (Button::Shift, &MackieControlProtocol::shift_press, &MackieControlProtocol::shift_release);
1345         DEFINE_BUTTON_HANDLER (Button::Option, &MackieControlProtocol::option_press, &MackieControlProtocol::option_release);
1346         DEFINE_BUTTON_HANDLER (Button::Ctrl, &MackieControlProtocol::control_press, &MackieControlProtocol::control_release);
1347         DEFINE_BUTTON_HANDLER (Button::CmdAlt, &MackieControlProtocol::cmd_alt_press, &MackieControlProtocol::cmd_alt_release);
1348         DEFINE_BUTTON_HANDLER (Button::Read, &MackieControlProtocol::read_press, &MackieControlProtocol::read_release);
1349         DEFINE_BUTTON_HANDLER (Button::Write, &MackieControlProtocol::write_press, &MackieControlProtocol::write_release);
1350         DEFINE_BUTTON_HANDLER (Button::Trim, &MackieControlProtocol::trim_press, &MackieControlProtocol::trim_release);
1351         DEFINE_BUTTON_HANDLER (Button::Touch, &MackieControlProtocol::touch_press, &MackieControlProtocol::touch_release);
1352         DEFINE_BUTTON_HANDLER (Button::Latch, &MackieControlProtocol::latch_press, &MackieControlProtocol::latch_release);
1353         DEFINE_BUTTON_HANDLER (Button::Grp, &MackieControlProtocol::grp_press, &MackieControlProtocol::grp_release);
1354         DEFINE_BUTTON_HANDLER (Button::Save, &MackieControlProtocol::save_press, &MackieControlProtocol::save_release);
1355         DEFINE_BUTTON_HANDLER (Button::Undo, &MackieControlProtocol::undo_press, &MackieControlProtocol::undo_release);
1356         DEFINE_BUTTON_HANDLER (Button::Cancel, &MackieControlProtocol::cancel_press, &MackieControlProtocol::cancel_release);
1357         DEFINE_BUTTON_HANDLER (Button::Enter, &MackieControlProtocol::enter_press, &MackieControlProtocol::enter_release);
1358         DEFINE_BUTTON_HANDLER (Button::Marker, &MackieControlProtocol::marker_press, &MackieControlProtocol::marker_release);
1359         DEFINE_BUTTON_HANDLER (Button::Nudge, &MackieControlProtocol::nudge_press, &MackieControlProtocol::nudge_release);
1360         DEFINE_BUTTON_HANDLER (Button::Loop, &MackieControlProtocol::loop_press, &MackieControlProtocol::loop_release);
1361         DEFINE_BUTTON_HANDLER (Button::Drop, &MackieControlProtocol::drop_press, &MackieControlProtocol::drop_release);
1362         DEFINE_BUTTON_HANDLER (Button::Replace, &MackieControlProtocol::replace_press, &MackieControlProtocol::replace_release);
1363         DEFINE_BUTTON_HANDLER (Button::Click, &MackieControlProtocol::click_press, &MackieControlProtocol::click_release);
1364         DEFINE_BUTTON_HANDLER (Button::ClearSolo, &MackieControlProtocol::clearsolo_press, &MackieControlProtocol::clearsolo_release);
1365         DEFINE_BUTTON_HANDLER (Button::Rewind, &MackieControlProtocol::rewind_press, &MackieControlProtocol::rewind_release);
1366         DEFINE_BUTTON_HANDLER (Button::Ffwd, &MackieControlProtocol::ffwd_press, &MackieControlProtocol::ffwd_release);
1367         DEFINE_BUTTON_HANDLER (Button::Stop, &MackieControlProtocol::stop_press, &MackieControlProtocol::stop_release);
1368         DEFINE_BUTTON_HANDLER (Button::Play, &MackieControlProtocol::play_press, &MackieControlProtocol::play_release);
1369         DEFINE_BUTTON_HANDLER (Button::Record, &MackieControlProtocol::record_press, &MackieControlProtocol::record_release);
1370         DEFINE_BUTTON_HANDLER (Button::CursorUp, &MackieControlProtocol::cursor_up_press, &MackieControlProtocol::cursor_up_release);
1371         DEFINE_BUTTON_HANDLER (Button::CursorDown, &MackieControlProtocol::cursor_down_press, &MackieControlProtocol::cursor_down_release);
1372         DEFINE_BUTTON_HANDLER (Button::CursorLeft, &MackieControlProtocol::cursor_left_press, &MackieControlProtocol::cursor_left_release);
1373         DEFINE_BUTTON_HANDLER (Button::CursorRight, &MackieControlProtocol::cursor_right_press, &MackieControlProtocol::cursor_right_release);
1374         DEFINE_BUTTON_HANDLER (Button::Zoom, &MackieControlProtocol::zoom_press, &MackieControlProtocol::zoom_release);
1375         DEFINE_BUTTON_HANDLER (Button::Scrub, &MackieControlProtocol::scrub_press, &MackieControlProtocol::scrub_release);
1376         DEFINE_BUTTON_HANDLER (Button::UserA, &MackieControlProtocol::user_a_press, &MackieControlProtocol::user_a_release);
1377         DEFINE_BUTTON_HANDLER (Button::UserB, &MackieControlProtocol::user_b_press, &MackieControlProtocol::user_b_release);
1378         DEFINE_BUTTON_HANDLER (Button::MasterFaderTouch, &MackieControlProtocol::master_fader_touch_press, &MackieControlProtocol::master_fader_touch_release);
1379
1380 }
1381
1382 void
1383 MackieControlProtocol::handle_button_event (Surface& surface, Button& button, ButtonState bs)
1384 {
1385         Button::ID button_id = button.bid();
1386
1387         if  (bs != press && bs != release) {
1388                 update_led (surface, button, none);
1389                 return;
1390         }
1391
1392         DEBUG_TRACE (DEBUG::MackieControl, string_compose ("Handling %1 for button %2 (%3)\n", (bs == press ? "press" : "release"), button.id(),
1393                                                            Button::id_to_name (button.bid())));
1394
1395         /* check profile first */
1396
1397         string action = _device_profile.get_button_action (button.bid(), _modifier_state);
1398
1399         if (!action.empty()) {
1400
1401                 if (action.find ('/') != string::npos) { /* good chance that this is really an action */
1402
1403                         DEBUG_TRACE (DEBUG::MackieControl, string_compose ("Looked up action for button %1 with modifier %2, got [%3]\n",
1404                                                                            button.bid(), _modifier_state, action));
1405
1406                         /* if there is a bound action for this button, and this is a press event,
1407                            carry out the action. If its a release event, do nothing since we
1408                            don't bind to them at all but don't want any other handling to
1409                            occur either.
1410                         */
1411                         if (bs == press) {
1412                                 DEBUG_TRACE (DEBUG::MackieControl, string_compose ("executing action %1\n", action));
1413                                 access_action (action);
1414                         }
1415
1416                         return;
1417
1418                 } else {
1419
1420                         /* "action" is more likely to be a button name. We use this to
1421                          * allow remapping buttons to different (builtin) functionality
1422                          * associated with an existing button. This is similar to the
1423                          * way that (for example) Nuendo moves the "Shift" function to
1424                          * the "Enter" key of the MCU Pro.
1425                          */
1426
1427                         int bid = Button::name_to_id (action);
1428
1429                         if (bid < 0) {
1430                                 DEBUG_TRACE (DEBUG::MackieControl, string_compose ("apparent button name %1 not found\n", action));
1431                                 return;
1432                         }
1433
1434                         button_id = (Button::ID) bid;
1435                         DEBUG_TRACE (DEBUG::MackieControl, string_compose ("handling button %1 as if it was %2 (%3)\n", Button::id_to_name (button.bid()), button_id, Button::id_to_name (button_id)));
1436                 }
1437         }
1438
1439         /* lookup using the device-INDEPENDENT button ID */
1440
1441         ButtonMap::iterator b = button_map.find (button_id);
1442
1443         if (b != button_map.end()) {
1444
1445                 ButtonHandlers& bh (b->second);
1446
1447                 switch  (bs) {
1448                 case press:
1449                         surface.write (button.set_state ((this->*(bh.press)) (button)));
1450                         break;
1451                 case release:
1452                         surface.write (button.set_state ((this->*(bh.release)) (button)));
1453                         break;
1454                 default:
1455                         break;
1456                 }
1457         } else {
1458                 DEBUG_TRACE (DEBUG::MackieControl, string_compose ("no button handlers for button ID %1 (device ID %2)\n",
1459                                                                    button.bid(), button.id()));
1460                 error << string_compose ("no button handlers for button ID %1 (device ID %2)\n",
1461                                          button.bid(), button.id()) << endmsg;
1462         }
1463 }
1464
1465 bool
1466 MackieControlProtocol::midi_input_handler (IOCondition ioc, MIDI::Port* port)
1467 {
1468         if (ioc & ~IO_IN) {
1469                 DEBUG_TRACE (DEBUG::MackieControl, "MIDI port closed\n");
1470                 return false;
1471         }
1472
1473         if (ioc & IO_IN) {
1474
1475                 DEBUG_TRACE (DEBUG::MackieControl, string_compose ("something happend on  %1\n", port->name()));
1476
1477                 /* Devices using regular JACK MIDI ports will need to have
1478                    the x-thread FIFO drained to avoid burning endless CPU.
1479
1480                    Devices using ipMIDI have port->selectable() as the same
1481                    file descriptor that data arrives on, so doing this
1482                    for them will simply throw all incoming data away.
1483                 */
1484
1485                 if (!_device_info.uses_ipmidi()) {
1486                         AsyncMIDIPort* asp = dynamic_cast<AsyncMIDIPort*>(port);
1487                         if (asp) {
1488                                 asp->clear ();
1489                         }
1490                 }
1491
1492                 DEBUG_TRACE (DEBUG::MackieControl, string_compose ("data available on %1\n", port->name()));
1493                 framepos_t now = session->engine().sample_time();
1494                 port->parse (now);
1495         }
1496
1497         return true;
1498 }
1499
1500 void
1501 MackieControlProtocol::clear_ports ()
1502 {
1503         if (_input_bundle) {
1504                 _input_bundle->remove_channels ();
1505                 _output_bundle->remove_channels ();
1506         }
1507 }
1508
1509 void
1510 MackieControlProtocol::set_view_mode (ViewMode m)
1511 {
1512         Glib::Threads::Mutex::Lock lm (surfaces_lock);
1513
1514         _view_mode = m;
1515
1516         for (Surfaces::iterator s = surfaces.begin(); s != surfaces.end(); ++s) {
1517                 (*s)->update_view_mode_display ();
1518         }
1519
1520 }
1521
1522 void
1523 MackieControlProtocol::set_flip_mode (FlipMode fm)
1524 {
1525         if (_flip_mode != fm) {
1526                 if (fm == Normal) {
1527                         update_global_button (Button::Flip, off);
1528                 } else {
1529                         update_global_button (Button::Flip, on);
1530                 }
1531
1532                 Glib::Threads::Mutex::Lock lm (surfaces_lock);
1533
1534                 _flip_mode = fm;
1535
1536                 for (Surfaces::iterator s = surfaces.begin(); s != surfaces.end(); ++s) {
1537                         (*s)->update_flip_mode_display ();
1538                 }
1539         }
1540 }
1541
1542 void
1543 MackieControlProtocol::set_pot_mode (PotMode m)
1544 {
1545         Glib::Threads::Mutex::Lock lm (surfaces_lock);
1546
1547         _pot_mode = m;
1548
1549         for (Surfaces::iterator s = surfaces.begin(); s != surfaces.end(); ++s) {
1550                 (*s)->update_potmode ();
1551
1552         }
1553
1554 }
1555
1556 void
1557 MackieControlProtocol::set_master_on_surface_strip (uint32_t surface, uint32_t strip_number)
1558 {
1559         force_special_route_to_strip (session->master_out(), surface, strip_number);
1560 }
1561
1562 void
1563 MackieControlProtocol::set_monitor_on_surface_strip (uint32_t surface, uint32_t strip_number)
1564 {
1565         force_special_route_to_strip (session->monitor_out(), surface, strip_number);
1566 }
1567
1568 void
1569 MackieControlProtocol::force_special_route_to_strip (boost::shared_ptr<Route> r, uint32_t surface, uint32_t strip_number)
1570 {
1571         if (!r) {
1572                 return;
1573         }
1574
1575         Glib::Threads::Mutex::Lock lm (surfaces_lock);
1576
1577         for (Surfaces::iterator s = surfaces.begin(); s != surfaces.end(); ++s) {
1578                 if ((*s)->number() == surface) {
1579                         Strip* strip = (*s)->nth_strip (strip_number);
1580                         if (strip) {
1581                                 strip->set_route (session->master_out());
1582                                 strip->lock_controls ();
1583                         }
1584                 }
1585         }
1586 }
1587
1588 void
1589 MackieControlProtocol::gui_track_selection_changed (ARDOUR::RouteNotificationListPtr rl, bool save_list)
1590 {
1591         _gui_track_selection_changed (rl.get(), save_list);
1592 }
1593
1594 void
1595 MackieControlProtocol::_gui_track_selection_changed (ARDOUR::RouteNotificationList* rl, bool save_list)
1596 {
1597         /* We need to keep a list of the most recently selected routes around,
1598            but we are not allowed to keep shared_ptr<Route> unless we want to
1599            handle the complexities of route deletion. So instead, the GUI sends
1600            us a notification using weak_ptr<Route>, which we keep a copy
1601            of. For efficiency's sake, however, we convert the weak_ptr's into
1602            shared_ptr<Route> before passing them to however many surfaces (and
1603            thus strips) that we have.
1604         */
1605
1606         StrongRouteNotificationList srl;
1607
1608         for (ARDOUR::RouteNotificationList::const_iterator i = rl->begin(); i != rl->end(); ++i) {
1609                 boost::shared_ptr<ARDOUR::Route> r = (*i).lock();
1610                 if (r) {
1611                         srl.push_back (r);
1612                 }
1613         }
1614
1615         {
1616                 Glib::Threads::Mutex::Lock lm (surfaces_lock);
1617
1618                 for (Surfaces::iterator s = surfaces.begin(); s != surfaces.end(); ++s) {
1619                         (*s)->gui_selection_changed (srl);
1620                 }
1621         }
1622
1623         if (save_list) {
1624                 _last_selected_routes = *rl;
1625         }
1626 }
1627
1628 framepos_t
1629 MackieControlProtocol::transport_frame() const
1630 {
1631         return session->transport_frame();
1632 }
1633
1634 void
1635 MackieControlProtocol::add_down_select_button (int surface, int strip)
1636 {
1637         _down_select_buttons.insert ((surface<<8)|(strip&0xf));
1638 }
1639
1640 void
1641 MackieControlProtocol::remove_down_select_button (int surface, int strip)
1642 {
1643         DownButtonList::iterator x = find (_down_select_buttons.begin(), _down_select_buttons.end(), (uint32_t) (surface<<8)|(strip&0xf));
1644         DEBUG_TRACE (DEBUG::MackieControl, string_compose ("removing surface %1 strip %2 from down select buttons\n", surface, strip));
1645         if (x != _down_select_buttons.end()) {
1646                 _down_select_buttons.erase (x);
1647         } else {
1648                 DEBUG_TRACE (DEBUG::MackieControl, string_compose ("surface %1 strip %2 not found in down select buttons\n",
1649                                                                    surface, strip));
1650         }
1651 }
1652
1653 void
1654 MackieControlProtocol::select_range ()
1655 {
1656         RouteList routes;
1657
1658         pull_route_range (_down_select_buttons, routes);
1659
1660         DEBUG_TRACE (DEBUG::MackieControl, string_compose ("select range: found %1 routes\n", routes.size()));
1661
1662         if (!routes.empty()) {
1663                 for (RouteList::iterator r = routes.begin(); r != routes.end(); ++r) {
1664
1665                         if (main_modifier_state() == MODIFIER_CONTROL) {
1666                                 ToggleRouteSelection ((*r)->remote_control_id ());
1667                         } else {
1668                                 if (r == routes.begin()) {
1669                                         SetRouteSelection ((*r)->remote_control_id());
1670                                 } else {
1671                                         AddRouteToSelection ((*r)->remote_control_id());
1672                                 }
1673                         }
1674                 }
1675         }
1676 }
1677
1678 void
1679 MackieControlProtocol::add_down_button (AutomationType a, int surface, int strip)
1680 {
1681         DownButtonMap::iterator m = _down_buttons.find (a);
1682
1683         if (m == _down_buttons.end()) {
1684                 _down_buttons[a] = DownButtonList();
1685         }
1686
1687         _down_buttons[a].insert ((surface<<8)|(strip&0xf));
1688 }
1689
1690 void
1691 MackieControlProtocol::remove_down_button (AutomationType a, int surface, int strip)
1692 {
1693         DownButtonMap::iterator m = _down_buttons.find (a);
1694
1695         DEBUG_TRACE (DEBUG::MackieControl, string_compose ("removing surface %1 strip %2 from down buttons for %3\n", surface, strip, (int) a));
1696
1697         if (m == _down_buttons.end()) {
1698                 return;
1699         }
1700
1701         DownButtonList& l (m->second);
1702         DownButtonList::iterator x = find (l.begin(), l.end(), (surface<<8)|(strip&0xf));
1703
1704         if (x != l.end()) {
1705                 l.erase (x);
1706         } else {
1707                 DEBUG_TRACE (DEBUG::MackieControl, string_compose ("surface %1 strip %2 not found in down buttons for %3\n",
1708                                                                    surface, strip, (int) a));
1709         }
1710 }
1711
1712 MackieControlProtocol::ControlList
1713 MackieControlProtocol::down_controls (AutomationType p)
1714 {
1715         ControlList controls;
1716         RouteList routes;
1717
1718         DownButtonMap::iterator m = _down_buttons.find (p);
1719
1720         if (m == _down_buttons.end()) {
1721                 return controls;
1722         }
1723
1724         DEBUG_TRACE (DEBUG::MackieControl, string_compose ("looking for down buttons for %1, got %2\n",
1725                                                            p, m->second.size()));
1726
1727         pull_route_range (m->second, routes);
1728
1729         switch (p) {
1730         case GainAutomation:
1731                 for (RouteList::iterator r = routes.begin(); r != routes.end(); ++r) {
1732                         controls.push_back ((*r)->gain_control());
1733                 }
1734                 break;
1735         case SoloAutomation:
1736                 for (RouteList::iterator r = routes.begin(); r != routes.end(); ++r) {
1737                         controls.push_back ((*r)->solo_control());
1738                 }
1739                 break;
1740         case MuteAutomation:
1741                 for (RouteList::iterator r = routes.begin(); r != routes.end(); ++r) {
1742                         controls.push_back ((*r)->mute_control());
1743                 }
1744                 break;
1745         case RecEnableAutomation:
1746                 for (RouteList::iterator r = routes.begin(); r != routes.end(); ++r) {
1747                         boost::shared_ptr<Track> trk = boost::dynamic_pointer_cast<Track> (*r);
1748                         if (trk) {
1749                                 controls.push_back (trk->rec_enable_control());
1750                         }
1751                 }
1752                 break;
1753         default:
1754                 break;
1755         }
1756
1757         return controls;
1758
1759 }
1760
1761 struct ButtonRangeSorter {
1762     bool operator() (const uint32_t& a, const uint32_t& b) {
1763             return (a>>8) < (b>>8) // a.surface < b.surface
1764                     ||
1765                     ((a>>8) == (b>>8) && (a&0xf) < (b&0xf)); // a.surface == b.surface && a.strip < b.strip
1766     }
1767 };
1768
1769 void
1770 MackieControlProtocol::pull_route_range (DownButtonList& down, RouteList& selected)
1771 {
1772         ButtonRangeSorter cmp;
1773
1774         if (down.empty()) {
1775                 return;
1776         }
1777
1778         list<uint32_t> ldown;
1779         ldown.insert (ldown.end(), down.begin(), down.end());
1780         ldown.sort (cmp);
1781
1782         uint32_t first = ldown.front();
1783         uint32_t last = ldown.back ();
1784
1785         uint32_t first_surface = first>>8;
1786         uint32_t first_strip = first&0xf;
1787
1788         uint32_t last_surface = last>>8;
1789         uint32_t last_strip = last&0xf;
1790
1791         DEBUG_TRACE (DEBUG::MackieControl, string_compose ("PRR %5 in list %1.%2 - %3.%4\n", first_surface, first_strip, last_surface, last_strip,
1792                                                            down.size()));
1793
1794         Glib::Threads::Mutex::Lock lm (surfaces_lock);
1795
1796         for (Surfaces::const_iterator s = surfaces.begin(); s != surfaces.end(); ++s) {
1797
1798                 if ((*s)->number() >= first_surface && (*s)->number() <= last_surface) {
1799
1800                         uint32_t fs;
1801                         uint32_t ls;
1802
1803                         if ((*s)->number() == first_surface) {
1804                                 fs = first_strip;
1805                         } else {
1806                                 fs = 0;
1807                         }
1808
1809                         if ((*s)->number() == last_surface) {
1810                                 ls = last_strip;
1811                                 ls += 1;
1812                         } else {
1813                                 ls = (*s)->n_strips ();
1814                         }
1815
1816                         DEBUG_TRACE (DEBUG::MackieControl, string_compose ("adding strips for surface %1 (%2 .. %3)\n",
1817                                                                            (*s)->number(), fs, ls));
1818
1819                         for (uint32_t n = fs; n < ls; ++n) {
1820                                 boost::shared_ptr<Route> r = (*s)->nth_strip (n)->route();
1821                                 if (r) {
1822                                         selected.push_back (r);
1823                                 }
1824                         }
1825                 }
1826         }
1827 }
1828
1829 void
1830 MackieControlProtocol::set_ipmidi_base (int16_t portnum)
1831 {
1832         /* this will not be saved without a session save, so .. */
1833
1834         session->set_dirty ();
1835
1836         _ipmidi_base = portnum;
1837
1838         /* if the current device uses ipMIDI we need
1839            to restart.
1840         */
1841
1842         if (active() && _device_info.uses_ipmidi()) {
1843                 needs_ipmidi_restart = true;
1844         }
1845 }
1846
1847 int
1848 MackieControlProtocol::ipmidi_restart ()
1849 {
1850         clear_surfaces ();
1851         if (create_surfaces ()) {
1852                 return -1;
1853         }
1854         switch_banks (_current_initial_bank, true);
1855         needs_ipmidi_restart = false;
1856         return 0;
1857 }
1858
1859 void
1860 MackieControlProtocol::clear_surfaces ()
1861 {
1862         clear_ports ();
1863
1864         {
1865                 Glib::Threads::Mutex::Lock lm (surfaces_lock);
1866                 _master_surface.reset ();
1867                 surfaces.clear ();
1868         }
1869 }
1870
1871 void
1872 MackieControlProtocol::set_touch_sensitivity (int sensitivity)
1873 {
1874         sensitivity = min (9, sensitivity);
1875         sensitivity = max (0, sensitivity);
1876
1877         Glib::Threads::Mutex::Lock lm (surfaces_lock);
1878
1879         for (Surfaces::const_iterator s = surfaces.begin(); s != surfaces.end(); ++s) {
1880                 (*s)->set_touch_sensitivity (sensitivity);
1881         }
1882 }
1883
1884 void
1885 MackieControlProtocol::recalibrate_faders ()
1886 {
1887         Glib::Threads::Mutex::Lock lm (surfaces_lock);
1888
1889         for (Surfaces::const_iterator s = surfaces.begin(); s != surfaces.end(); ++s) {
1890                 (*s)->recalibrate_faders ();
1891         }
1892 }
1893
1894 void
1895 MackieControlProtocol::toggle_backlight ()
1896 {
1897         Glib::Threads::Mutex::Lock lm (surfaces_lock);
1898
1899         for (Surfaces::const_iterator s = surfaces.begin(); s != surfaces.end(); ++s) {
1900                 (*s)->toggle_backlight ();
1901         }
1902 }
1903
1904 boost::shared_ptr<Surface>
1905 MackieControlProtocol::get_surface_by_raw_pointer (void* ptr) const
1906 {
1907         Glib::Threads::Mutex::Lock lm (surfaces_lock);
1908
1909         for (Surfaces::const_iterator s = surfaces.begin(); s != surfaces.end(); ++s) {
1910                 if ((*s).get() == (Surface*) ptr) {
1911                         return *s;
1912                 }
1913         }
1914
1915         return boost::shared_ptr<Surface> ();
1916 }
1917
1918 boost::shared_ptr<Surface>
1919 MackieControlProtocol::nth_surface (uint32_t n) const
1920 {
1921         Glib::Threads::Mutex::Lock lm (surfaces_lock);
1922
1923         for (Surfaces::const_iterator s = surfaces.begin(); s != surfaces.end(); ++s, --n) {
1924                 if (n == 0) {
1925                         return *s;
1926                 }
1927         }
1928
1929         return boost::shared_ptr<Surface> ();
1930 }
1931
1932 void
1933 MackieControlProtocol::connection_handler (boost::weak_ptr<ARDOUR::Port> wp1, std::string name1, boost::weak_ptr<ARDOUR::Port> wp2, std::string name2, bool yn)
1934 {
1935         Surfaces scopy;
1936         {
1937                 Glib::Threads::Mutex::Lock lm (surfaces_lock);
1938                 scopy = surfaces;
1939         }
1940
1941         for (Surfaces::const_iterator s = scopy.begin(); s != scopy.end(); ++s) {
1942                 if ((*s)->connection_handler (wp1, name1, wp2, name2, yn)) {
1943                         ConnectionChange (*s);
1944                         break;
1945                 }
1946         }
1947 }