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