]> git.cworth.org Git - scherzo/blob - scherzo.c
c0582f132517c674e762d1952459c5860113a703
[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 {
491 #define MAX_DEGREES 4
492     int relative_pitches[MAX_DEGREES];
493     int i;
494
495     assert (num_degrees <= MAX_DEGREES);
496
497     if (num_notes != num_degrees)
498             return 0;
499
500     for (i = 0; i < num_degrees; i++)
501         relative_pitches[i] = _modified_degree_to_half_steps (&degrees[i]);
502
503     for (i = 0; i < num_notes; i++)
504         if (notes[i].relative_pitch != relative_pitches[i])
505             return 0;
506
507     return 1;
508 }
509
510 static void
511 scherzo_analyze_chord (scherzo_t *scherzo)
512 {
513     void *local = talloc_new (NULL);
514     analyzed_note_t *notes;
515     note_group_t *note_group;
516     unsigned i, j, num_notes;
517     int bass_pitch;
518     const char *chord_name = NULL;
519
520     if (scherzo->pedal_pressed)
521         note_group = &scherzo->notes_pedaled;
522     else
523         note_group = &scherzo->notes_pressed;
524
525     num_notes = note_group->num_notes;
526
527     struct { modified_degree_t degrees[1]; const char *name; } octaves[] = {
528         { {{0, 0}}, "Octave"}
529     };
530
531     struct { modified_degree_t degrees[2]; const char *name; } intervals[] = {
532         { {{1, 0}, {2, -1}}, "Minor 2nd"},
533         { {{1, 0}, {2,  0}}, "Major 2nd"},
534         { {{1, 0}, {3, -1}}, "Minor 3rd"},
535         { {{1, 0}, {3,  0}}, "Major 3rd"},
536         { {{1, 0}, {4,  0}}, "Perfect 4th"},
537         { {{1, 0}, {5, -1}}, "Diminished 5th"},
538         { {{1, 0}, {5,  0}}, "Perfect 5th"},
539         { {{1, 0}, {6, -1}}, "Minor 6th"},
540         { {{1, 0}, {6,  0}}, "Major 6th"},
541         { {{1, 0}, {7, -1}}, "Minor 7th"},
542         { {{1, 0}, {7,  0}}, "Major 7th"}
543     };
544
545     struct { modified_degree_t degrees[3]; const char *name; } triads[] = {
546         { {{1, 0}, {3,  0}, {5, +1}}, "Augmented triad" },
547         { {{1, 0}, {3,  0}, {5,  0}}, "Major triad" },
548         { {{1, 0}, {3, -1}, {5,  0}}, "Minor triad" },
549         { {{1, 0}, {3, -1}, {5, -1}}, "Diminished triad" }
550     };
551
552     struct { modified_degree_t degrees[4]; const char *name; } sevenths[] = {
553         { {{1, 0}, {3,  0}, {5, +1}, {7,  0}}, "Augmented/major 7" },
554         { {{1, 0}, {3,  0}, {5, +1}, {7, -1}}, "Augmented 7" },
555         { {{1, 0}, {3,  0}, {5,  0}, {7,  0}}, "Major 7" },
556         { {{1, 0}, {3,  0}, {5,  0}, {7, -1}}, "Dominant 7" },
557         { {{1, 0}, {3, -1}, {5,  0}, {7,  0}}, "Minor/major 7" },
558         { {{1, 0}, {3, -1}, {5,  0}, {7, -1}}, "Minor 7" },
559         { {{1, 0}, {3, -1}, {5, -1}, {7,  0}}, "Diminished/major 7" },
560         { {{1, 0}, {3, -1}, {5, -1}, {7, -1}}, "Half-diminished 7" },
561         { {{1, 0}, {3, -1}, {5, -1}, {7, -2}}, "Diminished 7" }
562     };
563
564     if (scherzo->chord) {
565         score_remove_chord (scherzo->chord);
566         scherzo->chord = NULL;
567     }
568
569     if (num_notes <= 1)
570         goto DONE;
571
572     notes = talloc_array (local, analyzed_note_t, num_notes);
573     if (notes == NULL)
574         goto DONE;
575
576     for (i = 0; i < num_notes; i++) {
577         score_note_t *note = note_group->notes[i];
578         notes[i].note = note;
579         notes[i].midi_pitch = _score_pitch_and_octave_to_midi (note->pitch,
580                                                                note->octave);
581         /* Relative pitch will be filled in after sorting. */
582         notes[i].relative_pitch = 0;
583     }
584
585     /* First, sort by midi pitch to find the bass note. */
586     qsort (notes, num_notes, sizeof (analyzed_note_t),
587            _compare_analyzed_note_by_midi_pitch);
588     
589     bass_pitch = notes[0].midi_pitch;
590
591     /* With the bass note identified, we can find all relative pitches. */
592     for (i = 0; i < num_notes; i++) {
593         notes[i].relative_pitch = notes[i].midi_pitch - bass_pitch;
594         while (notes[i].relative_pitch >= 12)
595             notes[i].relative_pitch -= 12;
596     }
597
598     /* Now, sort again by relative pitch. */
599     qsort (notes, num_notes, sizeof (analyzed_note_t),
600            _compare_analyzed_note_by_relative_pitch);
601
602     /* Finally, eliminate all duplicate notes. */
603     for (i = 0; i < num_notes - 1; i++) {
604             if (notes[i+1].relative_pitch == notes[i].relative_pitch) {
605                     j = i+1;
606                     while (j < num_notes &&
607                            notes[j].relative_pitch == notes[i].relative_pitch)
608                     {
609                             j++;
610                     }
611                     /* The loop incremented j one past the last
612                      * duplicate. Decrement so that it points to the
613                      * last duplicate (and is guaranteed to not exceed
614                      * the array bounds).*/
615                     j--;
616
617                     if (j < num_notes - 1) {
618                             memmove (&notes[i+1], &notes[j+1],
619                                      (num_notes - j) * sizeof (analyzed_note_t));
620                     }
621
622                     num_notes -= (j - i);
623             }
624     }
625
626     switch (num_notes) {
627     case 1:
628         for (i = 0; i < ARRAY_SIZE (octaves); i++) {
629             if (_chord_signature_matches (notes, num_notes,
630                                           octaves[i].degrees, 1))
631                 chord_name = octaves[i].name;
632         }
633         break;
634     case 2:
635         for (i = 0; i < ARRAY_SIZE (intervals); i++) {
636             if (_chord_signature_matches (notes, num_notes,
637                                           intervals[i].degrees, 2))
638                 chord_name = intervals[i].name;
639         }
640         break;
641     case 3:
642         for (i = 0; i < ARRAY_SIZE (triads); i++) {
643             if (_chord_signature_matches (notes, num_notes,
644                                           triads[i].degrees, 3))
645                 chord_name = triads[i].name;
646         }
647         break;
648     case 4:
649         for (i = 0; i < ARRAY_SIZE(sevenths); i++) {
650             if (_chord_signature_matches (notes, num_notes,
651                                           sevenths[i].degrees, 4))
652                 chord_name = sevenths[i].name;
653         }
654         break;
655     }
656
657     if (chord_name)
658         scherzo->chord = score_add_chord (scherzo->treble, chord_name);
659     else
660         scherzo->chord = score_add_chord (scherzo->treble, "Unknown or not a chord");
661
662 DONE:
663     talloc_free (local);
664 }
665
666 static void
667 note_group_init (void *ctx, note_group_t *group)
668 {
669     group->ctx = ctx;
670     group->notes = NULL;
671     group->size = 0;
672     group->num_notes = 0;
673 }
674
675 static void
676 note_group_add_note (note_group_t *group, score_note_t *note)
677 {
678     int i;
679
680     /* Do nothing if note is already in group. */
681     for (i = 0; i < group->num_notes; i++) {
682         if (group->notes[i]->pitch == note->pitch &&
683             group->notes[i]->octave == note->octave)
684         {
685             return;
686         }
687     }
688
689     group->num_notes++;
690
691     if (group->num_notes > group->size) {
692         group->size++;
693         group->notes = talloc_realloc (group->ctx, group->notes,
694                                        score_note_t*, group->size);
695
696         if (group->notes == NULL) {
697             fprintf (stderr, "Out of memory.\n");
698             exit (1);
699         }
700     }
701
702     group->notes[group->num_notes - 1] = note;
703 }
704
705 static void
706 note_group_remove_note_at (note_group_t *group, int i)
707 {
708     if (i >= group->num_notes) {
709         fprintf (stderr, "Internal error: No note to remove at index %d\n", i);
710         exit (1);
711     }
712
713     if (i < group->num_notes - 1) {
714         memmove (group->notes + i, group->notes + i + 1,
715                  (group->num_notes - 1 - i) * sizeof (score_note_t*));
716     }
717     group->num_notes--;
718 }
719
720 static score_note_t *
721 scherzo_press_note (scherzo_t *scherzo, score_pitch_t pitch, int octave)
722 {
723     score_staff_t *staff;
724     score_note_t *note;
725     int i;
726
727     if (scherzo->challenge.note) {
728         staff = scherzo->challenge.staff;
729     } else if (octave >= 4) {
730         staff = scherzo->treble;
731     } else {
732         staff = scherzo->bass;
733     }
734
735     /* Do nothing if this note is already pressed. */
736     for (i = 0; i < scherzo->notes_pressed.num_notes; i++) {
737         if (scherzo->notes_pressed.notes[i]->pitch == pitch &&
738             scherzo->notes_pressed.notes[i]->octave == octave)
739         {
740             return scherzo->notes_pressed.notes[i];
741         }
742     }
743
744     note = score_add_note (staff, pitch, octave, SCORE_DURATION_WHOLE);
745
746     note_group_add_note (&scherzo->notes_pressed, note);
747
748     if (scherzo->pedal_pressed)
749         note_group_add_note (&scherzo->notes_pedaled, note);
750
751     scherzo_analyze_chord (scherzo);
752
753     return note;
754 }
755
756 static void
757 scherzo_release_note (scherzo_t *scherzo, score_pitch_t pitch, int octave)
758 {
759     score_note_t *note;
760     int i;
761     int found = 0;
762
763     for (i = scherzo->notes_pressed.num_notes - 1; i >=0; i--) {
764         note = scherzo->notes_pressed.notes[i];
765         if (note->pitch == pitch && note->octave == octave) {
766             found = 1;
767             if (! scherzo->pedal_pressed)
768                 score_remove_note (note);
769             note_group_remove_note_at (&scherzo->notes_pressed, i);
770         }
771     }
772
773     if (found == 0) {
774         fprintf (stderr, "Internal error: Failed to find note to release.\n");
775     }
776
777     scherzo_analyze_chord (scherzo);
778 }
779
780 static score_note_t *
781 scherzo_press_note_midi (scherzo_t *scherzo, unsigned char midi_note)
782 {
783     score_pitch_t pitch;
784     int octave;
785
786     _midi_to_score_pitch_and_octave (midi_note, &pitch, &octave);
787
788     return scherzo_press_note (scherzo, pitch, octave);
789 }
790
791 static void
792 scherzo_release_note_midi (scherzo_t *scherzo, unsigned char midi_note)
793 {
794     score_pitch_t pitch;
795     int octave;
796  
797     _midi_to_score_pitch_and_octave (midi_note, &pitch, &octave);
798
799     scherzo_release_note (scherzo, pitch, octave);
800 }
801
802 static void
803 scherzo_press_pedal (scherzo_t *scherzo)
804 {
805     int i;
806
807     scherzo->pedal_pressed = 1;
808
809     /* Copy all pressed notes to pedaled notes */
810     for (i = 0; i < scherzo->notes_pressed.num_notes; i++)
811         note_group_add_note (&scherzo->notes_pedaled, scherzo->notes_pressed.notes[i]);
812 }
813
814 static void
815 scherzo_release_pedal (scherzo_t *scherzo)
816 {
817     score_note_t *note, *new_note;
818     int i;
819
820     /* Make new notes in score for all pressed notes. */
821     for (i = 0; i < scherzo->notes_pressed.num_notes; i++) {
822         note = scherzo->notes_pressed.notes[i];
823         new_note = score_add_note (note->staff, note->pitch, note->octave, note->duration);
824         scherzo->notes_pressed.notes[i] = new_note;
825     }
826
827     /* Then remove all previously pedaled notes from the score. */
828     for (i = scherzo->notes_pedaled.num_notes - 1; i >=0; i--) {
829         note = scherzo->notes_pedaled.notes[i];
830         score_remove_note (note);
831         note_group_remove_note_at (&scherzo->notes_pedaled, i);
832     }
833
834     scherzo->pedal_pressed = 0;
835
836     scherzo_analyze_chord (scherzo);
837
838     gtk_widget_queue_draw (scherzo->window);
839 }
840
841 void
842 _select_challenge (scherzo_t *scherzo)
843 {
844     category_t *category_unused;
845     bool_t introduced_unused;
846     item_t *item;
847     challenge_t *challenge = &scherzo->challenge;
848     score_pitch_t pitch;
849     int octave;
850     char *s;
851
852     if (challenge->note) {
853         score_remove_note (challenge->note);
854         challenge->note = NULL;
855     }
856
857     mnemon_select_item (&scherzo->mnemon,
858                         &challenge->bin,
859                         &challenge->item_index,
860                         &category_unused,
861                         &introduced_unused);
862
863     item = challenge->bin->items[challenge->item_index];
864
865     s = item->challenge;
866     if (strncmp (s, "treble:", 7) == 0) {
867         s += 7;
868         challenge->staff = scherzo->treble;
869     } else if (strncmp (s, "bass:", 5) == 0) {
870         s += 5;
871         challenge->staff = scherzo->bass;
872     } else {
873         fprintf (stderr,
874                  "Malformed staff name: %s (expected 'treble:' or 'bass:')\n",
875                  s);
876         exit (1);
877     }
878
879     switch (*s) {
880     case 'C':
881         pitch = SCORE_PITCH_C;
882         break;
883     case 'D':
884         pitch = SCORE_PITCH_D;
885         break;
886     case 'E':
887         pitch = SCORE_PITCH_E;
888         break;
889     case 'F':
890         pitch = SCORE_PITCH_F;
891         break;
892     case 'G':
893         pitch = SCORE_PITCH_G;
894         break;
895     case 'A':
896         pitch = SCORE_PITCH_A;
897         break;
898     case 'B':
899         pitch = SCORE_PITCH_B;
900         break;
901     default:
902         fprintf (stderr, "Malformed pitch name: %s (expected 'A' - 'G')\n", s);
903         exit (1);
904     }
905     s++;
906
907     if (*s < '0' || *s > '9') {
908         fprintf (stderr, "Malformed octave number: %s (expected '0' - '9')\n", s);
909         exit (1);
910     }
911
912     octave = *s - '0';
913
914     challenge->note = score_add_note (challenge->staff, pitch, octave,
915                                       SCORE_DURATION_WHOLE);
916     challenge->satisfied = 0;
917     challenge->mistaken = 0;
918 }
919
920 /* Determine whether the user hit the correct note. */
921 static void
922 _judge_note (scherzo_t *scherzo, score_note_t *note)
923 {
924     challenge_t *challenge = &scherzo->challenge;
925
926     if (! scherzo->challenge.note) {
927         score_set_note_color_rgb (note, 0.0, 0.0, 0.0); /* black */
928         return;
929     }
930
931     if (note->pitch == challenge->note->pitch &&
932         note->octave == challenge->note->octave)
933     {
934         challenge->satisfied = 1;
935         score_set_note_color_rgb (note, 18/256., 130/256., 28/256.); /* green */
936     }
937     else
938     {
939         challenge->mistaken = 1;
940         score_set_note_color_rgb (note, 184/256., 4/256., 22/256.); /* red */
941     }
942 }
943
944 /* If the user got the right note (eventually), then score it in
945  * mnemon and show the next note. */
946 static void
947 _score_challenge (scherzo_t *scherzo)
948 {
949     challenge_t *challenge = &scherzo->challenge;
950
951     if (! challenge->note)
952         return;
953
954     if (! challenge->satisfied)
955         return;
956
957     mnemon_score_item (&scherzo->mnemon, challenge->bin, challenge->item_index,
958                        ! challenge->mistaken);
959
960     _select_challenge (scherzo);
961 }
962
963 static int
964 on_midi_input (unused (GIOChannel *channel),
965                unused (GIOCondition condition),
966                void *user_data)
967 {
968     unsigned char buf[MIDI_BUF_SIZE], *next;
969     scherzo_t *scherzo = user_data;
970     ssize_t remaining;
971     snd_seq_event_t event;
972     score_note_t *note;
973     int need_redraw = FALSE;
974
975     remaining = read (scherzo->midi_fd, buf, MIDI_BUF_SIZE);
976
977     next = buf;
978     while (remaining) {
979         long consumed;
980
981         consumed = snd_midi_event_encode (scherzo->snd_midi_event,
982                                           next, remaining, &event);
983
984         remaining -= consumed;
985         next += consumed;
986
987         switch (event.type) {
988         case SND_SEQ_EVENT_NONE:
989             /* Incomplete event. Nothing to do. */
990             break;
991         case SND_SEQ_EVENT_NOTEON:
992             note = scherzo_press_note_midi (scherzo, event.data.note.note);
993             _judge_note (scherzo, note);
994             need_redraw = TRUE;
995             break;
996         case SND_SEQ_EVENT_NOTEOFF:
997             scherzo_release_note_midi (scherzo, event.data.note.note);
998             _score_challenge (scherzo);
999             need_redraw = TRUE;
1000             break;
1001         case SND_SEQ_EVENT_CLOCK:
1002             /* Ignore for now as my piano sends a constant stream of these. */
1003             break;
1004         case SND_SEQ_EVENT_SENSING:
1005             /* Ignore for now as my piano sends a constant stream of these. */
1006             break;
1007         case SND_SEQ_EVENT_CONTROLLER:
1008             /* XXX: My piano gives me 64 for the sustain pedal, is
1009              * that universal? */
1010             if (event.data.control.param == 64) {
1011                 if (event.data.control.value == 0)
1012                     scherzo_release_pedal (scherzo);
1013                 else
1014                     scherzo_press_pedal (scherzo);
1015             } else {
1016                 fprintf (stderr, "Fixme: Unhandled MIDI Control event (param=%d, value=%d)\n",
1017                          event.data.control.param, event.data.control.value);
1018             }
1019             break;
1020         default:
1021             fprintf (stderr, "Fixme: Do not yet know how to handle MIDI event %d\n",
1022                      event.type);
1023             break;
1024         }
1025     }
1026
1027     if (need_redraw)
1028         gtk_widget_queue_draw (scherzo->window);
1029
1030     /* Return TRUE to continue to get called in the future. */
1031     return TRUE;
1032 }
1033
1034 int
1035 main (int argc, char *argv[])
1036 {
1037     GtkWidget *drawing_area;
1038     scherzo_t scherzo;
1039     int err;
1040
1041     srand (time (NULL));
1042
1043     gtk_init (&argc, &argv);
1044
1045     scherzo.ctx = talloc_new (NULL);
1046
1047     scherzo.score = score_create (scherzo.ctx);
1048     scherzo.staff_height = 100;
1049     score_set_staff_height (scherzo.score, scherzo.staff_height);
1050
1051     score_add_brace (scherzo.score, 2);
1052     scherzo.treble = score_add_staff (scherzo.score, SCORE_CLEF_G);
1053     scherzo.bass = score_add_staff (scherzo.score, SCORE_CLEF_F);
1054
1055     scherzo.chord = NULL;
1056
1057     /* Default to octave 4 and natural for computer keyboard keypresses. */
1058     scherzo.keyboard_octave = 4;
1059     scherzo.keyboard_accidental = SCORE_PITCH_ACCIDENTAL_NATURAL;
1060
1061     note_group_init (scherzo.ctx, &scherzo.notes_pressed);
1062     note_group_init (scherzo.ctx, &scherzo.notes_pedaled);
1063
1064     scherzo.pedal_pressed = 0;
1065
1066     mnemon_init (&scherzo.mnemon);
1067     /* XXX: Should create a default file if one cannot be loaded. */
1068     mnemon_load_category (&scherzo.mnemon, "scherzo-notes");
1069
1070     scherzo.challenge.note = NULL;
1071 /*
1072     _select_challenge (&scherzo);
1073 */
1074
1075     err = snd_midi_event_new (MIDI_BUF_SIZE, &scherzo.snd_midi_event);
1076     if (err) {
1077         fprintf (stderr, "Out of memory.\n");
1078         return 1;
1079     }
1080
1081 #define MIDI_DEVICE "/dev/midi1"
1082     scherzo.midi_fd = open (MIDI_DEVICE, O_RDONLY);
1083     if (scherzo.midi_fd < 0) {
1084         printf ("failed to open " MIDI_DEVICE ". Midi input will not be available.\n");
1085     } else {
1086         GIOChannel *channel;
1087
1088         channel = g_io_channel_unix_new (scherzo.midi_fd);
1089         g_io_channel_set_encoding (channel, NULL, NULL);
1090         g_io_add_watch (channel, G_IO_IN, on_midi_input, &scherzo);
1091     }
1092
1093     scherzo.window = gtk_window_new (GTK_WINDOW_TOPLEVEL);
1094
1095     gtk_window_set_default_size (GTK_WINDOW (scherzo.window), 1000, 600);
1096
1097     g_signal_connect (scherzo.window, "delete-event",
1098                       G_CALLBACK (on_delete_event_quit), NULL);
1099
1100     drawing_area = gtk_drawing_area_new ();
1101
1102     gtk_container_add (GTK_CONTAINER (scherzo.window), drawing_area);
1103
1104     g_signal_connect (drawing_area, "expose-event",  
1105                       G_CALLBACK (on_expose_event_draw),
1106                       &scherzo);
1107
1108     g_signal_connect (scherzo.window, "key-press-event",
1109                       G_CALLBACK (on_key_press_event),
1110                       &scherzo);
1111
1112     g_signal_connect (scherzo.window, "key-release-event",
1113                       G_CALLBACK (on_key_release_event),
1114                       &scherzo);
1115     
1116     gtk_widget_show_all (scherzo.window);
1117     
1118     gtk_main ();
1119
1120     mnemon_save (&scherzo.mnemon);
1121
1122     snd_midi_event_free (scherzo.snd_midi_event);
1123
1124     talloc_free (scherzo.ctx);
1125
1126     return 0;
1127 }