video: make vidconsole commands optional
[platform/kernel/u-boot.git] / drivers / video / console_truetype.c
1 // SPDX-License-Identifier: GPL-2.0+
2 /*
3  * Copyright (c) 2016 Google, Inc
4  */
5
6 #include <common.h>
7 #include <dm.h>
8 #include <log.h>
9 #include <malloc.h>
10 #include <video.h>
11 #include <video_console.h>
12
13 /* Functions needed by stb_truetype.h */
14 static int tt_floor(double val)
15 {
16         if (val < 0)
17                 return (int)(val - 0.999);
18
19         return (int)val;
20 }
21
22 static int tt_ceil(double val)
23 {
24         if (val < 0)
25                 return (int)val;
26
27         return (int)(val + 0.999);
28 }
29
30 static double frac(double val)
31 {
32         return val - tt_floor(val);
33 }
34
35 static double tt_fabs(double x)
36 {
37         return x < 0 ? -x : x;
38 }
39
40  /*
41   * Simple square root algorithm. This is from:
42   * http://stackoverflow.com/questions/1623375/writing-your-own-square-root-function
43   * Written by Chihung Yu
44   * Creative Commons license
45   * http://creativecommons.org/licenses/by-sa/3.0/legalcode
46   * It has been modified to compile correctly, and for U-Boot style.
47   */
48 static double tt_sqrt(double value)
49 {
50         double lo = 1.0;
51         double hi = value;
52
53         while (hi - lo > 0.00001) {
54                 double mid = lo + (hi - lo) / 2;
55
56                 if (mid * mid - value > 0.00001)
57                         hi = mid;
58                 else
59                         lo = mid;
60         }
61
62         return lo;
63 }
64
65 #define STBTT_ifloor            tt_floor
66 #define STBTT_iceil             tt_ceil
67 #define STBTT_fabs              tt_fabs
68 #define STBTT_sqrt              tt_sqrt
69 #define STBTT_malloc(size, u)   ((void)(u), malloc(size))
70 #define STBTT_free(size, u)     ((void)(u), free(size))
71 #define STBTT_assert(x)
72 #define STBTT_strlen(x)         strlen(x)
73 #define STBTT_memcpy            memcpy
74 #define STBTT_memset            memset
75
76 #define STB_TRUETYPE_IMPLEMENTATION
77 #include "stb_truetype.h"
78
79 /**
80  * struct pos_info - Records a cursor position
81  *
82  * @xpos_frac:  Fractional X position in pixels (multiplied by VID_FRAC_DIV)
83  * @ypos:       Y position (pixels from the top)
84  */
85 struct pos_info {
86         int xpos_frac;
87         int ypos;
88 };
89
90 /*
91  * Allow one for each character on the command line plus one for each newline.
92  * This is just an estimate, but it should not be exceeded.
93  */
94 #define POS_HISTORY_SIZE        (CONFIG_SYS_CBSIZE * 11 / 10)
95
96 /**
97  * struct console_tt_priv - Private data for this driver
98  *
99  * @font_size:  Vertical font size in pixels
100  * @font_data:  Pointer to TrueType font file contents
101  * @font:       TrueType font information for the current font
102  * @pos:        List of cursor positions for each character written. This is
103  *              used to handle backspace. We clear the frame buffer between
104  *              the last position and the current position, thus erasing the
105  *              last character. We record enough characters to go back to the
106  *              start of the current command line.
107  * @pos_ptr:    Current position in the position history
108  * @baseline:   Pixel offset of the font's baseline from the cursor position.
109  *              This is the 'ascent' of the font, scaled to pixel coordinates.
110  *              It measures the distance from the baseline to the top of the
111  *              font.
112  * @scale:      Scale of the font. This is calculated from the pixel height
113  *              of the font. It is used by the STB library to generate images
114  *              of the correct size.
115  */
116 struct console_tt_priv {
117         int font_size;
118         u8 *font_data;
119         stbtt_fontinfo font;
120         struct pos_info pos[POS_HISTORY_SIZE];
121         int pos_ptr;
122         int baseline;
123         double scale;
124 };
125
126 static int console_truetype_set_row(struct udevice *dev, uint row, int clr)
127 {
128         struct video_priv *vid_priv = dev_get_uclass_priv(dev->parent);
129         struct console_tt_priv *priv = dev_get_priv(dev);
130         void *line;
131         int pixels = priv->font_size * vid_priv->line_length;
132         int i;
133
134         line = vid_priv->fb + row * priv->font_size * vid_priv->line_length;
135         switch (vid_priv->bpix) {
136 #ifdef CONFIG_VIDEO_BPP8
137         case VIDEO_BPP8: {
138                 uint8_t *dst = line;
139
140                 for (i = 0; i < pixels; i++)
141                         *dst++ = clr;
142                 break;
143         }
144 #endif
145 #ifdef CONFIG_VIDEO_BPP16
146         case VIDEO_BPP16: {
147                 uint16_t *dst = line;
148
149                 for (i = 0; i < pixels; i++)
150                         *dst++ = clr;
151                 break;
152         }
153 #endif
154 #ifdef CONFIG_VIDEO_BPP32
155         case VIDEO_BPP32: {
156                 uint32_t *dst = line;
157
158                 for (i = 0; i < pixels; i++)
159                         *dst++ = clr;
160                 break;
161         }
162 #endif
163         default:
164                 return -ENOSYS;
165         }
166
167         return 0;
168 }
169
170 static int console_truetype_move_rows(struct udevice *dev, uint rowdst,
171                                      uint rowsrc, uint count)
172 {
173         struct video_priv *vid_priv = dev_get_uclass_priv(dev->parent);
174         struct console_tt_priv *priv = dev_get_priv(dev);
175         void *dst;
176         void *src;
177         int i, diff;
178
179         dst = vid_priv->fb + rowdst * priv->font_size * vid_priv->line_length;
180         src = vid_priv->fb + rowsrc * priv->font_size * vid_priv->line_length;
181         memmove(dst, src, priv->font_size * vid_priv->line_length * count);
182
183         /* Scroll up our position history */
184         diff = (rowsrc - rowdst) * priv->font_size;
185         for (i = 0; i < priv->pos_ptr; i++)
186                 priv->pos[i].ypos -= diff;
187
188         return 0;
189 }
190
191 static int console_truetype_putc_xy(struct udevice *dev, uint x, uint y,
192                                     char ch)
193 {
194         struct vidconsole_priv *vc_priv = dev_get_uclass_priv(dev);
195         struct udevice *vid = dev->parent;
196         struct video_priv *vid_priv = dev_get_uclass_priv(vid);
197         struct console_tt_priv *priv = dev_get_priv(dev);
198         stbtt_fontinfo *font = &priv->font;
199         int width, height, xoff, yoff;
200         double xpos, x_shift;
201         int lsb;
202         int width_frac, linenum;
203         struct pos_info *pos;
204         u8 *bits, *data;
205         int advance;
206         void *line;
207         int row;
208
209         /* First get some basic metrics about this character */
210         stbtt_GetCodepointHMetrics(font, ch, &advance, &lsb);
211
212         /*
213          * First out our current X position in fractional pixels. If we wrote
214          * a character previously, using kerning to fine-tune the position of
215          * this character */
216         xpos = frac(VID_TO_PIXEL((double)x));
217         if (vc_priv->last_ch) {
218                 xpos += priv->scale * stbtt_GetCodepointKernAdvance(font,
219                                                         vc_priv->last_ch, ch);
220         }
221
222         /*
223          * Figure out where the cursor will move to after this character, and
224          * abort if we are out of space on this line. Also calculate the
225          * effective width of this character, which will be our return value:
226          * it dictates how much the cursor will move forward on the line.
227          */
228         x_shift = xpos - (double)tt_floor(xpos);
229         xpos += advance * priv->scale;
230         width_frac = (int)VID_TO_POS(xpos);
231         if (x + width_frac >= vc_priv->xsize_frac)
232                 return -EAGAIN;
233
234         /* Write the current cursor position into history */
235         if (priv->pos_ptr < POS_HISTORY_SIZE) {
236                 pos = &priv->pos[priv->pos_ptr];
237                 pos->xpos_frac = vc_priv->xcur_frac;
238                 pos->ypos = vc_priv->ycur;
239                 priv->pos_ptr++;
240         }
241
242         /*
243          * Figure out how much past the start of a pixel we are, and pass this
244          * information into the render, which will return a 8-bit-per-pixel
245          * image of the character. For empty characters, like ' ', data will
246          * return NULL;
247          */
248         data = stbtt_GetCodepointBitmapSubpixel(font, priv->scale, priv->scale,
249                                                 x_shift, 0, ch, &width, &height,
250                                                 &xoff, &yoff);
251         if (!data)
252                 return width_frac;
253
254         /* Figure out where to write the character in the frame buffer */
255         bits = data;
256         line = vid_priv->fb + y * vid_priv->line_length +
257                 VID_TO_PIXEL(x) * VNBYTES(vid_priv->bpix);
258         linenum = priv->baseline + yoff;
259         if (linenum > 0)
260                 line += linenum * vid_priv->line_length;
261
262         /*
263          * Write a row at a time, converting the 8bpp image into the colour
264          * depth of the display. We only expect white-on-black or the reverse
265          * so the code only handles this simple case.
266          */
267         for (row = 0; row < height; row++) {
268                 switch (vid_priv->bpix) {
269 #ifdef CONFIG_VIDEO_BPP16
270                 case VIDEO_BPP16: {
271                         uint16_t *dst = (uint16_t *)line + xoff;
272                         int i;
273
274                         for (i = 0; i < width; i++) {
275                                 int val = *bits;
276                                 int out;
277
278                                 if (vid_priv->colour_bg)
279                                         val = 255 - val;
280                                 out = val >> 3 |
281                                         (val >> 2) << 5 |
282                                         (val >> 3) << 11;
283                                 if (vid_priv->colour_fg)
284                                         *dst++ |= out;
285                                 else
286                                         *dst++ &= out;
287                                 bits++;
288                         }
289                         break;
290                 }
291 #endif
292 #ifdef CONFIG_VIDEO_BPP32
293                 case VIDEO_BPP32: {
294                         u32 *dst = (u32 *)line + xoff;
295                         int i;
296
297                         for (i = 0; i < width; i++) {
298                                 int val = *bits;
299                                 int out;
300
301                                 if (vid_priv->colour_bg)
302                                         val = 255 - val;
303                                 out = val | val << 8 | val << 16;
304                                 if (vid_priv->colour_fg)
305                                         *dst++ |= out;
306                                 else
307                                         *dst++ &= out;
308                                 bits++;
309                         }
310                         break;
311                 }
312 #endif
313                 default:
314                         free(data);
315                         return -ENOSYS;
316                 }
317
318                 line += vid_priv->line_length;
319         }
320         free(data);
321
322         return width_frac;
323 }
324
325 /**
326  * console_truetype_erase() - Erase a character
327  *
328  * This is used for backspace. We erase a square of the display within the
329  * given bounds.
330  *
331  * @dev:        Device to update
332  * @xstart:     X start position in pixels from the left
333  * @ystart:     Y start position in pixels from the top
334  * @xend:       X end position in pixels from the left
335  * @yend:       Y end position  in pixels from the top
336  * @clr:        Value to write
337  * @return 0 if OK, -ENOSYS if the display depth is not supported
338  */
339 static int console_truetype_erase(struct udevice *dev, int xstart, int ystart,
340                                   int xend, int yend, int clr)
341 {
342         struct video_priv *vid_priv = dev_get_uclass_priv(dev->parent);
343         void *line;
344         int pixels = xend - xstart;
345         int row, i;
346
347         line = vid_priv->fb + ystart * vid_priv->line_length;
348         line += xstart * VNBYTES(vid_priv->bpix);
349         for (row = ystart; row < yend; row++) {
350                 switch (vid_priv->bpix) {
351 #ifdef CONFIG_VIDEO_BPP8
352                 case VIDEO_BPP8: {
353                         uint8_t *dst = line;
354
355                         for (i = 0; i < pixels; i++)
356                                 *dst++ = clr;
357                         break;
358                 }
359 #endif
360 #ifdef CONFIG_VIDEO_BPP16
361                 case VIDEO_BPP16: {
362                         uint16_t *dst = line;
363
364                         for (i = 0; i < pixels; i++)
365                                 *dst++ = clr;
366                         break;
367                 }
368 #endif
369 #ifdef CONFIG_VIDEO_BPP32
370                 case VIDEO_BPP32: {
371                         uint32_t *dst = line;
372
373                         for (i = 0; i < pixels; i++)
374                                 *dst++ = clr;
375                         break;
376                 }
377 #endif
378                 default:
379                         return -ENOSYS;
380                 }
381                 line += vid_priv->line_length;
382         }
383
384         return 0;
385 }
386
387 /**
388  * console_truetype_backspace() - Handle a backspace operation
389  *
390  * This clears the previous character so that the console looks as if it had
391  * not been entered.
392  *
393  * @dev:        Device to update
394  * @return 0 if OK, -ENOSYS if not supported
395  */
396 static int console_truetype_backspace(struct udevice *dev)
397 {
398         struct vidconsole_priv *vc_priv = dev_get_uclass_priv(dev);
399         struct console_tt_priv *priv = dev_get_priv(dev);
400         struct udevice *vid_dev = dev->parent;
401         struct video_priv *vid_priv = dev_get_uclass_priv(vid_dev);
402         struct pos_info *pos;
403         int xend;
404
405         /*
406          * This indicates a very strange error higher in the stack. The caller
407          * has sent out n character and n + 1 backspaces.
408          */
409         if (!priv->pos_ptr)
410                 return -ENOSYS;
411
412         /* Pop the last cursor position off the stack */
413         pos = &priv->pos[--priv->pos_ptr];
414
415         /*
416          * Figure out the end position for clearing. Normlly it is the current
417          * cursor position, but if we are clearing a character on the previous
418          * line, we clear from the end of the line.
419          */
420         if (pos->ypos == vc_priv->ycur)
421                 xend = VID_TO_PIXEL(vc_priv->xcur_frac);
422         else
423                 xend = vid_priv->xsize;
424
425         console_truetype_erase(dev, VID_TO_PIXEL(pos->xpos_frac), pos->ypos,
426                                xend, pos->ypos + vc_priv->y_charsize,
427                                vid_priv->colour_bg);
428
429         /* Move the cursor back to where it was when we pushed this record */
430         vc_priv->xcur_frac = pos->xpos_frac;
431         vc_priv->ycur = pos->ypos;
432
433         return 0;
434 }
435
436 static int console_truetype_entry_start(struct udevice *dev)
437 {
438         struct console_tt_priv *priv = dev_get_priv(dev);
439
440         /* A new input line has start, so clear our history */
441         priv->pos_ptr = 0;
442
443         return 0;
444 }
445
446 /*
447  * Provides a list of fonts which can be obtained at run-time in U-Boot. These
448  * are compiled in by the Makefile.
449  *
450  * At present there is no mechanism to select a particular font - the first
451  * one found is the one that is used. But the build system and the code here
452  * supports multiple fonts, which may be useful for certain firmware screens.
453  */
454 struct font_info {
455         char *name;
456         u8 *begin;
457         u8 *end;
458 };
459
460 #define FONT_DECL(_name) \
461         extern u8 __ttf_ ## _name ## _begin[]; \
462         extern u8 __ttf_ ## _name ## _end[];
463
464 #define FONT_ENTRY(_name)               { \
465         .name = #_name, \
466         .begin = __ttf_ ## _name ## _begin, \
467         .end = __ttf_ ## _name ## _end, \
468         }
469
470 FONT_DECL(nimbus_sans_l_regular);
471 FONT_DECL(ankacoder_c75_r);
472 FONT_DECL(rufscript010);
473 FONT_DECL(cantoraone_regular);
474
475 static struct font_info font_table[] = {
476 #ifdef CONFIG_CONSOLE_TRUETYPE_NIMBUS
477         FONT_ENTRY(nimbus_sans_l_regular),
478 #endif
479 #ifdef CONFIG_CONSOLE_TRUETYPE_ANKACODER
480         FONT_ENTRY(ankacoder_c75_r),
481 #endif
482 #ifdef CONFIG_CONSOLE_TRUETYPE_RUFSCRIPT
483         FONT_ENTRY(rufscript010),
484 #endif
485 #ifdef CONFIG_CONSOLE_TRUETYPE_CANTORAONE
486         FONT_ENTRY(cantoraone_regular),
487 #endif
488         {} /* sentinel */
489 };
490
491 #define FONT_BEGIN(name)        __ttf_ ## name ## _begin
492 #define FONT_END(name)          __ttf_ ## name ## _end
493 #define FONT_IS_VALID(name)     (abs(FONT_END(name) - FONT_BEGIN) > 4)
494
495 /**
496  * console_truetype_find_font() - Find a suitable font
497  *
498  * This searched for the first available font.
499  *
500  * @return pointer to the font, or NULL if none is found
501  */
502 static u8 *console_truetype_find_font(void)
503 {
504         struct font_info *tab;
505
506         for (tab = font_table; tab->begin; tab++) {
507                 if (abs(tab->begin - tab->end) > 4) {
508                         debug("%s: Font '%s', at %p, size %lx\n", __func__,
509                               tab->name, tab->begin,
510                               (ulong)(tab->end - tab->begin));
511                         return tab->begin;
512                 }
513         }
514
515         return NULL;
516 }
517
518 static int console_truetype_probe(struct udevice *dev)
519 {
520         struct vidconsole_priv *vc_priv = dev_get_uclass_priv(dev);
521         struct console_tt_priv *priv = dev_get_priv(dev);
522         struct udevice *vid_dev = dev->parent;
523         struct video_priv *vid_priv = dev_get_uclass_priv(vid_dev);
524         stbtt_fontinfo *font = &priv->font;
525         int ascent;
526
527         debug("%s: start\n", __func__);
528         if (vid_priv->font_size)
529                 priv->font_size = vid_priv->font_size;
530         else
531                 priv->font_size = CONFIG_CONSOLE_TRUETYPE_SIZE;
532         priv->font_data = console_truetype_find_font();
533         if (!priv->font_data) {
534                 debug("%s: Could not find any fonts\n", __func__);
535                 return -EBFONT;
536         }
537
538         vc_priv->x_charsize = priv->font_size;
539         vc_priv->y_charsize = priv->font_size;
540         vc_priv->xstart_frac = VID_TO_POS(2);
541         vc_priv->cols = vid_priv->xsize / priv->font_size;
542         vc_priv->rows = vid_priv->ysize / priv->font_size;
543         vc_priv->tab_width_frac = VID_TO_POS(priv->font_size) * 8 / 2;
544
545         if (!stbtt_InitFont(font, priv->font_data, 0)) {
546                 debug("%s: Font init failed\n", __func__);
547                 return -EPERM;
548         }
549
550         /* Pre-calculate some things we will need regularly */
551         priv->scale = stbtt_ScaleForPixelHeight(font, priv->font_size);
552         stbtt_GetFontVMetrics(font, &ascent, 0, 0);
553         priv->baseline = (int)(ascent * priv->scale);
554         debug("%s: ready\n", __func__);
555
556         return 0;
557 }
558
559 struct vidconsole_ops console_truetype_ops = {
560         .putc_xy        = console_truetype_putc_xy,
561         .move_rows      = console_truetype_move_rows,
562         .set_row        = console_truetype_set_row,
563         .backspace      = console_truetype_backspace,
564         .entry_start    = console_truetype_entry_start,
565 };
566
567 U_BOOT_DRIVER(vidconsole_truetype) = {
568         .name   = "vidconsole_tt",
569         .id     = UCLASS_VIDEO_CONSOLE,
570         .ops    = &console_truetype_ops,
571         .probe  = console_truetype_probe,
572         .priv_auto_alloc_size   = sizeof(struct console_tt_priv),
573 };