summaryrefslogtreecommitdiffstats
path: root/apps/plugins/speedread.c
blob: 42634fb536b82e3b2b2cdadc2be2ce181bd34c5c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
/***************************************************************************
 *             __________               __   ___.
 *   Open      \______   \ ____   ____ |  | _\_ |__   _______  ___
 *   Source     |       _//  _ \_/ ___\|  |/ /| __ \ /  _ \  \/  /
 *   Jukebox    |    |   (  <_> )  \___|    < | \_\ (  <_> > <  <
 *   Firmware   |____|_  /\____/ \___  >__|_ \|___  /\____/__/\_ \
 *                     \/            \/     \/    \/            \/
 * $Id$
 *
 * Copyright (C) 2017 Franklin Wei
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 *
 * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
 * KIND, either express or implied.
 *
 ***************************************************************************/

/* ideas for improvement:
 *  hyphenation of long words */

#include "plugin.h"

#include "fixedpoint.h"

#include "lib/helper.h"
#include "lib/pluginlib_actions.h"
#include "lib/pluginlib_exit.h"

#define LINE_LEN 1024
#define WORD_MAX 64

#define MIN_WPM 100
#define MAX_WPM 1000
#define DEF_WPM 250
#define WPM_INCREMENT 25

/* mininum bytes to skip when seeking */
#define SEEK_INTERVAL 100

#define FOCUS_X (7 * LCD_WIDTH / 20)
#define FOCUS_Y 0

#define FRAME_COLOR LCD_BLACK
#define BACKGROUND_COLOR LCD_WHITE /* inside frame */

#ifdef HAVE_LCD_COLOR
#define WORD_COLOR LCD_RGBPACK(48,48,48)
#define FOCUS_COLOR LCD_RGBPACK(204,0,0)
#define OUTSIDE_COLOR LCD_RGBPACK(128,128,128)
#define BAR_COLOR LCD_RGBPACK(230,230,230)
#else
#define WORD_COLOR LCD_BLACK
#define OUTSIDE_COLOR BACKGROUND_COLOR
#endif

#define BOOKMARK_FILE VIEWERS_DATA_DIR "/speedread.dat"
#define CONFIG_FILE VIEWERS_DATA_DIR "/speedread.cfg"

#define ANIM_TIME (75 * HZ / 100)

int fd = -1; /* -1 = prescripted demo */

int word_num; /* which word on a line */
off_t line_offs, begin_offs; /* offsets from the "real" beginning of the file to the current line and end of BOM */

int line_len = -1, custom_font = FONT_UI;

const char *last_word = NULL;

static const char *get_next_word(void)
{
    if(fd >= 0)
    {
        static char line_buf[LINE_LEN];
        static char *end = NULL;

    next_line:

        if(line_len < 0)
        {
            line_offs = rb->lseek(fd, 0, SEEK_CUR);
            line_len = rb->read_line(fd, line_buf, LINE_LEN);
            if(line_len <= 0)
                return NULL;

            char *word = rb->strtok_r(line_buf, " ", &end);

            word_num = 0;

            if(!word)
                goto next_line;
            else
            {
                last_word = word;
                return word;
            }
        }

        char *word = rb->strtok_r(NULL, " ", &end);
        if(!word)
        {
            /* end of line */
            line_len = -1;
            goto next_line;
        }
        ++word_num;

        last_word = word;
        return word;
    }
    else
    {
        /* feed the user a quick demo */
        static const char *words[] = { "This", "plugin", "is", "for", "speed-reading", "plain", "text", "files.",
                                 "Please", "open", "a", "plain", "text", "file", "to", "read", "by", "using", "the", "context", "menu.",
                                 "Have", "a", "nice", "day!" };
        static unsigned idx = 0;
        if(idx + 1 > ARRAYLEN(words))
            return NULL;
        last_word = words[idx++];
        return last_word;
    }
}

static const char *get_last_word(void)
{
    if(last_word)
        return last_word;
    else
    {
        last_word = get_next_word();
        return last_word;
    }
}

static void cleanup(void)
{
    if(custom_font != FONT_UI)
        rb->font_unload(custom_font);
#ifdef HAVE_BACKLIGHT
    backlight_use_settings();
#endif
}

