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