push2: numerous changes, including long press actions
[ardour.git] / libs / surfaces / push2 / push2.cc
1 /*
2         Copyright (C) 2016 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 #include <cairomm/context.h>
20 #include <cairomm/surface.h>
21 #include <pangomm/layout.h>
22
23 #include "pbd/compose.h"
24 #include "pbd/convert.h"
25 #include "pbd/debug.h"
26 #include "pbd/failed_constructor.h"
27
28 #include "midi++/parser.h"
29 #include "timecode/time.h"
30 #include "timecode/bbt_time.h"
31
32 #include "ardour/async_midi_port.h"
33 #include "ardour/audioengine.h"
34 #include "ardour/debug.h"
35 #include "ardour/midiport_manager.h"
36 #include "ardour/session.h"
37 #include "ardour/tempo.h"
38
39 #include "push2.h"
40
41 using namespace ARDOUR;
42 using namespace std;
43 using namespace PBD;
44 using namespace Glib;
45 using namespace ArdourSurface;
46
47 #include "i18n.h"
48
49 #include "pbd/abstract_ui.cc" // instantiate template
50
51 const int Push2::cols = 960;
52 const int Push2::rows = 160;
53 const int Push2::pixels_per_row = 1024;
54
55 #define ABLETON 0x2982
56 #define PUSH2   0x1967
57
58 Push2::Push2 (ARDOUR::Session& s)
59         : ControlProtocol (s, string (X_("Ableton Push 2")))
60         , AbstractUI<Push2Request> (name())
61         , handle (0)
62         , device_buffer (0)
63         , frame_buffer (Cairo::ImageSurface::create (Cairo::FORMAT_ARGB32, cols, rows))
64         , modifier_state (None)
65         , bank_start (0)
66 {
67         context = Cairo::Context::create (frame_buffer);
68         tc_clock_layout = Pango::Layout::create (context);
69         bbt_clock_layout = Pango::Layout::create (context);
70
71         Pango::FontDescription fd ("Sans Bold 24");
72         tc_clock_layout->set_font_description (fd);
73         bbt_clock_layout->set_font_description (fd);
74
75         Pango::FontDescription fd2 ("Sans 10");
76         for (int n = 0; n < 8; ++n) {
77                 upper_layout[n] = Pango::Layout::create (context);
78                 upper_layout[n]->set_font_description (fd2);
79                 upper_layout[n]->set_text ("solo");
80                 lower_layout[n] = Pango::Layout::create (context);
81                 lower_layout[n]->set_font_description (fd2);
82                 lower_layout[n]->set_text ("mute");
83         }
84
85         Pango::FontDescription fd3 ("Sans Bold 10");
86         for (int n = 0; n < 8; ++n) {
87                 mid_layout[n] = Pango::Layout::create (context);
88                 mid_layout[n]->set_font_description (fd3);
89         }
90
91         build_maps ();
92
93         if (open ()) {
94                 throw failed_constructor ();
95         }
96
97 }
98
99 Push2::~Push2 ()
100 {
101         close ();
102 }
103
104 int
105 Push2::open ()
106 {
107         int err;
108
109         if (handle) {
110                 /* already open */
111                 return 0;
112         }
113
114         if ((handle = libusb_open_device_with_vid_pid (NULL, ABLETON, PUSH2)) == 0) {
115                 return -1;
116         }
117
118         if ((err = libusb_claim_interface (handle, 0x00))) {
119                 return -1;
120         }
121
122         device_frame_buffer = new uint16_t[rows*pixels_per_row];
123
124         memset (device_frame_buffer, 0, sizeof (uint16_t) * rows * pixels_per_row);
125
126         frame_header[0] = 0xef;
127         frame_header[1] = 0xcd;
128         frame_header[2] = 0xab;
129         frame_header[3] = 0x89;
130         memset (&frame_header[4], 0, 12);
131
132         /* setup ports */
133
134         _async_in  = AudioEngine::instance()->register_input_port (DataType::MIDI, X_("push2 in"), true);
135         _async_out = AudioEngine::instance()->register_output_port (DataType::MIDI, X_("push2 out"), true);
136
137         if (_async_in == 0 || _async_out == 0) {
138                 return -1;
139         }
140
141         _input_port = boost::dynamic_pointer_cast<AsyncMIDIPort>(_async_in).get();
142         _output_port = boost::dynamic_pointer_cast<AsyncMIDIPort>(_async_out).get();
143
144         connect_to_parser ();
145
146         return 0;
147 }
148
149 int
150 Push2::close ()
151 {
152         init_buttons (false);
153
154         /* wait for button data to be flushed */
155         AsyncMIDIPort* asp;
156         asp = dynamic_cast<AsyncMIDIPort*> (_output_port);
157         asp->drain (10000, 500000);
158
159         AudioEngine::instance()->unregister_port (_async_in);
160         AudioEngine::instance()->unregister_port (_async_out);
161
162         _async_in.reset ((ARDOUR::Port*) 0);
163         _async_out.reset ((ARDOUR::Port*) 0);
164         _input_port = 0;
165         _output_port = 0;
166
167         vblank_connection.disconnect ();
168         periodic_connection.disconnect ();
169         session_connections.drop_connections ();
170         stripable_connections.drop_connections ();
171
172         if (handle) {
173                 libusb_release_interface (handle, 0x00);
174                 libusb_close (handle);
175                 handle = 0;
176         }
177
178         for (int n = 0; n < 8; ++n) {
179                 stripable[n].reset ();
180         }
181
182         delete [] device_frame_buffer;
183         device_frame_buffer = 0;
184
185         return 0;
186 }
187
188 void
189 Push2::init_buttons (bool startup)
190 {
191         /* This is a list of buttons that we want lit because they do something
192            in ardour related (loosely, sometimes) to their illuminated label.
193         */
194
195         ButtonID buttons[] = { Mute, Solo, Master, Up, Right, Left, Down, Note, Session, Mix, AddTrack, Delete, Undo,
196                                Metronome, Shift, Select, Play, RecordEnable, Automate, Repeat, Note, Session, DoubleLoop,
197                                Quantize, Duplicate, Browse,
198         };
199
200         for (size_t n = 0; n < sizeof (buttons) / sizeof (buttons[0]); ++n) {
201                 Button* b = id_button_map[buttons[n]];
202
203                 if (startup) {
204                         b->set_color (LED::White);
205                 } else {
206                         b->set_color (LED::Black);
207                 }
208                 b->set_state (LED::OneShot24th);
209                 write (b->state_msg());
210         }
211
212         /* Strip buttons should all be off (black) by default. They will change
213          * color to reflect various conditions
214          */
215
216         ButtonID strip_buttons[] = { Upper1, Upper2, Upper3, Upper4, Upper5, Upper6, Upper7, Upper8,
217                                      Lower1, Lower2, Lower3, Lower4, Lower5, Lower6, Lower7, Lower8, };
218
219         for (size_t n = 0; n < sizeof (strip_buttons) / sizeof (strip_buttons[0]); ++n) {
220                 Button* b = id_button_map[strip_buttons[n]];
221
222                 b->set_color (LED::Black);
223                 b->set_state (LED::OneShot24th);
224                 write (b->state_msg());
225         }
226
227         if (startup) {
228
229                 /* all other buttons are off (black) */
230
231                 ButtonID off_buttons[] = { TapTempo, Setup, User, Stop, Convert, New, FixedLength,
232                                            Fwd32ndT, Fwd32nd, Fwd16thT, Fwd16th, Fwd8thT, Fwd8th, Fwd4trT, Fwd4tr,
233                                            Accent, Scale, Layout, Note, Session, OctaveUp, PageRight, OctaveDown, PageLeft, };
234
235                 for (size_t n = 0; n < sizeof (off_buttons) / sizeof (off_buttons[0]); ++n) {
236                         Button* b = id_button_map[off_buttons[n]];
237
238                         b->set_color (LED::Black);
239                         b->set_state (LED::OneShot24th);
240                         write (b->state_msg());
241                 }
242         }
243
244 }
245
246 bool
247 Push2::probe ()
248 {
249         libusb_device_handle *h;
250         libusb_init (NULL);
251
252         if ((h = libusb_open_device_with_vid_pid (NULL, ABLETON, PUSH2)) == 0) {
253                 DEBUG_TRACE (DEBUG::Push2, "no Push2 device found\n");
254                 return false;
255         }
256
257         libusb_close (h);
258         DEBUG_TRACE (DEBUG::Push2, "Push2 device located\n");
259         return true;
260 }
261
262 void*
263 Push2::request_factory (uint32_t num_requests)
264 {
265         /* AbstractUI<T>::request_buffer_factory() is a template method only
266            instantiated in this source module. To provide something visible for
267            use in the interface/descriptor, we have this static method that is
268            template-free.
269         */
270         return request_buffer_factory (num_requests);
271 }
272
273 void
274 Push2::do_request (Push2Request * req)
275 {
276         DEBUG_TRACE (DEBUG::Push2, string_compose ("doing request type %1\n", req->type));
277         if (req->type == CallSlot) {
278
279                 call_slot (MISSING_INVALIDATOR, req->the_slot);
280
281         } else if (req->type == Quit) {
282
283                 stop ();
284         }
285 }
286
287 int
288 Push2::stop ()
289 {
290         BaseUI::quit ();
291         close ();
292         return 0;
293 }
294
295 /** render host-side frame buffer (a Cairo ImageSurface) to the current
296  * device-side frame buffer. The device frame buffer will be pushed to the
297  * device on the next call to vblank()
298  */
299
300 int
301 Push2::blit_to_device_frame_buffer ()
302 {
303         /* ensure that all drawing has been done before we fetch pixel data */
304
305         frame_buffer->flush ();
306
307         const int stride = 3840; /* bytes per row for Cairo::FORMAT_ARGB32 */
308         const uint8_t* data = frame_buffer->get_data ();
309
310         /* fill frame buffer (320kB) */
311
312         uint16_t* fb = (uint16_t*) device_frame_buffer;
313
314         for (int row = 0; row < rows; ++row) {
315
316                 const uint8_t* dp = data + row * stride;
317
318                 for (int col = 0; col < cols; ++col) {
319
320                         /* fetch r, g, b (range 0..255). Ignore alpha */
321
322                         const int r = (*((const uint32_t*)dp) >> 16) & 0xff;
323                         const int g = (*((const uint32_t*)dp) >> 8) & 0xff;
324                         const int b = *((const uint32_t*)dp) & 0xff;
325
326                         /* convert to 5 bits, 6 bits, 5 bits, respectively */
327                         /* generate 16 bit BGB565 value */
328
329                         *fb++ = (r >> 3) | ((g & 0xfc) << 3) | ((b & 0xf8) << 8);
330
331                         /* the push2 docs state that we should xor the pixel
332                          * data. Doing so doesn't work correctly, and not doing
333                          * so seems to work fine (colors roughly match intended
334                          * values).
335                          */
336
337                         dp += 4;
338                 }
339
340                 /* skip 128 bytes to next line. This is filler, used to avoid line borders occuring in the middle of 512
341                    byte USB buffers
342                 */
343
344                 fb += 64; /* 128 bytes = 64 int16_t */
345         }
346
347         return 0;
348 }
349
350 bool
351 Push2::redraw ()
352 {
353         string tc_clock_text;
354         string bbt_clock_text;
355
356         if (session) {
357                 framepos_t audible = session->audible_frame();
358                 Timecode::Time TC;
359                 bool negative = false;
360
361                 if (audible < 0) {
362                         audible = -audible;
363                         negative = true;
364                 }
365
366                 session->timecode_time (audible, TC);
367
368                 TC.negative = TC.negative || negative;
369
370                 tc_clock_text = Timecode::timecode_format_time(TC);
371
372                 Timecode::BBT_Time bbt = session->tempo_map().bbt_at_frame (audible);
373                 char buf[16];
374
375 #define BBT_BAR_CHAR "|"
376
377                 if (negative) {
378                         snprintf (buf, sizeof (buf), "-%03" PRIu32 BBT_BAR_CHAR "%02" PRIu32 BBT_BAR_CHAR "%04" PRIu32,
379                                   bbt.bars, bbt.beats, bbt.ticks);
380                 } else {
381                         snprintf (buf, sizeof (buf), " %03" PRIu32 BBT_BAR_CHAR "%02" PRIu32 BBT_BAR_CHAR "%04" PRIu32,
382                                   bbt.bars, bbt.beats, bbt.ticks);
383                 }
384
385                 bbt_clock_text = buf;
386         }
387
388         bool dirty = false;
389
390         if (tc_clock_text != tc_clock_layout->get_text()) {
391                 dirty = true;
392                 tc_clock_layout->set_text (tc_clock_text);
393         }
394
395         if (bbt_clock_text != tc_clock_layout->get_text()) {
396                 dirty = true;
397                 bbt_clock_layout->set_text (bbt_clock_text);
398         }
399
400         string mid_text;
401
402         for (int n = 0; n < 8; ++n) {
403                 if (stripable[n]) {
404                         mid_text = short_version (stripable[n]->name(), 10);
405                         if (mid_text != mid_layout[n]->get_text()) {
406                                 mid_layout[n]->set_text (mid_text);
407                                 dirty = true;
408                         }
409                 }
410         }
411
412         if (!dirty) {
413                 return false;
414         }
415
416         context->set_source_rgb (0.764, 0.882, 0.882);
417         context->rectangle (0, 0, 960, 160);
418         context->fill ();
419         context->set_source_rgb (0.23, 0.0, 0.349);
420         context->move_to (650, 25);
421         tc_clock_layout->update_from_cairo_context (context);
422         tc_clock_layout->show_in_cairo_context (context);
423         context->move_to (650, 60);
424         bbt_clock_layout->update_from_cairo_context (context);
425         bbt_clock_layout->show_in_cairo_context (context);
426
427         for (int n = 0; n < 8; ++n) {
428                 context->move_to (10 + (n*120), 2);
429                 upper_layout[n]->update_from_cairo_context (context);
430                 upper_layout[n]->show_in_cairo_context (context);
431         }
432
433         for (int n = 0; n < 8; ++n) {
434                 context->move_to (10 + (n*120), 140);
435                 lower_layout[n]->update_from_cairo_context (context);
436                 lower_layout[n]->show_in_cairo_context (context);
437         }
438
439         for (int n = 0; n < 8; ++n) {
440                 if (stripable[n] && stripable[n]->presentation_info().selected()) {
441                         context->rectangle (10 + (n*120) - 5, 115, 120, 22);
442                         context->set_source_rgb (1.0, 0.737, 0.172);
443                         context->fill();
444                 }
445                 context->set_source_rgb (0.0, 0.0, 0.0);
446                 context->move_to (10 + (n*120), 120);
447                 mid_layout[n]->update_from_cairo_context (context);
448                 mid_layout[n]->show_in_cairo_context (context);
449         }
450
451         /* render clock */
452         /* render foo */
453         /* render bar */
454
455         return true;
456 }
457
458 bool
459 Push2::vblank ()
460 {
461         int transferred = 0;
462         const int timeout_msecs = 1000;
463         int err;
464
465         if ((err = libusb_bulk_transfer (handle, 0x01, frame_header, sizeof (frame_header), &transferred, timeout_msecs))) {
466                 return false;
467         }
468
469         if (redraw()) {
470                 /* things changed */
471                 blit_to_device_frame_buffer ();
472         }
473
474         if ((err = libusb_bulk_transfer (handle, 0x01, (uint8_t*) device_frame_buffer , 2 * rows * pixels_per_row, &transferred, timeout_msecs))) {
475                 return false;
476         }
477
478         return true;
479 }
480
481 int
482 Push2::set_active (bool yn)
483 {
484         DEBUG_TRACE (DEBUG::Push2, string_compose("Push2Protocol::set_active init with yn: '%1'\n", yn));
485
486         if (yn == active()) {
487                 return 0;
488         }
489
490         if (yn) {
491
492                 /* start event loop */
493
494                 BaseUI::run ();
495
496                 if (open ()) {
497                         DEBUG_TRACE (DEBUG::Push2, "device open failed\n");
498                         close ();
499                         return -1;
500                 }
501
502                 /* Connect input port to event loop */
503
504                 AsyncMIDIPort* asp;
505
506                 asp = dynamic_cast<AsyncMIDIPort*> (_input_port);
507                 asp->xthread().set_receive_handler (sigc::bind (sigc::mem_fun (this, &Push2::midi_input_handler), _input_port));
508                 asp->xthread().attach (main_loop()->get_context());
509
510                 connect_session_signals ();
511
512                 /* set up periodic task used to push a frame buffer to the
513                  * device (25fps). The device can handle 60fps, but we don't
514                  * need that frame rate.
515                  */
516
517                 Glib::RefPtr<Glib::TimeoutSource> vblank_timeout = Glib::TimeoutSource::create (40); // milliseconds
518                 vblank_connection = vblank_timeout->connect (sigc::mem_fun (*this, &Push2::vblank));
519                 vblank_timeout->attach (main_loop()->get_context());
520
521
522                 Glib::RefPtr<Glib::TimeoutSource> periodic_timeout = Glib::TimeoutSource::create (1000); // milliseconds
523                 periodic_connection = periodic_timeout->connect (sigc::mem_fun (*this, &Push2::periodic));
524                 periodic_timeout->attach (main_loop()->get_context());
525
526                 init_buttons (true);
527                 init_touch_strip ();
528                 switch_bank (0);
529
530         } else {
531
532                 stop ();
533
534         }
535
536         ControlProtocol::set_active (yn);
537
538         DEBUG_TRACE (DEBUG::Push2, string_compose("Push2Protocol::set_active done with yn: '%1'\n", yn));
539
540         return 0;
541 }
542
543 void
544 Push2::init_touch_strip ()
545 {
546         MidiByteArray msg (9, 0xf0, 0x00, 0x21, 0x1d, 0x01, 0x01, 0x17, 0x00, 0xf7);
547         /* flags are the final byte (ignore end-of-sysex */
548
549         /* show bar, not point
550            autoreturn to center
551            bar starts at center
552         */
553         msg[7] = (1<<4) | (1<<5) | (1<<6);
554         write (msg);
555 }
556
557 void
558 Push2::write (const MidiByteArray& data)
559 {
560         /* immediate delivery */
561         _output_port->write (&data[0], data.size(), 0);
562 }
563
564 bool
565 Push2::midi_input_handler (IOCondition ioc, MIDI::Port* port)
566 {
567         if (ioc & ~IO_IN) {
568                 DEBUG_TRACE (DEBUG::Push2, "MIDI port closed\n");
569                 return false;
570         }
571
572         if (ioc & IO_IN) {
573
574                 // DEBUG_TRACE (DEBUG::Push2, string_compose ("something happend on  %1\n", port->name()));
575
576                 AsyncMIDIPort* asp = dynamic_cast<AsyncMIDIPort*>(port);
577                 if (asp) {
578                         asp->clear ();
579                 }
580
581                 //DEBUG_TRACE (DEBUG::Push2, string_compose ("data available on %1\n", port->name()));
582                 framepos_t now = AudioEngine::instance()->sample_time();
583                 port->parse (now);
584         }
585
586         return true;
587 }
588
589 bool
590 Push2::periodic ()
591 {
592         return true;
593 }
594
595 void
596 Push2::connect_to_parser ()
597 {
598         DEBUG_TRACE (DEBUG::Push2, string_compose ("Connecting to signals on port %2\n", _input_port->name()));
599
600         MIDI::Parser* p = _input_port->parser();
601
602         /* Incoming sysex */
603         p->sysex.connect_same_thread (*this, boost::bind (&Push2::handle_midi_sysex, this, _1, _2, _3));
604         /* V-Pot messages are Controller */
605         p->controller.connect_same_thread (*this, boost::bind (&Push2::handle_midi_controller_message, this, _1, _2));
606         /* Button messages are NoteOn */
607         p->note_on.connect_same_thread (*this, boost::bind (&Push2::handle_midi_note_on_message, this, _1, _2));
608         /* Button messages are NoteOn but libmidi++ sends note-on w/velocity = 0 as note-off so catch them too */
609         p->note_off.connect_same_thread (*this, boost::bind (&Push2::handle_midi_note_on_message, this, _1, _2));
610         /* Fader messages are Pitchbend */
611         p->channel_pitchbend[0].connect_same_thread (*this, boost::bind (&Push2::handle_midi_pitchbend_message, this, _1, _2));
612 }
613
614 void
615 Push2::handle_midi_sysex (MIDI::Parser&, MIDI::byte* raw_bytes, size_t sz)
616 {
617         DEBUG_TRACE (DEBUG::Push2, string_compose ("Sysex, %1 bytes\n", sz));
618 }
619
620 void
621 Push2::handle_midi_controller_message (MIDI::Parser&, MIDI::EventTwoBytes* ev)
622 {
623         DEBUG_TRACE (DEBUG::Push2, string_compose ("CC %1 (value %2)\n", (int) ev->controller_number, (int) ev->value));
624
625         CCButtonMap::iterator b = cc_button_map.find (ev->controller_number);
626
627         if (ev->value) {
628                 /* any press cancels any pending long press timeouts */
629                 for (set<ButtonID>::iterator x = buttons_down.begin(); x != buttons_down.end(); ++x) {
630                         Button* bb = id_button_map[*x];
631                         bb->timeout_connection.disconnect ();
632                 }
633         }
634
635         if (b != cc_button_map.end()) {
636
637                 Button* button = b->second;
638
639                 if (ev->value) {
640                         buttons_down.insert (button->id);
641                         start_press_timeout (*button, button->id);
642                 } else {
643                         buttons_down.erase (button->id);
644                         button->timeout_connection.disconnect ();
645                 }
646
647
648                 set<ButtonID>::iterator c = consumed.find (button->id);
649
650                 if (c == consumed.end()) {
651                         if (ev->value == 0) {
652                                 (this->*button->release_method)();
653                         } else {
654                                 (this->*button->press_method)();
655                         }
656                 } else {
657                         DEBUG_TRACE (DEBUG::Push2, "button was consumed, ignored\n");
658                         consumed.erase (c);
659                 }
660
661         } else {
662
663                 /* encoder/vpot */
664
665                 int delta = ev->value;
666
667                 if (delta > 63) {
668                         delta = -(128 - delta);
669                 }
670
671                 switch (ev->controller_number) {
672                 case 71:
673                         strip_vpot (0, delta);
674                         break;
675                 case 72:
676                         strip_vpot (1, delta);
677                         break;
678                 case 73:
679                         strip_vpot (2, delta);
680                         break;
681                 case 74:
682                         strip_vpot (3, delta);
683                         break;
684                 case 75:
685                         strip_vpot (4, delta);
686                         break;
687                 case 76:
688                         strip_vpot (5, delta);
689                         break;
690                 case 77:
691                         strip_vpot (6, delta);
692                         break;
693                 case 78:
694                         strip_vpot (7, delta);
695                         break;
696
697                         /* left side pair */
698                 case 14:
699                         strip_vpot (8, delta);
700                         break;
701                 case 15:
702                         other_vpot (1, delta);
703                         break;
704
705                         /* right side */
706                 case 79:
707                         other_vpot (2, delta);
708                         break;
709                 }
710         }
711 }
712
713 void
714 Push2::handle_midi_note_on_message (MIDI::Parser&, MIDI::EventTwoBytes* ev)
715 {
716         DEBUG_TRACE (DEBUG::Push2, string_compose ("Note On %1 (velocity %2)\n", (int) ev->note_number, (int) ev->velocity));
717
718         switch (ev->note_number) {
719         case 0:
720                 strip_vpot_touch (0, ev->velocity > 64);
721                 break;
722         case 1:
723                 strip_vpot_touch (1, ev->velocity > 64);
724                 break;
725         case 2:
726                 strip_vpot_touch (2, ev->velocity > 64);
727                 break;
728         case 3:
729                 strip_vpot_touch (3, ev->velocity > 64);
730                 break;
731         case 4:
732                 strip_vpot_touch (4, ev->velocity > 64);
733                 break;
734         case 5:
735                 strip_vpot_touch (5, ev->velocity > 64);
736                 break;
737         case 6:
738                 strip_vpot_touch (6, ev->velocity > 64);
739                 break;
740         case 7:
741                 strip_vpot_touch (7, ev->velocity > 64);
742                 break;
743
744                 /* left side */
745         case 10:
746                 other_vpot_touch (0, ev->velocity > 64);
747                 break;
748         case 9:
749                 other_vpot_touch (1, ev->velocity > 64);
750                 break;
751
752                 /* right side */
753         case 8:
754                 other_vpot_touch (3, ev->velocity > 64);
755                 break;
756
757                 /* touch strip */
758         case 12:
759                 if (ev->velocity < 64) {
760                         transport_stop ();
761                 }
762                 break;
763         }
764 }
765
766 void
767 Push2::handle_midi_note_off_message (MIDI::Parser&, MIDI::EventTwoBytes* ev)
768 {
769         DEBUG_TRACE (DEBUG::Push2, string_compose ("Note Off %1 (velocity %2)\n", (int) ev->note_number, (int) ev->velocity));
770 }
771
772 void
773 Push2::handle_midi_pitchbend_message (MIDI::Parser&, MIDI::pitchbend_t pb)
774 {
775         if (!session) {
776                 return;
777         }
778
779         float speed;
780
781         /* range of +1 .. -1 */
782         speed = ((int32_t) pb - 8192) / 8192.0;
783         /* convert to range of +3 .. -3 */
784         session->request_transport_speed (speed * 3.0);
785 }
786
787 void
788 Push2::thread_init ()
789 {
790         struct sched_param rtparam;
791
792         pthread_set_name (event_loop_name().c_str());
793
794         PBD::notify_event_loops_about_thread_creation (pthread_self(), event_loop_name(), 2048);
795         ARDOUR::SessionEvent::create_per_thread_pool (event_loop_name(), 128);
796
797         memset (&rtparam, 0, sizeof (rtparam));
798         rtparam.sched_priority = 9; /* XXX should be relative to audio (JACK) thread */
799
800         if (pthread_setschedparam (pthread_self(), SCHED_FIFO, &rtparam) != 0) {
801                 // do we care? not particularly.
802         }
803 }
804
805 void
806 Push2::connect_session_signals()
807 {
808         // receive routes added
809         //session->RouteAdded.connect(session_connections, MISSING_INVALIDATOR, boost::bind (&MackieControlProtocol::notify_routes_added, this, _1), this);
810         // receive VCAs added
811         //session->vca_manager().VCAAdded.connect(session_connections, MISSING_INVALIDATOR, boost::bind (&Push2::notify_vca_added, this, _1), this);
812
813         // receive record state toggled
814         session->RecordStateChanged.connect(session_connections, MISSING_INVALIDATOR, boost::bind (&Push2::notify_record_state_changed, this), this);
815         // receive transport state changed
816         session->TransportStateChange.connect(session_connections, MISSING_INVALIDATOR, boost::bind (&Push2::notify_transport_state_changed, this), this);
817         session->TransportLooped.connect (session_connections, MISSING_INVALIDATOR, boost::bind (&Push2::notify_loop_state_changed, this), this);
818         // receive punch-in and punch-out
819         Config->ParameterChanged.connect(session_connections, MISSING_INVALIDATOR, boost::bind (&Push2::notify_parameter_changed, this, _1), this);
820         session->config.ParameterChanged.connect (session_connections, MISSING_INVALIDATOR, boost::bind (&Push2::notify_parameter_changed, this, _1), this);
821         // receive rude solo changed
822         session->SoloActive.connect(session_connections, MISSING_INVALIDATOR, boost::bind (&Push2::notify_solo_active_changed, this, _1), this);
823 }
824
825 void
826 Push2::notify_record_state_changed ()
827 {
828         IDButtonMap::iterator b = id_button_map.find (RecordEnable);
829
830         if (b == id_button_map.end()) {
831                 return;
832         }
833
834         switch (session->record_status ()) {
835         case Session::Disabled:
836                 b->second->set_color (LED::White);
837                 b->second->set_state (LED::NoTransition);
838                 break;
839         case Session::Enabled:
840                 b->second->set_color (LED::Red);
841                 b->second->set_state (LED::Blinking4th);
842                 break;
843         case Session::Recording:
844                 b->second->set_color (LED::Red);
845                 b->second->set_state (LED::OneShot24th);
846                 break;
847         }
848
849         write (b->second->state_msg());
850 }
851
852 void
853 Push2::notify_transport_state_changed ()
854 {
855         Button* b = id_button_map[Play];
856
857         if (session->transport_rolling()) {
858                 b->set_state (LED::OneShot24th);
859                 b->set_color (LED::Green);
860         } else {
861
862                 /* disable any blink on FixedLength from pending edit range op */
863                 Button* fl = id_button_map[FixedLength];
864
865                 fl->set_color (LED::Black);
866                 fl->set_state (LED::NoTransition);
867                 write (fl->state_msg());
868
869                 b->set_color (LED::White);
870                 b->set_state (LED::NoTransition);
871         }
872
873         write (b->state_msg());
874 }
875
876 void
877 Push2::notify_loop_state_changed ()
878 {
879 }
880
881 void
882 Push2::notify_parameter_changed (std::string param)
883 {
884         IDButtonMap::iterator b;
885
886         if (param == "clicking") {
887                 if ((b = id_button_map.find (Metronome)) == id_button_map.end()) {
888                         return;
889                 }
890                 if (Config->get_clicking()) {
891                         b->second->set_state (LED::Blinking4th);
892                         b->second->set_color (LED::White);
893                 } else {
894                         b->second->set_color (LED::White);
895                         b->second->set_state (LED::NoTransition);
896                 }
897                 write (b->second->state_msg ());
898         }
899 }
900
901 void
902 Push2::notify_solo_active_changed (bool yn)
903 {
904         IDButtonMap::iterator b = id_button_map.find (Solo);
905
906         if (b == id_button_map.end()) {
907                 return;
908         }
909
910         if (yn) {
911                 b->second->set_state (LED::Blinking4th);
912                 b->second->set_color (LED::Red);
913         } else {
914                 b->second->set_state (LED::NoTransition);
915                 b->second->set_color (LED::White);
916         }
917
918         write (b->second->state_msg());
919 }
920
921 XMLNode&
922 Push2::get_state()
923 {
924         XMLNode& node (ControlProtocol::get_state());
925         XMLNode* child;
926
927         child = new XMLNode (X_("Input"));
928         child->add_child_nocopy (_async_in->get_state());
929         node.add_child_nocopy (*child);
930         child = new XMLNode (X_("Output"));
931         child->add_child_nocopy (_async_out->get_state());
932         node.add_child_nocopy (*child);
933
934         return node;
935 }
936
937 int
938 Push2::set_state (const XMLNode & node, int version)
939 {
940         DEBUG_TRACE (DEBUG::Push2, string_compose ("Push2::set_state: active %1\n", active()));
941
942         int retval = 0;
943
944         if (ControlProtocol::set_state (node, version)) {
945                 return -1;
946         }
947
948         XMLNode* child;
949
950         if ((child = node.child (X_("Input"))) != 0) {
951                 XMLNode* portnode = child->child (Port::state_node_name.c_str());
952                 if (portnode) {
953                         _async_in->set_state (*portnode, version);
954                 }
955         }
956
957         if ((child = node.child (X_("Output"))) != 0) {
958                 XMLNode* portnode = child->child (Port::state_node_name.c_str());
959                 if (portnode) {
960                         _async_out->set_state (*portnode, version);
961                 }
962         }
963
964         return retval;
965 }
966
967 void
968 Push2::switch_bank (uint32_t base)
969 {
970         if (!session) {
971                 return;
972         }
973
974         stripable_connections.drop_connections ();
975
976         /* try to get the first stripable for the requested bank */
977
978         stripable[0] = session->get_remote_nth_stripable (base, PresentationInfo::Flag (PresentationInfo::Route|PresentationInfo::VCA));
979
980         if (!stripable[0]) {
981                 return;
982         }
983
984         /* at least one stripable in this bank */
985         bank_start = base;
986
987         stripable[1] = session->get_remote_nth_stripable (base+1, PresentationInfo::Flag (PresentationInfo::Route|PresentationInfo::VCA));
988         stripable[2] = session->get_remote_nth_stripable (base+2, PresentationInfo::Flag (PresentationInfo::Route|PresentationInfo::VCA));
989         stripable[3] = session->get_remote_nth_stripable (base+3, PresentationInfo::Flag (PresentationInfo::Route|PresentationInfo::VCA));
990         stripable[4] = session->get_remote_nth_stripable (base+4, PresentationInfo::Flag (PresentationInfo::Route|PresentationInfo::VCA));
991         stripable[5] = session->get_remote_nth_stripable (base+5, PresentationInfo::Flag (PresentationInfo::Route|PresentationInfo::VCA));
992         stripable[6] = session->get_remote_nth_stripable (base+6, PresentationInfo::Flag (PresentationInfo::Route|PresentationInfo::VCA));
993         stripable[7] = session->get_remote_nth_stripable (base+7, PresentationInfo::Flag (PresentationInfo::Route|PresentationInfo::VCA));
994
995
996         for (int n = 0; n < 8; ++n) {
997                 if (!stripable[n]) {
998                         continue;
999                 }
1000
1001                 /* stripable goes away? refill the bank, starting at the same point */
1002
1003                 stripable[n]->DropReferences.connect (stripable_connections, MISSING_INVALIDATOR, boost::bind (&Push2::switch_bank, this, bank_start), this);
1004                 boost::shared_ptr<AutomationControl> sc = stripable[n]->solo_control();
1005                 if (sc) {
1006                         sc->Changed.connect (stripable_connections, MISSING_INVALIDATOR, boost::bind (&Push2::solo_change, this, n), this);
1007                 }
1008
1009                 boost::shared_ptr<AutomationControl> mc = stripable[n]->mute_control();
1010                 if (mc) {
1011                         mc->Changed.connect (stripable_connections, MISSING_INVALIDATOR, boost::bind (&Push2::mute_change, this, n), this);
1012                 }
1013
1014                 stripable[n]->presentation_info().PropertyChanged.connect (stripable_connections, MISSING_INVALIDATOR, boost::bind (&Push2::stripable_property_change, this, _1, n), this);
1015
1016                 solo_change (n);
1017                 mute_change (n);
1018
1019         }
1020
1021         /* master cannot be removed, so no need to connect to going-away signal */
1022         master = session->master_out ();
1023 }
1024
1025 void
1026 Push2::stripable_property_change (PropertyChange const& what_changed, int which)
1027 {
1028         if (what_changed.contains (Properties::selected)) {
1029                 /* cancel string, which will cause a redraw on the next update
1030                  * cycle. The redraw will reflect selected status
1031                  */
1032                 mid_layout[which]->set_text (string());
1033         }
1034 }
1035
1036 void
1037 Push2::solo_change (int n)
1038 {
1039         ButtonID bid;
1040
1041         switch (n) {
1042         case 0:
1043                 bid = Upper1;
1044                 break;
1045         case 1:
1046                 bid = Upper2;
1047                 break;
1048         case 2:
1049                 bid = Upper3;
1050                 break;
1051         case 3:
1052                 bid = Upper4;
1053                 break;
1054         case 4:
1055                 bid = Upper5;
1056                 break;
1057         case 5:
1058                 bid = Upper6;
1059                 break;
1060         case 6:
1061                 bid = Upper7;
1062                 break;
1063         case 7:
1064                 bid = Upper8;
1065                 break;
1066         default:
1067                 return;
1068         }
1069
1070         boost::shared_ptr<AutomationControl> ac = stripable[n]->solo_control ();
1071         if (!ac) {
1072                 return;
1073         }
1074
1075         Button* b = id_button_map[bid];
1076         if (ac->get_value()) {
1077                 b->set_color (LED::Red);
1078         } else {
1079                 b->set_color (LED::Black);
1080         }
1081         b->set_state (LED::OneShot24th);
1082         write (b->state_msg());
1083 }
1084
1085 void
1086 Push2::mute_change (int n)
1087 {
1088         ButtonID bid;
1089
1090         switch (n) {
1091         case 0:
1092                 bid = Lower1;
1093                 break;
1094         case 1:
1095                 bid = Lower2;
1096                 break;
1097         case 2:
1098                 bid = Lower3;
1099                 break;
1100         case 3:
1101                 bid = Lower4;
1102                 break;
1103         case 4:
1104                 bid = Lower5;
1105                 break;
1106         case 5:
1107                 bid = Lower6;
1108                 break;
1109         case 6:
1110                 bid = Lower7;
1111                 break;
1112         case 7:
1113                 bid = Lower8;
1114                 break;
1115         default:
1116                 return;
1117         }
1118
1119         boost::shared_ptr<AutomationControl> ac = stripable[n]->mute_control ();
1120         if (!ac) {
1121                 return;
1122         }
1123
1124         Button* b = id_button_map[bid];
1125
1126         if (ac->get_value ()) {
1127                 b->set_color (LED::Blue);
1128         } else {
1129                 b->set_color (LED::Black);
1130         }
1131         b->set_state (LED::OneShot24th);
1132         write (b->state_msg());
1133 }
1134
1135 void
1136 Push2::strip_vpot (int n, int delta)
1137 {
1138         if (stripable[n]) {
1139                 boost::shared_ptr<AutomationControl> ac = stripable[n]->gain_control();
1140                 if (ac) {
1141                         ac->set_value (ac->get_value() + ((2.0/64.0) * delta), PBD::Controllable::UseGroup);
1142                 }
1143         }
1144 }
1145
1146 void
1147 Push2::strip_vpot_touch (int n, bool touching)
1148 {
1149         if (stripable[n]) {
1150                 boost::shared_ptr<AutomationControl> ac = stripable[n]->gain_control();
1151                 if (ac) {
1152                         if (touching) {
1153                                 ac->start_touch (session->audible_frame());
1154                         } else {
1155                                 ac->stop_touch (true, session->audible_frame());
1156                         }
1157                 }
1158         }
1159 }
1160
1161 void
1162 Push2::other_vpot (int n, int delta)
1163 {
1164         switch (n) {
1165         case 0:
1166                 break;
1167         case 1:
1168                 break;
1169         case 2:
1170                 /* master gain control */
1171                 if (master) {
1172                         boost::shared_ptr<AutomationControl> ac = master->gain_control();
1173                         if (ac) {
1174                                 ac->set_value (ac->get_value() + ((2.0/64.0) * delta), PBD::Controllable::UseGroup);
1175                         }
1176                 }
1177                 break;
1178         }
1179 }
1180
1181 void
1182 Push2::other_vpot_touch (int n, bool touching)
1183 {
1184         switch (n) {
1185         case 0:
1186                 break;
1187         case 1:
1188                 break;
1189         case 2:
1190                 if (master) {
1191                         boost::shared_ptr<AutomationControl> ac = master->gain_control();
1192                         if (ac) {
1193                                 if (touching) {
1194                                         ac->start_touch (session->audible_frame());
1195                                 } else {
1196                                         ac->stop_touch (true, session->audible_frame());
1197                                 }
1198                         }
1199                 }
1200         }
1201 }
1202
1203 void
1204 Push2::start_shift ()
1205 {
1206         cerr << "start shift\n";
1207         modifier_state = ModifierState (modifier_state | ModShift);
1208         Button* b = id_button_map[Shift];
1209         b->set_color (LED::White);
1210         b->set_state (LED::Blinking16th);
1211         write (b->state_msg());
1212 }
1213
1214 void
1215 Push2::end_shift ()
1216 {
1217         if (modifier_state & ModShift) {
1218                 cerr << "end shift\n";
1219                 modifier_state = ModifierState (modifier_state & ~(ModShift));
1220                 Button* b = id_button_map[Shift];
1221                 b->timeout_connection.disconnect ();
1222                 b->set_color (LED::White);
1223                 b->set_state (LED::OneShot24th);
1224                 write (b->state_msg());
1225         }
1226 }
1227
1228 void
1229 Push2::start_select ()
1230 {
1231         cerr << "start select\n";
1232         modifier_state = ModifierState (modifier_state | ModSelect);
1233         Button* b = id_button_map[Select];
1234         b->set_color (LED::White);
1235         b->set_state (LED::Blinking16th);
1236         write (b->state_msg());
1237 }
1238
1239 void
1240 Push2::end_select ()
1241 {
1242         if (modifier_state & ModSelect) {
1243                 cerr << "end select\n";
1244                 modifier_state = ModifierState (modifier_state & ~(ModSelect));
1245                 Button* b = id_button_map[Select];
1246                 b->timeout_connection.disconnect ();
1247                 b->set_color (LED::White);
1248                 b->set_state (LED::OneShot24th);
1249                 write (b->state_msg());
1250         }
1251 }