/* returns height of drawn area */
static int reset_drawing(long proportion) /* 16.16 fixed point, goes from 0 --> 1 over time */
{
    int w, h;
    rb->lcd_getstringsize("X", &w, &h);

    /* clear word area */
    rb->lcd_set_foreground(BACKGROUND_COLOR);
    rb->lcd_fillrect(0, 0, LCD_WIDTH, h * 3 / 2);

    if(proportion)
    {
#ifdef HAVE_LCD_COLOR
        rb->lcd_set_foreground(BAR_COLOR);
#endif
        rb->lcd_fillrect(fp_mul(proportion, FOCUS_X << 16, 16) >> 16, FOCUS_Y, fp_mul((1 << 16) - proportion, LCD_WIDTH << 16, 16) >> 16, h * 3 / 2);
    }

    rb->lcd_set_foreground(FRAME_COLOR);

    /* draw frame */
    rb->lcd_fillrect(0, h * 3 / 2, LCD_WIDTH, w / 2);
    rb->lcd_fillrect(FOCUS_X - w / 4, FOCUS_Y + h * 5 / 4, w / 2, h / 2);

    rb->lcd_set_foreground(WORD_COLOR);

    return h * 3 / 2 + w / 2;
}

static void render_word(const char *word, int focus)
{
    /* focus char first */
    char buf[5] = { 0, 0, 0, 0, 0 };
    int idx = rb->utf8seek(word, focus);
    rb->memcpy(buf, word + idx, MIN(rb->utf8seek(word, focus + 1) - idx, 4));

    int focus_w;
    rb->lcd_getstringsize(buf, &focus_w, NULL);

#ifdef HAVE_LCD_COLOR
    rb->lcd_set_foreground(FOCUS_COLOR);
#endif

    rb->lcd_putsxy(FOCUS_X - focus_w / 2, FOCUS_Y, buf);

#ifdef HAVE_LCD_COLOR
    rb->lcd_set_foreground(WORD_COLOR);
#endif

    /* figure out how far left to shift */
    static char half[WORD_MAX];
    rb->strlcpy(half, word, rb->utf8seek(word, focus + 1));
    int w;
    rb->lcd_getstringsize(half, &w, NULL);

    int x = FOCUS_X - focus_w / 2 - w;

    /* first half */
    rb->lcd_putsxy(x, FOCUS_Y, half);

    /* second half */
    x = FOCUS_X + focus_w / 2;
    rb->lcd_putsxy(x, FOCUS_Y, word + rb->utf8seek(word, focus + 1));
}

static int calculate_focus(const char *word)
{
#if 0
    int len = rb->utf8length(word);
    int focus = -1;
    for(int i = len / 5; i < len / 2; ++i)
    {
        switch(tolower(word[rb->utf8seek(word, i)]))
        {
        case 'a': case 'e': case 'i': case 'o': case 'u':
            focus = i;
            break;
        default:
            break;
        }
    }

    if(focus < 0)
        focus = len / 2;
    return focus;
#else
    int len = rb->utf8length(word);
    if(rb->utf8length(word) > 13)
        return 4;
    else
    {
        int tab[] = {0,1,1,1,1,2,2,2,2,3,3,3,3};
        return tab[len - 1];
    }
#endif
}

static int calculate_delay(const char *word, int wpm)
{
    long base = 60 * HZ / wpm;
    long timeout = base;
    int len = rb->utf8length(word);

    if(len > 6)
        timeout += base / 5 * (len - 6);

    if(rb->strchr(word, ',') || rb->strchr(word, '-'))
        timeout += base / 2;

    if(rb->strchr(word, '.') || rb->strchr(word, '!') || rb->strchr(word, '?') || rb->strchr(word, ';'))
        timeout += 3 * base / 2;
    return timeout;
}

static long render_screen(const char *word, int wpm)
{
    /* significant inspiration taken from spread0r */
    long timeout = calculate_delay(word, wpm);
    int focus = calculate_focus(word);

    rb->lcd_setfont(custom_font);

    int h = reset_drawing(0);

    render_word(word, focus);

    rb->lcd_setfont(FONT_UI);

    rb->lcd_update_rect(0, 0, LCD_WIDTH, h);
    return timeout;
}

