]> git.cworth.org Git - scherzo/blob - scherzo.c
Fix chord analysis for intervals larger than an octave
[scherzo] / scherzo.c
1 /* scherzo - Music notation training
2  *
3  * Copyright © 2010 Carl Worth
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 3 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, see http://www.gnu.org/licenses/ .
17  */
18
19 #include <gtk/gtk.h>
20 #include <gdk/gdkkeysyms.h>
21
22 #include <asoundlib.h>
23
24 #include "score.h"
25 #include "mnemon.h"
26
27 #define ARRAY_SIZE(arr) (sizeof(arr) / sizeof(arr[0]))
28
29 #define unused(foo) foo __attribute__((unused))
30
31 #define MIDI_BUF_SIZE 4096
32
33 typedef struct challenge
34 {
35     bin_t *bin;
36     int item_index;
37     score_staff_t *staff;
38     score_note_t *note;
39
40     int satisfied;
41     int mistaken;
42 } challenge_t;
43
44 typedef struct note_group
45 {
46     void *ctx;
47     score_note_t **notes;
48     int size;
49     int num_notes;
50 } note_group_t;
51
52 typedef struct scherzo
53 {
54     void *ctx;
55
56     GtkWidget *window;
57     score_t *score;
58     int staff_height;
59     score_staff_t *treble;
60     score_staff_t *bass;
61     score_chord_t *chord;
62
63     /* This is for a "computer keyboard". Any "piano keyboard" key
64      * knows its own octave. */
65     int keyboard_octave;
66
67     int midi_fd;
68     snd_midi_event_t *snd_midi_event;
69
70     mnemon_t mnemon;
71     challenge_t challenge;
72
73     note_group_t notes_pressed;
74     note_group_t notes_pedaled;
75
76     int pedal_pressed;
77 } scherzo_t;
78
79 /* Forward declarations. */
80 static score_note_t *
81 scherzo_press_note (scherzo_t *scherzo, score_pitch_t pitch, int octave);
82
83 static void
84 scherzo_release_note (scherzo_t *scherzo, score_pitch_t pitch, int octave);
85
86 static void
87 scherzo_press_pedal (scherzo_t *scherzo);
88
89 static void
90 scherzo_release_pedal (scherzo_t *scherzo);
91
92 static void
93 _judge_note (scherzo_t *scherzo, score_note_t *note);
94
95 static void
96 _score_challenge (scherzo_t *scherzo);
97
98 static int
99 on_delete_event_quit (unused (GtkWidget *widget),
100                       unused (GdkEvent *event),
101                       unused (gpointer user_data))
102 {
103     gtk_main_quit ();
104
105     /* Returning FALSE allows the default handler for delete-event
106      * to proceed to cleanup the widget. */
107     return FALSE;
108 }
109
110 static int
111 on_expose_event_draw (GtkWidget *widget,
112                       unused (GdkEventExpose *expose),
113                       void * user_data)
114 {
115     scherzo_t *scherzo = user_data;
116     score_t *score = scherzo->score;
117     cairo_t *cr;
118     GtkAllocation allocation;
119     static const int pad = 10;
120     int widget_width;
121
122     gtk_widget_get_allocation (widget, &allocation);
123     widget_width = allocation.width;
124
125     cr = gdk_cairo_create (widget->window);
126
127     /* White background */
128     cairo_set_source_rgb (cr, 1.0, 1.0, 1.0);
129     cairo_paint (cr);
130
131     /* Add some padding on the sides and top */
132     cairo_translate (cr, pad, scherzo->staff_height);
133     score_set_staff_height (score, scherzo->staff_height);
134     score_set_width (score, widget_width - 2 * pad);
135
136     score_draw (score, cr);
137  
138     return TRUE;
139 }
140
141 static int
142 on_key_press_event (GtkWidget *widget,
143                     GdkEventKey *key,
144                     void *user_data)
145 {
146     scherzo_t *scherzo = user_data;
147     int octave;
148     score_pitch_t pitch;
149
150     if (scherzo->challenge.note)
151         octave = scherzo->challenge.note->octave;
152     else
153         octave = scherzo->keyboard_octave;
154
155     switch (key->keyval) {
156     case GDK_KEY_plus:
157     case GDK_KEY_KP_Add:
158     case GDK_KEY_equal:
159     case GDK_KEY_KP_Equal:
160         scherzo->staff_height += 4;
161         gtk_widget_queue_draw (widget);
162         return TRUE;
163         break;
164     case GDK_KEY_minus:
165     case GDK_KEY_KP_Subtract:
166         scherzo->staff_height -= 4;
167         gtk_widget_queue_draw (widget);
168         return TRUE;
169         break;
170     case GDK_KEY_q:
171     case GDK_KEY_Q:
172     case GDK_KEY_Escape:
173         gtk_main_quit ();
174         return FALSE;
175     case GDK_KEY_c:
176     case GDK_KEY_C:
177         pitch = SCORE_PITCH_C;
178         break;
179     case GDK_KEY_d:
180     case GDK_KEY_D:
181         pitch = SCORE_PITCH_D;
182         break;
183     case GDK_KEY_e:
184     case GDK_KEY_E:
185         pitch = SCORE_PITCH_E;
186         break;
187     case GDK_KEY_f:
188     case GDK_KEY_F:
189         pitch = SCORE_PITCH_F;
190         break;
191     case GDK_KEY_g:
192     case GDK_KEY_G:
193         pitch = SCORE_PITCH_G;
194         break;
195     case GDK_KEY_a:
196     case GDK_KEY_A:
197         pitch = SCORE_PITCH_A;
198         break;
199     case GDK_KEY_b:
200     case GDK_KEY_B:
201         pitch = SCORE_PITCH_B;
202         break;
203     case GDK_KEY_0:
204     case GDK_KEY_1:
205     case GDK_KEY_2:
206     case GDK_KEY_3:
207     case GDK_KEY_4:
208     case GDK_KEY_5:
209     case GDK_KEY_6:
210     case GDK_KEY_7:
211     case GDK_KEY_8:
212         scherzo->keyboard_octave = key->keyval - GDK_KEY_0;
213         break;
214     case GDK_KEY_space:
215         scherzo_press_pedal (scherzo);
216         break;
217     }
218
219     if ((key->keyval >= GDK_KEY_A && key->keyval <= GDK_KEY_G) ||
220         (key->keyval >= GDK_KEY_a && key->keyval <= GDK_KEY_g))
221     {
222         score_note_t *note;
223
224         note = scherzo_press_note (scherzo, pitch, octave);
225         _judge_note (scherzo, note);
226         gtk_widget_queue_draw (scherzo->window);
227
228         return TRUE;
229     }
230
231
232     /* Allow an unhandled event to propagate to other handlers. */
233     return FALSE;
234 }
235
236 static int
237 on_key_release_event (unused (GtkWidget *widget),
238                       GdkEventKey *key,
239                       void *user_data)
240 {
241     scherzo_t *scherzo = user_data;
242     int octave;
243     score_pitch_t pitch;
244
245     if (scherzo->challenge.note)
246         octave = scherzo->challenge.note->octave;
247     else
248         octave = scherzo->keyboard_octave;
249
250     switch (key->keyval) {
251     case GDK_KEY_c:
252     case GDK_KEY_C:
253         pitch = SCORE_PITCH_C;
254         break;
255     case GDK_KEY_d:
256     case GDK_KEY_D:
257         pitch = SCORE_PITCH_D;
258         break;
259     case GDK_KEY_e:
260     case GDK_KEY_E:
261         pitch = SCORE_PITCH_E;
262         break;
263     case GDK_KEY_f:
264     case GDK_KEY_F:
265         pitch = SCORE_PITCH_F;
266         break;
267     case GDK_KEY_g:
268     case GDK_KEY_G:
269         pitch = SCORE_PITCH_G;
270         break;
271     case GDK_KEY_a:
272     case GDK_KEY_A:
273         pitch = SCORE_PITCH_A;
274         break;
275     case GDK_KEY_b:
276     case GDK_KEY_B:
277         pitch = SCORE_PITCH_B;
278         break;
279     case GDK_KEY_space:
280         scherzo_release_pedal (scherzo);
281         break;
282     }
283
284     if ((key->keyval >= GDK_KEY_A && key->keyval <= GDK_KEY_G) ||
285         (key->keyval >= GDK_KEY_a && key->keyval <= GDK_KEY_g))
286     {
287         scherzo_release_note (scherzo, pitch, octave);
288         _score_challenge (scherzo);
289         gtk_widget_queue_draw (scherzo->window);
290
291         return TRUE;
292     }
293
294
295     /* Allow an unhandled event to propagate to other handlers. */
296     return FALSE;
297 }
298
299 static unsigned char
300 _score_pitch_and_octave_to_midi (score_pitch_t pitch,
301                                  int octave)
302 {
303     unsigned char midi_note = 12 * (octave + 1);
304
305     switch (SCORE_PITCH_NAME (pitch)) {
306     case SCORE_PITCH_NAME_C:
307         break;
308     case SCORE_PITCH_NAME_D:
309         midi_note += 2;
310         break;
311     case SCORE_PITCH_NAME_E:
312         midi_note += 4;
313         break;
314     case SCORE_PITCH_NAME_F:
315         midi_note += 5;
316         break;
317     case SCORE_PITCH_NAME_G:
318         midi_note += 7;
319         break;
320     case SCORE_PITCH_NAME_A:
321         midi_note += 9;
322         break;
323     case SCORE_PITCH_NAME_B:
324         midi_note += 11;
325         break;
326     }
327
328     switch (SCORE_PITCH_ACCIDENTAL (pitch)) {
329     case SCORE_PITCH_ACCIDENTAL_DOUBLE_FLAT:
330         midi_note -= 2;
331         break;
332     case SCORE_PITCH_ACCIDENTAL_FLAT:
333         midi_note -= 1;
334         break;
335     case SCORE_PITCH_ACCIDENTAL_NATURAL:
336         break;
337     case SCORE_PITCH_ACCIDENTAL_SHARP:
338         midi_note += 1;
339         break;
340     case SCORE_PITCH_ACCIDENTAL_DOUBLE_SHARP:
341         midi_note += 2;
342         break;
343     }
344
345     return midi_note;
346 }
347
348 static void
349 _midi_to_score_pitch_and_octave (unsigned char midi_note,
350                                  score_pitch_t *pitch,
351                                  int *octave)
352 {
353     *octave = midi_note / 12 - 1;
354
355     switch (midi_note % 12)
356     {
357     case 0:
358         *pitch = SCORE_PITCH_C;
359         break;
360     case 1:
361         *pitch = SCORE_PITCH_Cs;
362         break;
363     case 2:
364         *pitch = SCORE_PITCH_D;
365         break;
366     case 3:
367         *pitch = SCORE_PITCH_Ds;
368         break;
369     case 4:
370         *pitch = SCORE_PITCH_E;
371         break;
372     case 5:
373         *pitch = SCORE_PITCH_F;
374         break;
375     case 6:
376         *pitch = SCORE_PITCH_Fs;
377         break;
378     case 7:
379         *pitch = SCORE_PITCH_G;
380         break;
381     case 8:
382         *pitch = SCORE_PITCH_Gs;
383         break;
384     case 9:
385         *pitch = SCORE_PITCH_A;
386         break;
387     case 10:
388         *pitch = SCORE_PITCH_As;
389         break;
390     case 11:
391         *pitch = SCORE_PITCH_B;
392         break;
393     }
394 }
395
396 /* Determine a chord name (if any) from the current notes pressed */
397
398 typedef struct analyzed_note {
399     /* Original note being analzyed. */
400     score_note_t *note;
401
402     /* Absolute pitch (expressed as midi number). */
403     int midi_pitch;
404
405     /* Pitch relative to bass note. */
406     int relative_pitch;
407 } analyzed_note_t;
408
409 static int
410 _compare_analyzed_note (const void *va, const void *vb)
411 {
412     const analyzed_note_t *a = va, *b = vb;
413
414     return a->midi_pitch - b->midi_pitch;
415 }
416
417 static int
418 _chord_signature_matches (analyzed_note_t *notes,
419                           int num_notes,
420                           int *signature_pitches,
421                           int num_signature_pitches)
422 {
423     int n, s;
424
425     for (n = 0, s = 0; s < num_signature_pitches; s++) {
426         if (n >= num_notes)
427             return 0;
428         if (notes[n].relative_pitch != signature_pitches[s])
429             return 0;
430         n++;
431         /* Skip repeated notes in chord being tested. */
432         while (n < num_notes &&
433                notes[n].relative_pitch == signature_pitches[s])
434         {
435             n++;
436         }
437     }
438
439     /* If there are fewer notes in the signature than in the chord,
440      * then there is no match. */
441     if (n < num_notes)
442             return 0;
443
444     return 1;
445 }
446
447 static void
448 scherzo_analyze_chord (scherzo_t *scherzo)
449 {
450     void *local = talloc_new (NULL);
451     analyzed_note_t *notes;
452     note_group_t *note_group;
453     unsigned i, num_notes;
454     int bass_pitch;
455     const char *chord_name = NULL;
456
457     if (scherzo->pedal_pressed)
458         note_group = &scherzo->notes_pedaled;
459     else
460         note_group = &scherzo->notes_pressed;
461
462     num_notes = note_group->num_notes;
463
464     struct { int pitches[2]; const char *name; } intervals[] = {
465         { {0, 1}, "Minor 2nd"},
466         { {0, 2}, "Major 2nd"},
467         { {0, 3}, "Minor 3rd"},
468         { {0, 4}, "Major 3rd"},
469         { {0, 5}, "Perfect 4th"},
470         { {0, 6}, "Diminished 5th/Augmented 4th"},
471         { {0, 7}, "Perfect 5th"},
472         { {0, 8}, "Minor 6th"},
473         { {0, 9}, "Major 6th"},
474         { {0, 10}, "Minor 7th"},
475         { {0, 11}, "Major 7th"}
476     };
477
478     struct { int pitches[3]; const char *name; } triads[] = {
479         { {0, 4, 8}, "Augmented triad" },
480         { {0, 4, 7}, "Major triad" },
481         { {0, 3, 7}, "Minor triad" },
482         { {0, 3, 6}, "Diminished triad" }
483     };
484
485     struct { int pitches[4]; const char *name; } sevenths[] = {
486         { {0, 4, 8, 11}, "Augmented/major 7" },
487         { {0, 4, 7, 11}, "Major 7" },
488         { {0, 4, 7, 10}, "Dominant 7" },
489         { {0, 3, 7, 11}, "Minor/major 7" },
490         { {0, 3, 7, 10}, "Minor 7" },
491         { {0, 3, 6, 10}, "Half-diminished 7" },
492         { {0, 3, 6, 9},  "Diminished 7" },
493         { {0, 4, 8, 10}, "Augmented 7" },
494         { {0, 3, 6, 11}, "Diminished/major 7" },
495     };
496
497     if (scherzo->chord) {
498         score_remove_chord (scherzo->chord);
499         scherzo->chord = NULL;
500     }
501
502     if (num_notes <= 1)
503         goto DONE;
504
505     notes = talloc_array (local, analyzed_note_t, num_notes);
506     if (notes == NULL)
507         goto DONE;
508
509     for (i = 0; i < num_notes; i++) {
510         score_note_t *note = note_group->notes[i];
511         notes[i].note = note;
512         notes[i].midi_pitch = _score_pitch_and_octave_to_midi (note->pitch,
513                                                                note->octave);
514         /* Relative pitch will be filled in after sorting. */
515         notes[i].relative_pitch = 0;
516     }
517
518     qsort (notes, num_notes, sizeof (analyzed_note_t), _compare_analyzed_note);
519     
520     bass_pitch = notes[0].midi_pitch;
521
522     for (i = 0; i < num_notes; i++) {
523         notes[i].relative_pitch = notes[i].midi_pitch - bass_pitch;
524         while (notes[i].relative_pitch > 12)
525             notes[i].relative_pitch -= 12;
526     }
527
528     for (i = 0; i < ARRAY_SIZE (intervals); i++) {
529         if (_chord_signature_matches (notes, num_notes, intervals[i].pitches, 2))
530             chord_name = intervals[i].name;
531     }
532
533     for (i = 0; i < ARRAY_SIZE (triads); i++) {
534         if (_chord_signature_matches (notes, num_notes, triads[i].pitches, 3))
535             chord_name = triads[i].name;
536     }
537
538     for (i = 0; i < ARRAY_SIZE(sevenths); i++) {
539         if (_chord_signature_matches (notes, num_notes, sevenths[i].pitches, 4))
540             chord_name = sevenths[i].name;
541     }
542
543     if (chord_name)
544         scherzo->chord = score_add_chord (scherzo->treble, chord_name);
545     else
546         scherzo->chord = score_add_chord (scherzo->treble, "Unknown or not a chord");
547
548 DONE:
549     talloc_free (local);
550 }
551
552 static void
553 note_group_init (void *ctx, note_group_t *group)
554 {
555     group->ctx = ctx;
556     group->notes = NULL;
557     group->size = 0;
558     group->num_notes = 0;
559 }
560
561 static void
562 note_group_add_note (note_group_t *group, score_note_t *note)
563 {
564     group->num_notes++;
565
566     if (group->num_notes > group->size) {
567         group->size++;
568         group->notes = talloc_realloc (group->ctx, group->notes,
569                                        score_note_t*, group->size);
570
571         if (group->notes == NULL) {
572             fprintf (stderr, "Out of memory.\n");
573             exit (1);
574         }
575     }
576
577     group->notes[group->num_notes - 1] = note;
578 }
579
580 static void
581 note_group_remove_note_at (note_group_t *group, int i)
582 {
583     if (i >= group->num_notes) {
584         fprintf (stderr, "Internal error: No note to remove at index %d\n", i);
585         exit (1);
586     }
587
588     if (i < group->num_notes - 1) {
589         memmove (group->notes + i, group->notes + i + 1,
590                  (group->num_notes - 1 - i) * sizeof (score_note_t*));
591     }
592     group->num_notes--;
593 }
594
595 static score_note_t *
596 scherzo_press_note (scherzo_t *scherzo, score_pitch_t pitch, int octave)
597 {
598     score_staff_t *staff;
599     score_note_t *note;
600     int i;
601
602     if (scherzo->challenge.note) {
603         staff = scherzo->challenge.staff;
604     } else if (octave >= 4) {
605         staff = scherzo->treble;
606     } else {
607         staff = scherzo->bass;
608     }
609
610     /* Do nothing if this note is already pressed. */
611     for (i = 0; i < scherzo->notes_pressed.num_notes; i++) {
612         if (scherzo->notes_pressed.notes[i]->pitch == pitch &&
613             scherzo->notes_pressed.notes[i]->octave == octave)
614         {
615             return scherzo->notes_pressed.notes[i];
616         }
617     }
618
619     note = score_add_note (staff, pitch, octave, SCORE_DURATION_WHOLE);
620
621     note_group_add_note (&scherzo->notes_pressed, note);
622
623     if (scherzo->pedal_pressed)
624         note_group_add_note (&scherzo->notes_pedaled, note);
625
626     scherzo_analyze_chord (scherzo);
627
628     return note;
629 }
630
631 static void
632 scherzo_release_note (scherzo_t *scherzo, score_pitch_t pitch, int octave)
633 {
634     score_note_t *note;
635     int i;
636     int found = 0;
637
638     for (i = scherzo->notes_pressed.num_notes - 1; i >=0; i--) {
639         note = scherzo->notes_pressed.notes[i];
640         if (note->pitch == pitch && note->octave == octave) {
641             found = 1;
642             if (! scherzo->pedal_pressed)
643                 score_remove_note (note);
644             note_group_remove_note_at (&scherzo->notes_pressed, i);
645         }
646     }
647
648     if (found == 0) {
649         fprintf (stderr, "Internal error: Failed to find note to release.\n");
650     }
651
652     scherzo_analyze_chord (scherzo);
653 }
654
655 static score_note_t *
656 scherzo_press_note_midi (scherzo_t *scherzo, unsigned char midi_note)
657 {
658     score_pitch_t pitch;
659     int octave;
660
661     _midi_to_score_pitch_and_octave (midi_note, &pitch, &octave);
662
663     return scherzo_press_note (scherzo, pitch, octave);
664 }
665
666 static void
667 scherzo_release_note_midi (scherzo_t *scherzo, unsigned char midi_note)
668 {
669     score_pitch_t pitch;
670     int octave;
671  
672     _midi_to_score_pitch_and_octave (midi_note, &pitch, &octave);
673
674     scherzo_release_note (scherzo, pitch, octave);
675 }
676
677 static void
678 scherzo_press_pedal (scherzo_t *scherzo)
679 {
680     int i;
681
682     scherzo->pedal_pressed = 1;
683
684     /* Copy all pressed notes to pedaled notes */
685     for (i = 0; i < scherzo->notes_pressed.num_notes; i++)
686         note_group_add_note (&scherzo->notes_pedaled, scherzo->notes_pressed.notes[i]);
687 }
688
689 static void
690 scherzo_release_pedal (scherzo_t *scherzo)
691 {
692     score_note_t *note, *new_note;
693     int i;
694
695     /* Make new notes in score for all pressed notes. */
696     for (i = 0; i < scherzo->notes_pressed.num_notes; i++) {
697         note = scherzo->notes_pressed.notes[i];
698         new_note = score_add_note (note->staff, note->pitch, note->octave, note->duration);
699         scherzo->notes_pressed.notes[i] = new_note;
700     }
701
702     /* Then remove all previously pedaled notes from the score. */
703     for (i = scherzo->notes_pedaled.num_notes - 1; i >=0; i--) {
704         note = scherzo->notes_pedaled.notes[i];
705         score_remove_note (note);
706         note_group_remove_note_at (&scherzo->notes_pedaled, i);
707     }
708
709     scherzo->pedal_pressed = 0;
710
711     scherzo_analyze_chord (scherzo);
712
713     gtk_widget_queue_draw (scherzo->window);
714 }
715
716 void
717 _select_challenge (scherzo_t *scherzo)
718 {
719     category_t *category_unused;
720     bool_t introduced_unused;
721     item_t *item;
722     challenge_t *challenge = &scherzo->challenge;
723     score_pitch_t pitch;
724     int octave;
725     char *s;
726
727     if (challenge->note) {
728         score_remove_note (challenge->note);
729         challenge->note = NULL;
730     }
731
732     mnemon_select_item (&scherzo->mnemon,
733                         &challenge->bin,
734                         &challenge->item_index,
735                         &category_unused,
736                         &introduced_unused);
737
738     item = challenge->bin->items[challenge->item_index];
739
740     s = item->challenge;
741     if (strncmp (s, "treble:", 7) == 0) {
742         s += 7;
743         challenge->staff = scherzo->treble;
744     } else if (strncmp (s, "bass:", 5) == 0) {
745         s += 5;
746         challenge->staff = scherzo->bass;
747     } else {
748         fprintf (stderr,
749                  "Malformed staff name: %s (expected 'treble:' or 'bass:')\n",
750                  s);
751         exit (1);
752     }
753
754     switch (*s) {
755     case 'C':
756         pitch = SCORE_PITCH_VALUE(C, NATURAL);
757         break;
758     case 'D':
759         pitch = SCORE_PITCH_VALUE(D, NATURAL);
760         break;
761     case 'E':
762         pitch = SCORE_PITCH_VALUE(E, NATURAL);
763         break;
764     case 'F':
765         pitch = SCORE_PITCH_VALUE(F, NATURAL);
766         break;
767     case 'G':
768         pitch = SCORE_PITCH_VALUE(G, NATURAL);
769         break;
770     case 'A':
771         pitch = SCORE_PITCH_VALUE(A, NATURAL);
772         break;
773     case 'B':
774         pitch = SCORE_PITCH_VALUE(B, NATURAL);
775         break;
776     default:
777         fprintf (stderr, "Malformed pitch name: %s (expected 'A' - 'G')\n", s);
778         exit (1);
779     }
780     s++;
781
782     if (*s < '0' || *s > '9') {
783         fprintf (stderr, "Malformed octave number: %s (expected '0' - '9')\n", s);
784         exit (1);
785     }
786
787     octave = *s - '0';
788
789     challenge->note = score_add_note (challenge->staff, pitch, octave,
790                                       SCORE_DURATION_WHOLE);
791     challenge->satisfied = 0;
792     challenge->mistaken = 0;
793 }
794
795 /* Determine whether the user hit the correct note. */
796 static void
797 _judge_note (scherzo_t *scherzo, score_note_t *note)
798 {
799     challenge_t *challenge = &scherzo->challenge;
800
801     if (! scherzo->challenge.note) {
802         score_set_note_color_rgb (note, 0.0, 0.0, 0.0); /* black */
803         return;
804     }
805
806     if (note->pitch == challenge->note->pitch &&
807         note->octave == challenge->note->octave)
808     {
809         challenge->satisfied = 1;
810         score_set_note_color_rgb (note, 18/256., 130/256., 28/256.); /* green */
811     }
812     else
813     {
814         challenge->mistaken = 1;
815         score_set_note_color_rgb (note, 184/256., 4/256., 22/256.); /* red */
816     }
817 }
818
819 /* If the user got the right note (eventually), then score it in
820  * mnemon and show the next note. */
821 static void
822 _score_challenge (scherzo_t *scherzo)
823 {
824     challenge_t *challenge = &scherzo->challenge;
825
826     if (! challenge->note)
827         return;
828
829     if (! challenge->satisfied)
830         return;
831
832     mnemon_score_item (&scherzo->mnemon, challenge->bin, challenge->item_index,
833                        ! challenge->mistaken);
834
835     _select_challenge (scherzo);
836 }
837
838 static int
839 on_midi_input (unused (GIOChannel *channel),
840                unused (GIOCondition condition),
841                void *user_data)
842 {
843     unsigned char buf[MIDI_BUF_SIZE], *next;
844     scherzo_t *scherzo = user_data;
845     ssize_t remaining;
846     snd_seq_event_t event;
847     score_note_t *note;
848     int need_redraw = FALSE;
849
850     remaining = read (scherzo->midi_fd, buf, MIDI_BUF_SIZE);
851
852     next = buf;
853     while (remaining) {
854         long consumed;
855
856         consumed = snd_midi_event_encode (scherzo->snd_midi_event,
857                                           next, remaining, &event);
858
859         remaining -= consumed;
860         next += consumed;
861
862         switch (event.type) {
863         case SND_SEQ_EVENT_NONE:
864             /* Incomplete event. Nothing to do. */
865             break;
866         case SND_SEQ_EVENT_NOTEON:
867             note = scherzo_press_note_midi (scherzo, event.data.note.note);
868             _judge_note (scherzo, note);
869             need_redraw = TRUE;
870             break;
871         case SND_SEQ_EVENT_NOTEOFF:
872             scherzo_release_note_midi (scherzo, event.data.note.note);
873             _score_challenge (scherzo);
874             need_redraw = TRUE;
875             break;
876         case SND_SEQ_EVENT_CLOCK:
877             /* Ignore for now as my piano sends a constant stream of these. */
878             break;
879         case SND_SEQ_EVENT_SENSING:
880             /* Ignore for now as my piano sends a constant stream of these. */
881             break;
882         case SND_SEQ_EVENT_CONTROLLER:
883             /* XXX: My piano gives me 64 for the sustain pedal, is
884              * that universal? */
885             if (event.data.control.param == 64) {
886                 if (event.data.control.value == 0)
887                     scherzo_release_pedal (scherzo);
888                 else
889                     scherzo_press_pedal (scherzo);
890             } else {
891                 fprintf (stderr, "Fixme: Unhandled MIDI Control event (param=%d, value=%d)\n",
892                          event.data.control.param, event.data.control.value);
893             }
894             break;
895         default:
896             fprintf (stderr, "Fixme: Do not yet know how to handle MIDI event %d\n",
897                      event.type);
898             break;
899         }
900     }
901
902     if (need_redraw)
903         gtk_widget_queue_draw (scherzo->window);
904
905     /* Return TRUE to continue to get called in the future. */
906     return TRUE;
907 }
908
909 int
910 main (int argc, char *argv[])
911 {
912     GtkWidget *drawing_area;
913     scherzo_t scherzo;
914     int err;
915
916     srand (time (NULL));
917
918     gtk_init (&argc, &argv);
919
920     scherzo.ctx = talloc_new (NULL);
921
922     scherzo.score = score_create (scherzo.ctx);
923     scherzo.staff_height = 100;
924     score_set_staff_height (scherzo.score, scherzo.staff_height);
925
926     score_add_brace (scherzo.score, 2);
927     scherzo.treble = score_add_staff (scherzo.score, SCORE_CLEF_G);
928     scherzo.bass = score_add_staff (scherzo.score, SCORE_CLEF_F);
929
930     scherzo.chord = NULL;
931
932     /* Default to octave 4 for computer keyboard keypresses. */
933     scherzo.keyboard_octave = 4;
934
935     note_group_init (scherzo.ctx, &scherzo.notes_pressed);
936     note_group_init (scherzo.ctx, &scherzo.notes_pedaled);
937
938     scherzo.pedal_pressed = 0;
939
940     mnemon_init (&scherzo.mnemon);
941     /* XXX: Should create a default file if one cannot be loaded. */
942     mnemon_load_category (&scherzo.mnemon, "scherzo-notes");
943
944     scherzo.challenge.note = NULL;
945 /*
946     _select_challenge (&scherzo);
947 */
948
949     err = snd_midi_event_new (MIDI_BUF_SIZE, &scherzo.snd_midi_event);
950     if (err) {
951         fprintf (stderr, "Out of memory.\n");
952         return 1;
953     }
954
955 #define MIDI_DEVICE "/dev/midi1"
956     scherzo.midi_fd = open (MIDI_DEVICE, O_RDONLY);
957     if (scherzo.midi_fd < 0) {
958         printf ("failed to open " MIDI_DEVICE ". Midi input will not be available.\n");
959     } else {
960         GIOChannel *channel;
961
962         channel = g_io_channel_unix_new (scherzo.midi_fd);
963         g_io_channel_set_encoding (channel, NULL, NULL);
964         g_io_add_watch (channel, G_IO_IN, on_midi_input, &scherzo);
965     }
966
967     scherzo.window = gtk_window_new (GTK_WINDOW_TOPLEVEL);
968
969     gtk_window_set_default_size (GTK_WINDOW (scherzo.window), 1000, 600);
970
971     g_signal_connect (scherzo.window, "delete-event",
972                       G_CALLBACK (on_delete_event_quit), NULL);
973
974     drawing_area = gtk_drawing_area_new ();
975
976     gtk_container_add (GTK_CONTAINER (scherzo.window), drawing_area);
977
978     g_signal_connect (drawing_area, "expose-event",  
979                       G_CALLBACK (on_expose_event_draw),
980                       &scherzo);
981
982     g_signal_connect (scherzo.window, "key-press-event",
983                       G_CALLBACK (on_key_press_event),
984                       &scherzo);
985
986     g_signal_connect (scherzo.window, "key-release-event",
987                       G_CALLBACK (on_key_release_event),
988                       &scherzo);
989     
990     gtk_widget_show_all (scherzo.window);
991     
992     gtk_main ();
993
994     mnemon_save (&scherzo.mnemon);
995
996     snd_midi_event_free (scherzo.snd_midi_event);
997
998     talloc_free (scherzo.ctx);
999
1000     return 0;
1001 }