cont'd FP8 tweaks
[ardour.git] / libs / surfaces / faderport8 / faderport8.cc
1 /*
2  * Copyright (C) 2017 Robin Gareus <robin@gareus.org>
3  * Copyright (C) 2015 Paul Davis
4  *
5  * This program is free software; you can redistribute it and/or
6  * modify it under the terms of the GNU General Public License
7  * as published by the Free Software Foundation; either version 2
8  * of the License, or (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., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
18  */
19
20 #include <cstdlib>
21 #include <sstream>
22 #include <algorithm>
23
24 #include <stdint.h>
25
26 #include "pbd/error.h"
27 #include "pbd/failed_constructor.h"
28 #include "pbd/pthread_utils.h"
29 #include "pbd/compose.h"
30 #include "pbd/xml++.h"
31
32 #include "midi++/port.h"
33
34 #include "ardour/audioengine.h"
35 #include "ardour/audio_track.h"
36 #include "ardour/bundle.h"
37 #include "ardour/debug.h"
38 #include "ardour/midi_track.h"
39 #include "ardour/midiport_manager.h"
40 #include "ardour/plugin_insert.h"
41 #include "ardour/processor.h"
42 #include "ardour/rc_configuration.h"
43 #include "ardour/route.h"
44 #include "ardour/session.h"
45 #include "ardour/session_configuration.h"
46 #include "ardour/vca.h"
47
48 #include "faderport8.h"
49
50 using namespace ARDOUR;
51 using namespace ArdourSurface;
52 using namespace PBD;
53 using namespace Glib;
54 using namespace std;
55 using namespace ArdourSurface::FP8Types;
56
57 #include "pbd/i18n.h"
58
59 #include "pbd/abstract_ui.cc" // instantiate template
60
61 #ifndef NDEBUG
62 //#define VERBOSE_DEBUG
63 #endif
64
65 static void
66 debug_2byte_msg (std::string const& msg, int b0, int b1)
67 {
68 #ifndef NDEBUG
69         if (DEBUG_ENABLED(DEBUG::FaderPort8)) {
70                 DEBUG_STR_DECL(a);
71                 DEBUG_STR_APPEND(a, "RECV: ");
72                 DEBUG_STR_APPEND(a, msg);
73                 DEBUG_STR_APPEND(a,' ');
74                 DEBUG_STR_APPEND(a,hex);
75                 DEBUG_STR_APPEND(a,"0x");
76                 DEBUG_STR_APPEND(a, b0);
77                 DEBUG_STR_APPEND(a,' ');
78                 DEBUG_STR_APPEND(a,"0x");
79                 DEBUG_STR_APPEND(a, b1);
80                 DEBUG_STR_APPEND(a,'\n');
81                 DEBUG_TRACE (DEBUG::FaderPort8, DEBUG_STR(a).str());
82         }
83 #endif
84 }
85
86 FaderPort8::FaderPort8 (Session& s)
87         : ControlProtocol (s, _("PreSonus FaderPort8"))
88         , AbstractUI<FaderPort8Request> (name())
89         , _connection_state (ConnectionState (0))
90         , _device_active (false)
91         , _ctrls (*this)
92         , _channel_off (0)
93         , _plugin_off (0)
94         , _parameter_off (0)
95         , _blink_onoff (false)
96         , _shift_lock (false)
97         , _shift_pressed (0)
98         , gui (0)
99 {
100         boost::shared_ptr<ARDOUR::Port> inp;
101         boost::shared_ptr<ARDOUR::Port> outp;
102
103         inp  = AudioEngine::instance()->register_input_port (DataType::MIDI, "FaderPort8 Recv", true);
104         outp = AudioEngine::instance()->register_output_port (DataType::MIDI, "FaderPort8 Send", true);
105         _input_port = boost::dynamic_pointer_cast<AsyncMIDIPort>(inp);
106         _output_port = boost::dynamic_pointer_cast<AsyncMIDIPort>(outp);
107
108         if (_input_port == 0 || _output_port == 0) {
109                 throw failed_constructor();
110         }
111
112         _input_bundle.reset (new ARDOUR::Bundle (_("FaderPort8 (Receive)"), true));
113         _output_bundle.reset (new ARDOUR::Bundle (_("FaderPort8 (Send) "), false));
114
115         _input_bundle->add_channel (
116                 inp->name(),
117                 ARDOUR::DataType::MIDI,
118                 session->engine().make_port_name_non_relative (inp->name())
119                 );
120
121         _output_bundle->add_channel (
122                 outp->name(),
123                 ARDOUR::DataType::MIDI,
124                 session->engine().make_port_name_non_relative (outp->name())
125                 );
126
127         ARDOUR::AudioEngine::instance()->PortConnectedOrDisconnected.connect (port_connection, MISSING_INVALIDATOR, boost::bind (&FaderPort8::connection_handler, this, _1, _2, _3, _4, _5), this);
128
129         StripableSelectionChanged.connect (selection_connection, MISSING_INVALIDATOR, boost::bind (&FaderPort8::gui_track_selection_changed, this), this);
130
131         setup_actions ();
132         _ctrls.FaderModeChanged.connect_same_thread (modechange_connections, boost::bind (&FaderPort8::notify_fader_mode_changed, this));
133         _ctrls.MixModeChanged.connect_same_thread (modechange_connections, boost::bind (&FaderPort8::assign_strips, this, true));
134 }
135
136 FaderPort8::~FaderPort8 ()
137 {
138         cerr << "~FP8\n";
139         stop_midi_handling  ();
140         close ();
141
142         if (_input_port) {
143                 DEBUG_TRACE (DEBUG::FaderPort8, string_compose ("unregistering input port %1\n", boost::shared_ptr<ARDOUR::Port>(_input_port)->name()));
144                 AudioEngine::instance()->unregister_port (_input_port);
145                 _input_port.reset ();
146         }
147
148         if (_output_port) {
149                 _output_port->drain (10000,  250000); /* check every 10 msecs, wait up to 1/4 second for the port to drain */
150                 DEBUG_TRACE (DEBUG::FaderPort8, string_compose ("unregistering output port %1\n", boost::shared_ptr<ARDOUR::Port>(_output_port)->name()));
151                 AudioEngine::instance()->unregister_port (_output_port);
152                 _output_port.reset ();
153         }
154
155         tear_down_gui ();
156
157         /* stop event loop */
158         DEBUG_TRACE (DEBUG::FaderPort8, "BaseUI::quit ()\n");
159         BaseUI::quit ();
160 }
161
162 /* ****************************************************************************
163  * Event Loop
164  */
165
166 void*
167 FaderPort8::request_factory (uint32_t num_requests)
168 {
169         /* AbstractUI<T>::request_buffer_factory() is a template method only
170          * instantiated in this source module. To provide something visible for
171          * use in the interface/descriptor, we have this static method that is
172          * template-free.
173          */
174         return request_buffer_factory (num_requests);
175 }
176
177 void
178 FaderPort8::do_request (FaderPort8Request* req)
179 {
180         if (req->type == CallSlot) {
181                 call_slot (MISSING_INVALIDATOR, req->the_slot);
182         } else if (req->type == Quit) {
183                 stop ();
184         }
185 }
186
187 int
188 FaderPort8::stop ()
189 {
190         BaseUI::quit ();
191         return 0;
192 }
193
194 void
195 FaderPort8::thread_init ()
196 {
197         struct sched_param rtparam;
198
199         pthread_set_name (event_loop_name().c_str());
200
201         PBD::notify_event_loops_about_thread_creation (pthread_self(), event_loop_name(), 2048);
202         ARDOUR::SessionEvent::create_per_thread_pool (event_loop_name(), 128);
203
204         memset (&rtparam, 0, sizeof (rtparam));
205         rtparam.sched_priority = 9; /* XXX should be relative to audio (JACK) thread */
206
207         if (pthread_setschedparam (pthread_self(), SCHED_FIFO, &rtparam) != 0) {
208                 // do we care? not particularly.
209         }
210 }
211
212 bool
213 FaderPort8::periodic ()
214 {
215         /* prepare TC display -- handled by stripable Periodic () */
216         if (_ctrls.display_timecode ()) {
217                 // TODO allow BBT, HHMMSS
218                 // used in FP8Strip::periodic_update_timecode
219                 Timecode::Time TC;
220                 session->timecode_time (TC);
221                 _timecode = Timecode::timecode_format_time(TC);
222         } else {
223                 _timecode.clear ();
224         }
225
226         /* update stripables */
227         Periodic ();
228         return true;
229 }
230
231 bool
232 FaderPort8::blink_it ()
233 {
234         _blink_onoff = !_blink_onoff;
235         BlinkIt (_blink_onoff);
236         return true;
237 }
238
239 /* ****************************************************************************
240  * Port and Signal Connection Management
241  */
242 int
243 FaderPort8::set_active (bool yn)
244 {
245         DEBUG_TRACE (DEBUG::FaderPort8, string_compose("set_active init with yn: '%1'\n", yn));
246
247         if (yn == active()) {
248                 return 0;
249         }
250
251         if (yn) {
252                 /* start event loop */
253                 BaseUI::run ();
254                 connect_session_signals ();
255         } else {
256                 BaseUI::quit ();
257                 close ();
258         }
259
260         ControlProtocol::set_active (yn);
261         DEBUG_TRACE (DEBUG::FaderPort8, string_compose("set_active done with yn: '%1'\n", yn));
262         return 0;
263 }
264
265 void
266 FaderPort8::close ()
267 {
268         _assigned_strips.clear ();
269         stop_midi_handling ();
270         session_connections.drop_connections ();
271         automation_state_connections.drop_connections ();
272         assigned_stripable_connections.drop_connections ();
273         drop_ctrl_connections ();
274         port_connection.disconnect ();
275         selection_connection.disconnect ();
276 }
277
278 void
279 FaderPort8::stop_midi_handling ()
280 {
281         _periodic_connection.disconnect ();
282         _blink_connection.disconnect ();
283         midi_connections.drop_connections ();
284         /* Note: the input handler is still active at this point, but we're no
285          * longer connected to any of the parser signals
286          */
287 }
288
289 void
290 FaderPort8::connected ()
291 {
292         DEBUG_TRACE (DEBUG::FaderPort8, "initializing\n");
293         // ideally check firmware version >= 1.01 (USB bcdDevice 0x0101) (vendor 0x194f prod 0x0202)
294         // but we don't have a handle to the underlying USB device here.
295
296         _channel_off = _plugin_off = _parameter_off = 0;
297         _blink_onoff = false;
298         _shift_lock = false;
299         _shift_pressed = 0;
300
301         start_midi_handling ();
302         _ctrls.initialize ();
303
304         /* highlight bound user-actions */
305         for (FP8Controls::UserButtonMap::const_iterator i = _ctrls.user_buttons ().begin ();
306                         i != _ctrls.user_buttons ().end (); ++i) {
307                 _ctrls.button (i->first).set_active (! _user_action_map[i->first].empty ());
308         }
309         /* shift button lights */
310         tx_midi3 (0x90, 0x06, 0x00);
311         tx_midi3 (0x90, 0x46, 0x00);
312
313         send_session_state ();
314         assign_strips (true);
315
316         Glib::RefPtr<Glib::TimeoutSource> blink_timer =
317                 Glib::TimeoutSource::create (200);
318         _blink_connection = blink_timer->connect (sigc::mem_fun (*this, &FaderPort8::blink_it));
319         blink_timer->attach (main_loop()->get_context());
320
321         Glib::RefPtr<Glib::TimeoutSource> periodic_timer =
322                 Glib::TimeoutSource::create (100);
323         _periodic_connection = periodic_timer->connect (sigc::mem_fun (*this, &FaderPort8::periodic));
324         periodic_timer->attach (main_loop()->get_context());
325 }
326
327 void
328 FaderPort8::disconnected ()
329 {
330         stop_midi_handling ();
331         for (uint8_t id = 0; id < 8; ++id) {
332                 _ctrls.strip(id).unset_controllables ();
333         }
334 }
335
336 bool
337 FaderPort8::connection_handler (boost::weak_ptr<ARDOUR::Port>, std::string name1, boost::weak_ptr<ARDOUR::Port>, std::string name2, bool yn)
338 {
339 #ifdef VERBOSE_DEBUG
340         DEBUG_TRACE (DEBUG::FaderPort8, "FaderPort8::connection_handler: start\n");
341 #endif
342         if (!_input_port || !_output_port) {
343                 return false;
344         }
345
346         string ni = ARDOUR::AudioEngine::instance()->make_port_name_non_relative (boost::shared_ptr<ARDOUR::Port>(_input_port)->name());
347         string no = ARDOUR::AudioEngine::instance()->make_port_name_non_relative (boost::shared_ptr<ARDOUR::Port>(_output_port)->name());
348
349         if (ni == name1 || ni == name2) {
350                 if (yn) {
351                         _connection_state |= InputConnected;
352                 } else {
353                         _connection_state &= ~InputConnected;
354                 }
355         } else if (no == name1 || no == name2) {
356                 if (yn) {
357                         _connection_state |= OutputConnected;
358                 } else {
359                         _connection_state &= ~OutputConnected;
360                 }
361         } else {
362 #ifdef VERBOSE_DEBUG
363                 DEBUG_TRACE (DEBUG::FaderPort8, string_compose ("Connections between %1 and %2 changed, but I ignored it\n", name1, name2));
364 #endif
365                 /* not our ports */
366                 return false;
367         }
368
369         if ((_connection_state & (InputConnected|OutputConnected)) == (InputConnected|OutputConnected)) {
370
371                 /* XXX this is a horrible hack. Without a short sleep here,
372                  * something prevents the device wakeup messages from being
373                  * sent and/or the responses from being received.
374                  */
375                 g_usleep (100000);
376                 DEBUG_TRACE (DEBUG::FaderPort8, "device now connected for both input and output\n");
377                 connected ();
378                 _device_active = true;
379
380         } else {
381                 DEBUG_TRACE (DEBUG::FaderPort8, "Device disconnected (input or output or both) or not yet fully connected\n");
382                 disconnected ();
383                 _device_active = false;
384         }
385
386         ConnectionChange (); /* emit signal for our GUI */
387
388 #ifdef VERBOSE_DEBUG
389         DEBUG_TRACE (DEBUG::FaderPort8, "FaderPort8::connection_handler: end\n");
390 #endif
391
392         return true; /* connection status changed */
393 }
394
395 list<boost::shared_ptr<ARDOUR::Bundle> >
396 FaderPort8::bundles ()
397 {
398         list<boost::shared_ptr<ARDOUR::Bundle> > b;
399
400         if (_input_bundle) {
401                 b.push_back (_input_bundle);
402                 b.push_back (_output_bundle);
403         }
404
405         return b;
406 }
407
408 /* ****************************************************************************
409  * MIDI I/O
410  */
411 bool
412 FaderPort8::midi_input_handler (Glib::IOCondition ioc, boost::weak_ptr<ARDOUR::AsyncMIDIPort> wport)
413 {
414         boost::shared_ptr<AsyncMIDIPort> port (wport.lock());
415
416         if (!port) {
417                 return false;
418         }
419
420 #ifdef VERBOSE_DEBUG
421         DEBUG_TRACE (DEBUG::FaderPort8, string_compose ("something happend on %1\n", boost::shared_ptr<MIDI::Port>(port)->name()));
422 #endif
423
424         if (ioc & ~IO_IN) {
425                 return false;
426         }
427
428         if (ioc & IO_IN) {
429
430                 port->clear ();
431 #ifdef VERBOSE_DEBUG
432                 DEBUG_TRACE (DEBUG::FaderPort8, string_compose ("data available on %1\n", boost::shared_ptr<MIDI::Port>(port)->name()));
433 #endif
434                 framepos_t now = session->engine().sample_time();
435                 port->parse (now);
436         }
437
438         return true;
439 }
440
441 void
442 FaderPort8::start_midi_handling ()
443 {
444         _input_port->parser()->sysex.connect_same_thread (midi_connections, boost::bind (&FaderPort8::sysex_handler, this, _1, _2, _3));
445         _input_port->parser()->poly_pressure.connect_same_thread (midi_connections, boost::bind (&FaderPort8::polypressure_handler, this, _1, _2));
446         for (uint8_t i = 0; i < 16; ++i) {
447         _input_port->parser()->channel_pitchbend[i].connect_same_thread (midi_connections, boost::bind (&FaderPort8::pitchbend_handler, this, _1, i, _2));
448         }
449         _input_port->parser()->controller.connect_same_thread (midi_connections, boost::bind (&FaderPort8::controller_handler, this, _1, _2));
450         _input_port->parser()->note_on.connect_same_thread (midi_connections, boost::bind (&FaderPort8::note_on_handler, this, _1, _2));
451         _input_port->parser()->note_off.connect_same_thread (midi_connections, boost::bind (&FaderPort8::note_off_handler, this, _1, _2));
452
453         /* This connection means that whenever data is ready from the input
454          * port, the relevant thread will invoke our ::midi_input_handler()
455          * method, which will read the data, and invoke the parser.
456          */
457         _input_port->xthread().set_receive_handler (sigc::bind (sigc::mem_fun (this, &FaderPort8::midi_input_handler), boost::weak_ptr<AsyncMIDIPort> (_input_port)));
458         _input_port->xthread().attach (main_loop()->get_context());
459 }
460
461 size_t
462 FaderPort8::tx_midi (std::vector<uint8_t> const& d) const
463 {
464         /* work around midi buffer overflow for batch changes */
465         if (d.size() == 3 && (d[0] == 0x91 || d[0] == 0x92)) {
466                 /* set colors triplet in one go */
467         } else if (d.size() == 3 && (d[0] == 0x93)) {
468                 g_usleep (1500);
469         } else {
470                 g_usleep (400 * d.size());
471         }
472 #ifndef NDEBUG
473         size_t tx = _output_port->write (&d[0], d.size(), 0);
474         assert (tx == d.size());
475         return tx;
476 #else
477         return _output_port->write (&d[0], d.size(), 0);
478 #endif
479 }
480
481 /* ****************************************************************************
482  * MIDI Callbacks
483  */
484 void
485 FaderPort8::polypressure_handler (MIDI::Parser &, MIDI::EventTwoBytes* tb)
486 {
487         debug_2byte_msg ("PP", tb->controller_number, tb->value);
488         // outgoing only (meter)
489 }
490
491 void
492 FaderPort8::pitchbend_handler (MIDI::Parser &, uint8_t chan, MIDI::pitchbend_t pb)
493 {
494         debug_2byte_msg ("PB", chan, pb);
495         /* fader 0..16368 (0x3ff0 -- 1024 steps) */
496         bool handled = _ctrls.midi_fader (chan, pb);
497         /* if Shift key is held while moving a fader (group override), don't lock shift. */
498         if ((_shift_pressed > 0) && handled) {
499                 _shift_connection.disconnect ();
500                 _shift_lock = false;
501         }
502 }
503
504 void
505 FaderPort8::controller_handler (MIDI::Parser &, MIDI::EventTwoBytes* tb)
506 {
507         debug_2byte_msg ("CC", tb->controller_number, tb->value);
508         // encoder
509         // val Bit 7 = direction, Bits 0-6 = number of steps
510         if (tb->controller_number == 0x3c) {
511                 encoder_navigate (tb->value & 0x40 ? true : false, tb->value & 0x3f);
512         }
513         if (tb->controller_number == 0x10) {
514                 encoder_parameter (tb->value & 0x40 ? true : false, tb->value & 0x3f);
515         }
516 }
517
518 void
519 FaderPort8::note_on_handler (MIDI::Parser &, MIDI::EventTwoBytes* tb)
520 {
521         debug_2byte_msg ("ON", tb->note_number, tb->velocity);
522
523         /* fader touch */
524         if (tb->note_number >= 0x68 && tb->note_number <= 0x6f) {
525                 _ctrls.midi_touch (tb->note_number - 0x68, tb->velocity);
526                 return;
527         }
528
529         /* special case shift */
530         if (tb->note_number == 0x06 || tb->note_number == 0x46) {
531                 _shift_pressed |= (tb->note_number == 0x06) ? 1 : 2;
532                 if (_shift_pressed == 3) {
533                         return;
534                 }
535                 _shift_connection.disconnect ();
536                 if (_shift_lock) {
537                         _shift_lock = false;
538                         ShiftButtonChange (false);
539                         tx_midi3 (0x90, 0x06, 0x00);
540                         tx_midi3 (0x90, 0x46, 0x00);
541                         return;
542                 }
543
544                 Glib::RefPtr<Glib::TimeoutSource> shift_timer =
545                         Glib::TimeoutSource::create (1000);
546                 shift_timer->attach (main_loop()->get_context());
547                 _shift_connection = shift_timer->connect (sigc::mem_fun (*this, &FaderPort8::shift_timeout));
548
549                 ShiftButtonChange (true);
550                 tx_midi3 (0x90, 0x06, 0x7f);
551                 tx_midi3 (0x90, 0x46, 0x7f);
552                 return;
553         }
554
555         _ctrls.midi_event (tb->note_number, tb->velocity);
556 }
557
558 void
559 FaderPort8::note_off_handler (MIDI::Parser &, MIDI::EventTwoBytes* tb)
560 {
561         debug_2byte_msg ("OF", tb->note_number, tb->velocity);
562
563         if (tb->note_number >= 0x68 && tb->note_number <= 0x6f) {
564                 // fader touch
565                 _ctrls.midi_touch (tb->note_number - 0x68, tb->velocity);
566                 return;
567         }
568
569         /* special case shift */
570         if (tb->note_number == 0x06 || tb->note_number == 0x46) {
571                 _shift_pressed &= (tb->note_number == 0x06) ? 2 : 1;
572                 if (_shift_pressed > 0) {
573                         return;
574                 }
575                 if (_shift_lock) {
576                         return;
577                 }
578                 ShiftButtonChange (false);
579                 tx_midi3 (0x90, 0x06, 0x00);
580                 tx_midi3 (0x90, 0x46, 0x00);
581                 /* just in case this happens concurrently */
582                 _shift_connection.disconnect ();
583                 _shift_lock = false;
584                 return;
585         }
586
587         bool handled = _ctrls.midi_event (tb->note_number, tb->velocity);
588         /* if Shift key is held while activating an action, don't lock shift. */
589         if ((_shift_pressed > 0) && handled) {
590                 _shift_connection.disconnect ();
591                 _shift_lock = false;
592         }
593 }
594
595 void
596 FaderPort8::sysex_handler (MIDI::Parser &p, MIDI::byte *buf, size_t size)
597 {
598 #ifndef NDEBUG
599         if (DEBUG_ENABLED(DEBUG::FaderPort8)) {
600                 DEBUG_STR_DECL(a);
601                 DEBUG_STR_APPEND(a, string_compose ("RECV sysex siz=%1", size));
602                 for (size_t i=0; i < size; ++i) {
603                         DEBUG_STR_APPEND(a,hex);
604                         DEBUG_STR_APPEND(a,"0x");
605                         DEBUG_STR_APPEND(a,(int)buf[i]);
606                         DEBUG_STR_APPEND(a,' ');
607                 }
608                 DEBUG_STR_APPEND(a,'\n');
609                 DEBUG_TRACE (DEBUG::FaderPort8, DEBUG_STR(a).str());
610         }
611 #endif
612 }
613
614 /* ****************************************************************************
615  * User actions
616  */
617 void
618 FaderPort8::set_button_action (FP8Controls::ButtonId id, bool press, std::string const& action_name)
619 {
620         if (_ctrls.user_buttons().find (id) == _ctrls.user_buttons().end ()) {
621                 return;
622         }
623         _user_action_map[id].action (press).assign_action (action_name);
624
625         if (!_device_active) {
626                 return;
627         }
628         _ctrls.button (id).set_active (!_user_action_map[id].empty ());
629 }
630
631 std::string
632 FaderPort8::get_button_action (FP8Controls::ButtonId id, bool press)
633 {
634         return _user_action_map[id].action(press)._action_name;
635 }
636
637 /* ****************************************************************************
638  * Persistent State
639  */
640 XMLNode&
641 FaderPort8::get_state ()
642 {
643         DEBUG_TRACE (DEBUG::FaderPort8, "FaderPort8::get_state\n");
644         XMLNode& node (ControlProtocol::get_state());
645
646         XMLNode* child;
647
648         child = new XMLNode (X_("Input"));
649         child->add_child_nocopy (boost::shared_ptr<ARDOUR::Port>(_input_port)->get_state());
650         node.add_child_nocopy (*child);
651
652         child = new XMLNode (X_("Output"));
653         child->add_child_nocopy (boost::shared_ptr<ARDOUR::Port>(_output_port)->get_state());
654         node.add_child_nocopy (*child);
655
656         for (UserActionMap::const_iterator i = _user_action_map.begin (); i != _user_action_map.end (); ++i) {
657                 if (i->second.empty()) {
658                         continue;
659                 }
660                 std::string name;
661                 if (!_ctrls.button_enum_to_name (i->first, name)) {
662                         continue;
663                 }
664                 XMLNode* btn = new XMLNode (X_("Button"));
665                 btn->add_property (X_("id"), name);
666                 if (!i->second.action(true).empty ()) {
667                         btn->add_property ("press", i->second.action(true)._action_name);
668                 }
669                 if (!i->second.action(false).empty ()) {
670                         btn->add_property ("release", i->second.action(false)._action_name);
671                 }
672                 node.add_child_nocopy (*btn);
673         }
674
675         return node;
676 }
677
678 int
679 FaderPort8::set_state (const XMLNode& node, int version)
680 {
681         DEBUG_TRACE (DEBUG::FaderPort8, "FaderPort8::set_state\n");
682         XMLNodeList nlist;
683         XMLNodeConstIterator niter;
684         XMLNode const* child;
685
686         if (ControlProtocol::set_state (node, version)) {
687                 return -1;
688         }
689
690         if ((child = node.child (X_("Input"))) != 0) {
691                 XMLNode* portnode = child->child (Port::state_node_name.c_str());
692                 if (portnode) {
693                         DEBUG_TRACE (DEBUG::FaderPort8, "FaderPort8::set_state Input\n");
694                         boost::shared_ptr<ARDOUR::Port>(_input_port)->set_state (*portnode, version);
695                 }
696         }
697
698         if ((child = node.child (X_("Output"))) != 0) {
699                 XMLNode* portnode = child->child (Port::state_node_name.c_str());
700                 if (portnode) {
701                         DEBUG_TRACE (DEBUG::FaderPort8, "FaderPort8::set_state Output\n");
702                         boost::shared_ptr<ARDOUR::Port>(_output_port)->set_state (*portnode, version);
703                 }
704         }
705
706         _user_action_map.clear ();
707         // TODO: When re-loading state w/o surface re-init becomes possible,
708         // unset lights and reset colors of user buttons.
709
710         for (XMLNodeList::const_iterator n = node.children().begin(); n != node.children().end(); ++n) {
711                 if ((*n)->name() != X_("Button")) {
712                         continue;
713                 }
714                 XMLProperty const* prop = (*n)->property (X_("id"));
715                 if (!prop) {
716                         continue;
717                 }
718
719                 FP8Controls::ButtonId id;
720                 if (!_ctrls.button_name_to_enum (prop->value(), id)) {
721                         continue;
722                 }
723
724                 prop = (*n)->property (X_("press"));
725                 if (prop) {
726                         set_button_action (id, true, prop->value());
727                 }
728                 prop = (*n)->property (X_("release"));
729                 if (prop) {
730                         set_button_action (id, false, prop->value());
731                 }
732         }
733
734         return 0;
735 }
736
737 /* ****************************************************************************
738  * Stripable Assignment
739  */
740
741 static bool flt_audio_track (boost::shared_ptr<Stripable> s) {
742         return boost::dynamic_pointer_cast<AudioTrack>(s) != 0;
743 }
744
745 static bool flt_midi_track (boost::shared_ptr<Stripable> s) {
746         return boost::dynamic_pointer_cast<MidiTrack>(s) != 0;
747 }
748
749 static bool flt_bus (boost::shared_ptr<Stripable> s) {
750         if (boost::dynamic_pointer_cast<Route>(s) == 0) {
751                 return false;
752         }
753 #ifdef MIXBUS
754         if (s->mixbus () == 0) {
755                 return false;
756         }
757 #endif
758         return boost::dynamic_pointer_cast<Track>(s) == 0;
759 }
760
761 static bool flt_auxbus (boost::shared_ptr<Stripable> s) {
762         if (boost::dynamic_pointer_cast<Route>(s) == 0) {
763                 return false;
764         }
765 #ifdef MIXBUS
766         if (s->mixbus () > 0) {
767                 return false;
768         }
769 #endif
770         return boost::dynamic_pointer_cast<Track>(s) == 0;
771 }
772
773 static bool flt_vca (boost::shared_ptr<Stripable> s) {
774         return boost::dynamic_pointer_cast<VCA>(s) != 0;
775 }
776
777 static bool flt_selected (boost::shared_ptr<Stripable> s) {
778         return s->is_selected ();
779 }
780
781 static bool flt_mains (boost::shared_ptr<Stripable> s) {
782         return (s->is_master() || s->is_monitor());
783 }
784
785 static bool flt_all (boost::shared_ptr<Stripable> s) {
786         return true;
787 }
788
789 static bool flt_rec_armed (boost::shared_ptr<Stripable> s) {
790         boost::shared_ptr<Track> t = boost::dynamic_pointer_cast<Track>(s);
791         if (!t) {
792                 return false;
793         }
794         return t->rec_enable_control ()->get_value () > 0.;
795 }
796
797 static bool flt_instrument (boost::shared_ptr<Stripable> s) {
798         boost::shared_ptr<Route> r = boost::dynamic_pointer_cast<Route>(s);
799         if (!r) {
800                 return false;
801         }
802         return 0 != r->the_instrument ();
803 }
804
805 struct FP8SortByNewDisplayOrder
806 {
807         // return (a < b)
808         bool operator () (const boost::shared_ptr<Stripable> & a, const boost::shared_ptr<Stripable> & b) const
809         {
810                 if (a->presentation_info().flags () == b->presentation_info().flags ()) {
811                         return a->presentation_info().order() < b->presentation_info().order();
812                 }
813
814                 int cmp_a = 0;
815                 int cmp_b = 0;
816
817                 if (a->presentation_info().flags () & ARDOUR::PresentationInfo::VCA) {
818                         cmp_a = 1;
819                 }
820 #ifdef MIXBUS
821                 else if (a->presentation_info().flags () & ARDOUR::PresentationInfo::MasterOut) {
822                         cmp_a = 3;
823                 }
824                 else if (a->presentation_info().flags () & ARDOUR::PresentationInfo::Mixbus || a->mixbus()) {
825                         cmp_a = 2;
826                 }
827 #endif
828
829                 if (b->presentation_info().flags () & ARDOUR::PresentationInfo::VCA) {
830                         cmp_b = 1;
831                 }
832 #ifdef MIXBUS
833                 else if (b->presentation_info().flags () & ARDOUR::PresentationInfo::MasterOut) {
834                         cmp_b = 3;
835                 }
836                 else if (b->presentation_info().flags () & ARDOUR::PresentationInfo::Mixbus || b->mixbus()) {
837                         cmp_b = 2;
838                 }
839 #endif
840
841 #ifdef MIXBUS
842                 // this can happen with older MB sessions (no PresentationInfo::Mixbus flag)
843                 if (cmp_a == cmp_b) {
844                         return a->presentation_info().order() < b->presentation_info().order();
845                 }
846 #endif
847                 return cmp_a < cmp_b;
848         }
849 };
850
851 void
852 FaderPort8::filter_stripables (StripableList& strips) const
853 {
854         typedef bool (*FilterFunction)(boost::shared_ptr<Stripable>);
855         FilterFunction flt;
856
857         bool allow_master = false;
858         bool allow_monitor = false;
859
860         switch (_ctrls.mix_mode ()) {
861                 case MixAudio:
862                         flt = &flt_audio_track;
863                         break;
864                 case MixInstrument:
865                         flt = &flt_instrument;
866                         break;
867                 case MixBus:
868                         flt = &flt_bus;
869                         break;
870                 case MixVCA:
871                         flt = &flt_vca;
872                         break;
873                 case MixMIDI:
874                         flt = &flt_midi_track;
875                         break;
876                 case MixUser:
877                         allow_master = true;
878                         flt = &flt_selected;
879                         break;
880                 case MixOutputs:
881                         allow_master = true;
882                         allow_monitor = true;
883                         flt = &flt_mains;
884                         break;
885                 case MixInputs:
886                         flt = &flt_rec_armed;
887                         break;
888                 case MixFX:
889                         flt = &flt_auxbus;
890                         break;
891                 case MixAll:
892                         allow_master = true;
893                         flt = &flt_all;
894                         break;
895         }
896
897         StripableList all;
898         session->get_stripables (all);
899
900         for (StripableList::const_iterator s = all.begin(); s != all.end(); ++s) {
901                 if ((*s)->is_auditioner ()) { continue; }
902                 if ((*s)->is_hidden ()) { continue; }
903
904                 if (!allow_master  && (*s)->is_master ()) { continue; }
905                 if (!allow_monitor && (*s)->is_monitor ()) { continue; }
906
907                 if ((*flt)(*s)) {
908                         strips.push_back (*s);
909                 }
910         }
911         strips.sort (FP8SortByNewDisplayOrder());
912 }
913
914 /* Track/Pan mode: assign stripable to strips */
915 void
916 FaderPort8::assign_stripables (bool select_only)
917 {
918         StripableList strips;
919         filter_stripables (strips);
920
921         if (!select_only) {
922                 set_periodic_display_mode (FP8Strip::Stripables);
923         }
924
925         int n_strips = strips.size();
926         _channel_off = std::min (_channel_off, n_strips - 8);
927         _channel_off = std::max (0, _channel_off);
928
929         uint8_t id = 0;
930         int skip = _channel_off;
931         for (StripableList::const_iterator s = strips.begin(); s != strips.end(); ++s) {
932                 if (skip > 0) {
933                         --skip;
934                         continue;
935                 }
936
937                 _assigned_strips[*s] = id;
938                 (*s)->DropReferences.connect (assigned_stripable_connections, MISSING_INVALIDATOR,
939                                 boost::bind (&FaderPort8::notify_stripable_added_or_removed, this), this);
940
941                 (*s)->PropertyChanged.connect (assigned_stripable_connections, MISSING_INVALIDATOR,
942                                 boost::bind (&FaderPort8::notify_stripable_property_changed, this, boost::weak_ptr<Stripable> (*s), _1), this);
943                 (*s)->presentation_info ().PropertyChanged.connect (assigned_stripable_connections, MISSING_INVALIDATOR,
944                                 boost::bind (&FaderPort8::notify_stripable_property_changed, this, boost::weak_ptr<Stripable> (*s), _1), this);
945
946                 if (select_only) {
947                         _ctrls.strip(id).set_text_line (3, (*s)->name (), true);
948                         _ctrls.strip(id).select_button ().set_color ((*s)->presentation_info ().color());
949                         /* update selection lights */
950                         _ctrls.strip(id).select_button ().set_active ((*s)->is_selected ());
951                         _ctrls.strip(id).select_button ().set_blinking (*s == first_selected_stripable ());
952                 } else {
953                         _ctrls.strip(id).set_stripable (*s, _ctrls.fader_mode() == ModePan);
954                 }
955
956                  boost::function<void ()> cb (boost::bind (&FaderPort8::select_strip, this, boost::weak_ptr<Stripable> (*s)));
957                  _ctrls.strip(id).set_select_cb (cb);
958
959                 if (++id == 8) {
960                         break;
961                 }
962         }
963         for (; id < 8; ++id) {
964                 _ctrls.strip(id).unset_controllables (select_only ? (FP8Strip::CTRL_SELECT | FP8Strip::CTRL_TEXT3) : FP8Strip::CTRL_ALL);
965         }
966 }
967
968 void
969 FaderPort8::assign_processor_ctrls ()
970 {
971         if (_proc_params.size() == 0) {
972                 _ctrls.set_fader_mode (ModeTrack);
973                 return;
974         }
975         set_periodic_display_mode (FP8Strip::PluginParam);
976
977         std::vector <ProcessorCtrl*> toggle_params;
978         std::vector <ProcessorCtrl*> slider_params;
979
980         for ( std::list <ProcessorCtrl>::iterator i = _proc_params.begin(); i != _proc_params.end(); ++i) {
981                 if ((*i).ac->toggled()) {
982                         toggle_params.push_back (&(*i));
983                 } else {
984                         slider_params.push_back (&(*i));
985                 }
986         }
987
988         int n_parameters = std::max (toggle_params.size(), slider_params.size());
989
990         _parameter_off = std::min (_parameter_off, n_parameters - 8);
991         _parameter_off = std::max (0, _parameter_off);
992
993         uint8_t id = 0;
994         for (size_t i = _parameter_off; i < (size_t)n_parameters; ++i) {
995                 if (i >= toggle_params.size ()) {
996                         _ctrls.strip(id).unset_controllables (FP8Strip::CTRL_ALL & ~FP8Strip::CTRL_FADER & ~FP8Strip::CTRL_TEXT0 & ~FP8Strip::CTRL_TEXT1);
997                 }
998                 else if (i >= slider_params.size ()) {
999                         _ctrls.strip(id).unset_controllables (FP8Strip::CTRL_ALL & ~FP8Strip::CTRL_SELECT & ~FP8Strip::CTRL_TEXT3);
1000                 } else {
1001                         _ctrls.strip(id).unset_controllables (FP8Strip::CTRL_ALL & ~FP8Strip::CTRL_FADER & ~FP8Strip::CTRL_TEXT0 & ~FP8Strip::CTRL_TEXT1 & ~FP8Strip::CTRL_SELECT & ~FP8Strip::CTRL_TEXT3);
1002                 }
1003
1004                 if (i < slider_params.size ()) {
1005                         _ctrls.strip(id).set_fader_controllable (slider_params[i]->ac);
1006                         _ctrls.strip(id).set_text_line (0, slider_params[i]->name);
1007                 }
1008                 if (i < toggle_params.size ()) {
1009                         _ctrls.strip(id).set_select_controllable (toggle_params[i]->ac);
1010                         _ctrls.strip(id).set_text_line (3, toggle_params[i]->name, true);
1011                 }
1012                  if (++id == 8) {
1013                          break;
1014                  }
1015         }
1016
1017         // clear remaining
1018         for (; id < 8; ++id) {
1019                 _ctrls.strip(id).unset_controllables ();
1020         }
1021 }
1022
1023 void
1024 FaderPort8::build_well_known_processor_ctrls (boost::shared_ptr<Stripable> s, bool eq)
1025 {
1026 #define PUSH_BACK_NON_NULL(N, C) do {if (C) { _proc_params.push_back (ProcessorCtrl (N, C)); }} while (0)
1027
1028         _proc_params.clear ();
1029         if (eq) {
1030                 int cnt = s->eq_band_cnt();
1031                 PUSH_BACK_NON_NULL ("Enable", s->eq_enable_controllable ());
1032                 PUSH_BACK_NON_NULL ("HPF", s->eq_hpf_controllable ());
1033                 for (int band = 0; band < cnt; ++band) {
1034                         std::string bn = s->eq_band_name (band);
1035                         PUSH_BACK_NON_NULL (string_compose ("Gain %1", bn), s->eq_gain_controllable (band));
1036                         PUSH_BACK_NON_NULL (string_compose ("Freq %1", bn), s->eq_freq_controllable (band));
1037                         PUSH_BACK_NON_NULL (string_compose ("Band %1", bn), s->eq_q_controllable (band));
1038                         PUSH_BACK_NON_NULL (string_compose ("Shape %1", bn), s->eq_shape_controllable (band));
1039                 }
1040         } else {
1041                 PUSH_BACK_NON_NULL ("Enable", s->comp_enable_controllable ());
1042                 PUSH_BACK_NON_NULL ("Threshold", s->comp_threshold_controllable ());
1043                 PUSH_BACK_NON_NULL ("Speed", s->comp_speed_controllable ());
1044                 PUSH_BACK_NON_NULL ("Mode", s->comp_mode_controllable ());
1045         }
1046 }
1047
1048 void
1049 FaderPort8::select_plugin (int num)
1050 {
1051         // make sure drop_ctrl_connections() was called
1052         assert (_proc_params.size() == 0 && _showing_well_known == 0);
1053
1054         boost::shared_ptr<Route> r = boost::dynamic_pointer_cast<Route> (first_selected_stripable());
1055         if (!r) {
1056                 _ctrls.set_fader_mode (ModeTrack);
1057                 return;
1058         }
1059         if (num < 0) {
1060                 build_well_known_processor_ctrls (r, num == -1);
1061                 assign_processor_ctrls ();
1062                 _showing_well_known = num;
1063                 return;
1064         }
1065         _showing_well_known = 0;
1066
1067         boost::shared_ptr<Processor> proc = r->nth_plugin (num);
1068         if (!proc) {
1069                 _ctrls.set_fader_mode (ModeTrack);
1070                 return;
1071         }
1072
1073         // switching to "Mode Track" -> calls FaderPort8::notify_fader_mode_changed()
1074         // which drops the references, disconnects the signal and re-spills tracks
1075         proc->DropReferences.connect (processor_connections, MISSING_INVALIDATOR, boost::bind (&FP8Controls::set_fader_mode, &_ctrls, ModeTrack), this);
1076
1077         // build params
1078         _proc_params.clear();
1079         set<Evoral::Parameter> p = proc->what_can_be_automated ();
1080         for (set<Evoral::Parameter>::iterator i = p.begin(); i != p.end(); ++i) {
1081                 std::string n = proc->describe_parameter (*i);
1082                 if (n == "hidden") {
1083                         continue;
1084                 }
1085                 _proc_params.push_back (ProcessorCtrl (n, proc->automation_control (*i)));
1086         }
1087
1088         // TODO: open plugin GUI  if (_proc_params.size() > 0)
1089
1090         // display
1091         assign_processor_ctrls ();
1092 }
1093
1094 /* short 4 chars at most */
1095 static std::string plugintype (ARDOUR::PluginType t) {
1096         switch (t) {
1097                 case AudioUnit:
1098                         return "AU";
1099                 case LADSPA:
1100                         return "LV1";
1101                 case LV2:
1102                         return "LV2";
1103                 case Windows_VST:
1104                 case LXVST:
1105                 case MacVST:
1106                         return "VST";
1107                 case Lua:
1108                         return "Lua";
1109                 default:
1110                         break;
1111         }
1112         return enum_2_string (t);
1113 }
1114
1115 void
1116 FaderPort8::spill_plugins ()
1117 {
1118         boost::shared_ptr<Route> r = boost::dynamic_pointer_cast<Route> (first_selected_stripable());
1119         if (!r) {
1120                 _ctrls.set_fader_mode (ModeTrack);
1121                 return;
1122         }
1123
1124         drop_ctrl_connections ();
1125
1126         // switching to "Mode Track" -> calls FaderPort8::notify_fader_mode_changed()
1127         // which drops the references, disconnects the signal and re-spills tracks
1128         r->DropReferences.connect (processor_connections, MISSING_INVALIDATOR, boost::bind (&FP8Controls::set_fader_mode, &_ctrls, ModeTrack), this);
1129
1130         // update when processor change
1131         r->processors_changed.connect (processor_connections, MISSING_INVALIDATOR, boost::bind (&FaderPort8::spill_plugins, this), this);
1132
1133         // count available
1134         boost::shared_ptr<Processor> proc;
1135
1136         std::vector<uint32_t> procs;
1137
1138         for (uint32_t i = 0; 0 != (proc = r->nth_plugin (i)); ++i) {
1139                 if (!proc->display_to_user ()) {
1140 #ifdef MIXBUS
1141                         boost::shared_ptr<PluginInsert> pi = boost::dynamic_pointer_cast<PluginInsert> (proc);
1142                         if (pi->is_channelstrip ()) // don't skip MB PRE
1143 #endif
1144                         continue;
1145                 }
1146                 int n_controls = 0;
1147                 set<Evoral::Parameter> p = proc->what_can_be_automated ();
1148                 for (set<Evoral::Parameter>::iterator i = p.begin(); i != p.end(); ++i) {
1149                         std::string n = proc->describe_parameter (*i);
1150                         if (n == "hidden") {
1151                                 continue;
1152                         }
1153                         ++n_controls;
1154                 }
1155                 if (n_controls > 0) {
1156                         procs.push_back (i);
1157                 }
1158         }
1159
1160         int n_plugins = procs.size();
1161         int spillwidth = 8;
1162         bool have_well_known_eq = false;
1163         bool have_well_known_comp = false;
1164
1165         // reserve last slot(s) for "well-known"
1166         if (r->eq_band_cnt() > 0) {
1167                 --spillwidth;
1168                 have_well_known_eq = true;
1169         }
1170         if (r->comp_enable_controllable ()) {
1171                 --spillwidth;
1172                 have_well_known_comp = true;
1173         }
1174
1175         if (n_plugins == 0 && !have_well_known_eq && !have_well_known_comp) {
1176                 _ctrls.set_fader_mode (ModeTrack);
1177                 return;
1178         }
1179
1180         set_periodic_display_mode (FP8Strip::PluginSelect);
1181
1182         _plugin_off = std::min (_plugin_off, n_plugins - spillwidth);
1183         _plugin_off = std::max (0, _plugin_off);
1184
1185         uint8_t id = 0;
1186         for (uint32_t i = _plugin_off; ; ++i) {
1187                 if (i >= procs.size()) {
1188                         break;
1189                 }
1190                 boost::shared_ptr<Processor> proc = r->nth_plugin (procs[i]);
1191                 if (!proc) {
1192                         break;
1193                 }
1194                 boost::shared_ptr<PluginInsert> pi = boost::dynamic_pointer_cast<PluginInsert> (proc);
1195                 boost::function<void ()> cb (boost::bind (&FaderPort8::select_plugin, this, procs[i]));
1196
1197                 _ctrls.strip(id).unset_controllables (FP8Strip::CTRL_ALL & ~FP8Strip::CTRL_TEXT & ~FP8Strip::CTRL_SELECT);
1198                 _ctrls.strip(id).set_select_cb (cb);
1199                 _ctrls.strip(id).select_button ().set_color (0x00ff00ff);
1200                 _ctrls.strip(id).select_button ().set_active (true /*proc->enabled()*/);
1201                 _ctrls.strip(id).select_button ().set_blinking (false);
1202                 _ctrls.strip(id).set_text_line (0, proc->name());
1203                 _ctrls.strip(id).set_text_line (1, pi->plugin()->maker());
1204                 _ctrls.strip(id).set_text_line (2, plugintype (pi->type()));
1205                 _ctrls.strip(id).set_text_line (3, "");
1206
1207                 if (++id == spillwidth) {
1208                         break;
1209                 }
1210         }
1211         // clear remaining
1212         for (; id < spillwidth; ++id) {
1213                 _ctrls.strip(id).unset_controllables ();
1214         }
1215
1216         if (have_well_known_comp) {
1217                         assert (id < 8);
1218                  boost::function<void ()> cb (boost::bind (&FaderPort8::select_plugin, this, -2));
1219                  _ctrls.strip(id).unset_controllables (FP8Strip::CTRL_ALL & ~FP8Strip::CTRL_TEXT & ~FP8Strip::CTRL_SELECT);
1220                  _ctrls.strip(id).set_select_cb (cb);
1221                  _ctrls.strip(id).select_button ().set_color (0xffff00ff);
1222                  _ctrls.strip(id).select_button ().set_active (true);
1223                  _ctrls.strip(id).select_button ().set_blinking (false);
1224                  _ctrls.strip(id).set_text_line (0, "Comp");
1225                  _ctrls.strip(id).set_text_line (1, "Built-In");
1226                  _ctrls.strip(id).set_text_line (2, "--");
1227                  _ctrls.strip(id).set_text_line (3, "");
1228                  ++id;
1229         }
1230         if (have_well_known_eq) {
1231                         assert (id < 8);
1232                  boost::function<void ()> cb (boost::bind (&FaderPort8::select_plugin, this, -1));
1233                  _ctrls.strip(id).unset_controllables (FP8Strip::CTRL_ALL & ~FP8Strip::CTRL_TEXT & ~FP8Strip::CTRL_SELECT);
1234                  _ctrls.strip(id).set_select_cb (cb);
1235                  _ctrls.strip(id).select_button ().set_color (0xffff00ff);
1236                  _ctrls.strip(id).select_button ().set_active (true);
1237                  _ctrls.strip(id).select_button ().set_blinking (false);
1238                  _ctrls.strip(id).set_text_line (0, "EQ");
1239                  _ctrls.strip(id).set_text_line (1, "Built-In");
1240                  _ctrls.strip(id).set_text_line (2, "--");
1241                  _ctrls.strip(id).set_text_line (3, "");
1242                  ++id;
1243         }
1244         assert (id == 8);
1245 }
1246
1247 void
1248 FaderPort8::assign_sends ()
1249 {
1250         boost::shared_ptr<Stripable> s = first_selected_stripable();
1251         if (!s) {
1252                 _ctrls.set_fader_mode (ModeTrack);
1253                 return;
1254         }
1255
1256         int n_sends = 0;
1257         while (0 != s->send_level_controllable (n_sends)) {
1258                 ++n_sends;
1259         }
1260         if (n_sends == 0) {
1261                 _ctrls.set_fader_mode (ModeTrack);
1262                 return;
1263         }
1264
1265         drop_ctrl_connections ();
1266         s->DropReferences.connect (processor_connections, MISSING_INVALIDATOR, boost::bind (&FP8Controls::set_fader_mode, &_ctrls, ModeTrack), this);
1267
1268         set_periodic_display_mode (FP8Strip::SendDisplay);
1269
1270         _plugin_off = std::min (_plugin_off, n_sends - 8);
1271         _plugin_off = std::max (0, _plugin_off);
1272
1273         uint8_t id = 0;
1274         int skip = _parameter_off;
1275         for (uint32_t i = _plugin_off; ; ++i) {
1276                 if (skip > 0) {
1277                         --skip;
1278                         continue;
1279                 }
1280                 boost::shared_ptr<AutomationControl> send = s->send_level_controllable (i);
1281                 if (!send) {
1282                         break;
1283                 }
1284
1285                 _ctrls.strip(id).unset_controllables (FP8Strip::CTRL_ALL & ~FP8Strip::CTRL_FADER & ~FP8Strip::CTRL_TEXT0 & ~FP8Strip::CTRL_TEXT1 & ~FP8Strip::CTRL_TEXT3 & ~FP8Strip::CTRL_SELECT);
1286                 _ctrls.strip(id).set_fader_controllable (send);
1287                 _ctrls.strip(id).set_text_line (0, s->send_name (i));
1288                 _ctrls.strip(id).set_mute_controllable (s->send_enable_controllable (i));
1289
1290                 if (++id == 8) {
1291                         break;
1292                 }
1293         }
1294         // clear remaining
1295         for (; id < 8; ++id) {
1296                 _ctrls.strip(id).unset_controllables (FP8Strip::CTRL_ALL & ~FP8Strip::CTRL_TEXT3 & ~FP8Strip::CTRL_SELECT);
1297         }
1298 #ifdef MIXBUS // master-assign on last solo
1299         _ctrls.strip(7).set_solo_controllable (s->master_send_enable_controllable ());
1300 #endif
1301         /* set select buttons */
1302         assign_stripables (true);
1303 }
1304
1305 void
1306 FaderPort8::set_periodic_display_mode (FP8Strip::DisplayMode m)
1307 {
1308         for (uint8_t id = 0; id < 8; ++id) {
1309                 _ctrls.strip(id).set_periodic_display_mode (m);
1310         }
1311 }
1312
1313 void
1314 FaderPort8::assign_strips (bool reset_bank)
1315 {
1316         if (reset_bank) {
1317                 _channel_off = 0;
1318         }
1319
1320         _assigned_strips.clear ();
1321         assigned_stripable_connections.drop_connections ();
1322
1323         FaderMode fadermode = _ctrls.fader_mode ();
1324         switch (fadermode) {
1325                 case ModeTrack:
1326                 case ModePan:
1327                         assign_stripables ();
1328                         gui_track_selection_changed (); // update selection, automation-state
1329                         break;
1330                 case ModePlugins:
1331                         if (_proc_params.size() > 0) {
1332                                 assign_processor_ctrls ();
1333                         } else {
1334                                 spill_plugins ();
1335                         }
1336                         break;
1337                 case ModeSend:
1338                         assign_sends ();
1339                         break;
1340         }
1341 }
1342
1343
1344 void
1345 FaderPort8::drop_ctrl_connections ()
1346 {
1347         _proc_params.clear();
1348         processor_connections.drop_connections ();
1349         _showing_well_known = 0;
1350 }
1351
1352 void
1353 FaderPort8::notify_fader_mode_changed ()
1354 {
1355         FaderMode fadermode = _ctrls.fader_mode ();
1356
1357         boost::shared_ptr<Stripable> s = first_selected_stripable();
1358         if (!s && (fadermode == ModePlugins || fadermode == ModeSend)) {
1359                 _ctrls.set_fader_mode (ModeTrack);
1360                 return;
1361         }
1362
1363         drop_ctrl_connections ();
1364
1365         switch (fadermode) {
1366                 case ModeTrack:
1367                 case ModePan:
1368                         break;
1369                 case ModePlugins:
1370                 case ModeSend:
1371                         _plugin_off = 0;
1372                         _parameter_off = 0;
1373                         // force unset rec-arm button, see also FaderPort8::button_arm
1374                         _ctrls.button (FP8Controls::BtnArm).set_active (false);
1375                         ARMButtonChange (false);
1376                         break;
1377         }
1378         assign_strips (false);
1379         notify_automation_mode_changed ();
1380 }
1381
1382 /* ****************************************************************************
1383  * Assigned Stripable Callbacks
1384  */
1385
1386 void
1387 FaderPort8::notify_stripable_added_or_removed ()
1388 {
1389         /* called by
1390          *  - DropReferences
1391          *  - session->RouteAdded
1392          *  - PresentationInfo::Change
1393          *    - Properties::hidden
1394          *    - Properties::order
1395          */
1396         assign_strips (false);
1397 }
1398
1399 /* functor for FP8Strip's select button */
1400 void
1401 FaderPort8::select_strip (boost::weak_ptr<Stripable> ws)
1402 {
1403         boost::shared_ptr<Stripable> s = ws.lock();
1404         if (!s) {
1405                 return;
1406         }
1407         if (shift_mod ()) {
1408                 if (s->is_selected ()) {
1409                         RemoveStripableFromSelection (s);
1410                 } else {
1411                         SetStripableSelection (s);
1412                 }
1413                 return;
1414         }
1415         if (s->is_selected () && s != first_selected_stripable ()) {
1416                 set_first_selected_stripable (s);
1417                 gui_track_selection_changed ();
1418         } else {
1419                 ToggleStripableSelection (s);
1420         }
1421 }
1422
1423 /* called from static PresentationInfo::Change */
1424 void
1425 FaderPort8::notify_pi_property_changed (const PropertyChange& what_changed)
1426 {
1427         if (what_changed.contains (Properties::hidden)) {
1428                 notify_stripable_added_or_removed ();
1429         }
1430         if (what_changed.contains (Properties::order)) {
1431                 notify_stripable_added_or_removed ();
1432         }
1433         // Properties::selected is handled via StripableSelectionChanged
1434 }
1435
1436 void
1437 FaderPort8::notify_stripable_property_changed (boost::weak_ptr<Stripable> ws, const PropertyChange& what_changed)
1438 {
1439         boost::shared_ptr<Stripable> s = ws.lock();
1440         if (!s) {
1441                 assert (0); // this should not happen
1442                 return;
1443         }
1444         assert (_assigned_strips.find (s) != _assigned_strips.end());
1445         uint8_t id = _assigned_strips[s];
1446
1447         if (what_changed.contains (Properties::color)) {
1448                 _ctrls.strip(id).select_button ().set_color (s->presentation_info ().color());
1449         }
1450
1451         if (what_changed.contains (Properties::name)) {
1452                 switch (_ctrls.fader_mode ()) {
1453                         case ModeSend:
1454                                 _ctrls.strip(id).set_text_line (3, s->name(), true);
1455                                 break;
1456                         case ModeTrack:
1457                         case ModePan:
1458                                 _ctrls.strip(id).set_text_line (0, s->name());
1459                                 break;
1460                         case ModePlugins:
1461                                 assert (0);
1462                                 break;
1463                 }
1464         }
1465 }
1466
1467 void
1468 FaderPort8::gui_track_selection_changed (/*ARDOUR::StripableNotificationListPtr*/)
1469 {
1470         automation_state_connections.drop_connections();
1471
1472         switch (_ctrls.fader_mode ()) {
1473                 case ModePlugins:
1474                         if (_proc_params.size () > 0 && _showing_well_known < 0) {
1475                                 /* w/well-known -> re-assign to new strip */
1476                                 int wk = _showing_well_known;
1477                                 drop_ctrl_connections ();
1478                                 select_plugin (wk);
1479                         }
1480                         return;
1481                 case ModeSend:
1482                         _plugin_off = 0;
1483                         assign_sends ();
1484                         return;
1485                 case ModeTrack:
1486                 case ModePan:
1487                         break;
1488         }
1489
1490         /* update selection lights */
1491         for (StripAssignmentMap::const_iterator i = _assigned_strips.begin(); i != _assigned_strips.end(); ++i) {
1492                 boost::shared_ptr<ARDOUR::Stripable> s = i->first;
1493                 uint8_t id = i->second;
1494                 bool sel = s->is_selected ();
1495                 _ctrls.strip(id).select_button ().set_active (sel);
1496                 _ctrls.strip(id).select_button ().set_blinking (sel && s == first_selected_stripable ());
1497         }
1498
1499         /* track automation-mode of primary selection */
1500         boost::shared_ptr<Stripable> s = first_selected_stripable();
1501         if (s) {
1502                 boost::shared_ptr<AutomationControl> ac;
1503                 ac = s->gain_control();
1504                 if (ac && ac->alist()) {
1505                         ac->alist()->automation_state_changed.connect (automation_state_connections, MISSING_INVALIDATOR, boost::bind (&FaderPort8::notify_automation_mode_changed, this), this);
1506                 }
1507                 ac = s->pan_azimuth_control();
1508                 if (ac && ac->alist()) {
1509                         ac->alist()->automation_state_changed.connect (automation_state_connections, MISSING_INVALIDATOR, boost::bind (&FaderPort8::notify_automation_mode_changed, this), this);
1510                 }
1511         }
1512         /* set lights */
1513         notify_automation_mode_changed ();
1514 }
1515
1516
1517 /* ****************************************************************************
1518  * Banking
1519  */
1520
1521 void
1522 FaderPort8::move_selected_into_view ()
1523 {
1524         boost::shared_ptr<Stripable> selected = first_selected_stripable ();
1525         if (!selected) {
1526                 return;
1527         }
1528
1529         StripableList strips;
1530         filter_stripables (strips);
1531
1532         StripableList::iterator it = std::find (strips.begin(), strips.end(), selected);
1533         if (it == strips.end()) {
1534                 return;
1535         }
1536         int off = std::distance (strips.begin(), it);
1537
1538         if (_channel_off <= off && off < _channel_off + 8) {
1539                 return;
1540         }
1541
1542         if (_channel_off > off) {
1543                 _channel_off = off;
1544         } else {
1545                 _channel_off = off - 7;
1546         }
1547         assign_strips (false);
1548 }
1549
1550 void
1551 FaderPort8::select_prev_next (bool next)
1552 {
1553         StripableList strips;
1554         filter_stripables (strips);
1555
1556         boost::shared_ptr<Stripable> selected = first_selected_stripable ();
1557         if (!selected) {
1558                 if (strips.size() > 0) {
1559                         if (next) {
1560                                 SetStripableSelection (strips.front ());
1561                         } else {
1562                                 SetStripableSelection (strips.back ());
1563                         }
1564                 }
1565                 return;
1566         }
1567
1568         bool found = false;
1569         boost::shared_ptr<Stripable> toselect;
1570         for (StripableList::const_iterator s = strips.begin(); s != strips.end(); ++s) {
1571                 if (*s == selected) {
1572                         if (!next) {
1573                                 found = true;
1574                                 break;
1575                         }
1576                         ++s;
1577                         if (s != strips.end()) {
1578                                 toselect = *s;
1579                                 found = true;
1580                         }
1581                         break;
1582                 }
1583                 if (!next) {
1584                         toselect = *s;
1585                 }
1586         }
1587
1588         if (found && toselect) {
1589                 SetStripableSelection (toselect);
1590         }
1591 }
1592
1593 void
1594 FaderPort8::bank (bool down, bool page)
1595 {
1596         int dt = page ? 8 : 1;
1597         if (down) {
1598                 dt *= -1;
1599         }
1600         _channel_off += dt;
1601         assign_strips (false);
1602 }
1603
1604 void
1605 FaderPort8::bank_param (bool down, bool page)
1606 {
1607         int dt = page ? 8 : 1;
1608         if (down) {
1609                 dt *= -1;
1610         }
1611         switch (_ctrls.fader_mode ()) {
1612                 case ModePlugins:
1613                         if (_proc_params.size() > 0) {
1614                                 _parameter_off += dt;
1615                                 assign_processor_ctrls ();
1616                         } else {
1617                                 _plugin_off += dt;
1618                                 spill_plugins ();
1619                         }
1620                         break;
1621                 case ModeSend:
1622                         _plugin_off += dt;
1623                         assign_sends ();
1624                         break;
1625                 default:
1626                         break;
1627         }
1628 }