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