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