additional i18n.h changes for push2 branch
[ardour.git] / libs / surfaces / push2 / push2.cc
index 263ac74dfbc62571a0df57ee0b7dad5752a7c7ce..0544446a311ac0304fca87c8c35f4cd5eef97a6c 100644 (file)
@@ -1,37 +1,59 @@
 /*
-       Copyright (C) 2016 Paul Davis
+  Copyright (C) 2016 Paul Davis
 
-       This program is free software; you can redistribute it and/or modify
-       it under the terms of the GNU General Public License as published by
-       the Free Software Foundation; either version 2 of the License, or
-       (at your option) any later version.
+  This program is free software; you can redistribute it and/or modify
+  it under the terms of the GNU General Public License as published by
+  the Free Software Foundation; either version 2 of the License, or
+  (at your option) any later version.
 
-       This program is distributed in the hope that it will be useful,
-       but WITHOUT ANY WARRANTY; without even the implied warranty of
-       MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-       GNU General Public License for more details.
+  This program is distributed in the hope that it will be useful,
+  but WITHOUT ANY WARRANTY; without even the implied warranty of
+  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+  GNU General Public License for more details.
 
-       You should have received a copy of the GNU General Public License
-       along with this program; if not, write to the Free Software
-       Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
+  You should have received a copy of the GNU General Public License
+  along with this program; if not, write to the Free Software
+  Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
 */
 
-#include <cairomm/context.h>
-#include <cairomm/surface.h>
-#include <pangomm/layout.h>
+#include <stdlib.h>
 
 #include "pbd/compose.h"
+#include "pbd/convert.h"
 #include "pbd/debug.h"
 #include "pbd/failed_constructor.h"
+#include "pbd/file_utils.h"
+#include "pbd/search_path.h"
+#include "pbd/enumwriter.h"
 
 #include "midi++/parser.h"
+#include "timecode/time.h"
+#include "timecode/bbt_time.h"
 
 #include "ardour/async_midi_port.h"
 #include "ardour/audioengine.h"
 #include "ardour/debug.h"
+#include "ardour/filesystem_paths.h"
 #include "ardour/midiport_manager.h"
+#include "ardour/midi_track.h"
+#include "ardour/midi_port.h"
 #include "ardour/session.h"
+#include "ardour/tempo.h"
+
+#include "gtkmm2ext/gui_thread.h"
+#include "gtkmm2ext/rgb_macros.h"
+
+#include "canvas/colors.h"
+
 #include "push2.h"
+#include "gui.h"
+#include "layout.h"
+#include "scale.h"
+#include "mix.h"
+#include "track_mix.h"
+#include "menu.h"
+
+#include "pbd/i18n.h"
 
 using namespace ARDOUR;
 using namespace std;
@@ -39,8 +61,6 @@ using namespace PBD;
 using namespace Glib;
 using namespace ArdourSurface;
 
-#include "i18n.h"
-
 #include "pbd/abstract_ui.cc" // instantiate template
 
 const int Push2::cols = 960;
@@ -50,23 +70,149 @@ const int Push2::pixels_per_row = 1024;
 #define ABLETON 0x2982
 #define PUSH2   0x1967
 
+__attribute__((constructor)) static void
+register_enums ()
+{
+       EnumWriter& enum_writer (EnumWriter::instance());
+       vector<int> i;
+       vector<string> s;
+
+       MusicalMode::Type mode;
+
+#define REGISTER(e) enum_writer.register_distinct (typeid(e).name(), i, s); i.clear(); s.clear()
+#define REGISTER_CLASS_ENUM(t,e) i.push_back (t::e); s.push_back (#e)
+
+       REGISTER_CLASS_ENUM (MusicalMode,Dorian);
+       REGISTER_CLASS_ENUM (MusicalMode, IonianMajor);
+       REGISTER_CLASS_ENUM (MusicalMode, Minor);
+       REGISTER_CLASS_ENUM (MusicalMode, HarmonicMinor);
+       REGISTER_CLASS_ENUM (MusicalMode, MelodicMinorAscending);
+       REGISTER_CLASS_ENUM (MusicalMode, MelodicMinorDescending);
+       REGISTER_CLASS_ENUM (MusicalMode, Phrygian);
+       REGISTER_CLASS_ENUM (MusicalMode, Lydian);
+       REGISTER_CLASS_ENUM (MusicalMode, Mixolydian);
+       REGISTER_CLASS_ENUM (MusicalMode, Aeolian);
+       REGISTER_CLASS_ENUM (MusicalMode, Locrian);
+       REGISTER_CLASS_ENUM (MusicalMode, PentatonicMajor);
+       REGISTER_CLASS_ENUM (MusicalMode, PentatonicMinor);
+       REGISTER_CLASS_ENUM (MusicalMode, Chromatic);
+       REGISTER_CLASS_ENUM (MusicalMode, BluesScale);
+       REGISTER_CLASS_ENUM (MusicalMode, NeapolitanMinor);
+       REGISTER_CLASS_ENUM (MusicalMode, NeapolitanMajor);
+       REGISTER_CLASS_ENUM (MusicalMode, Oriental);
+       REGISTER_CLASS_ENUM (MusicalMode, DoubleHarmonic);
+       REGISTER_CLASS_ENUM (MusicalMode, Enigmatic);
+       REGISTER_CLASS_ENUM (MusicalMode, Hirajoshi);
+       REGISTER_CLASS_ENUM (MusicalMode, HungarianMinor);
+       REGISTER_CLASS_ENUM (MusicalMode, HungarianMajor);
+       REGISTER_CLASS_ENUM (MusicalMode, Kumoi);
+       REGISTER_CLASS_ENUM (MusicalMode, Iwato);
+       REGISTER_CLASS_ENUM (MusicalMode, Hindu);
+       REGISTER_CLASS_ENUM (MusicalMode, Spanish8Tone);
+       REGISTER_CLASS_ENUM (MusicalMode, Pelog);
+       REGISTER_CLASS_ENUM (MusicalMode, HungarianGypsy);
+       REGISTER_CLASS_ENUM (MusicalMode, Overtone);
+       REGISTER_CLASS_ENUM (MusicalMode, LeadingWholeTone);
+       REGISTER_CLASS_ENUM (MusicalMode, Arabian);
+       REGISTER_CLASS_ENUM (MusicalMode, Balinese);
+       REGISTER_CLASS_ENUM (MusicalMode, Gypsy);
+       REGISTER_CLASS_ENUM (MusicalMode, Mohammedan);
+       REGISTER_CLASS_ENUM (MusicalMode, Javanese);
+       REGISTER_CLASS_ENUM (MusicalMode, Persian);
+       REGISTER_CLASS_ENUM (MusicalMode, Algerian);
+       REGISTER (mode);
+}
+
 Push2::Push2 (ARDOUR::Session& s)
        : ControlProtocol (s, string (X_("Ableton Push 2")))
        , AbstractUI<Push2Request> (name())
        , handle (0)
        , device_buffer (0)
        , frame_buffer (Cairo::ImageSurface::create (Cairo::FORMAT_ARGB32, cols, rows))