static void begin_anim(void)
{
    long start = *rb->current_tick;
    long end = start + ANIM_TIME;

    const char *word = get_last_word();

    int focus = calculate_focus(word);

    rb->lcd_setfont(custom_font);

    while(*rb->current_tick < end)
    {
        int h = reset_drawing(fp_div((*rb->current_tick - start) << 16, ANIM_TIME << 16, 16));

        render_word(word, focus);
        rb->lcd_update_rect(0, 0, LCD_WIDTH, h);
    }

    rb->lcd_setfont(FONT_UI);
}

static void init_drawing(void)
{
#ifdef HAVE_BACKLIGHT
    backlight_ignore_timeout();
#endif
    atexit(cleanup);

    rb->lcd_set_background(OUTSIDE_COLOR);
    rb->lcd_set_backdrop(NULL);
    rb->lcd_set_drawmode(DRMODE_FG);
    rb->lcd_clear_display();

    rb->lcd_update();
}

enum { NOTHING = 0, SLOWER, FASTER, FFWD, BACK, PAUSE, QUIT };

static const struct button_mapping *plugin_contexts[] = { pla_main_ctx };

static int get_useraction(void)
{
    int button = pluginlib_getaction(0, plugin_contexts, ARRAYLEN(plugin_contexts));

    switch(button)
    {
#ifdef HAVE_SCROLLWHEEL
    case PLA_SCROLL_FWD:
    case PLA_SCROLL_FWD_REPEAT:
#else
    case PLA_UP:
#endif
        return FASTER;
#ifdef HAVE_SCROLLWHEEL
    case PLA_SCROLL_BACK:
    case PLA_SCROLL_BACK_REPEAT:
#else
    case PLA_DOWN:
#endif
        return SLOWER;
    case PLA_SELECT:
        return PAUSE;
    case PLA_CANCEL:
        return QUIT;
    case PLA_LEFT_REPEAT:
    case PLA_LEFT:
        return BACK;
    case PLA_RIGHT_REPEAT:
    case PLA_RIGHT:
        return FFWD;
    default:
        exit_on_usb(button); /* handle poweroff and USB events */
        return 0;
    }
}

static void save_bookmark(const char *fname, int wpm)
{
    if(!fname)
        return;
    rb->splash(0, "Saving...");
    /* copy every line except the one to be changed */
    int bookmark_fd = rb->open(BOOKMARK_FILE, O_RDONLY);
    int tmp_fd = rb->open(BOOKMARK_FILE ".tmp", O_WRONLY | O_CREAT | O_TRUNC, 0666);
    if(bookmark_fd >= 0)
    {
        while(1)
        {
            /* space for the filename, 3, integers, and a null */
            static char line[MAX_PATH + 1 + 10 + 1 + 10 + 1 + 10 + 1];
            int len = rb->read_line(bookmark_fd, line, sizeof(line));
            if(len <= 0)
                break;

            char *end;
            rb->strtok_r(line, " ", &end);
            rb->strtok_r(NULL, " ", &end);
            rb->strtok_r(NULL, " ", &end);
            char *bookmark_name = rb->strtok_r(NULL, "", &end);

            if(!bookmark_name)
                continue; /* avoid crash */
            if(rb->strcmp(fname, bookmark_name))
            {
                /* go back and clean up after strtok */
                for(int i = 0; i < len - 1; ++i)
                    if(!line[i])
                        line[i] = ' ';

                rb->write(tmp_fd, line, len);
                rb->fdprintf(tmp_fd, "\n");
            }
        }
        rb->close(bookmark_fd);
    }
    rb->fdprintf(tmp_fd, "%ld %d %d %s\n", line_offs, word_num, wpm, fname);
    rb->close(tmp_fd);
    rb->rename(BOOKMARK_FILE ".tmp", BOOKMARK_FILE);
}

