remove unused and useless stuff relating to bundles inside Mackie::Strip
[ardour.git] / libs / surfaces / mackie / surface.cc
index 9fecc2556e64501e457e1cb90b4debb378be1e08..020b389ad4a48bec5ff58cee0324b2ed33d4e148 100644 (file)
@@ -1,24 +1,48 @@
+/*
+    Copyright (C) 2012 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 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.
+
+*/
+
 #include <sstream>
 #include <iomanip>
 #include <iostream>
 #include <cstdio>
 #include <cmath>
 
+#include <glibmm/convert.h>
+
 #include "midi++/port.h"
-#include "midi++/manager.h"
 
+#include "ardour/audioengine.h"
+#include "ardour/automation_control.h"
 #include "ardour/debug.h"
 #include "ardour/route.h"
 #include "ardour/panner.h"
 #include "ardour/panner_shell.h"
 #include "ardour/rc_configuration.h"
+#include "ardour/session.h"
+#include "ardour/utils.h"
 
 #include "control_group.h"
 #include "surface_port.h"
 #include "surface.h"
 #include "strip.h"
 #include "mackie_control_protocol.h"
-#include "mackie_jog_wheel.h"
+#include "jog_wheel.h"
 
 #include "strip.h"
 #include "button.h"
 
 #include "i18n.h"
 
+#ifdef PLATFORM_WINDOWS
+#define random() rand()
+#endif
+
 using namespace std;
 using namespace PBD;
-using namespace Mackie;
 using ARDOUR::Route;
 using ARDOUR::Panner;
 using ARDOUR::Pannable;
-using ARDOUR::PannerShell;
+using ARDOUR::AutomationControl;
+using namespace ArdourSurface;
+using namespace Mackie;
+
+#define ui_context() MackieControlProtocol::instance() /* a UICallback-derived object that specifies the event loop for signal handling */
 
 // The MCU sysex header.4th byte Will be overwritten
 // when we get an incoming sysex that identifies
@@ -50,150 +81,191 @@ static MidiByteArray mackie_sysex_hdr_xt  (5, MIDI::sysex, 0x0, 0x0, 0x66, 0x15)
 
 static MidiByteArray empty_midi_byte_array;
 
-static GlobalControlDefinition mackie_global_controls[] = {
-       { "jog", 0x3c, Jog::factory, "none" },
-       { "external", 0x2e, Pot::factory, "none" },
-       { "io", 0x28, Button::factory, "assignment" },
-       { "sends", 0x29, Button::factory, "assignment" },
-       { "pan", 0x2a, Button::factory, "assignment" },
-       { "plugin", 0x2b, Button::factory, "assignment" },
-       { "eq", 0x2c, Button::factory, "assignment" },
-       { "dyn", 0x2d, Button::factory, "assignment" },
-       { "left", 0x2e, Button::factory, "bank" },
-       { "right", 0x2f, Button::factory, "bank" },
-       { "channel_left", 0x30, Button::factory, "bank" },
-       { "channel_right", 0x31, Button::factory, "bank" },
-       { "flip", 0x32, Button::factory, "none" },
-       { "edit", 0x33, Button::factory, "none" },
-       { "name_value", 0x34, Button::factory, "display" },
-       { "timecode_beats", 0x35, Button::factory, "display" },
-       { "F1", Button::F1, Button::factory, "none" },
-       { "F2", Button::F2, Button::factory, "none" },
-       { "F3", Button::F3, Button::factory, "none" },
-       { "F4", Button::F4, Button::factory, "none" },
-       { "F5", Button::F5, Button::factory, "none" },
-       { "F6", Button::F6, Button::factory, "none" },
-       { "F7", Button::F7, Button::factory, "none" },
-       { "F8", Button::F8, Button::factory, "none" },
-       { "F9", Button::F9, Button::factory, "none" },
-       { "F10", Button::F10, Button::factory, "none" },
-       { "F11", Button::F11, Button::factory, "none" },
-       { "F12", Button::F12, Button::factory, "none" },
-       { "F13", Button::F13, Button::factory, "none" },
-       { "F14", Button::F14, Button::factory, "none" },
-       { "F15", Button::F15, Button::factory, "none" },
-       { "F16", Button::F16, Button::factory, "none" },
-       { "shift", 0x46, Button::factory, "modifiers" },
-       { "option", 0x47, Button::factory, "modifiers" },
-       { "control", 0x48, Button::factory, "modifiers" },
-       { "cmd_alt", 0x49, Button::factory, "modifiers" },
-       { "on", 0x4a, Button::factory, "automation" },
-       { "rec_ready", 0x4b, Button::factory, "automation" },
-       { "undo", 0x4c, Button::factory, "functions" },
-       { "save", Button::Save, Button::factory, "automation" },
-       { "touch", Button::Touch, Button::factory, "automation" },
-       { "redo", Button::Redo, Button::factory, "functions" },
-       { "marker", Button::Marker, Button::factory, "functions" },
-       { "enter", Button::Enter, Button::factory, "functions" },
-       { "cancel", Button::Cancel, Button::factory, "functions" },
-       { "mixer", Button::Mixer, Button::factory, "functions" },
-       { "frm_left", 0x54, Button::factory, "transport" },
-       { "frm_right", 0x55, Button::factory, "transport" },
-       { "loop", Button::Loop, Button::factory, "transport" },
-       { "punch_in", 0x57, Button::factory, "transport" },
-       { "punch_out", 0x58, Button::factory, "transport" },
-       { "home", Button::Home, Button::factory, "transport" },
-       { "end", Button::End, Button::factory, "transport" },
-       { "rewind", Button::Rewind, Button::factory, "transport" },
-       { "ffwd", Button::Ffwd, Button::factory, "transport" },
-       { "stop", Button::Stop, Button::factory, "transport" },
-       { "play", Button::Play, Button::factory, "transport" },
-       { "record", Button::Record, Button::factory, "transport" },
-       { "cursor_up", Button::CursorUp, Button::factory, "cursor" },
-       { "cursor_down", Button::CursorDown, Button::factory, "cursor" },
-       { "cursor_left", Button::CursorLeft, Button::factory, "cursor" },
-       { "cursor_right", Button::CursorRight, Button::factory, "cursor" },
-       { "zoom", Button::Zoom, Button::factory, "none" },
-       { "scrub", Button::Scrub, Button::factory, "none" },
-       { "user_a", Button::UserA, Button::factory, "user" },
-       { "user_b", Button::UserB, Button::factory, "user" },
-       { "fader_touch", 0x70, Led::factory, "master" },
-       { "timecode", 0x71, Led::factory, "none" },
-       { "beats", 0x72, Led::factory, "none" },
-       { "solo", 0x73, Led::factory, "none" },
-       { "relay_click", 0x73, Led::factory, "none" },
-       { "", 0, Button::factory, "" }
-};
-       
 Surface::Surface (MackieControlProtocol& mcp, const std::string& device_name, uint32_t number, surface_type_t stype)
        : _mcp (mcp)
        , _stype (stype)
        , _number (number)
        , _name (device_name)
-       , _active (true)
+       , _active (false)
        , _connected (false)
        , _jog_wheel (0)