+       , _modifier_state (None)
+       , splash_start (0)
+       , _current_layout (0)
+       , drawn_layout (0)
+       , connection_state (ConnectionState (0))
+       , gui (0)
+       , _mode (MusicalMode::IonianMajor)
+       , _scale_root (0)
+       , _root_octave (3)
+       , _in_key (true)
+       , octave_shift (0)
+       , percussion (false)
 {
+       context = Cairo::Context::create (frame_buffer);
+
+       build_maps ();
+       build_color_map ();
+       fill_color_table ();
+
+       /* master cannot be removed, so no need to connect to going-away signal */
+       master = session->master_out ();
+
        if (open ()) {
                throw failed_constructor ();
        }
 
-       build_maps ();
+       ControlProtocol::StripableSelectionChanged.connect (selection_connection, MISSING_INVALIDATOR, boost::bind (&Push2::stripable_selection_change, this, _1), this);
+
+       /* catch current selection, if any */
+       {
+               StripableNotificationListPtr sp (new StripableNotificationList (ControlProtocol::last_selected()));
+               stripable_selection_change (sp);
+       }
+
+       /* catch arrival and departure of Push2 itself */
+       ARDOUR::AudioEngine::instance()->PortRegisteredOrUnregistered.connect (port_reg_connection, MISSING_INVALIDATOR, boost::bind (&Push2::port_registration_handler, this), this);
+
+       /* Catch port connections and disconnections */
+       ARDOUR::AudioEngine::instance()->PortConnectedOrDisconnected.connect (port_connection, MISSING_INVALIDATOR, boost::bind (&Push2::connection_handler, this, _1, _2, _3, _4, _5), this);
+
+       /* ports might already be there */
+       port_registration_handler ();
 }
 
 Push2::~Push2 ()
 {
-       close ();
+       stop ();
+
+       delete track_mix_layout;
+       delete mix_layout;
+       delete scale_layout;
+}
+
+void
+Push2::port_registration_handler ()
+{
+       if (!_async_in && !_async_out) {
+               /* ports not registered yet */
+               return;
+       }
+
+       if (_async_in->connected() && _async_out->connected()) {
+               /* don't waste cycles here */
+               return;
+       }
+
+       string input_port_name = X_("Ableton Push 2 MIDI 1 in");
+       string output_port_name = X_("Ableton Push 2 MIDI 1 out");
+       vector<string> in;
+       vector<string> out;
+
+       AudioEngine::instance()->get_ports (string_compose (".*%1", input_port_name), DataType::MIDI, PortFlags (IsPhysical|IsOutput), in);
+       AudioEngine::instance()->get_ports (string_compose (".*%1", output_port_name), DataType::MIDI, PortFlags (IsPhysical|IsInput), out);
+
+       if (!in.empty() && !out.empty()) {
+               cerr << "Push2: both ports found\n";
+               cerr << "\tconnecting to " << in.front() <<  " + " << out.front() << endl;
+               if (!_async_in->connected()) {
+                       AudioEngine::instance()->connect (_async_in->name(), in.front());
+               }
+               if (!_async_out->connected()) {
+                       AudioEngine::instance()->connect (_async_out->name(), out.front());
+               }
+       }
 }
 
 int
@@ -87,11 +233,9 @@ Push2::open ()
                return -1;
        }
 
-       device_frame_buffer[0] = new uint16_t[rows*pixels_per_row];
-       device_frame_buffer[1] = new uint16_t[rows*pixels_per_row];
+       device_frame_buffer = new uint16_t[rows*pixels_per_row];
 
-       memset (device_frame_buffer[0], 0, sizeof (uint16_t) * rows * pixels_per_row);
-       memset (device_frame_buffer[1], 0, sizeof (uint16_t) * rows * pixels_per_row);
+       memset (device_frame_buffer, 0, sizeof (uint16_t) * rows * pixels_per_row);
 
        frame_header[0] = 0xef;
        frame_header[1] = 0xcd;
@@ -101,24 +245,73 @@ Push2::open ()
 
        /* setup ports */
 
-       _async_in  = AudioEngine::instance()->register_input_port (DataType::MIDI, X_("push2 in"), true);
-       _async_out = AudioEngine::instance()->register_output_port (DataType::MIDI, X_("push2 out"), true);
+       _async_in  = AudioEngine::instance()->register_input_port (DataType::MIDI, X_("Push 2 in"), true);
+       _async_out = AudioEngine::instance()->register_output_port (DataType::MIDI, X_("Push 2 out"), true);
 
        if (_async_in == 0 || _async_out == 0) {
                return -1;
        }
 
+       /* We do not add our ports to the input/output bundles because we don't
+        * want users wiring them by hand. They could use JACK tools if they
+        * really insist on that.
+        */
+
        _input_port = boost::dynamic_pointer_cast<AsyncMIDIPort>(_async_in).get();
        _output_port = boost::dynamic_pointer_cast<AsyncMIDIPort>(_async_out).get();
 
+       /* Create a shadow port where, depending on the state of the surface,
+        * we will make pad note on/off events appear. The surface code will
+        * automatically this port to the first selected MIDI track.
+        */
+
+       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));
+       boost::shared_ptr<MidiPort> shadow_port = boost::dynamic_pointer_cast<AsyncMIDIPort>(_async_in)->shadow_port();
+
+       if (shadow_port) {
+
+               _output_bundle.reset (new ARDOUR::Bundle (_("Push 2 Pads"), false));
+
+               _output_bundle->add_channel (
+                       shadow_port->name(),
+                       ARDOUR::DataType::MIDI,
+                       session->engine().make_port_name_non_relative (shadow_port->name())
+                       );
+       }
+
+       session->BundleAddedOrRemoved ();
+
        connect_to_parser ();
 
+       mix_layout = new MixLayout (*this, *session, context);
+       scale_layout = new ScaleLayout (*this, *session, context);
+       track_mix_layout = new TrackMixLayout (*this, *session, context);
+
        return 0;
 }
 
+list<boost::shared_ptr<ARDOUR::Bundle> >
+Push2::bundles ()
+{
+       list<boost::shared_ptr<ARDOUR::Bundle> > b;
+
+       if (_output_bundle) {
+               b.push_back (_output_bundle);
+       }
+
+       return b;
+}
+
 int
 Push2::close ()
 {
+       init_buttons (false);
+
+       /* wait for button data to be flushed */
+       AsyncMIDIPort* asp;
+       asp = dynamic_cast<AsyncMIDIPort*> (_output_port);
+       asp->drain (10000, 500000);
+
        AudioEngine::instance()->unregister_port (_async_in);
        AudioEngine::instance()->unregister_port (_async_out);
 
@@ -131,21 +324,92 @@ Push2::close ()
        periodic_connection.disconnect ();
        session_connections.drop_connections ();
 
+       _current_layout = 0;
+       drawn_layout = 0;
+       delete mix_layout;
+       mix_layout = 0;
+       delete scale_layout;
+       scale_layout = 0;
+
        if (handle) {
                libusb_release_interface (handle, 0x00);
                libusb_close (handle);
                handle = 0;
        }
 
-       delete [] device_frame_buffer[0];
-       device_frame_buffer[0] = 0;
-
-       delete [] device_frame_buffer[1];
-       device_frame_buffer[1] = 0;
+       delete [] device_frame_buffer;
+       device_frame_buffer = 0;
 
        return 0;
 }
 