static bool load_bookmark(const char *fname, int *wpm)
{
    int bookmark_fd = rb->open(BOOKMARK_FILE, O_RDONLY);
    if(bookmark_fd >= 0)
    {
        while(1)
        {
            /* space for the filename, 2 integers, and a null */
            char line[MAX_PATH + 1 + 10 + 1 + 10 + 1];
            int len = rb->read_line(bookmark_fd, line, sizeof(line));
            if(len <= 0)
                break;

            char *end;
            char *tok = rb->strtok_r(line, " ", &end);
            if(!tok)
                continue;
            off_t offs = rb->atoi(tok);

            tok = rb->strtok_r(NULL, " ", &end);
            if(!tok)
                continue;
            int word = rb->atoi(tok);

            tok = rb->strtok_r(NULL, " ", &end);
            if(!tok)
                continue;
            *wpm = rb->atoi(tok);
            if(*wpm < MIN_WPM)
                *wpm = MIN_WPM;
            if(*wpm > MAX_WPM)
                *wpm = MAX_WPM;

            char *bookmark_name = rb->strtok_r(NULL, "", &end);

            if(!bookmark_name)
                continue;

            if(!rb->strcmp(fname, bookmark_name))
            {
                rb->lseek(fd, offs, SEEK_SET);
                for(int i = 0; i < word; ++i)
                    get_next_word();
                rb->close(bookmark_fd);
                return true;
            }
        }
        rb->close(bookmark_fd);
    }
    return false;
}

static void new_font(const char *path)
{
    if(custom_font != FONT_UI)
        rb->font_unload(custom_font);
    custom_font = rb->font_load(path);
    if(custom_font < 0)
        custom_font = FONT_UI;
}

static void save_font(const char *path)
{
    int font_fd = rb->open(CONFIG_FILE, O_WRONLY | O_TRUNC | O_CREAT, 0666);
    rb->write(font_fd, path, rb->strlen(path));
    rb->close(font_fd);
}

static char font_buf[MAX_PATH + 1];

static void load_font(void)
{
    int font_fd = rb->open(CONFIG_FILE, O_RDONLY);
    if(font_fd < 0)
        return;
    int len = rb->read(font_fd, font_buf, MAX_PATH);
    font_buf[len] = '\0';
    rb->close(font_fd);
    new_font(font_buf);
}

static void font_menu(void)
{
    /* taken from text_viewer */
    struct browse_context browse;
    char font[MAX_PATH], name[MAX_FILENAME+10];

    rb->snprintf(name, sizeof(name), "%s.fnt", rb->global_settings->font_file);
    rb->browse_context_init(&browse, SHOW_FONT,
                            BROWSE_SELECTONLY|BROWSE_NO_CONTEXT_MENU,
                            "Font", Icon_Menu_setting, FONT_DIR, name);

    browse.buf = font;
    browse.bufsize = sizeof(font);

    rb->rockbox_browse(&browse);

    if (browse.flags & BROWSE_SELECTED)
    {
        new_font(font);
        save_font(font);
    }
}

static bool confirm_restart(void)
{
    const struct text_message prompt = { (const char*[]) {"Are you sure?", "This will erase your current position."}, 2};
    enum yesno_res response = rb->gui_syncyesno_run(&prompt, NULL, NULL);
    if(response == YESNO_NO)
        return false;
    else
        return true;
}

static int config_menu(void)
{
    MENUITEM_STRINGLIST(menu, "Speedread Menu", NULL,
                        "Resume Reading",
                        "Restart from Beginning",
                        "Change Font",
                        "Quit");
    int rc = 0;
    int sel = 0;
    while(!rc)
    {
        switch(rb->do_menu(&menu, &sel, NULL, false))
        {
        case 0:
            rc = 1;
            break;
        case 1:
            if(fd >= 0 && confirm_restart())
            {
                rb->lseek(fd, begin_offs, SEEK_SET);
                line_len = -1;
                get_next_word();
                rc = 1;
            }
            break;
        case 2:
            font_menu();
            break;
        case 3:
            rc = 2;
            break;
        default:
            break;
        }
    }
    return rc - 1;
}

enum { SKIP = -1, FINISH = -2 };

