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