+       , _master_fader (0)
+       , _last_master_gain_written (-0.0f)
+       , connection_state (0)
+       , input_source (0)
 {
-       DEBUG_TRACE (DEBUG::MackieControl, "Surface::init\n");
-       
-       _port = new SurfacePort (*this);
+       DEBUG_TRACE (DEBUG::MackieControl, "Surface::Surface init\n");
 
-       if (_mcp.device_info().has_global_controls()) {
-               init_controls ();
+       try {
+               _port = new SurfacePort (*this);
+       } catch (...) {
+               throw failed_constructor ();
        }
 
-       if (_mcp.device_info().has_jog_wheel()) {
-               _jog_wheel = new Mackie::JogWheel (_mcp);
+       /* only the first Surface object has global controls */
+       /* lets use master_position instead */
+       uint32_t mp = _mcp.device_info().master_position();
+       if (_number == mp) {
+               DEBUG_TRACE (DEBUG::MackieControl, "Surface matches MasterPosition. Might have global controls.\n");
+               if (_mcp.device_info().has_global_controls()) {
+                       init_controls ();
+                       DEBUG_TRACE (DEBUG::MackieControl, "init_controls done\n");
+               }
+
+               if (_mcp.device_info().has_master_fader()) {
+                       setup_master ();
+                       DEBUG_TRACE (DEBUG::MackieControl, "setup_master done\n");
+               }
        }
 
        uint32_t n = _mcp.device_info().strip_cnt();
-       
+
        if (n) {
                init_strips (n);
+               DEBUG_TRACE (DEBUG::MackieControl, "init_strips done\n");
        }
 
-       connect_to_signals ();
-
-       /* wakey wakey */
+       if (!_mcp.device_info().uses_ipmidi()) {
+               ARDOUR::AudioEngine::instance()->PortConnectedOrDisconnected.connect (port_connection, MISSING_INVALIDATOR, boost::bind (&Surface::connection_handler, this, _1, _2, _3, _4, _5), &_mcp);
+       } else {
+               /* ipMIDI port already exists, we can just assume that we're
+                * connected.
+                *
+                * If the user still hasn't connected the ipMIDI surface and/or
+                * turned it on, then they have to press "Discover Mackie
+                * Devices" in the GUI at the right time.
+                */
+
+               connection_state |= (InputConnected|OutputConnected);
+               connected ();
+       }
 
-       MidiByteArray wakeup (7, MIDI::sysex, 0x00, 0x00, 0x66, 0x14, 0x00, MIDI::eox);
-       _port->write (wakeup);
-       wakeup[4] = 0x15; /* wakup Mackie XT */
-       _port->write (wakeup);
-       wakeup[4] = 0x10; /* wakupe Logic Control */
-       _port->write (wakeup);
-       wakeup[4] = 0x11; /* wakeup Logic Control XT */
-       _port->write (wakeup);
+       connect_to_signals ();
 
-       DEBUG_TRACE (DEBUG::MackieControl, "Surface::init finish\n");
+       DEBUG_TRACE (DEBUG::MackieControl, "Surface::Surface done\n");
 }
 
 Surface::~Surface ()
 {
-       DEBUG_TRACE (DEBUG::MackieControl, "Surface: destructor\n");
+       DEBUG_TRACE (DEBUG::MackieControl, "Surface::~Surface init\n");
 
-       // faders to minimum
-       write_sysex (0x61);
-       // All LEDs off
-       write_sysex (0x62);
-       // Reset (reboot into offline mode)
-       // _write_sysex (0x63);
+       // zero_all ();
 
        // delete groups
        for (Groups::iterator it = groups.begin(); it != groups.end(); ++it) {
                delete it->second;
        }
-       
+
        // delete controls
        for (Controls::iterator it = controls.begin(); it != controls.end(); ++it) {
                delete *it;
        }
-       
+
+       port_connection.disconnect ();
+
+       if (input_source) {
+               g_source_destroy (input_source);
+               input_source = 0;
+       }
+
        delete _jog_wheel;
        delete _port;
+
+       DEBUG_TRACE (DEBUG::MackieControl, "Surface::~Surface done\n");
+}
+
+void
+Surface::connection_handler (boost::weak_ptr<ARDOUR::Port>, std::string name1, boost::weak_ptr<ARDOUR::Port>, std::string name2, bool yn)
+{
+       if (!_port) {
+               return;
+       }
+
+       string ni = ARDOUR::AudioEngine::instance()->make_port_name_non_relative (_port->input_name());
+       string no = ARDOUR::AudioEngine::instance()->make_port_name_non_relative (_port->output_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;
+               }
+       }
+
+       if ((connection_state & (InputConnected|OutputConnected)) == (InputConnected|OutputConnected)) {
+
+               /* this will send a device query message, which should
+                  result in a response that will kick off device type
+                  discovery and activation of the surface(s).
+
+                  The intended order of events is:
+
+                  - each surface sends a device query message
+                  - devices respond with either MCP or LCP response (sysex in both
+                  cases)
+                  - sysex message causes Surface::turn_it_on() which tells the
+                  MCP object that the surface is ready, and sets up strip
+                  displays and binds faders and buttons for that surface
+
+                  In the case of LCP, where this is a handshake process that could
+                  fail, the response process to the initial sysex after a device query
+                  will mark the surface inactive, which won't shut anything down
+                  but will stop any writes to the device.
+
+                  Note: there are no known cases of the handshake process failing.
+
+                  We actually can't initiate this in this callback, so we have
+                  to queue it with the MCP event loop.
+               */
+
+               connected ();
+
+       } else {
+               DEBUG_TRACE (DEBUG::MackieControl, string_compose ("Surface %1 disconnected (input or output or both)\n", _name));
+               _active = false;
+       }
+}
+
+XMLNode&
+Surface::get_state()
+{
+       char buf[64];
+       snprintf (buf, sizeof (buf), X_("surface-%u"), _number);
+       XMLNode* node = new XMLNode (buf);
+
+       node->add_child_nocopy (_port->get_state());
+
+       return *node;
+}
+
+int
+Surface::set_state (const XMLNode& node, int version)
+{
+       char buf[64];
+       snprintf (buf, sizeof (buf), X_("surface-%u"), _number);
+       XMLNode* mynode = node.child (buf);
+
+       if (!mynode) {
+               return 0;
+       }
+
+       XMLNode* portnode = mynode->child (X_("Port"));
+       if (portnode) {
+               if (_port->set_state (*portnode, version)) {
+                       return -1;
+               }
+       }
+
+       return 0;
 }
 
-const MidiByteArray& 
+const MidiByteArray&
 Surface::sysex_hdr() const
 {
        switch  (_stype) {
@@ -204,111 +276,180 @@ Surface::sysex_hdr() const
        return mackie_sysex_hdr;
 }
 
-void 
+static GlobalControlDefinition mackie_global_controls[] = {
+       { "external", Pot::External, Pot::factory, "none" },
+       { "fader_touch", Led::FaderTouch, Led::factory, "master" },
+       { "timecode", Led::Timecode, Led::factory, "none" },
+       { "beats", Led::Beats, Led::factory, "none" },
+       { "solo", Led::RudeSolo, Led::factory, "none" },
+       { "relay_click", Led::RelayClick, Led::factory, "none" },
+       { "", 0, Led::factory, "" }
+};
+
+void
 Surface::init_controls()
 {
        Group* group;
 
+       DEBUG_TRACE (DEBUG::MackieControl, "Surface::init_controls: creating groups\n");
        groups["assignment"] = new Group  ("assignment");
        groups["automation"] = new Group  ("automation");
        groups["bank"] = new Group  ("bank");
        groups["cursor"] = new Group  ("cursor");
        groups["display"] = new Group  ("display");
-       groups["functions"] = new Group  ("functions");
+       groups["function select"] = new Group  ("function select");
+       groups["global view"] = new Group ("global view");
+       groups["master"] = new Group ("master");
        groups["modifiers"] = new Group  ("modifiers");
        groups["none"] = new Group  ("none");
        groups["transport"] = new Group  ("transport");
        groups["user"] = new Group  ("user");
-       groups["master"] = new Group ("master");
+       groups["utilities"] = new Group  ("utilities");
+
+       DEBUG_TRACE (DEBUG::MackieControl, "Surface::init_controls: creating jog wheel\n");
+       if (_mcp.device_info().has_jog_wheel()) {
+               _jog_wheel = new Mackie::JogWheel (_mcp);
+       }
 
+       DEBUG_TRACE (DEBUG::MackieControl, "Surface::init_controls: creating global controls\n");
        for (uint32_t n = 0; mackie_global_controls[n].name[0]; ++n) {
                group = groups[mackie_global_controls[n].group_name];
                Control* control = mackie_global_controls[n].factory (*this, mackie_global_controls[n].id, mackie_global_controls[n].name, *group);
-               controls_by_name[mackie_global_controls[n].name] = control;
-               group->add (*control);
-       }
-}
-
-static StripControlDefinition mackie_strip_controls[] = {
-       { "gain", 0, Fader::factory, },
-       { "vpot", Pot::base_id, Pot::factory, },
-       { "recenable", Button::recenable_base_id, Button::factory, },
-       { "solo", Button::solo_base_id, Button::factory, },
-       { "mute", Button::mute_base_id, Button::factory, },
-       { "select", Button::select_base_id, Button::factory, },
-       { "vselect", Button::vselect_base_id, Button::factory, },
-       { "fader_touch", Button::fader_touch_base_id, Button::factory, },
-       { "meter", 0, Meter::factory, },
-       { "", 0, Button::factory, }
-};
+               controls_by_device_independent_id[mackie_global_controls[n].id] = control;
+       }
+
+       /* add global buttons */
+       DEBUG_TRACE (DEBUG::MackieControl, "Surface::init_controls: adding global buttons\n");
+       const map<Button::ID,GlobalButtonInfo>& global_buttons (_mcp.device_info().global_buttons());
 
-void 
+       for (map<Button::ID,GlobalButtonInfo>::const_iterator b = global_buttons.begin(); b != global_buttons.end(); ++b){
+               group = groups[b->second.group];
+               controls_by_device_independent_id[b->first] = Button::factory (*this, b->first, b->second.id, b->second.label, *group);
+       }
+}
+
+void
 Surface::init_strips (uint32_t n)
 {
+       const map<Button::ID,StripButtonInfo>& strip_buttons (_mcp.device_info().strip_buttons());
+
        for (uint32_t i = 0; i < n; ++i) {
 
                char name[32];
-               
+
                snprintf (name, sizeof (name), "strip_%d", (8* _number) + i);
 
-               Strip* strip = new Strip (*this, name, i, mackie_strip_controls);
-               
+               Strip* strip = new Strip (*this, name, i, strip_buttons);
+
                groups[name] = strip;
                strips.push_back (strip);
        }
 }
 
