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