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