+void
+Push2::init_buttons (bool startup)
+{
+       /* This is a list of buttons that we want lit because they do something
+          in ardour related (loosely, sometimes) to their illuminated label.
+       */
+
+       ButtonID buttons[] = { Mute, Solo, Master, Up, Right, Left, Down, Note, Session, Mix, AddTrack, Delete, Undo,
+                              Metronome, Shift, Select, Play, RecordEnable, Automate, Repeat, Note, Session, DoubleLoop,
+                              Quantize, Duplicate, Browse, PageRight, PageLeft, OctaveUp, OctaveDown, Layout, Scale
+       };
+
+       for (size_t n = 0; n < sizeof (buttons) / sizeof (buttons[0]); ++n) {
+               Button* b = id_button_map[buttons[n]];
+
+               if (startup) {
+                       b->set_color (LED::White);
+               } else {
+                       b->set_color (LED::Black);
+               }
+               b->set_state (LED::OneShot24th);
+               write (b->state_msg());
+       }
+
+       /* Strip buttons should all be off (black) by default. They will change
+        * color to reflect various conditions
+        */
+
+       ButtonID strip_buttons[] = { Upper1, Upper2, Upper3, Upper4, Upper5, Upper6, Upper7, Upper8,
+                                    Lower1, Lower2, Lower3, Lower4, Lower5, Lower6, Lower7, Lower8, };
+
+       for (size_t n = 0; n < sizeof (strip_buttons) / sizeof (strip_buttons[0]); ++n) {
+               Button* b = id_button_map[strip_buttons[n]];
+
+               b->set_color (LED::Black);
+               b->set_state (LED::OneShot24th);
+               write (b->state_msg());
+       }
+
+       if (startup) {
+
+               /* all other buttons are off (black) */
+
+               ButtonID off_buttons[] = { TapTempo, Setup, User, Stop, Convert, New, FixedLength,
+                                          Fwd32ndT, Fwd32nd, Fwd16thT, Fwd16th, Fwd8thT, Fwd8th, Fwd4trT, Fwd4tr,
+                                          Accent, Note, Session,  };
+
+               for (size_t n = 0; n < sizeof (off_buttons) / sizeof (off_buttons[0]); ++n) {
+                       Button* b = id_button_map[off_buttons[n]];
+
+                       b->set_color (LED::Black);
+                       b->set_state (LED::OneShot24th);
+                       write (b->state_msg());
+               }
+       }
+
+       if (!startup) {
+               for (NNPadMap::iterator pi = nn_pad_map.begin(); pi != nn_pad_map.end(); ++pi) {
+                       Pad* pad = pi->second;
+
+                       pad->set_color (LED::Black);
+                       pad->set_state (LED::OneShot24th);
+                       write (pad->state_msg());
+               }
+       }
+}
+
 bool
 Push2::probe ()
 {
@@ -201,7 +465,7 @@ Push2::stop ()
  */
 
 int
-Push2::render ()
+Push2::blit_to_device_frame_buffer ()
 {
        /* ensure that all drawing has been done before we fetch pixel data */
 
@@ -212,9 +476,7 @@ Push2::render ()
 
        /* fill frame buffer (320kB) */
 
-       Glib::Threads::Mutex::Lock lm (fb_lock);
-
-       uint16_t* fb = (uint16_t*) device_frame_buffer[device_buffer];
+       uint16_t* fb = (uint16_t*) device_frame_buffer;
 
        for (int row = 0; row < rows; ++row) {
 
@@ -233,6 +495,12 @@ Push2::render ()
 
                        *fb++ = (r >> 3) | ((g & 0xfc) << 3) | ((b & 0xf8) << 8);
 
+                       /* the push2 docs state that we should xor the pixel
+                        * data. Doing so doesn't work correctly, and not doing
+                        * so seems to work fine (colors roughly match intended
+                        * values).
+                        */
+
                        dp += 4;
                }
 
@@ -243,12 +511,42 @@ Push2::render ()
                fb += 64; /* 128 bytes = 64 int16_t */
        }
 
-       /* swap buffers (under lock protection) */
-       // device_buffer = (device_buffer ? 0 : 1);
-
        return 0;
 }
 
+bool
+Push2::redraw ()
+{
+       if (splash_start) {
+
+               /* display splash for 3 seconds */
+
+               if (get_microseconds() - splash_start > 3000000) {
+                       splash_start = 0;
+               } else {
+                       return false;
+               }
+       }
+
+       Glib::Threads::Mutex::Lock lm (layout_lock, Glib::Threads::TRY_LOCK);
+
+       if (!lm.locked()) {
+               /* can't get layout, no re-render needed */
+               return false;
+       }
+
+       bool render_needed = false;
+
+       if (drawn_layout != _current_layout) {
+               render_needed = true;
+       }
+
+       bool dirty = _current_layout->redraw (context, render_needed);
+       drawn_layout = _current_layout;
+
+       return dirty || render_needed;
+}
+
 bool
 Push2::vblank ()
 {
@@ -260,12 +558,13 @@ Push2::vblank ()
                return false;
        }
 
-       {
-               Glib::Threads::Mutex::Lock lm (fb_lock);
+       if (redraw()) {
+               /* things changed */
+               blit_to_device_frame_buffer ();
+       }
 
-               if ((err = libusb_bulk_transfer (handle, 0x01, (uint8_t*) device_frame_buffer[device_buffer] , 2 * rows * pixels_per_row, &transferred, timeout_msecs))) {
-                       return false;
-               }
+       if ((err = libusb_bulk_transfer (handle, 0x01, (uint8_t*) device_frame_buffer , 2 * rows * pixels_per_row, &transferred, timeout_msecs))) {
+               return false;
        }
 
        return true;
@@ -302,28 +601,6 @@ Push2::set_active (bool yn)
 
                connect_session_signals ();
 
-               /* say hello */
-
-               Cairo::RefPtr<Cairo::Context> context = Cairo::Context::create (frame_buffer);
-               Glib::RefPtr<Pango::Layout> layout = Pango::Layout::create (context);
-
-               layout->set_text ("hello, Ardour");
-               Pango::FontDescription fd ("Sans Bold 12");
-               layout->set_font_description (fd);
-
-               context->set_source_rgb (0.0, 1.0, 1.0);
-               context->rectangle (0, 0, 960, 160);
-               context->fill ();
-               context->set_source_rgb (0.0, 0.0, 0.0);
-               context->rectangle (50, 50, 860, 60);
-               context->fill ();
-               context->move_to (60, 60);
-               context->set_source_rgb ((random()%255) / 255.0, (random()%255) / 255.0, (random()%255) / 255.0);
-               layout->update_from_cairo_context (context);
-               layout->show_in_cairo_context (context);
-
-               render ();
-
                /* set up periodic task used to push a frame buffer to the
                 * device (25fps). The device can handle 60fps, but we don't
                 * need that frame rate.
@@ -338,6 +615,12 @@ Push2::set_active (bool yn)
                periodic_connection = periodic_timeout->connect (sigc::mem_fun (*this, &Push2::periodic));
                periodic_timeout->attach (main_loop()->get_context());
 
+               init_buttons (true);
+               init_touch_strip ();
+               set_pad_scale (_scale_root, _root_octave, _mode, _in_key);
+               splash ();
+               set_current_layout (mix_layout);
+
        } else {
 
                stop ();
@@ -351,10 +634,23 @@ Push2::set_active (bool yn)
        return 0;
 }
 
+void
+Push2::init_touch_strip ()
+{
+       MidiByteArray msg (9, 0xf0, 0x00, 0x21, 0x1d, 0x01, 0x01, 0x17, 0x00, 0xf7);
+       /* flags are the final byte (ignore end-of-sysex */
+
+       /* show bar, not point
+          autoreturn to center
+          bar starts at center
+       */
+       msg[7] = (1<<4) | (1<<5) | (1<<6);
+       write (msg);
+}
+
 void
 Push2::write (const MidiByteArray& data)
 {
-       cerr << data << endl;
        /* immediate delivery */
        _output_port->write (&data[0], data.size(), 0);
 }
