change bundling of Push 2 ports so that the implicit connection ports don't show up
[ardour.git] / libs / surfaces / push2 / push2.cc
1 /*
2         Copyright (C) 2016 Paul Davis
3
4         This program is free software; you can redistribute it and/or modify
5         it under the terms of the GNU General Public License as published by
6         the Free Software Foundation; either version 2 of the License, or
7         (at your option) any later version.
8
9         This program is distributed in the hope that it will be useful,
10         but WITHOUT ANY WARRANTY; without even the implied warranty of
11         MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12         GNU General Public License for more details.
13
14         You should have received a copy of the GNU General Public License
15         along with this program; if not, write to the Free Software
16         Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
17 */
18
19 #include <cairomm/context.h>
20 #include <cairomm/surface.h>
21 #include <pangomm/layout.h>
22
23 #include "pbd/compose.h"
24 #include "pbd/convert.h"
25 #include "pbd/debug.h"
26 #include "pbd/failed_constructor.h"
27 #include "pbd/file_utils.h"
28 #include "pbd/search_path.h"
29 #include "pbd/enumwriter.h"
30
31 #include "midi++/parser.h"
32 #include "timecode/time.h"
33 #include "timecode/bbt_time.h"
34
35 #include "ardour/async_midi_port.h"
36 #include "ardour/audioengine.h"
37 #include "ardour/debug.h"
38 #include "ardour/filesystem_paths.h"
39 #include "ardour/midiport_manager.h"
40 #include "ardour/midi_track.h"
41 #include "ardour/midi_port.h"
42 #include "ardour/session.h"
43 #include "ardour/tempo.h"
44
45 #include "push2.h"
46 #include "gui.h"
47
48 using namespace ARDOUR;
49 using namespace std;
50 using namespace PBD;
51 using namespace Glib;
52 using namespace ArdourSurface;
53
54 #include "i18n.h"
55
56 #include "pbd/abstract_ui.cc" // instantiate template
57
58 const int Push2::cols = 960;
59 const int Push2::rows = 160;
60 const int Push2::pixels_per_row = 1024;
61
62 #define ABLETON 0x2982
63 #define PUSH2   0x1967
64
65 __attribute__((constructor)) static void
66 register_enums ()
67 {
68         EnumWriter& enum_writer (EnumWriter::instance());
69         vector<int> i;
70         vector<string> s;
71
72         MusicalMode::Type mode;
73
74 #define REGISTER(e) enum_writer.register_distinct (typeid(e).name(), i, s); i.clear(); s.clear()
75 #define REGISTER_CLASS_ENUM(t,e) i.push_back (t::e); s.push_back (#e)
76
77         REGISTER_CLASS_ENUM (MusicalMode,Dorian);
78         REGISTER_CLASS_ENUM (MusicalMode, IonianMajor);
79         REGISTER_CLASS_ENUM (MusicalMode, Minor);
80         REGISTER_CLASS_ENUM (MusicalMode, HarmonicMinor);
81         REGISTER_CLASS_ENUM (MusicalMode, MelodicMinorAscending);
82         REGISTER_CLASS_ENUM (MusicalMode, MelodicMinorDescending);
83         REGISTER_CLASS_ENUM (MusicalMode, Phrygian);
84         REGISTER_CLASS_ENUM (MusicalMode, Lydian);
85         REGISTER_CLASS_ENUM (MusicalMode, Mixolydian);
86         REGISTER_CLASS_ENUM (MusicalMode, Aeolian);
87         REGISTER_CLASS_ENUM (MusicalMode, Locrian);
88         REGISTER_CLASS_ENUM (MusicalMode, PentatonicMajor);
89         REGISTER_CLASS_ENUM (MusicalMode, PentatonicMinor);
90         REGISTER_CLASS_ENUM (MusicalMode, Chromatic);
91         REGISTER_CLASS_ENUM (MusicalMode, BluesScale);
92         REGISTER_CLASS_ENUM (MusicalMode, NeapolitanMinor);
93         REGISTER_CLASS_ENUM (MusicalMode, NeapolitanMajor);
94         REGISTER_CLASS_ENUM (MusicalMode, Oriental);
95         REGISTER_CLASS_ENUM (MusicalMode, DoubleHarmonic);
96         REGISTER_CLASS_ENUM (MusicalMode, Enigmatic);
97         REGISTER_CLASS_ENUM (MusicalMode, Hirajoshi);
98         REGISTER_CLASS_ENUM (MusicalMode, HungarianMinor);
99         REGISTER_CLASS_ENUM (MusicalMode, HungarianMajor);
100         REGISTER_CLASS_ENUM (MusicalMode, Kumoi);
101         REGISTER_CLASS_ENUM (MusicalMode, Iwato);
102         REGISTER_CLASS_ENUM (MusicalMode, Hindu);
103         REGISTER_CLASS_ENUM (MusicalMode, Spanish8Tone);
104         REGISTER_CLASS_ENUM (MusicalMode, Pelog);
105         REGISTER_CLASS_ENUM (MusicalMode, HungarianGypsy);
106         REGISTER_CLASS_ENUM (MusicalMode, Overtone);
107         REGISTER_CLASS_ENUM (MusicalMode, LeadingWholeTone);
108         REGISTER_CLASS_ENUM (MusicalMode, Arabian);
109         REGISTER_CLASS_ENUM (MusicalMode, Balinese);
110         REGISTER_CLASS_ENUM (MusicalMode, Gypsy);
111         REGISTER_CLASS_ENUM (MusicalMode, Mohammedan);
112         REGISTER_CLASS_ENUM (MusicalMode, Javanese);
113         REGISTER_CLASS_ENUM (MusicalMode, Persian);
114         REGISTER_CLASS_ENUM (MusicalMode, Algerian);
115         REGISTER (mode);
116 }
117
118 Push2::Push2 (ARDOUR::Session& s)
119         : ControlProtocol (s, string (X_("Ableton Push 2")))
120         , AbstractUI<Push2Request> (name())
121         , handle (0)
122         , device_buffer (0)
123         , frame_buffer (Cairo::ImageSurface::create (Cairo::FORMAT_ARGB32, cols, rows))
124         , modifier_state (None)
125         , splash_start (0)
126         , bank_start (0)
127         , connection_state (ConnectionState (0))
128         , gui (0)
129         , _mode (MusicalMode::IonianMajor)
130         , _scale_root (0)
131         , _root_octave (3)
132         , _in_key (true)
133         , octave_shift (0)
134 {
135         context = Cairo::Context::create (frame_buffer);
136         tc_clock_layout = Pango::Layout::create (context);
137         bbt_clock_layout = Pango::Layout::create (context);
138
139         Pango::FontDescription fd ("Sans Bold 24");
140         tc_clock_layout->set_font_description (fd);
141         bbt_clock_layout->set_font_description (fd);
142
143         Pango::FontDescription fd2 ("Sans 10");
144         for (int n = 0; n < 8; ++n) {
145                 upper_layout[n] = Pango::Layout::create (context);
146                 upper_layout[n]->set_font_description (fd2);
147                 upper_layout[n]->set_text ("solo");
148                 lower_layout[n] = Pango::Layout::create (context);
149                 lower_layout[n]->set_font_description (fd2);
150                 lower_layout[n]->set_text ("mute");
151         }
152
153         Pango::FontDescription fd3 ("Sans Bold 10");
154         for (int n = 0; n < 8; ++n) {
155                 mid_layout[n] = Pango::Layout::create (context);
156                 mid_layout[n]->set_font_description (fd3);
157         }
158
159         build_pad_table ();
160         build_maps ();
161
162         if (open ()) {
163                 throw failed_constructor ();
164         }
165
166         StripableSelectionChanged.connect (selection_connection, MISSING_INVALIDATOR, boost::bind (&Push2::stripable_selection_change, this, _1), this);
167
168         /* catch arrival and departure of Push2 itself */
169         ARDOUR::AudioEngine::instance()->PortRegisteredOrUnregistered.connect (port_reg_connection, MISSING_INVALIDATOR, boost::bind (&Push2::port_registration_handler, this), this);
170
171         /* Catch port connections and disconnections */
172         ARDOUR::AudioEngine::instance()->PortConnectedOrDisconnected.connect (port_connection, MISSING_INVALIDATOR, boost::bind (&Push2::connection_handler, this, _1, _2, _3, _4, _5), this);
173
174         /* ports might already be there */
175         port_registration_handler ();
176 }
177
178 Push2::~Push2 ()
179 {
180         stop ();
181 }
182
183 void
184 Push2::port_registration_handler ()
185 {
186         if (_async_in->connected() && _async_out->connected()) {
187                 /* don't waste cycles here */
188                 return;
189         }
190
191         string input_port_name = X_("Ableton Push 2 MIDI 1 in");
192         string output_port_name = X_("Ableton Push 2 MIDI 1 out");
193         vector<string> in;
194         vector<string> out;
195
196         AudioEngine::instance()->get_ports (string_compose (".*%1", input_port_name), DataType::MIDI, PortFlags (IsPhysical|IsOutput|ControlOnly), in);
197         AudioEngine::instance()->get_ports (string_compose (".*%1", output_port_name), DataType::MIDI, PortFlags (IsPhysical|IsInput|ControlOnly), out);
198
199         if (!in.empty() && !out.empty()) {
200                 cerr << "Push2: both ports found\n";
201                 cerr << "\tconnecting to " << in.front() <<  " + " << out.front() << endl;
202                 if (!_async_in->connected()) {
203                         AudioEngine::instance()->connect (_async_in->name(), in.front());
204                 }
205                 if (!_async_out->connected()) {
206                         AudioEngine::instance()->connect (_async_out->name(), out.front());
207                 }
208         }
209 }
210
211 int
212 Push2::open ()
213 {
214         int err;
215
216         if (handle) {
217                 /* already open */
218                 return 0;
219         }
220
221         if ((handle = libusb_open_device_with_vid_pid (NULL, ABLETON, PUSH2)) == 0) {
222                 return -1;
223         }
224
225         if ((err = libusb_claim_interface (handle, 0x00))) {
226                 return -1;
227         }
228
229         device_frame_buffer = new uint16_t[rows*pixels_per_row];
230
231         memset (device_frame_buffer, 0, sizeof (uint16_t) * rows * pixels_per_row);
232
233         frame_header[0] = 0xef;
234         frame_header[1] = 0xcd;
235         frame_header[2] = 0xab;
236         frame_header[3] = 0x89;
237         memset (&frame_header[4], 0, 12);
238
239         /* setup ports */
240
241         _async_in  = AudioEngine::instance()->register_input_port (DataType::MIDI, X_("Push 2 in"), true);
242         _async_out = AudioEngine::instance()->register_output_port (DataType::MIDI, X_("Push 2 out"), true);
243
244         if (_async_in == 0 || _async_out == 0) {
245                 return -1;
246         }
247
248         /* We do not add our ports to the input/output bundles because we don't
249          * want users wiring them by hand. They could use JACK tools if they
250          * really insist on that.
251          */
252
253         _input_port = boost::dynamic_pointer_cast<AsyncMIDIPort>(_async_in).get();
254         _output_port = boost::dynamic_pointer_cast<AsyncMIDIPort>(_async_out).get();
255
256         /* Create a shadow port where, depending on the state of the surface,
257          * we will make pad note on/off events appear. The surface code will
258          * automatically this port to the first selected MIDI track.
259          */
260
261         boost::dynamic_pointer_cast<AsyncMIDIPort>(_async_in)->add_shadow_port (string_compose (_("%1 Pads"), X_("Push 2")), boost::bind (&Push2::pad_filter, this, _1, _2));
262         boost::shared_ptr<MidiPort> shadow_port = boost::dynamic_pointer_cast<AsyncMIDIPort>(_async_in)->shadow_port();
263
264         if (shadow_port) {
265
266                 _output_bundle.reset (new ARDOUR::Bundle (_("Push 2 Pads"), false));
267
268                 _output_bundle->add_channel (
269                         shadow_port->name(),
270                         ARDOUR::DataType::MIDI,
271                         session->engine().make_port_name_non_relative (shadow_port->name())
272                         );
273         }
274
275         session->BundleAddedOrRemoved ();
276
277         connect_to_parser ();
278
279         return 0;
280 }
281
282 list<boost::shared_ptr<ARDOUR::Bundle> >
283 Push2::bundles ()
284 {
285         list<boost::shared_ptr<ARDOUR::Bundle> > b;
286
287         if (_output_bundle) {
288                 b.push_back (_output_bundle);
289         }
290
291         return b;
292 }
293
294 int
295 Push2::close ()
296 {
297         init_buttons (false);
298
299         /* wait for button data to be flushed */
300         AsyncMIDIPort* asp;
301         asp = dynamic_cast<AsyncMIDIPort*> (_output_port);
302         asp->drain (10000, 500000);
303
304         AudioEngine::instance()->unregister_port (_async_in);
305         AudioEngine::instance()->unregister_port (_async_out);
306
307         _async_in.reset ((ARDOUR::Port*) 0);
308         _async_out.reset ((ARDOUR::Port*) 0);
309         _input_port = 0;
310         _output_port = 0;
311
312         vblank_connection.disconnect ();
313         periodic_connection.disconnect ();
314         session_connections.drop_connections ();
315         stripable_connections.drop_connections ();
316
317         if (handle) {
318                 libusb_release_interface (handle, 0x00);
319                 libusb_close (handle);
320                 handle = 0;
321         }
322
323         for (int n = 0; n < 8; ++n) {
324                 stripable[n].reset ();
325         }
326
327         delete [] device_frame_buffer;
328         device_frame_buffer = 0;
329
330         return 0;
331 }
332
333 void
334 Push2::init_buttons (bool startup)
335 {
336         /* This is a list of buttons that we want lit because they do something
337            in ardour related (loosely, sometimes) to their illuminated label.
338         */
339
340         ButtonID buttons[] = { Mute, Solo, Master, Up, Right, Left, Down, Note, Session, Mix, AddTrack, Delete, Undo,
341                                Metronome, Shift, Select, Play, RecordEnable, Automate, Repeat, Note, Session, DoubleLoop,
342                                Quantize, Duplicate, Browse, PageRight, PageLeft, OctaveUp, OctaveDown
343         };
344
345         for (size_t n = 0; n < sizeof (buttons) / sizeof (buttons[0]); ++n) {
346                 Button* b = id_button_map[buttons[n]];
347
348                 if (startup) {
349                         b->set_color (LED::White);
350                 } else {
351                         b->set_color (LED::Black);
352                 }
353                 b->set_state (LED::OneShot24th);
354                 write (b->state_msg());
355         }
356
357         /* Strip buttons should all be off (black) by default. They will change
358          * color to reflect various conditions
359          */
360
361         ButtonID strip_buttons[] = { Upper1, Upper2, Upper3, Upper4, Upper5, Upper6, Upper7, Upper8,
362                                      Lower1, Lower2, Lower3, Lower4, Lower5, Lower6, Lower7, Lower8, };
363
364         for (size_t n = 0; n < sizeof (strip_buttons) / sizeof (strip_buttons[0]); ++n) {
365                 Button* b = id_button_map[strip_buttons[n]];
366
367                 b->set_color (LED::Black);
368                 b->set_state (LED::OneShot24th);
369                 write (b->state_msg());
370         }
371
372         if (startup) {
373
374                 /* all other buttons are off (black) */
375
376                 ButtonID off_buttons[] = { TapTempo, Setup, User, Stop, Convert, New, FixedLength,
377                                            Fwd32ndT, Fwd32nd, Fwd16thT, Fwd16th, Fwd8thT, Fwd8th, Fwd4trT, Fwd4tr,
378                                            Accent, Scale, Layout, Note, Session,  };
379
380                 for (size_t n = 0; n < sizeof (off_buttons) / sizeof (off_buttons[0]); ++n) {
381                         Button* b = id_button_map[off_buttons[n]];
382
383                         b->set_color (LED::Black);
384                         b->set_state (LED::OneShot24th);
385                         write (b->state_msg());
386                 }
387         }
388
389         if (!startup) {
390                 for (NNPadMap::iterator pi = nn_pad_map.begin(); pi != nn_pad_map.end(); ++pi) {
391                         Pad* pad = pi->second;
392
393                         pad->set_color (LED::Black);
394                         pad->set_state (LED::OneShot24th);
395                         write (pad->state_msg());
396                 }
397         }
398 }
399
400 bool
401 Push2::probe ()
402 {
403         libusb_device_handle *h;
404         libusb_init (NULL);
405
406         if ((h = libusb_open_device_with_vid_pid (NULL, ABLETON, PUSH2)) == 0) {
407                 DEBUG_TRACE (DEBUG::Push2, "no Push2 device found\n");
408                 return false;
409         }
410
411         libusb_close (h);
412         DEBUG_TRACE (DEBUG::Push2, "Push2 device located\n");
413         return true;
414 }
415
416 void*
417 Push2::request_factory (uint32_t num_requests)
418 {
419         /* AbstractUI<T>::request_buffer_factory() is a template method only
420            instantiated in this source module. To provide something visible for
421            use in the interface/descriptor, we have this static method that is
422            template-free.
423         */
424         return request_buffer_factory (num_requests);
425 }
426
427 void
428 Push2::do_request (Push2Request * req)
429 {
430         DEBUG_TRACE (DEBUG::Push2, string_compose ("doing request type %1\n", req->type));
431         if (req->type == CallSlot) {
432
433                 call_slot (MISSING_INVALIDATOR, req->the_slot);
434
435         } else if (req->type == Quit) {
436
437                 stop ();
438         }
439 }
440
441 int
442 Push2::stop ()
443 {
444         BaseUI::quit ();
445         close ();
446         return 0;
447 }
448
449 /** render host-side frame buffer (a Cairo ImageSurface) to the current
450  * device-side frame buffer. The device frame buffer will be pushed to the
451  * device on the next call to vblank()
452  */
453
454 int
455 Push2::blit_to_device_frame_buffer ()
456 {
457         /* ensure that all drawing has been done before we fetch pixel data */
458
459         frame_buffer->flush ();
460
461         const int stride = 3840; /* bytes per row for Cairo::FORMAT_ARGB32 */
462         const uint8_t* data = frame_buffer->get_data ();
463
464         /* fill frame buffer (320kB) */
465
466         uint16_t* fb = (uint16_t*) device_frame_buffer;
467
468         for (int row = 0; row < rows; ++row) {
469
470                 const uint8_t* dp = data + row * stride;
471
472                 for (int col = 0; col < cols; ++col) {
473
474                         /* fetch r, g, b (range 0..255). Ignore alpha */
475
476                         const int r = (*((const uint32_t*)dp) >> 16) & 0xff;
477                         const int g = (*((const uint32_t*)dp) >> 8) & 0xff;
478                         const int b = *((const uint32_t*)dp) & 0xff;
479
480                         /* convert to 5 bits, 6 bits, 5 bits, respectively */
481                         /* generate 16 bit BGB565 value */
482
483                         *fb++ = (r >> 3) | ((g & 0xfc) << 3) | ((b & 0xf8) << 8);
484
485                         /* the push2 docs state that we should xor the pixel
486                          * data. Doing so doesn't work correctly, and not doing
487                          * so seems to work fine (colors roughly match intended
488                          * values).
489                          */
490
491                         dp += 4;
492                 }
493
494                 /* skip 128 bytes to next line. This is filler, used to avoid line borders occuring in the middle of 512
495                    byte USB buffers
496                 */
497
498                 fb += 64; /* 128 bytes = 64 int16_t */
499         }
500
501         return 0;
502 }
503
504 bool
505 Push2::redraw ()
506 {
507         string tc_clock_text;
508         string bbt_clock_text;
509
510         if (splash_start) {
511                 if (get_microseconds() - splash_start > 4000000) {
512                         splash_start = 0;
513                 } else {
514                         return false;
515                 }
516         }
517
518         if (session) {
519                 framepos_t audible = session->audible_frame();
520                 Timecode::Time TC;
521                 bool negative = false;
522
523                 if (audible < 0) {
524                         audible = -audible;
525                         negative = true;
526                 }
527
528                 session->timecode_time (audible, TC);
529
530                 TC.negative = TC.negative || negative;
531
532                 tc_clock_text = Timecode::timecode_format_time(TC);
533
534                 Timecode::BBT_Time bbt = session->tempo_map().bbt_at_frame (audible);
535                 char buf[16];
536
537 #define BBT_BAR_CHAR "|"
538
539                 if (negative) {
540                         snprintf (buf, sizeof (buf), "-%03" PRIu32 BBT_BAR_CHAR "%02" PRIu32 BBT_BAR_CHAR "%04" PRIu32,
541                                   bbt.bars, bbt.beats, bbt.ticks);
542                 } else {
543                         snprintf (buf, sizeof (buf), " %03" PRIu32 BBT_BAR_CHAR "%02" PRIu32 BBT_BAR_CHAR "%04" PRIu32,
544                                   bbt.bars, bbt.beats, bbt.ticks);
545                 }
546
547                 bbt_clock_text = buf;
548         }
549
550         bool dirty = false;
551
552         if (tc_clock_text != tc_clock_layout->get_text()) {
553                 dirty = true;
554                 tc_clock_layout->set_text (tc_clock_text);
555         }
556
557         if (bbt_clock_text != tc_clock_layout->get_text()) {
558                 dirty = true;
559                 bbt_clock_layout->set_text (bbt_clock_text);
560         }
561
562         string mid_text;
563
564         for (int n = 0; n < 8; ++n) {
565                 if (stripable[n]) {
566                         mid_text = short_version (stripable[n]->name(), 10);
567                         if (mid_text != mid_layout[n]->get_text()) {
568                                 mid_layout[n]->set_text (mid_text);
569                                 dirty = true;
570                         }
571                 }
572         }
573
574         if (!dirty) {
575                 return false;
576         }
577
578         context->set_source_rgb (0.764, 0.882, 0.882);
579         context->rectangle (0, 0, 960, 160);
580         context->fill ();
581         context->set_source_rgb (0.23, 0.0, 0.349);
582         context->move_to (650, 25);
583         tc_clock_layout->update_from_cairo_context (context);
584         tc_clock_layout->show_in_cairo_context (context);
585         context->move_to (650, 60);
586         bbt_clock_layout->update_from_cairo_context (context);
587         bbt_clock_layout->show_in_cairo_context (context);
588
589         for (int n = 0; n < 8; ++n) {
590                 context->move_to (10 + (n*120), 2);
591                 upper_layout[n]->update_from_cairo_context (context);
592                 upper_layout[n]->show_in_cairo_context (context);
593         }
594
595         for (int n = 0; n < 8; ++n) {
596                 context->move_to (10 + (n*120), 140);
597                 lower_layout[n]->update_from_cairo_context (context);
598                 lower_layout[n]->show_in_cairo_context (context);
599         }
600
601         for (int n = 0; n < 8; ++n) {
602                 if (stripable[n] && stripable[n]->presentation_info().selected()) {
603                         context->rectangle (10 + (n*120) - 5, 115, 120, 22);
604                         context->set_source_rgb (1.0, 0.737, 0.172);
605                         context->fill();
606                 }
607                 context->set_source_rgb (0.0, 0.0, 0.0);
608                 context->move_to (10 + (n*120), 120);
609                 mid_layout[n]->update_from_cairo_context (context);
610                 mid_layout[n]->show_in_cairo_context (context);
611         }
612
613         /* render clock */
614         /* render foo */
615         /* render bar */
616
617         return true;
618 }
619
620 bool
621 Push2::vblank ()
622 {
623         int transferred = 0;
624         const int timeout_msecs = 1000;
625         int err;
626
627         if ((err = libusb_bulk_transfer (handle, 0x01, frame_header, sizeof (frame_header), &transferred, timeout_msecs))) {
628                 return false;
629         }
630
631         if (redraw()) {
632                 /* things changed */
633                 blit_to_device_frame_buffer ();
634         }
635
636         if ((err = libusb_bulk_transfer (handle, 0x01, (uint8_t*) device_frame_buffer , 2 * rows * pixels_per_row, &transferred, timeout_msecs))) {
637                 return false;
638         }
639
640         return true;
641 }
642
643 int
644 Push2::set_active (bool yn)
645 {
646         DEBUG_TRACE (DEBUG::Push2, string_compose("Push2Protocol::set_active init with yn: '%1'\n", yn));
647
648         if (yn == active()) {
649                 return 0;
650         }
651
652         if (yn) {
653
654                 /* start event loop */
655
656                 BaseUI::run ();
657
658                 if (open ()) {
659                         DEBUG_TRACE (DEBUG::Push2, "device open failed\n");
660                         close ();
661                         return -1;
662                 }
663
664                 /* Connect input port to event loop */
665
666                 AsyncMIDIPort* asp;
667
668                 asp = dynamic_cast<AsyncMIDIPort*> (_input_port);
669                 asp->xthread().set_receive_handler (sigc::bind (sigc::mem_fun (this, &Push2::midi_input_handler), _input_port));
670                 asp->xthread().attach (main_loop()->get_context());
671
672                 connect_session_signals ();
673
674                 /* set up periodic task used to push a frame buffer to the
675                  * device (25fps). The device can handle 60fps, but we don't
676                  * need that frame rate.
677                  */
678
679                 Glib::RefPtr<Glib::TimeoutSource> vblank_timeout = Glib::TimeoutSource::create (40); // milliseconds
680                 vblank_connection = vblank_timeout->connect (sigc::mem_fun (*this, &Push2::vblank));
681                 vblank_timeout->attach (main_loop()->get_context());
682
683
684                 Glib::RefPtr<Glib::TimeoutSource> periodic_timeout = Glib::TimeoutSource::create (1000); // milliseconds
685                 periodic_connection = periodic_timeout->connect (sigc::mem_fun (*this, &Push2::periodic));
686                 periodic_timeout->attach (main_loop()->get_context());
687
688                 init_buttons (true);
689                 init_touch_strip ();
690                 set_pad_scale (_scale_root, _root_octave, _mode, _in_key);
691                 switch_bank (0);
692                 splash ();
693
694         } else {
695
696                 stop ();
697
698         }
699
700         ControlProtocol::set_active (yn);
701
702         DEBUG_TRACE (DEBUG::Push2, string_compose("Push2Protocol::set_active done with yn: '%1'\n", yn));
703
704         return 0;
705 }
706
707 void
708 Push2::init_touch_strip ()
709 {
710         MidiByteArray msg (9, 0xf0, 0x00, 0x21, 0x1d, 0x01, 0x01, 0x17, 0x00, 0xf7);
711         /* flags are the final byte (ignore end-of-sysex */
712
713         /* show bar, not point
714            autoreturn to center
715            bar starts at center
716         */
717         msg[7] = (1<<4) | (1<<5) | (1<<6);
718         write (msg);
719 }
720
721 void
722 Push2::write (const MidiByteArray& data)
723 {
724         /* immediate delivery */
725         _output_port->write (&data[0], data.size(), 0);
726 }
727
728 bool
729 Push2::midi_input_handler (IOCondition ioc, MIDI::Port* port)
730 {
731         if (ioc & ~IO_IN) {
732                 DEBUG_TRACE (DEBUG::Push2, "MIDI port closed\n");
733                 return false;
734         }
735
736         if (ioc & IO_IN) {
737
738                 // DEBUG_TRACE (DEBUG::Push2, string_compose ("something happend on  %1\n", port->name()));
739
740                 AsyncMIDIPort* asp = dynamic_cast<AsyncMIDIPort*>(port);
741                 if (asp) {
742                         asp->clear ();
743                 }
744
745                 //DEBUG_TRACE (DEBUG::Push2, string_compose ("data available on %1\n", port->name()));
746                 framepos_t now = AudioEngine::instance()->sample_time();
747                 port->parse (now);
748         }
749
750         return true;
751 }
752
753 bool
754 Push2::periodic ()
755 {
756         return true;
757 }
758
759 void
760 Push2::connect_to_parser ()
761 {
762         DEBUG_TRACE (DEBUG::Push2, string_compose ("Connecting to signals on port %2\n", _input_port->name()));
763
764         MIDI::Parser* p = _input_port->parser();
765
766         /* Incoming sysex */
767         p->sysex.connect_same_thread (*this, boost::bind (&Push2::handle_midi_sysex, this, _1, _2, _3));
768         /* V-Pot messages are Controller */
769         p->controller.connect_same_thread (*this, boost::bind (&Push2::handle_midi_controller_message, this, _1, _2));
770         /* Button messages are NoteOn */
771         p->note_on.connect_same_thread (*this, boost::bind (&Push2::handle_midi_note_on_message, this, _1, _2));
772         /* Button messages are NoteOn but libmidi++ sends note-on w/velocity = 0 as note-off so catch them too */
773         p->note_off.connect_same_thread (*this, boost::bind (&Push2::handle_midi_note_on_message, this, _1, _2));
774         /* Fader messages are Pitchbend */
775         p->channel_pitchbend[0].connect_same_thread (*this, boost::bind (&Push2::handle_midi_pitchbend_message, this, _1, _2));
776 }
777
778 void
779 Push2::handle_midi_sysex (MIDI::Parser&, MIDI::byte* raw_bytes, size_t sz)
780 {
781         DEBUG_TRACE (DEBUG::Push2, string_compose ("Sysex, %1 bytes\n", sz));
782 }
783
784 void
785 Push2::handle_midi_controller_message (MIDI::Parser&, MIDI::EventTwoBytes* ev)
786 {
787         DEBUG_TRACE (DEBUG::Push2, string_compose ("CC %1 (value %2)\n", (int) ev->controller_number, (int) ev->value));
788
789         CCButtonMap::iterator b = cc_button_map.find (ev->controller_number);
790
791         if (ev->value) {
792                 /* any press cancels any pending long press timeouts */
793                 for (set<ButtonID>::iterator x = buttons_down.begin(); x != buttons_down.end(); ++x) {
794                         Button* bb = id_button_map[*x];
795                         bb->timeout_connection.disconnect ();
796                 }
797         }
798
799         if (b != cc_button_map.end()) {
800
801                 Button* button = b->second;
802
803                 if (ev->value) {
804                         buttons_down.insert (button->id);
805                         start_press_timeout (*button, button->id);
806                 } else {
807                         buttons_down.erase (button->id);
808                         button->timeout_connection.disconnect ();
809                 }
810
811
812                 set<ButtonID>::iterator c = consumed.find (button->id);
813
814                 if (c == consumed.end()) {
815                         if (ev->value == 0) {
816                                 (this->*button->release_method)();
817                         } else {
818                                 (this->*button->press_method)();
819                         }
820                 } else {
821                         DEBUG_TRACE (DEBUG::Push2, "button was consumed, ignored\n");
822                         consumed.erase (c);
823                 }
824
825         } else {
826
827                 /* encoder/vpot */
828
829                 int delta = ev->value;
830
831                 if (delta > 63) {
832                         delta = -(128 - delta);
833                 }
834
835                 switch (ev->controller_number) {
836                 case 71:
837                         strip_vpot (0, delta);
838                         break;
839                 case 72:
840                         strip_vpot (1, delta);
841                         break;
842                 case 73:
843                         strip_vpot (2, delta);
844                         break;
845                 case 74:
846                         strip_vpot (3, delta);
847                         break;
848                 case 75:
849                         strip_vpot (4, delta);
850                         break;
851                 case 76:
852                         strip_vpot (5, delta);
853                         break;
854                 case 77:
855                         strip_vpot (6, delta);
856                         break;
857                 case 78:
858                         strip_vpot (7, delta);
859                         break;
860
861                         /* left side pair */
862                 case 14:
863                         strip_vpot (8, delta);
864                         break;
865                 case 15:
866                         other_vpot (1, delta);
867                         break;
868
869                         /* right side */
870                 case 79:
871                         other_vpot (2, delta);
872                         break;
873                 }
874         }
875 }
876
877 void
878 Push2::handle_midi_note_on_message (MIDI::Parser& parser, MIDI::EventTwoBytes* ev)
879 {
880         DEBUG_TRACE (DEBUG::Push2, string_compose ("Note On %1 (velocity %2)\n", (int) ev->note_number, (int) ev->velocity));
881
882         if (ev->velocity == 0) {
883                 handle_midi_note_off_message (parser, ev);
884                 return;
885         }
886
887         switch (ev->note_number) {
888         case 0:
889                 strip_vpot_touch (0, ev->velocity > 64);
890                 break;
891         case 1:
892                 strip_vpot_touch (1, ev->velocity > 64);
893                 break;
894         case 2:
895                 strip_vpot_touch (2, ev->velocity > 64);
896                 break;
897         case 3:
898                 strip_vpot_touch (3, ev->velocity > 64);
899                 break;
900         case 4:
901                 strip_vpot_touch (4, ev->velocity > 64);
902                 break;
903         case 5:
904                 strip_vpot_touch (5, ev->velocity > 64);
905                 break;
906         case 6:
907                 strip_vpot_touch (6, ev->velocity > 64);
908                 break;
909         case 7:
910                 strip_vpot_touch (7, ev->velocity > 64);
911                 break;
912
913                 /* left side */
914         case 10:
915                 other_vpot_touch (0, ev->velocity > 64);
916                 break;
917         case 9:
918                 other_vpot_touch (1, ev->velocity > 64);
919                 break;
920
921                 /* right side */
922         case 8:
923                 other_vpot_touch (3, ev->velocity > 64);
924                 break;
925
926                 /* touch strip */
927         case 12:
928                 if (ev->velocity < 64) {
929                         transport_stop ();
930                 }
931                 break;
932         }
933
934         if (ev->note_number < 11) {
935                 return;
936         }
937
938         /* Pad */
939
940         NNPadMap::iterator pi = nn_pad_map.find (ev->note_number);
941
942         if (pi == nn_pad_map.end()) {
943                 return;
944         }
945
946         Pad* pad = pi->second;
947
948         if (pad->do_when_pressed == Pad::FlashOn) {
949                 pad->set_color (LED::White);
950                 pad->set_state (LED::OneShot24th);
951                 write (pad->state_msg());
952         } else if (pad->do_when_pressed == Pad::FlashOff) {
953                 pad->set_color (LED::Black);
954                 pad->set_state (LED::OneShot24th);
955                 write (pad->state_msg());
956         }
957 }
958
959 void
960 Push2::handle_midi_note_off_message (MIDI::Parser&, MIDI::EventTwoBytes* ev)
961 {
962         DEBUG_TRACE (DEBUG::Push2, string_compose ("Note Off %1 (velocity %2)\n", (int) ev->note_number, (int) ev->velocity));
963
964         if (ev->note_number < 11) {
965                 /* theoretically related to encoder touch start/end, but
966                  * actually they send note on with two different velocity
967                  * values (127 & 64).
968                  */
969                 return;
970         }
971
972         NNPadMap::iterator pi = nn_pad_map.find (ev->note_number);
973
974         if (pi == nn_pad_map.end()) {
975                 return;
976         }
977
978         Pad* pad = pi->second;
979
980         if (pad->do_when_pressed == Pad::FlashOn) {
981                 pad->set_color (LED::Black);
982                 pad->set_state (LED::OneShot24th);
983                 write (pad->state_msg());
984         } else if (pad->do_when_pressed == Pad::FlashOff) {
985                 pad->set_color (pad->perma_color);
986                 pad->set_state (LED::OneShot24th);
987                 write (pad->state_msg());
988         }
989 }
990
991 void
992 Push2::handle_midi_pitchbend_message (MIDI::Parser&, MIDI::pitchbend_t pb)
993 {
994         if (!session) {
995                 return;
996         }
997
998         float speed;
999
1000         /* range of +1 .. -1 */
1001         speed = ((int32_t) pb - 8192) / 8192.0;
1002         /* convert to range of +3 .. -3 */
1003         session->request_transport_speed (speed * 3.0);
1004 }
1005
1006 void
1007 Push2::thread_init ()
1008 {
1009         struct sched_param rtparam;
1010
1011         pthread_set_name (event_loop_name().c_str());
1012
1013         PBD::notify_event_loops_about_thread_creation (pthread_self(), event_loop_name(), 2048);
1014         ARDOUR::SessionEvent::create_per_thread_pool (event_loop_name(), 128);
1015
1016         memset (&rtparam, 0, sizeof (rtparam));
1017         rtparam.sched_priority = 9; /* XXX should be relative to audio (JACK) thread */
1018
1019         if (pthread_setschedparam (pthread_self(), SCHED_FIFO, &rtparam) != 0) {
1020                 // do we care? not particularly.
1021         }
1022 }
1023
1024 void
1025 Push2::connect_session_signals()
1026 {
1027         // receive routes added
1028         //session->RouteAdded.connect(session_connections, MISSING_INVALIDATOR, boost::bind (&MackieControlProtocol::notify_routes_added, this, _1), this);
1029         // receive VCAs added
1030         //session->vca_manager().VCAAdded.connect(session_connections, MISSING_INVALIDATOR, boost::bind (&Push2::notify_vca_added, this, _1), this);
1031
1032         // receive record state toggled
1033         session->RecordStateChanged.connect(session_connections, MISSING_INVALIDATOR, boost::bind (&Push2::notify_record_state_changed, this), this);
1034         // receive transport state changed
1035         session->TransportStateChange.connect(session_connections, MISSING_INVALIDATOR, boost::bind (&Push2::notify_transport_state_changed, this), this);
1036         session->TransportLooped.connect (session_connections, MISSING_INVALIDATOR, boost::bind (&Push2::notify_loop_state_changed, this), this);
1037         // receive punch-in and punch-out
1038         Config->ParameterChanged.connect(session_connections, MISSING_INVALIDATOR, boost::bind (&Push2::notify_parameter_changed, this, _1), this);
1039         session->config.ParameterChanged.connect (session_connections, MISSING_INVALIDATOR, boost::bind (&Push2::notify_parameter_changed, this, _1), this);
1040         // receive rude solo changed
1041         session->SoloActive.connect(session_connections, MISSING_INVALIDATOR, boost::bind (&Push2::notify_solo_active_changed, this, _1), this);
1042 }
1043
1044 void
1045 Push2::notify_record_state_changed ()
1046 {
1047         IDButtonMap::iterator b = id_button_map.find (RecordEnable);
1048
1049         if (b == id_button_map.end()) {
1050                 return;
1051         }
1052
1053         switch (session->record_status ()) {
1054         case Session::Disabled:
1055                 b->second->set_color (LED::White);
1056                 b->second->set_state (LED::NoTransition);
1057                 break;
1058         case Session::Enabled:
1059                 b->second->set_color (LED::Red);
1060                 b->second->set_state (LED::Blinking4th);
1061                 break;
1062         case Session::Recording:
1063                 b->second->set_color (LED::Red);
1064                 b->second->set_state (LED::OneShot24th);
1065                 break;
1066         }
1067
1068         write (b->second->state_msg());
1069 }
1070
1071 void
1072 Push2::notify_transport_state_changed ()
1073 {
1074         Button* b = id_button_map[Play];
1075
1076         if (session->transport_rolling()) {
1077                 b->set_state (LED::OneShot24th);
1078                 b->set_color (LED::Green);
1079         } else {
1080
1081                 /* disable any blink on FixedLength from pending edit range op */
1082                 Button* fl = id_button_map[FixedLength];
1083
1084                 fl->set_color (LED::Black);
1085                 fl->set_state (LED::NoTransition);
1086                 write (fl->state_msg());
1087
1088                 b->set_color (LED::White);
1089                 b->set_state (LED::NoTransition);
1090         }
1091
1092         write (b->state_msg());
1093 }
1094
1095 void
1096 Push2::notify_loop_state_changed ()
1097 {
1098 }
1099
1100 void
1101 Push2::notify_parameter_changed (std::string param)
1102 {
1103         IDButtonMap::iterator b;
1104
1105         if (param == "clicking") {
1106                 if ((b = id_button_map.find (Metronome)) == id_button_map.end()) {
1107                         return;
1108                 }
1109                 if (Config->get_clicking()) {
1110                         b->second->set_state (LED::Blinking4th);
1111                         b->second->set_color (LED::White);
1112                 } else {
1113                         b->second->set_color (LED::White);
1114                         b->second->set_state (LED::NoTransition);
1115                 }
1116                 write (b->second->state_msg ());
1117         }
1118 }
1119
1120 void
1121 Push2::notify_solo_active_changed (bool yn)
1122 {
1123         IDButtonMap::iterator b = id_button_map.find (Solo);
1124
1125         if (b == id_button_map.end()) {
1126                 return;
1127         }
1128
1129         if (yn) {
1130                 b->second->set_state (LED::Blinking4th);
1131                 b->second->set_color (LED::Red);
1132         } else {
1133                 b->second->set_state (LED::NoTransition);
1134                 b->second->set_color (LED::White);
1135         }
1136
1137         write (b->second->state_msg());
1138 }
1139
1140 XMLNode&
1141 Push2::get_state()
1142 {
1143         XMLNode& node (ControlProtocol::get_state());
1144         XMLNode* child;
1145
1146         child = new XMLNode (X_("Input"));
1147         child->add_child_nocopy (_async_in->get_state());
1148         node.add_child_nocopy (*child);
1149         child = new XMLNode (X_("Output"));
1150         child->add_child_nocopy (_async_out->get_state());
1151         node.add_child_nocopy (*child);
1152
1153         node.add_property (X_("root"), to_string (_scale_root, std::dec));
1154         node.add_property (X_("root_octave"), to_string (_root_octave, std::dec));
1155         node.add_property (X_("in_key"), _in_key ? X_("yes") : X_("no"));
1156         node.add_property (X_("mode"), enum_2_string (_mode));
1157
1158         return node;
1159 }
1160
1161 int
1162 Push2::set_state (const XMLNode & node, int version)
1163 {
1164         DEBUG_TRACE (DEBUG::Push2, string_compose ("Push2::set_state: active %1\n", active()));
1165
1166         int retval = 0;
1167
1168         if (ControlProtocol::set_state (node, version)) {
1169                 return -1;
1170         }
1171
1172         XMLNode* child;
1173
1174         if ((child = node.child (X_("Input"))) != 0) {
1175                 XMLNode* portnode = child->child (Port::state_node_name.c_str());
1176                 if (portnode) {
1177                         _async_in->set_state (*portnode, version);
1178                 }
1179         }
1180
1181         if ((child = node.child (X_("Output"))) != 0) {
1182                 XMLNode* portnode = child->child (Port::state_node_name.c_str());
1183                 if (portnode) {
1184                         _async_out->set_state (*portnode, version);
1185                 }
1186         }
1187
1188         XMLProperty const* prop;
1189
1190         if ((prop = node.property (X_("root"))) != 0) {
1191                 _scale_root = atoi (prop->value());
1192         }
1193
1194         if ((prop = node.property (X_("root_octave"))) != 0) {
1195                 _root_octave = atoi (prop->value());
1196         }
1197
1198         if ((prop = node.property (X_("in_key"))) != 0) {
1199                 _in_key = string_is_affirmative (prop->value());
1200         }
1201
1202         if ((prop = node.property (X_("mode"))) != 0) {
1203                 _mode = (MusicalMode::Type) string_2_enum (prop->value(), _mode);
1204         }
1205
1206         return retval;
1207 }
1208
1209 void
1210 Push2::switch_bank (uint32_t base)
1211 {
1212         if (!session) {
1213                 return;
1214         }
1215
1216         stripable_connections.drop_connections ();
1217
1218         /* try to get the first stripable for the requested bank */
1219
1220         stripable[0] = session->get_remote_nth_stripable (base, PresentationInfo::Flag (PresentationInfo::Route|PresentationInfo::VCA));
1221
1222         if (!stripable[0]) {
1223                 return;
1224         }
1225
1226         /* at least one stripable in this bank */
1227         bank_start = base;
1228
1229         stripable[1] = session->get_remote_nth_stripable (base+1, PresentationInfo::Flag (PresentationInfo::Route|PresentationInfo::VCA));
1230         stripable[2] = session->get_remote_nth_stripable (base+2, PresentationInfo::Flag (PresentationInfo::Route|PresentationInfo::VCA));
1231         stripable[3] = session->get_remote_nth_stripable (base+3, PresentationInfo::Flag (PresentationInfo::Route|PresentationInfo::VCA));
1232         stripable[4] = session->get_remote_nth_stripable (base+4, PresentationInfo::Flag (PresentationInfo::Route|PresentationInfo::VCA));
1233         stripable[5] = session->get_remote_nth_stripable (base+5, PresentationInfo::Flag (PresentationInfo::Route|PresentationInfo::VCA));
1234         stripable[6] = session->get_remote_nth_stripable (base+6, PresentationInfo::Flag (PresentationInfo::Route|PresentationInfo::VCA));
1235         stripable[7] = session->get_remote_nth_stripable (base+7, PresentationInfo::Flag (PresentationInfo::Route|PresentationInfo::VCA));
1236
1237
1238         for (int n = 0; n < 8; ++n) {
1239                 if (!stripable[n]) {
1240                         continue;
1241                 }
1242
1243                 /* stripable goes away? refill the bank, starting at the same point */
1244
1245                 stripable[n]->DropReferences.connect (stripable_connections, MISSING_INVALIDATOR, boost::bind (&Push2::switch_bank, this, bank_start), this);
1246                 boost::shared_ptr<AutomationControl> sc = stripable[n]->solo_control();
1247                 if (sc) {
1248                         sc->Changed.connect (stripable_connections, MISSING_INVALIDATOR, boost::bind (&Push2::solo_change, this, n), this);
1249                 }
1250
1251                 boost::shared_ptr<AutomationControl> mc = stripable[n]->mute_control();
1252                 if (mc) {
1253                         mc->Changed.connect (stripable_connections, MISSING_INVALIDATOR, boost::bind (&Push2::mute_change, this, n), this);
1254                 }
1255
1256                 stripable[n]->presentation_info().PropertyChanged.connect (stripable_connections, MISSING_INVALIDATOR, boost::bind (&Push2::stripable_property_change, this, _1, n), this);
1257
1258                 solo_change (n);
1259                 mute_change (n);
1260
1261         }
1262
1263         /* master cannot be removed, so no need to connect to going-away signal */
1264         master = session->master_out ();
1265 }
1266
1267 void
1268 Push2::stripable_property_change (PropertyChange const& what_changed, int which)
1269 {
1270         if (what_changed.contains (Properties::selected)) {
1271                 if (!stripable[which]) {
1272                         return;
1273                 }
1274
1275                 /* cancel string, which will cause a redraw on the next update
1276                  * cycle. The redraw will reflect selected status
1277                  */
1278
1279                 mid_layout[which]->set_text (string());
1280         }
1281 }
1282
1283 void
1284 Push2::stripable_selection_change (StripableNotificationListPtr selected)
1285 {
1286
1287         boost::shared_ptr<MidiPort> pad_port = boost::dynamic_pointer_cast<AsyncMIDIPort>(_async_in)->shadow_port();
1288         boost::shared_ptr<MidiTrack> current_midi_track = current_pad_target.lock();
1289         boost::shared_ptr<MidiTrack> new_pad_target;
1290
1291         /* See if there's a MIDI track selected */
1292
1293         for (StripableNotificationList::iterator si = selected->begin(); si != selected->end(); ++si) {
1294
1295                 new_pad_target = boost::dynamic_pointer_cast<MidiTrack> ((*si).lock());
1296
1297                 if (new_pad_target) {
1298                         break;
1299                 }
1300         }
1301
1302         if (new_pad_target) {
1303                 cerr << "new midi pad target " << new_pad_target->name() << endl;
1304         } else {
1305                 cerr << "no midi pad target\n";
1306         }
1307
1308         if (current_midi_track == new_pad_target) {
1309                 /* nothing to do */
1310                 return;
1311         }
1312
1313         if (!new_pad_target) {
1314                 /* leave existing connection alone */
1315                 return;
1316         }
1317
1318         /* disconnect from pad port, if appropriate */
1319
1320         if (current_midi_track && pad_port) {
1321                 cerr << "Disconnect pads from " << current_midi_track->name() << endl;
1322                 current_midi_track->input()->disconnect (current_midi_track->input()->nth(0), pad_port->name(), this);
1323         }
1324
1325         /* now connect the pad port to this (newly) selected midi
1326          * track, if indeed there is one.
1327          */
1328
1329         if (new_pad_target && pad_port) {
1330                 cerr << "Reconnect pads to " << new_pad_target->name() << endl;
1331                 new_pad_target->input()->connect (new_pad_target->input()->nth (0), pad_port->name(), this);
1332                 current_pad_target = new_pad_target;
1333         } else {
1334                 current_pad_target.reset ();
1335         }
1336 }
1337
1338
1339 void
1340 Push2::solo_change (int n)
1341 {
1342         ButtonID bid;
1343
1344         switch (n) {
1345         case 0:
1346                 bid = Upper1;
1347                 break;
1348         case 1:
1349                 bid = Upper2;
1350                 break;
1351         case 2:
1352                 bid = Upper3;
1353                 break;
1354         case 3:
1355                 bid = Upper4;
1356                 break;
1357         case 4:
1358                 bid = Upper5;
1359                 break;
1360         case 5:
1361                 bid = Upper6;
1362                 break;
1363         case 6:
1364                 bid = Upper7;
1365                 break;
1366         case 7:
1367                 bid = Upper8;
1368                 break;
1369         default:
1370                 return;
1371         }
1372
1373         boost::shared_ptr<SoloControl> ac = stripable[n]->solo_control ();
1374         if (!ac) {
1375                 return;
1376         }
1377
1378         Button* b = id_button_map[bid];
1379
1380         if (ac->soloed()) {
1381                 b->set_color (LED::Green);
1382         } else {
1383                 b->set_color (LED::Black);
1384         }
1385
1386         if (ac->soloed_by_others_upstream() || ac->soloed_by_others_downstream()) {
1387                 b->set_state (LED::Blinking4th);
1388         } else {
1389                 b->set_state (LED::OneShot24th);
1390         }
1391
1392         write (b->state_msg());
1393 }
1394
1395 void
1396 Push2::mute_change (int n)
1397 {
1398         ButtonID bid;
1399
1400         if (!stripable[n]) {
1401                 return;
1402         }
1403
1404         cerr << "Mute changed on " << n << ' ' << stripable[n]->name() << endl;
1405
1406         switch (n) {
1407         case 0:
1408                 bid = Lower1;
1409                 break;
1410         case 1:
1411                 bid = Lower2;
1412                 break;
1413         case 2:
1414                 bid = Lower3;
1415                 break;
1416         case 3:
1417                 bid = Lower4;
1418                 break;
1419         case 4:
1420                 bid = Lower5;
1421                 break;
1422         case 5:
1423                 bid = Lower6;
1424                 break;
1425         case 6:
1426                 bid = Lower7;
1427                 break;
1428         case 7:
1429                 bid = Lower8;
1430                 break;
1431         default:
1432                 return;
1433         }
1434
1435         boost::shared_ptr<MuteControl> mc = stripable[n]->mute_control ();
1436
1437         if (!mc) {
1438                 return;
1439         }
1440
1441         Button* b = id_button_map[bid];
1442
1443         if (Config->get_show_solo_mutes() && !Config->get_solo_control_is_listen_control ()) {
1444
1445                 if (mc->muted_by_self ()) {
1446                         /* full mute */
1447                         b->set_color (LED::Blue);
1448                         b->set_state (LED::OneShot24th);
1449                         cerr << "FULL MUTE1\n";
1450                 } else if (mc->muted_by_others_soloing () || mc->muted_by_masters ()) {
1451                         /* this will reflect both solo mutes AND master mutes */
1452                         b->set_color (LED::Blue);
1453                         b->set_state (LED::Blinking4th);
1454                         cerr << "OTHER MUTE1\n";
1455                 } else {
1456                         /* no mute at all */
1457                         b->set_color (LED::Black);
1458                         b->set_state (LED::OneShot24th);
1459                         cerr << "NO MUTE1\n";
1460                 }
1461
1462         } else {
1463
1464                 if (mc->muted_by_self()) {
1465                         /* full mute */
1466                         b->set_color (LED::Blue);
1467                         b->set_state (LED::OneShot24th);
1468                         cerr << "FULL MUTE2\n";
1469                 } else if (mc->muted_by_masters ()) {
1470                         /* this shows only master mutes, not mute-by-others-soloing */
1471                         b->set_color (LED::Blue);
1472                         b->set_state (LED::Blinking4th);
1473                         cerr << "OTHER MUTE1\n";
1474                 } else {
1475                         /* no mute at all */
1476                         b->set_color (LED::Black);
1477                         b->set_state (LED::OneShot24th);
1478                         cerr << "NO MUTE2\n";
1479                 }
1480         }
1481
1482         write (b->state_msg());
1483 }
1484
1485 void
1486 Push2::strip_vpot (int n, int delta)
1487 {
1488         if (stripable[n]) {
1489                 boost::shared_ptr<AutomationControl> ac = stripable[n]->gain_control();
1490                 if (ac) {
1491                         ac->set_value (ac->get_value() + ((2.0/64.0) * delta), PBD::Controllable::UseGroup);
1492                 }
1493         }
1494 }
1495
1496 void
1497 Push2::strip_vpot_touch (int n, bool touching)
1498 {
1499         if (stripable[n]) {
1500                 boost::shared_ptr<AutomationControl> ac = stripable[n]->gain_control();
1501                 if (ac) {
1502                         if (touching) {
1503                                 ac->start_touch (session->audible_frame());
1504                         } else {
1505                                 ac->stop_touch (true, session->audible_frame());
1506                         }
1507                 }
1508         }
1509 }
1510
1511 void
1512 Push2::other_vpot (int n, int delta)
1513 {
1514         switch (n) {
1515         case 0:
1516                 break;
1517         case 1:
1518                 break;
1519         case 2:
1520                 /* master gain control */
1521                 if (master) {
1522                         boost::shared_ptr<AutomationControl> ac = master->gain_control();
1523                         if (ac) {
1524                                 ac->set_value (ac->get_value() + ((2.0/64.0) * delta), PBD::Controllable::UseGroup);
1525                         }
1526                 }
1527                 break;
1528         }
1529 }
1530
1531 void
1532 Push2::other_vpot_touch (int n, bool touching)
1533 {
1534         switch (n) {
1535         case 0:
1536                 break;
1537         case 1:
1538                 break;
1539         case 2:
1540                 if (master) {
1541                         boost::shared_ptr<AutomationControl> ac = master->gain_control();
1542                         if (ac) {
1543                                 if (touching) {
1544                                         ac->start_touch (session->audible_frame());
1545                                 } else {
1546                                         ac->stop_touch (true, session->audible_frame());
1547                                 }
1548                         }
1549                 }
1550         }
1551 }
1552
1553 void
1554 Push2::start_shift ()
1555 {
1556         cerr << "start shift\n";
1557         modifier_state = ModifierState (modifier_state | ModShift);
1558         Button* b = id_button_map[Shift];
1559         b->set_color (LED::White);
1560         b->set_state (LED::Blinking16th);
1561         write (b->state_msg());
1562 }
1563
1564 void
1565 Push2::end_shift ()
1566 {
1567         if (modifier_state & ModShift) {
1568                 cerr << "end shift\n";
1569                 modifier_state = ModifierState (modifier_state & ~(ModShift));
1570                 Button* b = id_button_map[Shift];
1571                 b->timeout_connection.disconnect ();
1572                 b->set_color (LED::White);
1573                 b->set_state (LED::OneShot24th);
1574                 write (b->state_msg());
1575         }
1576 }
1577
1578 void
1579 Push2::start_select ()
1580 {
1581         cerr << "start select\n";
1582         modifier_state = ModifierState (modifier_state | ModSelect);
1583         Button* b = id_button_map[Select];
1584         b->set_color (LED::White);
1585         b->set_state (LED::Blinking16th);
1586         write (b->state_msg());
1587 }
1588
1589 void
1590 Push2::end_select ()
1591 {
1592         if (modifier_state & ModSelect) {
1593                 cerr << "end select\n";
1594                 modifier_state = ModifierState (modifier_state & ~(ModSelect));
1595                 Button* b = id_button_map[Select];
1596                 b->timeout_connection.disconnect ();
1597                 b->set_color (LED::White);
1598                 b->set_state (LED::OneShot24th);
1599                 write (b->state_msg());
1600         }
1601 }
1602
1603 void
1604 Push2::splash ()
1605 {
1606         std::string splash_file;
1607
1608         Searchpath rc (ARDOUR::ardour_data_search_path());
1609         rc.add_subdirectory_to_paths ("resources");
1610
1611         if (!find_file (rc, PROGRAM_NAME "-splash.png", splash_file)) {
1612                 cerr << "Cannot find splash screen image file\n";
1613                 throw failed_constructor();
1614         }
1615
1616         Cairo::RefPtr<Cairo::ImageSurface> img = Cairo::ImageSurface::create_from_png (splash_file);
1617
1618         double x_ratio = (double) img->get_width() / (cols - 20);
1619         double y_ratio = (double) img->get_height() / (rows - 20);
1620         double scale = min (x_ratio, y_ratio);
1621
1622         /* background */
1623
1624         context->set_source_rgb (0.764, 0.882, 0.882);
1625         context->paint ();
1626
1627         /* image */
1628
1629         context->save ();
1630         context->translate (5, 5);
1631         context->scale (scale, scale);
1632         context->set_source (img, 0, 0);
1633         context->paint ();
1634         context->restore ();
1635
1636         /* text */
1637
1638         Glib::RefPtr<Pango::Layout> some_text = Pango::Layout::create (context);
1639
1640         Pango::FontDescription fd ("Sans 38");
1641         some_text->set_font_description (fd);
1642         some_text->set_text (string_compose ("%1 %2", PROGRAM_NAME, VERSIONSTRING));
1643
1644         context->move_to (200, 10);
1645         context->set_source_rgb (0, 0, 0);
1646         some_text->update_from_cairo_context (context);
1647         some_text->show_in_cairo_context (context);
1648
1649         Pango::FontDescription fd2 ("Sans Italic 18");
1650         some_text->set_font_description (fd2);
1651         some_text->set_text (_("Ableton Push 2 Support"));
1652
1653         context->move_to (200, 80);
1654         context->set_source_rgb (0, 0, 0);
1655         some_text->update_from_cairo_context (context);
1656         some_text->show_in_cairo_context (context);
1657
1658         splash_start = get_microseconds ();
1659         blit_to_device_frame_buffer ();
1660 }
1661
1662 bool
1663 Push2::pad_filter (MidiBuffer& in, MidiBuffer& out) const
1664 {
1665         /* This filter is called asynchronously from a realtime process
1666            context. It must use atomics to check state, and must not block.
1667         */
1668
1669         bool matched = false;
1670
1671         for (MidiBuffer::iterator ev = in.begin(); ev != in.end(); ++ev) {
1672                 if ((*ev).is_note_on() || (*ev).is_note_off()) {
1673
1674                         /* encoder touch start/touch end use note
1675                          * 0-10. touchstrip uses note 12
1676                          */
1677
1678                         if ((*ev).note() > 10 && (*ev).note() != 12) {
1679
1680                                 const int n = (*ev).note ();
1681                                 NNPadMap::const_iterator nni = nn_pad_map.find (n);
1682
1683                                 if (nni != nn_pad_map.end()) {
1684                                         Pad const * pad = nni->second;
1685                                         /* shift for output to the shadow port */
1686                                         if (pad->filtered >= 0) {
1687                                                 (*ev).set_note (pad->filtered);
1688                                                 out.push_back (*ev);
1689                                                 /* shift back so that the pads light correctly  */
1690                                                 (*ev).set_note (n);
1691                                         } else {
1692                                                 /* no mapping, don't send event */
1693                                         }
1694                                 } else {
1695                                         out.push_back (*ev);
1696                                 }
1697
1698                                 matched = true;
1699                         }
1700                 }
1701         }
1702
1703         return matched;
1704 }
1705
1706 bool
1707 Push2::connection_handler (boost::weak_ptr<ARDOUR::Port>, std::string name1, boost::weak_ptr<ARDOUR::Port>, std::string name2, bool yn)
1708 {
1709         DEBUG_TRACE (DEBUG::FaderPort, "FaderPort::connection_handler  start\n");
1710         if (!_input_port || !_output_port) {
1711                 return false;
1712         }
1713
1714         string ni = ARDOUR::AudioEngine::instance()->make_port_name_non_relative (boost::shared_ptr<ARDOUR::Port>(_async_in)->name());
1715         string no = ARDOUR::AudioEngine::instance()->make_port_name_non_relative (boost::shared_ptr<ARDOUR::Port>(_async_out)->name());
1716
1717         if (ni == name1 || ni == name2) {
1718                 if (yn) {
1719                         connection_state |= InputConnected;
1720                 } else {
1721                         connection_state &= ~InputConnected;
1722                 }
1723         } else if (no == name1 || no == name2) {
1724                 if (yn) {
1725                         connection_state |= OutputConnected;
1726                 } else {
1727                         connection_state &= ~OutputConnected;
1728                 }
1729         } else {
1730                 DEBUG_TRACE (DEBUG::FaderPort, string_compose ("Connections between %1 and %2 changed, but I ignored it\n", name1, name2));
1731                 /* not our ports */
1732                 return false;
1733         }
1734
1735         if ((connection_state & (InputConnected|OutputConnected)) == (InputConnected|OutputConnected)) {
1736
1737                 /* XXX this is a horrible hack. Without a short sleep here,
1738                    something prevents the device wakeup messages from being
1739                    sent and/or the responses from being received.
1740                 */
1741
1742                 g_usleep (100000);
1743                 DEBUG_TRACE (DEBUG::FaderPort, "device now connected for both input and output\n");
1744                 // connected ();
1745
1746         } else {
1747                 DEBUG_TRACE (DEBUG::FaderPort, "Device disconnected (input or output or both) or not yet fully connected\n");
1748         }
1749
1750         ConnectionChange (); /* emit signal for our GUI */
1751
1752         DEBUG_TRACE (DEBUG::FaderPort, "FaderPort::connection_handler  end\n");
1753
1754         return true; /* connection status changed */
1755 }
1756
1757 boost::shared_ptr<Port>
1758 Push2::output_port()
1759 {
1760         return _async_out;
1761 }
1762
1763 boost::shared_ptr<Port>
1764 Push2::input_port()
1765 {
1766         return _async_in;
1767 }
1768
1769 void
1770 Push2::build_pad_table ()
1771 {
1772         for (int n = 36; n < 100; ++n) {
1773                 pad_map[n] = n + (octave_shift*12);
1774         }
1775
1776         PadChange (); /* emit signal */
1777 }
1778
1779 int
1780 Push2::pad_note (int row, int col) const
1781 {
1782         NNPadMap::const_iterator nni = nn_pad_map.find (36+(row*8)+col);
1783
1784         if (nni != nn_pad_map.end()) {
1785                 return nni->second->filtered;
1786         }
1787
1788         return 0;
1789 }
1790
1791 void
1792 Push2::set_pad_scale (int root, int octave, MusicalMode::Type mode, bool inkey)
1793 {
1794         MusicalMode m (mode);
1795         vector<float>::iterator interval;
1796         int note;
1797         const int original_root = root;
1798
1799         interval = m.steps.begin();
1800         root += (octave*12);
1801         note = root;
1802
1803         const int root_start = root;
1804
1805         set<int> mode_map; /* contains only notes in mode, O(logN) lookup */
1806         vector<int> mode_vector; /* sorted in note order */
1807
1808         mode_map.insert (note);
1809         mode_vector.push_back (note);
1810
1811         /* build a map of all notes in the mode, from the root to 127 */
1812
1813         while (note < 128) {
1814
1815                 if (interval == m.steps.end()) {
1816
1817                         /* last distance was the end of the scale,
1818                            so wrap, adding the next note at one
1819                            octave above the last root.
1820                         */
1821
1822                         interval = m.steps.begin();
1823                         root += 12;
1824                         mode_map.insert (root);
1825                         mode_vector.push_back (root);
1826
1827                 } else {
1828                         note = (int) floor (root + (2.0 * (*interval)));
1829                         interval++;
1830                         mode_map.insert (note);
1831                         mode_vector.push_back (note);
1832                 }
1833         }
1834
1835         if (inkey) {
1836
1837                 vector<int>::iterator notei;
1838                 int row_offset = 0;
1839                 for (int row = 0; row < 8; ++row) {
1840
1841                         /* Ableton's grid layout wraps the available notes in the scale
1842                          * by offsetting 3 notes per row (from the bottom)
1843                          */
1844
1845                         notei = mode_vector.begin();
1846                         notei += row_offset;
1847                         row_offset += 3;
1848
1849                         for (int col = 0; col < 8; ++col) {
1850                                 int index = 36 + (row*8) + col;
1851                                 Pad* pad = nn_pad_map[index];
1852                                 int notenum;
1853                                 if (notei != mode_vector.end()) {
1854
1855                                         notenum = *notei;
1856                                         pad->filtered = notenum;
1857
1858                                         if ((notenum % 12) == original_root) {
1859                                                 pad->set_color (LED::Green);
1860                                                 pad->perma_color = LED::Green;
1861                                         } else {
1862                                                 pad->set_color (LED::White);
1863                                                 pad->perma_color = LED::White;
1864                                         }
1865
1866                                         pad->do_when_pressed = Pad::FlashOff;
1867                                         notei++;
1868
1869                                 } else {
1870
1871                                         pad->set_color (LED::Black);
1872                                         pad->do_when_pressed = Pad::Nothing;
1873                                         pad->filtered = -1;
1874                                 }
1875
1876                                 write (pad->state_msg());
1877                         }
1878                 }
1879
1880         } else {
1881
1882                 /* chromatic: all notes available, but highlight those in the scale */
1883
1884                 for (note = 36; note < 100; ++note) {
1885
1886                         Pad* pad = nn_pad_map[note];
1887
1888                         /* Chromatic: all pads play, half-tone steps. Light
1889                          * those in the scale, and highlight root notes
1890                          */
1891
1892                         pad->filtered = root_start + (note - 36);
1893
1894                         if (mode_map.find (note) != mode_map.end()) {
1895
1896                                 if ((note % 12) == original_root) {
1897                                         pad->set_color (LED::Green);
1898                                         pad->perma_color = LED::Green;
1899                                 } else {
1900                                         pad->set_color (LED::White);
1901                                         pad->perma_color = LED::White;
1902                                 }
1903
1904                                 pad->do_when_pressed = Pad::FlashOff;
1905
1906                         } else {
1907
1908                                 /* note is not in mode, turn it off */
1909
1910                                 pad->do_when_pressed = Pad::FlashOn;
1911                                 pad->set_color (LED::Black);
1912
1913                         }
1914
1915                         write (pad->state_msg());
1916                 }
1917         }
1918
1919         PadChange (); /* EMIT SIGNAL */
1920
1921         /* store state */
1922
1923         _scale_root = original_root;
1924         _root_octave = octave;
1925         _in_key = inkey;
1926         _mode = mode;
1927 }