]> git.cworth.org Git - mnemon/blob - main.c
Further separation of mnemon main program from mnemon library.
[mnemon] / main.c
1 /* mnemon - A memory training program
2  * 
3  * Copyright © 2006,2011 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, or (at your option)
8  * 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, write to the Free Software Foundation,
17  * Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA."
18  */
19
20 /* for asprintf */
21 #define _GNU_SOURCE
22 #include <stdio.h>
23 #include <stdlib.h>
24 #include <stdarg.h>
25 #include <stdint.h>
26 #include <math.h>
27
28 #include <sys/types.h>
29 #include <sys/time.h>
30 #include <sys/stat.h>
31 #include <unistd.h>
32 #include <dirent.h>
33 #include <errno.h>
34 #include <string.h>
35 #include <assert.h>
36
37 #include <readline/readline.h>
38 #include <readline/history.h>
39
40 #include "mnemon.h"
41
42 #define ASSERT_NOT_REACHED              \
43 do {                                    \
44     static const int NOT_REACHED = 0;   \
45     assert (NOT_REACHED);               \
46 } while (0)
47
48 typedef struct progress {
49     int to_introduce;
50     int to_master;
51     int unlearned;
52     int mastered;
53 } progress_t;
54
55 static char *
56 xstrndup (const char *s, size_t n)
57 {
58     char *ret;
59
60     ret = strndup (s, n);
61     if (ret == NULL) {
62         fprintf (stderr, "Error: out of memory\n");
63         exit (1);
64     }
65
66     return ret;
67 }
68
69 static void
70 xasprintf (char **strp, const char *fmt, ...)
71 {
72     va_list ap;
73     int ret;
74
75     va_start (ap, fmt);
76     ret = vasprintf (strp, fmt, ap);
77     va_end (ap);
78
79     if (ret < 0) {
80         fprintf (stderr, "Error: out of memory\n");
81         exit (1);
82     }
83 }
84
85 static void
86 _show_challenge (mnemon_t *mnemon,
87                  challenge_type_t challenge_type,
88                  const char *challenge)
89 {
90     const char *program;
91     char *command;
92
93     if (challenge_type == CHALLENGE_TYPE_TEXT) {
94         printf ("%s\n", challenge);
95         return;
96     }
97
98     /* XXX: Yes, shelling out to system is total cheese. The planned
99      * fix here is to bring graphical display in process, (or at least
100      * have a custom external program that accepts image filenames on
101      * stdin.
102      */
103     switch (challenge_type) {
104     case CHALLENGE_TYPE_TEXT:
105         ASSERT_NOT_REACHED;
106         break;
107     case CHALLENGE_TYPE_IMAGE:
108         program = "xli -gamma 2.2";
109         break;
110     case CHALLENGE_TYPE_AUDIO:
111         program = "play";
112         break;
113     case CHALLENGE_TYPE_MIDI:
114         program = "timidity -Os";
115         break;
116     case CHALLENGE_TYPE_TEXT_TO_SPEECH:
117         program = "mnemon-tts";
118         break;
119     }
120
121     xasprintf (&command, "%s %s/%s >/dev/null 2>&1 &",
122                program,
123                mnemon->dir_name,
124                challenge);
125     system (command);
126     free (command);
127 }
128
129 static void
130 _hide_challenge (unused (mnemon_t *mnemon),
131                  challenge_type_t challenge_type)
132 {
133     char * command;
134
135     if (challenge_type != CHALLENGE_TYPE_IMAGE)
136         return;
137
138     /* XXX: And this is just embarrassing (obviously wrong in several
139      * ways). Hopefully I'll amend away any commit that includes this.
140      */
141     xasprintf (&command, "killall xli");
142     system (command);
143     free (command);
144 }
145
146 typedef int (item_match_predicate_t) (void *closure, item_t *item);
147
148 /* Return the number of items in the bin from the given category (or
149  * from all categories if category == NULL) */
150 static int
151 bin_num_items_matching (bin_t                   *bin,
152                         item_match_predicate_t  *predicate,
153                         void                    *closure)
154 {
155     int i, num_items = 0;
156
157     if (predicate == NULL)
158         return bin->num_items;
159
160     for (i = 0; i < bin->num_items; i++)
161         if ((predicate) (closure, bin->items[i]))
162             num_items++;
163
164     return num_items;
165 }
166
167 typedef struct _item_in_category_closure
168 {
169     mnemon_t *mnemon;
170     category_t *category;
171 } item_in_category_closure_t;
172
173 static int
174 mnemon_item_in_category (void *closure, item_t *item)
175 {
176     item_in_category_closure_t *iicc = closure;
177     mnemon_t *mnemon = iicc->mnemon;
178     category_t *category = iicc->category;
179
180     return (mnemon_item_category (mnemon, item) == category);
181 }
182
183 typedef struct _item_in_category_of_length_closure
184 {
185     mnemon_t *mnemon;
186     category_t *category;
187     int length;
188 } item_in_category_of_length_closure_t;
189
190 static int
191 mnemon_item_in_category_of_length (void *closure, item_t *item)
192 {
193     item_in_category_of_length_closure_t *iicolc = closure;
194     mnemon_t *mnemon = iicolc->mnemon;
195     category_t *category = iicolc->category;
196     unsigned int length = iicolc->length;
197
198     if (mnemon_item_category (mnemon, item) != category)
199         return 0;
200
201     return strlen (item->challenge) == length;
202 }
203
204 #define HISTOGRAM_ROW_FORMAT "%3d: %3d"
205 #define HISTOGRAM_BAR_WIDTH  63
206
207 static void
208 print_histogram_bar (double     size,
209                      double     max)
210 {
211     int units_per_cell = (int) ceil (max / HISTOGRAM_BAR_WIDTH);
212     static char const *boxes[8] = {
213         "█", "▉", "▊", "▋",
214         "▌", "▍", "▎", "▏"
215     };
216
217     while (size > units_per_cell) {
218         printf(boxes[0]);
219         size -= units_per_cell;
220     }
221
222     size /= units_per_cell;
223
224     if (size > 7.5/8.0)
225         printf(boxes[0]);
226     else if (size > 6.5/8.0)
227         printf(boxes[1]);
228     else if (size > 5.5/8.0)
229         printf(boxes[2]);
230     else if (size > 4.5/8.0)
231         printf(boxes[3]);
232     else if (size > 3.5/8.0)
233         printf(boxes[4]);
234     else if (size > 2.5/8.0)
235         printf(boxes[5]);
236     else if (size > 1.5/8.0)
237         printf(boxes[6]);
238     else if (size > 0.5/8.0)
239         printf(boxes[7]);
240
241     printf ("\n");
242 }
243
244 /* Print a histogram showing the number of items in each bin.
245  *
246  * If category_name is not NULL, then only the items from the given
247  * category (matching a particular filename within the user's .mnemon
248  * directory) will be shown.
249  *
250  * If length is non zero, then only items with a challenge string of
251  * 'length' characters will be shown. (This is only useful for
252  * particular types of challenges, such as for showing anagram
253  * challenges of a given length).
254  *
255  * To see a histogram of all currently-loaded items, pass NULL for
256  * category and 0 for length.
257  *
258  * Note: Some bins may be removed entirely by (a misfeature side
259  * effect of) the mnemon_do_challenges function, (such as bin 0 being
260  * removed after the introduction phase is complete). An accurate
261  * histogram can be guaranteed by calling menmon_print_histogram
262  * immediately after calling mnemon_load.
263  */
264 static void
265 print_histogram (mnemon_t    *mnemon,
266                  const char  *category_name,
267                  int         length)
268 {
269     int i, last_score, max;
270     category_t *category = NULL;
271     bin_t *bin;
272     int num_items;
273     item_match_predicate_t *predicate = NULL;
274     void *closure = NULL;
275     item_in_category_closure_t item_in_category;
276     item_in_category_of_length_closure_t item_in_category_of_length;
277
278     if (mnemon->num_bins == 0)
279         return;
280
281     if (category_name) {
282         category = mnemon_get_category_if_exists (mnemon, category_name);
283         if (category) {
284             if (length) {
285                 predicate = mnemon_item_in_category_of_length;
286                 item_in_category_of_length.mnemon = mnemon;
287                 item_in_category_of_length.category = category;
288                 item_in_category_of_length.length = length;
289                 closure = &item_in_category_of_length;
290             } else {
291                 predicate = mnemon_item_in_category;
292                 item_in_category.mnemon = mnemon;
293                 item_in_category.category = category;
294                 closure = &item_in_category;
295             }
296         }
297     }
298
299     for (i = 0; i < mnemon->num_bins; i++) {
300         num_items = bin_num_items_matching (&mnemon->bins[i],
301                                             predicate, closure);
302         if (i == 0 || num_items > max)
303             max = num_items;
304     }
305
306     for (i = 0; i < mnemon->num_bins; i++) {
307         bin = &mnemon->bins[i];
308         if (i != 0)
309             while (bin->score - last_score > 1)
310                 printf (HISTOGRAM_ROW_FORMAT "\n", ++last_score, 0);
311         num_items = bin_num_items_matching (bin,
312                                             predicate, closure);
313         printf (HISTOGRAM_ROW_FORMAT " ", bin->score, num_items);
314         print_histogram_bar (num_items, max);
315         last_score = bin->score;
316     }
317 }
318
319 static void
320 _handle_command (mnemon_t               *mnemon,
321                  const char     *command)
322 {
323     const char *arg;
324     int len;
325     switch (command[0]) {
326         /* 'h' for histogram */
327         case 'h':
328         {
329             char *category = NULL;
330             int length = 0;
331
332             arg = command + 1;
333             arg += strspn (arg, " \t");
334             len = strcspn (arg, " \t");
335             if (len) {
336                 category = xstrndup (arg, len);
337                 arg += len;
338                 arg += strspn (arg, " \t");
339                 if (*arg)
340                     length = atoi (arg);
341             }
342             print_histogram (mnemon, category, length);
343         }
344         break;
345         /* 'r' for repeat */
346         case 'r':
347         {
348             /* Nothing necessary for repeating. */
349         }
350         break;
351         default:
352             printf ("Unknown command: %s\n", command);
353             break;
354     }
355 }
356
357 static void
358 _handle_response (mnemon_t      *mnemon,
359                   bin_t         *bin,
360                   int            item_index,
361                   item_t        *item,
362                   const char    *response,
363                   double         response_time,
364                   double         time_limit,
365                   progress_t    *progress)
366 {
367     bool_t correct;
368     int old_score = item->score;
369
370     correct = (strcmp (response, item->response) == 0);
371
372     if (! correct)
373     {
374             printf ("  %s is the correct answer.",
375                     item->response);
376     }
377
378     if (correct &&
379         (time_limit != 0.0 && response_time > time_limit))
380     {
381             printf ("Correct, but not quite quick enough (%0.2f seconds---needed %0.2f seconds)\n",
382                     response_time, time_limit);
383             correct = 0;
384     }
385
386     mnemon_score_item (mnemon, bin, item_index, correct);
387
388
389     if (correct) {
390         if (item->score < 0) {
391             printf ("Yes---just give me %d more.",
392                     - item->score);
393         } else if (item->score == 1) {
394             if (old_score < 0) {
395                 progress->unlearned--;
396                 printf ("You got it!");
397             } else {
398                 printf ("On your first try, no less!");
399             }
400         } else {
401             printf ("Masterful (%dx).", item->score);
402             if (progress->to_master)
403                 progress->to_master--;
404         }
405     } else {
406         if (old_score > 0) {
407             printf (" Oops, you knew that, right? (%dx)\n ",
408                     old_score);
409             progress->unlearned++;
410             /* We increase to_master here as an extra penalty. If the
411              * user is forgetting stuff learned previously, then more
412              * time should be spent on mastering than learning new
413              * items. Note that we only do this during the initial
414              * phase while new items are still being introduced. */
415             if (progress->to_introduce)
416                 progress->to_master++;
417         }
418     }
419
420     printf (" ");
421     if (progress->to_introduce)
422         printf ("%d to come. ", progress->to_introduce);
423     if (progress->unlearned)
424         printf ("%d still unlearned. ", progress->unlearned);
425     if (progress->to_introduce == 0 && progress->to_master > 0)
426         printf ("%d items to master", progress->to_master);
427     printf ("\n\n");
428 }
429
430 /* A session of challenges consists of three phases, some of which may
431  * be entirely empty, as follows:
432  *    
433  * 1. The introduction phase
434  *  
435  *     This phase is controlled by the to_introduce counter which is
436  *     by default set to 10. It is decremented every time an item is
437  *     introduced from the bin with score 0, or (if there is no bin
438  *     with score 0), every time an item is introduced from the bin
439  *     with the lowest non-negative score of any bin.
440  *
441  * 2. The mastering phase
442  *  
443  *     This phase is controlled by the to_master counter which is
444  *     initially set to 10. It begins at the beginning of the session
445  *     so can run concurrently with the introduction phase. The
446  *     to_master counter is decremented every time an item with a
447  *     positive (non-zero) score is answered correctly. It is also
448  *     incremented every time an item with a positive (non-zero) score
449  *     is answered incorrectly during the introduction phase. If
450  *     perfect mastery is demonstrated, the mastering phase is likely
451  *     to be complete simultaneous with the introduction stage. If the
452  *     user is really struggling with mastery, the mastering phase
453  *     will extend long after the introduction phase is over. But
454  *     since we never incremeent to_master after the introduction
455  *     phase is over, the user cannot build an infinite snowball of
456  *     to_master items and have to give up in despair.
457  *
458  * 3. The solidifying phase
459  *  
460  *     This final phase continues after the mastering phase for as
461  *     long as any items with a negative score remain. The idea here
462  *     is that we want to quickly give the reinforcement from a missed
463  *     item in the current session. Also, there's a bit of a challenge
464  *     to the user to demonstrate good mastery of any non-negative
465  *     items presented so that the phase actually terminates. It's
466  *     possible for this phase to extend for an arbitrary amount of
467  *     time, but not very likely, (since the negative items are chosen
468  *     preferentially and the user will continue to see the correct
469  *     answers to them over and over).
470  *
471  * This function returns after all three phases are complete.
472  *
473  * The user's progress (the movement of items to various new bins) is
474  * kept only in memory. In order to save this progress to disk, the
475  * caller must call mnemon_save.
476  */
477 static void
478 _do_challenges (mnemon_t *mnemon, progress_t *progress)
479 {
480     bin_t *bin;
481     int item_index;
482     item_t *item;
483     category_t *category;
484     char *response;
485     int i;
486
487     /* Count the number of items with negative scores. */
488     progress->unlearned = 0;
489     for (i = 0; i < mnemon->num_bins; i++) {
490         bin = &mnemon->bins[i];
491         if (bin->score >= 0)
492             break;
493         progress->unlearned += bin->num_items;
494     }
495
496     progress->to_introduce -= progress->unlearned;
497     if (progress->to_introduce < 0)
498         progress->to_introduce = 0;
499
500     /* Get rid of bin with score of 0 if we aren't going to be
501      * introducing anything from it. */
502     if (progress->to_introduce == 0) {
503         mnemon_remove_bin (mnemon, 0);
504     }
505
506     if (progress->unlearned) {
507         printf ("You've got %d items to learn already. ", progress->unlearned);
508         if (progress->to_introduce)
509             printf ("I'll introduce %d more as we go.", progress->to_introduce);
510         printf ("\n");
511     } else {
512         printf ("Introducing %d new items.\n", progress->to_introduce);
513     }
514     printf ("\n");
515
516     do {
517         struct timeval start, end;
518         int introduced;
519         
520         mnemon_select_item (mnemon, &bin, &item_index, &category, &introduced);
521         item = bin->items[item_index];
522
523         if (progress->to_introduce > 0 && introduced)
524             progress->to_introduce--;
525
526         while (1) {
527             if (category->time_limit > 0.0) {
528                 response = readline ("The next one is timed. Press enter when ready:");
529                 free (response);
530             }
531
532             _show_challenge (mnemon, category->challenge_type,
533                              item->challenge);
534
535             gettimeofday (&start, NULL);
536             response = readline ("> ");
537             gettimeofday (&end, NULL);
538
539             _hide_challenge (mnemon, category->challenge_type);
540
541             /* Terminate on EOF */
542             if (response == NULL) {
543                 printf ("\n");
544                 return;
545             }
546
547             if (response[0] == '/') {
548                 _handle_command (mnemon, response + 1);
549                 free (response);
550             } else {
551                 break;
552             }
553         }
554
555         _handle_response (mnemon, bin, item_index,
556                           item, response,
557                           (end.tv_sec + end.tv_usec / 1e6) -
558                           (start.tv_sec + start.tv_usec / 1e6),
559                           category->time_limit, progress);
560         free (response);
561
562         /* Replay audio challenges for reinforcement. */
563         if (category->repeat)
564         {
565             _show_challenge (mnemon, category->challenge_type,
566                              item->challenge);
567             printf ("%s\n", item->challenge);
568             sleep (2);
569         }
570     } while (progress->to_introduce ||
571              progress->unlearned ||
572              progress->to_master > 0);
573 }
574
575 int
576 main (int argc, char *argv[])
577 {
578     mnemon_t mnemon;
579     char *response;
580     progress_t progress;
581
582     void _load_categories()
583     {
584         if (argc > 1) {
585             int i;
586             for (i = 1; i < argc; i++)
587                 mnemon_load_category (&mnemon, argv[i]);
588         } else {
589             mnemon_load (&mnemon);
590         }
591     }
592
593     srand (time (NULL));
594
595     mnemon_init (&mnemon);
596
597     _load_categories ();
598
599     /* Set some reasonable defaults for a session */
600     progress.to_introduce = 10;
601     progress.to_master = 10;
602     progress.unlearned = 0;
603     progress.mastered = -1;
604
605     _do_challenges (&mnemon, &progress);
606
607     mnemon_save (&mnemon);
608
609     mnemon_fini (&mnemon);
610
611     mnemon_init (&mnemon);
612
613     _load_categories ();
614
615     printf ("Great job.\nHere are your current results:\n");
616     print_histogram (&mnemon, NULL, 0);
617     response = readline ("Press enter to quit.\n");
618     free (response);
619
620     mnemon_fini (&mnemon);
621
622     return 0;
623 }