-float 
+void
+Surface::setup_master ()
+{
+       boost::shared_ptr<Route> m;
+
+       if ((m = _mcp.get_session().monitor_out()) == 0) {
+               m = _mcp.get_session().master_out();
+       }
+
+       if (!m) {
+               return;
+       }
+
+       _master_fader = dynamic_cast<Fader*> (Fader::factory (*this, _mcp.device_info().strip_cnt(), "master", *groups["master"]));
+
+       _master_fader->set_control (m->gain_control());
+       m->gain_control()->Changed.connect (*this, MISSING_INVALIDATOR, boost::bind (&Surface::master_gain_changed, this), ui_context());
+
+       Groups::iterator group_it;
+       group_it = groups.find("master");
+
+       DeviceInfo device_info = _mcp.device_info();
+       GlobalButtonInfo master_button = device_info.get_global_button(Button::MasterFaderTouch);
+       Button* bb = dynamic_cast<Button*> (Button::factory (
+               *this,
+               Button::MasterFaderTouch,
+               master_button.id,
+               master_button.label,
+               *(group_it->second)
+));
+       DEBUG_TRACE (DEBUG::MackieControl, string_compose ("surface %1 Master Fader new button BID %2 id %3\n",
+               number(), Button::MasterFaderTouch, bb->id()));
+}
+
+void
+Surface::master_gain_changed ()
+{
+       if (!_master_fader) {
+               return;
+       }
+
+       boost::shared_ptr<AutomationControl> ac = _master_fader->control();
+       if (!ac) {
+               return;
+       }
+
+       float normalized_position = ac->internal_to_interface (ac->get_value());
+       if (normalized_position == _last_master_gain_written) {
+               return;
+       }
+
+       DEBUG_TRACE (DEBUG::MackieControl, "Surface::master_gain_changed: updating surface master fader\n");
+
+       _port->write (_master_fader->set_position (normalized_position));
+       _last_master_gain_written = normalized_position;
+}
+
+float
 Surface::scaled_delta (float delta, float current_speed)
 {
        /* XXX needs work before use */
-       return (std::pow (float(delta + 1), 2) + current_speed) / 100.0;
+       const float sign = delta < 0.0 ? -1.0 : 1.0;
+
+       return ((sign * std::pow (delta + 1.0, 2.0)) + current_speed) / 100.0;
 }
 
-void 
+void
 Surface::display_bank_start (uint32_t current_bank)
 {
        if  (current_bank == 0) {
                // send Ar. to 2-char display on the master
-               _port->write (two_char_display ("Ar", ".."));
+               show_two_char_display ("Ar", "..");
        } else {
                // write the current first remote_id to the 2-char display
-               _port->write (two_char_display (current_bank));
+               show_two_char_display (current_bank);
        }
 }
 
-void 
+void
 Surface::blank_jog_ring ()
 {
-       Control* control = controls_by_name["jog"];
+       Control* control = controls_by_device_independent_id[Jog::ID];
 
        if (control) {
                Pot* pot = dynamic_cast<Pot*> (control);
                if (pot) {
-                       _port->write (pot->set_onoff (false));
+                       _port->write (pot->set (0.0, false, Pot::spread));
                }
        }
 }
 
-bool 
-Surface::has_timecode_display () const
-{
-       return false;
-}
-
 float
 Surface::scrub_scaling_factor () const
 {
        return 100.0;
 }
 
