Merge branch 'ovenwerks-master'
[ardour.git] / libs / surfaces / mackie / surface.cc
1 /*
2     Copyright (C) 2012 Paul Davis 
3
4     This program is free software; you can redistribute it and/or modify
5     it under the terms of the GNU General Public License as published by
6     the Free Software Foundation; either version 2 of the License, or
7     (at your option) any later version.
8
9     This program is distributed in the hope that it will be useful,
10     but WITHOUT ANY WARRANTY; without even the implied warranty of
11     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12     GNU General Public License for more details.
13
14     You should have received a copy of the GNU General Public License
15     along with this program; if not, write to the Free Software
16     Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
17
18 */
19
20 #include <sstream>
21 #include <iomanip>
22 #include <iostream>
23 #include <cstdio>
24 #include <cmath>
25
26 #include "midi++/port.h"
27
28 #include "ardour/automation_control.h"
29 #include "ardour/debug.h"
30 #include "ardour/route.h"
31 #include "ardour/panner.h"
32 #include "ardour/panner_shell.h"
33 #include "ardour/rc_configuration.h"
34 #include "ardour/session.h"
35 #include "ardour/utils.h"
36
37 #include "control_group.h"
38 #include "surface_port.h"
39 #include "surface.h"
40 #include "strip.h"
41 #include "mackie_control_protocol.h"
42 #include "jog_wheel.h"
43
44 #include "strip.h"
45 #include "button.h"
46 #include "led.h"
47 #include "pot.h"
48 #include "fader.h"
49 #include "jog.h"
50 #include "meter.h"
51
52 #include "i18n.h"
53
54 using namespace std;
55 using namespace PBD;
56 using ARDOUR::Route;
57 using ARDOUR::Panner;
58 using ARDOUR::Pannable;
59 using ARDOUR::AutomationControl;
60 using namespace ArdourSurface;
61 using namespace Mackie;
62
63 #define ui_context() MackieControlProtocol::instance() /* a UICallback-derived object that specifies the event loop for signal handling */
64
65 // The MCU sysex header.4th byte Will be overwritten
66 // when we get an incoming sysex that identifies
67 // the device type
68 static MidiByteArray mackie_sysex_hdr  (5, MIDI::sysex, 0x0, 0x0, 0x66, 0x14);
69
70 // The MCU extender sysex header.4th byte Will be overwritten
71 // when we get an incoming sysex that identifies
72 // the device type
73 static MidiByteArray mackie_sysex_hdr_xt  (5, MIDI::sysex, 0x0, 0x0, 0x66, 0x15);
74
75 static MidiByteArray empty_midi_byte_array;
76
77 Surface::Surface (MackieControlProtocol& mcp, const std::string& device_name, uint32_t number, surface_type_t stype)
78         : _mcp (mcp)
79         , _stype (stype)
80         , _number (number)
81         , _name (device_name)
82         , _active (false)
83         , _connected (false)
84         , _jog_wheel (0)
85         , _master_fader (0)
86         , _last_master_gain_written (-0.0f)
87 {
88         DEBUG_TRACE (DEBUG::MackieControl, "Surface::Surface init\n");
89         
90         try {
91                 _port = new SurfacePort (*this);
92         } catch (...) {
93                 throw failed_constructor ();
94         }
95
96         /* only the first Surface object has global controls */
97         /* lets use master_position instead */
98         uint32_t mp = _mcp.device_info().master_position();
99         if (_number == mp) {
100                 DEBUG_TRACE (DEBUG::MackieControl, "Surface matches MasterPosition. Might have global controls.\n");
101                 if (_mcp.device_info().has_global_controls()) {
102                         init_controls ();
103                         DEBUG_TRACE (DEBUG::MackieControl, "init_controls done\n");
104                 }
105
106                 if (_mcp.device_info().has_master_fader()) {
107                         setup_master ();
108                         DEBUG_TRACE (DEBUG::MackieControl, "setup_master done\n");
109                 }
110         }
111
112         uint32_t n = _mcp.device_info().strip_cnt();
113         
114         if (n) {
115                 init_strips (n);
116                 DEBUG_TRACE (DEBUG::MackieControl, "init_strips done\n");
117         }
118         
119         connect_to_signals ();
120
121         DEBUG_TRACE (DEBUG::MackieControl, "Surface::Surface done\n");
122 }
123
124 Surface::~Surface ()
125 {
126         DEBUG_TRACE (DEBUG::MackieControl, "Surface::~Surface init\n");
127
128         zero_all ();
129
130         // delete groups
131         for (Groups::iterator it = groups.begin(); it != groups.end(); ++it) {
132                 delete it->second;
133         }
134         
135         // delete controls
136         for (Controls::iterator it = controls.begin(); it != controls.end(); ++it) {
137                 delete *it;
138         }
139         
140         delete _jog_wheel;
141         delete _port;
142
143         DEBUG_TRACE (DEBUG::MackieControl, "Surface::~Surface done\n");
144 }
145
146 XMLNode&
147 Surface::get_state()
148 {
149         char buf[64];
150         snprintf (buf, sizeof (buf), X_("surface-%u"), _number);
151         XMLNode* node = new XMLNode (buf);
152
153         node->add_child_nocopy (_port->get_state());
154
155         return *node;
156 }
157
158 int
159 Surface::set_state (const XMLNode& node, int version)
160 {
161         char buf[64];
162         snprintf (buf, sizeof (buf), X_("surface-%u"), _number);
163         XMLNode* mynode = node.child (buf);
164
165         if (!mynode) {
166                 return 0;
167         }
168
169         XMLNode* portnode = mynode->child (X_("Port"));
170         if (portnode) {
171                 if (_port->set_state (*portnode, version)) {
172                         return -1;
173                 }
174         }
175
176         return 0;
177 }
178
179 const MidiByteArray& 
180 Surface::sysex_hdr() const
181 {
182         switch  (_stype) {
183         case mcu: return mackie_sysex_hdr;
184         case ext: return mackie_sysex_hdr_xt;
185         }
186         cout << "SurfacePort::sysex_hdr _port_type not known" << endl;
187         return mackie_sysex_hdr;
188 }
189
190 static GlobalControlDefinition mackie_global_controls[] = {
191         { "external", Pot::External, Pot::factory, "none" },
192         { "fader_touch", Led::FaderTouch, Led::factory, "master" },
193         { "timecode", Led::Timecode, Led::factory, "none" },
194         { "beats", Led::Beats, Led::factory, "none" },
195         { "solo", Led::RudeSolo, Led::factory, "none" },
196         { "relay_click", Led::RelayClick, Led::factory, "none" },
197         { "", 0, Led::factory, "" }
198 };
199
200 void 
201 Surface::init_controls()
202 {
203         Group* group;
204         
205         DEBUG_TRACE (DEBUG::MackieControl, "Surface::init_controls: creating groups\n");
206         groups["assignment"] = new Group  ("assignment");
207         groups["automation"] = new Group  ("automation");
208         groups["bank"] = new Group  ("bank");
209         groups["cursor"] = new Group  ("cursor");
210         groups["display"] = new Group  ("display");
211         groups["function select"] = new Group  ("function select");
212         groups["global view"] = new Group ("global view");
213         groups["master"] = new Group ("master");
214         groups["modifiers"] = new Group  ("modifiers");
215         groups["none"] = new Group  ("none");
216         groups["transport"] = new Group  ("transport");
217         groups["user"] = new Group  ("user");
218         groups["utilities"] = new Group  ("utilities");
219                 
220         DEBUG_TRACE (DEBUG::MackieControl, "Surface::init_controls: creating jog wheel\n");
221         if (_mcp.device_info().has_jog_wheel()) {
222                 _jog_wheel = new Mackie::JogWheel (_mcp);
223         }
224
225         DEBUG_TRACE (DEBUG::MackieControl, "Surface::init_controls: creating global controls\n");
226         for (uint32_t n = 0; mackie_global_controls[n].name[0]; ++n) {
227                 group = groups[mackie_global_controls[n].group_name];
228                 Control* control = mackie_global_controls[n].factory (*this, mackie_global_controls[n].id, mackie_global_controls[n].name, *group);
229                 controls_by_device_independent_id[mackie_global_controls[n].id] = control;
230         }
231
232         /* add global buttons */
233         DEBUG_TRACE (DEBUG::MackieControl, "Surface::init_controls: adding global buttons\n");
234         const map<Button::ID,GlobalButtonInfo>& global_buttons (_mcp.device_info().global_buttons());
235
236         for (map<Button::ID,GlobalButtonInfo>::const_iterator b = global_buttons.begin(); b != global_buttons.end(); ++b){
237                 group = groups[b->second.group];
238                 controls_by_device_independent_id[b->first] = Button::factory (*this, b->first, b->second.id, b->second.label, *group);
239         }
240 }
241
242 void 
243 Surface::init_strips (uint32_t n)
244 {
245         const map<Button::ID,StripButtonInfo>& strip_buttons (_mcp.device_info().strip_buttons());
246
247         for (uint32_t i = 0; i < n; ++i) {
248
249                 char name[32];
250                 
251                 snprintf (name, sizeof (name), "strip_%d", (8* _number) + i);
252
253                 Strip* strip = new Strip (*this, name, i, strip_buttons);
254                 
255                 groups[name] = strip;
256                 strips.push_back (strip);
257         }
258 }
259
260 void
261 Surface::setup_master ()
262 {
263         boost::shared_ptr<Route> m;
264         
265         if ((m = _mcp.get_session().monitor_out()) == 0) {
266                 m = _mcp.get_session().master_out();
267         } 
268         
269         if (!m) {
270                 return;
271         }
272
273         _master_fader = dynamic_cast<Fader*> (Fader::factory (*this, _mcp.device_info().strip_cnt(), "master", *groups["master"]));
274         
275         _master_fader->set_control (m->gain_control());
276         m->gain_control()->Changed.connect (*this, MISSING_INVALIDATOR, boost::bind (&Surface::master_gain_changed, this), ui_context());
277
278         Groups::iterator group_it;
279         group_it = groups.find("master");
280
281         DeviceInfo device_info = _mcp.device_info();
282         GlobalButtonInfo master_button = device_info.get_global_button(Button::MasterFaderTouch);
283         Button* bb = dynamic_cast<Button*> (Button::factory (
284                 *this,
285                 Button::MasterFaderTouch,
286                 master_button.id,
287                 master_button.label,
288                 *(group_it->second)
289 ));
290         DEBUG_TRACE (DEBUG::MackieControl, string_compose ("surface %1 Master Fader new button BID %2 id %3\n",
291                 number(), Button::MasterFaderTouch, bb->id()));
292 }
293
294 void
295 Surface::master_gain_changed ()
296 {
297         if (!_master_fader) {
298                 return;
299         }
300
301         boost::shared_ptr<AutomationControl> ac = _master_fader->control();
302         if (!ac) {
303                 return;
304         }
305
306         float normalized_position = ac->internal_to_interface (ac->get_value());
307         if (normalized_position == _last_master_gain_written) {
308                 return;
309         }
310
311         DEBUG_TRACE (DEBUG::MackieControl, "Surface::master_gain_changed: updating surface master fader\n");
312
313         _port->write (_master_fader->set_position (normalized_position));
314         _last_master_gain_written = normalized_position;
315 }
316
317 float 
318 Surface::scaled_delta (float delta, float current_speed)
319 {
320         /* XXX needs work before use */
321         const float sign = delta < 0.0 ? -1.0 : 1.0;
322
323         return ((sign * std::pow (delta + 1.0, 2.0)) + current_speed) / 100.0;
324 }
325
326 void 
327 Surface::display_bank_start (uint32_t current_bank)
328 {
329         if  (current_bank == 0) {
330                 // send Ar. to 2-char display on the master
331                 show_two_char_display ("Ar", "..");
332         } else {
333                 // write the current first remote_id to the 2-char display
334                 show_two_char_display (current_bank);
335         }
336 }
337
338 void 
339 Surface::blank_jog_ring ()
340 {
341         Control* control = controls_by_device_independent_id[Jog::ID];
342
343         if (control) {
344                 Pot* pot = dynamic_cast<Pot*> (control);
345                 if (pot) {
346                         _port->write (pot->set (0.0, false, Pot::spread));
347                 }
348         }
349 }
350
351 float
352 Surface::scrub_scaling_factor () const
353 {
354         return 100.0;
355 }
356
357 void 
358 Surface::connect_to_signals ()
359 {
360         if (!_connected) {
361
362
363                 DEBUG_TRACE (DEBUG::MackieControl, string_compose ("Surface %1 connecting to signals on port %2\n", 
364                                                                    number(), _port->input_port().name()));
365
366                 MIDI::Parser* p = _port->input_port().parser();
367
368                 /* Incoming sysex */
369                 p->sysex.connect_same_thread (*this, boost::bind (&Surface::handle_midi_sysex, this, _1, _2, _3));
370                 /* V-Pot messages are Controller */
371                 p->controller.connect_same_thread (*this, boost::bind (&Surface::handle_midi_controller_message, this, _1, _2));
372                 /* Button messages are NoteOn */
373                 p->note_on.connect_same_thread (*this, boost::bind (&Surface::handle_midi_note_on_message, this, _1, _2));
374                 /* Button messages are NoteOn but libmidi++ sends note-on w/velocity = 0 as note-off so catch them too */
375                 p->note_off.connect_same_thread (*this, boost::bind (&Surface::handle_midi_note_on_message, this, _1, _2));
376                 /* Fader messages are Pitchbend */
377                 uint32_t i;
378                 for (i = 0; i < _mcp.device_info().strip_cnt(); i++) {
379                         p->channel_pitchbend[i].connect_same_thread (*this, boost::bind (&Surface::handle_midi_pitchbend_message, this, _1, _2, i));
380                 }
381                 // Master fader
382                 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()));
383                 
384                 _connected = true;
385         }
386 }
387
388 void
389 Surface::handle_midi_pitchbend_message (MIDI::Parser&, MIDI::pitchbend_t pb, uint32_t fader_id)
390 {
391         /* Pitchbend messages are fader position messages. Nothing in the data we get
392          * from the MIDI::Parser conveys the fader ID, which was given by the
393          * channel ID in the status byte.
394          *
395          * Instead, we have used bind() to supply the fader-within-strip ID 
396          * when we connected to the per-channel pitchbend events.
397          */
398
399         DEBUG_TRACE (DEBUG::MackieControl, string_compose ("Surface::handle_midi_pitchbend_message on port %3, fader = %1 value = %2\n",
400                                                            fader_id, pb, _number));
401         
402         if (_mcp.device_info().no_handshake()) {
403                 turn_it_on ();
404         }
405
406         Fader* fader = faders[fader_id];
407
408         if (fader) {
409                 Strip* strip = dynamic_cast<Strip*> (&fader->group());
410                 float pos = (pb >> 4)/1023.0; // only the top 10 bytes are used
411                 if (strip) {
412                         strip->handle_fader (*fader, pos);
413                 } else {
414                         DEBUG_TRACE (DEBUG::MackieControl, "Handling master fader\n");
415                         /* master fader */
416                         fader->set_value (pos); // alter master gain
417                         _port->write (fader->set_position (pos)); // write back value (required for servo)
418                 }
419         } else {
420                 DEBUG_TRACE (DEBUG::MackieControl, "fader not found\n");
421         }
422 }
423
424 void 
425 Surface::handle_midi_note_on_message (MIDI::Parser &, MIDI::EventTwoBytes* ev)
426 {
427         DEBUG_TRACE (DEBUG::MackieControl, string_compose ("Surface::handle_midi_note_on_message %1 = %2\n", (int) ev->note_number, (int) ev->velocity));
428         
429         if (_mcp.device_info().no_handshake()) {
430                 turn_it_on ();
431         }
432
433         /* fader touch sense is given by "buttons" 0xe..0xe7 and 0xe8 for the
434          * master. 
435          */
436
437         if (ev->note_number >= 0xE0 && ev->note_number <= 0xE8) {
438                 Fader* fader = faders[ev->note_number];
439
440                 DEBUG_TRACE (DEBUG::MackieControl, string_compose ("Surface: fader touch message, fader = %1\n", fader));
441
442                 if (fader) {
443
444                         Strip* strip = dynamic_cast<Strip*> (&fader->group());
445
446                         if (ev->velocity > 64) {
447                                 strip->handle_fader_touch (*fader, true);
448                         } else {
449                                 strip->handle_fader_touch (*fader, false);
450                         }
451                 }
452                 return;
453         }
454
455         Button* button = buttons[ev->note_number];
456
457         if (button) {
458                 Strip* strip = dynamic_cast<Strip*> (&button->group());
459
460                 if (strip) {
461                         DEBUG_TRACE (DEBUG::MackieControl, string_compose ("strip %1 button %2 pressed ? %3\n",
462                                                                            strip->index(), button->name(), (ev->velocity > 64)));
463                         strip->handle_button (*button, ev->velocity > 64 ? press : release);
464                 } else {
465                         /* global button */
466                         DEBUG_TRACE (DEBUG::MackieControl, string_compose ("global button %1\n", button->id()));
467                         _mcp.handle_button_event (*this, *button, ev->velocity > 64 ? press : release);
468                 }
469         } else {
470                 DEBUG_TRACE (DEBUG::MackieControl, string_compose ("no button found for %1\n", (int) ev->note_number));
471         }
472 }
473
474 void 
475 Surface::handle_midi_controller_message (MIDI::Parser &, MIDI::EventTwoBytes* ev)
476 {
477         DEBUG_TRACE (DEBUG::MackieControl, string_compose ("SurfacePort::handle_midi_controller %1 = %2\n", (int) ev->controller_number, (int) ev->value));
478
479         if (_mcp.device_info().no_handshake()) {
480                 turn_it_on ();
481         }
482
483         Pot* pot = pots[ev->controller_number];
484
485         // bit 6 gives the sign
486         float sign = (ev->value & 0x40) == 0 ? 1.0 : -1.0; 
487         // bits 0..5 give the velocity. we interpret this as "ticks
488         // moved before this message was sent"
489         float ticks = (ev->value & 0x3f);
490         if (ticks == 0) {
491                 /* euphonix and perhaps other devices send zero
492                    when they mean 1, we think.
493                 */
494                 ticks = 1;
495         }
496
497         float delta = 0;
498         if (mcp().modifier_state() == MackieControlProtocol::MODIFIER_CONTROL) {
499                 delta = sign * (ticks / (float) 0xff);
500         } else {
501                 delta = sign * (ticks / (float) 0x3f);
502         }
503         
504         if (!pot) {
505                 if (ev->controller_number == Jog::ID && _jog_wheel) {
506
507                         DEBUG_TRACE (DEBUG::MackieControl, string_compose ("Jog wheel moved %1\n", ticks));
508                         _jog_wheel->jog_event (delta);
509                         return;
510                 }
511                 // add external (pedal?) control here
512
513                 return;
514         }
515
516         Strip* strip = dynamic_cast<Strip*> (&pot->group());
517         if (strip) {
518                 strip->handle_pot (*pot, delta);
519         } 
520 }
521
522 void 
523 Surface::handle_midi_sysex (MIDI::Parser &, MIDI::byte * raw_bytes, size_t count)
524 {
525         MidiByteArray bytes (count, raw_bytes);
526
527         DEBUG_TRACE (DEBUG::MackieControl, string_compose ("handle_midi_sysex: %1\n", bytes));
528
529         if (_mcp.device_info().no_handshake()) {
530                 turn_it_on ();
531         }
532
533         /* always save the device type ID so that our outgoing sysex messages
534          * are correct 
535          */
536
537         if (_stype == mcu) {
538                 mackie_sysex_hdr[4] = bytes[4];
539         } else {
540                 mackie_sysex_hdr_xt[4] = bytes[4];
541         }
542
543         switch (bytes[5]) {
544         case 0x01:
545                 /* MCP: Device Ready 
546                    LCP: Connection Challenge 
547                 */
548                 if (bytes[4] == 0x10 || bytes[4] == 0x11) {
549                         DEBUG_TRACE (DEBUG::MackieControl, "Logic Control Device connection challenge\n");
550                         write_sysex (host_connection_query (bytes));
551                 } else {
552                         DEBUG_TRACE (DEBUG::MackieControl, string_compose ("Mackie Control Device ready, current status = %1\n", _active));
553                         if (!_active) {
554                                 turn_it_on ();
555                         }
556                 }
557                 break;
558
559         case 0x03: /* LCP Connection Confirmation */
560                 DEBUG_TRACE (DEBUG::MackieControl, "Logic Control Device confirms connection, ardour replies\n");
561                 if (bytes[4] == 0x10 || bytes[4] == 0x11) {
562                         write_sysex (host_connection_confirmation (bytes));
563                         _active = true;
564                 }
565                 break;
566
567         case 0x04: /* LCP: Confirmation Denied */
568                 DEBUG_TRACE (DEBUG::MackieControl, "Logic Control Device denies connection\n");
569                 _active = false;
570                 break;
571         default:
572                 error << "MCP: unknown sysex: " << bytes << endmsg;
573         }
574 }
575
576 static MidiByteArray 
577 calculate_challenge_response (MidiByteArray::iterator begin, MidiByteArray::iterator end)
578 {
579         MidiByteArray l;
580         back_insert_iterator<MidiByteArray> back  (l);
581         copy (begin, end, back);
582         
583         MidiByteArray retval;
584         
585         // this is how to calculate the response to the challenge.
586         // from the Logic docs.
587         retval <<  (0x7f &  (l[0] +  (l[1] ^ 0xa) - l[3]));
588         retval <<  (0x7f &  ( (l[2] >> l[3]) ^  (l[0] + l[3])));
589         retval <<  (0x7f &  ((l[3] -  (l[2] << 2)) ^  (l[0] | l[1])));
590         retval <<  (0x7f &  (l[1] - l[2] +  (0xf0 ^  (l[3] << 4))));
591         
592         return retval;
593 }
594
595 // not used right now
596 MidiByteArray 
597 Surface::host_connection_query (MidiByteArray & bytes)
598 {
599         MidiByteArray response;
600         
601         if (bytes[4] != 0x10 && bytes[4] != 0x11) {
602                 /* not a Logic Control device - no response required */
603                 return response;
604         }
605
606         // handle host connection query
607         DEBUG_TRACE (DEBUG::MackieControl, string_compose ("host connection query: %1\n", bytes));
608         
609         if  (bytes.size() != 18) {
610                 cerr << "expecting 18 bytes, read " << bytes << " from " << _port->input_port().name() << endl;
611                 return response;
612         }
613
614         // build and send host connection reply
615         response << 0x02;
616         copy (bytes.begin() + 6, bytes.begin() + 6 + 7, back_inserter (response));
617         response << calculate_challenge_response (bytes.begin() + 6 + 7, bytes.begin() + 6 + 7 + 4);
618         return response;
619 }
620
621 // not used right now
622 MidiByteArray 
623 Surface::host_connection_confirmation (const MidiByteArray & bytes)
624 {
625         DEBUG_TRACE (DEBUG::MackieControl, string_compose ("host_connection_confirmation: %1\n", bytes));
626         
627         // decode host connection confirmation
628         if  (bytes.size() != 14) {
629                 ostringstream os;
630                 os << "expecting 14 bytes, read " << bytes << " from " << _port->input_port().name();
631                 throw MackieControlException (os.str());
632         }
633         
634         // send version request
635         return MidiByteArray (2, 0x13, 0x00);
636 }
637
638 void
639 Surface::turn_it_on ()
640 {
641         if (_active) {
642                 return;
643         }
644
645         _active = true;
646
647         _mcp.device_ready ();
648
649         for (Strips::iterator s = strips.begin(); s != strips.end(); ++s) {
650                 (*s)->notify_all ();
651         }
652
653         update_view_mode_display ();
654
655         if (_mcp.device_info ().has_global_controls ()) {
656                 _mcp.update_global_button (Button::Read, _mcp.metering_active ());
657         }
658 }
659
660 void 
661 Surface::write_sysex (const MidiByteArray & mba)
662 {
663         if (mba.empty()) {
664                 return;
665         }
666
667         MidiByteArray buf;
668         buf << sysex_hdr() << mba << MIDI::eox;
669         _port->write (buf);
670 }
671
672 void 
673 Surface::write_sysex (MIDI::byte msg)
674 {
675         MidiByteArray buf;
676         buf << sysex_hdr() << msg << MIDI::eox;
677         _port->write (buf);
678 }
679
680 uint32_t
681 Surface::n_strips (bool with_locked_strips) const
682 {
683         if (with_locked_strips) {
684                 return strips.size();
685         } 
686
687         uint32_t n = 0;
688
689         for (Strips::const_iterator it = strips.begin(); it != strips.end(); ++it) {
690                 if (!(*it)->locked()) {
691                         ++n;
692                 }
693         }
694         return n;
695 }
696
697 Strip*
698 Surface::nth_strip (uint32_t n) const
699 {
700         if (n > n_strips()) {
701                 return 0;
702         }
703         return strips[n];
704 }
705
706 void
707 Surface::zero_all ()
708 {
709         if (_mcp.device_info().has_timecode_display ()) {
710                 display_timecode (string (10, '0'), string (10, ' '));
711         }
712         
713         if (_mcp.device_info().has_two_character_display()) {
714                 show_two_char_display (string (2, '0'), string (2, ' '));
715         }
716
717         if (_mcp.device_info().has_master_fader () && _master_fader) {
718                 _port->write (_master_fader->zero ());
719         }
720
721         // zero all strips
722         for (Strips::iterator it = strips.begin(); it != strips.end(); ++it) {
723                 (*it)->zero();
724         }
725
726         zero_controls ();
727 }
728
729 void
730 Surface::zero_controls ()
731 {
732         if (!_mcp.device_info().has_global_controls()) {
733                 return;
734         }
735
736         // turn off global buttons and leds
737         // global buttons are only ever on mcu_port, so we don't have
738         // to figure out which port.
739
740         for (Controls::iterator it = controls.begin(); it != controls.end(); ++it) {
741                 Control & control = **it;
742                 if (!control.group().is_strip()) {
743                         _port->write (control.zero());
744                 }
745         }
746
747         // and the led ring for the master strip
748         blank_jog_ring ();
749
750         _last_master_gain_written = 0.0f;
751 }
752
753 void
754 Surface::periodic (uint64_t now_usecs)
755 {
756         master_gain_changed();
757         for (Strips::iterator s = strips.begin(); s != strips.end(); ++s) {
758                 (*s)->periodic (now_usecs);
759         }
760 }
761
762 void
763 Surface::write (const MidiByteArray& data) 
764 {
765         if (_active) {
766                 _port->write (data);
767         } else {
768                 DEBUG_TRACE (DEBUG::MackieControl, "surface not active, write ignored\n");
769         }
770 }
771
772 void
773 Surface::map_routes (const vector<boost::shared_ptr<Route> >& routes)
774 {
775         vector<boost::shared_ptr<Route> >::const_iterator r;
776         Strips::iterator s = strips.begin();
777
778         DEBUG_TRACE (DEBUG::MackieControl, string_compose ("Mapping %1 routes", routes.size()));
779
780         for (r = routes.begin(); r != routes.end() && s != strips.end(); ++s) {
781
782                 /* don't try to assign routes to a locked strip. it won't
783                    use it anyway, but if we do, then we get out of sync
784                    with the proposed mapping.
785                 */
786
787                 if (!(*s)->locked()) {
788                         (*s)->set_route (*r);
789                         ++r;
790                 }
791         }
792
793         for (; s != strips.end(); ++s) {
794                 (*s)->set_route (boost::shared_ptr<Route>());
795         }
796
797
798 }
799
800 static char 
801 translate_seven_segment (char achar)
802 {
803         achar = toupper (achar);
804
805         if  (achar >= 0x40 && achar <= 0x60) {
806                 return achar - 0x40;
807         } else if  (achar >= 0x21 && achar <= 0x3f) {
808                 return achar;
809         } else {
810                 return 0x00;
811         }
812 }
813
814 void
815 Surface::show_two_char_display (const std::string & msg, const std::string & dots)
816 {
817         if (_stype != mcu || !_mcp.device_info().has_two_character_display() || msg.length() != 2 || dots.length() != 2) {
818                 return;
819         }
820         
821         MidiByteArray right (3, 0xb0, 0x4b, 0x00);
822         MidiByteArray left (3, 0xb0, 0x4a, 0x00);
823         
824         right[2] = translate_seven_segment (msg[0]) +  (dots[0] == '.' ? 0x40 : 0x00);
825         left[2] = translate_seven_segment (msg[1]) +  (dots[1] == '.' ? 0x40 : 0x00);
826         
827         _port->write (right);
828         _port->write (left);
829 }
830
831 void
832 Surface::show_two_char_display (unsigned int value, const std::string & /*dots*/)
833 {
834         ostringstream os;
835         os << setfill('0') << setw(2) << value % 100;
836         show_two_char_display (os.str());
837 }
838
839 void
840 Surface::display_timecode (const std::string & timecode, const std::string & last_timecode)
841 {
842         if (!_active || !_mcp.device_info().has_timecode_display()) {
843                 return;
844         }
845         // if there's no change, send nothing, not even sysex header
846         if  (timecode == last_timecode) return;
847         
848         // length sanity checking
849         string local_timecode = timecode;
850
851         // truncate to 10 characters
852         if  (local_timecode.length() > 10) {
853                 local_timecode = local_timecode.substr (0, 10);
854         }
855
856         // pad to 10 characters
857         while  (local_timecode.length() < 10) { 
858                 local_timecode += " ";
859         }
860         
861         // translate characters.
862         // Only the characters that actually changed are sent.
863         int position = 0x3f;
864         int i;
865         for (i = local_timecode.length () - 1; i >= 0; i--) {
866                 position++;
867                 if (local_timecode[i] == last_timecode[i]) {
868                         continue;
869                 }
870                 MidiByteArray retval (2, 0xb0, position);
871                 retval << translate_seven_segment (local_timecode[i]);
872                 _port->write (retval);
873         }
874 }
875
876 void
877 Surface::update_flip_mode_display ()
878 {
879         for (Strips::iterator s = strips.begin(); s != strips.end(); ++s) {
880                 (*s)->flip_mode_changed (true);
881         }
882 }
883
884 void
885 Surface::update_view_mode_display ()
886 {
887         string text;
888         int id = -1;
889
890         if (!_active) {
891                 return;
892         }
893
894         switch (_mcp.view_mode()) {
895         case MackieControlProtocol::Mixer:
896                 show_two_char_display ("Mx");
897                 id = Button::Pan;
898                 break;
899         case MackieControlProtocol::Dynamics:
900                 show_two_char_display ("Dy");
901                 id = Button::Dyn;
902                 break;
903         case MackieControlProtocol::EQ:
904                 show_two_char_display ("EQ");
905                 id = Button::Eq;
906                 break;
907         case MackieControlProtocol::Loop:
908                 show_two_char_display ("LP");
909                 id = Button::Loop;
910                 break;
911         case MackieControlProtocol::AudioTracks:
912                 show_two_char_display ("AT");
913                 break;
914         case MackieControlProtocol::MidiTracks:
915                 show_two_char_display ("MT");
916                 break;
917         case MackieControlProtocol::Sends:
918                 show_two_char_display ("Sn");
919                 id = Button::Send;
920                 break;
921         case MackieControlProtocol::Plugins:
922                 show_two_char_display ("Pl");
923                 id = Button::Plugin;
924                 break;
925         default:
926                 break;
927         }
928
929         if (id >= 0) {
930                 
931                 /* we are attempting to turn a global button/LED on */
932
933                 map<int,Control*>::iterator x = controls_by_device_independent_id.find (id);
934
935                 if (x != controls_by_device_independent_id.end()) {
936                         Button* button = dynamic_cast<Button*> (x->second);
937                         if (button) {
938                                 _port->write (button->set_state (on));
939                         }
940                 }
941         }
942
943         if (!text.empty()) {
944                 for (Strips::iterator s = strips.begin(); s != strips.end(); ++s) {
945                         _port->write ((*s)->display (1, text));
946                 }
947         }
948 }
949
950 void
951 Surface::gui_selection_changed (const ARDOUR::StrongRouteNotificationList& routes)
952 {
953         for (Strips::iterator s = strips.begin(); s != strips.end(); ++s) {
954                 (*s)->gui_selection_changed (routes);
955         }
956 }
957
958 void
959 Surface::say_hello ()
960 {
961         /* wakeup for Mackie Control */
962         MidiByteArray wakeup (7, MIDI::sysex, 0x00, 0x00, 0x66, 0x14, 0x00, MIDI::eox);
963         _port->write (wakeup);
964         wakeup[4] = 0x15; /* wakup Mackie XT */
965         _port->write (wakeup);
966         wakeup[4] = 0x10; /* wakupe Logic Control */
967         _port->write (wakeup);
968         wakeup[4] = 0x11; /* wakeup Logic Control XT */
969         _port->write (wakeup);
970 }
971
972 void
973 Surface::next_jog_mode ()
974 {
975 }
976
977 void
978 Surface::set_jog_mode (JogWheel::Mode)
979 {
980 }       
981
982 bool
983 Surface::route_is_locked_to_strip (boost::shared_ptr<Route> r) const
984 {
985         for (Strips::const_iterator s = strips.begin(); s != strips.end(); ++s) {
986                 if ((*s)->route() == r && (*s)->locked()) {
987                         return true;
988                 }
989         }
990         return false;
991 }
992
993 void 
994 Surface::notify_metering_state_changed()
995 {
996         for (Strips::const_iterator s = strips.begin(); s != strips.end(); ++s) {
997                 (*s)->notify_metering_state_changed ();
998         }
999 }