add shift modifier support
[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/debug.h"
25 #include "pbd/failed_constructor.h"
26
27 #include "midi++/parser.h"
28 #include "timecode/time.h"
29 #include "timecode/bbt_time.h"
30
31 #include "ardour/async_midi_port.h"
32 #include "ardour/audioengine.h"
33 #include "ardour/debug.h"
34 #include "ardour/midiport_manager.h"
35 #include "ardour/session.h"
36 #include "ardour/tempo.h"
37
38 #include "push2.h"
39
40 using namespace ARDOUR;
41 using namespace std;
42 using namespace PBD;
43 using namespace Glib;
44 using namespace ArdourSurface;
45
46 #include "i18n.h"
47
48 #include "pbd/abstract_ui.cc" // instantiate template
49
50 const int Push2::cols = 960;
51 const int Push2::rows = 160;
52 const int Push2::pixels_per_row = 1024;
53
54 #define ABLETON 0x2982
55 #define PUSH2   0x1967
56
57 Push2::Push2 (ARDOUR::Session& s)
58         : ControlProtocol (s, string (X_("Ableton Push 2")))
59         , AbstractUI<Push2Request> (name())
60         , handle (0)
61         , device_buffer (0)
62         , frame_buffer (Cairo::ImageSurface::create (Cairo::FORMAT_ARGB32, cols, rows))
63         , modifier_state (None)
64 {
65         context = Cairo::Context::create (frame_buffer);
66         tc_clock_layout = Pango::Layout::create (context);
67         bbt_clock_layout = Pango::Layout::create (context);
68
69         Pango::FontDescription fd ("Sans Bold 24");
70         tc_clock_layout->set_font_description (fd);
71         bbt_clock_layout->set_font_description (fd);
72
73         Pango::FontDescription fd2 ("Sans Bold 10");
74         for (int n = 0; n < 8; ++n) {
75                 upper_layout[n] = Pango::Layout::create (context);
76                 upper_layout[n]->set_font_description (fd2);
77                 upper_layout[n]->set_text ("solo");
78                 lower_layout[n] = Pango::Layout::create (context);
79                 lower_layout[n]->set_font_description (fd2);
80                 lower_layout[n]->set_text ("mute");
81                 mid_layout[n] = Pango::Layout::create (context);
82                 mid_layout[n]->set_font_description (fd2);
83                 mid_layout[n]->set_text (string_compose ("Inst %1", n));
84         }
85
86         build_maps ();
87
88         if (open ()) {
89                 throw failed_constructor ();
90         }
91
92 }
93
94 Push2::~Push2 ()
95 {
96         close ();
97 }
98
99 int
100 Push2::open ()
101 {
102         int err;
103
104         if (handle) {
105                 /* already open */
106                 return 0;
107         }
108
109         if ((handle = libusb_open_device_with_vid_pid (NULL, ABLETON, PUSH2)) == 0) {
110                 return -1;
111         }
112
113         if ((err = libusb_claim_interface (handle, 0x00))) {
114                 return -1;
115         }
116
117         device_frame_buffer = new uint16_t[rows*pixels_per_row];
118
119         memset (device_frame_buffer, 0, sizeof (uint16_t) * rows * pixels_per_row);
120
121         frame_header[0] = 0xef;
122         frame_header[1] = 0xcd;
123         frame_header[2] = 0xab;
124         frame_header[3] = 0x89;
125         memset (&frame_header[4], 0, 12);
126
127         /* setup ports */
128
129         _async_in  = AudioEngine::instance()->register_input_port (DataType::MIDI, X_("push2 in"), true);
130         _async_out = AudioEngine::instance()->register_output_port (DataType::MIDI, X_("push2 out"), true);
131
132         if (_async_in == 0 || _async_out == 0) {
133                 return -1;
134         }
135
136         _input_port = boost::dynamic_pointer_cast<AsyncMIDIPort>(_async_in).get();
137         _output_port = boost::dynamic_pointer_cast<AsyncMIDIPort>(_async_out).get();
138
139         connect_to_parser ();
140
141         return 0;
142 }
143
144 int
145 Push2::close ()
146 {
147         AudioEngine::instance()->unregister_port (_async_in);
148         AudioEngine::instance()->unregister_port (_async_out);
149
150         _async_in.reset ((ARDOUR::Port*) 0);
151         _async_out.reset ((ARDOUR::Port*) 0);
152         _input_port = 0;
153         _output_port = 0;
154
155         vblank_connection.disconnect ();
156         periodic_connection.disconnect ();
157         session_connections.drop_connections ();
158
159         if (handle) {
160                 libusb_release_interface (handle, 0x00);
161                 libusb_close (handle);
162                 handle = 0;
163         }
164
165         delete [] device_frame_buffer;
166         device_frame_buffer = 0;
167
168         return 0;
169 }
170
171 void
172 Push2::init_buttons ()
173 {
174         ButtonID buttons[] = { Mute, Solo, Master, Up, Right, Left, Down, Note, Session, Mix, AddTrack, Delete, Undo,
175                                Metronome, Shift, Select, Play, RecordEnable, Automate, Repeat, Note, Session, DoubleLoop,
176                                Quantize, Duplicate,
177         };
178
179         for (size_t n = 0; n < sizeof (buttons) / sizeof (buttons[0]); ++n) {
180                 Button* b = id_button_map[buttons[n]];
181
182                 b->set_color (LED::White);
183                 b->set_state (LED::OneShot24th);
184                 write (b->state_msg());
185         }
186 }
187
188 bool
189 Push2::probe ()
190 {
191         libusb_device_handle *h;
192         libusb_init (NULL);
193
194         if ((h = libusb_open_device_with_vid_pid (NULL, ABLETON, PUSH2)) == 0) {
195                 DEBUG_TRACE (DEBUG::Push2, "no Push2 device found\n");
196                 return false;
197         }
198
199         libusb_close (h);
200         DEBUG_TRACE (DEBUG::Push2, "Push2 device located\n");
201         return true;
202 }
203
204 void*
205 Push2::request_factory (uint32_t num_requests)
206 {
207         /* AbstractUI<T>::request_buffer_factory() is a template method only
208            instantiated in this source module. To provide something visible for
209            use in the interface/descriptor, we have this static method that is
210            template-free.
211         */
212         return request_buffer_factory (num_requests);
213 }
214
215 void
216 Push2::do_request (Push2Request * req)
217 {
218         DEBUG_TRACE (DEBUG::Push2, string_compose ("doing request type %1\n", req->type));
219         if (req->type == CallSlot) {
220
221                 call_slot (MISSING_INVALIDATOR, req->the_slot);
222
223         } else if (req->type == Quit) {
224
225                 stop ();
226         }
227 }
228
229 int
230 Push2::stop ()
231 {
232         BaseUI::quit ();
233         close ();
234         return 0;
235 }
236
237 /** render host-side frame buffer (a Cairo ImageSurface) to the current
238  * device-side frame buffer. The device frame buffer will be pushed to the
239  * device on the next call to vblank()
240  */
241
242 int
243 Push2::bitblt_to_device_frame_buffer ()
244 {
245         /* ensure that all drawing has been done before we fetch pixel data */
246
247         frame_buffer->flush ();
248
249         const int stride = 3840; /* bytes per row for Cairo::FORMAT_ARGB32 */
250         const uint8_t* data = frame_buffer->get_data ();
251
252         /* fill frame buffer (320kB) */
253
254         uint16_t* fb = (uint16_t*) device_frame_buffer;
255
256         for (int row = 0; row < rows; ++row) {
257
258                 const uint8_t* dp = data + row * stride;
259
260                 for (int col = 0; col < cols; ++col) {
261
262                         /* fetch r, g, b (range 0..255). Ignore alpha */
263
264                         const int r = (*((const uint32_t*)dp) >> 16) & 0xff;
265                         const int g = (*((const uint32_t*)dp) >> 8) & 0xff;
266                         const int b = *((const uint32_t*)dp) & 0xff;
267
268                         /* convert to 5 bits, 6 bits, 5 bits, respectively */
269                         /* generate 16 bit BGB565 value */
270
271                         *fb++ = (r >> 3) | ((g & 0xfc) << 3) | ((b & 0xf8) << 8);
272
273                         dp += 4;
274                 }
275
276                 /* skip 128 bytes to next line. This is filler, used to avoid line borders occuring in the middle of 512
277                    byte USB buffers
278                 */
279
280                 fb += 64; /* 128 bytes = 64 int16_t */
281         }
282
283         return 0;
284 }
285
286 bool
287 Push2::redraw ()
288 {
289         string tc_clock_text;
290         string bbt_clock_text;
291
292         if (session) {
293                 framepos_t audible = session->audible_frame();
294                 Timecode::Time TC;
295                 bool negative = false;
296
297                 if (audible < 0) {
298                         audible = -audible;
299                         negative = true;
300                 }
301
302                 session->timecode_time (audible, TC);
303
304                 TC.negative = TC.negative || negative;
305
306                 tc_clock_text = Timecode::timecode_format_time(TC);
307
308                 Timecode::BBT_Time bbt = session->tempo_map().bbt_at_frame (audible);
309                 char buf[16];
310
311 #define BBT_BAR_CHAR "|"
312
313                 if (negative) {
314                         snprintf (buf, sizeof (buf), "-%03" PRIu32 BBT_BAR_CHAR "%02" PRIu32 BBT_BAR_CHAR "%04" PRIu32,
315                                   bbt.bars, bbt.beats, bbt.ticks);
316                 } else {
317                         snprintf (buf, sizeof (buf), " %03" PRIu32 BBT_BAR_CHAR "%02" PRIu32 BBT_BAR_CHAR "%04" PRIu32,
318                                   bbt.bars, bbt.beats, bbt.ticks);
319                 }
320
321                 bbt_clock_text = buf;
322         }
323
324         bool dirty = false;
325
326         if (tc_clock_text != tc_clock_layout->get_text()) {
327                 dirty = true;
328                 tc_clock_layout->set_text (tc_clock_text);
329         }
330
331         if (bbt_clock_text != tc_clock_layout->get_text()) {
332                 dirty = true;
333                 bbt_clock_layout->set_text (bbt_clock_text);
334         }
335
336         if (!dirty) {
337                 return false;
338         }
339
340         context->set_source_rgb (0.764, 0.882, 0.882);
341         context->rectangle (0, 0, 960, 160);
342         context->fill ();
343         context->set_source_rgb (0.23, 0.0, 0.349);
344         context->move_to (650, 25);
345         tc_clock_layout->update_from_cairo_context (context);
346         tc_clock_layout->show_in_cairo_context (context);
347         context->move_to (650, 60);
348         bbt_clock_layout->update_from_cairo_context (context);
349         bbt_clock_layout->show_in_cairo_context (context);
350
351         for (int n = 0; n < 8; ++n) {
352                 context->move_to (10 + (n*120), 2);
353                 upper_layout[n]->update_from_cairo_context (context);
354                 upper_layout[n]->show_in_cairo_context (context);
355         }
356
357         for (int n = 0; n < 8; ++n) {
358                 context->move_to (10 + (n*120), 140);
359                 lower_layout[n]->update_from_cairo_context (context);
360                 lower_layout[n]->show_in_cairo_context (context);
361         }
362
363         for (int n = 0; n < 8; ++n) {
364                 context->move_to (10 + (n*120), 120);
365                 context->set_source_rgb (0.0, 0.0, 0.0);
366                 mid_layout[n]->update_from_cairo_context (context);
367                 mid_layout[n]->show_in_cairo_context (context);
368         }
369
370         /* render clock */
371         /* render foo */
372         /* render bar */
373
374         return true;
375 }
376
377 bool
378 Push2::vblank ()
379 {
380         int transferred = 0;
381         const int timeout_msecs = 1000;
382         int err;
383
384         if ((err = libusb_bulk_transfer (handle, 0x01, frame_header, sizeof (frame_header), &transferred, timeout_msecs))) {
385                 return false;
386         }
387
388         if (redraw()) {
389                 /* things changed */
390                 bitblt_to_device_frame_buffer ();
391         }
392
393         if ((err = libusb_bulk_transfer (handle, 0x01, (uint8_t*) device_frame_buffer , 2 * rows * pixels_per_row, &transferred, timeout_msecs))) {
394                 return false;
395         }
396
397         return true;
398 }
399
400 int
401 Push2::set_active (bool yn)
402 {
403         DEBUG_TRACE (DEBUG::Push2, string_compose("Push2Protocol::set_active init with yn: '%1'\n", yn));
404
405         if (yn == active()) {
406                 return 0;
407         }
408
409         if (yn) {
410
411                 /* start event loop */
412
413                 BaseUI::run ();
414
415                 if (open ()) {
416                         DEBUG_TRACE (DEBUG::Push2, "device open failed\n");
417                         close ();
418                         return -1;
419                 }
420
421                 /* Connect input port to event loop */
422
423                 AsyncMIDIPort* asp;
424
425                 asp = dynamic_cast<AsyncMIDIPort*> (_input_port);
426                 asp->xthread().set_receive_handler (sigc::bind (sigc::mem_fun (this, &Push2::midi_input_handler), _input_port));
427                 asp->xthread().attach (main_loop()->get_context());
428
429                 connect_session_signals ();
430
431                 /* set up periodic task used to push a frame buffer to the
432                  * device (25fps). The device can handle 60fps, but we don't
433                  * need that frame rate.
434                  */
435
436                 Glib::RefPtr<Glib::TimeoutSource> vblank_timeout = Glib::TimeoutSource::create (40); // milliseconds
437                 vblank_connection = vblank_timeout->connect (sigc::mem_fun (*this, &Push2::vblank));
438                 vblank_timeout->attach (main_loop()->get_context());
439
440
441                 Glib::RefPtr<Glib::TimeoutSource> periodic_timeout = Glib::TimeoutSource::create (1000); // milliseconds
442                 periodic_connection = periodic_timeout->connect (sigc::mem_fun (*this, &Push2::periodic));
443                 periodic_timeout->attach (main_loop()->get_context());
444
445                 init_buttons ();
446
447         } else {
448
449                 stop ();
450
451         }
452
453         ControlProtocol::set_active (yn);
454
455         DEBUG_TRACE (DEBUG::Push2, string_compose("Push2Protocol::set_active done with yn: '%1'\n", yn));
456
457         return 0;
458 }
459
460 void
461 Push2::write (const MidiByteArray& data)
462 {
463         cerr << data << endl;
464         /* immediate delivery */
465         _output_port->write (&data[0], data.size(), 0);
466 }
467
468 bool
469 Push2::midi_input_handler (IOCondition ioc, MIDI::Port* port)
470 {
471         if (ioc & ~IO_IN) {
472                 DEBUG_TRACE (DEBUG::Push2, "MIDI port closed\n");
473                 return false;
474         }
475
476         if (ioc & IO_IN) {
477
478                 // DEBUG_TRACE (DEBUG::Push2, string_compose ("something happend on  %1\n", port->name()));
479
480                 AsyncMIDIPort* asp = dynamic_cast<AsyncMIDIPort*>(port);
481                 if (asp) {
482                         asp->clear ();
483                 }
484
485                 //DEBUG_TRACE (DEBUG::Push2, string_compose ("data available on %1\n", port->name()));
486                 framepos_t now = AudioEngine::instance()->sample_time();
487                 port->parse (now);
488         }
489
490         return true;
491 }
492
493 bool
494 Push2::periodic ()
495 {
496         return true;
497 }
498
499 void
500 Push2::connect_to_parser ()
501 {
502         DEBUG_TRACE (DEBUG::Push2, string_compose ("Connecting to signals on port %2\n", _input_port->name()));
503
504         MIDI::Parser* p = _input_port->parser();
505
506         /* Incoming sysex */
507         p->sysex.connect_same_thread (*this, boost::bind (&Push2::handle_midi_sysex, this, _1, _2, _3));
508         /* V-Pot messages are Controller */
509         p->controller.connect_same_thread (*this, boost::bind (&Push2::handle_midi_controller_message, this, _1, _2));
510         /* Button messages are NoteOn */
511         p->note_on.connect_same_thread (*this, boost::bind (&Push2::handle_midi_note_on_message, this, _1, _2));
512         /* Button messages are NoteOn but libmidi++ sends note-on w/velocity = 0 as note-off so catch them too */
513         p->note_off.connect_same_thread (*this, boost::bind (&Push2::handle_midi_note_on_message, this, _1, _2));
514         /* Fader messages are Pitchbend */
515         p->channel_pitchbend[0].connect_same_thread (*this, boost::bind (&Push2::handle_midi_pitchbend_message, this, _1, _2));
516 }
517
518 void
519 Push2::handle_midi_sysex (MIDI::Parser&, MIDI::byte* raw_bytes, size_t sz)
520 {
521         cerr << "sysex, " << sz << " bytes\n";
522 }
523
524 void
525 Push2::handle_midi_controller_message (MIDI::Parser&, MIDI::EventTwoBytes* ev)
526 {
527         CCButtonMap::iterator b = cc_button_map.find (ev->controller_number);
528         if (b != cc_button_map.end()) {
529                 if (ev->value == 0) {
530                         (this->*b->second->release_method)();
531                 } else {
532                         (this->*b->second->press_method)();
533                 }
534         }
535 }
536
537 void
538 Push2::handle_midi_note_on_message (MIDI::Parser&, MIDI::EventTwoBytes* ev)
539 {
540         cerr << "note on" << (int) ev->note_number << ", velocity " << (int) ev->velocity << endl;
541 }
542
543 void
544 Push2::handle_midi_note_off_message (MIDI::Parser&, MIDI::EventTwoBytes* ev)
545 {
546         cerr << "note on" << (int) ev->note_number << ", velocity " << (int) ev->velocity << endl;
547 }
548
549 void
550 Push2::handle_midi_pitchbend_message (MIDI::Parser&, MIDI::pitchbend_t pb)
551 {
552         cerr << "pitchbend @ " << pb << endl;
553 }
554
555 void
556 Push2::build_maps ()
557 {
558         /* Pads */
559
560         Pad* pad;
561
562 #define MAKE_PAD(x,y,nn) \
563         pad = new Pad ((x), (y), (nn)); \
564         nn_pad_map.insert (make_pair (pad->extra(), pad)); \
565         coord_pad_map.insert (make_pair (pad->coord(), pad));
566
567         MAKE_PAD (0, 1, 93);
568         MAKE_PAD (0, 2, 94);
569         MAKE_PAD (0, 3, 95);
570         MAKE_PAD (0, 4, 96);
571         MAKE_PAD (0, 5, 97);
572         MAKE_PAD (0, 6, 98);
573         MAKE_PAD (0, 7, 90);
574         MAKE_PAD (1, 0, 84);
575         MAKE_PAD (1, 1, 85);
576         MAKE_PAD (1, 2, 86);
577         MAKE_PAD (1, 3, 87);
578         MAKE_PAD (1, 4, 88);
579         MAKE_PAD (1, 5, 89);
580         MAKE_PAD (1, 6, 90);
581         MAKE_PAD (1, 7, 91);
582         MAKE_PAD (2, 0, 76);
583         MAKE_PAD (2, 1, 77);
584         MAKE_PAD (2, 2, 78);
585         MAKE_PAD (2, 3, 79);
586         MAKE_PAD (2, 4, 80);
587         MAKE_PAD (2, 5, 81);
588         MAKE_PAD (2, 6, 82);
589         MAKE_PAD (2, 7, 83);
590         MAKE_PAD (3, 0, 68);
591         MAKE_PAD (3, 1, 69);
592         MAKE_PAD (3, 2, 70);
593         MAKE_PAD (3, 3, 71);
594         MAKE_PAD (3, 4, 72);
595         MAKE_PAD (3, 5, 73);
596         MAKE_PAD (3, 6, 74);
597         MAKE_PAD (3, 7, 75);
598         MAKE_PAD (4, 0, 60);
599         MAKE_PAD (4, 1, 61);
600         MAKE_PAD (4, 2, 62);
601         MAKE_PAD (4, 3, 63);
602         MAKE_PAD (4, 4, 64);
603         MAKE_PAD (4, 5, 65);
604         MAKE_PAD (4, 6, 66);
605         MAKE_PAD (4, 7, 67);
606         MAKE_PAD (5, 0, 52);
607         MAKE_PAD (5, 1, 53);
608         MAKE_PAD (5, 2, 54);
609         MAKE_PAD (5, 3, 56);
610         MAKE_PAD (5, 4, 56);
611         MAKE_PAD (5, 5, 57);
612         MAKE_PAD (5, 6, 58);
613         MAKE_PAD (5, 7, 59);
614         MAKE_PAD (6, 0, 44);
615         MAKE_PAD (6, 1, 45);
616         MAKE_PAD (6, 2, 46);
617         MAKE_PAD (6, 3, 47);
618         MAKE_PAD (6, 4, 48);
619         MAKE_PAD (6, 5, 49);
620         MAKE_PAD (6, 6, 50);
621         MAKE_PAD (6, 7, 51);
622         MAKE_PAD (7, 0, 36);
623         MAKE_PAD (7, 1, 37);
624         MAKE_PAD (7, 2, 38);
625         MAKE_PAD (7, 3, 39);
626         MAKE_PAD (7, 4, 40);
627         MAKE_PAD (7, 5, 41);
628         MAKE_PAD (7, 6, 42);
629         MAKE_PAD (7, 7, 43);
630
631         /* Now color buttons */
632
633         Button *button;
634
635 #define MAKE_COLOR_BUTTON(i,cc) \
636         button = new ColorButton ((i), (cc)); \
637         cc_button_map.insert (make_pair (button->controller_number(), button)); \
638         id_button_map.insert (make_pair (button->id, button));
639 #define MAKE_COLOR_BUTTON_PRESS(i,cc,p)\
640         button = new ColorButton ((i), (cc), (p)); \
641         cc_button_map.insert (make_pair (button->controller_number(), button)); \
642         id_button_map.insert (make_pair (button->id, button))
643
644         MAKE_COLOR_BUTTON (Upper1, 102);
645         MAKE_COLOR_BUTTON (Upper2, 103);
646         MAKE_COLOR_BUTTON (Upper3, 104);
647         MAKE_COLOR_BUTTON (Upper4, 105);
648         MAKE_COLOR_BUTTON (Upper5, 106);
649         MAKE_COLOR_BUTTON (Upper6, 107);
650         MAKE_COLOR_BUTTON (Upper7, 108);
651         MAKE_COLOR_BUTTON (Upper8, 109);
652         MAKE_COLOR_BUTTON (Lower1, 21);
653         MAKE_COLOR_BUTTON (Lower2, 22);
654         MAKE_COLOR_BUTTON (Lower3, 23);
655         MAKE_COLOR_BUTTON (Lower4, 24);
656         MAKE_COLOR_BUTTON (Lower5, 25);
657         MAKE_COLOR_BUTTON (Lower6, 26);
658         MAKE_COLOR_BUTTON (Lower7, 27);
659         MAKE_COLOR_BUTTON (Master, 28);
660         MAKE_COLOR_BUTTON (Mute, 60);
661         MAKE_COLOR_BUTTON_PRESS (Solo, 61, &Push2::button_solo);
662         MAKE_COLOR_BUTTON (Stop, 29);
663         MAKE_COLOR_BUTTON (Fwd32ndT, 43);
664         MAKE_COLOR_BUTTON (Fwd32nd,42 );
665         MAKE_COLOR_BUTTON (Fwd16thT, 41);
666         MAKE_COLOR_BUTTON (Fwd16th, 40);
667         MAKE_COLOR_BUTTON (Fwd8thT, 39 );
668         MAKE_COLOR_BUTTON (Fwd8th, 38);
669         MAKE_COLOR_BUTTON (Fwd4trT, 37);
670         MAKE_COLOR_BUTTON (Fwd4tr, 36);
671         MAKE_COLOR_BUTTON (Automate, 89);
672         MAKE_COLOR_BUTTON_PRESS (RecordEnable, 86, &Push2::button_recenable);
673         MAKE_COLOR_BUTTON_PRESS (Play, 85, &Push2::button_play);
674
675 #define MAKE_WHITE_BUTTON(i,cc)\
676         button = new WhiteButton ((i), (cc)); \
677         cc_button_map.insert (make_pair (button->controller_number(), button)); \
678         id_button_map.insert (make_pair (button->id, button))
679 #define MAKE_WHITE_BUTTON_PRESS(i,cc,p)\
680         button = new WhiteButton ((i), (cc), (p)); \
681         cc_button_map.insert (make_pair (button->controller_number(), button)); \
682         id_button_map.insert (make_pair (button->id, button))
683 #define MAKE_WHITE_BUTTON_PRESS_RELEASE(i,cc,p,r)                                \
684         button = new WhiteButton ((i), (cc), (p), (r)); \
685         cc_button_map.insert (make_pair (button->controller_number(), button)); \
686         id_button_map.insert (make_pair (button->id, button))
687
688         MAKE_WHITE_BUTTON (TapTempo, 3);
689         MAKE_WHITE_BUTTON_PRESS (Metronome, 9, &Push2::button_metronome);
690         MAKE_WHITE_BUTTON (Setup, 30);
691         MAKE_WHITE_BUTTON (User, 59);
692         MAKE_WHITE_BUTTON (Delete, 118);
693         MAKE_WHITE_BUTTON (AddDevice, 52);
694         MAKE_WHITE_BUTTON (Device, 110);
695         MAKE_WHITE_BUTTON (Mix, 112);
696         MAKE_WHITE_BUTTON (Undo, 119);
697         MAKE_WHITE_BUTTON (AddTrack, 53);
698         MAKE_WHITE_BUTTON (Browse, 113);
699         MAKE_WHITE_BUTTON (Convert, 35);
700         MAKE_WHITE_BUTTON (DoubleLoop, 117);
701         MAKE_WHITE_BUTTON (Quantize, 116);
702         MAKE_WHITE_BUTTON (Duplicate, 88);
703         MAKE_WHITE_BUTTON_PRESS (New, 87, &Push2::button_new);
704         MAKE_WHITE_BUTTON_PRESS (FixedLength, 90, &Push2::button_fixed_length);
705         MAKE_WHITE_BUTTON_PRESS (Up, 46, &Push2::button_up);
706         MAKE_WHITE_BUTTON_PRESS (Right, 45, &Push2::button_right);
707         MAKE_WHITE_BUTTON_PRESS (Down, 47, &Push2::button_down);
708         MAKE_WHITE_BUTTON_PRESS (Left, 44, &Push2::button_left);
709         MAKE_WHITE_BUTTON_PRESS (Repeat, 56, &Push2::button_repeat);
710         MAKE_WHITE_BUTTON (Accent, 57);
711         MAKE_WHITE_BUTTON (Scale, 58);
712         MAKE_WHITE_BUTTON (Layout, 31);
713         MAKE_WHITE_BUTTON (Note, 50);
714         MAKE_WHITE_BUTTON (Session, 51);
715         MAKE_WHITE_BUTTON (Layout, 31);
716         MAKE_WHITE_BUTTON (OctaveUp, 55);
717         MAKE_WHITE_BUTTON (PageRight, 63);
718         MAKE_WHITE_BUTTON (OctaveDown, 54);
719         MAKE_WHITE_BUTTON (PageLeft, 62);
720         MAKE_WHITE_BUTTON_PRESS_RELEASE (Shift, 49, &Push2::button_shift_press, &Push2::button_shift_release);
721         MAKE_WHITE_BUTTON (Select, 48);
722 }
723
724 void
725 Push2::thread_init ()
726 {
727         struct sched_param rtparam;
728
729         pthread_set_name (event_loop_name().c_str());
730
731         PBD::notify_event_loops_about_thread_creation (pthread_self(), event_loop_name(), 2048);
732         ARDOUR::SessionEvent::create_per_thread_pool (event_loop_name(), 128);
733
734         memset (&rtparam, 0, sizeof (rtparam));
735         rtparam.sched_priority = 9; /* XXX should be relative to audio (JACK) thread */
736
737         if (pthread_setschedparam (pthread_self(), SCHED_FIFO, &rtparam) != 0) {
738                 // do we care? not particularly.
739         }
740 }
741
742 void
743 Push2::connect_session_signals()
744 {
745         // receive routes added
746         //session->RouteAdded.connect(session_connections, MISSING_INVALIDATOR, boost::bind (&MackieControlProtocol::notify_routes_added, this, _1), this);
747         // receive VCAs added
748         //session->vca_manager().VCAAdded.connect(session_connections, MISSING_INVALIDATOR, boost::bind (&Push2::notify_vca_added, this, _1), this);
749
750         // receive record state toggled
751         session->RecordStateChanged.connect(session_connections, MISSING_INVALIDATOR, boost::bind (&Push2::notify_record_state_changed, this), this);
752         // receive transport state changed
753         session->TransportStateChange.connect(session_connections, MISSING_INVALIDATOR, boost::bind (&Push2::notify_transport_state_changed, this), this);
754         session->TransportLooped.connect (session_connections, MISSING_INVALIDATOR, boost::bind (&Push2::notify_loop_state_changed, this), this);
755         // receive punch-in and punch-out
756         Config->ParameterChanged.connect(session_connections, MISSING_INVALIDATOR, boost::bind (&Push2::notify_parameter_changed, this, _1), this);
757         session->config.ParameterChanged.connect (session_connections, MISSING_INVALIDATOR, boost::bind (&Push2::notify_parameter_changed, this, _1), this);
758         // receive rude solo changed
759         session->SoloActive.connect(session_connections, MISSING_INVALIDATOR, boost::bind (&Push2::notify_solo_active_changed, this, _1), this);
760 }
761
762 void
763 Push2::notify_record_state_changed ()
764 {
765         IDButtonMap::iterator b = id_button_map.find (RecordEnable);
766
767         if (b == id_button_map.end()) {
768                 return;
769         }
770
771         switch (session->record_status ()) {
772         case Session::Disabled:
773                 b->second->set_color (LED::White);
774                 b->second->set_state (LED::NoTransition);
775                 break;
776         case Session::Enabled:
777                 b->second->set_color (LED::Red);
778                 b->second->set_state (LED::Blinking4th);
779                 break;
780         case Session::Recording:
781                 b->second->set_color (LED::Red);
782                 b->second->set_state (LED::OneShot24th);
783                 break;
784         }
785
786         write (b->second->state_msg());
787 }
788
789 void
790 Push2::notify_transport_state_changed ()
791 {
792         Button* b = id_button_map[Play];
793
794         if (session->transport_rolling()) {
795                 b->set_state (LED::OneShot24th);
796                 b->set_color (LED::Green);
797         } else {
798
799                 /* disable any blink on FixedLength from pending edit range op */
800                 Button* fl = id_button_map[FixedLength];
801
802                 fl->set_color (LED::Black);
803                 fl->set_state (LED::NoTransition);
804                 write (fl->state_msg());
805
806                 b->set_color (LED::White);
807                 b->set_state (LED::NoTransition);
808         }
809
810         write (b->state_msg());
811 }
812
813 void
814 Push2::notify_loop_state_changed ()
815 {
816 }
817
818 void
819 Push2::notify_parameter_changed (std::string param)
820 {
821         IDButtonMap::iterator b;
822
823         if (param == "clicking") {
824                 if ((b = id_button_map.find (Metronome)) == id_button_map.end()) {
825                         return;
826                 }
827                 if (Config->get_clicking()) {
828                         b->second->set_state (LED::Blinking4th);
829                         b->second->set_color (LED::White);
830                 } else {
831                         b->second->set_color (LED::White);
832                         b->second->set_state (LED::NoTransition);
833                 }
834                 write (b->second->state_msg ());
835         }
836 }
837
838 void
839 Push2::notify_solo_active_changed (bool yn)
840 {
841         IDButtonMap::iterator b = id_button_map.find (Solo);
842
843         if (b == id_button_map.end()) {
844                 return;
845         }
846
847         if (yn) {
848                 b->second->set_state (LED::Blinking4th);
849                 b->second->set_color (LED::Red);
850         } else {
851                 b->second->set_state (LED::NoTransition);
852                 b->second->set_color (LED::White);
853         }
854
855         write (b->second->state_msg());
856 }
857
858 XMLNode&
859 Push2::get_state()
860 {
861         XMLNode& node (ControlProtocol::get_state());
862         XMLNode* child;
863
864         child = new XMLNode (X_("Input"));
865         child->add_child_nocopy (_async_in->get_state());
866         node.add_child_nocopy (*child);
867         child = new XMLNode (X_("Output"));
868         child->add_child_nocopy (_async_out->get_state());
869         node.add_child_nocopy (*child);
870
871         return node;
872 }
873
874 int
875 Push2::set_state (const XMLNode & node, int version)
876 {
877         DEBUG_TRACE (DEBUG::Push2, string_compose ("Push2::set_state: active %1\n", active()));
878
879         int retval = 0;
880
881         if (ControlProtocol::set_state (node, version)) {
882                 return -1;
883         }
884
885         XMLNode* child;
886
887         if ((child = node.child (X_("Input"))) != 0) {
888                 XMLNode* portnode = child->child (Port::state_node_name.c_str());
889                 if (portnode) {
890                         _async_in->set_state (*portnode, version);
891                 }
892         }
893
894         if ((child = node.child (X_("Output"))) != 0) {
895                 XMLNode* portnode = child->child (Port::state_node_name.c_str());
896                 if (portnode) {
897                         _async_out->set_state (*portnode, version);
898                 }
899         }
900
901         return retval;
902 }