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