@@ -412,199 +708,219 @@ Push2::connect_to_parser ()
 void
 Push2::handle_midi_sysex (MIDI::Parser&, MIDI::byte* raw_bytes, size_t sz)
 {
-       cerr << "sysex, " << sz << " bytes\n";
+       DEBUG_TRACE (DEBUG::Push2, string_compose ("Sysex, %1 bytes\n", sz));
 }
 
 void
 Push2::handle_midi_controller_message (MIDI::Parser&, MIDI::EventTwoBytes* ev)
 {
+       DEBUG_TRACE (DEBUG::Push2, string_compose ("CC %1 (value %2)\n", (int) ev->controller_number, (int) ev->value));
+
        CCButtonMap::iterator b = cc_button_map.find (ev->controller_number);
+
+       if (ev->value) {
+               /* any press cancels any pending long press timeouts */
+               for (set<ButtonID>::iterator x = buttons_down.begin(); x != buttons_down.end(); ++x) {
+                       Button* bb = id_button_map[*x];
+                       bb->timeout_connection.disconnect ();
+               }
+       }
+
        if (b != cc_button_map.end()) {
-               if (ev->value == 0) {
-                       (this->*b->second->release_method)();
+
+               Button* button = b->second;
+
+               if (ev->value) {
+                       buttons_down.insert (button->id);
+                       start_press_timeout (*button, button->id);
                } else {
-                       (this->*b->second->press_method)();
+                       buttons_down.erase (button->id);
+                       button->timeout_connection.disconnect ();
+               }
+
+
+               set<ButtonID>::iterator c = consumed.find (button->id);
+
+               if (c == consumed.end()) {
+                       if (ev->value == 0) {
+                               (this->*button->release_method)();
+                       } else {
+                               (this->*button->press_method)();
+                       }
+               } else {
+                       DEBUG_TRACE (DEBUG::Push2, "button was consumed, ignored\n");
+                       consumed.erase (c);
+               }
+
+       } else {
+
+               /* encoder/vpot */
+
+               int delta = ev->value;
+
+               if (delta > 63) {
+                       delta = -(128 - delta);
+               }
+
+               switch (ev->controller_number) {
+               case 71:
+                       _current_layout->strip_vpot (0, delta);
+                       break;
+               case 72:
+                       _current_layout->strip_vpot (1, delta);
+                       break;
+               case 73:
+                       _current_layout->strip_vpot (2, delta);
+                       break;
+               case 74:
+                       _current_layout->strip_vpot (3, delta);
+                       break;
+               case 75:
+                       _current_layout->strip_vpot (4, delta);
+                       break;
+               case 76:
+                       _current_layout->strip_vpot (5, delta);
+                       break;
+               case 77:
+                       _current_layout->strip_vpot (6, delta);
+                       break;
+               case 78:
+                       _current_layout->strip_vpot (7, delta);
+                       break;
+
+                       /* left side pair */
+               case 14:
+                       other_vpot (8, delta);
+                       break;
+               case 15:
+                       other_vpot (1, delta);
+                       break;
+
+                       /* right side */
+               case 79:
+                       other_vpot (2, delta);
+                       break;
                }
        }
 }
 
 void
-Push2::handle_midi_note_on_message (MIDI::Parser&, MIDI::EventTwoBytes* ev)
+Push2::handle_midi_note_on_message (MIDI::Parser& parser, MIDI::EventTwoBytes* ev)
 {
-       cerr << "note on" << (int) ev->note_number << ", velocity " << (int) ev->velocity << endl;
+       DEBUG_TRACE (DEBUG::Push2, string_compose ("Note On %1 (velocity %2)\n", (int) ev->note_number, (int) ev->velocity));
+
+       if (ev->velocity == 0) {
+               handle_midi_note_off_message (parser, ev);
+               return;
+       }
+
+       switch (ev->note_number) {
+       case 0:
+               _current_layout->strip_vpot_touch (0, ev->velocity > 64);
+               break;
+       case 1:
+               _current_layout->strip_vpot_touch (1, ev->velocity > 64);
+               break;
+       case 2:
+               _current_layout->strip_vpot_touch (2, ev->velocity > 64);
+               break;
+       case 3:
+               _current_layout->strip_vpot_touch (3, ev->velocity > 64);
+               break;
+       case 4:
+               _current_layout->strip_vpot_touch (4, ev->velocity > 64);
+               break;
+       case 5:
+               _current_layout->strip_vpot_touch (5, ev->velocity > 64);
+               break;
+       case 6:
+               _current_layout->strip_vpot_touch (6, ev->velocity > 64);
+               break;
+       case 7:
+               _current_layout->strip_vpot_touch (7, ev->velocity > 64);
+               break;
+
+               /* left side */
+       case 10:
+               other_vpot_touch (0, ev->velocity > 64);
+               break;
+       case 9:
+               other_vpot_touch (1, ev->velocity > 64);
+               break;
+
+               /* right side */
+       case 8:
+               other_vpot_touch (3, ev->velocity > 64);
+               break;
+
+               /* touch strip */
+       case 12:
+               if (ev->velocity < 64) {
+                       transport_stop ();
+               }
+               break;
+       }
+
+       if (ev->note_number < 11) {
+               return;
+       }
+
+       /* Pad */
+
+       NNPadMap::iterator pi = nn_pad_map.find (ev->note_number);
+
+       if (pi == nn_pad_map.end()) {
+               return;
+       }
+
+       Pad* pad = pi->second;
+
+       if (pad->do_when_pressed == Pad::FlashOn) {
+               pad->set_color (LED::White);
+               pad->set_state (LED::OneShot24th);
+               write (pad->state_msg());
+       } else if (pad->do_when_pressed == Pad::FlashOff) {
+               pad->set_color (LED::Black);
+               pad->set_state (LED::OneShot24th);
+               write (pad->state_msg());
+       }
 }
 
 void
 Push2::handle_midi_note_off_message (MIDI::Parser&, MIDI::EventTwoBytes* ev)
 {
-       cerr << "note on" << (int) ev->note_number << ", velocity " << (int) ev->velocity << endl;
+       DEBUG_TRACE (DEBUG::Push2, string_compose ("Note Off %1 (velocity %2)\n", (int) ev->note_number, (int) ev->velocity));
+
+       if (ev->note_number < 11) {
+               /* theoretically related to encoder touch start/end, but
+                * actually they send note on with two different velocity
+                * values (127 & 64).
+                */
+               return;
+       }
+
+       NNPadMap::iterator pi = nn_pad_map.find (ev->note_number);
+
+       if (pi == nn_pad_map.end()) {
+               return;
+       }
+
+       Pad* pad = pi->second;
+
+       if (pad->do_when_pressed == Pad::FlashOn) {
+               pad->set_color (LED::Black);
+               pad->set_state (LED::OneShot24th);
+               write (pad->state_msg());
+       } else if (pad->do_when_pressed == Pad::FlashOff) {
+               pad->set_color (pad->perma_color);
+               pad->set_state (LED::OneShot24th);
+               write (pad->state_msg());
+       }
 }
 
 void
 Push2::handle_midi_pitchbend_message (MIDI::Parser&, MIDI::pitchbend_t pb)
 {
-       cerr << "pitchbend @ " << pb << endl;
-}
-
-void
-Push2::build_maps ()
-{
-       /* Pads */
-
-       Pad* pad;
-
-#define MAKE_PAD(x,y,nn) \
-       pad = new Pad ((x), (y), (nn)); \
-       nn_pad_map.insert (make_pair (pad->extra(), pad)); \
-       coord_pad_map.insert (make_pair (pad->coord(), pad));
-
-       MAKE_PAD (0, 1, 93);
-       MAKE_PAD (0, 2, 94);
-       MAKE_PAD (0, 3, 95);
-       MAKE_PAD (0, 4, 96);
-       MAKE_PAD (0, 5, 97);
-       MAKE_PAD (0, 6, 98);
-       MAKE_PAD (0, 7, 90);
-       MAKE_PAD (1, 0, 84);
-       MAKE_PAD (1, 1, 85);
-       MAKE_PAD (1, 2, 86);
-       MAKE_PAD (1, 3, 87);
-       MAKE_PAD (1, 4, 88);
-       MAKE_PAD (1, 5, 89);
-       MAKE_PAD (1, 6, 90);
-       MAKE_PAD (1, 7, 91);
-       MAKE_PAD (2, 0, 76);
-       MAKE_PAD (2, 1, 77);
-       MAKE_PAD (2, 2, 78);
-       MAKE_PAD (2, 3, 79);
-       MAKE_PAD (2, 4, 80);
-       MAKE_PAD (2, 5, 81);
-       MAKE_PAD (2, 6, 82);
-       MAKE_PAD (2, 7, 83);
-       MAKE_PAD (3, 0, 68);
-       MAKE_PAD (3, 1, 69);
-       MAKE_PAD (3, 2, 70);
-       MAKE_PAD (3, 3, 71);
-       MAKE_PAD (3, 4, 72);
-       MAKE_PAD (3, 5, 73);
-       MAKE_PAD (3, 6, 74);
-       MAKE_PAD (3, 7, 75);
-       MAKE_PAD (4, 0, 60);
-       MAKE_PAD (4, 1, 61);
-       MAKE_PAD (4, 2, 62);
-       MAKE_PAD (4, 3, 63);
-       MAKE_PAD (4, 4, 64);
-       MAKE_PAD (4, 5, 65);
-       MAKE_PAD (4, 6, 66);
-       MAKE_PAD (4, 7, 67);
-       MAKE_PAD (5, 0, 52);
-       MAKE_PAD (5, 1, 53);
-       MAKE_PAD (5, 2, 54);
-       MAKE_PAD (5, 3, 56);
-       MAKE_PAD (5, 4, 56);
-       MAKE_PAD (5, 5, 57);
-       MAKE_PAD (5, 6, 58);
-       MAKE_PAD (5, 7, 59);
-       MAKE_PAD (6, 0, 44);
-       MAKE_PAD (6, 1, 45);
-       MAKE_PAD (6, 2, 46);
-       MAKE_PAD (6, 3, 47);
-       MAKE_PAD (6, 4, 48);
-       MAKE_PAD (6, 5, 49);
-       MAKE_PAD (6, 6, 50);
-       MAKE_PAD (6, 7, 51);
-       MAKE_PAD (7, 0, 36);
-       MAKE_PAD (7, 1, 37);
-       MAKE_PAD (7, 2, 38);
-       MAKE_PAD (7, 3, 39);
-       MAKE_PAD (7, 4, 40);
-       MAKE_PAD (7, 5, 41);
-       MAKE_PAD (7, 6, 42);
-       MAKE_PAD (7, 7, 43);
-
-       /* Now color buttons */
-
-       Button *button;
-
-#define MAKE_COLOR_BUTTON(i,cc) \
-       button = new ColorButton ((i), (cc)); \
-       cc_button_map.insert (make_pair (button->controller_number(), button)); \
-       id_button_map.insert (make_pair (button->id, button));
-#define MAKE_COLOR_BUTTON_PRESS(i,cc,p)\
-       button = new ColorButton ((i), (cc), (p)); \
-       cc_button_map.insert (make_pair (button->controller_number(), button)); \
-       id_button_map.insert (make_pair (button->id, button))
-
-       MAKE_COLOR_BUTTON (Upper1, 102);
-       MAKE_COLOR_BUTTON (Upper2, 103);
-       MAKE_COLOR_BUTTON (Upper3, 104);
-       MAKE_COLOR_BUTTON (Upper4, 105);
-       MAKE_COLOR_BUTTON (Upper5, 106);
-       MAKE_COLOR_BUTTON (Upper6, 107);
-       MAKE_COLOR_BUTTON (Upper7, 108);
-       MAKE_COLOR_BUTTON (Upper8, 109);
-       MAKE_COLOR_BUTTON (Lower1, 21);
-       MAKE_COLOR_BUTTON (Lower2, 22);
-       MAKE_COLOR_BUTTON (Lower3, 23);
-       MAKE_COLOR_BUTTON (Lower4, 24);
-       MAKE_COLOR_BUTTON (Lower5, 25);
-       MAKE_COLOR_BUTTON (Lower6, 26);
-       MAKE_COLOR_BUTTON (Lower7, 27);
-       MAKE_COLOR_BUTTON (Mute, 60);
-       MAKE_COLOR_BUTTON (Solo, 61);
-       MAKE_COLOR_BUTTON (Stop, 29);
-       MAKE_COLOR_BUTTON (Fwd32ndT, 43);
-       MAKE_COLOR_BUTTON (Fwd32nd,42 );
-       MAKE_COLOR_BUTTON (Fwd16thT, 41);
-       MAKE_COLOR_BUTTON (Fwd16th, 40);
-       MAKE_COLOR_BUTTON (Fwd8thT, 39 );
-       MAKE_COLOR_BUTTON (Fwd8th, 38);
-       MAKE_COLOR_BUTTON (Fwd4trT, 37);
-       MAKE_COLOR_BUTTON (Fwd4tr, 36);
-       MAKE_COLOR_BUTTON (Automate, 89);
-       MAKE_COLOR_BUTTON_PRESS (RecordEnable, 86, &Push2::button_recenable);
-       MAKE_COLOR_BUTTON_PRESS (Play, 85, &Push2::button_play);
-
-#define MAKE_WHITE_BUTTON(i,cc)\
-       button = new WhiteButton ((i), (cc)); \
-       cc_button_map.insert (make_pair (button->controller_number(), button)); \
-       id_button_map.insert (make_pair (button->id, button))
-#define MAKE_WHITE_BUTTON_PRESS(i,cc,p)\
-       button = new WhiteButton ((i), (cc), (p)); \
-       cc_button_map.insert (make_pair (button->controller_number(), button)); \
-       id_button_map.insert (make_pair (button->id, button))
-
-       MAKE_WHITE_BUTTON (TapTempo, 3);
-       MAKE_WHITE_BUTTON_PRESS (Metronome, 9, &Push2::button_metronome);
-       MAKE_WHITE_BUTTON (Setup, 30);
-       MAKE_WHITE_BUTTON (User, 59);
-       MAKE_WHITE_BUTTON (Delete, 118);
-       MAKE_WHITE_BUTTON (AddDevice, 52);
-       MAKE_WHITE_BUTTON (Device, 110);
-       MAKE_WHITE_BUTTON (Mix, 112);
-       MAKE_WHITE_BUTTON (Undo, 119);
-       MAKE_WHITE_BUTTON (AddTrack, 53);
-       MAKE_WHITE_BUTTON (Browse, 113);
-       MAKE_WHITE_BUTTON (Convert, 35);
-       MAKE_WHITE_BUTTON (DoubleLoop, 117);
-       MAKE_WHITE_BUTTON (Quantize, 116);
-       MAKE_WHITE_BUTTON (Duplicate, 88);
-       MAKE_WHITE_BUTTON (New, 87);
-       MAKE_WHITE_BUTTON (FixedLength, 90);
-       MAKE_WHITE_BUTTON_PRESS (Up, 46, &Push2::button_up);
-       MAKE_WHITE_BUTTON_PRESS (Right, 45, &Push2::button_right);
-       MAKE_WHITE_BUTTON_PRESS (Down, 47, &Push2::button_down);
-       MAKE_WHITE_BUTTON_PRESS (Left, 44, &Push2::button_left);
-       MAKE_WHITE_BUTTON_PRESS (Repeat, 56, &Push2::button_repeat);
-       MAKE_WHITE_BUTTON (Accent, 57);
-       MAKE_WHITE_BUTTON (Scale, 58);
-       MAKE_WHITE_BUTTON (Layout, 31);
-       MAKE_WHITE_BUTTON (OctaveUp, 55);
-       MAKE_WHITE_BUTTON (PageRight, 63);
-       MAKE_WHITE_BUTTON (OctaveDown, 54);
-       MAKE_WHITE_BUTTON (PageLeft, 62);
-       MAKE_WHITE_BUTTON (Shift, 49);
-       MAKE_WHITE_BUTTON (Select, 48);
 }
 
 void
@@ -654,16 +970,17 @@ Push2::notify_record_state_changed ()
                return;
        }
 
