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