]> git.cworth.org Git - scherzo/blob - scherzo.c
Add recognition of 6, m6, and 7-flat-5 chords.
[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,
493                           score_pitch_t *root)
494 {
495 #define MAX_DEGREES 4
496     int relative_pitches[MAX_DEGREES];
497     int i, root_index;
498
499     assert (num_degrees <= MAX_DEGREES);
500
501     if (num_notes != num_degrees)
502         return 0;
503
504     if (inversion >= num_degrees)
505         return 0;
506
507     /* We never spell simple intervals as inversions. */
508     if (num_degrees == 2 && inversion > 0)
509         return 0;
510
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             return 0;
527
528     root_index = (num_notes - inversion) % num_notes;
529     *root = notes[root_index].note->pitch;
530
531     return 1;
532 }
533
534 static const char *
535 _pitch_str (score_pitch_t pitch)
536 {
537     switch (pitch) {
538     case SCORE_PITCH_Cff:
539         return "C𝄫";
540     case SCORE_PITCH_Cf:
541         return "C♭";
542     case SCORE_PITCH_C:
543         return "C";
544     case SCORE_PITCH_Cs:
545         return "C♯";
546     case SCORE_PITCH_Css:
547         return "C𝄪";
548     case SCORE_PITCH_Dff:
549         return "D𝄫";
550     case SCORE_PITCH_Df:
551         return "D♭";
552     case SCORE_PITCH_D:
553         return "D";
554     case SCORE_PITCH_Ds:
555         return "D♯";
556     case SCORE_PITCH_Dss:
557         return "D𝄪";
558     case SCORE_PITCH_Eff:
559         return "E𝄫";
560     case SCORE_PITCH_Ef:
561         return "E♭";
562     case SCORE_PITCH_E:
563         return "E";
564     case SCORE_PITCH_Es:
565         return "E♯";
566     case SCORE_PITCH_Ess:
567         return "E𝄪";
568     case SCORE_PITCH_Fff:
569         return "F𝄫";
570     case SCORE_PITCH_Ff:
571         return "F♭";
572     case SCORE_PITCH_F:
573         return "F";
574     case SCORE_PITCH_Fs:
575         return "F♯";
576     case SCORE_PITCH_Fss:
577         return "F𝄪";
578     case SCORE_PITCH_Gff:
579         return "G𝄫";
580     case SCORE_PITCH_Gf:
581         return "G♭";
582     case SCORE_PITCH_G:
583         return "G";
584     case SCORE_PITCH_Gs:
585         return "G♯";
586     case SCORE_PITCH_Gss:
587         return "G𝄪";
588     case SCORE_PITCH_Aff:
589         return "A𝄫";
590     case SCORE_PITCH_Af:
591         return "A♭";
592     case SCORE_PITCH_A:
593         return "A";
594     case SCORE_PITCH_As:
595         return "A♯";
596     case SCORE_PITCH_Ass:
597         return "A𝄪";
598     case SCORE_PITCH_Bff:
599         return "B𝄫";
600     case SCORE_PITCH_Bf:
601         return "B♭";
602     case SCORE_PITCH_B:
603         return "B";
604     case SCORE_PITCH_Bs:
605         return "B♯";
606     case SCORE_PITCH_Bss:
607         return "B𝄪";
608     }
609
610     fprintf (stderr, "Internal error: Unknown pitch %d\n", pitch);
611     exit (1);
612 }
613
614 static void
615 scherzo_analyze_chord (scherzo_t *scherzo)
616 {
617     void *local = talloc_new (NULL);
618     analyzed_note_t *notes;
619     note_group_t *note_group;
620     unsigned i, j, num_notes;
621     int bass_pitch, inversion;
622     score_pitch_t root;
623     const char *chord_name = NULL;
624
625     if (scherzo->pedal_pressed)
626         note_group = &scherzo->notes_pedaled;
627     else
628         note_group = &scherzo->notes_pressed;
629
630     num_notes = note_group->num_notes;
631
632     struct { modified_degree_t degrees[1]; const char *name; } octaves[] = {
633         { {{1, 0}}, " Octave"}
634     };
635
636     struct { modified_degree_t degrees[2]; const char *name; } intervals[] = {
637         { {{1, 0}, {2, -1}}, " Minor 2nd"},
638         { {{1, 0}, {2,  0}}, " Major 2nd"},
639         { {{1, 0}, {3, -1}}, " Minor 3rd"},
640         { {{1, 0}, {3,  0}}, " Major 3rd"},
641         { {{1, 0}, {4,  0}}, " Perfect 4th"},
642         { {{1, 0}, {5, -1}}, " Diminished 5th"},
643         { {{1, 0}, {5,  0}}, " Perfect 5th"},
644         { {{1, 0}, {6, -1}}, " Minor 6th"},
645         { {{1, 0}, {6,  0}}, " Major 6th"},
646         { {{1, 0}, {7, -1}}, " Minor 7th"},
647         { {{1, 0}, {7,  0}}, " Major 7th"}
648     };
649
650 /* XXX: The superscript rise value should be relative to the current
651  * font size. Best would be for pango to support this. See:
652  *
653  * https://bugzilla.gnome.org/show_bug.cgi?id=708780
654  *
655  * For now, these are emipirically-derived values that look reasonable
656  * at the default size that score.c is using to draw the staff. If the
657  * user scales the staff up or down then these will look wrong.
658  */
659
660 #define SUP "<span font='33' rise='30000'>"
661 #define PUS "</span>"
662
663     struct { modified_degree_t degrees[3]; const char *name; } triads[] = {
664         { {{1, 0}, {3,  0}, {5, +1}}, SUP "+" PUS },
665         { {{1, 0}, {3,  0}, {5,  0}}, "" },
666         { {{1, 0}, {3, -1}, {5,  0}}, "m" },
667         { {{1, 0}, {3, -1}, {5, -1}}, "°" }
668     };
669
670     struct { modified_degree_t degrees[4]; const char *name; } tetrachords[] = {
671         /* Sixth chords */
672         { {{1, 0}, {3,  0}, {5,  0}, {6,  0}}, "6" },
673         { {{1, 0}, {3, -1}, {5,  0}, {6,  0}}, "m6" },
674         /* Seventh chords */
675         { {{1, 0}, {3,  0}, {5, +1}, {7,  0}}, SUP "+M7" PUS },
676         { {{1, 0}, {3,  0}, {5, +1}, {7, -1}}, SUP "+7" PUS },
677         { {{1, 0}, {3,  0}, {5,  0}, {7,  0}}, "M7" },
678         { {{1, 0}, {3,  0}, {5,  0}, {7, -1}}, "7" },
679         { {{1, 0}, {3,  0}, {5, -1}, {7, -1}}, SUP "7♭5" PUS },
680         { {{1, 0}, {3, -1}, {5,  0}, {7,  0}}, "m" SUP "M7" PUS },
681         { {{1, 0}, {3, -1}, {5,  0}, {7, -1}}, "m7" },
682         { {{1, 0}, {3, -1}, {5, -1}, {7,  0}}, "°" SUP "M7" PUS },
683         { {{1, 0}, {3, -1}, {5, -1}, {7, -1}}, "𝆩" SUP "7" PUS },
684         { {{1, 0}, {3, -1}, {5, -1}, {7, -2}}, "°" SUP "7" PUS }
685     };
686
687     if (scherzo->chord) {
688         score_remove_chord (scherzo->chord);
689         scherzo->chord = NULL;
690     }
691
692     if (num_notes <= 1)
693         goto DONE;
694
695     notes = talloc_array (local, analyzed_note_t, num_notes);
696     if (notes == NULL)
697         goto DONE;
698
699     for (i = 0; i < num_notes; i++) {
700         score_note_t *note = note_group->notes[i];
701         notes[i].note = note;
702         notes[i].midi_pitch = _score_pitch_and_octave_to_midi (note->pitch,
703                                                                note->octave);
704         /* Relative pitch will be filled in after sorting. */
705         notes[i].relative_pitch = 0;
706     }
707
708     /* First, sort by midi pitch to find the bass note. */
709     qsort (notes, num_notes, sizeof (analyzed_note_t),
710            _compare_analyzed_note_by_midi_pitch);
711     
712     bass_pitch = notes[0].midi_pitch;
713
714     /* With the bass note identified, we can find all relative pitches. */
715     for (i = 0; i < num_notes; i++) {
716         notes[i].relative_pitch = notes[i].midi_pitch - bass_pitch;
717         while (notes[i].relative_pitch >= 12)
718             notes[i].relative_pitch -= 12;
719     }
720
721     /* Now, sort again by relative pitch. */
722     qsort (notes, num_notes, sizeof (analyzed_note_t),
723            _compare_analyzed_note_by_relative_pitch);
724
725     /* Finally, eliminate all duplicate notes. */
726     for (i = 0; i < num_notes - 1; i++) {
727             if (notes[i+1].relative_pitch == notes[i].relative_pitch) {
728                     j = i+1;
729                     while (j < num_notes &&
730                            notes[j].relative_pitch == notes[i].relative_pitch)
731                     {
732                             j++;
733                     }
734                     /* The loop incremented j one past the last
735                      * duplicate. Decrement so that it points to the
736                      * last duplicate (and is guaranteed to not exceed
737                      * the array bounds).*/
738                     j--;
739
740                     if (j < num_notes - 1) {
741                             memmove (&notes[i+1], &notes[j+1],
742                                      (num_notes - j) * sizeof (analyzed_note_t));
743                     }
744
745                     num_notes -= (j - i);
746             }
747     }
748
749     for (inversion = 0; inversion < 4; inversion++) {
750         switch (num_notes) {
751         case 1:
752             for (i = 0; i < ARRAY_SIZE (octaves); i++) {
753                 if (_chord_signature_matches (notes, num_notes,
754                                               octaves[i].degrees, 1,
755                                               inversion, &root))
756                 {
757                     chord_name = octaves[i].name;
758                     goto CHORD_NAME_KNOWN;
759                 }
760             }
761             break;
762         case 2:
763             for (i = 0; i < ARRAY_SIZE (intervals); i++) {
764                 if (_chord_signature_matches (notes, num_notes,
765                                               intervals[i].degrees, 2,
766                                               inversion, &root))
767                 {
768                     chord_name = intervals[i].name;
769                     goto CHORD_NAME_KNOWN;
770                 }
771             }
772             break;
773         case 3:
774             for (i = 0; i < ARRAY_SIZE (triads); i++) {
775                 if (_chord_signature_matches (notes, num_notes,
776                                               triads[i].degrees, 3,
777                                               inversion, &root))
778                 {
779                     chord_name = triads[i].name;
780                     goto CHORD_NAME_KNOWN;
781                 }
782             }
783             break;
784         case 4:
785             for (i = 0; i < ARRAY_SIZE(tetrachords); i++) {
786                 if (_chord_signature_matches (notes, num_notes,
787                                               tetrachords[i].degrees, 4,
788                                               inversion, &root))
789                 {
790                     chord_name = tetrachords[i].name;
791                     goto CHORD_NAME_KNOWN;
792                 }
793             }
794             break;
795         }
796     }
797     CHORD_NAME_KNOWN:
798
799     if (chord_name) {
800         if (inversion) {
801             const char *inversion_str;
802             switch (inversion) {
803             case 1:
804                 inversion_str = "1st inversion";
805                 break;
806             case 2:
807                 inversion_str = "2nd inversion";
808                 break;
809             case 3:
810                 inversion_str = "3rd inversion";
811                 break;
812             default:
813                 fprintf (stderr, "Internal error: Unexpected inversion: %d\n",
814                          inversion);
815                 exit(1);
816             }
817             chord_name = talloc_asprintf (local, "%s%s %s",
818                                           _pitch_str (root),
819                                           chord_name, inversion_str);
820         } else {
821             chord_name = talloc_asprintf (local, "%s%s",
822                                           _pitch_str (root),
823                                           chord_name);
824         }
825     } else {
826         chord_name = talloc_strdup (local, "Unknown chord");
827     }
828
829     scherzo->chord = score_add_chord (scherzo->treble, chord_name);
830
831 DONE:
832     talloc_free (local);
833 }
834
835 static void
836 note_group_init (void *ctx, note_group_t *group)
837 {
838     group->ctx = ctx;
839     group->notes = NULL;
840     group->size = 0;
841     group->num_notes = 0;
842 }
843
844 static void
845 note_group_add_note (note_group_t *group, score_note_t *note)
846 {
847     int i;
848
849     /* Do nothing if note is already in group. */
850     for (i = 0; i < group->num_notes; i++) {
851         if (group->notes[i]->pitch == note->pitch &&
852             group->notes[i]->octave == note->octave)
853         {
854             return;
855         }
856     }
857
858     group->num_notes++;
859
860     if (group->num_notes > group->size) {
861         group->size++;
862         group->notes = talloc_realloc (group->ctx, group->notes,
863                                        score_note_t*, group->size);
864
865         if (group->notes == NULL) {
866             fprintf (stderr, "Out of memory.\n");
867             exit (1);
868         }
869     }
870
871     group->notes[group->num_notes - 1] = note;
872 }
873
874 static void
875 note_group_remove_note_at (note_group_t *group, int i)
876 {
877     if (i >= group->num_notes) {
878         fprintf (stderr, "Internal error: No note to remove at index %d\n", i);
879         exit (1);
880     }
881
882     if (i < group->num_notes - 1) {
883         memmove (group->notes + i, group->notes + i + 1,
884                  (group->num_notes - 1 - i) * sizeof (score_note_t*));
885     }
886     group->num_notes--;
887 }
888
889 static score_note_t *
890 scherzo_press_note (scherzo_t *scherzo, score_pitch_t pitch, int octave)
891 {
892     score_staff_t *staff;
893     score_note_t *note;
894     int i;
895
896     if (scherzo->challenge.note) {
897         staff = scherzo->challenge.staff;
898     } else if (octave >= 4) {
899         staff = scherzo->treble;
900     } else {
901         staff = scherzo->bass;
902     }
903
904     /* Do nothing if this note is already pressed. */
905     for (i = 0; i < scherzo->notes_pressed.num_notes; i++) {
906         if (scherzo->notes_pressed.notes[i]->pitch == pitch &&
907             scherzo->notes_pressed.notes[i]->octave == octave)
908         {
909             return scherzo->notes_pressed.notes[i];
910         }
911     }
912
913     note = score_add_note (staff, pitch, octave, SCORE_DURATION_WHOLE);
914
915     note_group_add_note (&scherzo->notes_pressed, note);
916
917     if (scherzo->pedal_pressed)
918         note_group_add_note (&scherzo->notes_pedaled, note);
919
920     scherzo_analyze_chord (scherzo);
921
922     return note;
923 }
924
925 static void
926 scherzo_release_note (scherzo_t *scherzo, score_pitch_t pitch, int octave)
927 {
928     score_note_t *note;
929     int i;
930     int found = 0;
931
932     for (i = scherzo->notes_pressed.num_notes - 1; i >=0; i--) {
933         note = scherzo->notes_pressed.notes[i];
934         if (note->pitch == pitch && note->octave == octave) {
935             found = 1;
936             if (! scherzo->pedal_pressed)
937                 score_remove_note (note);
938             note_group_remove_note_at (&scherzo->notes_pressed, i);
939         }
940     }
941
942     if (found == 0) {
943         fprintf (stderr, "Internal error: Failed to find note to release.\n");
944     }
945
946     scherzo_analyze_chord (scherzo);
947 }
948
949 static score_note_t *
950 scherzo_press_note_midi (scherzo_t *scherzo, unsigned char midi_note)
951 {
952     score_pitch_t pitch;
953     int octave;
954
955     _midi_to_score_pitch_and_octave (midi_note, &pitch, &octave);
956
957     return scherzo_press_note (scherzo, pitch, octave);
958 }
959
960 static void
961 scherzo_release_note_midi (scherzo_t *scherzo, unsigned char midi_note)
962 {
963     score_pitch_t pitch;
964     int octave;
965  
966     _midi_to_score_pitch_and_octave (midi_note, &pitch, &octave);
967
968     scherzo_release_note (scherzo, pitch, octave);
969 }
970
971 static void
972 scherzo_press_pedal (scherzo_t *scherzo)
973 {
974     int i;
975
976     scherzo->pedal_pressed = 1;
977
978     /* Copy all pressed notes to pedaled notes */
979     for (i = 0; i < scherzo->notes_pressed.num_notes; i++)
980         note_group_add_note (&scherzo->notes_pedaled, scherzo->notes_pressed.notes[i]);
981 }
982
983 static void
984 scherzo_release_pedal (scherzo_t *scherzo)
985 {
986     score_note_t *note, *new_note;
987     int i;
988
989     /* Make new notes in score for all pressed notes. */
990     for (i = 0; i < scherzo->notes_pressed.num_notes; i++) {
991         note = scherzo->notes_pressed.notes[i];
992         new_note = score_add_note (note->staff, note->pitch, note->octave, note->duration);
993         scherzo->notes_pressed.notes[i] = new_note;
994     }
995
996     /* Then remove all previously pedaled notes from the score. */
997     for (i = scherzo->notes_pedaled.num_notes - 1; i >=0; i--) {
998         note = scherzo->notes_pedaled.notes[i];
999         score_remove_note (note);
1000         note_group_remove_note_at (&scherzo->notes_pedaled, i);
1001     }
1002
1003     scherzo->pedal_pressed = 0;
1004
1005     scherzo_analyze_chord (scherzo);
1006
1007     gtk_widget_queue_draw (scherzo->window);
1008 }
1009
1010 void
1011 _select_challenge (scherzo_t *scherzo)
1012 {
1013     category_t *category_unused;
1014     bool_t introduced_unused;
1015     item_t *item;
1016     challenge_t *challenge = &scherzo->challenge;
1017     score_pitch_t pitch;
1018     int octave;
1019     char *s;
1020
1021     if (challenge->note) {
1022         score_remove_note (challenge->note);
1023         challenge->note = NULL;
1024     }
1025
1026     mnemon_select_item (&scherzo->mnemon,
1027                         &challenge->bin,
1028                         &challenge->item_index,
1029                         &category_unused,
1030                         &introduced_unused);
1031
1032     item = challenge->bin->items[challenge->item_index];
1033
1034     s = item->challenge;
1035     if (strncmp (s, "treble:", 7) == 0) {
1036         s += 7;
1037         challenge->staff = scherzo->treble;
1038     } else if (strncmp (s, "bass:", 5) == 0) {
1039         s += 5;
1040         challenge->staff = scherzo->bass;
1041     } else {
1042         fprintf (stderr,
1043                  "Malformed staff name: %s (expected 'treble:' or 'bass:')\n",
1044                  s);
1045         exit (1);
1046     }
1047
1048     switch (*s) {
1049     case 'C':
1050         pitch = SCORE_PITCH_C;
1051         break;
1052     case 'D':
1053         pitch = SCORE_PITCH_D;
1054         break;
1055     case 'E':
1056         pitch = SCORE_PITCH_E;
1057         break;
1058     case 'F':
1059         pitch = SCORE_PITCH_F;
1060         break;
1061     case 'G':
1062         pitch = SCORE_PITCH_G;
1063         break;
1064     case 'A':
1065         pitch = SCORE_PITCH_A;
1066         break;
1067     case 'B':
1068         pitch = SCORE_PITCH_B;
1069         break;
1070     default:
1071         fprintf (stderr, "Malformed pitch name: %s (expected 'A' - 'G')\n", s);
1072         exit (1);
1073     }
1074     s++;
1075
1076     if (*s < '0' || *s > '9') {
1077         fprintf (stderr, "Malformed octave number: %s (expected '0' - '9')\n", s);
1078         exit (1);
1079     }
1080
1081     octave = *s - '0';
1082
1083     challenge->note = score_add_note (challenge->staff, pitch, octave,
1084                                       SCORE_DURATION_WHOLE);
1085     challenge->satisfied = 0;
1086     challenge->mistaken = 0;
1087 }
1088
1089 /* Determine whether the user hit the correct note. */
1090 static void
1091 _judge_note (scherzo_t *scherzo, score_note_t *note)
1092 {
1093     challenge_t *challenge = &scherzo->challenge;
1094
1095     if (! scherzo->challenge.note) {
1096         score_set_note_color_rgb (note, 0.0, 0.0, 0.0); /* black */
1097         return;
1098     }
1099
1100     if (note->pitch == challenge->note->pitch &&
1101         note->octave == challenge->note->octave)
1102     {
1103         challenge->satisfied = 1;
1104         score_set_note_color_rgb (note, 18/256., 130/256., 28/256.); /* green */
1105     }
1106     else
1107     {
1108         challenge->mistaken = 1;
1109         score_set_note_color_rgb (note, 184/256., 4/256., 22/256.); /* red */
1110     }
1111 }
1112
1113 /* If the user got the right note (eventually), then score it in
1114  * mnemon and show the next note. */
1115 static void
1116 _score_challenge (scherzo_t *scherzo)
1117 {
1118     challenge_t *challenge = &scherzo->challenge;
1119
1120     if (! challenge->note)
1121         return;
1122
1123     if (! challenge->satisfied)
1124         return;
1125
1126     mnemon_score_item (&scherzo->mnemon, challenge->bin, challenge->item_index,
1127                        ! challenge->mistaken);
1128
1129     _select_challenge (scherzo);
1130 }
1131
1132 static int
1133 on_midi_input (unused (GIOChannel *channel),
1134                unused (GIOCondition condition),
1135                void *user_data)
1136 {
1137     unsigned char buf[MIDI_BUF_SIZE], *next;
1138     scherzo_t *scherzo = user_data;
1139     ssize_t remaining;
1140     snd_seq_event_t event;
1141     score_note_t *note;
1142     int need_redraw = FALSE;
1143
1144     remaining = read (scherzo->midi_fd, buf, MIDI_BUF_SIZE);
1145
1146     next = buf;
1147     while (remaining) {
1148         long consumed;
1149
1150         consumed = snd_midi_event_encode (scherzo->snd_midi_event,
1151                                           next, remaining, &event);
1152
1153         remaining -= consumed;
1154         next += consumed;
1155
1156         switch (event.type) {
1157         case SND_SEQ_EVENT_NONE:
1158             /* Incomplete event. Nothing to do. */
1159             break;
1160         case SND_SEQ_EVENT_NOTEON:
1161             note = scherzo_press_note_midi (scherzo, event.data.note.note);
1162             _judge_note (scherzo, note);
1163             need_redraw = TRUE;
1164             break;
1165         case SND_SEQ_EVENT_NOTEOFF:
1166             scherzo_release_note_midi (scherzo, event.data.note.note);
1167             _score_challenge (scherzo);
1168             need_redraw = TRUE;
1169             break;
1170         case SND_SEQ_EVENT_CLOCK:
1171             /* Ignore for now as my piano sends a constant stream of these. */
1172             break;
1173         case SND_SEQ_EVENT_SENSING:
1174             /* Ignore for now as my piano sends a constant stream of these. */
1175             break;
1176         case SND_SEQ_EVENT_CONTROLLER:
1177             /* XXX: My piano gives me 64 for the sustain pedal, is
1178              * that universal? */
1179             if (event.data.control.param == 64) {
1180                 if (event.data.control.value == 0)
1181                     scherzo_release_pedal (scherzo);
1182                 else
1183                     scherzo_press_pedal (scherzo);
1184             } else {
1185                 fprintf (stderr, "Fixme: Unhandled MIDI Control event (param=%d, value=%d)\n",
1186                          event.data.control.param, event.data.control.value);
1187             }
1188             break;
1189         default:
1190             fprintf (stderr, "Fixme: Do not yet know how to handle MIDI event %d\n",
1191                      event.type);
1192             break;
1193         }
1194     }
1195
1196     if (need_redraw)
1197         gtk_widget_queue_draw (scherzo->window);
1198
1199     /* Return TRUE to continue to get called in the future. */
1200     return TRUE;
1201 }
1202
1203 int
1204 main (int argc, char *argv[])
1205 {
1206     GtkWidget *drawing_area;
1207     scherzo_t scherzo;
1208     int err;
1209
1210     srand (time (NULL));
1211
1212     gtk_init (&argc, &argv);
1213
1214     scherzo.ctx = talloc_new (NULL);
1215
1216     scherzo.score = score_create (scherzo.ctx);
1217     scherzo.staff_height = 100;
1218     score_set_staff_height (scherzo.score, scherzo.staff_height);
1219
1220     score_add_brace (scherzo.score, 2);
1221     scherzo.treble = score_add_staff (scherzo.score, SCORE_CLEF_G);
1222     scherzo.bass = score_add_staff (scherzo.score, SCORE_CLEF_F);
1223
1224     scherzo.chord = NULL;
1225
1226     /* Default to octave 4 and natural for computer keyboard keypresses. */
1227     scherzo.keyboard_octave = 4;
1228     scherzo.keyboard_accidental = SCORE_PITCH_ACCIDENTAL_NATURAL;
1229
1230     note_group_init (scherzo.ctx, &scherzo.notes_pressed);
1231     note_group_init (scherzo.ctx, &scherzo.notes_pedaled);
1232
1233     scherzo.pedal_pressed = 0;
1234
1235     mnemon_init (&scherzo.mnemon);
1236     /* XXX: Should create a default file if one cannot be loaded. */
1237     mnemon_load_category (&scherzo.mnemon, "scherzo-notes");
1238
1239     scherzo.challenge.note = NULL;
1240 /*
1241     _select_challenge (&scherzo);
1242 */
1243
1244     err = snd_midi_event_new (MIDI_BUF_SIZE, &scherzo.snd_midi_event);
1245     if (err) {
1246         fprintf (stderr, "Out of memory.\n");
1247         return 1;
1248     }
1249
1250 #define MIDI_DEVICE "/dev/midi1"
1251     scherzo.midi_fd = open (MIDI_DEVICE, O_RDONLY);
1252     if (scherzo.midi_fd < 0) {
1253         printf ("failed to open " MIDI_DEVICE ". Midi input will not be available.\n");
1254     } else {
1255         GIOChannel *channel;
1256
1257         channel = g_io_channel_unix_new (scherzo.midi_fd);
1258         g_io_channel_set_encoding (channel, NULL, NULL);
1259         g_io_add_watch (channel, G_IO_IN, on_midi_input, &scherzo);
1260     }
1261
1262     scherzo.window = gtk_window_new (GTK_WINDOW_TOPLEVEL);
1263
1264     gtk_window_set_default_size (GTK_WINDOW (scherzo.window), 1000, 600);
1265
1266     g_signal_connect (scherzo.window, "delete-event",
1267                       G_CALLBACK (on_delete_event_quit), NULL);
1268
1269     drawing_area = gtk_drawing_area_new ();
1270
1271     gtk_container_add (GTK_CONTAINER (scherzo.window), drawing_area);
1272
1273     g_signal_connect (drawing_area, "expose-event",  
1274                       G_CALLBACK (on_expose_event_draw),
1275                       &scherzo);
1276
1277     g_signal_connect (scherzo.window, "key-press-event",
1278                       G_CALLBACK (on_key_press_event),
1279                       &scherzo);
1280
1281     g_signal_connect (scherzo.window, "key-release-event",
1282                       G_CALLBACK (on_key_release_event),
1283                       &scherzo);
1284     
1285     gtk_widget_show_all (scherzo.window);
1286     
1287     gtk_main ();
1288
1289     mnemon_save (&scherzo.mnemon);
1290
1291     snd_midi_event_free (scherzo.snd_midi_event);
1292
1293     talloc_free (scherzo.ctx);
1294
1295     return 0;
1296 }