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