Recording screen: show a more compact view if 6 lines do not fit but 4 do. Should...
[kugel-rb.git] / apps / misc.c
blobf1f5c4aa12c27f9d3669252a12ee7ba31db2f6e2
1 /***************************************************************************
2 * __________ __ ___.
3 * Open \______ \ ____ ____ | | _\_ |__ _______ ___
4 * Source | _// _ \_/ ___\| |/ /| __ \ / _ \ \/ /
5 * Jukebox | | ( <_> ) \___| < | \_\ ( <_> > < <
6 * Firmware |____|_ /\____/ \___ >__|_ \|___ /\____/__/\_ \
7 * \/ \/ \/ \/ \/
8 * $Id$
10 * Copyright (C) 2002 by Daniel Stenberg
12 * This program is free software; you can redistribute it and/or
13 * modify it under the terms of the GNU General Public License
14 * as published by the Free Software Foundation; either version 2
15 * of the License, or (at your option) any later version.
17 * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
18 * KIND, either express or implied.
20 ****************************************************************************/
21 #include <stdlib.h>
22 #include <ctype.h>
23 #include "config.h"
24 #include "lcd.h"
25 #include "file.h"
26 #ifdef __PCTOOL__
27 #include <stdint.h>
28 #include <stdarg.h>
29 #else
30 #include "sprintf.h"
31 #include "lang.h"
32 #include "string.h"
33 #include "dir.h"
34 #include "lcd-remote.h"
35 #include "errno.h"
36 #include "system.h"
37 #include "timefuncs.h"
38 #include "screens.h"
39 #include "talk.h"
40 #include "mpeg.h"
41 #include "audio.h"
42 #include "mp3_playback.h"
43 #include "settings.h"
44 #include "ata.h"
45 #include "ata_idle_notify.h"
46 #include "kernel.h"
47 #include "power.h"
48 #include "powermgmt.h"
49 #include "backlight.h"
50 #include "version.h"
51 #include "font.h"
52 #include "splash.h"
53 #include "tagcache.h"
54 #include "scrobbler.h"
55 #include "sound.h"
56 #include "playlist.h"
57 #include "yesno.h"
59 #ifdef HAVE_MMC
60 #include "ata_mmc.h"
61 #endif
62 #include "tree.h"
63 #include "eeprom_settings.h"
64 #if defined(HAVE_RECORDING) && !defined(__PCTOOL__)
65 #include "recording.h"
66 #endif
67 #if defined(HAVE_LCD_BITMAP) && !defined(__PCTOOL__)
68 #include "bmp.h"
69 #include "icons.h"
70 #endif /* End HAVE_LCD_BITMAP */
71 #include "gui/gwps-common.h"
72 #include "bookmark.h"
74 #include "misc.h"
75 #include "playback.h"
77 #ifdef BOOTFILE
78 #if !defined(USB_NONE) && !defined(USB_IPODSTYLE)
79 #include "rolo.h"
80 #include "yesno.h"
81 #endif
82 #endif
84 /* Format a large-range value for output, using the appropriate unit so that
85 * the displayed value is in the range 1 <= display < 1000 (1024 for "binary"
86 * units) if possible, and 3 significant digits are shown. If a buffer is
87 * given, the result is snprintf()'d into that buffer, otherwise the result is
88 * voiced.*/
89 char *output_dyn_value(char *buf, int buf_size, int value,
90 const unsigned char **units, bool bin_scale)
92 int scale = bin_scale ? 1024 : 1000;
93 int fraction = 0;
94 int unit_no = 0;
95 char tbuf[5];
97 while (value >= scale)
99 fraction = value % scale;
100 value /= scale;
101 unit_no++;
103 if (bin_scale)
104 fraction = fraction * 1000 / 1024;
106 if (value >= 100 || !unit_no)
107 tbuf[0] = '\0';
108 else if (value >= 10)
109 snprintf(tbuf, sizeof(tbuf), "%01d", fraction / 100);
110 else
111 snprintf(tbuf, sizeof(tbuf), "%02d", fraction / 10);
113 if (buf)
115 if (strlen(tbuf))
116 snprintf(buf, buf_size, "%d%s%s%s", value, str(LANG_POINT),
117 tbuf, P2STR(units[unit_no]));
118 else
119 snprintf(buf, buf_size, "%d%s", value, P2STR(units[unit_no]));
121 else
123 talk_fractional(tbuf, value, P2ID(units[unit_no]));
125 return buf;
128 /* Create a filename with a number part in a way that the number is 1
129 * higher than the highest numbered file matching the same pattern.
130 * It is allowed that buffer and path point to the same memory location,
131 * saving a strcpy(). Path must always be given without trailing slash.
132 * "num" can point to an int specifying the number to use or NULL or a value
133 * less than zero to number automatically. The final number used will also
134 * be returned in *num. If *num is >= 0 then *num will be incremented by
135 * one. */
136 char *create_numbered_filename(char *buffer, const char *path,
137 const char *prefix, const char *suffix,
138 int numberlen IF_CNFN_NUM_(, int *num))
140 DIR *dir;
141 struct dirent *entry;
142 int max_num;
143 int pathlen;
144 int prefixlen = strlen(prefix);
145 char fmtstring[12];
147 if (buffer != path)
148 strncpy(buffer, path, MAX_PATH);
150 pathlen = strlen(buffer);
152 #ifdef IF_CNFN_NUM
153 if (num && *num >= 0)
155 /* number specified */
156 max_num = *num;
158 else
159 #endif
161 /* automatic numbering */
162 max_num = 0;
164 dir = opendir(pathlen ? buffer : "/");
165 if (!dir)
166 return NULL;
168 while ((entry = readdir(dir)))
170 int curr_num;
172 if (strncasecmp((char *)entry->d_name, prefix, prefixlen)
173 || strcasecmp((char *)entry->d_name + prefixlen + numberlen, suffix))
174 continue;
176 curr_num = atoi((char *)entry->d_name + prefixlen);
177 if (curr_num > max_num)
178 max_num = curr_num;
181 closedir(dir);
184 max_num++;
186 snprintf(fmtstring, sizeof(fmtstring), "/%%s%%0%dd%%s", numberlen);
187 snprintf(buffer + pathlen, MAX_PATH - pathlen, fmtstring, prefix,
188 max_num, suffix);
190 #ifdef IF_CNFN_NUM
191 if (num)
192 *num = max_num;
193 #endif
195 return buffer;
198 /* Format time into buf.
200 * buf - buffer to format to.
201 * buf_size - size of buffer.
202 * t - time to format, in milliseconds.
204 void format_time(char* buf, int buf_size, long t)
206 if ( t < 3600000 )
208 snprintf(buf, buf_size, "%d:%02d",
209 (int) (t / 60000), (int) (t % 60000 / 1000));
211 else
213 snprintf(buf, buf_size, "%d:%02d:%02d",
214 (int) (t / 3600000), (int) (t % 3600000 / 60000),
215 (int) (t % 60000 / 1000));
219 #if CONFIG_RTC
220 /* Create a filename with a date+time part.
221 It is allowed that buffer and path point to the same memory location,
222 saving a strcpy(). Path must always be given without trailing slash.
223 unique_time as true makes the function wait until the current time has
224 changed. */
225 char *create_datetime_filename(char *buffer, const char *path,
226 const char *prefix, const char *suffix,
227 bool unique_time)
229 struct tm *tm = get_time();
230 static struct tm last_tm;
231 int pathlen;
233 while (unique_time && !memcmp(get_time(), &last_tm, sizeof (struct tm)))
234 sleep(HZ/10);
236 last_tm = *tm;
238 if (buffer != path)
239 strncpy(buffer, path, MAX_PATH);
241 pathlen = strlen(buffer);
242 snprintf(buffer + pathlen, MAX_PATH - pathlen,
243 "/%s%02d%02d%02d-%02d%02d%02d%s", prefix,
244 tm->tm_year % 100, tm->tm_mon + 1, tm->tm_mday,
245 tm->tm_hour, tm->tm_min, tm->tm_sec, suffix);
247 return buffer;
249 #endif /* CONFIG_RTC */
251 /* Ask the user if they really want to erase the current dynamic playlist
252 * returns true if the playlist should be replaced */
253 bool warn_on_pl_erase(void)
255 if (global_settings.warnon_erase_dynplaylist &&
256 !global_settings.party_mode &&
257 playlist_modified(NULL))
259 static const char *lines[] =
260 {ID2P(LANG_WARN_ERASEDYNPLAYLIST_PROMPT)};
261 static const struct text_message message={lines, 1};
263 return (gui_syncyesno_run(&message, NULL, NULL) == YESNO_YES);
265 else
266 return true;
269 /* Read (up to) a line of text from fd into buffer and return number of bytes
270 * read (which may be larger than the number of bytes stored in buffer). If
271 * an error occurs, -1 is returned (and buffer contains whatever could be
272 * read). A line is terminated by a LF char. Neither LF nor CR chars are
273 * stored in buffer.
275 int read_line(int fd, char* buffer, int buffer_size)
277 int count = 0;
278 int num_read = 0;
280 errno = 0;
282 while (count < buffer_size)
284 unsigned char c;
286 if (1 != read(fd, &c, 1))
287 break;
289 num_read++;
291 if ( c == '\n' )
292 break;
294 if ( c == '\r' )
295 continue;
297 buffer[count++] = c;
300 buffer[MIN(count, buffer_size - 1)] = 0;
302 return errno ? -1 : num_read;
305 /* Performance optimized version of the previous function. */
306 int fast_readline(int fd, char *buf, int buf_size, void *parameters,
307 int (*callback)(int n, const char *buf, void *parameters))
309 char *p, *next;
310 int rc, pos = 0;
311 int count = 0;
313 while ( 1 )
315 next = NULL;
317 rc = read(fd, &buf[pos], buf_size - pos - 1);
318 if (rc >= 0)
319 buf[pos+rc] = '\0';
321 if ( (p = strchr(buf, '\r')) != NULL)
323 *p = '\0';
324 next = ++p;
326 else
327 p = buf;
329 if ( (p = strchr(p, '\n')) != NULL)
331 *p = '\0';
332 next = ++p;
335 rc = callback(count, buf, parameters);
336 if (rc < 0)
337 return rc;
339 count++;
340 if (next)
342 pos = buf_size - ((long)next - (long)buf) - 1;
343 memmove(buf, next, pos);
345 else
346 break ;
349 return 0;
352 #ifdef HAVE_LCD_BITMAP
354 #if LCD_DEPTH == 16
355 #define BMP_COMPRESSION 3 /* BI_BITFIELDS */
356 #define BMP_NUMCOLORS 3
357 #else
358 #define BMP_COMPRESSION 0 /* BI_RGB */
359 #if LCD_DEPTH <= 8
360 #define BMP_NUMCOLORS (1 << LCD_DEPTH)
361 #else
362 #define BMP_NUMCOLORS 0
363 #endif
364 #endif
366 #if LCD_DEPTH == 1
367 #define BMP_BPP 1
368 #define BMP_LINESIZE ((LCD_WIDTH/8 + 3) & ~3)
369 #elif LCD_DEPTH <= 4
370 #define BMP_BPP 4
371 #define BMP_LINESIZE ((LCD_WIDTH/2 + 3) & ~3)
372 #elif LCD_DEPTH <= 8
373 #define BMP_BPP 8
374 #define BMP_LINESIZE ((LCD_WIDTH + 3) & ~3)
375 #elif LCD_DEPTH <= 16
376 #define BMP_BPP 16
377 #define BMP_LINESIZE ((LCD_WIDTH*2 + 3) & ~3)
378 #else
379 #define BMP_BPP 24
380 #define BMP_LINESIZE ((LCD_WIDTH*3 + 3) & ~3)
381 #endif
383 #define BMP_HEADERSIZE (54 + 4 * BMP_NUMCOLORS)
384 #define BMP_DATASIZE (BMP_LINESIZE * LCD_HEIGHT)
385 #define BMP_TOTALSIZE (BMP_HEADERSIZE + BMP_DATASIZE)
387 #define LE16_CONST(x) (x)&0xff, ((x)>>8)&0xff
388 #define LE32_CONST(x) (x)&0xff, ((x)>>8)&0xff, ((x)>>16)&0xff, ((x)>>24)&0xff
390 static const unsigned char bmpheader[] =
392 0x42, 0x4d, /* 'BM' */
393 LE32_CONST(BMP_TOTALSIZE), /* Total file size */
394 0x00, 0x00, 0x00, 0x00, /* Reserved */
395 LE32_CONST(BMP_HEADERSIZE), /* Offset to start of pixel data */
397 0x28, 0x00, 0x00, 0x00, /* Size of (2nd) header */
398 LE32_CONST(LCD_WIDTH), /* Width in pixels */
399 LE32_CONST(LCD_HEIGHT), /* Height in pixels */
400 0x01, 0x00, /* Number of planes (always 1) */
401 LE16_CONST(BMP_BPP), /* Bits per pixel 1/4/8/16/24 */
402 LE32_CONST(BMP_COMPRESSION),/* Compression mode */
403 LE32_CONST(BMP_DATASIZE), /* Size of bitmap data */
404 0xc4, 0x0e, 0x00, 0x00, /* Horizontal resolution (pixels/meter) */
405 0xc4, 0x0e, 0x00, 0x00, /* Vertical resolution (pixels/meter) */
406 LE32_CONST(BMP_NUMCOLORS), /* Number of used colours */
407 LE32_CONST(BMP_NUMCOLORS), /* Number of important colours */
409 #if LCD_DEPTH == 1
410 #ifdef MROBE_100
411 2, 2, 94, 0x00, /* Colour #0 */
412 3, 6, 241, 0x00 /* Colour #1 */
413 #else
414 0x90, 0xee, 0x90, 0x00, /* Colour #0 */
415 0x00, 0x00, 0x00, 0x00 /* Colour #1 */
416 #endif
417 #elif LCD_DEPTH == 2
418 0xe6, 0xd8, 0xad, 0x00, /* Colour #0 */
419 0x99, 0x90, 0x73, 0x00, /* Colour #1 */
420 0x4c, 0x48, 0x39, 0x00, /* Colour #2 */
421 0x00, 0x00, 0x00, 0x00 /* Colour #3 */
422 #elif LCD_DEPTH == 16
423 0x00, 0xf8, 0x00, 0x00, /* red bitfield mask */
424 0xe0, 0x07, 0x00, 0x00, /* green bitfield mask */
425 0x1f, 0x00, 0x00, 0x00 /* blue bitfield mask */
426 #endif
429 static void (*screen_dump_hook)(int fh) = NULL;
431 void screen_dump(void)
433 int fh;
434 char filename[MAX_PATH];
435 int bx, by;
436 #if LCD_DEPTH == 1
437 static unsigned char line_block[8][BMP_LINESIZE];
438 #elif LCD_DEPTH == 2
439 #if LCD_PIXELFORMAT == HORIZONTAL_PACKING
440 static unsigned char line_block[BMP_LINESIZE];
441 #elif LCD_PIXELFORMAT == VERTICAL_PACKING
442 static unsigned char line_block[4][BMP_LINESIZE];
443 #elif LCD_PIXELFORMAT == VERTICAL_INTERLEAVED
444 static unsigned char line_block[8][BMP_LINESIZE];
445 #endif
446 #elif LCD_DEPTH == 16
447 static unsigned short line_block[BMP_LINESIZE/2];
448 #endif
450 #if CONFIG_RTC
451 create_datetime_filename(filename, "", "dump ", ".bmp", false);
452 #else
453 create_numbered_filename(filename, "", "dump_", ".bmp", 4
454 IF_CNFN_NUM_(, NULL));
455 #endif
457 fh = creat(filename);
458 if (fh < 0)
459 return;
461 if (screen_dump_hook)
463 screen_dump_hook(fh);
465 else
467 write(fh, bmpheader, sizeof(bmpheader));
469 /* BMP image goes bottom up */
470 #if LCD_DEPTH == 1
471 for (by = LCD_FBHEIGHT - 1; by >= 0; by--)
473 unsigned char *src = &lcd_framebuffer[by][0];
474 unsigned char *dst = &line_block[0][0];
476 memset(line_block, 0, sizeof(line_block));
477 for (bx = LCD_WIDTH/8; bx > 0; bx--)
479 unsigned dst_mask = 0x80;
480 int ix;
482 for (ix = 8; ix > 0; ix--)
484 unsigned char *dst_blk = dst;
485 unsigned src_byte = *src++;
486 int iy;
488 for (iy = 8; iy > 0; iy--)
490 if (src_byte & 0x80)
491 *dst_blk |= dst_mask;
492 src_byte <<= 1;
493 dst_blk += BMP_LINESIZE;
495 dst_mask >>= 1;
497 dst++;
500 write(fh, line_block, sizeof(line_block));
502 #elif LCD_DEPTH == 2
503 #if LCD_PIXELFORMAT == HORIZONTAL_PACKING
504 for (by = LCD_FBHEIGHT - 1; by >= 0; by--)
506 unsigned char *src = &lcd_framebuffer[by][0];
507 unsigned char *dst = line_block;
509 memset(line_block, 0, sizeof(line_block));
510 for (bx = LCD_FBWIDTH; bx > 0; bx--)
512 unsigned src_byte = *src++;
514 *dst++ = ((src_byte >> 2) & 0x30) | ((src_byte >> 4) & 0x03);
515 *dst++ = ((src_byte << 2) & 0x30) | (src_byte & 0x03);
518 write(fh, line_block, sizeof(line_block));
520 #elif LCD_PIXELFORMAT == VERTICAL_PACKING
521 for (by = LCD_FBHEIGHT - 1; by >= 0; by--)
523 unsigned char *src = &lcd_framebuffer[by][0];
524 unsigned char *dst = &line_block[3][0];
526 memset(line_block, 0, sizeof(line_block));
527 for (bx = LCD_WIDTH/2; bx > 0; bx--)
529 unsigned char *dst_blk = dst++;
530 unsigned src_byte0 = *src++ << 4;
531 unsigned src_byte1 = *src++;
532 int iy;
534 for (iy = 4; iy > 0; iy--)
536 *dst_blk = (src_byte0 & 0x30) | (src_byte1 & 0x03);
537 src_byte0 >>= 2;
538 src_byte1 >>= 2;
539 dst_blk -= BMP_LINESIZE;
543 write(fh, line_block, sizeof(line_block));
545 #elif LCD_PIXELFORMAT == VERTICAL_INTERLEAVED
546 for (by = LCD_FBHEIGHT - 1; by >= 0; by--)
548 const fb_data *src = &lcd_framebuffer[by][0];
549 unsigned char *dst = &line_block[7][0];
551 memset(line_block, 0, sizeof(line_block));
552 for (bx = LCD_WIDTH/2; bx > 0; bx--)
554 unsigned char *dst_blk = dst++;
555 unsigned src_data0 = *src++ << 4;
556 unsigned src_data1 = *src++;
557 int iy;
559 for (iy = 8; iy > 0; iy--)
561 *dst_blk = (src_data0 & 0x10) | (src_data1 & 0x01)
562 | ((src_data0 & 0x1000) | (src_data1 & 0x0100)) >> 7;
563 src_data0 >>= 1;
564 src_data1 >>= 1;
565 dst_blk -= BMP_LINESIZE;
569 write(fh, line_block, sizeof(line_block));
571 #endif
572 #elif LCD_DEPTH == 16
573 for (by = LCD_HEIGHT - 1; by >= 0; by--)
575 unsigned short *src = &lcd_framebuffer[by][0];
576 unsigned short *dst = line_block;
578 memset(line_block, 0, sizeof(line_block));
579 for (bx = LCD_WIDTH; bx > 0; bx--)
581 #if (LCD_PIXELFORMAT == RGB565SWAPPED)
582 /* iPod LCD data is big endian although the CPU is not */
583 *dst++ = htobe16(*src++);
584 #else
585 *dst++ = htole16(*src++);
586 #endif
589 write(fh, line_block, sizeof(line_block));
591 #endif /* LCD_DEPTH */
594 close(fh);
597 void screen_dump_set_hook(void (*hook)(int fh))
599 screen_dump_hook = hook;
602 #endif /* HAVE_LCD_BITMAP */
604 /* parse a line from a configuration file. the line format is:
606 name: value
608 Any whitespace before setting name or value (after ':') is ignored.
609 A # as first non-whitespace character discards the whole line.
610 Function sets pointers to null-terminated setting name and value.
611 Returns false if no valid config entry was found.
614 bool settings_parseline(char* line, char** name, char** value)
616 char* ptr;
618 while ( isspace(*line) )
619 line++;
621 if ( *line == '#' )
622 return false;
624 ptr = strchr(line, ':');
625 if ( !ptr )
626 return false;
628 *name = line;
629 *ptr = 0;
630 ptr++;
631 while (isspace(*ptr))
632 ptr++;
633 *value = ptr;
634 return true;
637 static void system_flush(void)
639 tree_flush();
640 call_ata_idle_notifys(true); /*doesnt work on usb and shutdown from ata thread */
643 static void system_restore(void)
645 tree_restore();
648 static bool clean_shutdown(void (*callback)(void *), void *parameter)
650 #ifdef SIMULATOR
651 (void)callback;
652 (void)parameter;
653 bookmark_autobookmark();
654 call_ata_idle_notifys(true);
655 exit(0);
656 #else
657 long msg_id = -1;
658 int i;
660 scrobbler_poweroff();
662 #if CONFIG_CHARGING && !defined(HAVE_POWEROFF_WHILE_CHARGING)
663 if(!charger_inserted())
664 #endif
666 bool batt_safe = battery_level_safe();
667 int audio_stat = audio_status();
669 FOR_NB_SCREENS(i)
670 screens[i].clear_display();
672 if (batt_safe)
674 #ifdef HAVE_TAGCACHE
675 if (!tagcache_prepare_shutdown())
677 cancel_shutdown();
678 gui_syncsplash(HZ, ID2P(LANG_TAGCACHE_BUSY));
679 return false;
681 #endif
682 if (battery_level() > 10)
683 gui_syncsplash(0, str(LANG_SHUTTINGDOWN));
684 else
686 msg_id = LANG_WARNING_BATTERY_LOW;
687 gui_syncsplash(0, "%s %s",
688 str(LANG_WARNING_BATTERY_LOW),
689 str(LANG_SHUTTINGDOWN));
692 else
694 msg_id = LANG_WARNING_BATTERY_EMPTY;
695 gui_syncsplash(0, "%s %s",
696 str(LANG_WARNING_BATTERY_EMPTY),
697 str(LANG_SHUTTINGDOWN));
700 if (global_settings.fade_on_stop
701 && (audio_stat & AUDIO_STATUS_PLAY))
703 fade(false, false);
706 if (batt_safe) /* do not save on critical battery */
708 #if defined(HAVE_RECORDING) && CONFIG_CODEC == SWCODEC
709 if (audio_stat & AUDIO_STATUS_RECORD)
711 rec_command(RECORDING_CMD_STOP);
712 /* wait for stop to complete */
713 while (audio_status() & AUDIO_STATUS_RECORD)
714 sleep(1);
716 #endif
717 bookmark_autobookmark();
719 /* audio_stop_recording == audio_stop for HWCODEC */
720 audio_stop();
722 if (callback != NULL)
723 callback(parameter);
725 #if CONFIG_CODEC != SWCODEC
726 /* wait for audio_stop or audio_stop_recording to complete */
727 while (audio_status())
728 sleep(1);
729 #endif
731 #if defined(HAVE_RECORDING) && CONFIG_CODEC == SWCODEC
732 audio_close_recording();
733 #endif
735 if(global_settings.talk_menu)
737 bool enqueue = false;
738 if(msg_id != -1)
740 talk_id(msg_id, enqueue);
741 enqueue = true;
743 talk_id(LANG_SHUTTINGDOWN, enqueue);
744 #if CONFIG_CODEC == SWCODEC
745 voice_wait();
746 #endif
749 system_flush();
750 #ifdef HAVE_EEPROM_SETTINGS
751 if (firmware_settings.initialized)
753 firmware_settings.disk_clean = true;
754 firmware_settings.bl_version = 0;
755 eeprom_settings_store();
757 #endif
759 #ifdef HAVE_DIRCACHE
760 else
761 dircache_disable();
762 #endif
764 shutdown_hw();
766 #endif
767 return false;
770 bool list_stop_handler(void)
772 bool ret = false;
774 /* Stop the music if it is playing */
775 if(audio_status())
777 if (!global_settings.party_mode)
779 if (global_settings.fade_on_stop)
780 fade(false, false);
781 bookmark_autobookmark();
782 audio_stop();
783 ret = true; /* bookmarking can make a refresh necessary */
786 #if CONFIG_CHARGING
787 #if (CONFIG_KEYPAD == RECORDER_PAD) && !defined(HAVE_SW_POWEROFF)
788 else
790 if (charger_inserted())
791 charging_splash();
792 else
793 shutdown_screen(); /* won't return if shutdown actually happens */
795 ret = true; /* screen is dirty, caller needs to refresh */
797 #endif
798 #ifndef HAVE_POWEROFF_WHILE_CHARGING
800 static long last_off = 0;
802 if (TIME_BEFORE(current_tick, last_off + HZ/2))
804 if (charger_inserted())
806 charging_splash();
807 ret = true; /* screen is dirty, caller needs to refresh */
810 last_off = current_tick;
812 #endif
813 #endif /* CONFIG_CHARGING */
814 return ret;
817 #if CONFIG_CHARGING
818 static bool waiting_to_resume_play = false;
819 static long play_resume_tick;
821 static void car_adapter_mode_processing(bool inserted)
823 if (global_settings.car_adapter_mode)
825 if(inserted)
828 * Just got plugged in, delay & resume if we were playing
830 if (audio_status() & AUDIO_STATUS_PAUSE)
832 /* delay resume a bit while the engine is cranking */
833 play_resume_tick = current_tick + HZ*5;
834 waiting_to_resume_play = true;
837 else
840 * Just got unplugged, pause if playing
842 if ((audio_status() & AUDIO_STATUS_PLAY) &&
843 !(audio_status() & AUDIO_STATUS_PAUSE))
845 if (global_settings.fade_on_stop)
846 fade(false, false);
847 else
848 audio_pause();
850 waiting_to_resume_play = false;
855 static void car_adapter_tick(void)
857 if (waiting_to_resume_play)
859 if (TIME_AFTER(current_tick, play_resume_tick))
861 if (audio_status() & AUDIO_STATUS_PAUSE)
863 queue_broadcast(SYS_CAR_ADAPTER_RESUME, 0);
865 waiting_to_resume_play = false;
870 void car_adapter_mode_init(void)
872 tick_add_task(car_adapter_tick);
874 #endif
876 #ifdef HAVE_HEADPHONE_DETECTION
877 static void unplug_change(bool inserted)
879 static bool headphone_caused_pause = false;
881 if (global_settings.unplug_mode)
883 int audio_stat = audio_status();
884 if (inserted)
886 if ((audio_stat & AUDIO_STATUS_PLAY) &&
887 headphone_caused_pause &&
888 global_settings.unplug_mode > 1 )
889 audio_resume();
890 backlight_on();
891 headphone_caused_pause = false;
892 } else {
893 if ((audio_stat & AUDIO_STATUS_PLAY) &&
894 !(audio_stat & AUDIO_STATUS_PAUSE))
896 headphone_caused_pause = true;
897 audio_pause();
899 if (global_settings.unplug_rw)
901 if (audio_current_track()->elapsed >
902 (unsigned long)(global_settings.unplug_rw*1000))
903 audio_ff_rewind(audio_current_track()->elapsed -
904 (global_settings.unplug_rw*1000));
905 else
906 audio_ff_rewind(0);
912 #endif
914 long default_event_handler_ex(long event, void (*callback)(void *), void *parameter)
916 switch(event)
918 case SYS_BATTERY_UPDATE:
919 if(global_settings.talk_battery_level)
921 talk_ids(true, VOICE_PAUSE, VOICE_PAUSE,
922 LANG_BATTERY_TIME,
923 TALK_ID(battery_level(), UNIT_PERCENT),
924 VOICE_PAUSE);
925 talk_force_enqueue_next();
927 break;
928 case SYS_USB_CONNECTED:
929 if (callback != NULL)
930 callback(parameter);
931 #ifdef HAVE_MMC
932 if (!mmc_touched() ||
933 (mmc_remove_request() == SYS_HOTSWAP_EXTRACTED))
934 #endif
936 scrobbler_flush_cache();
937 system_flush();
938 #ifdef BOOTFILE
939 #if !defined(USB_NONE) && !defined(USB_IPODSTYLE)
940 check_bootfile(false); /* gets initial size */
941 #endif
942 #endif
943 usb_screen();
944 #ifdef BOOTFILE
945 #if !defined(USB_NONE) && !defined(USB_IPODSTYLE)
946 check_bootfile(true);
947 #endif
948 #endif
949 system_restore();
951 return SYS_USB_CONNECTED;
952 case SYS_POWEROFF:
953 if (!clean_shutdown(callback, parameter))
954 return SYS_POWEROFF;
955 break;
956 #if CONFIG_CHARGING
957 case SYS_CHARGER_CONNECTED:
958 car_adapter_mode_processing(true);
959 return SYS_CHARGER_CONNECTED;
961 case SYS_CHARGER_DISCONNECTED:
962 car_adapter_mode_processing(false);
963 return SYS_CHARGER_DISCONNECTED;
965 case SYS_CAR_ADAPTER_RESUME:
966 audio_resume();
967 return SYS_CAR_ADAPTER_RESUME;
968 #endif
969 #ifdef HAVE_HEADPHONE_DETECTION
970 case SYS_PHONE_PLUGGED:
971 unplug_change(true);
972 return SYS_PHONE_PLUGGED;
974 case SYS_PHONE_UNPLUGGED:
975 unplug_change(false);
976 return SYS_PHONE_UNPLUGGED;
977 #endif
979 return 0;
982 long default_event_handler(long event)
984 return default_event_handler_ex(event, NULL, NULL);
987 int show_logo( void )
989 #ifdef HAVE_LCD_BITMAP
990 char version[32];
991 int font_h, font_w;
993 snprintf(version, sizeof(version), "Ver. %s", appsversion);
995 lcd_clear_display();
996 lcd_bitmap(rockboxlogo, 0, 10, BMPWIDTH_rockboxlogo, BMPHEIGHT_rockboxlogo);
997 lcd_setfont(FONT_SYSFIXED);
998 lcd_getstringsize((unsigned char *)"A", &font_w, &font_h);
999 lcd_putsxy((LCD_WIDTH/2) - ((strlen(version)*font_w)/2),
1000 LCD_HEIGHT-font_h, (unsigned char *)version);
1001 lcd_setfont(FONT_UI);
1003 #else
1004 char *rockbox = " ROCKbox!";
1006 lcd_clear_display();
1007 lcd_double_height(true);
1008 lcd_puts(0, 0, rockbox);
1009 lcd_puts_scroll(0, 1, appsversion);
1010 #endif
1011 lcd_update();
1013 #ifdef HAVE_REMOTE_LCD
1014 lcd_remote_clear_display();
1015 lcd_remote_bitmap(remote_rockboxlogo, 0, 10, BMPWIDTH_remote_rockboxlogo,
1016 BMPHEIGHT_remote_rockboxlogo);
1017 lcd_remote_setfont(FONT_SYSFIXED);
1018 lcd_remote_getstringsize((unsigned char *)"A", &font_w, &font_h);
1019 lcd_remote_putsxy((LCD_REMOTE_WIDTH/2) - ((strlen(version)*font_w)/2),
1020 LCD_REMOTE_HEIGHT-font_h, (unsigned char *)version);
1021 lcd_remote_setfont(FONT_UI);
1022 lcd_remote_update();
1023 #endif
1025 return 0;
1028 #if CONFIG_CODEC == SWCODEC
1029 int get_replaygain_mode(bool have_track_gain, bool have_album_gain)
1031 int type;
1033 bool track = ((global_settings.replaygain_type == REPLAYGAIN_TRACK)
1034 || ((global_settings.replaygain_type == REPLAYGAIN_SHUFFLE)
1035 && global_settings.playlist_shuffle));
1037 type = (!track && have_album_gain) ? REPLAYGAIN_ALBUM
1038 : have_track_gain ? REPLAYGAIN_TRACK : -1;
1040 return type;
1042 #endif
1044 #ifdef BOOTFILE
1045 #if !defined(USB_NONE) && !defined(USB_IPODSTYLE)
1047 memorize/compare details about the BOOTFILE
1048 we don't use dircache because it may not be up to date after
1049 USB disconnect (scanning in the background)
1051 void check_bootfile(bool do_rolo)
1053 static unsigned short wrtdate = 0;
1054 static unsigned short wrttime = 0;
1055 DIR* dir = NULL;
1056 struct dirent* entry = NULL;
1058 /* 1. open BOOTDIR and find the BOOTFILE dir entry */
1059 dir = opendir(BOOTDIR);
1061 if(!dir) return; /* do we want an error splash? */
1063 /* loop all files in BOOTDIR */
1064 while(0 != (entry = readdir(dir)))
1066 if(!strcasecmp(entry->d_name, BOOTFILE))
1068 /* found the bootfile */
1069 if(wrtdate && do_rolo)
1071 if((entry->wrtdate != wrtdate) ||
1072 (entry->wrttime != wrttime))
1074 static const char *lines[] = { ID2P(LANG_BOOT_CHANGED),
1075 ID2P(LANG_REBOOT_NOW) };
1076 static const struct text_message message={ lines, 2 };
1077 button_clear_queue(); /* Empty the keyboard buffer */
1078 if(gui_syncyesno_run(&message, NULL, NULL) == YESNO_YES)
1079 rolo_load(BOOTDIR "/" BOOTFILE);
1082 wrtdate = entry->wrtdate;
1083 wrttime = entry->wrttime;
1086 closedir(dir);
1088 #endif
1089 #endif
1091 /* check range, set volume and save settings */
1092 void setvol(void)
1094 const int min_vol = sound_min(SOUND_VOLUME);
1095 const int max_vol = sound_max(SOUND_VOLUME);
1096 if (global_settings.volume < min_vol)
1097 global_settings.volume = min_vol;
1098 if (global_settings.volume > max_vol)
1099 global_settings.volume = max_vol;
1100 sound_set_volume(global_settings.volume);
1101 settings_save();
1104 char* strrsplt(char* str, int c)
1106 char* s = strrchr(str, c);
1108 if (s != NULL)
1110 *s++ = '\0';
1112 else
1114 s = str;
1117 return s;
1120 /* Test file existence, using dircache of possible */
1121 bool file_exists(const char *file)
1123 int fd;
1125 if (!file || strlen(file) <= 0)
1126 return false;
1128 #ifdef HAVE_DIRCACHE
1129 if (dircache_is_enabled())
1130 return (dircache_get_entry_ptr(file) != NULL);
1131 #endif
1133 fd = open(file, O_RDONLY);
1134 if (fd < 0)
1135 return false;
1136 close(fd);
1137 return true;
1140 bool dir_exists(const char *path)
1142 DIR* d = opendir(path);
1143 if (!d)
1144 return false;
1145 closedir(d);
1146 return true;
1150 * removes the extension of filename (if it doesn't start with a .)
1151 * puts the result in buffer
1153 char *strip_extension(char* buffer, int buffer_size, const char *filename)
1155 char *dot = strrchr(filename, '.');
1156 int len;
1158 if (buffer_size <= 0)
1160 return NULL;
1163 buffer_size--; /* Make room for end nil */
1165 if (dot != 0 && filename[0] != '.')
1167 len = dot - filename;
1168 len = MIN(len, buffer_size);
1169 strncpy(buffer, filename, len);
1171 else
1173 len = buffer_size;
1174 strncpy(buffer, filename, buffer_size);
1177 buffer[len] = 0;
1179 return buffer;
1181 #endif /* !defined(__PCTOOL__) */
1183 /** Open a UTF-8 file and set file descriptor to first byte after BOM.
1184 * If no BOM is present this behaves like open().
1185 * If the file is opened for writing and O_TRUNC is set, write a BOM to
1186 * the opened file and leave the file pointer set after the BOM.
1188 int open_utf8(const char* pathname, int flags)
1190 int fd;
1191 unsigned char bom[BOM_SIZE];
1193 fd = open(pathname, flags);
1194 if(fd < 0)
1195 return fd;
1197 if(flags & (O_TRUNC | O_WRONLY))
1199 write(fd, BOM, BOM_SIZE);
1201 else
1203 read(fd, bom, BOM_SIZE);
1204 /* check for BOM */
1205 if(memcmp(bom, BOM, BOM_SIZE))
1206 lseek(fd, 0, SEEK_SET);
1208 return fd;
1212 #ifdef HAVE_LCD_COLOR
1214 * Helper function to convert a string of 6 hex digits to a native colour
1217 static int hex2dec(int c)
1219 return (((c) >= '0' && ((c) <= '9')) ? (c) - '0' :
1220 (toupper(c)) - 'A' + 10);
1223 int hex_to_rgb(const char* hex, int* color)
1225 int red, green, blue;
1226 int i = 0;
1228 while ((i < 6) && (isxdigit(hex[i])))
1229 i++;
1231 if (i < 6)
1232 return -1;
1234 red = (hex2dec(hex[0]) << 4) | hex2dec(hex[1]);
1235 green = (hex2dec(hex[2]) << 4) | hex2dec(hex[3]);
1236 blue = (hex2dec(hex[4]) << 4) | hex2dec(hex[5]);
1238 *color = LCD_RGBPACK(red,green,blue);
1240 return 0;
1242 #endif /* HAVE_LCD_COLOR */
1244 #ifdef HAVE_LCD_BITMAP
1245 /* A simplified scanf - used (at time of writing) by wps parsing functions.
1247 fmt - char array specifying the format of each list option. Valid values
1248 are: d - int
1249 s - string (sets pointer to string, without copying)
1250 c - hex colour (RGB888 - e.g. ff00ff)
1251 g - greyscale "colour" (0-3)
1252 set_vals - if not NULL 1 is set in the bitplace if the item was read OK
1253 0 if not read.
1254 first item is LSB, (max 32 items! )
1255 Stops parseing if an item is invalid unless the item == '-'
1256 sep - list separator (e.g. ',' or '|')
1257 str - string to parse, must be terminated by 0 or sep
1258 ... - pointers to store the parsed values
1260 return value - pointer to char after parsed data, 0 if there was an error.
1264 /* '0'-'3' are ASCII 0x30 to 0x33 */
1265 #define is0123(x) (((x) & 0xfc) == 0x30)
1267 const char* parse_list(const char *fmt, uint32_t *set_vals,
1268 const char sep, const char* str, ...)
1270 va_list ap;
1271 const char* p = str, *f = fmt;
1272 const char** s;
1273 int* d;
1274 bool set;
1275 int i=0;
1277 va_start(ap, str);
1278 if (set_vals)
1279 *set_vals = 0;
1280 while (*fmt)
1282 /* Check for separator, if we're not at the start */
1283 if (f != fmt)
1285 if (*p != sep)
1286 goto err;
1287 p++;
1289 set = false;
1290 switch (*fmt++)
1292 case 's': /* string - return a pointer to it (not a copy) */
1293 s = va_arg(ap, const char **);
1295 *s = p;
1296 while (*p && *p != sep)
1297 p++;
1298 set = (s[0][0]!='-') && (s[0][1]!=sep) ;
1299 break;
1301 case 'd': /* int */
1302 d = va_arg(ap, int*);
1303 if (!isdigit(*p))
1305 if (!set_vals || *p != '-')
1306 goto err;
1307 while (*p && *p != sep)
1308 p++;
1310 else
1312 *d = *p++ - '0';
1313 while (isdigit(*p))
1314 *d = (*d * 10) + (*p++ - '0');
1315 set = true;
1318 break;
1320 #ifdef HAVE_LCD_COLOR
1321 case 'c': /* colour (rrggbb - e.g. f3c1a8) */
1322 d = va_arg(ap, int*);
1324 if (hex_to_rgb(p, d) < 0)
1326 if (!set_vals || *p != '-')
1327 goto err;
1328 while (*p && *p != sep)
1329 p++;
1331 else
1333 p += 6;
1334 set = true;
1337 break;
1338 #endif
1340 #if LCD_DEPTH == 2 || (defined(HAVE_REMOTE_LCD) && LCD_REMOTE_DEPTH == 2)
1341 case 'g': /* greyscale colour (0-3) */
1342 d = va_arg(ap, int*);
1344 if (is0123(*p))
1346 *d = *p++ - '0';
1347 set = true;
1349 else if (!set_vals || *p != '-')
1350 goto err;
1351 else
1353 while (*p && *p != sep)
1354 p++;
1357 break;
1358 #endif
1360 default: /* Unknown format type */
1361 goto err;
1362 break;
1364 if (set_vals && set)
1365 *set_vals |= (1<<i);
1366 i++;
1369 va_end(ap);
1370 return p;
1372 err:
1373 va_end(ap);
1374 return 0;
1376 #endif