-       b->second->set_color (LED::Red);
-
        switch (session->record_status ()) {
        case Session::Disabled:
-               b->second->set_state (LED::Off);
+               b->second->set_color (LED::White);
+               b->second->set_state (LED::NoTransition);
                break;
        case Session::Enabled:
+               b->second->set_color (LED::Red);
                b->second->set_state (LED::Blinking4th);
                break;
        case Session::Recording:
+               b->second->set_color (LED::Red);
                b->second->set_state (LED::OneShot24th);
                break;
        }
@@ -674,20 +991,25 @@ Push2::notify_record_state_changed ()
 void
 Push2::notify_transport_state_changed ()
 {
-       IDButtonMap::iterator b = id_button_map.find (Play);
-
-       if (b == id_button_map.end()) {
-               return;
-       }
+       Button* b = id_button_map[Play];
 
        if (session->transport_rolling()) {
-               b->second->set_state (LED::OneShot24th);
-               b->second->set_color (LED::Blue);
+               b->set_state (LED::OneShot24th);
+               b->set_color (LED::Green);
        } else {
-               b->second->set_state (LED::Off);
+
+               /* disable any blink on FixedLength from pending edit range op */
+               Button* fl = id_button_map[FixedLength];
+
+               fl->set_color (LED::Black);
+               fl->set_state (LED::NoTransition);
+               write (fl->state_msg());
+
+               b->set_color (LED::White);
+               b->set_state (LED::NoTransition);
        }
 
-       write (b->second->state_msg());
+       write (b->state_msg());
 }
 
 void
