Colors customizable - 'w' + 'f' "fix" - Alex
[terminatorX.git] / src / tX_midiin.cc
1 /*
2   terminatorX - realtime audio scratching software
3   Copyright (C) 2002 Arthur Peters
4         
5   This program is free software; you can redistribute it and/or modify
6   it under the terms of the GNU General Public License as published by
7   the Free Software Foundation; either version 2 of the License, or
8   (at your option) any later version.
9  
10   This program is distributed in the hope that it will be useful,
11   but WITHOUT ANY WARRANTY; without even the implied warranty of
12   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13   GNU General Public License for more details.
14  
15   You should have received a copy of the GNU General Public License
16   along with this program; if not, write to the Free Software
17   Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
18  
19   File: tX_midiin.cc
20  
21   Description: Implements MIDI input to control turntable parameters.
22   
23         Changes (Alexander K├Ânig <alex@lisas.de>:
24         - Using a glib GIOCallback instead of polling events
25         - Updating the treeview immedialtey after bind/unbind_clicked
26         - Adding "remove binding" option
27         - Adding destroy handler for the GUI
28         - moving printf to tX_* macros
29         - removing some debug code
30 */    
31
32 #include "tX_midiin.h"
33 #include "tX_vtt.h"
34 #include "tX_glade_interface.h"
35 #include "tX_glade_support.h"
36
37 #ifdef USE_ALSA_MIDI_IN
38 #include "tX_global.h"
39 #include <iostream>
40 #include "tX_engine.h"
41
42 using namespace std;
43
44 static gboolean midi_callback(GIOChannel *source, GIOCondition condition, gpointer data) {
45         tX_midiin *midi=(tX_midiin *) data;
46         midi->check_event();
47         
48         return TRUE;
49 }
50
51 tX_midiin::tX_midiin()
52 {
53         is_open=false;
54         sp_to_learn=NULL;
55         learn_dialog=NULL;
56         
57         if (snd_seq_open(&ALSASeqHandle, "default", SND_SEQ_OPEN_INPUT, 0) < 0) {
58                 tX_error("tX_midiin(): failed to open the default sequencer device.");
59                 return;
60         }
61         snd_seq_set_client_name(ALSASeqHandle, "terminatorX");
62         portid =
63                 snd_seq_create_simple_port(ALSASeqHandle,
64                                                                    "Control Input",
65                                                                    SND_SEQ_PORT_CAP_WRITE
66                                                                    | SND_SEQ_PORT_CAP_SUBS_WRITE,
67                                                                    SND_SEQ_PORT_TYPE_APPLICATION);
68         if (portid < 0) {
69                 tX_error("tX_midiin(): error creating sequencer port.");
70                 return;
71         }
72
73         snd_seq_nonblock( ALSASeqHandle, 1 );
74         
75         struct pollfd fds[32];
76         
77         int res=snd_seq_poll_descriptors (ALSASeqHandle, fds, 32, POLLIN);
78
79         if (res!=1) {
80                 tX_error("Failed to poll ALSA descriptors: %i.\n", res);
81         }
82         
83         GIOChannel *ioc=g_io_channel_unix_new(fds[0].fd);
84         g_io_add_watch(ioc, (GIOCondition)( G_IO_IN ), midi_callback, (gpointer) this);
85         g_io_channel_unref(ioc);
86         
87         is_open=true;
88
89         tX_debug("tX_midiin(): sequencer successfully opened."); 
90 }
91
92 tX_midiin::~tX_midiin()
93 {
94         if (is_open) {
95                 snd_seq_close(ALSASeqHandle);
96                 tX_debug("tX_midiin(): sequencer closed.");
97         }
98 }
99
100 int tX_midiin::check_event()
101 {
102         snd_seq_event_t *ev;
103                 
104         while( snd_seq_event_input(ALSASeqHandle, &ev) != -EAGAIN )
105         {
106
107                 //MidiEvent::type MessageType=MidiEvent::NONE;
108                 //int Volume=0,Note=0,EventDevice=0;
109                 tX_midievent event;
110                 event.is_noteon = false;
111                 bool event_usable = true;
112
113                 switch (ev->type) {
114                         case SND_SEQ_EVENT_CONTROLLER: 
115                                 event.type = tX_midievent::CC;
116                                 event.number = ev->data.control.param;
117                                 event.value = ev->data.control.value / 127.0;
118                                 event.channel = ev->data.control.channel;
119                                 break;
120                         case SND_SEQ_EVENT_PITCHBEND:
121                                 event.type = tX_midievent::PITCHBEND;
122                                 event.number = ev->data.control.param;
123                                 event.value = (ev->data.control.value + 8191.0) / 16382.0; // 127.0;
124                                 event.channel = ev->data.control.channel;
125                                 break;
126                         case SND_SEQ_EVENT_CONTROL14:
127                                 event.type = tX_midievent::CC14;
128                                 event.number = ev->data.control.param;
129                                 event.value = ev->data.control.value / 16383.0;
130                                 event.channel = ev->data.control.channel;
131                                 break;
132                         case SND_SEQ_EVENT_REGPARAM:
133                                 event.type = tX_midievent::RPN;
134                                 event.number = ev->data.control.param;
135                                 event.value = ev->data.control.value / 16383.0;
136                                 event.channel = ev->data.control.channel;
137                                 break;
138                         case SND_SEQ_EVENT_NONREGPARAM:
139                                 event.type = tX_midievent::NRPN;
140                                 event.number = ev->data.control.param;
141                                 event.value = ev->data.control.value / 16383.0;
142                                 event.channel = ev->data.control.channel;
143                                 break;                                          
144                         case SND_SEQ_EVENT_NOTEON:
145                                 event.type = tX_midievent::NOTE;
146                                 event.number = ev->data.note.note;
147                                 event.value = ev->data.note.velocity / 127.0;
148                                 event.channel = ev->data.note.channel;
149
150                                 event.is_noteon = true;
151                                 if( event.value == 0 )
152                                         event.is_noteon = false;
153                                 break;
154                         case SND_SEQ_EVENT_NOTEOFF: 
155                                 event.type = tX_midievent::NOTE;
156                                 event.number = ev->data.note.note;
157                                 event.value = ev->data.note.velocity / 127.0;
158                                 event.channel = ev->data.note.channel;
159                                 
160                                 event.is_noteon = false;
161                                 break;
162                         default:
163                                 event_usable = false;
164                 }
165
166                 snd_seq_free_event(ev);
167                 
168                 if( event_usable ) {
169                         if (event.channel<0 || event.channel>15) {
170                                 tX_error("tX_midiin::check_event(): invaild event channel %i.", event.channel);
171                                 return -1;
172                         }
173
174                         if (sp_to_learn) {
175                                 sp_to_learn->bound_midi_event=event;
176                                 sp_to_learn=NULL;
177                                 
178                                 if (learn_dialog) {
179                                         gtk_widget_destroy(learn_dialog);
180                                         learn_dialog=NULL;
181                                 }
182                         } else {
183                                 // This should be solved with a hash table. Possibly.
184                                 
185                                 list <tX_seqpar *> :: iterator sp;                      
186                                 
187                                 for (sp=tX_seqpar::all.begin(); sp!=tX_seqpar::all.end(); sp++) {
188                                         if ( (*sp)->bound_midi_event.type_matches (event) ) {
189                                                 (*sp)->handle_midi_input (event);
190                                         }
191                                 }
192                         }
193                         
194                         last_event = event;
195                 }
196
197         }
198         return 1;
199 }
200
201 void tX_midiin::configure_bindings( vtt_class* vtt )
202 {
203         list <tX_seqpar *> :: iterator sp;
204
205         GType types[3] = { G_TYPE_STRING, G_TYPE_STRING, G_TYPE_POINTER };
206         GtkListStore* model = gtk_list_store_newv(3, types);
207         GtkTreeIter iter;
208         char tempstr[128];
209         
210         for (sp=tX_seqpar::all.begin(); sp!=tX_seqpar::all.end(); sp++) {
211                 if (((*sp)->is_mappable) && ((*sp)->vtt) == (void*) vtt) {
212                         
213                         snprintf( tempstr, sizeof(tempstr), "Type: %d, Number: %d, Channel: %d",
214                                           (*sp)->bound_midi_event.type, (*sp)->bound_midi_event.number,
215                                           (*sp)->bound_midi_event.channel );
216
217                         gtk_list_store_append( model, &iter );
218                         gtk_list_store_set( model, &iter,
219                                                                 0, (*sp)->get_name(),
220                                                                 1, tempstr,
221                                                                 2, (*sp),
222                                                                 -1 );
223                 }
224         }
225
226         // it will delete itself.
227         new midi_binding_gui(GTK_TREE_MODEL(model), this);
228 }
229
230 tX_midiin::midi_binding_gui::midi_binding_gui ( GtkTreeModel* _model, tX_midiin* _midi )
231         : model(_model), midi( _midi )
232 {
233         GtkWidget *hbox1;
234         GtkWidget *scrolledwindow1;
235         GtkWidget *vbox1;
236         GtkWidget *label1;
237         GtkWidget *frame1;
238         
239         window = gtk_window_new (GTK_WINDOW_TOPLEVEL);
240         gtk_window_set_title (GTK_WINDOW (window), "Configure MIDI Bindings");
241         gtk_window_set_default_size(GTK_WINDOW(window), 600, 260);
242         
243         hbox1 = gtk_hbox_new (FALSE, 2);
244         gtk_widget_show (hbox1);
245         gtk_container_add (GTK_CONTAINER (window), hbox1);
246         gtk_container_set_border_width(GTK_CONTAINER(hbox1), 4);
247         
248         scrolledwindow1 = gtk_scrolled_window_new (NULL, NULL);
249         gtk_widget_show (scrolledwindow1);
250         gtk_box_pack_start (GTK_BOX (hbox1), scrolledwindow1, TRUE, TRUE, 0);
251         
252         parameter_treeview = gtk_tree_view_new_with_model (model);
253         gtk_widget_show (parameter_treeview);
254         gtk_container_add (GTK_CONTAINER (scrolledwindow1), parameter_treeview);
255         
256         GtkCellRenderer   *renderer = gtk_cell_renderer_text_new ();
257         gtk_tree_view_insert_column_with_attributes( GTK_TREE_VIEW( parameter_treeview ),
258                                                                                            -1, "Parameter", renderer,
259                                                                                            "text", 0,
260                                                                                            NULL );
261         gtk_tree_view_insert_column_with_attributes( GTK_TREE_VIEW( parameter_treeview ),
262                                                                                            -1, "Event", renderer,
263                                                                                            "text", 1,
264                                                                                            NULL );
265         gtk_tree_view_set_headers_visible( GTK_TREE_VIEW(parameter_treeview), TRUE );
266         
267         vbox1 = gtk_vbox_new (FALSE, 0);
268         gtk_widget_show (vbox1);
269         gtk_box_pack_start (GTK_BOX (hbox1), vbox1, FALSE, FALSE, 0);
270         
271         label1 = gtk_label_new ("Selected MIDI Event:");
272         gtk_widget_show (label1);
273         gtk_box_pack_start (GTK_BOX (vbox1), label1, FALSE, FALSE, 0);
274         gtk_label_set_justify (GTK_LABEL (label1), GTK_JUSTIFY_LEFT);
275         
276         frame1 = gtk_frame_new (NULL);
277         gtk_widget_show (frame1);
278         gtk_box_pack_start (GTK_BOX (vbox1), frame1, TRUE, TRUE, 0);
279         gtk_container_set_border_width (GTK_CONTAINER (frame1), 2);
280         gtk_frame_set_label_align (GTK_FRAME (frame1), 0, 0);
281         gtk_frame_set_shadow_type (GTK_FRAME (frame1), GTK_SHADOW_IN);
282         
283         midi_event_info = gtk_label_new ("Use a MIDI thing to select it.");
284         gtk_widget_show (midi_event_info);
285         gtk_container_add (GTK_CONTAINER (frame1), midi_event_info);
286         gtk_label_set_justify (GTK_LABEL (midi_event_info), GTK_JUSTIFY_LEFT);
287         
288         bind_button = gtk_button_new_with_mnemonic ("Bind");
289         gtk_widget_show (bind_button);
290         gtk_box_pack_start (GTK_BOX (vbox1), bind_button, FALSE, FALSE, 0);
291         
292         GtkWidget* unbind_button = gtk_button_new_with_mnemonic ("Remove Binding");
293         gtk_widget_show (unbind_button);
294         gtk_box_pack_start (GTK_BOX (vbox1), unbind_button, FALSE, FALSE, 0);   
295         
296         GtkWidget* close_button = gtk_button_new_with_mnemonic ("Close");
297         gtk_widget_show (close_button);
298         gtk_box_pack_start (GTK_BOX (vbox1), close_button, FALSE, FALSE, 0);
299         
300         gtk_signal_connect(GTK_OBJECT(bind_button), "clicked", (GtkSignalFunc) bind_clicked, (void *) this);
301         gtk_signal_connect(GTK_OBJECT(unbind_button), "clicked", (GtkSignalFunc) unbind_clicked, (void *) this);        
302         gtk_signal_connect(GTK_OBJECT(close_button), "clicked", (GtkSignalFunc) close_clicked, (void *) this);
303         gtk_signal_connect(GTK_OBJECT(window), "destroy", (GtkSignalFunc) close_clicked, (void *) this);
304         
305         timer_tag = gtk_timeout_add( 100, (GtkFunction) timer, (void *) this);
306         
307         gtk_widget_show_all( GTK_WIDGET( window ) );
308 }
309
310 void tX_midiin::midi_binding_gui::window_closed(GtkWidget *widget, gpointer _this )
311 {
312         tX_midiin::midi_binding_gui* this_ = (tX_midiin::midi_binding_gui*)_this;
313
314         delete this_;
315 }
316
317 void tX_midiin::midi_binding_gui::unbind_clicked( GtkButton *button, gpointer _this )
318 {
319         tX_midiin::midi_binding_gui* this_ = (tX_midiin::midi_binding_gui*)_this;
320         GtkTreeModel* model;
321         GtkTreeSelection* selection;
322         GtkTreeIter iter;
323         char tmpstr[128];
324         tX_seqpar* param;
325
326         selection = gtk_tree_view_get_selection( GTK_TREE_VIEW(this_->parameter_treeview) );
327         gtk_tree_selection_get_selected( selection, &model, &iter );
328         gtk_tree_model_get( model, &iter, 2, &param, -1 );
329         
330         param->bound_midi_event.type=tX_midievent::NONE;
331         param->bound_midi_event.number=0;
332         param->bound_midi_event.channel=0;
333         
334         snprintf( tmpstr, sizeof(tmpstr), "Type: %d, Number: %d, Channel: %d",
335                                 param->bound_midi_event.type, param->bound_midi_event.number,
336                                 param->bound_midi_event.channel );
337
338         gtk_list_store_set(GTK_LIST_STORE(model), &iter, 0, param->get_name(), 1, tmpstr, 2, param, -1 );       
339 }
340
341
342 void tX_midiin::midi_binding_gui::bind_clicked( GtkButton *button, gpointer _this )
343 {
344         tX_midiin::midi_binding_gui* this_ = (tX_midiin::midi_binding_gui*)_this;
345         GtkTreeModel* model;
346         GtkTreeSelection* selection;
347         GtkTreeIter iter;
348         char tmpstr[128];
349         tX_seqpar* param;
350
351         selection = gtk_tree_view_get_selection( GTK_TREE_VIEW(this_->parameter_treeview) );
352         gtk_tree_selection_get_selected( selection, &model, &iter );
353         gtk_tree_model_get( model, &iter, 2, &param, -1 );
354         
355         param->bound_midi_event = this_->last_event;
356         
357         snprintf( tmpstr, sizeof(tmpstr), "Type: %d, Number: %d, Channel: %d",
358                                 param->bound_midi_event.type, param->bound_midi_event.number,
359                                 param->bound_midi_event.channel );
360
361         gtk_list_store_set(GTK_LIST_STORE(model), &iter, 0, param->get_name(), 1, tmpstr, 2, param, -1 );       
362 }
363
364 void tX_midiin::midi_binding_gui::close_clicked( GtkButton *button, gpointer _this )
365 {
366         tX_midiin::midi_binding_gui* this_ = (tX_midiin::midi_binding_gui*)_this;
367         
368         gtk_widget_destroy( this_->window );
369 }
370
371 gint tX_midiin::midi_binding_gui::timer( gpointer _this )
372 {
373         tX_midiin::midi_binding_gui* this_ = (tX_midiin::midi_binding_gui*)_this;
374         tX_midievent tmpevent = this_->midi->get_last_event();
375
376         if( tmpevent.type_matches( this_->last_event ) )
377                 return TRUE;
378         
379         this_->last_event = tmpevent;
380         this_->last_event.clear_non_type();
381
382         snprintf( this_->tempstr, sizeof(this_->tempstr),
383                           "Type: %d (CC=%d, NOTE=%d)\nNumber: %d\nChannel: %d\n",
384                           this_->last_event.type, tX_midievent::CC, tX_midievent::NOTE,
385                           this_->last_event.number,
386                           this_->last_event.channel );
387
388         gtk_label_set_text( GTK_LABEL(this_->midi_event_info), this_->tempstr );
389
390         return TRUE;
391 }
392
393 tX_midiin::midi_binding_gui::~midi_binding_gui ()
394 {
395         gtk_timeout_remove( timer_tag );
396 }
397
398 void tX_midiin::set_midi_learn_sp(tX_seqpar *sp)
399 {
400         char buffer[512];
401         
402         if (learn_dialog) {
403                 gtk_widget_destroy(learn_dialog);
404         }
405         
406         sp_to_learn=sp;
407         
408         if (!sp_to_learn) return;
409         
410         learn_dialog=create_tX_midilearn();
411         GtkWidget *label=lookup_widget(learn_dialog, "midilabel");
412         
413         sprintf(buffer, "Learning MIDI mapping for <b>%s</b>\nfor turntable <b>%s</b>.\n\nWaiting for MIDI event...", sp->get_name(), sp->get_vtt_name());
414         gtk_label_set_markup(GTK_LABEL(label), buffer);
415         gtk_widget_show(learn_dialog);
416         
417         g_signal_connect(G_OBJECT(lookup_widget(learn_dialog, "cancel")), "clicked", G_CALLBACK (tX_midiin::midi_learn_cancel), this);
418         g_signal_connect(G_OBJECT(learn_dialog), "destroy", G_CALLBACK (tX_midiin::midi_learn_destroy), this);
419 }
420
421 void tX_midiin::cancel_midi_learn()
422 {
423         sp_to_learn=NULL;
424         learn_dialog=NULL;
425 }
426
427 gboolean tX_midiin::midi_learn_cancel(GtkWidget *widget, tX_midiin *midi)
428 {
429         midi->sp_to_learn=NULL;
430         gtk_widget_destroy(midi->learn_dialog);
431 }
432
433 gboolean tX_midiin::midi_learn_destroy(GtkWidget *widget, tX_midiin *midi)
434 {
435         midi->cancel_midi_learn();
436 }
437
438 void tX_midiin::store_connections(FILE *rc, char *indent) 
439 {
440         gzFile *rz;
441         
442         tX_store("%s<midi_connections>\n", indent);
443         strcat(indent, "\t");
444
445         snd_seq_addr_t my_addr;
446         my_addr.client=snd_seq_client_id(ALSASeqHandle);
447         my_addr.port=portid;
448
449         snd_seq_query_subscribe_t *subs;
450         snd_seq_query_subscribe_alloca(&subs);
451         snd_seq_query_subscribe_set_root(subs, &my_addr);
452         snd_seq_query_subscribe_set_type(subs, SND_SEQ_QUERY_SUBS_WRITE);
453         snd_seq_query_subscribe_set_index(subs, 0);
454         
455         while (snd_seq_query_port_subscribers(ALSASeqHandle, subs) >= 0) {
456                 const snd_seq_addr_t *addr;
457                 addr = snd_seq_query_subscribe_get_addr(subs);
458                 
459                 tX_store("%s<link client=\"%i\" port=\"%i\"/>\n", indent, addr->client, addr->port);
460                 snd_seq_query_subscribe_set_index(subs, snd_seq_query_subscribe_get_index(subs) + 1);
461         }       
462                 
463         indent[strlen(indent)-1]=0;
464         tX_store("%s</midi_connections>\n", indent);    
465 }
466
467 void tX_midiin::restore_connections(xmlNodePtr node)
468 {
469         snd_seq_addr_t my_addr;
470         my_addr.client=snd_seq_client_id(ALSASeqHandle);
471         my_addr.port=portid;
472         
473         if (xmlStrcmp(node->name, (xmlChar *) "midi_connections")==0) {
474                 for (xmlNodePtr cur=node->xmlChildrenNode; cur != NULL; cur = cur->next) {
475                         if (cur->type == XML_ELEMENT_NODE) {
476                                 if (xmlStrcmp(cur->name, (xmlChar *) "link")==0) {
477                                         char *buffer;
478                                         int client=-1;
479                                         int port=-1;
480                                         
481                                         buffer=(char *) xmlGetProp(cur, (xmlChar *) "client");
482                                         if (buffer) {
483                                                 sscanf(buffer, "%i", &client);
484                                         }
485                                         
486                                         buffer=(char *) xmlGetProp(cur, (xmlChar *) "port");
487                                         if (buffer) {
488                                                 sscanf(buffer, "%i", &port);
489                                         }
490                                         
491                                         if ((port>=0) && (client>=0)) {
492                                                 snd_seq_addr_t sender_addr;
493                                                 sender_addr.client=client;
494                                                 sender_addr.port=port;
495                                                 
496                                                 snd_seq_port_subscribe_t *subs;
497                                                 snd_seq_port_subscribe_alloca(&subs);
498                                                 snd_seq_port_subscribe_set_sender(subs, &sender_addr);
499                                                 snd_seq_port_subscribe_set_dest(subs, &my_addr);
500
501                                                 if (snd_seq_subscribe_port(ALSASeqHandle, subs) < 0) {
502                                                         tX_error("tX_midiin::restore_connections() -> failed to connect to: %d:%d.", port, client);
503                                                 }
504                                         } else {
505                                                 tX_error("tX_midiin::restore_connections() -> invalid port: %d:%d.", port, client);
506                                         }
507                                         
508                                 } else {
509                                         tX_error("tX_midiin::restore_connections() -> invalid element: %s.", cur->name);
510                                 }
511                         }
512                 }
513         } else {
514                 tX_error("tX_midiin::restore_connections() -> invalid XML element.");
515         }
516 }
517
518
519 extern "C" {
520         void tX_midiin_store_connections(FILE *rc, char *indent);
521         void tX_midiin_restore_connections(xmlNodePtr node);
522 };
523
524 void tX_midiin_store_connections(FILE *rc, char *indent) 
525 {
526         tX_engine::get_instance()->get_midi()->store_connections(rc, indent);
527 }
528
529 void tX_midiin_restore_connections(xmlNodePtr node) 
530 {
531         tX_engine::get_instance()->get_midi()->restore_connections(node);
532 }
533
534 #endif // USE_ALSA_MIDI_IN