static int poll_input(int *wpm, long *clear, const char *fname, off_t file_size)
{
    switch(get_useraction())
    {
    case FASTER:
        if(*wpm + WPM_INCREMENT <= MAX_WPM)
            *wpm += WPM_INCREMENT;
        rb->splashf(0, "%d wpm", *wpm);
        *clear = *rb->current_tick + HZ;
        break;
    case SLOWER:
        if(*wpm - WPM_INCREMENT >= MIN_WPM)
            *wpm -= WPM_INCREMENT;
        rb->splashf(0, "%d wpm", *wpm);
        *clear = *rb->current_tick + HZ;
        break;
    case FFWD:
        if(fd >= 0)
        {
            off_t base_offs = rb->lseek(fd, 0, SEEK_CUR);
            off_t offs = 0;

            do {
                offs += SEEK_INTERVAL;
                if(offs >= 1000 * SEEK_INTERVAL)
                    offs += 199 * SEEK_INTERVAL;
                else if(offs >= 100 * SEEK_INTERVAL)
                    offs += 99 * SEEK_INTERVAL;
                else if(offs >= 10 * SEEK_INTERVAL)
                    offs += 9 * SEEK_INTERVAL;
                rb->splashf(0, "%ld/%ld bytes", offs + base_offs, file_size);
                rb->sleep(HZ/20);
            } while(get_useraction() == FFWD && offs + base_offs < file_size && offs + base_offs >= 0);

            *clear = *rb->current_tick + HZ;

            rb->lseek(fd, offs, SEEK_CUR);

            /* discard the next word (or more likely, portion of a word) */
            line_len = -1;
            get_next_word();

            return SKIP;
        }
        break;
    case BACK:
        if(fd >= 0)
        {
            off_t base_offs = rb->lseek(fd, 0, SEEK_CUR);
            off_t offs = 0;

            do {
                offs -= SEEK_INTERVAL;
                if(offs <= -1000 * SEEK_INTERVAL)
                    offs -= 199 * SEEK_INTERVAL;
                else if(offs <= -100 * SEEK_INTERVAL)
                    offs -= 99 * SEEK_INTERVAL;
                else if(offs <= -10 * SEEK_INTERVAL)
                    offs -= 9 * SEEK_INTERVAL;
                rb->splashf(0, "%ld/%ld bytes", offs + base_offs, file_size);
                rb->sleep(HZ/20);
            } while(get_useraction() == FFWD && offs + base_offs < file_size && offs + base_offs >= 0);

            *clear = *rb->current_tick + HZ;

            rb->lseek(fd, offs, SEEK_CUR);

            /* discard the next word (or more likely, portion of a word) */
            line_len = -1;
            get_next_word();

            return SKIP;
        }
        break;
    case PAUSE:
    case QUIT:
        if(config_menu())
        {
            save_bookmark(fname, *wpm);
            return FINISH;
        }
        else
        {
            init_drawing();
            begin_anim();
        }
        break;
    case NOTHING:
    default:
        break;
    }
    return 0;
}

enum plugin_status plugin_start(const void *param)
{
    const char *fname = param;

    off_t file_size = 0;

    load_font();

    bool loaded = false;

    int wpm = DEF_WPM;

    if(fname)
    {
        fd = rb->open_utf8(fname, O_RDONLY);

        begin_offs = rb->lseek(fd, 0, SEEK_CUR); /* skip BOM */
        file_size = rb->lseek(fd, 0, SEEK_END);
        rb->lseek(fd, begin_offs, SEEK_SET);

        loaded = load_bookmark(fname, &wpm);
    }

    init_drawing();

    long clear = -1;
    if(loaded)
    {
        rb->splash(0, "Loaded bookmark.");
        clear = *rb->current_tick + HZ;
    }

    begin_anim();

    /* main loop */
    while(1)
    {
        switch(poll_input(&wpm, &clear, fname, file_size))
        {
        case SKIP:
            continue;
        case FINISH:
            goto done;
        default:
            break;
        }

        const char *word = get_next_word();
        if(!word)
            break;
        bool want_full_update = false;
        if(TIME_AFTER(*rb->current_tick, clear) && clear != -1)
        {
            clear = -1;
            rb->lcd_clear_display();
            want_full_update = true;
        }
        long interval = render_screen(word, wpm);

        long frame_done = *rb->current_tick + interval;

        if(want_full_update)
            rb->lcd_update();

        while(!TIME_AFTER(*rb->current_tick, frame_done))
        {
            switch(poll_input(&wpm, &clear, fname, file_size))
            {
            case SKIP:
                goto next_word;
            case FINISH:
                goto done;
            default:
                break;
            }
            rb->yield();
        }
    next_word:
        ;
    }

done:
    rb->close(fd);

    return PLUGIN_OK;
}