]> git.cworth.org Git - scherzo/blob - scherzo.c
6a5f2b3176c7f441fdf097714746705a74a91a2c
[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) ((int) (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     int active;
36     bin_t *bin;
37     int item_index;
38     score_staff_t *staff;
39     pitch_t pitch;
40
41     int satisfied;
42     int mistaken;
43 } challenge_t;
44
45 typedef struct pitch_group
46 {
47     void *ctx;
48     pitch_t *pitches;
49     int size;
50     int num_pitches;
51 } pitch_group_t;
52
53 typedef struct scherzo
54 {
55     void *ctx;
56
57     GtkWidget *window;
58     score_t *score;
59     int staff_height;
60
61     score_staff_t *treble;
62     score_staff_t *bass;
63     score_chord_t *chord;
64
65     /* The word "keyboard" here is referring to a "computer
66      * keyboard". Any "piano keyboard" key knows its own octave and
67      * accidental already. */
68     int keyboard_octave;
69     pitch_accidental_t keyboard_accidental;
70
71     int midi_fd;
72     snd_midi_event_t *snd_midi_event;
73
74     mnemon_t mnemon;
75     challenge_t challenge;
76
77     pitch_group_t notes_pressed;
78     pitch_group_t notes_pedaled;
79
80     int pedal_pressed;
81 } scherzo_t;
82
83 /* Forward declarations. */
84 static void
85 scherzo_press_note (scherzo_t *scherzo, pitch_t pitch);
86
87 static void
88 scherzo_release_note (scherzo_t *scherzo, pitch_t pitch);
89
90 static void
91 scherzo_press_pedal (scherzo_t *scherzo);
92
93 static void
94 scherzo_release_pedal (scherzo_t *scherzo);
95
96 static void
97 _judge_pitch (scherzo_t *scherzo, pitch_t pitch);
98
99 static void
100 _score_challenge (scherzo_t *scherzo);
101
102 static int
103 on_delete_event_quit (unused (GtkWidget *widget),
104                       unused (GdkEvent *event),
105                       unused (gpointer user_data))
106 {
107     gtk_main_quit ();
108
109     /* Returning FALSE allows the default handler for delete-event
110      * to proceed to cleanup the widget. */
111     return FALSE;
112 }
113
114 static int
115 on_expose_event_draw (GtkWidget *widget,
116                       unused (GdkEventExpose *expose),
117                       void * user_data)
118 {
119     scherzo_t *scherzo = user_data;
120     score_t *score = scherzo->score;
121     cairo_t *cr;
122     GtkAllocation allocation;
123     static const int pad = 10;
124     int widget_width;
125
126     gtk_widget_get_allocation (widget, &allocation);
127     widget_width = allocation.width;
128
129     cr = gdk_cairo_create (widget->window);
130
131     /* White background */
132     cairo_set_source_rgb (cr, 1.0, 1.0, 1.0);
133     cairo_paint (cr);
134
135     /* Add some padding on the sides and top */
136     cairo_translate (cr, pad, scherzo->staff_height);
137     score_set_staff_height (score, scherzo->staff_height);
138     score_set_width (score, widget_width - 2 * pad);
139
140     score_draw (score, cr);
141  
142     return TRUE;
143 }
144
145 static int
146 on_key_press_event (GtkWidget *widget,
147                     GdkEventKey *key,
148                     void *user_data)
149 {
150     scherzo_t *scherzo = user_data;
151     int octave;
152     /* Initialize to keep the compiler quiet. */
153     pitch_name_t pitch_name = PITCH_NATURAL (C, 0);
154     pitch_t pitch;
155
156     if (scherzo->challenge.active)
157         octave = PITCH_OCTAVE (scherzo->challenge.pitch);
158     else
159         octave = scherzo->keyboard_octave;
160
161     switch (key->keyval) {
162     case GDK_KEY_plus:
163     case GDK_KEY_KP_Add:
164     case GDK_KEY_equal:
165     case GDK_KEY_KP_Equal:
166         scherzo->staff_height += 4;
167         gtk_widget_queue_draw (widget);
168         return TRUE;
169         break;
170     case GDK_KEY_minus:
171     case GDK_KEY_KP_Subtract:
172         scherzo->staff_height -= 4;
173         gtk_widget_queue_draw (widget);
174         return TRUE;
175         break;
176     case GDK_KEY_q:
177     case GDK_KEY_Q:
178     case GDK_KEY_Escape:
179         gtk_main_quit ();
180         return FALSE;
181     case GDK_KEY_c:
182     case GDK_KEY_C:
183         pitch_name = PITCH_NAME_C;
184         break;
185     case GDK_KEY_d:
186     case GDK_KEY_D:
187         pitch_name = PITCH_NAME_D;
188         break;
189     case GDK_KEY_e:
190     case GDK_KEY_E:
191         pitch_name = PITCH_NAME_E;
192         break;
193     case GDK_KEY_f:
194     case GDK_KEY_F:
195         pitch_name = PITCH_NAME_F;
196         break;
197     case GDK_KEY_g:
198     case GDK_KEY_G:
199         pitch_name = PITCH_NAME_G;
200         break;
201     case GDK_KEY_a:
202     case GDK_KEY_A:
203         pitch_name = PITCH_NAME_A;
204         break;
205     case GDK_KEY_b:
206     case GDK_KEY_B:
207         pitch_name = PITCH_NAME_B;
208         break;
209     case GDK_KEY_0:
210     case GDK_KEY_1:
211     case GDK_KEY_2:
212     case GDK_KEY_3:
213     case GDK_KEY_4:
214     case GDK_KEY_5:
215     case GDK_KEY_6:
216     case GDK_KEY_7:
217     case GDK_KEY_8:
218         scherzo->keyboard_octave = key->keyval - GDK_KEY_0;
219         break;
220     case GDK_KEY_space:
221         scherzo_press_pedal (scherzo);
222         break;
223     case GDK_KEY_Up:
224         if (scherzo->keyboard_accidental < PITCH_ACCIDENTAL_DOUBLE_SHARP)
225             scherzo->keyboard_accidental++;
226         break;
227     case GDK_KEY_Down:
228         if (scherzo->keyboard_accidental > PITCH_ACCIDENTAL_DOUBLE_FLAT)
229             scherzo->keyboard_accidental--;
230         break;
231     }
232
233     pitch = PITCH (pitch_name, scherzo->keyboard_accidental, octave);
234
235     if ((key->keyval >= GDK_KEY_A && key->keyval <= GDK_KEY_G) ||
236         (key->keyval >= GDK_KEY_a && key->keyval <= GDK_KEY_g))
237     {
238         scherzo_press_note (scherzo, pitch);
239         _judge_pitch (scherzo, pitch);
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     pitch_name_t pitch_name = PITCH_NAME_C;
259     pitch_t pitch;
260
261     if (scherzo->challenge.active)
262         octave = PITCH_OCTAVE (scherzo->challenge.pitch);
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 = PITCH_NAME_C;
270         break;
271     case GDK_KEY_d:
272     case GDK_KEY_D:
273         pitch_name = PITCH_NAME_D;
274         break;
275     case GDK_KEY_e:
276     case GDK_KEY_E:
277         pitch_name = PITCH_NAME_E;
278         break;
279     case GDK_KEY_f:
280     case GDK_KEY_F:
281         pitch_name = PITCH_NAME_F;
282         break;
283     case GDK_KEY_g:
284     case GDK_KEY_G:
285         pitch_name = PITCH_NAME_G;
286         break;
287     case GDK_KEY_a:
288     case GDK_KEY_A:
289         pitch_name = PITCH_NAME_A;
290         break;
291     case GDK_KEY_b:
292     case GDK_KEY_B:
293         pitch_name = PITCH_NAME_B;
294         break;
295     case GDK_KEY_space:
296         scherzo_release_pedal (scherzo);
297         break;
298     }
299
300     pitch = PITCH (pitch_name, scherzo->keyboard_accidental, octave);
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);
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 _pitch_to_midi (pitch_t pitch)
319 {
320     int octave = PITCH_OCTAVE (pitch);
321     unsigned char midi_note = 12 * (octave + 1);
322
323     switch (PITCH_NAME (pitch)) {
324     case PITCH_NAME_C:
325         break;
326     case PITCH_NAME_D:
327         midi_note += 2;
328         break;
329     case PITCH_NAME_E:
330         midi_note += 4;
331         break;
332     case PITCH_NAME_F:
333         midi_note += 5;
334         break;
335     case PITCH_NAME_G:
336         midi_note += 7;
337         break;
338     case PITCH_NAME_A:
339         midi_note += 9;
340         break;
341     case PITCH_NAME_B:
342         midi_note += 11;
343         break;
344     }
345
346     switch (PITCH_ACCIDENTAL (pitch)) {
347     case PITCH_ACCIDENTAL_DOUBLE_FLAT:
348         midi_note -= 2;
349         break;
350     case PITCH_ACCIDENTAL_FLAT:
351         midi_note -= 1;
352         break;
353     case PITCH_ACCIDENTAL_NATURAL:
354         break;
355     case PITCH_ACCIDENTAL_SHARP:
356         midi_note += 1;
357         break;
358     case PITCH_ACCIDENTAL_DOUBLE_SHARP:
359         midi_note += 2;
360         break;
361     }
362
363     return midi_note;
364 }
365
366 /* octave can optionally by NULL */
367 static pitch_t
368 _midi_to_pitch (unsigned char midi_note)
369 {
370     int octave = octave = midi_note / 12 - 1;
371
372     switch (midi_note % 12)
373     {
374     default:
375     case 0:
376         return PITCH_LITERAL (C, NATURAL, octave);
377         break;
378     case 1:
379         return PITCH_LITERAL (C, SHARP, octave);
380         break;
381     case 2:
382         return PITCH_LITERAL (D, NATURAL, octave);
383         break;
384     case 3:
385         return PITCH_LITERAL (D, SHARP, octave);
386         break;
387     case 4:
388         return PITCH_LITERAL (E, NATURAL, octave);
389         break;
390     case 5:
391         return PITCH_LITERAL (F, NATURAL, octave);
392         break;
393     case 6:
394         return PITCH_LITERAL (F, SHARP, octave);
395         break;
396     case 7:
397         return PITCH_LITERAL (G, NATURAL, octave);
398         break;
399     case 8:
400         return PITCH_LITERAL (G, SHARP, octave);
401         break;
402     case 9:
403         return PITCH_LITERAL (A, NATURAL, octave);
404         break;
405     case 10:
406         return PITCH_LITERAL (A, SHARP, octave);
407         break;
408     case 11:
409         return PITCH_LITERAL (B, NATURAL, octave);
410         break;
411     }
412 }
413
414 /* Return true if 'a' and 'b' sound identical, (even if spelled differently)
415  *
416  * This comparison considers octaves as significant. So Bb and A# in
417  * the same octave are considered enharmonic, but Bb and A# in
418  * different octaves are not. */
419 static int
420 _pitches_are_enharmonic (pitch_t a, pitch_t b)
421 {
422     return _pitch_to_midi (a) == _pitch_to_midi (b);
423 }
424
425 /* Determine a chord name (if any) from the current notes pressed */
426
427 typedef struct analyzed_pitch {
428     /* Original note being analzyed. */
429     pitch_t pitch;
430
431     /* Absolute pitch (expressed as midi number). */
432     int midi_pitch;
433
434     /* Pitch relative to bass note. */
435     int relative_pitch;
436 } analyzed_pitch_t;
437
438 static int
439 _compare_analyzed_pitch_by_midi_pitch (const void *va, const void *vb)
440 {
441     const analyzed_pitch_t *a = va, *b = vb;
442
443     return a->midi_pitch - b->midi_pitch;
444 }
445
446 static int
447 _compare_analyzed_pitch_by_relative_pitch (const void *va, const void *vb)
448 {
449     const analyzed_pitch_t *a = va, *b = vb;
450
451     return a->relative_pitch - b->relative_pitch;
452 }
453
454 typedef struct modified_degree
455 {
456     int degree;
457     int modification;
458 } modified_degree_t;
459
460 static int
461 _modified_degree_to_half_steps (const modified_degree_t *degree)
462 {
463     int half_steps;
464     int scale_degree = degree->degree;
465
466     /* Restrict to actual degrees within a scale. */
467     if (scale_degree > 7)
468         scale_degree = (scale_degree % 8) + 1;
469
470     /* Number of half steps from root to specified degree within a
471      * diatonic scale. */
472     switch (scale_degree) {
473     case 1:
474         half_steps = 0;
475         break;
476     case 2:
477         half_steps = 2;
478         break;
479     case 3:
480         half_steps = 4;
481         break;
482     case 4:
483         half_steps = 5;
484         break;
485     case 5:
486         half_steps = 7;
487         break;
488     case 6:
489         half_steps = 9;
490         break;
491     case 7:
492         half_steps = 11;
493         break;
494     default:
495         fprintf (stderr, "Internal: Invalid degree %d\n", degree->degree);
496         exit (1);
497         break;
498     }
499
500     return half_steps + degree->modification;
501 }
502
503 /* Number of half steps from 'root' up to 'pitch' (that is, counting
504  * the steps up a chromatic scale), within the same octave. */
505 static int
506 _pitch_from_root_in_half_steps (pitch_t pitch, pitch_t root)
507 {
508     int root_midi = _pitch_to_midi (root);
509     int pitch_midi = _pitch_to_midi (pitch);
510
511     while (pitch_midi < root_midi)
512         pitch_midi += 12;
513
514     return (pitch_midi - root_midi) % 12;
515 }
516
517 static int
518 _chord_signature_matches (analyzed_pitch_t *pitches,
519                           int num_pitches,
520                           modified_degree_t *degrees,
521                           int num_degrees,
522                           int inversion,
523                           pitch_t *root)
524 {
525 #define MAX_DEGREES 6
526     int relative_pitches[MAX_DEGREES];
527     int i, root_index;
528
529     assert (num_degrees <= MAX_DEGREES);
530
531     if (num_pitches != num_degrees)
532         return 0;
533
534     if (inversion >= num_degrees)
535         return 0;
536
537     /* We never spell simple intervals as inversions. */
538     if (num_degrees == 2 && inversion > 0)
539         return 0;
540
541     for (i = 0; i < num_degrees; i++) {
542         /* The num_degrees is in the addition just to ensure all
543          * inputs to the modulus operator remain positive. */
544         int index = (i + num_degrees - inversion) % num_degrees;
545
546         /* Again, adding a 12 to keep things positive. */
547         relative_pitches[index] =
548             (12 +
549              _modified_degree_to_half_steps (&degrees[i]) -
550              _modified_degree_to_half_steps (&degrees[inversion])) % 12;
551                 
552     }
553
554     for (i = 0; i < num_pitches; i++)
555         if (pitches[i].relative_pitch != relative_pitches[i])
556             return 0;
557
558     root_index = (num_pitches - inversion) % num_pitches;
559     *root = pitches[root_index].pitch;
560
561     return 1;
562 }
563
564 static const char *
565 _pitch_str (pitch_t pitch)
566 {
567     static char double_flat[] = "X𝄫";
568     static char flat[] = "X♭";
569     static char natural[] = "X";
570     static char sharp[] = "X♯";
571     static char double_sharp[] = "X𝄪";
572     char *ret;
573
574     switch (PITCH_ACCIDENTAL (pitch)) {
575     case PITCH_ACCIDENTAL_DOUBLE_FLAT:
576         ret = double_flat;
577         break;
578     case PITCH_ACCIDENTAL_FLAT:
579         ret = flat;
580         break;
581     case PITCH_ACCIDENTAL_NATURAL:
582         ret = natural;
583         break;
584     case PITCH_ACCIDENTAL_SHARP:
585         ret = sharp;
586         break;
587     case PITCH_ACCIDENTAL_DOUBLE_SHARP:
588         ret = double_sharp;
589         break;
590     }
591
592     switch (PITCH_NAME(pitch)) {
593     case PITCH_NAME_C:
594         ret[0] = 'C';
595         break;
596     case PITCH_NAME_D:
597         ret[0] = 'D';
598         break;
599     case PITCH_NAME_E:
600         ret[0] = 'E';
601         break;
602     case PITCH_NAME_F:
603         ret[0] = 'F';
604         break;
605     case PITCH_NAME_G:
606         ret[0] = 'G';
607         break;
608     case PITCH_NAME_A:
609         ret[0] = 'A';
610         break;
611     case PITCH_NAME_B:
612         ret[0] = 'B';
613         break;
614     }
615
616     return ret;
617 }
618
619 typedef struct chord_signature
620 {
621     int num_degrees;
622     modified_degree_t degrees[MAX_DEGREES];
623     const char *name;
624 } chord_signature_t;
625
626 /* XXX: The superscript rise value should be relative to the current
627  * font size. Best would be for pango to support this. See:
628  *
629  * https://bugzilla.gnome.org/show_bug.cgi?id=708780
630  *
631  * For now, these are emipirically-derived values that look reasonable
632  * at the default size that score.c is using to draw the staff. If the
633  * user scales the staff up or down then these will look wrong.
634  */
635
636 #define SUP "<span font='33' rise='30000'>"
637 #define PUS "</span>"
638
639 chord_signature_t signatures[] = {
640     /* Octave */
641     { 1, {{1, 0}}, "P8" },
642
643     /* Intervals */
644     { 2, {{1, 0}, {2, -1}}, "m2" },
645     { 2, {{1, 0}, {2,  0}}, "M2" },
646     { 2, {{1, 0}, {3, -1}}, "m3" },
647     { 2, {{1, 0}, {3,  0}}, "M3" },
648     { 2, {{1, 0}, {4,  0}}, "P4" },
649     { 2, {{1, 0}, {5, -1}}, "Tri-tone" },
650     { 2, {{1, 0}, {5,  0}}, "P5" },
651     { 2, {{1, 0}, {6, -1}}, "m6" },
652     { 2, {{1, 0}, {6,  0}}, "M6" },
653     { 2, {{1, 0}, {7, -1}}, "m7" },
654     { 2, {{1, 0}, {7,  0}}, "M7" },
655
656     /* Triads */
657     { 3, {{1, 0}, {4,  0}, {5,  0}}, "sus" },
658     { 3, {{1, 0}, {3,  0}, {5, +1}}, SUP "+" PUS },
659     { 3, {{1, 0}, {3,  0}, {5,  0}}, "" },
660     { 3, {{1, 0}, {3, -1}, {5,  0}}, "m" },
661     { 3, {{1, 0}, {3, -1}, {5, -1}}, "°" },
662     { 3, {{1, 0}, {2,  0}, {5,  0}}, "msus2" },
663
664     /* Seventh chords with no 3rd */
665     { 3, {{1, 0}, {5, +1}, {7,  0}}, SUP "+M7" PUS },
666     { 3, {{1, 0}, {5, +1}, {7, -1}}, SUP "+7" PUS },
667     { 3, {{1, 0}, {5,  0}, {7,  0}}, "M7" },
668     { 3, {{1, 0}, {5,  0}, {7, -1}}, "7" },
669     { 3, {{1, 0}, {5, -1}, {7, -1}}, "7♭5" },
670
671     /* Seventh chords with no 5th */
672     { 3, {{1, 0}, {4,  0}, {7,  0}}, "M7sus" },
673     { 3, {{1, 0}, {4,  0}, {7, -1}}, "7sus" },
674     { 3, {{1, 0}, {3,  0}, {7,  0}}, "M7" },
675     { 3, {{1, 0}, {3,  0}, {7, -1}}, "7" },
676     { 3, {{1, 0}, {3, -1}, {7,  0}}, "m" SUP "M7" PUS },
677     { 3, {{1, 0}, {3, -1}, {7, -1}}, "m7" },
678     { 3, {{1, 0}, {2,  0}, {7,  0}}, "m" SUP "M7" PUS "sus2" },
679     { 3, {{1, 0}, {2,  0}, {7, -1}}, "m7sus2" },
680
681     /* Sixth chords */
682     { 4, {{1, 0}, {4,  0}, {5,  0}, {6,  0}}, "6sus" },
683     { 4, {{1, 0}, {3,  0}, {5,  0}, {6,  0}}, "6" }, /* Ambiguous with m7 */
684     { 4, {{1, 0}, {3, -1}, {5,  0}, {6,  0}}, "m6" },
685     { 4, {{1, 0}, {2,  0}, {5,  0}, {6,  0}}, "m6sus2" },
686
687     /* Seventh chords */
688     { 4, {{1, 0}, {4,  0}, {5, +1}, {7,  0}}, SUP "+M7" PUS "sus" },
689     { 4, {{1, 0}, {4,  0}, {5, +1}, {7, -1}}, SUP "+7" PUS "sus" },
690     { 4, {{1, 0}, {4,  0}, {5,  0}, {7,  0}}, "M7sus" },
691     { 4, {{1, 0}, {4,  0}, {5,  0}, {7, -1}}, "7sus" },
692     { 4, {{1, 0}, {4,  0}, {5, -1}, {7, -1}}, "7♭5sus" },
693     { 4, {{1, 0}, {3,  0}, {5, +1}, {7,  0}}, SUP "+M7" PUS },
694     { 4, {{1, 0}, {3,  0}, {5, +1}, {7, -1}}, SUP "+7" PUS },
695     { 4, {{1, 0}, {3,  0}, {5,  0}, {7,  0}}, "M7" },
696     { 4, {{1, 0}, {3,  0}, {5,  0}, {7, -1}}, "7" },
697     { 4, {{1, 0}, {3,  0}, {5, -1}, {7, -1}}, "7♭5" },
698     { 4, {{1, 0}, {3, -1}, {5,  0}, {7,  0}}, "m" SUP "M7" PUS },
699     { 4, {{1, 0}, {3, -1}, {5,  0}, {7, -1}}, "m7" },
700     { 4, {{1, 0}, {3, -1}, {5, -1}, {7,  0}}, "°" SUP "M7" PUS },
701     { 4, {{1, 0}, {3, -1}, {5, -1}, {7, -1}}, "𝆩" SUP "7" PUS },
702     { 4, {{1, 0}, {3, -1}, {5, -1}, {7, -2}}, "°" SUP "7" PUS },
703     { 4, {{1, 0}, {2,  0}, {5,  0}, {7,  0}}, "m" SUP "M7" PUS "sus2" },
704     { 4, {{1, 0}, {2,  0}, {5,  0}, {7, -1}}, "m7sus2" },
705     { 4, {{1, 0}, {2,  0}, {5, -1}, {7,  0}}, "°" SUP "M7" PUS "sus2" },
706     { 4, {{1, 0}, {2,  0}, {5, -1}, {7, -1}}, "𝆩" SUP "7" PUS "sus2" },
707     { 4, {{1, 0}, {2,  0}, {5, -1}, {7, -2}}, "°" SUP "7" PUS "sus2" }, /* Ambiguous with 7 */
708
709     /* The sorting for chords with degree higher than 9 is funny
710      * to keep the array in degree order after reducing each
711      * degree to an actual scale degree, (9 -> 2, 11 -> 4, 13 ->
712      * 6) */
713
714     /* Ninth chords voiced with no 5th */
715     { 4, {{1, 0}, {9,  0}, {4,  0}, {7,  0}}, "M9sus" },
716     { 4, {{1, 0}, {9,  0}, {4,  0}, {7, -1}}, "9sus" },
717     { 4, {{1, 0}, {9,  0}, {3,  0}, {7,  0}}, "M9" },
718     { 4, {{1, 0}, {9,  0}, {3,  0}, {7, -1}}, "9" },
719     { 4, {{1, 0}, {9,  0}, {3, -1}, {7,  0}}, "m" SUP "M9" PUS },
720     { 4, {{1, 0}, {9,  0}, {3, -1}, {7, -1}}, "m9" },
721     { 4, {{1, 0}, {9, -1}, {3, -1}, {7, -1}}, "m♭9" },
722     { 4, {{1, 0}, {9,  0}, {3, -1}, {6,  0}}, "m6/9" },
723     { 4, {{1, 0}, {9, -1}, {3, -1}, {6,  0}}, "m6/♭9" },
724
725     /* Sixth plus 9 */
726     { 5, {{1, 0}, {9,  0}, {3,  0}, {5,  0}, {6,  0}}, "6/9" },
727     { 5, {{1, 0}, {9,  0}, {3, -1}, {5,  0}, {6,  0}}, "m6/9" },
728     { 5, {{1, 0}, {9, -1}, {3, -1}, {5,  0}, {6,  0}}, "m6/♭9" },
729
730     /* Seventh plus altered 9 */
731     { 5, {{1, 0}, {9, +1}, {3,  0}, {5,  0}, {7, -1}}, "7♯9" },
732     { 5, {{1, 0}, {9, -1}, {3,  0}, {5,  0}, {7, -1}}, "7♭9" },
733     { 5, {{1, 0}, {9, +1}, {3,  0}, {5, -1}, {7, -1}}, "7♭5♯9" },
734     { 5, {{1, 0}, {9, -1}, {3,  0}, {5, -1}, {7, -1}}, "7♭5♭9" },
735
736     /* Ninth chords */
737     { 5, {{1, 0}, {9,  0}, {4,  0}, {5, +1}, {7,  0}}, SUP "+M9" PUS "sus" },
738     { 5, {{1, 0}, {9,  0}, {4,  0}, {5, +1}, {7, -1}}, SUP "+9" PUS "sus" },
739     { 5, {{1, 0}, {9,  0}, {4,  0}, {5,  0}, {7,  0}}, "M9sus" },
740     { 5, {{1, 0}, {9,  0}, {4,  0}, {5,  0}, {7, -1}}, "9sus" },
741     { 5, {{1, 0}, {9,  0}, {3,  0}, {5, +1}, {7,  0}}, SUP "+M9" PUS },
742     { 5, {{1, 0}, {9,  0}, {3,  0}, {5, +1}, {7, -1}}, SUP "+9" PUS },
743     { 5, {{1, 0}, {9,  0}, {3,  0}, {5,  0}, {7,  0}}, "M9" },
744     { 5, {{1, 0}, {9,  0}, {3,  0}, {5,  0}, {7, -1}}, "9" },
745     { 5, {{1, 0}, {9,  0}, {3, -1}, {5,  0}, {7,  0}}, "m" SUP "M9" PUS },
746     { 5, {{1, 0}, {9,  0}, {3, -1}, {5,  0}, {7, -1}}, "m9" },
747     { 5, {{1, 0}, {9, -1}, {3, -1}, {5,  0}, {7, -1}}, "m♭9" },
748     { 5, {{1, 0}, {9,  0}, {3,  0}, {5, -1}, {7,  0}}, "M9" SUP "♭5" PUS },
749     { 5, {{1, 0}, {9,  0}, {3,  0}, {5, -1}, {7, -1}}, "9" SUP "♭5" PUS },
750     { 5, {{1, 0}, {9,  0}, {3, -1}, {5, -1}, {7,  0}}, "m" SUP "M9♭5" PUS },
751     { 5, {{1, 0}, {9,  0}, {3, -1}, {5, -1}, {7, -1}}, "𝆩" SUP "9" PUS },
752     { 5, {{1, 0}, {9, -1}, {3, -1}, {5, -1}, {7, -1}}, "𝆩" SUP "♭9" PUS },
753     { 5, {{1, 0}, {9,  0}, {3, -1}, {5, -1}, {7, -2}}, "°" SUP "9" PUS },
754     { 5, {{1, 0}, {9, -1}, {3, -1}, {5, -1}, {7, -2}}, "°" SUP "♭9" PUS },
755
756     /* Eleventh chords */
757     { 6, {{1, 0}, {9,  0}, {3,  0}, {11,  0}, {5, +1}, {7,  0}}, SUP "+M11" PUS },
758     { 6, {{1, 0}, {9,  0}, {3,  0}, {11,  0}, {5, +1}, {7, -1}}, SUP "+11" PUS },
759     { 6, {{1, 0}, {9,  0}, {3,  0}, {11,  0}, {5,  0}, {7,  0}}, "M11" },
760     { 6, {{1, 0}, {9,  0}, {3,  0}, {11,  0}, {5,  0}, {7, -1}}, "11" },
761     { 6, {{1, 0}, {9,  0}, {3, -1}, {11,  0}, {5,  0}, {7,  0}}, "m" SUP "M11" PUS },
762     { 6, {{1, 0}, {9,  0}, {3, -1}, {11,  0}, {5,  0}, {7, -1}}, "m11" },
763     { 6, {{1, 0}, {9, -1}, {3, -1}, {11,  0}, {5, -1}, {7, -1}}, "𝆩" SUP "11" PUS },
764     { 6, {{1, 0}, {9, -1}, {3, -1}, {11, -1}, {5, -1}, {7, -2}}, "°" SUP "11" PUS }
765 };
766
767 static void
768 scherzo_adjust_pitch_to_match_modified_degree (pitch_t *pitch,
769                                                pitch_t root,
770                                                modified_degree_t *degree)
771 {
772     pitch_name_t name = PITCH_NAME (*pitch);
773     pitch_accidental_t accidental = PITCH_ACCIDENTAL (*pitch);
774     int octave = PITCH_OCTAVE (*pitch);
775     int degree_zero_based = (degree->degree - 1) % 7;
776     int degree_delta;
777
778     int note_degree_zero_based = name - PITCH_NAME (root);
779     if (note_degree_zero_based < 0)
780         note_degree_zero_based += 7;
781
782     if (note_degree_zero_based == degree_zero_based)
783         return;
784
785     degree_delta = note_degree_zero_based - degree_zero_based;
786     if (degree_delta > 3)
787         degree_delta = - (7 - degree_delta);
788     if (degree_delta < -3)
789         degree_delta = - (-7 - degree_delta);
790
791     if (abs (degree_delta) != 1) {
792         fprintf (stderr, "Internal error: Cannot adjust a note more than one degree (%d vs. %d).\n", note_degree_zero_based + 1, degree->degree);
793         exit (1);
794     }
795
796     if (degree_delta == -1) {
797         if (name == PITCH_NAME_B) {
798             name = PITCH_NAME_C;
799             octave++;
800         } else {
801             name++;
802         }
803         switch (name) {
804         case PITCH_NAME_D:
805         case PITCH_NAME_E:
806         case PITCH_NAME_G:
807         case PITCH_NAME_A:
808         case PITCH_NAME_B:
809             accidental -= 2;
810             break;
811         case PITCH_NAME_C:
812         case PITCH_NAME_F:
813             accidental -= 1;
814             break;
815         }
816     }
817
818     if (degree_delta == +1) {
819         if (name == PITCH_NAME_C) {
820             name = PITCH_NAME_B;
821             octave--;
822         } else {
823             name--;
824         }
825         switch (name) {
826         case PITCH_NAME_C:
827         case PITCH_NAME_D:
828         case PITCH_NAME_F:
829         case PITCH_NAME_G:
830         case PITCH_NAME_A:
831             accidental += 2;
832             break;
833         case PITCH_NAME_E:
834         case PITCH_NAME_B:
835             accidental += 1;
836         }
837     }
838
839     if (accidental < 0 || accidental > PITCH_ACCIDENTAL_DOUBLE_SHARP) {
840         fprintf (stderr, "Internal error: Trying to adjust an accidental out of range (degree_delta == %d (%d - %d), new accidental == %d).\n", degree_delta, note_degree_zero_based, degree_zero_based, accidental);
841         exit (1);
842     }
843
844     *pitch = PITCH (name, accidental, octave);
845 }
846
847 static void
848 _spell_chord_by_signature (pitch_group_t *chord,
849                            chord_signature_t *signature,
850                            pitch_t root)
851 {
852     int i, degree, note_half_steps, degree_half_steps;
853     int root_midi;
854
855     /* Sanitize root to eliminate things like double-flats,
856      * double-sharps, Cb, E#, etc. */
857     root_midi = _pitch_to_midi (root);
858     root = _midi_to_pitch (root_midi);
859     
860     for (i = 0; i < chord->num_pitches; i++) {
861         note_half_steps = _pitch_from_root_in_half_steps (chord->pitches[i],
862                                                           root);
863         for (degree = 0; degree < signature->num_degrees; degree++) {
864             degree_half_steps = _modified_degree_to_half_steps (&signature->degrees[degree]);
865             if (note_half_steps == degree_half_steps) {
866                 scherzo_adjust_pitch_to_match_modified_degree (&chord->pitches[i],
867                                                                root,
868                                                                &signature->degrees[degree]);
869                 break;
870             }
871         }
872         if (note_half_steps != degree_half_steps) {
873             fprintf (stderr, "Internal error: Chord and degree mis-match\n");
874             exit (1);
875         }
876     }
877 }
878
879 static void
880 _analyze_chord (pitch_group_t *chord,
881                 chord_signature_t **signature_ret,
882                 pitch_t **root_ret)
883 {
884     void *local = talloc_new (NULL);
885     analyzed_pitch_t *pitches;
886     int i, j, num_pitches;
887     int bass_pitch, inversion;
888     pitch_t root;
889     chord_signature_t *match = NULL;
890
891     /* Default to no-match for any early return */
892     *signature_ret = NULL;
893     *root_ret = NULL;
894
895     num_pitches = chord->num_pitches;
896
897     if (chord->num_pitches <= 1)
898         goto DONE;
899
900     pitches = talloc_array (local, analyzed_pitch_t, num_pitches);
901     if (pitches == NULL)
902         goto DONE;
903
904     for (i = 0; i < num_pitches; i++) {
905         pitch_t pitch = chord->pitches[i];
906         pitches[i].pitch = pitch;
907         pitches[i].midi_pitch = _pitch_to_midi (pitch);
908         /* Relative pitch will be filled in after sorting. */
909         pitches[i].relative_pitch = 0;
910     }
911
912     /* First, sort by midi pitch to find the bass note. */
913     qsort (pitches, num_pitches, sizeof (analyzed_pitch_t),
914            _compare_analyzed_pitch_by_midi_pitch);
915     
916     bass_pitch = pitches[0].midi_pitch;
917
918     /* With the bass note identified, we can find all relative pitches. */
919     for (i = 0; i < num_pitches; i++) {
920         pitches[i].relative_pitch = pitches[i].midi_pitch - bass_pitch;
921         while (pitches[i].relative_pitch >= 12)
922             pitches[i].relative_pitch -= 12;
923     }
924
925     /* Now, sort again by relative pitch. */
926     qsort (pitches, num_pitches, sizeof (analyzed_pitch_t),
927            _compare_analyzed_pitch_by_relative_pitch);
928
929     /* Finally, eliminate all duplicate notes. */
930     for (i = 0; i < num_pitches - 1; i++) {
931             if (pitches[i+1].relative_pitch == pitches[i].relative_pitch) {
932                     j = i+1;
933                     while (j < num_pitches &&
934                            pitches[j].relative_pitch == pitches[i].relative_pitch)
935                     {
936                             j++;
937                     }
938                     /* The loop incremented j one past the last
939                      * duplicate. Decrement so that it points to the
940                      * last duplicate (and is guaranteed to not exceed
941                      * the array bounds).*/
942                     j--;
943
944                     if (j < num_pitches - 1) {
945                             memmove (&pitches[i+1], &pitches[j+1],
946                                      (num_pitches - j) * sizeof (analyzed_pitch_t));
947                     }
948
949                     num_pitches -= (j - i);
950             }
951     }
952
953     for (inversion = 0; inversion < 4; inversion++) {
954         for (i = 0; i < ARRAY_SIZE (signatures); i++) {
955             if (_chord_signature_matches (pitches, num_pitches,
956                                           signatures[i].degrees,
957                                           signatures[i].num_degrees,
958                                           inversion, &root))
959             {
960                 match = &signatures[i];
961                 goto HAVE_MATCH;
962             }
963         }
964     }
965 HAVE_MATCH:
966
967     if (match) {
968         *signature_ret = match;
969         for (i = 0; i < chord->num_pitches; i++) {
970             if (chord->pitches[i] == root) {
971                 *root_ret = &chord->pitches[i];
972                 break;
973             }
974         }
975     }
976
977 DONE:
978     talloc_free (local);
979 }
980
981 static void
982 pitch_group_init (void *ctx, pitch_group_t *group)
983 {
984     group->ctx = ctx;
985     group->pitches = NULL;
986     group->size = 0;
987     group->num_pitches = 0;
988 }
989
990 static void
991 pitch_group_add_pitch (pitch_group_t *group, pitch_t pitch)
992 {
993     int i;
994
995     /* Do nothing if pitch is already in group. */
996     for (i = 0; i < group->num_pitches; i++)
997         if (group->pitches[i] == pitch)
998             return;
999
1000     group->num_pitches++;
1001
1002     if (group->num_pitches > group->size) {
1003         group->size++;
1004         group->pitches = talloc_realloc (group->ctx, group->pitches,
1005                                          pitch_t, group->size);
1006
1007         if (group->pitches == NULL) {
1008             fprintf (stderr, "Out of memory.\n");
1009             exit (1);
1010         }
1011     }
1012
1013     group->pitches[group->num_pitches - 1] = pitch;
1014 }
1015
1016 static void
1017 pitch_group_remove_pitch_at (pitch_group_t *group, int i)
1018 {
1019     if (i > group->num_pitches) {
1020         fprintf (stderr, "Internal error: Cannot remove pitch %d from group with only %d %s\n",
1021                  i, group->num_pitches,
1022                  group->num_pitches == 1 ? "pitch" : "pitches");
1023         exit (1);
1024     }
1025
1026     if (i < group->num_pitches - 1) {
1027         memmove (group->pitches + i, group->pitches + i + 1,
1028                  (group->num_pitches - 1 - i) * sizeof (pitch_t));
1029     }
1030
1031     group->num_pitches--;
1032 }
1033
1034 /* Remove a 'pitch' from 'group', (including any enharmonic pitch)
1035  * See also: pitch_group_remove_pitch
1036  */
1037 static void
1038 pitch_group_remove_pitch_enharmonic (pitch_group_t *group, pitch_t pitch)
1039 {
1040     int i;
1041
1042     for (i = 0; i < group->num_pitches; i++)
1043         if (_pitches_are_enharmonic (group->pitches[i], pitch))
1044             pitch_group_remove_pitch_at (group, i);
1045 }
1046
1047 /* Remove an exactly-matching pitch from 'group'
1048  * See also: pitch_group_remove_pitch_enharmonic
1049  *
1050 static void
1051 pitch_group_remove_pitch (pitch_group_t *group, pitch_t pitch)
1052 {
1053     int i;
1054
1055     for (i = 0; i < group->num_pitches; i++)
1056         if (group->pitches[i] == pitch)
1057             pitch_group_remove_pitch_at (group, i);
1058 }
1059 */
1060
1061 static void
1062 scherzo_update_notes_and_chord (scherzo_t *scherzo)
1063 {
1064     if (scherzo->notes_pressed.num_pitches == 0 &&
1065         scherzo->notes_pedaled.num_pitches == 0)
1066     {
1067         score_remove_notes (scherzo->score);
1068
1069         score_remove_chords (scherzo->score);
1070
1071         gtk_widget_queue_draw (scherzo->window);
1072     }
1073 }
1074
1075 static void
1076 scherzo_press_note (scherzo_t *scherzo, pitch_t pitch)
1077 {
1078     void *local = talloc_new (NULL);
1079     pitch_group_t *chord;
1080     chord_signature_t *signature;
1081     char *chord_name = NULL;
1082     pitch_t *root;
1083     int i;
1084
1085     /* Do nothing if this note is already pressed. */
1086     for (i = 0; i < scherzo->notes_pressed.num_pitches; i++)
1087         if (scherzo->notes_pressed.pitches[i] == pitch)
1088             return;
1089
1090     pitch_group_add_pitch (&scherzo->notes_pressed, pitch);
1091
1092     if (scherzo->pedal_pressed)
1093         pitch_group_add_pitch (&scherzo->notes_pedaled, pitch);
1094
1095     /* Remove all notes/chords from score, then add current notes. */
1096     score_remove_notes (scherzo->score);
1097     score_remove_chords (scherzo->score);
1098
1099     if (scherzo->pedal_pressed)
1100         chord = &scherzo->notes_pedaled;
1101     else
1102         chord = &scherzo->notes_pressed;
1103
1104     _analyze_chord (chord, &signature, &root);
1105
1106     if (signature) {
1107         /* Don't print root pitch for octaves and inversions,
1108          * (since a pitch name alone looks like a major triad) */
1109         if (signature->num_degrees < 3) {
1110             chord_name = talloc_strdup (local, signature->name);
1111         } else {
1112             _spell_chord_by_signature (&scherzo->notes_pressed,
1113                                        signature, *root);
1114             _spell_chord_by_signature (&scherzo->notes_pedaled,
1115                                        signature, *root);
1116
1117             chord_name = talloc_asprintf (local, "%s%s",
1118                                           _pitch_str (*root),
1119                                           signature->name);
1120         }
1121     } else if (chord->num_pitches > 2) {
1122         chord_name = talloc_strdup (local, "?");
1123     }
1124
1125     if (chord_name)
1126         scherzo->chord = score_add_chord (scherzo->treble, chord_name);
1127
1128     for (i = 0; i < scherzo->notes_pressed.num_pitches; i++)
1129     {
1130         score_add_note (scherzo->score, scherzo->notes_pressed.pitches[i],
1131                         SCORE_DURATION_WHOLE);
1132     }
1133
1134     for (i = 0; i < scherzo->notes_pedaled.num_pitches; i++)
1135     {
1136         score_add_note (scherzo->score, scherzo->notes_pedaled.pitches[i],
1137                         SCORE_DURATION_WHOLE);
1138     }
1139
1140     talloc_free (local);
1141 }
1142
1143 static void
1144 scherzo_release_note (scherzo_t *scherzo, pitch_t pitch)
1145 {
1146     pitch_group_remove_pitch_enharmonic (&scherzo->notes_pressed, pitch);
1147
1148     if (scherzo->notes_pressed.num_pitches == 0)
1149         scherzo_update_notes_and_chord (scherzo);
1150 }
1151
1152 static pitch_t
1153 scherzo_press_note_midi (scherzo_t *scherzo, unsigned char midi_note)
1154 {
1155     pitch_t pitch = _midi_to_pitch (midi_note);
1156
1157     scherzo_press_note (scherzo, pitch);
1158
1159     return pitch;
1160 }
1161
1162 static void
1163 scherzo_release_note_midi (scherzo_t *scherzo, unsigned char midi_note)
1164 {
1165     scherzo_release_note (scherzo, _midi_to_pitch (midi_note));
1166 }
1167
1168 static void
1169 scherzo_press_pedal (scherzo_t *scherzo)
1170 {
1171     int i;
1172
1173     if (scherzo->pedal_pressed)
1174         return;
1175
1176     scherzo->pedal_pressed = 1;
1177
1178     /* Copy all pressed notes to pedaled notes */
1179     for (i = 0; i < scherzo->notes_pressed.num_pitches; i++)
1180         pitch_group_add_pitch (&scherzo->notes_pedaled, scherzo->notes_pressed.pitches[i]);
1181 }
1182
1183 static void
1184 scherzo_release_pedal (scherzo_t *scherzo)
1185 {
1186     int i;
1187
1188     if (! scherzo->pedal_pressed)
1189         return;
1190
1191     /* Remove all previously pedaled notes. */
1192     for (i = scherzo->notes_pedaled.num_pitches - 1; i >=0; i--)
1193         pitch_group_remove_pitch_at (&scherzo->notes_pedaled, i);
1194
1195     scherzo->pedal_pressed = 0;
1196
1197     scherzo_update_notes_and_chord (scherzo);
1198 }
1199
1200 static void
1201 _select_challenge (scherzo_t *scherzo)
1202 {
1203     category_t *category_unused;
1204     bool_t introduced_unused;
1205     item_t *item;
1206     challenge_t *challenge = &scherzo->challenge;
1207     pitch_name_t pitch_name;
1208     int octave;
1209     char *s;
1210
1211     mnemon_select_item (&scherzo->mnemon,
1212                         &challenge->bin,
1213                         &challenge->item_index,
1214                         &category_unused,
1215                         &introduced_unused);
1216
1217     item = challenge->bin->items[challenge->item_index];
1218
1219     s = item->challenge;
1220     if (strncmp (s, "treble:", 7) == 0) {
1221         s += 7;
1222         challenge->staff = scherzo->treble;
1223     } else if (strncmp (s, "bass:", 5) == 0) {
1224         s += 5;
1225         challenge->staff = scherzo->bass;
1226     } else {
1227         fprintf (stderr,
1228                  "Malformed staff name: %s (expected 'treble:' or 'bass:')\n",
1229                  s);
1230         exit (1);
1231     }
1232
1233     switch (*s) {
1234     case 'C':
1235         pitch_name = PITCH_NAME_C;
1236         break;
1237     case 'D':
1238         pitch_name = PITCH_NAME_D;
1239         break;
1240     case 'E':
1241         pitch_name = PITCH_NAME_E;
1242         break;
1243     case 'F':
1244         pitch_name = PITCH_NAME_F;
1245         break;
1246     case 'G':
1247         pitch_name = PITCH_NAME_G;
1248         break;
1249     case 'A':
1250         pitch_name = PITCH_NAME_A;
1251         break;
1252     case 'B':
1253         pitch_name = PITCH_NAME_B;
1254         break;
1255     default:
1256         fprintf (stderr, "Malformed pitch name: %s (expected 'A' - 'G')\n", s);
1257         exit (1);
1258     }
1259     s++;
1260
1261     if (*s < '0' || *s > '9') {
1262         fprintf (stderr, "Malformed octave number: %s (expected '0' - '9')\n", s);
1263         exit (1);
1264     }
1265
1266     octave = *s - '0';
1267
1268     challenge->pitch = PITCH (pitch_name, PITCH_ACCIDENTAL_NATURAL, octave);
1269
1270     challenge->active = 1;
1271     challenge->satisfied = 0;
1272     challenge->mistaken = 0;
1273 }
1274
1275 /* Determine whether the user hit the correct note. */
1276 static void
1277 _judge_pitch (scherzo_t *scherzo, pitch_t pitch)
1278 {
1279     challenge_t *challenge = &scherzo->challenge;
1280
1281     if (! challenge->active)
1282         return;
1283
1284     if (pitch == challenge->pitch)
1285         challenge->satisfied = 1;
1286     else
1287         challenge->mistaken = 1;
1288 }
1289
1290 /* If the user got the right note (eventually), then score it in
1291  * mnemon and show the next note. */
1292 static void
1293 _score_challenge (scherzo_t *scherzo)
1294 {
1295     challenge_t *challenge = &scherzo->challenge;
1296
1297     if (! challenge->active)
1298         return;
1299
1300     if (! challenge->satisfied)
1301         return;
1302
1303     mnemon_score_item (&scherzo->mnemon, challenge->bin, challenge->item_index,
1304                        ! challenge->mistaken);
1305
1306     _select_challenge (scherzo);
1307 }
1308
1309 static int
1310 on_midi_input (unused (GIOChannel *channel),
1311                unused (GIOCondition condition),
1312                void *user_data)
1313 {
1314     unsigned char buf[MIDI_BUF_SIZE], *next;
1315     scherzo_t *scherzo = user_data;
1316     ssize_t remaining;
1317     snd_seq_event_t event;
1318     pitch_t pitch;
1319     int need_redraw = FALSE;
1320
1321     remaining = read (scherzo->midi_fd, buf, MIDI_BUF_SIZE);
1322
1323     next = buf;
1324     while (remaining) {
1325         long consumed;
1326
1327         consumed = snd_midi_event_encode (scherzo->snd_midi_event,
1328                                           next, remaining, &event);
1329
1330         remaining -= consumed;
1331         next += consumed;
1332
1333         switch (event.type) {
1334         case SND_SEQ_EVENT_NONE:
1335             /* Incomplete event. Nothing to do. */
1336             break;
1337         case SND_SEQ_EVENT_NOTEON:
1338             pitch = scherzo_press_note_midi (scherzo, event.data.note.note);
1339             _judge_pitch (scherzo, pitch);
1340             need_redraw = TRUE;
1341             break;
1342         case SND_SEQ_EVENT_NOTEOFF:
1343             scherzo_release_note_midi (scherzo, event.data.note.note);
1344             _score_challenge (scherzo);
1345             need_redraw = TRUE;
1346             break;
1347         case SND_SEQ_EVENT_CLOCK:
1348             /* Ignore for now as my piano sends a constant stream of these. */
1349             break;
1350         case SND_SEQ_EVENT_SENSING:
1351             /* Ignore for now as my piano sends a constant stream of these. */
1352             break;
1353         case SND_SEQ_EVENT_CONTROLLER:
1354             /* XXX: My piano gives me 64 for the sustain pedal, is
1355              * that universal? */
1356             if (event.data.control.param == 64) {
1357                 if (event.data.control.value == 0)
1358                     scherzo_release_pedal (scherzo);
1359                 else
1360                     scherzo_press_pedal (scherzo);
1361             } else {
1362                 fprintf (stderr, "Fixme: Unhandled MIDI Control event (param=%d, value=%d)\n",
1363                          event.data.control.param, event.data.control.value);
1364             }
1365             break;
1366         default:
1367             fprintf (stderr, "Fixme: Do not yet know how to handle MIDI event %d\n",
1368                      event.type);
1369             break;
1370         }
1371     }
1372
1373     if (need_redraw)
1374         gtk_widget_queue_draw (scherzo->window);
1375
1376     /* Return TRUE to continue to get called in the future. */
1377     return TRUE;
1378 }
1379
1380 int
1381 main (int argc, char *argv[])
1382 {
1383     GtkWidget *drawing_area;
1384     scherzo_t scherzo;
1385     int err;
1386
1387     srand (time (NULL));
1388
1389     gtk_init (&argc, &argv);
1390
1391     scherzo.ctx = talloc_new (NULL);
1392
1393     scherzo.score = score_create (scherzo.ctx);
1394     scherzo.staff_height = 100;
1395     score_set_staff_height (scherzo.score, scherzo.staff_height);
1396
1397     score_add_brace (scherzo.score, 2);
1398     scherzo.treble = score_add_staff (scherzo.score, SCORE_CLEF_G);
1399     scherzo.bass = score_add_staff (scherzo.score, SCORE_CLEF_F);
1400
1401     scherzo.chord = NULL;
1402
1403     /* Default to octave 4 and natural for computer keyboard keypresses. */
1404     scherzo.keyboard_octave = 4;
1405     scherzo.keyboard_accidental = PITCH_ACCIDENTAL_NATURAL;
1406
1407     pitch_group_init (scherzo.ctx, &scherzo.notes_pressed);
1408     pitch_group_init (scherzo.ctx, &scherzo.notes_pedaled);
1409
1410     scherzo.pedal_pressed = 0;
1411
1412     mnemon_init (&scherzo.mnemon);
1413     /* XXX: Should create a default file if one cannot be loaded. */
1414     mnemon_load_category (&scherzo.mnemon, "scherzo-notes");
1415
1416     scherzo.challenge.active = 0;
1417 /*
1418     _select_challenge (&scherzo);
1419 */
1420
1421     err = snd_midi_event_new (MIDI_BUF_SIZE, &scherzo.snd_midi_event);
1422     if (err) {
1423         fprintf (stderr, "Out of memory.\n");
1424         return 1;
1425     }
1426
1427 #define MIDI_DEVICE "/dev/midi1"
1428     scherzo.midi_fd = open (MIDI_DEVICE, O_RDONLY);
1429     if (scherzo.midi_fd < 0) {
1430         printf ("failed to open " MIDI_DEVICE ". Midi input will not be available.\n");
1431     } else {
1432         GIOChannel *channel;
1433
1434         channel = g_io_channel_unix_new (scherzo.midi_fd);
1435         g_io_channel_set_encoding (channel, NULL, NULL);
1436         g_io_add_watch (channel, G_IO_IN, on_midi_input, &scherzo);
1437     }
1438
1439     scherzo.window = gtk_window_new (GTK_WINDOW_TOPLEVEL);
1440
1441     gtk_window_set_default_size (GTK_WINDOW (scherzo.window), 1000, 600);
1442
1443     g_signal_connect (scherzo.window, "delete-event",
1444                       G_CALLBACK (on_delete_event_quit), NULL);
1445
1446     drawing_area = gtk_drawing_area_new ();
1447
1448     gtk_container_add (GTK_CONTAINER (scherzo.window), drawing_area);
1449
1450     g_signal_connect (drawing_area, "expose-event",  
1451                       G_CALLBACK (on_expose_event_draw),
1452                       &scherzo);
1453
1454     g_signal_connect (scherzo.window, "key-press-event",
1455                       G_CALLBACK (on_key_press_event),
1456                       &scherzo);
1457
1458     g_signal_connect (scherzo.window, "key-release-event",
1459                       G_CALLBACK (on_key_release_event),
1460                       &scherzo);
1461     
1462     gtk_widget_show_all (scherzo.window);
1463     
1464     gtk_main ();
1465
1466     mnemon_save (&scherzo.mnemon);
1467
1468     snd_midi_event_free (scherzo.snd_midi_event);
1469
1470     talloc_free (scherzo.ctx);
1471
1472     return 0;
1473 }