@@ -696,8 +1018,23 @@ Push2::notify_loop_state_changed ()
 }
 
 void
-Push2::notify_parameter_changed (std::string)
+Push2::notify_parameter_changed (std::string param)
 {
+       IDButtonMap::iterator b;
+
+       if (param == "clicking") {
+               if ((b = id_button_map.find (Metronome)) == id_button_map.end()) {
+                       return;
+               }
+               if (Config->get_clicking()) {
+                       b->second->set_state (LED::Blinking4th);
+                       b->second->set_color (LED::White);
+               } else {
+                       b->second->set_color (LED::White);
+                       b->second->set_state (LED::NoTransition);
+               }
+               write (b->second->state_msg ());
+       }
 }
 
 void
@@ -710,9 +1047,11 @@ Push2::notify_solo_active_changed (bool yn)
        }
 
        if (yn) {
-               b->second->set_state (LED::Blinking24th);
+               b->second->set_state (LED::Blinking4th);
+               b->second->set_color (LED::Red);
        } else {
-               b->second->set_state (LED::Off);
+               b->second->set_state (LED::NoTransition);
+               b->second->set_color (LED::White);
        }
 
        write (b->second->state_msg());
@@ -731,6 +1070,11 @@ Push2::get_state()
        child->add_child_nocopy (_async_out->get_state());
        node.add_child_nocopy (*child);
 
+       node.add_property (X_("root"), to_string (_scale_root, std::dec));
+       node.add_property (X_("root_octave"), to_string (_root_octave, std::dec));
+       node.add_property (X_("in_key"), _in_key ? X_("yes") : X_("no"));
+       node.add_property (X_("mode"), enum_2_string (_mode));
+
        return node;
 }
 
@@ -761,5 +1105,633 @@ Push2::set_state (const XMLNode & node, int version)
                }
        }
 
+       XMLProperty const* prop;
+
+       if ((prop = node.property (X_("root"))) != 0) {
+               _scale_root = atoi (prop->value());
+       }
+
+       if ((prop = node.property (X_("root_octave"))) != 0) {
+               _root_octave = atoi (prop->value());
+       }
+
+       if ((prop = node.property (X_("in_key"))) != 0) {
+               _in_key = string_is_affirmative (prop->value());
+       }
+
+       if ((prop = node.property (X_("mode"))) != 0) {
+               _mode = (MusicalMode::Type) string_2_enum (prop->value(), _mode);
+       }
+
        return retval;
 }
