]> git.cworth.org Git - scherzo/blob - scherzo.c
Add support for recognizing inverted 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     score_pitch_name_t pitch_name;
151     score_pitch_t pitch;
152
153     if (scherzo->challenge.note)
154         octave = scherzo->challenge.note->octave;
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_q:
174     case GDK_KEY_Q:
175     case GDK_KEY_Escape:
176         gtk_main_quit ();
177         return FALSE;
178     case GDK_KEY_c:
179     case GDK_KEY_C:
180         pitch_name = SCORE_PITCH_NAME_C;
181         break;
182     case GDK_KEY_d:
183     case GDK_KEY_D:
184         pitch_name = SCORE_PITCH_NAME_D;
185         break;
186     case GDK_KEY_e:
187     case GDK_KEY_E:
188         pitch_name = SCORE_PITCH_NAME_E;
189         break;
190     case GDK_KEY_f:
191     case GDK_KEY_F:
192         pitch_name = SCORE_PITCH_NAME_F;
193         break;
194     case GDK_KEY_g:
195     case GDK_KEY_G:
196         pitch_name = SCORE_PITCH_NAME_G;
197         break;
198     case GDK_KEY_a:
199     case GDK_KEY_A:
200         pitch_name = SCORE_PITCH_NAME_A;
201         break;
202     case GDK_KEY_b:
203     case GDK_KEY_B:
204         pitch_name = SCORE_PITCH_NAME_B;
205         break;
206     case GDK_KEY_0:
207     case GDK_KEY_1:
208     case GDK_KEY_2:
209     case GDK_KEY_3:
210     case GDK_KEY_4:
211     case GDK_KEY_5:
212     case GDK_KEY_6:
213     case GDK_KEY_7:
214     case GDK_KEY_8:
215         scherzo->keyboard_octave = key->keyval - GDK_KEY_0;
216         break;
217     case GDK_KEY_space:
218         scherzo_press_pedal (scherzo);
219         break;
220     case GDK_KEY_Up:
221         if (scherzo->keyboard_accidental < SCORE_PITCH_ACCIDENTAL_DOUBLE_SHARP)
222             scherzo->keyboard_accidental++;
223         break;
224     case GDK_KEY_Down:
225         if (scherzo->keyboard_accidental > SCORE_PITCH_ACCIDENTAL_DOUBLE_FLAT)
226             scherzo->keyboard_accidental--;
227         break;
228     }
229
230     pitch = SCORE_PITCH (pitch_name, scherzo->keyboard_accidental);
231
232     if ((key->keyval >= GDK_KEY_A && key->keyval <= GDK_KEY_G) ||
233         (key->keyval >= GDK_KEY_a && key->keyval <= GDK_KEY_g))
234     {
235         score_note_t *note;
236
237         note = scherzo_press_note (scherzo, pitch, octave);
238         _judge_note (scherzo, note);
239         gtk_widget_queue_draw (scherzo->window);
240
241         return TRUE;
242     }
243
244
245     /* Allow an unhandled event to propagate to other handlers. */
246     return FALSE;
247 }
248
249 static int
250 on_key_release_event (unused (GtkWidget *widget),
251                       GdkEventKey *key,
252                       void *user_data)
253 {
254     scherzo_t *scherzo = user_data;
255     int octave;
256     score_pitch_name_t pitch_name;
257     score_pitch_t pitch;
258
259     if (scherzo->challenge.note)
260         octave = scherzo->challenge.note->octave;
261     else
262         octave = scherzo->keyboard_octave;
263
264     switch (key->keyval) {
265     case GDK_KEY_c:
266     case GDK_KEY_C:
267         pitch_name = SCORE_PITCH_NAME_C;
268         break;
269     case GDK_KEY_d:
270     case GDK_KEY_D:
271         pitch_name = SCORE_PITCH_NAME_D;
272         break;
273     case GDK_KEY_e:
274     case GDK_KEY_E:
275         pitch_name = SCORE_PITCH_NAME_E;
276         break;
277     case GDK_KEY_f:
278     case GDK_KEY_F:
279         pitch_name = SCORE_PITCH_NAME_F;
280         break;
281     case GDK_KEY_g:
282     case GDK_KEY_G:
283         pitch_name = SCORE_PITCH_NAME_G;
284         break;
285     case GDK_KEY_a:
286     case GDK_KEY_A:
287         pitch_name = SCORE_PITCH_NAME_A;
288         break;
289     case GDK_KEY_b:
290     case GDK_KEY_B:
291         pitch_name = SCORE_PITCH_NAME_B;
292         break;
293     case GDK_KEY_space:
294         scherzo_release_pedal (scherzo);
295         break;
296     }
297
298     pitch = SCORE_PITCH (pitch_name, scherzo->keyboard_accidental);
299
300     if ((key->keyval >= GDK_KEY_A && key->keyval <= GDK_KEY_G) ||
301         (key->keyval >= GDK_KEY_a && key->keyval <= GDK_KEY_g))
302     {
303         scherzo_release_note (scherzo, pitch, octave);
304         _score_challenge (scherzo);
305         gtk_widget_queue_draw (scherzo->window);
306
307         return TRUE;
308     }
309
310
311     /* Allow an unhandled event to propagate to other handlers. */
312     return FALSE;
313 }
314
315 static unsigned char
316 _score_pitch_and_octave_to_midi (score_pitch_t pitch,
317                                  int octave)
318 {
319     unsigned char midi_note = 12 * (octave + 1);
320
321     switch (SCORE_PITCH_NAME (pitch)) {
322     case SCORE_PITCH_NAME_C:
323         break;
324     case SCORE_PITCH_NAME_D:
325         midi_note += 2;
326         break;
327     case SCORE_PITCH_NAME_E:
328         midi_note += 4;
329         break;
330     case SCORE_PITCH_NAME_F:
331         midi_note += 5;
332         break;
333     case SCORE_PITCH_NAME_G:
334         midi_note += 7;
335         break;
336     case SCORE_PITCH_NAME_A:
337         midi_note += 9;
338         break;
339     case SCORE_PITCH_NAME_B:
340         midi_note += 11;
341         break;
342     }
343
344     switch (SCORE_PITCH_ACCIDENTAL (pitch)) {
345     case SCORE_PITCH_ACCIDENTAL_DOUBLE_FLAT:
346         midi_note -= 2;
347         break;
348     case SCORE_PITCH_ACCIDENTAL_FLAT:
349         midi_note -= 1;
350         break;
351     case SCORE_PITCH_ACCIDENTAL_NATURAL:
352         break;
353     case SCORE_PITCH_ACCIDENTAL_SHARP:
354         midi_note += 1;
355         break;
356     case SCORE_PITCH_ACCIDENTAL_DOUBLE_SHARP:
357         midi_note += 2;
358         break;
359     }
360
361     return midi_note;
362 }
363
364 static void
365 _midi_to_score_pitch_and_octave (unsigned char midi_note,
366                                  score_pitch_t *pitch,
367                                  int *octave)
368 {
369     *octave = midi_note / 12 - 1;
370
371     switch (midi_note % 12)
372     {
373     case 0:
374         *pitch = SCORE_PITCH_C;
375         break;
376     case 1:
377         *pitch = SCORE_PITCH_Cs;
378         break;
379     case 2:
380         *pitch = SCORE_PITCH_D;
381         break;
382     case 3:
383         *pitch = SCORE_PITCH_Ds;
384         break;
385     case 4:
386         *pitch = SCORE_PITCH_E;
387         break;
388     case 5:
389         *pitch = SCORE_PITCH_F;
390         break;
391     case 6:
392         *pitch = SCORE_PITCH_Fs;
393         break;
394     case 7:
395         *pitch = SCORE_PITCH_G;
396         break;
397     case 8:
398         *pitch = SCORE_PITCH_Gs;
399         break;
400     case 9:
401         *pitch = SCORE_PITCH_A;
402         break;
403     case 10:
404         *pitch = SCORE_PITCH_As;
405         break;
406     case 11:
407         *pitch = SCORE_PITCH_B;
408         break;
409     }
410 }
411
412 /* Determine a chord name (if any) from the current notes pressed */
413
414 typedef struct analyzed_note {
415     /* Original note being analzyed. */
416     score_note_t *note;
417
418     /* Absolute pitch (expressed as midi number). */
419     int midi_pitch;
420
421     /* Pitch relative to bass note. */
422     int relative_pitch;
423 } analyzed_note_t;
424
425 static int
426 _compare_analyzed_note_by_midi_pitch (const void *va, const void *vb)
427 {
428     const analyzed_note_t *a = va, *b = vb;
429
430     return a->midi_pitch - b->midi_pitch;
431 }
432
433 static int
434 _compare_analyzed_note_by_relative_pitch (const void *va, const void *vb)
435 {
436     const analyzed_note_t *a = va, *b = vb;
437
438     return a->relative_pitch - b->relative_pitch;
439 }
440
441 typedef struct modified_degree
442 {
443     int degree;
444     int modification;
445 } modified_degree_t;
446
447 static int
448 _modified_degree_to_half_steps (const modified_degree_t *degree)
449 {
450     int half_steps;
451
452     /* Number of half steps from root to specified degree within a
453      * diatonic scaled. */
454     switch (degree->degree) {
455     case 1:
456         half_steps = 0;
457         break;
458     case 2:
459         half_steps = 2;
460         break;
461     case 3:
462         half_steps = 4;
463         break;
464     case 4:
465         half_steps = 5;
466         break;
467     case 5:
468         half_steps = 7;
469         break;
470     case 6:
471         half_steps = 9;
472         break;
473     case 7:
474         half_steps = 11;
475         break;
476     default:
477         fprintf (stderr, "Internal: Invalid degree %d\n", degree->degree);
478         exit (1);
479         break;
480     }
481
482     return half_steps + degree->modification;
483 }
484
485 static int
486 _chord_signature_matches (analyzed_note_t *notes,
487                           int num_notes,
488                           modified_degree_t *degrees,
489                           int num_degrees,
490                           int *inversion_ret)
491 {
492 #define MAX_DEGREES 4
493     int relative_pitches[MAX_DEGREES];
494     int inversion, max_inversions;
495     int i;
496
497     assert (num_degrees <= MAX_DEGREES);
498
499     if (num_notes != num_degrees)
500             return 0;
501
502     max_inversions = num_degrees;
503
504     /* We never spell simple intervals as inversions. */
505     if (num_degrees == 2)
506         max_inversions = 1;
507
508     for (inversion = 0; inversion < max_inversions; inversion++) {
509         for (i = 0; i < num_degrees; i++) {
510             /* The num_degrees is in the addition just to ensure all
511              * inputs to the modulus operator remain positive. */
512             int index = (i + num_degrees - inversion) % num_degrees;
513
514             /* Again, adding a 12 to keep things positive. */
515             relative_pitches[index] =
516                 (12 +
517                  _modified_degree_to_half_steps (&degrees[i]) -
518                  _modified_degree_to_half_steps (&degrees[inversion])) % 12;
519                 
520         }
521
522         for (i = 0; i < num_notes; i++)
523             if (notes[i].relative_pitch != relative_pitches[i])
524                 goto NEXT_INVERSION;
525
526         *inversion_ret = inversion;
527
528         return 1;
529
530     NEXT_INVERSION:
531         ;
532     }
533
534     return 0;
535 }
536
537 static void
538 scherzo_analyze_chord (scherzo_t *scherzo)
539 {
540     void *local = talloc_new (NULL);
541     analyzed_note_t *notes;
542     note_group_t *note_group;
543     unsigned i, j, num_notes;
544     int bass_pitch, inversion;
545     const char *chord_name = NULL;
546
547     if (scherzo->pedal_pressed)
548         note_group = &scherzo->notes_pedaled;
549     else
550         note_group = &scherzo->notes_pressed;
551
552     num_notes = note_group->num_notes;
553
554     struct { modified_degree_t degrees[1]; const char *name; } octaves[] = {
555         { {{1, 0}}, "Octave"}
556     };
557
558     struct { modified_degree_t degrees[2]; const char *name; } intervals[] = {
559         { {{1, 0}, {2, -1}}, "Minor 2nd"},
560         { {{1, 0}, {2,  0}}, "Major 2nd"},
561         { {{1, 0}, {3, -1}}, "Minor 3rd"},
562         { {{1, 0}, {3,  0}}, "Major 3rd"},
563         { {{1, 0}, {4,  0}}, "Perfect 4th"},
564         { {{1, 0}, {5, -1}}, "Diminished 5th"},
565         { {{1, 0}, {5,  0}}, "Perfect 5th"},
566         { {{1, 0}, {6, -1}}, "Minor 6th"},
567         { {{1, 0}, {6,  0}}, "Major 6th"},
568         { {{1, 0}, {7, -1}}, "Minor 7th"},
569         { {{1, 0}, {7,  0}}, "Major 7th"}
570     };
571
572     struct { modified_degree_t degrees[3]; const char *name; } triads[] = {
573         { {{1, 0}, {3,  0}, {5, +1}}, "Augmented triad" },
574         { {{1, 0}, {3,  0}, {5,  0}}, "Major triad" },
575         { {{1, 0}, {3, -1}, {5,  0}}, "Minor triad" },
576         { {{1, 0}, {3, -1}, {5, -1}}, "Diminished triad" }
577     };
578
579     struct { modified_degree_t degrees[4]; const char *name; } sevenths[] = {
580         { {{1, 0}, {3,  0}, {5, +1}, {7,  0}}, "Augmented/major 7" },
581         { {{1, 0}, {3,  0}, {5, +1}, {7, -1}}, "Augmented 7" },
582         { {{1, 0}, {3,  0}, {5,  0}, {7,  0}}, "Major 7" },
583         { {{1, 0}, {3,  0}, {5,  0}, {7, -1}}, "Dominant 7" },
584         { {{1, 0}, {3, -1}, {5,  0}, {7,  0}}, "Minor/major 7" },
585         { {{1, 0}, {3, -1}, {5,  0}, {7, -1}}, "Minor 7" },
586         { {{1, 0}, {3, -1}, {5, -1}, {7,  0}}, "Diminished/major 7" },
587         { {{1, 0}, {3, -1}, {5, -1}, {7, -1}}, "Half-diminished 7" },
588         { {{1, 0}, {3, -1}, {5, -1}, {7, -2}}, "Diminished 7" }
589     };
590
591     if (scherzo->chord) {
592         score_remove_chord (scherzo->chord);
593         scherzo->chord = NULL;
594     }
595
596     if (num_notes <= 1)
597         goto DONE;
598
599     notes = talloc_array (local, analyzed_note_t, num_notes);
600     if (notes == NULL)
601         goto DONE;
602
603     for (i = 0; i < num_notes; i++) {
604         score_note_t *note = note_group->notes[i];
605         notes[i].note = note;
606         notes[i].midi_pitch = _score_pitch_and_octave_to_midi (note->pitch,
607                                                                note->octave);
608         /* Relative pitch will be filled in after sorting. */
609         notes[i].relative_pitch = 0;
610     }
611
612     /* First, sort by midi pitch to find the bass note. */
613     qsort (notes, num_notes, sizeof (analyzed_note_t),
614            _compare_analyzed_note_by_midi_pitch);
615     
616     bass_pitch = notes[0].midi_pitch;
617
618     /* With the bass note identified, we can find all relative pitches. */
619     for (i = 0; i < num_notes; i++) {
620         notes[i].relative_pitch = notes[i].midi_pitch - bass_pitch;
621         while (notes[i].relative_pitch >= 12)
622             notes[i].relative_pitch -= 12;
623     }
624
625     /* Now, sort again by relative pitch. */
626     qsort (notes, num_notes, sizeof (analyzed_note_t),
627            _compare_analyzed_note_by_relative_pitch);
628
629     /* Finally, eliminate all duplicate notes. */
630     for (i = 0; i < num_notes - 1; i++) {
631             if (notes[i+1].relative_pitch == notes[i].relative_pitch) {
632                     j = i+1;
633                     while (j < num_notes &&
634                            notes[j].relative_pitch == notes[i].relative_pitch)
635                     {
636                             j++;
637                     }
638                     /* The loop incremented j one past the last
639                      * duplicate. Decrement so that it points to the
640                      * last duplicate (and is guaranteed to not exceed
641                      * the array bounds).*/
642                     j--;
643
644                     if (j < num_notes - 1) {
645                             memmove (&notes[i+1], &notes[j+1],
646                                      (num_notes - j) * sizeof (analyzed_note_t));
647                     }
648
649                     num_notes -= (j - i);
650             }
651     }
652
653     switch (num_notes) {
654     case 1:
655         for (i = 0; i < ARRAY_SIZE (octaves); i++) {
656             if (_chord_signature_matches (notes, num_notes,
657                                           octaves[i].degrees, 1, &inversion))
658             {
659                 chord_name = octaves[i].name;
660                 break;
661             }
662         }
663         break;
664     case 2:
665         for (i = 0; i < ARRAY_SIZE (intervals); i++) {
666             if (_chord_signature_matches (notes, num_notes,
667                                           intervals[i].degrees, 2, &inversion))
668             {
669                 chord_name = intervals[i].name;
670                 break;
671             }
672         }
673         break;
674     case 3:
675         for (i = 0; i < ARRAY_SIZE (triads); i++) {
676             if (_chord_signature_matches (notes, num_notes,
677                                           triads[i].degrees, 3, &inversion))
678             {
679                 chord_name = triads[i].name;
680                 break;
681             }
682         }
683         break;
684     case 4:
685         for (i = 0; i < ARRAY_SIZE(sevenths); i++) {
686             if (_chord_signature_matches (notes, num_notes,
687                                           sevenths[i].degrees, 4, &inversion))
688             {
689                 chord_name = sevenths[i].name;
690                 break;
691             }
692         }
693         break;
694     }
695
696     if (chord_name) {
697         if (inversion) {
698             const char *inversion_str;
699             switch (inversion) {
700             case 1:
701                 inversion_str = "1st inversion";
702                 break;
703             case 2:
704                 inversion_str = "2nd inversion";
705                 break;
706             case 3:
707                 inversion_str = "3rd inversion";
708                 break;
709             default:
710                 fprintf (stderr, "Internal error: Unexpected inversion: %d\n",
711                          inversion);
712                 exit(1);
713             }
714             chord_name = talloc_asprintf (local, "%s %s",
715                                           chord_name, inversion_str);
716         } else {
717             chord_name = talloc_strdup (local, chord_name);
718         }
719     } else {
720         chord_name = talloc_strdup (local, "Unknown chord");
721     }
722
723     scherzo->chord = score_add_chord (scherzo->treble, chord_name);
724
725 DONE:
726     talloc_free (local);
727 }
728
729 static void
730 note_group_init (void *ctx, note_group_t *group)
731 {
732     group->ctx = ctx;
733     group->notes = NULL;
734     group->size = 0;
735     group->num_notes = 0;
736 }
737
738 static void
739 note_group_add_note (note_group_t *group, score_note_t *note)
740 {
741     int i;
742
743     /* Do nothing if note is already in group. */
744     for (i = 0; i < group->num_notes; i++) {
745         if (group->notes[i]->pitch == note->pitch &&
746             group->notes[i]->octave == note->octave)
747         {
748             return;
749         }
750     }
751
752     group->num_notes++;
753
754     if (group->num_notes > group->size) {
755         group->size++;
756         group->notes = talloc_realloc (group->ctx, group->notes,
757                                        score_note_t*, group->size);
758
759         if (group->notes == NULL) {
760             fprintf (stderr, "Out of memory.\n");
761             exit (1);
762         }
763     }
764
765     group->notes[group->num_notes - 1] = note;
766 }
767
768 static void
769 note_group_remove_note_at (note_group_t *group, int i)
770 {
771     if (i >= group->num_notes) {
772         fprintf (stderr, "Internal error: No note to remove at index %d\n", i);
773         exit (1);
774     }
775
776     if (i < group->num_notes - 1) {
777         memmove (group->notes + i, group->notes + i + 1,
778                  (group->num_notes - 1 - i) * sizeof (score_note_t*));
779     }
780     group->num_notes--;
781 }
782
783 static score_note_t *
784 scherzo_press_note (scherzo_t *scherzo, score_pitch_t pitch, int octave)
785 {
786     score_staff_t *staff;
787     score_note_t *note;
788     int i;
789
790     if (scherzo->challenge.note) {
791         staff = scherzo->challenge.staff;
792     } else if (octave >= 4) {
793         staff = scherzo->treble;
794     } else {
795         staff = scherzo->bass;
796     }
797
798     /* Do nothing if this note is already pressed. */
799     for (i = 0; i < scherzo->notes_pressed.num_notes; i++) {
800         if (scherzo->notes_pressed.notes[i]->pitch == pitch &&
801             scherzo->notes_pressed.notes[i]->octave == octave)
802         {
803             return scherzo->notes_pressed.notes[i];
804         }
805     }
806
807     note = score_add_note (staff, pitch, octave, SCORE_DURATION_WHOLE);
808
809     note_group_add_note (&scherzo->notes_pressed, note);
810
811     if (scherzo->pedal_pressed)
812         note_group_add_note (&scherzo->notes_pedaled, note);
813
814     scherzo_analyze_chord (scherzo);
815
816     return note;
817 }
818
819 static void
820 scherzo_release_note (scherzo_t *scherzo, score_pitch_t pitch, int octave)
821 {
822     score_note_t *note;
823     int i;
824     int found = 0;
825
826     for (i = scherzo->notes_pressed.num_notes - 1; i >=0; i--) {
827         note = scherzo->notes_pressed.notes[i];
828         if (note->pitch == pitch && note->octave == octave) {
829             found = 1;
830             if (! scherzo->pedal_pressed)
831                 score_remove_note (note);
832             note_group_remove_note_at (&scherzo->notes_pressed, i);
833         }
834     }
835
836     if (found == 0) {
837         fprintf (stderr, "Internal error: Failed to find note to release.\n");
838     }
839
840     scherzo_analyze_chord (scherzo);
841 }
842
843 static score_note_t *
844 scherzo_press_note_midi (scherzo_t *scherzo, unsigned char midi_note)
845 {
846     score_pitch_t pitch;
847     int octave;
848
849     _midi_to_score_pitch_and_octave (midi_note, &pitch, &octave);
850
851     return scherzo_press_note (scherzo, pitch, octave);
852 }
853
854 static void
855 scherzo_release_note_midi (scherzo_t *scherzo, unsigned char midi_note)
856 {
857     score_pitch_t pitch;
858     int octave;
859  
860     _midi_to_score_pitch_and_octave (midi_note, &pitch, &octave);
861
862     scherzo_release_note (scherzo, pitch, octave);
863 }
864
865 static void
866 scherzo_press_pedal (scherzo_t *scherzo)
867 {
868     int i;
869
870     scherzo->pedal_pressed = 1;
871
872     /* Copy all pressed notes to pedaled notes */
873     for (i = 0; i < scherzo->notes_pressed.num_notes; i++)
874         note_group_add_note (&scherzo->notes_pedaled, scherzo->notes_pressed.notes[i]);
875 }
876
877 static void
878 scherzo_release_pedal (scherzo_t *scherzo)
879 {
880     score_note_t *note, *new_note;
881     int i;
882
883     /* Make new notes in score for all pressed notes. */
884     for (i = 0; i < scherzo->notes_pressed.num_notes; i++) {
885         note = scherzo->notes_pressed.notes[i];
886         new_note = score_add_note (note->staff, note->pitch, note->octave, note->duration);
887         scherzo->notes_pressed.notes[i] = new_note;
888     }
889
890     /* Then remove all previously pedaled notes from the score. */
891     for (i = scherzo->notes_pedaled.num_notes - 1; i >=0; i--) {
892         note = scherzo->notes_pedaled.notes[i];
893         score_remove_note (note);
894         note_group_remove_note_at (&scherzo->notes_pedaled, i);
895     }
896
897     scherzo->pedal_pressed = 0;
898
899     scherzo_analyze_chord (scherzo);
900
901     gtk_widget_queue_draw (scherzo->window);
902 }
903
904 void
905 _select_challenge (scherzo_t *scherzo)
906 {
907     category_t *category_unused;
908     bool_t introduced_unused;
909     item_t *item;
910     challenge_t *challenge = &scherzo->challenge;
911     score_pitch_t pitch;
912     int octave;
913     char *s;
914
915     if (challenge->note) {
916         score_remove_note (challenge->note);
917         challenge->note = NULL;
918     }
919
920     mnemon_select_item (&scherzo->mnemon,
921                         &challenge->bin,
922                         &challenge->item_index,
923                         &category_unused,
924                         &introduced_unused);
925
926     item = challenge->bin->items[challenge->item_index];
927
928     s = item->challenge;
929     if (strncmp (s, "treble:", 7) == 0) {
930         s += 7;
931         challenge->staff = scherzo->treble;
932     } else if (strncmp (s, "bass:", 5) == 0) {
933         s += 5;
934         challenge->staff = scherzo->bass;
935     } else {
936         fprintf (stderr,
937                  "Malformed staff name: %s (expected 'treble:' or 'bass:')\n",
938                  s);
939         exit (1);
940     }
941
942     switch (*s) {
943     case 'C':
944         pitch = SCORE_PITCH_C;
945         break;
946     case 'D':
947         pitch = SCORE_PITCH_D;
948         break;
949     case 'E':
950         pitch = SCORE_PITCH_E;
951         break;
952     case 'F':
953         pitch = SCORE_PITCH_F;
954         break;
955     case 'G':
956         pitch = SCORE_PITCH_G;
957         break;
958     case 'A':
959         pitch = SCORE_PITCH_A;
960         break;
961     case 'B':
962         pitch = SCORE_PITCH_B;
963         break;
964     default:
965         fprintf (stderr, "Malformed pitch name: %s (expected 'A' - 'G')\n", s);
966         exit (1);
967     }
968     s++;
969
970     if (*s < '0' || *s > '9') {
971         fprintf (stderr, "Malformed octave number: %s (expected '0' - '9')\n", s);
972         exit (1);
973     }
974
975     octave = *s - '0';
976
977     challenge->note = score_add_note (challenge->staff, pitch, octave,
978                                       SCORE_DURATION_WHOLE);
979     challenge->satisfied = 0;
980     challenge->mistaken = 0;
981 }
982
983 /* Determine whether the user hit the correct note. */
984 static void
985 _judge_note (scherzo_t *scherzo, score_note_t *note)
986 {
987     challenge_t *challenge = &scherzo->challenge;
988
989     if (! scherzo->challenge.note) {
990         score_set_note_color_rgb (note, 0.0, 0.0, 0.0); /* black */
991         return;
992     }
993
994     if (note->pitch == challenge->note->pitch &&
995         note->octave == challenge->note->octave)
996     {
997         challenge->satisfied = 1;
998         score_set_note_color_rgb (note, 18/256., 130/256., 28/256.); /* green */
999     }
1000     else
1001     {
1002         challenge->mistaken = 1;
1003         score_set_note_color_rgb (note, 184/256., 4/256., 22/256.); /* red */
1004     }
1005 }
1006
1007 /* If the user got the right note (eventually), then score it in
1008  * mnemon and show the next note. */
1009 static void
1010 _score_challenge (scherzo_t *scherzo)
1011 {
1012     challenge_t *challenge = &scherzo->challenge;
1013
1014     if (! challenge->note)
1015         return;
1016
1017     if (! challenge->satisfied)
1018         return;
1019
1020     mnemon_score_item (&scherzo->mnemon, challenge->bin, challenge->item_index,
1021                        ! challenge->mistaken);
1022
1023     _select_challenge (scherzo);
1024 }
1025
1026 static int
1027 on_midi_input (unused (GIOChannel *channel),
1028                unused (GIOCondition condition),
1029                void *user_data)
1030 {
1031     unsigned char buf[MIDI_BUF_SIZE], *next;
1032     scherzo_t *scherzo = user_data;
1033     ssize_t remaining;
1034     snd_seq_event_t event;
1035     score_note_t *note;
1036     int need_redraw = FALSE;
1037
1038     remaining = read (scherzo->midi_fd, buf, MIDI_BUF_SIZE);
1039
1040     next = buf;
1041     while (remaining) {
1042         long consumed;
1043
1044         consumed = snd_midi_event_encode (scherzo->snd_midi_event,
1045                                           next, remaining, &event);
1046
1047         remaining -= consumed;
1048         next += consumed;
1049
1050         switch (event.type) {
1051         case SND_SEQ_EVENT_NONE:
1052             /* Incomplete event. Nothing to do. */
1053             break;
1054         case SND_SEQ_EVENT_NOTEON:
1055             note = scherzo_press_note_midi (scherzo, event.data.note.note);
1056             _judge_note (scherzo, note);
1057             need_redraw = TRUE;
1058             break;
1059         case SND_SEQ_EVENT_NOTEOFF:
1060             scherzo_release_note_midi (scherzo, event.data.note.note);
1061             _score_challenge (scherzo);
1062             need_redraw = TRUE;
1063             break;
1064         case SND_SEQ_EVENT_CLOCK:
1065             /* Ignore for now as my piano sends a constant stream of these. */
1066             break;
1067         case SND_SEQ_EVENT_SENSING:
1068             /* Ignore for now as my piano sends a constant stream of these. */
1069             break;
1070         case SND_SEQ_EVENT_CONTROLLER:
1071             /* XXX: My piano gives me 64 for the sustain pedal, is
1072              * that universal? */
1073             if (event.data.control.param == 64) {
1074                 if (event.data.control.value == 0)
1075                     scherzo_release_pedal (scherzo);
1076                 else
1077                     scherzo_press_pedal (scherzo);
1078             } else {
1079                 fprintf (stderr, "Fixme: Unhandled MIDI Control event (param=%d, value=%d)\n",
1080                          event.data.control.param, event.data.control.value);
1081             }
1082             break;
1083         default:
1084             fprintf (stderr, "Fixme: Do not yet know how to handle MIDI event %d\n",
1085                      event.type);
1086             break;
1087         }
1088     }
1089
1090     if (need_redraw)
1091         gtk_widget_queue_draw (scherzo->window);
1092
1093     /* Return TRUE to continue to get called in the future. */
1094     return TRUE;
1095 }
1096
1097 int
1098 main (int argc, char *argv[])
1099 {
1100     GtkWidget *drawing_area;
1101     scherzo_t scherzo;
1102     int err;
1103
1104     srand (time (NULL));
1105
1106     gtk_init (&argc, &argv);
1107
1108     scherzo.ctx = talloc_new (NULL);
1109
1110     scherzo.score = score_create (scherzo.ctx);
1111     scherzo.staff_height = 100;
1112     score_set_staff_height (scherzo.score, scherzo.staff_height);
1113
1114     score_add_brace (scherzo.score, 2);
1115     scherzo.treble = score_add_staff (scherzo.score, SCORE_CLEF_G);
1116     scherzo.bass = score_add_staff (scherzo.score, SCORE_CLEF_F);
1117
1118     scherzo.chord = NULL;
1119
1120     /* Default to octave 4 and natural for computer keyboard keypresses. */
1121     scherzo.keyboard_octave = 4;
1122     scherzo.keyboard_accidental = SCORE_PITCH_ACCIDENTAL_NATURAL;
1123
1124     note_group_init (scherzo.ctx, &scherzo.notes_pressed);
1125     note_group_init (scherzo.ctx, &scherzo.notes_pedaled);
1126
1127     scherzo.pedal_pressed = 0;
1128
1129     mnemon_init (&scherzo.mnemon);
1130     /* XXX: Should create a default file if one cannot be loaded. */
1131     mnemon_load_category (&scherzo.mnemon, "scherzo-notes");
1132
1133     scherzo.challenge.note = NULL;
1134 /*
1135     _select_challenge (&scherzo);
1136 */
1137
1138     err = snd_midi_event_new (MIDI_BUF_SIZE, &scherzo.snd_midi_event);
1139     if (err) {
1140         fprintf (stderr, "Out of memory.\n");
1141         return 1;
1142     }
1143
1144 #define MIDI_DEVICE "/dev/midi1"
1145     scherzo.midi_fd = open (MIDI_DEVICE, O_RDONLY);
1146     if (scherzo.midi_fd < 0) {
1147         printf ("failed to open " MIDI_DEVICE ". Midi input will not be available.\n");
1148     } else {
1149         GIOChannel *channel;
1150
1151         channel = g_io_channel_unix_new (scherzo.midi_fd);
1152         g_io_channel_set_encoding (channel, NULL, NULL);
1153         g_io_add_watch (channel, G_IO_IN, on_midi_input, &scherzo);
1154     }
1155
1156     scherzo.window = gtk_window_new (GTK_WINDOW_TOPLEVEL);
1157
1158     gtk_window_set_default_size (GTK_WINDOW (scherzo.window), 1000, 600);
1159
1160     g_signal_connect (scherzo.window, "delete-event",
1161                       G_CALLBACK (on_delete_event_quit), NULL);
1162
1163     drawing_area = gtk_drawing_area_new ();
1164
1165     gtk_container_add (GTK_CONTAINER (scherzo.window), drawing_area);
1166
1167     g_signal_connect (drawing_area, "expose-event",  
1168                       G_CALLBACK (on_expose_event_draw),
1169                       &scherzo);
1170
1171     g_signal_connect (scherzo.window, "key-press-event",
1172                       G_CALLBACK (on_key_press_event),
1173                       &scherzo);
1174
1175     g_signal_connect (scherzo.window, "key-release-event",
1176                       G_CALLBACK (on_key_release_event),
1177                       &scherzo);
1178     
1179     gtk_widget_show_all (scherzo.window);
1180     
1181     gtk_main ();
1182
1183     mnemon_save (&scherzo.mnemon);
1184
1185     snd_midi_event_free (scherzo.snd_midi_event);
1186
1187     talloc_free (scherzo.ctx);
1188
1189     return 0;
1190 }