-void 
+void
 Surface::connect_to_signals ()
 {
        if (!_connected) {
 
 
-               DEBUG_TRACE (DEBUG::MackieControl, string_compose ("Surface %1 connecting to signals on port %2\n", 
+               DEBUG_TRACE (DEBUG::MackieControl, string_compose ("Surface %1 connecting to signals on port %2\n",
                                                                   number(), _port->input_port().name()));
 
                MIDI::Parser* p = _port->input_port().parser();
@@ -319,16 +460,16 @@ Surface::connect_to_signals ()
                p->controller.connect_same_thread (*this, boost::bind (&Surface::handle_midi_controller_message, this, _1, _2));
                /* Button messages are NoteOn */
                p->note_on.connect_same_thread (*this, boost::bind (&Surface::handle_midi_note_on_message, this, _1, _2));
+               /* Button messages are NoteOn but libmidi++ sends note-on w/velocity = 0 as note-off so catch them too */
+               p->note_off.connect_same_thread (*this, boost::bind (&Surface::handle_midi_note_on_message, this, _1, _2));
                /* Fader messages are Pitchbend */
-               p->channel_pitchbend[0].connect_same_thread (*this, boost::bind (&Surface::handle_midi_pitchbend_message, this, _1, _2, 0U));
-               p->channel_pitchbend[1].connect_same_thread (*this, boost::bind (&Surface::handle_midi_pitchbend_message, this, _1, _2, 1U));
-               p->channel_pitchbend[2].connect_same_thread (*this, boost::bind (&Surface::handle_midi_pitchbend_message, this, _1, _2, 2U));
-               p->channel_pitchbend[3].connect_same_thread (*this, boost::bind (&Surface::handle_midi_pitchbend_message, this, _1, _2, 3U));
-               p->channel_pitchbend[4].connect_same_thread (*this, boost::bind (&Surface::handle_midi_pitchbend_message, this, _1, _2, 4U));
-               p->channel_pitchbend[5].connect_same_thread (*this, boost::bind (&Surface::handle_midi_pitchbend_message, this, _1, _2, 5U));
-               p->channel_pitchbend[6].connect_same_thread (*this, boost::bind (&Surface::handle_midi_pitchbend_message, this, _1, _2, 6U));
-               p->channel_pitchbend[7].connect_same_thread (*this, boost::bind (&Surface::handle_midi_pitchbend_message, this, _1, _2, 7U));
-               
+               uint32_t i;
+               for (i = 0; i < _mcp.device_info().strip_cnt(); i++) {
+                       p->channel_pitchbend[i].connect_same_thread (*this, boost::bind (&Surface::handle_midi_pitchbend_message, this, _1, _2, i));
+               }
+               // Master fader
+               p->channel_pitchbend[_mcp.device_info().strip_cnt()].connect_same_thread (*this, boost::bind (&Surface::handle_midi_pitchbend_message, this, _1, _2, _mcp.device_info().strip_cnt()));
+
                _connected = true;
        }
 }
@@ -336,139 +477,200 @@ Surface::connect_to_signals ()
 void
 Surface::handle_midi_pitchbend_message (MIDI::Parser&, MIDI::pitchbend_t pb, uint32_t fader_id)
 {
-       /* Pitchbend messages are fader messages. Nothing in the data we get
+       /* Pitchbend messages are fader position messages. Nothing in the data we get
         * from the MIDI::Parser conveys the fader ID, which was given by the
         * channel ID in the status byte.
         *
-        * Instead, we have used bind() to supply the fader-within-strip ID 
+        * Instead, we have used bind() to supply the fader-within-strip ID
         * when we connected to the per-channel pitchbend events.
         */
 
-       DEBUG_TRACE (DEBUG::MackieControl, string_compose ("handle_midi pitchbend on port %3, fader = %1 value = %2\n", 
-                                                          fader_id, pb, _number));
-       
+       DEBUG_TRACE (DEBUG::MackieControl, string_compose ("Surface::handle_midi_pitchbend_message on port %3, fader = %1 value = %2 (%4)\n",
+                                                          fader_id, pb, _number, pb/16384.0));
+
+       if (_mcp.device_info().no_handshake()) {
+               turn_it_on ();
+       }
+
+       if (_mcp.main_modifier_state() & MackieControlProtocol::MODIFIER_SHIFT) {
+               /* user is doing a reset to unity gain but device sends a PB
+                * message in the middle of the touch on/off messages. Ignore
+                * it.
+                */
+               return;
+       }
+
        Fader* fader = faders[fader_id];
 
        if (fader) {
                Strip* strip = dynamic_cast<Strip*> (&fader->group());
+               float pos = pb / 16384.0;
                if (strip) {
-                       float midi_pos = pb >> 4; // only the top 10 bytes are used
-                       strip->handle_fader (*fader, midi_pos/1023.0);
+                       strip->handle_fader (*fader, pos);
                } else {
+                       DEBUG_TRACE (DEBUG::MackieControl, "Handling master fader\n");
                        /* master fader */
+                       fader->set_value (pos); // alter master gain
+                       _port->write (fader->set_position (pos)); // write back value (required for servo)
                }
        } else {
                DEBUG_TRACE (DEBUG::MackieControl, "fader not found\n");
        }
 }
 
-void 
+void
 Surface::handle_midi_note_on_message (MIDI::Parser &, MIDI::EventTwoBytes* ev)
 {
-       DEBUG_TRACE (DEBUG::MackieControl, string_compose ("SurfacePort::handle_note_on %1 = %2\n", (int) ev->note_number, (int) ev->velocity));
-       
+       DEBUG_TRACE (DEBUG::MackieControl, string_compose ("Surface::handle_midi_note_on_message %1 = %2\n", (int) ev->note_number, (int) ev->velocity));
+
+       if (_mcp.device_info().no_handshake()) {
+               turn_it_on ();
+       }
+
+       if (_mcp.device_info().device_type() == DeviceInfo::HUI && ev->note_number == 0 && ev->velocity == 127) {
+               turn_it_on ();
+       }
+
+       /* fader touch sense is given by "buttons" 0xe..0xe7 and 0xe8 for the
+        * master.
+        */
+
+       if (ev->note_number >= 0xE0 && ev->note_number <= 0xE8) {
+               Fader* fader = faders[ev->note_number];
+
+               DEBUG_TRACE (DEBUG::MackieControl, string_compose ("Surface: fader touch message, fader = %1\n", fader));
+
+               if (fader) {
+
+                       Strip* strip = dynamic_cast<Strip*> (&fader->group());
+
+                       if (ev->velocity > 64) {
+                               strip->handle_fader_touch (*fader, true);
+                       } else {
+                               strip->handle_fader_touch (*fader, false);
+                       }
+               }
+               return;
+       }
+
        Button* button = buttons[ev->note_number];
 
        if (button) {
+
+               if (ev->velocity > 64) {
+                       button->pressed ();
+               }
+
                Strip* strip = dynamic_cast<Strip*> (&button->group());
 
                if (strip) {
                        DEBUG_TRACE (DEBUG::MackieControl, string_compose ("strip %1 button %2 pressed ? %3\n",
-                                                                          strip->index(), button->name(), (ev->velocity == 0x7f)));
-                       strip->handle_button (*button, ev->velocity == 0x7f ? press : release);
+                                                                          strip->index(), button->name(), (ev->velocity > 64)));
+                       strip->handle_button (*button, ev->velocity > 64 ? press : release);
                } else {
                        /* global button */
                        DEBUG_TRACE (DEBUG::MackieControl, string_compose ("global button %1\n", button->id()));
-                       _mcp.handle_button_event (*this, *button, ev->velocity == 0x7f ? press : release);
+                       _mcp.handle_button_event (*this, *button, ev->velocity > 64 ? press : release);
                }
+
+               if (ev->velocity <= 64) {
+                       button->released ();
+               }
+
        } else {
-               DEBUG_TRACE (DEBUG::MackieControl, string_compose ("no button found for %1\n", ev->note_number));
+               DEBUG_TRACE (DEBUG::MackieControl, string_compose ("no button found for %1\n", (int) ev->note_number));
        }
+
+       /* button release should reset timer AFTER handler(s) have run */
 }
 
