fixed underscores - closest possible (#47)
[smdp.git] / src / viewer.c
1 /*
2  * Functions necessary to display a deck of slides in different color modes
3  * using ncurses. Only white, red, and blue are supported, as they can be
4  * faded in 256 color mode.
5  * Copyright (C) 2014 Michael Goehler
6  *
7  * This file is part of mdp.
8  *
9  * This program is free software: you can redistribute it and/or modify
10  * it under the terms of the GNU General Public License as published by
11  * the Free Software Foundation, either version 3 of the License, or
12  * (at your option) any later version.
13  *
14  * This program is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17  * GNU General Public License for more details.
18  *
19  * You should have received a copy of the GNU General Public License
20  * along with this program. If not, see <http://www.gnu.org/licenses/>.
21  *
22  */
23
24 #include <ctype.h>  // isalnum
25 #include <locale.h> // setlocale
26 #include <string.h> // strchr
27 #include <unistd.h> // usleep
28
29 #include "viewer.h"
30
31 // color ramp for fading from black to color
32 static short white_ramp[24] = { 16, 232, 233, 234, 235, 236,
33                                237, 238, 239, 240, 241, 242,
34                                244, 245, 246, 247, 248, 249,
35                                250, 251, 252, 253, 254, 255 };
36
37 static short blue_ramp[24]  = { 16,  17,  17,  18,  18,  19,
38                                 19,  20,  20,  21,  27,  33,
39                                 32,  39,  38,  45,  44,  44,
40                                 81,  81,  51,  51, 123, 123 };
41
42 static short red_ramp[24]   = { 16,  52,  52,  53,  53,  89,
43                                 89,  90,  90, 126, 127, 127,
44                                163, 163, 164, 164, 200, 200,
45                                201, 201, 207, 207, 213, 213 };
46
47 // color ramp for fading from white to color
48 static short white_ramp_invert[24] = { 15, 255, 254, 254, 252, 251,
49                                       250, 249, 248, 247, 246, 245,
50                                       243, 242, 241, 240, 239, 238,
51                                       237, 236, 235, 234, 233, 232};
52
53 static short blue_ramp_invert[24]  = { 15, 231, 231, 195, 195, 159,
54                                       159, 123, 123,  87,  51,  44,
55                                        45,  38,  39,  32,  33,  33,
56                                        26,  26,  27,  27,  21,  21};
57
58 static short red_ramp_invert[24]   = { 15, 231, 231, 224, 224, 225,
59                                       225, 218, 218, 219, 212, 213,
60                                       206, 207, 201, 200, 199, 199,
61                                       198, 198, 197, 197, 196, 196};
62
63 int ncurses_display(deck_t *deck, int notrans, int nofade, int invert) {
64
65     int c = 0;          // char
66     int i = 0;          // iterate
67     int l = 0;          // line number
68     int lc = 0;         // line count
69     int sc = 1;         // slide count
70     int colors = 0;     // amount of colors supported
71     int fade = 0;       // disable color fading by default
72     int trans = -1;     // enable transparency if term supports it
73     int max_lines = 0;  // max lines per slide
74     int max_cols = 0;   // max columns per line
75     int offset;         // text offset
76
77     // header line 1 is displayed at the top
78     int bar_top = (deck->headers > 0) ? 1 : 0;
79     // header line 2 is displayed at the bottom
80     // anyway we display the slide number at the bottom
81     int bar_bottom = 1;
82
83     slide_t *slide = deck->slide;
84     line_t *line;
85
86     // set locale to display UTF-8 correctly in ncurses
87     setlocale(LC_CTYPE, "");
88
89     // init ncurses
90     initscr();
91
92     while(slide) {
93         lc = 0;
94         line = slide->line;
95
96         while(line) {
97             if(line->length > COLS) {
98                 i = line->length;
99                 offset = 0;
100                 while(i > COLS) {
101
102                     i = prev_blank(line->text, offset + COLS) - offset;
103
104                     // single word is > COLS
105                     if(!i) {
106                         // calculate min_width
107                         i = next_blank(line->text, offset + COLS) - offset;
108
109                         // disable ncurses
110                         endwin();
111
112                         // print error
113                         fprintf(stderr, "Error: Terminal width (%i columns) too small. Need at least %i columns.\n", COLS, i);
114                         fprintf(stderr, "You may need to shorten some lines by inserting line breaks.\n");
115
116                         return 1;
117                     }
118
119                     // set max_cols
120                     max_cols = MAX(i, max_cols);
121
122                     // iterate to next line
123                     offset = prev_blank(line->text, offset + COLS);
124                     i = line->length - offset;
125                     lc++;
126                 }
127                 // set max_cols one last time
128                 max_cols = MAX(i, max_cols);
129             } else {
130                 // set max_cols
131                 max_cols = MAX(line->length, max_cols);
132             }
133             lc++;
134             line = line->next;
135         }
136
137         max_lines = MAX(lc, max_lines);
138
139         slide = slide->next;
140     }
141
142     // not enough lines
143     if(max_lines + bar_top + bar_bottom > LINES) {
144
145         // disable ncurses
146         endwin();
147
148         // print error
149         fprintf(stderr, "Error: Terminal height (%i lines) too small. Need at least %i lines.\n", LINES, max_lines + bar_top + bar_bottom);
150         fprintf(stderr, "You may need to add additional horizontal rules ('***') to split your file in shorter slides.\n");
151
152         return 1;
153     }
154
155     // disable cursor
156     curs_set(0);
157
158     // disable output of keyboard typing
159     noecho();
160
161     // make getch() process one char at a time
162     cbreak();
163
164     // enable arrow keys
165     keypad(stdscr,TRUE);
166
167     // set colors
168     if(has_colors() == TRUE) {
169         start_color();
170         use_default_colors();
171
172         // 256 color mode
173         if(COLORS == 256) {
174
175             if(notrans) {
176                 if(invert) {
177                     trans = 15; // white in 256 color mode
178                 } else {
179                     trans = 16; // black in 256 color mode
180                 }
181             }
182
183             if(invert) {
184                 init_pair(CP_WHITE, 232, trans);
185                 init_pair(CP_BLUE, 21, trans);
186                 init_pair(CP_RED, 196, trans);
187                 init_pair(CP_BLACK, 15, 232);
188             } else {
189                 init_pair(CP_WHITE, 255, trans);
190                 init_pair(CP_BLUE, 123, trans);
191                 init_pair(CP_RED, 213, trans);
192                 init_pair(CP_BLACK, 16, 255);
193             }
194             init_pair(CP_YELLOW, 208, trans);
195
196             // enable color fading
197             if(!nofade)
198                 fade = true;
199
200         // 8 color mode
201         } else {
202
203             if(notrans) {
204                 if(invert) {
205                     trans = 7; // white in 8 color mode
206                 } else {
207                     trans = 0; // black in 8 color mode
208                 }
209             }
210
211             if(invert) {
212                 init_pair(CP_WHITE, 0, trans);
213                 init_pair(CP_BLACK, 7, 0);
214             } else {
215                 init_pair(CP_WHITE, 7, trans);
216                 init_pair(CP_BLACK, 0, 7);
217             }
218             init_pair(CP_BLUE, 4, trans);
219             init_pair(CP_RED, 1, trans);
220             init_pair(CP_YELLOW, 3, trans);
221         }
222
223         colors = 1;
224     }
225
226     // set background color of main window
227     if(colors)
228         wbkgd(stdscr, COLOR_PAIR(CP_YELLOW));
229
230     // setup main window
231     WINDOW *content = newwin(LINES - bar_top - bar_bottom, COLS, 0 + bar_top, 0);
232     if(colors)
233         wbkgd(content, COLOR_PAIR(CP_WHITE));
234
235     slide = deck->slide;
236     while(slide) {
237         // clear windows
238         werase(content);
239         werase(stdscr);
240
241         // always resize window in case terminal geometry has changed
242         wresize(content, LINES - bar_top - bar_bottom, COLS);
243
244         // setup header
245         if(bar_top) {
246             line = deck->header;
247             offset = next_blank(line->text, 0) + 1;
248             // add text to header
249             mvwprintw(stdscr,
250                       0, (COLS - line->length + offset) / 2,
251                       "%s", &line->text->text[offset]);
252         }
253
254         // setup footer
255         if(deck->headers > 1) {
256             line = deck->header->next;
257             offset = next_blank(line->text, 0) + 1;
258             // add text to left footer
259             mvwprintw(stdscr,
260                       LINES - 1, 3,
261                       "%s", &line->text->text[offset]);
262         }
263         // add slide number to right footer
264         mvwprintw(stdscr,
265                   LINES - 1, COLS - int_length(deck->slides) - int_length(sc) - 6,
266                   "%d / %d", sc, deck->slides);
267
268         // make header + fooder visible
269         wrefresh(stdscr);
270
271         line = slide->line;
272         l = 0;
273
274         // print lines
275         while(line) {
276             add_line(content, l, (COLS - max_cols) / 2, line, max_cols, colors);
277             l += (line->length / COLS) + 1;
278             line = line->next;
279         }
280
281         // make content visible
282         wrefresh(content);
283
284         // fade in
285         if(fade)
286             fade_in(content, trans, colors, invert);
287
288         // re-enable fading after any undefined key press
289         if(COLORS == 256 && !nofade)
290             fade = true;
291
292         // wait for user input
293         c = getch();
294
295         // evaluate user input
296         i = 0;
297         switch(c) {
298
299             // show previous slide
300             case KEY_UP:
301             case KEY_LEFT:
302             case KEY_PPAGE:
303             case 8:   // BACKSPACE (ascii)
304             case 127: // BACKSPACE (xterm)
305             case 263: // BACKSPACE (getty)
306             case 'h':
307             case 'k':
308                 if(slide->prev) {
309                     slide = slide->prev;
310                     sc--;
311                 } else {
312                     fade = false;
313                 }
314                 break;
315
316             // show next slide
317             case KEY_DOWN:
318             case KEY_RIGHT:
319             case KEY_NPAGE:
320             case '\n': // ENTER
321             case ' ':  // SPACE
322             case 'j':
323             case 'l':
324                 if(slide->next) {
325                     slide = slide->next;
326                     sc++;
327                 } else {
328                     fade = false;
329                 }
330                 break;
331
332             // show slide n
333             case '9': i++;
334             case '8': i++;
335             case '7': i++;
336             case '6': i++;
337             case '5': i++;
338             case '4': i++;
339             case '3': i++;
340             case '2': i++;
341             case '1': i++;
342                 if(i <= deck->slides) {
343                     while(sc != i) {
344                         // search forward
345                         if(sc < i) {
346                             if(slide->next) {
347                                 slide = slide->next;
348                                 sc++;
349                             }
350                         // search backward
351                         } else {
352                             if(slide->prev) {
353                                 slide = slide->prev;
354                                 sc--;
355                             }
356                         }
357                     }
358                 } else {
359                     // disable fading if slide n doesn't exist
360                     fade = false;
361                 }
362                 break;
363
364             // show first slide
365             case KEY_HOME:
366                 slide = deck->slide;
367                 sc = 1;
368                 break;
369
370             // show last slide
371             case KEY_END:
372                 for(i = sc; i <= deck->slides; i++) {
373                     if(slide->next) {
374                             slide = slide->next;
375                             sc++;
376                     }
377                 }
378                 break;
379
380             // quit
381             case 'q':
382                 // do not fade out on exit
383                 fade = false;
384                 slide = NULL;
385                 break;
386
387             default:
388                 // disable fading on undefined key press
389                 fade = false;
390                 break;
391         }
392
393         // fade out
394         if(fade)
395             fade_out(content, trans, colors, invert);
396     }
397
398     endwin();
399
400     return 0;
401 }
402
403 void add_line(WINDOW *window, int y, int x, line_t *line, int max_cols, int colors) {
404
405     if(!line->text->text) {
406         return;
407     }
408
409     int i; // increment
410     int offset = 0; // text offset
411
412     // move the cursor in position
413     wmove(window, y, x);
414
415     // IS_UNORDERED_LIST_3
416     if(CHECK_BIT(line->bits, IS_UNORDERED_LIST_3)) {
417         offset = next_nonblank(line->text, 0);
418         char prompt[13];
419         strcpy(&prompt[0], CHECK_BIT(line->bits, IS_UNORDERED_LIST_1)? " |  " : "    ");
420         strcpy(&prompt[4], CHECK_BIT(line->bits, IS_UNORDERED_LIST_2)? " |  " : "    ");
421
422         if(CHECK_BIT(line->bits, IS_UNORDERED_LIST_EXT)) {
423             strcpy(&prompt[8], line->next && CHECK_BIT(line->next->bits, IS_UNORDERED_LIST_3)? " |  " : "    ");
424         } else {
425             strcpy(&prompt[8], " +- ");
426             offset += 2;
427         }
428
429         wprintw(window,
430                 "%s", prompt);
431
432         if(!CHECK_BIT(line->bits, IS_CODE))
433             inline_display(window, &line->text->text[offset], colors);
434
435     // IS_UNORDERED_LIST_2
436     } else if(CHECK_BIT(line->bits, IS_UNORDERED_LIST_2)) {
437         offset = next_nonblank(line->text, 0);
438         char prompt[9];
439         strcpy(&prompt[0], CHECK_BIT(line->bits, IS_UNORDERED_LIST_1)? " |  " : "    ");
440
441         if(CHECK_BIT(line->bits, IS_UNORDERED_LIST_EXT)) {
442             strcpy(&prompt[4], line->next && CHECK_BIT(line->next->bits, IS_UNORDERED_LIST_2)? " |  " : "    ");
443         } else {
444             strcpy(&prompt[4], " +- ");
445             offset += 2;
446         }
447
448         wprintw(window,
449                 "%s", prompt);
450
451         if(!CHECK_BIT(line->bits, IS_CODE))
452             inline_display(window, &line->text->text[offset], colors);
453
454     // IS_UNORDERED_LIST_1
455     } else if(CHECK_BIT(line->bits, IS_UNORDERED_LIST_1)) {
456         offset = next_nonblank(line->text, 0);
457         char prompt[5];
458
459         if(CHECK_BIT(line->bits, IS_UNORDERED_LIST_EXT)) {
460             strcpy(&prompt[0], line->next && CHECK_BIT(line->next->bits, IS_UNORDERED_LIST_1)? " |  " : "    ");
461         } else {
462             strcpy(&prompt[0], " +- ");
463             offset += 2;
464         }
465
466         wprintw(window,
467                 "%s", prompt);
468
469         if(!CHECK_BIT(line->bits, IS_CODE))
470             inline_display(window, &line->text->text[offset], colors);
471     }
472
473     // IS_CODE
474     if(CHECK_BIT(line->bits, IS_CODE)) {
475
476         // set static offset for code
477         offset = CODE_INDENT;
478
479         // reverse color for code blocks
480         if(colors)
481             wattron(window, COLOR_PAIR(CP_BLACK));
482
483         // print whole lines
484         wprintw(window,
485                 "%s", &line->text->text[offset]);
486     }
487
488     if(!CHECK_BIT(line->bits, IS_UNORDERED_LIST_1) &&
489        !CHECK_BIT(line->bits, IS_UNORDERED_LIST_2) &&
490        !CHECK_BIT(line->bits, IS_UNORDERED_LIST_3) &&
491        !CHECK_BIT(line->bits, IS_CODE)) {
492
493         // IS_QUOTE
494         if(CHECK_BIT(line->bits, IS_QUOTE)) {
495             while(line->text->text[offset] == '>') {
496                 // print a reverse color block
497                 if(colors) {
498                     wattron(window, COLOR_PAIR(CP_BLACK));
499                     wprintw(window, "%s", " ");
500                     wattron(window, COLOR_PAIR(CP_WHITE));
501                     wprintw(window, "%s", " ");
502                 } else {
503                     wprintw(window, "%s", ">");
504                 }
505
506                 // find next quote or break
507                 offset++;
508                 if(line->text->text[offset] == ' ')
509                     offset = next_word(line->text, offset);
510             }
511
512             inline_display(window, &line->text->text[offset], colors);
513         } else {
514
515             // IS_CENTER
516             if(CHECK_BIT(line->bits, IS_CENTER)) {
517                 if(line->length < max_cols) {
518                     wmove(window, y, x + ((max_cols - line->length) / 2));
519                 }
520             }
521
522             // IS_H1 || IS_H2
523             if(CHECK_BIT(line->bits, IS_H1) || CHECK_BIT(line->bits, IS_H2)) {
524
525                 // set headline color
526                 if(colors)
527                     wattron(window, COLOR_PAIR(CP_BLUE));
528
529                 // enable underline for H1
530                 if(CHECK_BIT(line->bits, IS_H1))
531                     wattron(window, A_UNDERLINE);
532
533                 // skip hashes
534                 while(line->text->text[offset] == '#')
535                     offset = next_word(line->text, offset);
536
537                 // print whole lines
538                 wprintw(window,
539                         "%s", &line->text->text[offset]);
540
541                 wattroff(window, A_UNDERLINE);
542
543             // no line-wide markdown
544             } else {
545
546                 inline_display(window, &line->text->text[offset], colors);
547             }
548         }
549     }
550
551     // fill rest off line with spaces
552     for(i = getcurx(window) - x; i < max_cols; i++)
553         wprintw(window, "%s", " ");
554
555     // reset to default color
556     if(colors)
557         wattron(window, COLOR_PAIR(CP_WHITE));
558     wattroff(window, A_UNDERLINE);
559 }
560
561 void inline_display(WINDOW *window, const char *c, const int colors) {
562     const static char *special = "\\*_`"; // list of interpreted chars
563     const char *i = c; // iterator
564     cstack_t *stack = cstack_init();
565
566
567     // for each char in line
568     for(; *i; i++) {
569
570         // if char is in special char list
571         if(strchr(special, *i)) {
572
573             // closing special char (or second backslash)
574             // only if not followed by :alnum:
575             if((stack->top)(stack, *i) &&
576                (!isalnum(*(i + 1)) || *(i + 1) == '\0' || *i == '\\')) {
577
578                 switch(*i) {
579                     // print escaped backslash
580                     case '\\':
581                         wprintw(window, "%c", *i);
582                         break;
583                     // disable highlight
584                     case '*':
585                         if(colors)
586                             wattron(window, COLOR_PAIR(CP_WHITE));
587                         break;
588                     // disable underline
589                     case '_':
590                         wattroff(window, A_UNDERLINE);
591                         break;
592                     // disable inline code
593                     case '`':
594                         if(colors)
595                             wattron(window, COLOR_PAIR(CP_WHITE));
596                         break;
597                 }
598
599                 // remove top special char from stack
600                 (stack->pop)(stack);
601
602             // treat special as regular char
603             } else if((stack->top)(stack, '\\')) {
604                 wprintw(window, "%c", *i);
605
606                 // remove backslash from stack
607                 (stack->pop)(stack);
608
609             // opening special char
610             } else {
611
612                 // emphasis or code span can start after new-line or space only
613                 // and of cause after another emphasis markup
614                 if(*(i - 1) == ' ' ||
615                    ((*(i - 1) == '_' || *(i - 1) == '*') && (*(i - 2) == ' ' || (i - 1) == c)) ||
616                    *i == '\\' ||
617                    i == c) {
618
619                     switch(*i) {
620                         // enable highlight
621                         case '*':
622                             if(colors)
623                                 wattron(window, COLOR_PAIR(CP_RED));
624                             break;
625                         // enable underline
626                         case '_':
627                             wattron(window, A_UNDERLINE);
628                             break;
629                         // enable inline code
630                         case '`':
631                             if(colors)
632                                 wattron(window, COLOR_PAIR(CP_BLACK));
633                             break;
634                         // do nothing for backslashes
635                     }
636
637                     // push special char to stack
638                     (stack->push)(stack, *i);
639
640                 } else {
641                     wprintw(window, "%c", *i);
642                 }
643             }
644
645         } else {
646             // remove backslash from stack
647             if((stack->top)(stack, '\\'))
648                 (stack->pop)(stack);
649
650             // print regular char
651             wprintw(window, "%c", *i);
652         }
653     }
654
655     // pop stack until empty to prevent formated trailing spaces
656     while(!(stack->empty)(stack)) {
657         switch((stack->pop)(stack)) {
658             // disable highlight
659             case '*':
660                 if(colors)
661                     wattron(window, COLOR_PAIR(CP_WHITE));
662                 break;
663             // disable underline
664             case '_':
665                 wattroff(window, A_UNDERLINE);
666                 break;
667             // disable inline code
668             case '`':
669                 if(colors)
670                     wattron(window, COLOR_PAIR(CP_WHITE));
671                 break;
672             // do nothing for backslashes
673         }
674     }
675
676     (stack->delete)(stack);
677 }
678
679 void fade_out(WINDOW *window, int trans, int colors, int invert) {
680     int i; // increment
681     if(colors && COLORS == 256) {
682         for(i = 22; i >= 0; i--) {
683
684             // dim color pairs
685             if(invert) {
686                 init_pair(CP_WHITE, white_ramp_invert[i], trans);
687                 init_pair(CP_BLUE, blue_ramp_invert[i], trans);
688                 init_pair(CP_RED, red_ramp_invert[i], trans);
689                 init_pair(CP_BLACK, 15, white_ramp_invert[i]);
690             } else {
691                 init_pair(CP_WHITE, white_ramp[i], trans);
692                 init_pair(CP_BLUE, blue_ramp[i], trans);
693                 init_pair(CP_RED, red_ramp[i], trans);
694                 init_pair(CP_BLACK, 16, white_ramp[i]);
695             }
696
697             // refresh window with new color
698             wrefresh(window);
699
700             // delay for our eyes to recognize the change
701             usleep(FADE_DELAY);
702         }
703     }
704 }
705
706 void fade_in(WINDOW *window, int trans, int colors, int invert) {
707     int i; // increment
708     if(colors && COLORS == 256) {
709         for(i = 0; i <= 23; i++) {
710
711             // brighten color pairs
712             if(invert) {
713                 init_pair(CP_WHITE, white_ramp_invert[i], trans);
714                 init_pair(CP_BLUE, blue_ramp_invert[i], trans);
715                 init_pair(CP_RED, red_ramp_invert[i], trans);
716                 init_pair(CP_BLACK, 15, white_ramp_invert[i]);
717             } else {
718                 init_pair(CP_WHITE, white_ramp[i], trans);
719                 init_pair(CP_BLUE, blue_ramp[i], trans);
720                 init_pair(CP_RED, red_ramp[i], trans);
721                 init_pair(CP_BLACK, 16, white_ramp[i]);
722             }
723
724             // refresh window with new color
725             wrefresh(window);
726
727             // delay for our eyes to recognize the change
728             usleep(FADE_DELAY);
729         }
730     }
731 }
732
733 int int_length (int val) {
734     int l = 1;
735     while(val > 9) {
736         l++;
737         val /= 10;
738     }
739     return l;
740 }