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