-void 
+void
 Surface::handle_midi_controller_message (MIDI::Parser &, MIDI::EventTwoBytes* ev)
 {
        DEBUG_TRACE (DEBUG::MackieControl, string_compose ("SurfacePort::handle_midi_controller %1 = %2\n", (int) ev->controller_number, (int) ev->value));
 
+       if (_mcp.device_info().no_handshake()) {
+               turn_it_on ();
+       }
+
        Pot* pot = pots[ev->controller_number];
 
-       if (!pot && ev->controller_number == Jog::base_id) {
-               pot = dynamic_cast<Pot*> (controls_by_name["jog"]);
-       }
-
-       if (pot) {
-               ControlState state;
-               
-               // bit 6 gives the sign
-               float sign = (ev->value & 0x40) == 0 ? 1.0 : -1.0; 
-               // bits 0..5 give the velocity. we interpret this as "ticks
-               // moved before this message was sent"
-               float ticks = (ev->value & 0x3f);
-               if (ticks == 0) {
-                       /* euphonix and perhaps other devices send zero
-                          when they mean 1, we think.
-                       */
-                       ticks = 1;
-               }
-               float delta = sign * (ticks / (float) 0x3f);
-               
-               /* Pots only emit events when they move, not when they
-                  stop moving. So to get a stop event, we need to use a timeout.
+       // bit 6 gives the sign
+       float sign = (ev->value & 0x40) == 0 ? 1.0 : -1.0;
+       // bits 0..5 give the velocity. we interpret this as "ticks
+       // moved before this message was sent"
+       float ticks = (ev->value & 0x3f);
+       if (ticks == 0) {
+               /* euphonix and perhaps other devices send zero
+                  when they mean 1, we think.
                */
-               
-               _mcp.add_in_use_timeout (*this, *pot, pot);
+               ticks = 1;
+       }
 
-               Strip* strip = dynamic_cast<Strip*> (&pot->group());
+       float delta = 0;
+       if (mcp().main_modifier_state() == MackieControlProtocol::MODIFIER_CONTROL) {
+               delta = sign * (ticks / (float) 0xff);
+       } else {
+               delta = sign * (ticks / (float) 0x3f);
+       }
 
-               if (strip) {
-                       strip->handle_pot (*pot, delta);
-               } else {
-                       JogWheel* wheel = dynamic_cast<JogWheel*> (pot);
-                       if (wheel) {
-                               DEBUG_TRACE (DEBUG::MackieControl, string_compose ("Jog wheel moved %1\n", state.ticks));
-                               wheel->jog_event (*_port, *pot, delta);
-                       } else {
-                               DEBUG_TRACE (DEBUG::MackieControl, string_compose ("External controller moved %1\n", state.ticks));
-                               cout << "external controller" << delta << endl;
-                       }
+       if (!pot) {
+               if (ev->controller_number == Jog::ID && _jog_wheel) {
+
+                       DEBUG_TRACE (DEBUG::MackieControl, string_compose ("Jog wheel moved %1\n", ticks));
+                       _jog_wheel->jog_event (delta);
+                       return;
                }
-       } else {
-               DEBUG_TRACE (DEBUG::MackieControl, "pot not found\n");
+               // add external (pedal?) control here
+
+               return;
+       }
+
+       Strip* strip = dynamic_cast<Strip*> (&pot->group());
+       if (strip) {
+               strip->handle_pot (*pot, delta);
        }
 }
 
-void 
+void
 Surface::handle_midi_sysex (MIDI::Parser &, MIDI::byte * raw_bytes, size_t count)
 {
        MidiByteArray bytes (count, raw_bytes);
 
-
        DEBUG_TRACE (DEBUG::MackieControl, string_compose ("handle_midi_sysex: %1\n", bytes));
 
+       if (_mcp.device_info().no_handshake()) {
+               turn_it_on ();
+       }
+
        /* always save the device type ID so that our outgoing sysex messages
-        * are correct 
+        * are correct
         */
 
        if (_stype == mcu) {
-               mackie_sysex_hdr[3] = bytes[4];
+               mackie_sysex_hdr[4] = bytes[4];
        } else {
-               mackie_sysex_hdr_xt[3] = bytes[4];
+               mackie_sysex_hdr_xt[4] = bytes[4];
        }
 
        switch (bytes[5]) {
        case 0x01:
-               /* MCP: Device Ready 
-                  LCP: Connection Challenge 
+               /* MCP: Device Ready
+                  LCP: Connection Challenge
                */
                if (bytes[4] == 0x10 || bytes[4] == 0x11) {
+                       DEBUG_TRACE (DEBUG::MackieControl, "Logic Control Device connection challenge\n");
                        write_sysex (host_connection_query (bytes));
                } else {
-                       _active = true;
+                       DEBUG_TRACE (DEBUG::MackieControl, string_compose ("Mackie Control Device ready, current status = %1\n", _active));
+                       if (!_active) {
+                               turn_it_on ();
+                       }
                }
                break;
 
        case 0x03: /* LCP Connection Confirmation */
+               DEBUG_TRACE (DEBUG::MackieControl, "Logic Control Device confirms connection, ardour replies\n");
                if (bytes[4] == 0x10 || bytes[4] == 0x11) {
                        write_sysex (host_connection_confirmation (bytes));
                        _active = true;
@@ -476,6 +678,7 @@ Surface::handle_midi_sysex (MIDI::Parser &, MIDI::byte * raw_bytes, size_t count
                break;
 
        case 0x04: /* LCP: Confirmation Denied */
+               DEBUG_TRACE (DEBUG::MackieControl, "Logic Control Device denies connection\n");
                _active = false;
                break;
        default:
@@ -483,31 +686,30 @@ Surface::handle_midi_sysex (MIDI::Parser &, MIDI::byte * raw_bytes, size_t count
        }
 }
 
-static MidiByteArray 
+static MidiByteArray
 calculate_challenge_response (MidiByteArray::iterator begin, MidiByteArray::iterator end)
 {
        MidiByteArray l;
        back_insert_iterator<MidiByteArray> back  (l);
        copy (begin, end, back);
-       
+
        MidiByteArray retval;
-       
+
        // this is how to calculate the response to the challenge.
        // from the Logic docs.
        retval <<  (0x7f &  (l[0] +  (l[1] ^ 0xa) - l[3]));
        retval <<  (0x7f &  ( (l[2] >> l[3]) ^  (l[0] + l[3])));
        retval <<  (0x7f &  ((l[3] -  (l[2] << 2)) ^  (l[0] | l[1])));
        retval <<  (0x7f &  (l[1] - l[2] +  (0xf0 ^  (l[3] << 4))));
-       
+
        return retval;
 }
 
-// not used right now
-MidiByteArray 
+MidiByteArray
 Surface::host_connection_query (MidiByteArray & bytes)
 {
        MidiByteArray response;
-       
+
        if (bytes[4] != 0x10 && bytes[4] != 0x11) {
                /* not a Logic Control device - no response required */
                return response;
@@ -515,7 +717,7 @@ Surface::host_connection_query (MidiByteArray & bytes)
 
        // handle host connection query
        DEBUG_TRACE (DEBUG::MackieControl, string_compose ("host connection query: %1\n", bytes));
-       
+
        if  (bytes.size() != 18) {
                cerr << "expecting 18 bytes, read " << bytes << " from " << _port->input_port().name() << endl;
                return response;
@@ -528,30 +730,45 @@ Surface::host_connection_query (MidiByteArray & bytes)
        return response;
 }
 
-// not used right now
-MidiByteArray 
+MidiByteArray
 Surface::host_connection_confirmation (const MidiByteArray & bytes)
 {
        DEBUG_TRACE (DEBUG::MackieControl, string_compose ("host_connection_confirmation: %1\n", bytes));
-       
+
        // decode host connection confirmation
        if  (bytes.size() != 14) {
                ostringstream os;
                os << "expecting 14 bytes, read " << bytes << " from " << _port->input_port().name();
                throw MackieControlException (os.str());
        }
-       
+
        // send version request
        return MidiByteArray (2, 0x13, 0x00);
 }
 
-void 
-Surface::handle_port_inactive (SurfacePort * port)
+void
+Surface::turn_it_on ()
 {
-       _active = false;
+       if (_active) {
+               return;
+       }
+
+       _active = true;
+
+       _mcp.device_ready ();
+
+       for (Strips::iterator s = strips.begin(); s != strips.end(); ++s) {
+               (*s)->notify_all ();
+       }
+
+       update_view_mode_display ();
+
+       if (_mcp.device_info ().has_global_controls ()) {
+               _mcp.update_global_button (Button::Read, _mcp.metering_active ());
+       }
 }
 
-void 
+void
 Surface::write_sysex (const MidiByteArray & mba)
 {
        if (mba.empty()) {
@@ -563,7 +780,7 @@ Surface::write_sysex (const MidiByteArray & mba)
        _port->write (buf);
 }
 
-void 
+void
 Surface::write_sysex (MIDI::byte msg)
 {
        MidiByteArray buf;
@@ -571,18 +788,21 @@ Surface::write_sysex (MIDI::byte msg)
        _port->write (buf);
 }
 
-void
-Surface::drop_routes ()
+uint32_t
+Surface::n_strips (bool with_locked_strips) const
 {
-       for (Strips::iterator s = strips.begin(); s != strips.end(); ++s) {
-               (*s)->set_route (boost::shared_ptr<Route>());
+       if (with_locked_strips) {
+               return strips.size();
        }
-}
 
-uint32_t
-Surface::n_strips () const
-{
-       return strips.size();
+       uint32_t n = 0;
+
+       for (Strips::const_iterator it = strips.begin(); it != strips.end(); ++it) {
+               if (!(*it)->locked()) {
+                       ++n;
+               }
+       }
+       return n;
 }
 
 Strip*
@@ -597,16 +817,34 @@ Surface::nth_strip (uint32_t n) const
 void
 Surface::zero_all ()
 {
-       // TODO turn off Timecode displays
+       if (_mcp.device_info().has_timecode_display ()) {
+               display_timecode (string (10, '0'), string (10, ' '));
+       }
+
+       if (_mcp.device_info().has_two_character_display()) {
+               show_two_char_display (string (2, '0'), string (2, ' '));
+       }
+
+       if (_mcp.device_info().has_master_fader () && _master_fader) {
+               _port->write (_master_fader->zero ());
+       }
 
        // zero all strips
        for (Strips::iterator it = strips.begin(); it != strips.end(); ++it) {
-               _port->write ((*it)->zero());
+               (*it)->zero();
+       }
+
+       zero_controls ();
+}
+
+void
+Surface::zero_controls ()
+{
+       if (!_mcp.device_info().has_global_controls()) {
+               return;
        }
 
        // turn off global buttons and leds
-        // global buttons are only ever on mcu_port, so we don't have
-       // to figure out which port.
 
        for (Controls::iterator it = controls.begin(); it != controls.end(); ++it) {
                Control & control = **it;
@@ -615,51 +853,36 @@ Surface::zero_all ()
                }
        }
 
-       // any hardware-specific stuff
-       // clear 2-char display
-       _port->write (two_char_display ("  "));
-
        // and the led ring for the master strip
        blank_jog_ring ();
+
+       _last_master_gain_written = 0.0f;
 }
 
 void
-Surface::periodic ()
+Surface::periodic (uint64_t now_usecs)
 {
+       master_gain_changed();
        for (Strips::iterator s = strips.begin(); s != strips.end(); ++s) {
-               (*s)->periodic ();
+               (*s)->periodic (now_usecs);
        }
-
 }
 
 void
-Surface::write (const MidiByteArray& data) 
+Surface::redisplay (ARDOUR::microseconds_t now)
 {
-       _port->write (data);
+       for (Strips::iterator s = strips.begin(); s != strips.end(); ++s) {
+               (*s)->redisplay (now);
+       }
 }
 
-void 
-Surface::jog_wheel_state_display (JogWheel::State state)
+void
+Surface::write (const MidiByteArray& data)
 {
-       switch (state) {
-       case JogWheel::zoom:
-                       _port->write (two_char_display ("Zm"));
-                       break;
-               case JogWheel::scroll:
-                       _port->write (two_char_display ("Sc"));
-                       break;
-               case JogWheel::scrub:
-                       _port->write (two_char_display ("Sb"));
-                       break;
-               case JogWheel::shuttle:
-                       _port->write (two_char_display ("Sh"));
-                       break;
-               case JogWheel::speed:
-                       _port->write (two_char_display ("Sp"));
-                       break;
-               case JogWheel::select:
-                       _port->write (two_char_display ("Se"));
-                       break;
+       if (_active) {
+               _port->write (data);
+       } else {
+               DEBUG_TRACE (DEBUG::MackieControl, "surface not active, write ignored\n");
        }
 }
 
@@ -667,70 +890,78 @@ void
 Surface::map_routes (const vector<boost::shared_ptr<Route> >& routes)
 {
        vector<boost::shared_ptr<Route> >::const_iterator r;
-       Strips::iterator s;
+       Strips::iterator s = strips.begin();
 
-       for (s = strips.begin(); s != strips.end(); ++s) {
-               (*s)->set_route (boost::shared_ptr<Route>());
+       DEBUG_TRACE (DEBUG::MackieControl, string_compose ("Mapping %1 routes\n", routes.size()));
+
+       for (r = routes.begin(); r != routes.end() && s != strips.end(); ++s) {
+
+               /* don't try to assign routes to a locked strip. it won't
+                  use it anyway, but if we do, then we get out of sync
+                  with the proposed mapping.
+               */
+
+               if (!(*s)->locked()) {
+                       (*s)->set_route (*r);
+                       ++r;
+               }
        }
 
-       for (r = routes.begin(), s = strips.begin(); r != routes.end() && s != strips.end(); ++r, ++s) {
-               (*s)->set_route (*r);
+       for (; s != strips.end(); ++s) {
+               (*s)->set_route (boost::shared_ptr<Route>());
        }
+
+
 }
 
-static char translate_seven_segment (char achar)
+static char
+translate_seven_segment (char achar)
 {
        achar = toupper (achar);
-       if  (achar >= 0x40 && achar <= 0x60)
+
+       if  (achar >= 0x40 && achar <= 0x60) {
                return achar - 0x40;
-       else if  (achar >= 0x21 && achar <= 0x3f)
-      return achar;
-       else
-      return 0x00;
+       } else if  (achar >= 0x21 && achar <= 0x3f) {
+               return achar;
+       } else {
+               return 0x00;
+       }
 }
 
-MidiByteArray 
-Surface::two_char_display (const std::string & msg, const std::string & dots)
+void
+Surface::show_two_char_display (const std::string & msg, const std::string & dots)
 {
-       if (_stype != mcu) {
-               return MidiByteArray();
+       if (_stype != mcu || !_mcp.device_info().has_two_character_display() || msg.length() != 2 || dots.length() != 2) {
+               return;
        }
 
-       if  (msg.length() != 2) throw MackieControlException ("MackieMidiBuilder::two_char_display: msg must be exactly 2 characters");
-       if  (dots.length() != 2) throw MackieControlException ("MackieMidiBuilder::two_char_display: dots must be exactly 2 characters");
-       
-       MidiByteArray bytes (6, 0xb0, 0x4a, 0x00, 0xb0, 0x4b, 0x00);
-       
-       // chars are understood by the surface in right-to-left order
-       // could also exchange the 0x4a and 0x4b, above
-       bytes[5] = translate_seven_segment (msg[0]) +  (dots[0] == '.' ? 0x40 : 0x00);
-       bytes[2] = translate_seven_segment (msg[1]) +  (dots[1] == '.' ? 0x40 : 0x00);
-       
-       return bytes;
+       MidiByteArray right (3, 0xb0, 0x4b, 0x00);
+       MidiByteArray left (3, 0xb0, 0x4a, 0x00);
+
+       right[2] = translate_seven_segment (msg[0]) +  (dots[0] == '.' ? 0x40 : 0x00);
+       left[2] = translate_seven_segment (msg[1]) +  (dots[1] == '.' ? 0x40 : 0x00);
+
+       _port->write (right);
+       _port->write (left);
 }
 
-MidiByteArray 
-Surface::two_char_display (unsigned int value, const std::string & /*dots*/)
+void
+Surface::show_two_char_display (unsigned int value, const std::string & /*dots*/)
 {
        ostringstream os;
        os << setfill('0') << setw(2) << value % 100;
-       return two_char_display (os.str());
+       show_two_char_display (os.str());
 }
 
-void 
-Surface::display_timecode (const std::string & timecode, const std::string & timecode_last)
+void
+Surface::display_timecode (const std::string & timecode, const std::string & last_timecode)
 {
-       if (has_timecode_display()) {
-               _port->write (timecode_display (timecode, timecode_last));
+       if (!_active || !_mcp.device_info().has_timecode_display()) {
+               return;
        }
-}
-
-MidiByteArray 
-Surface::timecode_display (const std::string & timecode, const std::string & last_timecode)
-{
        // if there's no change, send nothing, not even sysex header
-       if  (timecode == last_timecode) return MidiByteArray();
-       
+       if  (timecode == last_timecode) return;
+
        // length sanity checking
        string local_timecode = timecode;
 
@@ -740,39 +971,38 @@ Surface::timecode_display (const std::string & timecode, const std::string & las
        }
 
        // pad to 10 characters
-       while  (local_timecode.length() < 10) { 
+       while  (local_timecode.length() < 10) {
                local_timecode += " ";
        }
-               
-       // find the suffix of local_timecode that differs from last_timecode
-       std::pair<string::const_iterator,string::iterator> pp = mismatch (last_timecode.begin(), last_timecode.end(), local_timecode.begin());
-       
-       MidiByteArray retval;
-       
-       // sysex header
-       retval << sysex_hdr();
-       
-       // code for timecode display
-       retval << 0x10;
-       
-       // translate characters. These are sent in reverse order of display
-       // hence the reverse iterators
-       string::reverse_iterator rend = reverse_iterator<string::iterator> (pp.second);
-       for  (string::reverse_iterator it = local_timecode.rbegin(); it != rend; ++it) {
-               retval << translate_seven_segment (*it);
-       }
-       
-       // sysex trailer
-       retval << MIDI::eox;
-       
-       return retval;
+
+       // translate characters.
+       // Only the characters that actually changed are sent.
+       int position = 0x3f;
+       int i;
+       for (i = local_timecode.length () - 1; i >= 0; i--) {
+               position++;
+               if (local_timecode[i] == last_timecode[i]) {
+                       continue;
+               }
+               MidiByteArray retval (2, 0xb0, position);
+               retval << translate_seven_segment (local_timecode[i]);
+               _port->write (retval);
+       }
 }
 
 void
 Surface::update_flip_mode_display ()
 {
        for (Strips::iterator s = strips.begin(); s != strips.end(); ++s) {
-               (*s)->notify_all ();
+               (*s)->flip_mode_changed (true);
+       }
+}
+
+ void
+Surface::update_potmode ()
+{
+       for (Strips::iterator s = strips.begin(); s != strips.end(); ++s) {
+               (*s)->potmode_changed (false);
        }
 }
 
@@ -780,67 +1010,258 @@ void
 Surface::update_view_mode_display ()
 {
        string text;
-       Button* button = 0;
+       int id = -1;
+
+       if (!_active) {
+               return;
+       }
 
        switch (_mcp.view_mode()) {
-       case MackieControlProtocol::Global:
-               _port->write (two_char_display ("Gl"));
-               button = buttons[Button::Pan];
-               text = _("Pan");
-               break;
-       case MackieControlProtocol::Dynamics:
-               _port->write (two_char_display ("Dy"));
-               button = buttons[Button::Dyn];
-               text = _("");
-               break;
-       case MackieControlProtocol::EQ:
-               _port->write (two_char_display ("EQ"));
-               button = buttons[Button::Eq];
-               text = _("");
+       case MackieControlProtocol::Mixer:
+               show_two_char_display ("Mx");
+               //id = Button::Pan;
                break;
        case MackieControlProtocol::Loop:
-               _port->write (two_char_display ("LP"));
-               button = buttons[Button::Loop];
-               text = _("");
+               show_two_char_display ("LP");
+               id = Button::Loop;
                break;
        case MackieControlProtocol::AudioTracks:
-               _port->write (two_char_display ("AT"));
-               text = _("");
+               show_two_char_display ("AT");
                break;
        case MackieControlProtocol::MidiTracks:
-               _port->write (two_char_display ("MT"));
-               text = _("");
-               break;
-       case MackieControlProtocol::Busses:
-               _port->write (two_char_display ("Bs"));
-               text = _("");
+               show_two_char_display ("MT");
                break;
-       case MackieControlProtocol::Sends:
-               _port->write (two_char_display ("Sn"));
-               button = buttons[Button::Sends];
-               text = _("");
-               break;
-       case MackieControlProtocol::Plugins:
-               _port->write (two_char_display ("Pl"));
-               button = buttons[Button::Plugin];
-               text = _("");
+       default:
                break;
        }
 
-       if (button) {
-               _port->write (button->set_state (on));
+       if (id >= 0) {
+
+               /* we are attempting to turn a global button/LED on */
+
+               map<int,Control*>::iterator x = controls_by_device_independent_id.find (id);
+
+               if (x != controls_by_device_independent_id.end()) {
+                       Button* button = dynamic_cast<Button*> (x->second);
+                       if (button) {
+                               _port->write (button->set_state (on));
+                       }
+               }
        }
 
-       for (Strips::iterator s = strips.begin(); s != strips.end(); ++s) {
-               _port->write ((*s)->display (1, text));
+       if (!text.empty()) {
+               for (Strips::iterator s = strips.begin(); s != strips.end(); ++s) {
+                       _port->write ((*s)->display (1, text));
+               }
        }
 }
 
 void
-Surface::gui_selection_changed (ARDOUR::RouteNotificationListPtr routes)
+Surface::gui_selection_changed (const ARDOUR::StrongRouteNotificationList& routes)
 {
        for (Strips::iterator s = strips.begin(); s != strips.end(); ++s) {
-               _port->write ((*s)->gui_selection_changed (routes));
+               (*s)->gui_selection_changed (routes);
        }
 }
 
+void
+Surface::say_hello ()
+{
+       /* wakeup for Mackie Control */
+       MidiByteArray wakeup (7, MIDI::sysex, 0x00, 0x00, 0x66, 0x14, 0x00, MIDI::eox);
+       _port->write (wakeup);
+       wakeup[4] = 0x15; /* wakup Mackie XT */
+       _port->write (wakeup);
+       wakeup[4] = 0x10; /* wakeup Logic Control */
+       _port->write (wakeup);
+       wakeup[4] = 0x11; /* wakeup Logic Control XT */
+       _port->write (wakeup);
+}
+
+void
+Surface::next_jog_mode ()
+{
+}
+
+void
+Surface::set_jog_mode (JogWheel::Mode)
+{
+}
+
+bool
+Surface::route_is_locked_to_strip (boost::shared_ptr<Route> r) const
+{
+       for (Strips::const_iterator s = strips.begin(); s != strips.end(); ++s) {
+               if ((*s)->route() == r && (*s)->locked()) {
+                       return true;
+               }
+       }
+       return false;
+}
+
+void
+Surface::notify_metering_state_changed()
+{
+       for (Strips::const_iterator s = strips.begin(); s != strips.end(); ++s) {
+               (*s)->notify_metering_state_changed ();
+       }
+}
+
+void
+Surface::reset ()
+{
+       if (_port) {
+               /* reset msg for Mackie Control */
+               MidiByteArray msg;
+               msg << sysex_hdr();
+               msg << 0x08;
+               msg << 0x00;
+               msg << MIDI::eox;
+               _port->write (msg);
+       }
+}
+
+void
+Surface::toggle_backlight ()
+{
+       if (_port) {
+               int onoff = random() %2;
+               MidiByteArray msg;
+               msg << sysex_hdr ();
+               msg << 0xa;
+               msg << (onoff ? 0x1 : 0x0);
+               msg << MIDI::eox;
+               _port->write (msg);
+       }
+}
+
+void
+Surface::recalibrate_faders ()
+{
+       if (_port) {
+               MidiByteArray msg;
+               msg << sysex_hdr ();
+               msg << 0x09;
+               msg << 0x00;
+               msg << MIDI::eox;
+               _port->write (msg);
+       }
+}
+
+void
+Surface::set_touch_sensitivity (int sensitivity)
+{
+       /* NOTE: assumed called from GUI code, hence sleep() */
+
+       /* sensitivity already clamped by caller */
+
+       if (_port) {
+               MidiByteArray msg;
+
+               msg << sysex_hdr ();
+               msg << 0x0e;
+               msg << 0xff; /* overwritten for each fader below */
+               msg << (sensitivity & 0x7f);
+               msg << MIDI::eox;
+
+               for (int fader = 0; fader < 9; ++fader) {
+                       msg[6] = fader;
+                       _port->write (msg);
+               }
+       }
+}
+
+void
+Surface::hui_heartbeat ()
+{
+       if (!_port) {
+               return;
+       }
+
+       MidiByteArray msg (3, MIDI::on, 0x0, 0x0);
+       _port->write (msg);
+}
+
+void
+Surface::connected ()
+{
+       DEBUG_TRACE (DEBUG::MackieControl, string_compose ("Surface %1 now connected, trying to ping device...\n", _name));
+
+       say_hello ();
+
+       if (_mcp.device_info().no_handshake()) {
+               turn_it_on ();
+       }
+}
+
+MidiByteArray
+Surface::display_line (string const& msg, int line_num)
+{
+       MidiByteArray midi_msg;
+       midi_msg << sysex_hdr ();
+       midi_msg << 0x12;
+       midi_msg << (line_num ? 0x38 : 0x0); /* offsets into char array
+                                             * on device that
+                                             * correspond to line
+                                             * starts
+                                             */
+       if (msg.empty()) {
+
+               midi_msg.insert (midi_msg.end(), 55, ' ');
+
+       } else {
+
+               /* ascii data to display. @param msg is UTF-8 which is not legal. */
+               string ascii = Glib::convert_with_fallback (msg, "UTF-8", "ISO-8859-1", "_");
+               string::size_type len = ascii.length();
+
+               if (len > 55) {
+                       midi_msg << ascii.substr (0, 55);
+               } else {
+                       midi_msg << ascii;
+
+                       for (string::size_type i = len; i < 55; ++i) {
+                               midi_msg << ' ';
+                       }
+               }
+       }
+
+       midi_msg << MIDI::eox;
+
+       return midi_msg;
+}
+
+/** display @param msg on the 55x2 screen for @param msecs milliseconds
+ *
+ *  @param msg is assumed to be UTF-8 encoded, and will be converted
+ *  to ASCII with an underscore as fallback character before being
+ *  sent to the device.
+ */
+void
+Surface::display_message_for (string const& msg, uint64_t msecs)
+{
+       string::size_type newline;
+
+       if ((newline = msg.find ('\n')) == string::npos) {
+
+               _port->write (display_line (msg, 0));
+               _port->write (display_line (string(), 1));
+
+       } else if (newline == 0) {
+
+               _port->write (display_line (string(), 0));
+               _port->write (display_line (msg.substr (1), 1));
+
+       } else {
+
+               string first_line = msg.substr (0, newline-1);
+               string second_line = msg.substr (newline+1);
+
+               _port->write (display_line (first_line, 0));
+               _port->write (display_line (second_line.substr (0, second_line.find_first_of ('\n')), 1));
+       }
+
+       for (Strips::const_iterator s = strips.begin(); s != strips.end(); ++s) {
+               (*s)->block_screen_display_for (msecs);
+       }
+}