+
+void
+Push2::other_vpot (int n, int delta)
+{
+       switch (n) {
+       case 0:
+               break;
+       case 1:
+               break;
+       case 2:
+               /* master gain control */
+               if (master) {
+                       boost::shared_ptr<AutomationControl> ac = master->gain_control();
+                       if (ac) {
+                               ac->set_value (ac->get_value() + ((2.0/64.0) * delta), PBD::Controllable::UseGroup);
+                       }
+               }
+               break;
+       }
+}
+
+void
+Push2::other_vpot_touch (int n, bool touching)
+{
+       switch (n) {
+       case 0:
+               break;
+       case 1:
+               break;
+       case 2:
+               if (master) {
+                       boost::shared_ptr<AutomationControl> ac = master->gain_control();
+                       if (ac) {
+                               if (touching) {
+                                       ac->start_touch (session->audible_frame());
+                               } else {
+                                       ac->stop_touch (true, session->audible_frame());
+                               }
+                       }
+               }
+       }
+}
+
+void
+Push2::start_shift ()
+{
+       cerr << "start shift\n";
+       _modifier_state = ModifierState (_modifier_state | ModShift);
+       Button* b = id_button_map[Shift];
+       b->set_color (LED::White);
+       b->set_state (LED::Blinking16th);
+       write (b->state_msg());
+}
+
+void
+Push2::end_shift ()
+{
+       if (_modifier_state & ModShift) {
+               cerr << "end shift\n";
+               _modifier_state = ModifierState (_modifier_state & ~(ModShift));
+               Button* b = id_button_map[Shift];
+               b->timeout_connection.disconnect ();
+               b->set_color (LED::White);
+               b->set_state (LED::OneShot24th);
+               write (b->state_msg());
+       }
+}
+
+void
+Push2::splash ()
+{
+       std::string splash_file;
+
+       Searchpath rc (ARDOUR::ardour_data_search_path());
+       rc.add_subdirectory_to_paths ("resources");
+
+       if (!find_file (rc, PROGRAM_NAME "-splash.png", splash_file)) {
+               cerr << "Cannot find splash screen image file\n";
+               throw failed_constructor();
+       }
+
+       Cairo::RefPtr<Cairo::ImageSurface> img = Cairo::ImageSurface::create_from_png (splash_file);
+
+       double x_ratio = (double) img->get_width() / (cols - 20);
+       double y_ratio = (double) img->get_height() / (rows - 20);
+       double scale = min (x_ratio, y_ratio);
+
+       /* background */
+
+       context->set_source_rgb (0.764, 0.882, 0.882);
+       context->paint ();
+
+       /* image */
+
+       context->save ();
+       context->translate (5, 5);
+       context->scale (scale, scale);
+       context->set_source (img, 0, 0);
+       context->paint ();
+       context->restore ();
+
+       /* text */
+
+       Glib::RefPtr<Pango::Layout> some_text = Pango::Layout::create (context);
+
+       Pango::FontDescription fd ("Sans 38");
+       some_text->set_font_description (fd);
+       some_text->set_text (string_compose ("%1 %2", PROGRAM_NAME, VERSIONSTRING));
+
+       context->move_to (200, 10);
+       context->set_source_rgb (0, 0, 0);
+       some_text->update_from_cairo_context (context);
+       some_text->show_in_cairo_context (context);
+
+       Pango::FontDescription fd2 ("Sans Italic 18");
+       some_text->set_font_description (fd2);
+       some_text->set_text (_("Ableton Push 2 Support"));
+
+       context->move_to (200, 80);
+       context->set_source_rgb (0, 0, 0);
+       some_text->update_from_cairo_context (context);
+       some_text->show_in_cairo_context (context);
+
+       splash_start = get_microseconds ();
+       blit_to_device_frame_buffer ();
+}
+
+bool
+Push2::pad_filter (MidiBuffer& in, MidiBuffer& out) const
+{
+       /* This filter is called asynchronously from a realtime process
+          context. It must use atomics to check state, and must not block.
+       */
+
+       bool matched = false;
+
+       for (MidiBuffer::iterator ev = in.begin(); ev != in.end(); ++ev) {
+               if ((*ev).is_note_on() || (*ev).is_note_off()) {
+
+                       /* encoder touch start/touch end use note
+                        * 0-10. touchstrip uses note 12
+                        */
+
+                       if ((*ev).note() > 10 && (*ev).note() != 12) {
+
+                               const int n = (*ev).note ();
+                               NNPadMap::const_iterator nni = nn_pad_map.find (n);
+
+                               if (nni != nn_pad_map.end()) {
+                                       Pad const * pad = nni->second;
+                                       /* shift for output to the shadow port */
+                                       if (pad->filtered >= 0) {
+                                               (*ev).set_note (pad->filtered + (octave_shift*12));
+                                               out.push_back (*ev);
+                                               /* shift back so that the pads light correctly  */
+                                               (*ev).set_note (n);
+                                       } else {
+                                               /* no mapping, don't send event */
+                                       }
+                               } else {
+                                       out.push_back (*ev);
+                               }
+
+                               matched = true;
+                       }
+               } else if ((*ev).is_pitch_bender() || (*ev).is_aftertouch() || (*ev).is_channel_pressure()) {
+                       out.push_back (*ev);
+               }
+       }
+
+       return matched;
+}
+
+bool
+Push2::connection_handler (boost::weak_ptr<ARDOUR::Port>, std::string name1, boost::weak_ptr<ARDOUR::Port>, std::string name2, bool yn)
+{
+       DEBUG_TRACE (DEBUG::FaderPort, "FaderPort::connection_handler  start\n");
+       if (!_input_port || !_output_port) {
+               return false;
+       }
+
+       string ni = ARDOUR::AudioEngine::instance()->make_port_name_non_relative (boost::shared_ptr<ARDOUR::Port>(_async_in)->name());
+       string no = ARDOUR::AudioEngine::instance()->make_port_name_non_relative (boost::shared_ptr<ARDOUR::Port>(_async_out)->name());
+
+       if (ni == name1 || ni == name2) {
+               if (yn) {
+                       connection_state |= InputConnected;
+               } else {
+                       connection_state &= ~InputConnected;
+               }
+       } else if (no == name1 || no == name2) {
+               if (yn) {
+                       connection_state |= OutputConnected;
+               } else {
+                       connection_state &= ~OutputConnected;
+               }
+       } else {
+               DEBUG_TRACE (DEBUG::FaderPort, string_compose ("Connections between %1 and %2 changed, but I ignored it\n", name1, name2));
+               /* not our ports */
+               return false;
+       }
+
+       if ((connection_state & (InputConnected|OutputConnected)) == (InputConnected|OutputConnected)) {
+
+               /* XXX this is a horrible hack. Without a short sleep here,
+                  something prevents the device wakeup messages from being
+                  sent and/or the responses from being received.
+               */
+
+               g_usleep (100000);
+                DEBUG_TRACE (DEBUG::FaderPort, "device now connected for both input and output\n");
+                // connected ();
+
+       } else {
+               DEBUG_TRACE (DEBUG::FaderPort, "Device disconnected (input or output or both) or not yet fully connected\n");
+       }
+
+       ConnectionChange (); /* emit signal for our GUI */
+
+       DEBUG_TRACE (DEBUG::FaderPort, "FaderPort::connection_handler  end\n");
+
+       return true; /* connection status changed */
+}
+
+boost::shared_ptr<Port>
+Push2::output_port()
+{
+       return _async_out;
+}
+
+boost::shared_ptr<Port>
+Push2::input_port()
+{
+       return _async_in;
+}
+
+int
+Push2::pad_note (int row, int col) const
+{
+       NNPadMap::const_iterator nni = nn_pad_map.find (36+(row*8)+col);
+
+       if (nni != nn_pad_map.end()) {
+               return nni->second->filtered;
+       }
+
+       return 0;
+}
+
+void
+Push2::set_pad_scale (int root, int octave, MusicalMode::Type mode, bool inkey)
+{
+       MusicalMode m (mode);
+       vector<float>::iterator interval;
+       int note;
+       const int original_root = root;
+
+       interval = m.steps.begin();
+       root += (octave*12);
+       note = root;
+
+       const int root_start = root;
+
+       set<int> mode_map; /* contains only notes in mode, O(logN) lookup */
+       vector<int> mode_vector; /* sorted in note order */
+
+       mode_map.insert (note);
+       mode_vector.push_back (note);
+
+       /* build a map of all notes in the mode, from the root to 127 */
+
+       while (note < 128) {
+
+               if (interval == m.steps.end()) {
+
+                       /* last distance was the end of the scale,
+                          so wrap, adding the next note at one
+                          octave above the last root.
+                       */
+
+                       interval = m.steps.begin();
+                       root += 12;
+                       mode_map.insert (root);
+                       mode_vector.push_back (root);
+
+               } else {
+                       note = (int) floor (root + (2.0 * (*interval)));
+                       interval++;
+                       mode_map.insert (note);
+                       mode_vector.push_back (note);
+               }
+       }
+
+       if (inkey) {
+
+               vector<int>::iterator notei;
+               int row_offset = 0;
+               for (int row = 0; row < 8; ++row) {
+
+                       /* Ableton's grid layout wraps the available notes in the scale
+                        * by offsetting 3 notes per row (from the bottom)
+                        */
+
+                       notei = mode_vector.begin();
+                       notei += row_offset;
+                       row_offset += 3;
+
+                       for (int col = 0; col < 8; ++col) {
+                               int index = 36 + (row*8) + col;
+                               Pad* pad = nn_pad_map[index];
+                               int notenum;
+                               if (notei != mode_vector.end()) {
+
+                                       notenum = *notei;
+                                       pad->filtered = notenum;
+
+                                       if ((notenum % 12) == original_root) {
+                                               pad->set_color (LED::Green);
+                                               pad->perma_color = LED::Green;
+                                       } else {
+                                               pad->set_color (LED::White);
+                                               pad->perma_color = LED::White;
+                                       }
+
+                                       pad->do_when_pressed = Pad::FlashOff;
+                                       notei++;
+
+                               } else {
+
+                                       pad->set_color (LED::Black);
+                                       pad->do_when_pressed = Pad::Nothing;
+                                       pad->filtered = -1;
+                               }
+
+                               write (pad->state_msg());
+                       }
+               }
+
+       } else {
+
+               /* chromatic: all notes available, but highlight those in the scale */
+
+               for (note = 36; note < 100; ++note) {
+
+                       Pad* pad = nn_pad_map[note];
+
+                       /* Chromatic: all pads play, half-tone steps. Light
+                        * those in the scale, and highlight root notes
+                        */
+
+                       pad->filtered = root_start + (note - 36);
+
+                       if (mode_map.find (note) != mode_map.end()) {
+
+                               if ((note % 12) == original_root) {
+                                       pad->set_color (LED::Green);
+                                       pad->perma_color = LED::Green;
+                               } else {
+                                       pad->set_color (LED::White);
+                                       pad->perma_color = LED::White;
+                               }
+
+                               pad->do_when_pressed = Pad::FlashOff;
+
+                       } else {
+
+                               /* note is not in mode, turn it off */
+
+                               pad->do_when_pressed = Pad::FlashOn;
+                               pad->set_color (LED::Black);
+
+                       }
+
+                       write (pad->state_msg());
+               }
+       }
+
+       PadChange (); /* EMIT SIGNAL */
+
+       /* store state */
+
+       _scale_root = original_root;
+       _root_octave = octave;
+       _in_key = inkey;
+       _mode = mode;
+}
+
+void
+Push2::set_percussive_mode (bool yn)
+{
+       if (!yn) {
+               cerr << "back to scale\n";
+               set_pad_scale (_scale_root, _root_octave, _mode, _in_key);
+               percussion = false;
+               return;
+       }
+
+       int drum_note = 36;
+
+       for (int row = 0; row < 8; ++row) {
+
+               for (int col = 0; col < 4; ++col) {
+
+                       int index = 36 + (row*8) + col;
+                       Pad* pad = nn_pad_map[index];
+
+                       pad->filtered = drum_note;
+                       drum_note++;
+               }
+       }
+
+       for (int row = 0; row < 8; ++row) {
+
+               for (int col = 4; col < 8; ++col) {
+
+                       int index = 36 + (row*8) + col;
+                       Pad* pad = nn_pad_map[index];
+
+                       pad->filtered = drum_note;
+                       drum_note++;
+               }
+       }
+
+       percussion = true;
+
+       PadChange (); /* EMIT SIGNAL */
+}
+
+Push2Layout*
+Push2::current_layout () const
+{
+       Glib::Threads::Mutex::Lock lm (layout_lock);
+       return _current_layout;
+}
+
+void
+Push2::stripable_selection_change (StripableNotificationListPtr selected)
+{
+       boost::shared_ptr<MidiPort> pad_port = boost::dynamic_pointer_cast<AsyncMIDIPort>(_async_in)->shadow_port();
+       boost::shared_ptr<MidiTrack> current_midi_track = current_pad_target.lock();
+       boost::shared_ptr<MidiTrack> new_pad_target;
+
+       /* See if there's a MIDI track selected */
+
+       for (StripableNotificationList::iterator si = selected->begin(); si != selected->end(); ++si) {
+
+               new_pad_target = boost::dynamic_pointer_cast<MidiTrack> ((*si).lock());
+
+               if (new_pad_target) {
+                       break;
+               }
+       }
+
+       if (new_pad_target) {
+               cerr << "new midi pad target " << new_pad_target->name() << endl;
+       } else {
+               cerr << "no midi pad target\n";
+       }
+
+       if (current_midi_track == new_pad_target) {
+               /* nothing to do */
+               return;
+       }
+
+       if (!new_pad_target) {
+               /* leave existing connection alone */
+               return;
+       }
+
+       /* disconnect from pad port, if appropriate */
+
+       if (current_midi_track && pad_port) {
+               cerr << "Disconnect pads from " << current_midi_track->name() << endl;
+               current_midi_track->input()->disconnect (current_midi_track->input()->nth(0), pad_port->name(), this);
+       }
+
+       /* now connect the pad port to this (newly) selected midi
+        * track, if indeed there is one.
+        */
+
+       if (new_pad_target && pad_port) {
+               cerr << "Reconnect pads to " << new_pad_target->name() << endl;
+               new_pad_target->input()->connect (new_pad_target->input()->nth (0), pad_port->name(), this);
+               current_pad_target = new_pad_target;
+       } else {
+               current_pad_target.reset ();
+       }
+}
+
+Push2::Button*
+Push2::button_by_id (ButtonID bid)
+{
+       return id_button_map[bid];
+}
+
+uint8_t
+Push2::get_color_index (uint32_t rgb)
+{
+       ColorMap::iterator i = color_map.find (rgb);
+
+       if (i != color_map.end()) {
+               return i->second;
+       }
+
+       int r, g, b, a;
+       UINT_TO_RGBA (rgb, &r, &g, &b, &a);
+       int w = 204; /* not sure where/when we should get this value */
+
+       /* get a free index */
+
+       uint8_t index;
+
+       if (color_map_free_list.empty()) {
+               /* random replacement of any entry above zero and below 122 (where the
+                * Ableton standard colors live)
+                */
+               index = 1 + (random() % 121);
+       } else {
+               index = color_map_free_list.top();
+               color_map_free_list.pop();
+       }
+
+       MidiByteArray palette_msg (17, 0xf0, 0x00 , 0x21, 0x1d, 0x01, 0x01, 0x03, 0x7D, 0x00, 0x00, 0x00, 0x00, 0x7F, 0x01, 0x7E, 0x00, 0xF7);
+       MidiByteArray update_pallette_msg (8, 0xf0, 0x00, 0x21, 0x1d, 0x01, 0x01, 0x05, 0xF7);
+
+       palette_msg[7] = index;
+       palette_msg[8] = r & 0x7f;
+       palette_msg[9] = r & 0x1;
+       palette_msg[10] = g & 0x7f;
+       palette_msg[11] = g & 0x1;
+       palette_msg[12] = b & 0x7f;
+       palette_msg[13] = b & 0x1;
+       palette_msg[14] = w & 0x7f;
+       palette_msg[15] = w & 0x1;
+
+       write (palette_msg);
+       write (update_pallette_msg);
+
+       color_map[index] = rgb;
+
+       return index;
+}
+
+void
+Push2::build_color_map ()
+{
+       /* These are "standard" colors that Ableton docs suggest will always be
+          there. Put them in our color map so that when we look up these
+          colors, we will use the Ableton indices for them.
+       */
+
+       color_map.insert (make_pair (RGB_TO_UINT (0,0,0), 0));
+       color_map.insert (make_pair (RGB_TO_UINT (204,204,204), 122));
+       color_map.insert (make_pair (RGB_TO_UINT (64,64,64), 123));
+       color_map.insert (make_pair (RGB_TO_UINT (20,20,20), 124));
+       color_map.insert (make_pair (RGB_TO_UINT (0,0,255), 125));
+       color_map.insert (make_pair (RGB_TO_UINT (0,255,0), 126));
+       color_map.insert (make_pair (RGB_TO_UINT (255,0,0), 127));
+
+       for (uint8_t n = 1; n < 122; ++n) {
+               color_map_free_list.push (n);
+       }
+}
+
+void
+Push2::fill_color_table ()
+{
+       colors.insert (make_pair (DarkBackground, ArdourCanvas::rgba_to_color (0, 0, 0, 1)));
+       colors.insert (make_pair (LightBackground, ArdourCanvas::rgba_to_color (0.98, 0.98, 0.98, 1)));
+
+       colors.insert (make_pair (ParameterName, ArdourCanvas::rgba_to_color (0.98, 0.98, 0.98, 1)));
+
+       colors.insert (make_pair (KnobArcBackground, ArdourCanvas::rgba_to_color (0.3, 0.3, 0.3, 1.0)));
+       colors.insert (make_pair (KnobArcStart, ArdourCanvas::rgba_to_color (1.0, 0.0, 0.0, 1.0)));
+       colors.insert (make_pair (KnobArcEnd, ArdourCanvas::rgba_to_color (0.0, 1.0, 0.0, 1.0)));
+
+       colors.insert (make_pair (KnobLineShadow, ArdourCanvas::rgba_to_color  (0, 0, 0, 0.3)));
+       colors.insert (make_pair (KnobLine, ArdourCanvas::rgba_to_color (1, 1, 1, 1)));
+
+       colors.insert (make_pair (KnobForeground, ArdourCanvas::rgba_to_color (0.2, 0.2, 0.2, 1)));
+       colors.insert (make_pair (KnobBackground, ArdourCanvas::rgba_to_color (0.2, 0.2, 0.2, 1)));
+       colors.insert (make_pair (KnobShadow, ArdourCanvas::rgba_to_color (0, 0, 0, 0.1)));
+       colors.insert (make_pair (KnobBorder, ArdourCanvas::rgba_to_color (0, 0, 0, 1)));
+
+}
+
+uint32_t
+Push2::get_color (ColorName name)
+{
+       Colors::iterator c = colors.find (name);
+       if (c != colors.end()) {
+               return c->second;
+       }
+
+       return random();
+}
+
+void
+Push2::set_current_layout (Push2Layout* layout)
+{
+       if (_current_layout) {
+               _current_layout->on_hide ();
+       }
+
+       _current_layout = layout;
+       drawn_layout = 0;
+
+       if (_current_layout) {
+               _current_layout->on_show ();
+       }
+}