Make parse_list() a bit stricter by only allowing items to be skipped if they are...
[kugel-rb.git] / apps / misc.c
blob4d7ddd57e6df14f877f0ae1acbf97d4468a9ebce
1 /***************************************************************************
2 * __________ __ ___.
3 * Open \______ \ ____ ____ | | _\_ |__ _______ ___
4 * Source | _// _ \_/ ___\| |/ /| __ \ / _ \ \/ /
5 * Jukebox | | ( <_> ) \___| < | \_\ ( <_> > < <
6 * Firmware |____|_ /\____/ \___ >__|_ \|___ /\____/__/\_ \
7 * \/ \/ \/ \/ \/
8 * $Id$
10 * Copyright (C) 2002 by Daniel Stenberg
12 * All files in this archive are subject to the GNU General Public License.
13 * See the file COPYING in the source tree root for full license agreement.
15 * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
16 * KIND, either express or implied.
18 ****************************************************************************/
19 #include <stdlib.h>
20 #include <ctype.h>
21 #include "config.h"
22 #include "lcd.h"
23 #include "file.h"
24 #ifdef __PCTOOL__
25 #include <stdarg.h>
26 #else
27 #include "sprintf.h"
28 #include "lang.h"
29 #include "string.h"
30 #include "dir.h"
31 #include "lcd-remote.h"
32 #include "errno.h"
33 #include "system.h"
34 #include "timefuncs.h"
35 #include "screens.h"
36 #include "talk.h"
37 #include "mpeg.h"
38 #include "audio.h"
39 #include "mp3_playback.h"
40 #include "settings.h"
41 #include "ata.h"
42 #include "ata_idle_notify.h"
43 #include "kernel.h"
44 #include "power.h"
45 #include "powermgmt.h"
46 #include "backlight.h"
47 #include "version.h"
48 #include "font.h"
49 #include "splash.h"
50 #include "tagcache.h"
51 #include "scrobbler.h"
52 #include "sound.h"
53 #include "playlist.h"
54 #include "yesno.h"
56 #ifdef HAVE_MMC
57 #include "ata_mmc.h"
58 #endif
59 #include "tree.h"
60 #include "eeprom_settings.h"
61 #if defined(HAVE_RECORDING) && !defined(__PCTOOL__)
62 #include "recording.h"
63 #endif
64 #if defined(HAVE_LCD_BITMAP) && !defined(__PCTOOL__)
65 #include "bmp.h"
66 #include "icons.h"
67 #endif /* End HAVE_LCD_BITMAP */
68 #include "gui/gwps-common.h"
69 #include "bookmark.h"
71 #include "misc.h"
72 #include "playback.h"
74 #ifdef BOOTFILE
75 #if !defined(USB_NONE) && !defined(USB_IPODSTYLE)
76 #include "rolo.h"
77 #include "yesno.h"
78 #endif
79 #endif
81 /* Format a large-range value for output, using the appropriate unit so that
82 * the displayed value is in the range 1 <= display < 1000 (1024 for "binary"
83 * units) if possible, and 3 significant digits are shown. If a buffer is
84 * given, the result is snprintf()'d into that buffer, otherwise the result is
85 * voiced.*/
86 char *output_dyn_value(char *buf, int buf_size, int value,
87 const unsigned char **units, bool bin_scale)
89 int scale = bin_scale ? 1024 : 1000;
90 int fraction = 0;
91 int unit_no = 0;
92 char tbuf[5];
94 while (value >= scale)
96 fraction = value % scale;
97 value /= scale;
98 unit_no++;
100 if (bin_scale)
101 fraction = fraction * 1000 / 1024;
103 if (value >= 100 || !unit_no)
104 tbuf[0] = '\0';
105 else if (value >= 10)
106 snprintf(tbuf, sizeof(tbuf), "%01d", fraction / 100);
107 else
108 snprintf(tbuf, sizeof(tbuf), "%02d", fraction / 10);
110 if (buf)
112 if (strlen(tbuf))
113 snprintf(buf, buf_size, "%d%s%s%s", value, str(LANG_POINT),
114 tbuf, P2STR(units[unit_no]));
115 else
116 snprintf(buf, buf_size, "%d%s", value, P2STR(units[unit_no]));
118 else
120 talk_fractional(tbuf, value, P2ID(units[unit_no]));
122 return buf;
125 /* Create a filename with a number part in a way that the number is 1
126 * higher than the highest numbered file matching the same pattern.
127 * It is allowed that buffer and path point to the same memory location,
128 * saving a strcpy(). Path must always be given without trailing slash.
129 * "num" can point to an int specifying the number to use or NULL or a value
130 * less than zero to number automatically. The final number used will also
131 * be returned in *num. If *num is >= 0 then *num will be incremented by
132 * one. */
133 char *create_numbered_filename(char *buffer, const char *path,
134 const char *prefix, const char *suffix,
135 int numberlen IF_CNFN_NUM_(, int *num))
137 DIR *dir;
138 struct dirent *entry;
139 int max_num;
140 int pathlen;
141 int prefixlen = strlen(prefix);
142 char fmtstring[12];
144 if (buffer != path)
145 strncpy(buffer, path, MAX_PATH);
147 pathlen = strlen(buffer);
149 #ifdef IF_CNFN_NUM
150 if (num && *num >= 0)
152 /* number specified */
153 max_num = *num;
155 else
156 #endif
158 /* automatic numbering */
159 max_num = 0;
161 dir = opendir(pathlen ? buffer : "/");
162 if (!dir)
163 return NULL;
165 while ((entry = readdir(dir)))
167 int curr_num;
169 if (strncasecmp((char *)entry->d_name, prefix, prefixlen)
170 || strcasecmp((char *)entry->d_name + prefixlen + numberlen, suffix))
171 continue;
173 curr_num = atoi((char *)entry->d_name + prefixlen);
174 if (curr_num > max_num)
175 max_num = curr_num;
178 closedir(dir);
181 max_num++;
183 snprintf(fmtstring, sizeof(fmtstring), "/%%s%%0%dd%%s", numberlen);
184 snprintf(buffer + pathlen, MAX_PATH - pathlen, fmtstring, prefix,
185 max_num, suffix);
187 #ifdef IF_CNFN_NUM
188 if (num)
189 *num = max_num;
190 #endif
192 return buffer;
195 /* Format time into buf.
197 * buf - buffer to format to.
198 * buf_size - size of buffer.
199 * t - time to format, in milliseconds.
201 void format_time(char* buf, int buf_size, long t)
203 if ( t < 3600000 )
205 snprintf(buf, buf_size, "%d:%02d",
206 (int) (t / 60000), (int) (t % 60000 / 1000));
208 else
210 snprintf(buf, buf_size, "%d:%02d:%02d",
211 (int) (t / 3600000), (int) (t % 3600000 / 60000),
212 (int) (t % 60000 / 1000));
216 #if CONFIG_RTC
217 /* Create a filename with a date+time part.
218 It is allowed that buffer and path point to the same memory location,
219 saving a strcpy(). Path must always be given without trailing slash.
220 unique_time as true makes the function wait until the current time has
221 changed. */
222 char *create_datetime_filename(char *buffer, const char *path,
223 const char *prefix, const char *suffix,
224 bool unique_time)
226 struct tm *tm = get_time();
227 static struct tm last_tm;
228 int pathlen;
230 while (unique_time && !memcmp(get_time(), &last_tm, sizeof (struct tm)))
231 sleep(HZ/10);
233 last_tm = *tm;
235 if (buffer != path)
236 strncpy(buffer, path, MAX_PATH);
238 pathlen = strlen(buffer);
239 snprintf(buffer + pathlen, MAX_PATH - pathlen,
240 "/%s%02d%02d%02d-%02d%02d%02d%s", prefix,
241 tm->tm_year % 100, tm->tm_mon + 1, tm->tm_mday,
242 tm->tm_hour, tm->tm_min, tm->tm_sec, suffix);
244 return buffer;
246 #endif /* CONFIG_RTC */
248 /* Ask the user if they really want to erase the current dynamic playlist
249 * returns true if the playlist should be replaced */
250 bool warn_on_pl_erase(void)
252 if (global_settings.warnon_erase_dynplaylist &&
253 !global_settings.party_mode &&
254 playlist_modified(NULL))
256 static const char *lines[] =
257 {ID2P(LANG_WARN_ERASEDYNPLAYLIST_PROMPT)};
258 static const struct text_message message={lines, 1};
260 return (gui_syncyesno_run(&message, NULL, NULL) == YESNO_YES);
262 else
263 return true;
266 /* Read (up to) a line of text from fd into buffer and return number of bytes
267 * read (which may be larger than the number of bytes stored in buffer). If
268 * an error occurs, -1 is returned (and buffer contains whatever could be
269 * read). A line is terminated by a LF char. Neither LF nor CR chars are
270 * stored in buffer.
272 int read_line(int fd, char* buffer, int buffer_size)
274 int count = 0;
275 int num_read = 0;
277 errno = 0;
279 while (count < buffer_size)
281 unsigned char c;
283 if (1 != read(fd, &c, 1))
284 break;
286 num_read++;
288 if ( c == '\n' )
289 break;
291 if ( c == '\r' )
292 continue;
294 buffer[count++] = c;
297 buffer[MIN(count, buffer_size - 1)] = 0;
299 return errno ? -1 : num_read;
302 /* Performance optimized version of the previous function. */
303 int fast_readline(int fd, char *buf, int buf_size, void *parameters,
304 int (*callback)(int n, const char *buf, void *parameters))
306 char *p, *next;
307 int rc, pos = 0;
308 int count = 0;
310 while ( 1 )
312 next = NULL;
314 rc = read(fd, &buf[pos], buf_size - pos - 1);
315 if (rc >= 0)
316 buf[pos+rc] = '\0';
318 if ( (p = strchr(buf, '\r')) != NULL)
320 *p = '\0';
321 next = ++p;
323 else
324 p = buf;
326 if ( (p = strchr(p, '\n')) != NULL)
328 *p = '\0';
329 next = ++p;
332 rc = callback(count, buf, parameters);
333 if (rc < 0)
334 return rc;
336 count++;
337 if (next)
339 pos = buf_size - ((long)next - (long)buf) - 1;
340 memmove(buf, next, pos);
342 else
343 break ;
346 return 0;
349 #ifdef HAVE_LCD_BITMAP
351 #if LCD_DEPTH == 16
352 #define BMP_COMPRESSION 3 /* BI_BITFIELDS */
353 #define BMP_NUMCOLORS 3
354 #else
355 #define BMP_COMPRESSION 0 /* BI_RGB */
356 #if LCD_DEPTH <= 8
357 #define BMP_NUMCOLORS (1 << LCD_DEPTH)
358 #else
359 #define BMP_NUMCOLORS 0
360 #endif
361 #endif
363 #if LCD_DEPTH == 1
364 #define BMP_BPP 1
365 #define BMP_LINESIZE ((LCD_WIDTH/8 + 3) & ~3)
366 #elif LCD_DEPTH <= 4
367 #define BMP_BPP 4
368 #define BMP_LINESIZE ((LCD_WIDTH/2 + 3) & ~3)
369 #elif LCD_DEPTH <= 8
370 #define BMP_BPP 8
371 #define BMP_LINESIZE ((LCD_WIDTH + 3) & ~3)
372 #elif LCD_DEPTH <= 16
373 #define BMP_BPP 16
374 #define BMP_LINESIZE ((LCD_WIDTH*2 + 3) & ~3)
375 #else
376 #define BMP_BPP 24
377 #define BMP_LINESIZE ((LCD_WIDTH*3 + 3) & ~3)
378 #endif
380 #define BMP_HEADERSIZE (54 + 4 * BMP_NUMCOLORS)
381 #define BMP_DATASIZE (BMP_LINESIZE * LCD_HEIGHT)
382 #define BMP_TOTALSIZE (BMP_HEADERSIZE + BMP_DATASIZE)
384 #define LE16_CONST(x) (x)&0xff, ((x)>>8)&0xff
385 #define LE32_CONST(x) (x)&0xff, ((x)>>8)&0xff, ((x)>>16)&0xff, ((x)>>24)&0xff
387 static const unsigned char bmpheader[] =
389 0x42, 0x4d, /* 'BM' */
390 LE32_CONST(BMP_TOTALSIZE), /* Total file size */
391 0x00, 0x00, 0x00, 0x00, /* Reserved */
392 LE32_CONST(BMP_HEADERSIZE), /* Offset to start of pixel data */
394 0x28, 0x00, 0x00, 0x00, /* Size of (2nd) header */
395 LE32_CONST(LCD_WIDTH), /* Width in pixels */
396 LE32_CONST(LCD_HEIGHT), /* Height in pixels */
397 0x01, 0x00, /* Number of planes (always 1) */
398 LE16_CONST(BMP_BPP), /* Bits per pixel 1/4/8/16/24 */
399 LE32_CONST(BMP_COMPRESSION),/* Compression mode */
400 LE32_CONST(BMP_DATASIZE), /* Size of bitmap data */
401 0xc4, 0x0e, 0x00, 0x00, /* Horizontal resolution (pixels/meter) */
402 0xc4, 0x0e, 0x00, 0x00, /* Vertical resolution (pixels/meter) */
403 LE32_CONST(BMP_NUMCOLORS), /* Number of used colours */
404 LE32_CONST(BMP_NUMCOLORS), /* Number of important colours */
406 #if LCD_DEPTH == 1
407 #ifdef MROBE_100
408 2, 2, 94, 0x00, /* Colour #0 */
409 3, 6, 241, 0x00 /* Colour #1 */
410 #else
411 0x90, 0xee, 0x90, 0x00, /* Colour #0 */
412 0x00, 0x00, 0x00, 0x00 /* Colour #1 */
413 #endif
414 #elif LCD_DEPTH == 2
415 0xe6, 0xd8, 0xad, 0x00, /* Colour #0 */
416 0x99, 0x90, 0x73, 0x00, /* Colour #1 */
417 0x4c, 0x48, 0x39, 0x00, /* Colour #2 */
418 0x00, 0x00, 0x00, 0x00 /* Colour #3 */
419 #elif LCD_DEPTH == 16
420 0x00, 0xf8, 0x00, 0x00, /* red bitfield mask */
421 0xe0, 0x07, 0x00, 0x00, /* green bitfield mask */
422 0x1f, 0x00, 0x00, 0x00 /* blue bitfield mask */
423 #endif
426 static void (*screen_dump_hook)(int fh) = NULL;
428 void screen_dump(void)
430 int fh;
431 char filename[MAX_PATH];
432 int bx, by;
433 #if LCD_DEPTH == 1
434 static unsigned char line_block[8][BMP_LINESIZE];
435 #elif LCD_DEPTH == 2
436 #if LCD_PIXELFORMAT == HORIZONTAL_PACKING
437 static unsigned char line_block[BMP_LINESIZE];
438 #elif LCD_PIXELFORMAT == VERTICAL_PACKING
439 static unsigned char line_block[4][BMP_LINESIZE];
440 #elif LCD_PIXELFORMAT == VERTICAL_INTERLEAVED
441 static unsigned char line_block[8][BMP_LINESIZE];
442 #endif
443 #elif LCD_DEPTH == 16
444 static unsigned short line_block[BMP_LINESIZE/2];
445 #endif
447 #if CONFIG_RTC
448 create_datetime_filename(filename, "", "dump ", ".bmp", false);
449 #else
450 create_numbered_filename(filename, "", "dump_", ".bmp", 4
451 IF_CNFN_NUM_(, NULL));
452 #endif
454 fh = creat(filename);
455 if (fh < 0)
456 return;
458 if (screen_dump_hook)
460 screen_dump_hook(fh);
462 else
464 write(fh, bmpheader, sizeof(bmpheader));
466 /* BMP image goes bottom up */
467 #if LCD_DEPTH == 1
468 for (by = LCD_FBHEIGHT - 1; by >= 0; by--)
470 unsigned char *src = &lcd_framebuffer[by][0];
471 unsigned char *dst = &line_block[0][0];
473 memset(line_block, 0, sizeof(line_block));
474 for (bx = LCD_WIDTH/8; bx > 0; bx--)
476 unsigned dst_mask = 0x80;
477 int ix;
479 for (ix = 8; ix > 0; ix--)
481 unsigned char *dst_blk = dst;
482 unsigned src_byte = *src++;
483 int iy;
485 for (iy = 8; iy > 0; iy--)
487 if (src_byte & 0x80)
488 *dst_blk |= dst_mask;
489 src_byte <<= 1;
490 dst_blk += BMP_LINESIZE;
492 dst_mask >>= 1;
494 dst++;
497 write(fh, line_block, sizeof(line_block));
499 #elif LCD_DEPTH == 2
500 #if LCD_PIXELFORMAT == HORIZONTAL_PACKING
501 for (by = LCD_FBHEIGHT - 1; by >= 0; by--)
503 unsigned char *src = &lcd_framebuffer[by][0];
504 unsigned char *dst = line_block;
506 memset(line_block, 0, sizeof(line_block));
507 for (bx = LCD_FBWIDTH; bx > 0; bx--)
509 unsigned src_byte = *src++;
511 *dst++ = ((src_byte >> 2) & 0x30) | ((src_byte >> 4) & 0x03);
512 *dst++ = ((src_byte << 2) & 0x30) | (src_byte & 0x03);
515 write(fh, line_block, sizeof(line_block));
517 #elif LCD_PIXELFORMAT == VERTICAL_PACKING
518 for (by = LCD_FBHEIGHT - 1; by >= 0; by--)
520 unsigned char *src = &lcd_framebuffer[by][0];
521 unsigned char *dst = &line_block[3][0];
523 memset(line_block, 0, sizeof(line_block));
524 for (bx = LCD_WIDTH/2; bx > 0; bx--)
526 unsigned char *dst_blk = dst++;
527 unsigned src_byte0 = *src++ << 4;
528 unsigned src_byte1 = *src++;
529 int iy;
531 for (iy = 4; iy > 0; iy--)
533 *dst_blk = (src_byte0 & 0x30) | (src_byte1 & 0x03);
534 src_byte0 >>= 2;
535 src_byte1 >>= 2;
536 dst_blk -= BMP_LINESIZE;
540 write(fh, line_block, sizeof(line_block));
542 #elif LCD_PIXELFORMAT == VERTICAL_INTERLEAVED
543 for (by = LCD_FBHEIGHT - 1; by >= 0; by--)
545 const fb_data *src = &lcd_framebuffer[by][0];
546 unsigned char *dst = &line_block[7][0];
548 memset(line_block, 0, sizeof(line_block));
549 for (bx = LCD_WIDTH/2; bx > 0; bx--)
551 unsigned char *dst_blk = dst++;
552 unsigned src_data0 = *src++ << 4;
553 unsigned src_data1 = *src++;
554 int iy;
556 for (iy = 8; iy > 0; iy--)
558 *dst_blk = (src_data0 & 0x10) | (src_data1 & 0x01)
559 | ((src_data0 & 0x1000) | (src_data1 & 0x0100)) >> 7;
560 src_data0 >>= 1;
561 src_data1 >>= 1;
562 dst_blk -= BMP_LINESIZE;
566 write(fh, line_block, sizeof(line_block));
568 #endif
569 #elif LCD_DEPTH == 16
570 for (by = LCD_HEIGHT - 1; by >= 0; by--)
572 unsigned short *src = &lcd_framebuffer[by][0];
573 unsigned short *dst = line_block;
575 memset(line_block, 0, sizeof(line_block));
576 for (bx = LCD_WIDTH; bx > 0; bx--)
578 #if (LCD_PIXELFORMAT == RGB565SWAPPED)
579 /* iPod LCD data is big endian although the CPU is not */
580 *dst++ = htobe16(*src++);
581 #else
582 *dst++ = htole16(*src++);
583 #endif
586 write(fh, line_block, sizeof(line_block));
588 #endif /* LCD_DEPTH */
591 close(fh);
594 void screen_dump_set_hook(void (*hook)(int fh))
596 screen_dump_hook = hook;
599 #endif /* HAVE_LCD_BITMAP */
601 /* parse a line from a configuration file. the line format is:
603 name: value
605 Any whitespace before setting name or value (after ':') is ignored.
606 A # as first non-whitespace character discards the whole line.
607 Function sets pointers to null-terminated setting name and value.
608 Returns false if no valid config entry was found.
611 bool settings_parseline(char* line, char** name, char** value)
613 char* ptr;
615 while ( isspace(*line) )
616 line++;
618 if ( *line == '#' )
619 return false;
621 ptr = strchr(line, ':');
622 if ( !ptr )
623 return false;
625 *name = line;
626 *ptr = 0;
627 ptr++;
628 while (isspace(*ptr))
629 ptr++;
630 *value = ptr;
631 return true;
634 static void system_flush(void)
636 tree_flush();
637 call_ata_idle_notifys(true); /*doesnt work on usb and shutdown from ata thread */
640 static void system_restore(void)
642 tree_restore();
645 static bool clean_shutdown(void (*callback)(void *), void *parameter)
647 #ifdef SIMULATOR
648 (void)callback;
649 (void)parameter;
650 bookmark_autobookmark();
651 call_ata_idle_notifys(true);
652 exit(0);
653 #else
654 long msg_id = -1;
655 int i;
657 scrobbler_poweroff();
659 #if CONFIG_CHARGING && !defined(HAVE_POWEROFF_WHILE_CHARGING)
660 if(!charger_inserted())
661 #endif
663 bool batt_safe = battery_level_safe();
664 int audio_stat = audio_status();
666 FOR_NB_SCREENS(i)
667 screens[i].clear_display();
669 if (batt_safe)
671 #ifdef HAVE_TAGCACHE
672 if (!tagcache_prepare_shutdown())
674 cancel_shutdown();
675 gui_syncsplash(HZ, ID2P(LANG_TAGCACHE_BUSY));
676 return false;
678 #endif
679 if (battery_level() > 10)
680 gui_syncsplash(0, str(LANG_SHUTTINGDOWN));
681 else
683 msg_id = LANG_WARNING_BATTERY_LOW;
684 gui_syncsplash(0, "%s %s",
685 str(LANG_WARNING_BATTERY_LOW),
686 str(LANG_SHUTTINGDOWN));
689 else
691 msg_id = LANG_WARNING_BATTERY_EMPTY;
692 gui_syncsplash(0, "%s %s",
693 str(LANG_WARNING_BATTERY_EMPTY),
694 str(LANG_SHUTTINGDOWN));
697 if (global_settings.fade_on_stop
698 && (audio_stat & AUDIO_STATUS_PLAY))
700 fade(0);
703 if (batt_safe) /* do not save on critical battery */
705 #if defined(HAVE_RECORDING) && CONFIG_CODEC == SWCODEC
706 if (audio_stat & AUDIO_STATUS_RECORD)
708 rec_command(RECORDING_CMD_STOP);
709 /* wait for stop to complete */
710 while (audio_status() & AUDIO_STATUS_RECORD)
711 sleep(1);
713 #endif
714 bookmark_autobookmark();
716 /* audio_stop_recording == audio_stop for HWCODEC */
717 audio_stop();
719 if (callback != NULL)
720 callback(parameter);
722 #if CONFIG_CODEC != SWCODEC
723 /* wait for audio_stop or audio_stop_recording to complete */
724 while (audio_status())
725 sleep(1);
726 #endif
728 #if defined(HAVE_RECORDING) && CONFIG_CODEC == SWCODEC
729 audio_close_recording();
730 #endif
732 if(global_settings.talk_menu)
734 bool enqueue = false;
735 if(msg_id != -1)
737 talk_id(msg_id, enqueue);
738 enqueue = true;
740 talk_id(LANG_SHUTTINGDOWN, enqueue);
741 #if CONFIG_CODEC == SWCODEC
742 voice_wait();
743 #endif
746 system_flush();
747 #ifdef HAVE_EEPROM_SETTINGS
748 if (firmware_settings.initialized)
750 firmware_settings.disk_clean = true;
751 firmware_settings.bl_version = 0;
752 eeprom_settings_store();
754 #endif
756 #ifdef HAVE_DIRCACHE
757 else
758 dircache_disable();
759 #endif
761 shutdown_hw();
763 #endif
764 return false;
767 bool list_stop_handler(void)
769 bool ret = false;
771 /* Stop the music if it is playing */
772 if(audio_status())
774 if (!global_settings.party_mode)
776 if (global_settings.fade_on_stop)
777 fade(0);
778 bookmark_autobookmark();
779 audio_stop();
780 ret = true; /* bookmarking can make a refresh necessary */
783 #if CONFIG_CHARGING
784 #if (CONFIG_KEYPAD == RECORDER_PAD) && !defined(HAVE_SW_POWEROFF)
785 else
787 if (charger_inserted())
788 charging_splash();
789 else
790 shutdown_screen(); /* won't return if shutdown actually happens */
792 ret = true; /* screen is dirty, caller needs to refresh */
794 #endif
795 #ifndef HAVE_POWEROFF_WHILE_CHARGING
797 static long last_off = 0;
799 if (TIME_BEFORE(current_tick, last_off + HZ/2))
801 if (charger_inserted())
803 charging_splash();
804 ret = true; /* screen is dirty, caller needs to refresh */
807 last_off = current_tick;
809 #endif
810 #endif /* CONFIG_CHARGING */
811 return ret;
814 #if CONFIG_CHARGING
815 static bool waiting_to_resume_play = false;
816 static long play_resume_tick;
818 static void car_adapter_mode_processing(bool inserted)
820 if (global_settings.car_adapter_mode)
822 if(inserted)
825 * Just got plugged in, delay & resume if we were playing
827 if (audio_status() & AUDIO_STATUS_PAUSE)
829 /* delay resume a bit while the engine is cranking */
830 play_resume_tick = current_tick + HZ*5;
831 waiting_to_resume_play = true;
834 else
837 * Just got unplugged, pause if playing
839 if ((audio_status() & AUDIO_STATUS_PLAY) &&
840 !(audio_status() & AUDIO_STATUS_PAUSE))
842 if (global_settings.fade_on_stop)
843 fade(0);
844 else
845 audio_pause();
847 waiting_to_resume_play = false;
852 static void car_adapter_tick(void)
854 if (waiting_to_resume_play)
856 if (TIME_AFTER(current_tick, play_resume_tick))
858 if (audio_status() & AUDIO_STATUS_PAUSE)
860 queue_broadcast(SYS_CAR_ADAPTER_RESUME, 0);
862 waiting_to_resume_play = false;
867 void car_adapter_mode_init(void)
869 tick_add_task(car_adapter_tick);
871 #endif
873 #ifdef HAVE_HEADPHONE_DETECTION
874 static void unplug_change(bool inserted)
876 static bool headphone_caused_pause = false;
878 if (global_settings.unplug_mode)
880 int audio_stat = audio_status();
881 if (inserted)
883 if ((audio_stat & AUDIO_STATUS_PLAY) &&
884 headphone_caused_pause &&
885 global_settings.unplug_mode > 1 )
886 audio_resume();
887 backlight_on();
888 headphone_caused_pause = false;
889 } else {
890 if ((audio_stat & AUDIO_STATUS_PLAY) &&
891 !(audio_stat & AUDIO_STATUS_PAUSE))
893 headphone_caused_pause = true;
894 audio_pause();
896 if (global_settings.unplug_rw)
898 if (audio_current_track()->elapsed >
899 (unsigned long)(global_settings.unplug_rw*1000))
900 audio_ff_rewind(audio_current_track()->elapsed -
901 (global_settings.unplug_rw*1000));
902 else
903 audio_ff_rewind(0);
909 #endif
911 long default_event_handler_ex(long event, void (*callback)(void *), void *parameter)
913 switch(event)
915 case SYS_BATTERY_UPDATE:
916 if(global_settings.talk_battery_level)
918 talk_ids(true, VOICE_PAUSE, VOICE_PAUSE,
919 LANG_BATTERY_TIME,
920 TALK_ID(battery_level(), UNIT_PERCENT),
921 VOICE_PAUSE);
922 talk_force_enqueue_next();
924 break;
925 case SYS_USB_CONNECTED:
926 if (callback != NULL)
927 callback(parameter);
928 #ifdef HAVE_MMC
929 if (!mmc_touched() ||
930 (mmc_remove_request() == SYS_HOTSWAP_EXTRACTED))
931 #endif
933 scrobbler_flush_cache();
934 system_flush();
935 #ifdef BOOTFILE
936 #if !defined(USB_NONE) && !defined(USB_IPODSTYLE)
937 check_bootfile(false); /* gets initial size */
938 #endif
939 #endif
940 usb_screen();
941 #ifdef BOOTFILE
942 #if !defined(USB_NONE) && !defined(USB_IPODSTYLE)
943 check_bootfile(true);
944 #endif
945 #endif
946 system_restore();
948 return SYS_USB_CONNECTED;
949 case SYS_POWEROFF:
950 if (!clean_shutdown(callback, parameter))
951 return SYS_POWEROFF;
952 break;
953 #if CONFIG_CHARGING
954 case SYS_CHARGER_CONNECTED:
955 car_adapter_mode_processing(true);
956 return SYS_CHARGER_CONNECTED;
958 case SYS_CHARGER_DISCONNECTED:
959 car_adapter_mode_processing(false);
960 return SYS_CHARGER_DISCONNECTED;
962 case SYS_CAR_ADAPTER_RESUME:
963 audio_resume();
964 return SYS_CAR_ADAPTER_RESUME;
965 #endif
966 #ifdef HAVE_HEADPHONE_DETECTION
967 case SYS_PHONE_PLUGGED:
968 unplug_change(true);
969 return SYS_PHONE_PLUGGED;
971 case SYS_PHONE_UNPLUGGED:
972 unplug_change(false);
973 return SYS_PHONE_UNPLUGGED;
974 #endif
976 return 0;
979 long default_event_handler(long event)
981 return default_event_handler_ex(event, NULL, NULL);
984 int show_logo( void )
986 #ifdef HAVE_LCD_BITMAP
987 char version[32];
988 int font_h, font_w;
990 snprintf(version, sizeof(version), "Ver. %s", appsversion);
992 lcd_clear_display();
993 lcd_bitmap(rockboxlogo, 0, 10, BMPWIDTH_rockboxlogo, BMPHEIGHT_rockboxlogo);
994 lcd_setfont(FONT_SYSFIXED);
995 lcd_getstringsize((unsigned char *)"A", &font_w, &font_h);
996 lcd_putsxy((LCD_WIDTH/2) - ((strlen(version)*font_w)/2),
997 LCD_HEIGHT-font_h, (unsigned char *)version);
998 lcd_setfont(FONT_UI);
1000 #else
1001 char *rockbox = " ROCKbox!";
1003 lcd_clear_display();
1004 lcd_double_height(true);
1005 lcd_puts(0, 0, rockbox);
1006 lcd_puts_scroll(0, 1, appsversion);
1007 #endif
1008 lcd_update();
1010 #ifdef HAVE_REMOTE_LCD
1011 lcd_remote_clear_display();
1012 lcd_remote_bitmap(remote_rockboxlogo, 0, 10, BMPWIDTH_remote_rockboxlogo,
1013 BMPHEIGHT_remote_rockboxlogo);
1014 lcd_remote_setfont(FONT_SYSFIXED);
1015 lcd_remote_getstringsize((unsigned char *)"A", &font_w, &font_h);
1016 lcd_remote_putsxy((LCD_REMOTE_WIDTH/2) - ((strlen(version)*font_w)/2),
1017 LCD_REMOTE_HEIGHT-font_h, (unsigned char *)version);
1018 lcd_remote_setfont(FONT_UI);
1019 lcd_remote_update();
1020 #endif
1022 return 0;
1025 #if CONFIG_CODEC == SWCODEC
1026 int get_replaygain_mode(bool have_track_gain, bool have_album_gain)
1028 int type;
1030 bool track = ((global_settings.replaygain_type == REPLAYGAIN_TRACK)
1031 || ((global_settings.replaygain_type == REPLAYGAIN_SHUFFLE)
1032 && global_settings.playlist_shuffle));
1034 type = (!track && have_album_gain) ? REPLAYGAIN_ALBUM
1035 : have_track_gain ? REPLAYGAIN_TRACK : -1;
1037 return type;
1039 #endif
1041 #ifdef BOOTFILE
1042 #if !defined(USB_NONE) && !defined(USB_IPODSTYLE)
1044 memorize/compare details about the BOOTFILE
1045 we don't use dircache because it may not be up to date after
1046 USB disconnect (scanning in the background)
1048 void check_bootfile(bool do_rolo)
1050 static unsigned short wrtdate = 0;
1051 static unsigned short wrttime = 0;
1052 DIR* dir = NULL;
1053 struct dirent* entry = NULL;
1055 /* 1. open BOOTDIR and find the BOOTFILE dir entry */
1056 dir = opendir(BOOTDIR);
1058 if(!dir) return; /* do we want an error splash? */
1060 /* loop all files in BOOTDIR */
1061 while(0 != (entry = readdir(dir)))
1063 if(!strcasecmp(entry->d_name, BOOTFILE))
1065 /* found the bootfile */
1066 if(wrtdate && do_rolo)
1068 if((entry->wrtdate != wrtdate) ||
1069 (entry->wrttime != wrttime))
1071 static const char *lines[] = { ID2P(LANG_BOOT_CHANGED),
1072 ID2P(LANG_REBOOT_NOW) };
1073 static const struct text_message message={ lines, 2 };
1074 button_clear_queue(); /* Empty the keyboard buffer */
1075 if(gui_syncyesno_run(&message, NULL, NULL) == YESNO_YES)
1076 rolo_load(BOOTDIR "/" BOOTFILE);
1079 wrtdate = entry->wrtdate;
1080 wrttime = entry->wrttime;
1083 closedir(dir);
1085 #endif
1086 #endif
1088 /* check range, set volume and save settings */
1089 void setvol(void)
1091 const int min_vol = sound_min(SOUND_VOLUME);
1092 const int max_vol = sound_max(SOUND_VOLUME);
1093 if (global_settings.volume < min_vol)
1094 global_settings.volume = min_vol;
1095 if (global_settings.volume > max_vol)
1096 global_settings.volume = max_vol;
1097 sound_set_volume(global_settings.volume);
1098 settings_save();
1101 char* strrsplt(char* str, int c)
1103 char* s = strrchr(str, c);
1105 if (s != NULL)
1107 *s++ = '\0';
1109 else
1111 s = str;
1114 return s;
1117 /* Test file existence, using dircache of possible */
1118 bool file_exists(const char *file)
1120 int fd;
1122 if (!file || strlen(file) <= 0)
1123 return false;
1125 #ifdef HAVE_DIRCACHE
1126 if (dircache_is_enabled())
1127 return (dircache_get_entry_ptr(file) != NULL);
1128 #endif
1130 fd = open(file, O_RDONLY);
1131 if (fd < 0)
1132 return false;
1133 close(fd);
1134 return true;
1137 bool dir_exists(const char *path)
1139 DIR* d = opendir(path);
1140 if (!d)
1141 return false;
1142 closedir(d);
1143 return true;
1147 * removes the extension of filename (if it doesn't start with a .)
1148 * puts the result in buffer
1150 char *strip_extension(char* buffer, int buffer_size, const char *filename)
1152 char *dot = strrchr(filename, '.');
1153 int len;
1155 if (buffer_size <= 0)
1157 return NULL;
1160 buffer_size--; /* Make room for end nil */
1162 if (dot != 0 && filename[0] != '.')
1164 len = dot - filename;
1165 len = MIN(len, buffer_size);
1166 strncpy(buffer, filename, len);
1168 else
1170 len = buffer_size;
1171 strncpy(buffer, filename, buffer_size);
1174 buffer[len] = 0;
1176 return buffer;
1178 #endif /* !defined(__PCTOOL__) */
1180 #ifdef HAVE_LCD_COLOR
1182 * Helper function to convert a string of 6 hex digits to a native colour
1185 static int hex2dec(int c)
1187 return (((c) >= '0' && ((c) <= '9')) ? (c) - '0' :
1188 (toupper(c)) - 'A' + 10);
1191 int hex_to_rgb(const char* hex, int* color)
1193 int red, green, blue;
1194 int i = 0;
1196 while ((i < 6) && (isxdigit(hex[i])))
1197 i++;
1199 if (i < 6)
1200 return -1;
1202 red = (hex2dec(hex[0]) << 4) | hex2dec(hex[1]);
1203 green = (hex2dec(hex[2]) << 4) | hex2dec(hex[3]);
1204 blue = (hex2dec(hex[4]) << 4) | hex2dec(hex[5]);
1206 *color = LCD_RGBPACK(red,green,blue);
1208 return 0;
1210 #endif /* HAVE_LCD_COLOR */
1212 #ifdef HAVE_LCD_BITMAP
1213 /* A simplified scanf - used (at time of writing) by wps parsing functions.
1215 fmt - char array specifying the format of each list option. Valid values
1216 are: d - int
1217 s - string (sets pointer to string, without copying)
1218 c - hex colour (RGB888 - e.g. ff00ff)
1219 g - greyscale "colour" (0-3)
1220 valid_vals - if not NULL 1 is set in the bitplace if the item was read OK
1221 0 if not read.
1222 first item is LSB, (max 32 items! )
1223 Stops parseing if an item is invalid unless the item == '-'
1224 sep - list separator (e.g. ',' or '|')
1225 str - string to parse, must be terminated by 0 or sep
1226 ... - pointers to store the parsed values
1228 return value - pointer to char after parsed data, 0 if there was an error.
1232 /* '0'-'3' are ASCII 0x30 to 0x33 */
1233 #define is0123(x) (((x) & 0xfc) == 0x30)
1235 const char* parse_list(const char *fmt, unsigned int *valid_vals,
1236 const char sep, const char* str, ...)
1238 va_list ap;
1239 const char* p = str, *f = fmt;
1240 const char** s;
1241 int* d;
1242 bool valid;
1243 int i=0;
1245 va_start(ap, str);
1246 if (valid_vals)
1247 *valid_vals = 0;
1248 while (*fmt)
1250 /* Check for separator, if we're not at the start */
1251 if (f != fmt)
1253 if (*p != sep)
1254 goto err;
1255 p++;
1257 valid = false;
1258 switch (*fmt++)
1260 case 's': /* string - return a pointer to it (not a copy) */
1261 s = va_arg(ap, const char **);
1263 *s = p;
1264 while (*p && *p != sep)
1265 p++;
1266 valid = (*s[0]!='-') && (*s[1]!=sep) ;
1267 break;
1269 case 'd': /* int */
1270 d = va_arg(ap, int*);
1271 if (!isdigit(*p))
1273 if (!valid_vals || *p != '-')
1274 goto err;
1275 while (*p && *p != sep)
1276 p++;
1278 else
1280 *d = *p++ - '0';
1281 while (isdigit(*p))
1282 *d = (*d * 10) + (*p++ - '0');
1283 valid = true;
1286 break;
1288 #ifdef HAVE_LCD_COLOR
1289 case 'c': /* colour (rrggbb - e.g. f3c1a8) */
1290 d = va_arg(ap, int*);
1292 if (hex_to_rgb(p, d) < 0)
1294 if (!valid_vals || *p != '-')
1295 goto err;
1296 while (*p && *p != sep)
1297 p++;
1299 else
1301 p += 6;
1302 valid = true;
1305 break;
1306 #endif
1308 #if LCD_DEPTH == 2 || (defined(HAVE_REMOTE_LCD) && LCD_REMOTE_DEPTH == 2)
1309 case 'g': /* greyscale colour (0-3) */
1310 d = va_arg(ap, int*);
1312 if (is0123(*p))
1314 *d = *p++ - '0';
1315 valid = true;
1317 else if (!valid_vals || *p != '-')
1318 goto err;
1319 else
1321 while (*p && *p != sep)
1322 p++;
1325 break;
1326 #endif
1328 default: /* Unknown format type */
1329 goto err;
1330 break;
1332 if (valid_vals && valid)
1333 *valid_vals |= (1<<i);
1334 i++;
1337 va_end(ap);
1338 return p;
1340 err:
1341 va_end(ap);
1342 return 0;
1344 #endif