ash,hush: optional support for $HISTFILESIZE.
[oweals/busybox.git] / miscutils / fbsplash.c
1 /* vi: set sw=4 ts=4: */
2 /*
3  * Copyright (C) 2008 Michele Sanges <michele.sanges@gmail.com>
4  *
5  * Licensed under GPLv2 or later, see file LICENSE in this source tree.
6  *
7  * Usage:
8  * - use kernel option 'vga=xxx' or otherwise enable framebuffer device.
9  * - put somewhere fbsplash.cfg file and an image in .ppm format.
10  * - run applet: $ setsid fbsplash [params] &
11  *      -c: hide cursor
12  *      -d /dev/fbN: framebuffer device (if not /dev/fb0)
13  *      -s path_to_image_file (can be "-" for stdin)
14  *      -i path_to_cfg_file
15  *      -f path_to_fifo (can be "-" for stdin)
16  * - if you want to run it only in presence of a kernel parameter
17  *   (for example fbsplash=on), use:
18  *   grep -q "fbsplash=on" </proc/cmdline && setsid fbsplash [params]
19  * - commands for fifo:
20  *   "NN" (ASCII decimal number) - percentage to show on progress bar.
21  *   "exit" (or just close fifo) - well you guessed it.
22  */
23
24 #include "libbb.h"
25 #include <linux/fb.h>
26
27 /* If you want logging messages on /tmp/fbsplash.log... */
28 #define DEBUG 0
29
30 struct globals {
31 #if DEBUG
32         bool bdebug_messages;   // enable/disable logging
33         FILE *logfile_fd;       // log file
34 #endif
35         unsigned char *addr;    // pointer to framebuffer memory
36         unsigned ns[7];         // n-parameters
37         const char *image_filename;
38         struct fb_var_screeninfo scr_var;
39         struct fb_fix_screeninfo scr_fix;
40         unsigned bytes_per_pixel;
41 };
42 #define G (*ptr_to_globals)
43 #define INIT_G() do { \
44         SET_PTR_TO_GLOBALS(xzalloc(sizeof(G))); \
45 } while (0)
46
47 #define nbar_width      ns[0]   // progress bar width
48 #define nbar_height     ns[1]   // progress bar height
49 #define nbar_posx       ns[2]   // progress bar horizontal position
50 #define nbar_posy       ns[3]   // progress bar vertical position
51 #define nbar_colr       ns[4]   // progress bar color red component
52 #define nbar_colg       ns[5]   // progress bar color green component
53 #define nbar_colb       ns[6]   // progress bar color blue component
54
55 #if DEBUG
56 #define DEBUG_MESSAGE(strMessage, args...) \
57         if (G.bdebug_messages) { \
58                 fprintf(G.logfile_fd, "[%s][%s] - %s\n", \
59                 __FILE__, __FUNCTION__, strMessage);    \
60         }
61 #else
62 #define DEBUG_MESSAGE(...) ((void)0)
63 #endif
64
65
66 /**
67  * Open and initialize the framebuffer device
68  * \param *strfb_device pointer to framebuffer device
69  */
70 static void fb_open(const char *strfb_device)
71 {
72         int fbfd = xopen(strfb_device, O_RDWR);
73
74         // framebuffer properties
75         xioctl(fbfd, FBIOGET_VSCREENINFO, &G.scr_var);
76         xioctl(fbfd, FBIOGET_FSCREENINFO, &G.scr_fix);
77
78         if (G.scr_var.bits_per_pixel < 16 || G.scr_var.bits_per_pixel > 32)
79                 bb_error_msg_and_die("unsupported %u bpp", (int)G.scr_var.bits_per_pixel);
80         G.bytes_per_pixel = (G.scr_var.bits_per_pixel + 7) >> 3;
81
82         // map the device in memory
83         G.addr = mmap(NULL,
84                         G.scr_var.xres * G.scr_var.yres * G.bytes_per_pixel,
85                         PROT_WRITE, MAP_SHARED, fbfd, 0);
86         if (G.addr == MAP_FAILED)
87                 bb_perror_msg_and_die("mmap");
88
89         // point to the start of the visible screen
90         G.addr += G.scr_var.yoffset * G.scr_fix.line_length + G.scr_var.xoffset * G.bytes_per_pixel;
91         close(fbfd);
92 }
93
94
95 /**
96  * Return pixel value of the passed RGB color
97  */
98 static unsigned fb_pixel_value(unsigned r, unsigned g, unsigned b)
99 {
100         if (G.bytes_per_pixel == 2) {
101                 r >>= 3;  // 5-bit red
102                 g >>= 2;  // 6-bit green
103                 b >>= 3;  // 5-bit blue
104                 return b + (g << 5) + (r << (5+6));
105         }
106         // RGB 888
107         return b + (g << 8) + (r << 16);
108 }
109
110 /**
111  * Draw pixel on framebuffer
112  */
113 static void fb_write_pixel(unsigned char *addr, unsigned pixel)
114 {
115         switch (G.bytes_per_pixel) {
116         case 2:
117                 *(uint16_t *)addr = pixel;
118                 break;
119         case 4:
120                 *(uint32_t *)addr = pixel;
121                 break;
122         default: // 24 bits per pixel
123                 addr[0] = pixel;
124                 addr[1] = pixel >> 8;
125                 addr[2] = pixel >> 16;
126         }
127 }
128
129
130 /**
131  * Draw hollow rectangle on framebuffer
132  */
133 static void fb_drawrectangle(void)
134 {
135         int cnt;
136         unsigned thispix;
137         unsigned char *ptr1, *ptr2;
138         unsigned char nred = G.nbar_colr/2;
139         unsigned char ngreen =  G.nbar_colg/2;
140         unsigned char nblue = G.nbar_colb/2;
141
142         thispix = fb_pixel_value(nred, ngreen, nblue);
143
144         // horizontal lines
145         ptr1 = G.addr + (G.nbar_posy * G.scr_var.xres + G.nbar_posx) * G.bytes_per_pixel;
146         ptr2 = G.addr + ((G.nbar_posy + G.nbar_height - 1) * G.scr_var.xres + G.nbar_posx) * G.bytes_per_pixel;
147         cnt = G.nbar_width - 1;
148         do {
149                 fb_write_pixel(ptr1, thispix);
150                 fb_write_pixel(ptr2, thispix);
151                 ptr1 += G.bytes_per_pixel;
152                 ptr2 += G.bytes_per_pixel;
153         } while (--cnt >= 0);
154
155         // vertical lines
156         ptr1 = G.addr + (G.nbar_posy * G.scr_var.xres + G.nbar_posx) * G.bytes_per_pixel;
157         ptr2 = G.addr + (G.nbar_posy * G.scr_var.xres + G.nbar_posx + G.nbar_width - 1) * G.bytes_per_pixel;
158         cnt = G.nbar_height - 1;
159         do {
160                 fb_write_pixel(ptr1, thispix);
161                 fb_write_pixel(ptr2, thispix);
162                 ptr1 += G.scr_var.xres * G.bytes_per_pixel;
163                 ptr2 += G.scr_var.xres * G.bytes_per_pixel;
164         } while (--cnt >= 0);
165 }
166
167
168 /**
169  * Draw filled rectangle on framebuffer
170  * \param nx1pos,ny1pos upper left position
171  * \param nx2pos,ny2pos down right position
172  * \param nred,ngreen,nblue rgb color
173  */
174 static void fb_drawfullrectangle(int nx1pos, int ny1pos, int nx2pos, int ny2pos,
175         unsigned char nred, unsigned char ngreen, unsigned char nblue)
176 {
177         int cnt1, cnt2, nypos;
178         unsigned thispix;
179         unsigned char *ptr;
180
181         thispix = fb_pixel_value(nred, ngreen, nblue);
182
183         cnt1 = ny2pos - ny1pos;
184         nypos = ny1pos;
185         do {
186                 ptr = G.addr + (nypos * G.scr_var.xres + nx1pos) * G.bytes_per_pixel;
187                 cnt2 = nx2pos - nx1pos;
188                 do {
189                         fb_write_pixel(ptr, thispix);
190                         ptr += G.bytes_per_pixel;
191                 } while (--cnt2 >= 0);
192
193                 nypos++;
194         } while (--cnt1 >= 0);
195 }
196
197
198 /**
199  * Draw a progress bar on framebuffer
200  * \param percent percentage of loading
201  */
202 static void fb_drawprogressbar(unsigned percent)
203 {
204         int i, left_x, top_y, width, height;
205
206         // outer box
207         left_x = G.nbar_posx;
208         top_y = G.nbar_posy;
209         width = G.nbar_width - 1;
210         height = G.nbar_height - 1;
211         if ((height | width) < 0)
212                 return;
213         // NB: "width" of 1 actually makes rect with width of 2!
214         fb_drawrectangle();
215
216         // inner "empty" rectangle
217         left_x++;
218         top_y++;
219         width -= 2;
220         height -= 2;
221         if ((height | width) < 0)
222                 return;
223         fb_drawfullrectangle(
224                         left_x, top_y,
225                                         left_x + width, top_y + height,
226                         G.nbar_colr, G.nbar_colg, G.nbar_colb);
227
228         if (percent > 0) {
229                 // actual progress bar
230                 width = width * percent / 100;
231                 i = height;
232                 if (height == 0)
233                         height++; // divide by 0 is bad
234                 while (i >= 0) {
235                         // draw one-line thick "rectangle"
236                         // top line will have gray lvl 200, bottom one 100
237                         unsigned gray_level = 100 + i*100/height;
238                         fb_drawfullrectangle(
239                                         left_x, top_y, left_x + width, top_y,
240                                         gray_level, gray_level, gray_level);
241                         top_y++;
242                         i--;
243                 }
244         }
245 }
246
247
248 /**
249  * Draw image from PPM file
250  */
251 static void fb_drawimage(void)
252 {
253         FILE *theme_file;
254         char *read_ptr;
255         unsigned char *pixline;
256         unsigned i, j, width, height, line_size;
257
258         if (LONE_DASH(G.image_filename)) {
259                 theme_file = stdin;
260         } else {
261                 int fd = open_zipped(G.image_filename);
262                 if (fd < 0)
263                         bb_simple_perror_msg_and_die(G.image_filename);
264                 theme_file = xfdopen_for_read(fd);
265         }
266
267         /* Parse ppm header:
268          * - Magic: two characters "P6".
269          * - Whitespace (blanks, TABs, CRs, LFs).
270          * - A width, formatted as ASCII characters in decimal.
271          * - Whitespace.
272          * - A height, ASCII decimal.
273          * - Whitespace.
274          * - The maximum color value, ASCII decimal, in 0..65535
275          * - Newline or other single whitespace character.
276          *   (we support newline only)
277          * - A raster of Width * Height pixels in triplets of rgb
278          *   in pure binary by 1 or 2 bytes. (we support only 1 byte)
279          */
280 #define concat_buf bb_common_bufsiz1
281         read_ptr = concat_buf;
282         while (1) {
283                 int w, h, max_color_val;
284                 int rem = concat_buf + sizeof(concat_buf) - read_ptr;
285                 if (rem < 2
286                  || fgets(read_ptr, rem, theme_file) == NULL
287                 ) {
288                         bb_error_msg_and_die("bad PPM file '%s'", G.image_filename);
289                 }
290                 read_ptr = strchrnul(read_ptr, '#');
291                 *read_ptr = '\0'; /* ignore #comments */
292                 if (sscanf(concat_buf, "P6 %u %u %u", &w, &h, &max_color_val) == 3
293                  && max_color_val <= 255
294                 ) {
295                         width = w; /* w is on stack, width may be in register */
296                         height = h;
297                         break;
298                 }
299         }
300
301         line_size = width*3;
302         pixline = xmalloc(line_size);
303
304         if (width > G.scr_var.xres)
305                 width = G.scr_var.xres;
306         if (height > G.scr_var.yres)
307                 height = G.scr_var.yres;
308         for (j = 0; j < height; j++) {
309                 unsigned char *pixel;
310                 unsigned char *src;
311
312                 if (fread(pixline, 1, line_size, theme_file) != line_size)
313                         bb_error_msg_and_die("bad PPM file '%s'", G.image_filename);
314                 pixel = pixline;
315                 src = G.addr + j * G.scr_fix.line_length;
316                 for (i = 0; i < width; i++) {
317                         unsigned thispix = fb_pixel_value(pixel[0], pixel[1], pixel[2]);
318                         fb_write_pixel(src, thispix);
319                         src += G.bytes_per_pixel;
320                         pixel += 3;
321                 }
322         }
323         free(pixline);
324         fclose(theme_file);
325 }
326
327
328 /**
329  * Parse configuration file
330  * \param *cfg_filename name of the configuration file
331  */
332 static void init(const char *cfg_filename)
333 {
334         static const char param_names[] ALIGN1 =
335                 "BAR_WIDTH\0" "BAR_HEIGHT\0"
336                 "BAR_LEFT\0" "BAR_TOP\0"
337                 "BAR_R\0" "BAR_G\0" "BAR_B\0"
338 #if DEBUG
339                 "DEBUG\0"
340 #endif
341                 ;
342         char *token[2];
343         parser_t *parser = config_open2(cfg_filename, xfopen_stdin);
344         while (config_read(parser, token, 2, 2, "#=",
345                                 (PARSE_NORMAL | PARSE_MIN_DIE) & ~(PARSE_TRIM | PARSE_COLLAPSE))) {
346                 unsigned val = xatoi_positive(token[1]);
347                 int i = index_in_strings(param_names, token[0]);
348                 if (i < 0)
349                         bb_error_msg_and_die("syntax error: %s", token[0]);
350                 if (i >= 0 && i < 7)
351                         G.ns[i] = val;
352 #if DEBUG
353                 if (i == 7) {
354                         G.bdebug_messages = val;
355                         if (G.bdebug_messages)
356                                 G.logfile_fd = xfopen_for_write("/tmp/fbsplash.log");
357                 }
358 #endif
359         }
360         config_close(parser);
361 }
362
363
364 int fbsplash_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
365 int fbsplash_main(int argc UNUSED_PARAM, char **argv)
366 {
367         const char *fb_device, *cfg_filename, *fifo_filename;
368         FILE *fp = fp; // for compiler
369         char *num_buf;
370         unsigned num;
371         bool bCursorOff;
372
373         INIT_G();
374
375         // parse command line options
376         fb_device = "/dev/fb0";
377         cfg_filename = NULL;
378         fifo_filename = NULL;
379         bCursorOff = 1 & getopt32(argv, "cs:d:i:f:",
380                         &G.image_filename, &fb_device, &cfg_filename, &fifo_filename);
381
382         // parse configuration file
383         if (cfg_filename)
384                 init(cfg_filename);
385
386         // We must have -s IMG
387         if (!G.image_filename)
388                 bb_show_usage();
389
390         fb_open(fb_device);
391
392         if (fifo_filename && bCursorOff) {
393                 // hide cursor (BEFORE any fb ops)
394                 full_write(STDOUT_FILENO, "\033[?25l", 6);
395         }
396
397         fb_drawimage();
398
399         if (!fifo_filename)
400                 return EXIT_SUCCESS;
401
402         fp = xfopen_stdin(fifo_filename);
403         if (fp != stdin) {
404                 // For named pipes, we want to support this:
405                 //  mkfifo cmd_pipe
406                 //  fbsplash -f cmd_pipe .... &
407                 //  ...
408                 //  echo 33 >cmd_pipe
409                 //  ...
410                 //  echo 66 >cmd_pipe
411                 // This means that we don't want fbsplash to get EOF
412                 // when last writer closes input end.
413                 // The simplest way is to open fifo for writing too
414                 // and become an additional writer :)
415                 open(fifo_filename, O_WRONLY); // errors are ignored
416         }
417
418         fb_drawprogressbar(0);
419         // Block on read, waiting for some input.
420         // Use of <stdio.h> style I/O allows to correctly
421         // handle a case when we have many buffered lines
422         // already in the pipe
423         while ((num_buf = xmalloc_fgetline(fp)) != NULL) {
424                 if (strncmp(num_buf, "exit", 4) == 0) {
425                         DEBUG_MESSAGE("exit");
426                         break;
427                 }
428                 num = atoi(num_buf);
429                 if (isdigit(num_buf[0]) && (num <= 100)) {
430 #if DEBUG
431                         DEBUG_MESSAGE(itoa(num));
432 #endif
433                         fb_drawprogressbar(num);
434                 }
435                 free(num_buf);
436         }
437
438         if (bCursorOff) // restore cursor
439                 full_write(STDOUT_FILENO, "\033[?25h", 6);
440
441         return EXIT_SUCCESS;
442 }