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