clean up some debugging output.
[kugel-rb.git] / apps / misc.c
blobf37bd5f081bbcba399b727e7b7335cd943c198ab
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 <stdarg.h>
28 #else
29 #include "sprintf.h"
30 #include "lang.h"
31 #include "string.h"
32 #include "dir.h"
33 #include "lcd-remote.h"
34 #include "errno.h"
35 #include "system.h"
36 #include "timefuncs.h"
37 #include "screens.h"
38 #include "talk.h"
39 #include "mpeg.h"
40 #include "audio.h"
41 #include "mp3_playback.h"
42 #include "settings.h"
43 #include "ata.h"
44 #include "ata_idle_notify.h"
45 #include "kernel.h"
46 #include "power.h"
47 #include "powermgmt.h"
48 #include "backlight.h"
49 #include "version.h"
50 #include "font.h"
51 #include "splash.h"
52 #include "tagcache.h"
53 #include "scrobbler.h"
54 #include "sound.h"
55 #include "playlist.h"
56 #include "yesno.h"
58 #ifdef HAVE_MMC
59 #include "ata_mmc.h"
60 #endif
61 #include "tree.h"
62 #include "eeprom_settings.h"
63 #if defined(HAVE_RECORDING) && !defined(__PCTOOL__)
64 #include "recording.h"
65 #endif
66 #if defined(HAVE_LCD_BITMAP) && !defined(__PCTOOL__)
67 #include "bmp.h"
68 #include "icons.h"
69 #endif /* End HAVE_LCD_BITMAP */
70 #include "gui/gwps-common.h"
71 #include "bookmark.h"
73 #include "misc.h"
74 #include "playback.h"
76 #ifdef BOOTFILE
77 #if !defined(USB_NONE) && !defined(USB_IPODSTYLE)
78 #include "rolo.h"
79 #include "yesno.h"
80 #endif
81 #endif
83 /* Format a large-range value for output, using the appropriate unit so that
84 * the displayed value is in the range 1 <= display < 1000 (1024 for "binary"
85 * units) if possible, and 3 significant digits are shown. If a buffer is
86 * given, the result is snprintf()'d into that buffer, otherwise the result is
87 * voiced.*/
88 char *output_dyn_value(char *buf, int buf_size, int value,
89 const unsigned char **units, bool bin_scale)
91 int scale = bin_scale ? 1024 : 1000;
92 int fraction = 0;
93 int unit_no = 0;
94 char tbuf[5];
96 while (value >= scale)
98 fraction = value % scale;
99 value /= scale;
100 unit_no++;
102 if (bin_scale)
103 fraction = fraction * 1000 / 1024;
105 if (value >= 100 || !unit_no)
106 tbuf[0] = '\0';
107 else if (value >= 10)
108 snprintf(tbuf, sizeof(tbuf), "%01d", fraction / 100);
109 else
110 snprintf(tbuf, sizeof(tbuf), "%02d", fraction / 10);
112 if (buf)
114 if (strlen(tbuf))
115 snprintf(buf, buf_size, "%d%s%s%s", value, str(LANG_POINT),
116 tbuf, P2STR(units[unit_no]));
117 else
118 snprintf(buf, buf_size, "%d%s", value, P2STR(units[unit_no]));
120 else
122 talk_fractional(tbuf, value, P2ID(units[unit_no]));
124 return buf;
127 /* Create a filename with a number part in a way that the number is 1
128 * higher than the highest numbered file matching the same pattern.
129 * It is allowed that buffer and path point to the same memory location,
130 * saving a strcpy(). Path must always be given without trailing slash.
131 * "num" can point to an int specifying the number to use or NULL or a value
132 * less than zero to number automatically. The final number used will also
133 * be returned in *num. If *num is >= 0 then *num will be incremented by
134 * one. */
135 char *create_numbered_filename(char *buffer, const char *path,
136 const char *prefix, const char *suffix,
137 int numberlen IF_CNFN_NUM_(, int *num))
139 DIR *dir;
140 struct dirent *entry;
141 int max_num;
142 int pathlen;
143 int prefixlen = strlen(prefix);
144 char fmtstring[12];
146 if (buffer != path)
147 strncpy(buffer, path, MAX_PATH);
149 pathlen = strlen(buffer);
151 #ifdef IF_CNFN_NUM
152 if (num && *num >= 0)
154 /* number specified */
155 max_num = *num;
157 else
158 #endif
160 /* automatic numbering */
161 max_num = 0;
163 dir = opendir(pathlen ? buffer : "/");
164 if (!dir)
165 return NULL;
167 while ((entry = readdir(dir)))
169 int curr_num;
171 if (strncasecmp((char *)entry->d_name, prefix, prefixlen)
172 || strcasecmp((char *)entry->d_name + prefixlen + numberlen, suffix))
173 continue;
175 curr_num = atoi((char *)entry->d_name + prefixlen);
176 if (curr_num > max_num)
177 max_num = curr_num;
180 closedir(dir);
183 max_num++;
185 snprintf(fmtstring, sizeof(fmtstring), "/%%s%%0%dd%%s", numberlen);
186 snprintf(buffer + pathlen, MAX_PATH - pathlen, fmtstring, prefix,
187 max_num, suffix);
189 #ifdef IF_CNFN_NUM
190 if (num)
191 *num = max_num;
192 #endif
194 return buffer;
197 /* Format time into buf.
199 * buf - buffer to format to.
200 * buf_size - size of buffer.
201 * t - time to format, in milliseconds.
203 void format_time(char* buf, int buf_size, long t)
205 if ( t < 3600000 )
207 snprintf(buf, buf_size, "%d:%02d",
208 (int) (t / 60000), (int) (t % 60000 / 1000));
210 else
212 snprintf(buf, buf_size, "%d:%02d:%02d",
213 (int) (t / 3600000), (int) (t % 3600000 / 60000),
214 (int) (t % 60000 / 1000));
218 #if CONFIG_RTC
219 /* Create a filename with a date+time part.
220 It is allowed that buffer and path point to the same memory location,
221 saving a strcpy(). Path must always be given without trailing slash.
222 unique_time as true makes the function wait until the current time has
223 changed. */
224 char *create_datetime_filename(char *buffer, const char *path,
225 const char *prefix, const char *suffix,
226 bool unique_time)
228 struct tm *tm = get_time();
229 static struct tm last_tm;
230 int pathlen;
232 while (unique_time && !memcmp(get_time(), &last_tm, sizeof (struct tm)))
233 sleep(HZ/10);
235 last_tm = *tm;
237 if (buffer != path)
238 strncpy(buffer, path, MAX_PATH);
240 pathlen = strlen(buffer);
241 snprintf(buffer + pathlen, MAX_PATH - pathlen,
242 "/%s%02d%02d%02d-%02d%02d%02d%s", prefix,
243 tm->tm_year % 100, tm->tm_mon + 1, tm->tm_mday,
244 tm->tm_hour, tm->tm_min, tm->tm_sec, suffix);
246 return buffer;
248 #endif /* CONFIG_RTC */
250 /* Ask the user if they really want to erase the current dynamic playlist
251 * returns true if the playlist should be replaced */
252 bool warn_on_pl_erase(void)
254 if (global_settings.warnon_erase_dynplaylist &&
255 !global_settings.party_mode &&
256 playlist_modified(NULL))
258 static const char *lines[] =
259 {ID2P(LANG_WARN_ERASEDYNPLAYLIST_PROMPT)};
260 static const struct text_message message={lines, 1};
262 return (gui_syncyesno_run(&message, NULL, NULL) == YESNO_YES);
264 else
265 return true;
268 /* Read (up to) a line of text from fd into buffer and return number of bytes
269 * read (which may be larger than the number of bytes stored in buffer). If
270 * an error occurs, -1 is returned (and buffer contains whatever could be
271 * read). A line is terminated by a LF char. Neither LF nor CR chars are
272 * stored in buffer.
274 int read_line(int fd, char* buffer, int buffer_size)
276 int count = 0;
277 int num_read = 0;
279 errno = 0;
281 while (count < buffer_size)
283 unsigned char c;
285 if (1 != read(fd, &c, 1))
286 break;
288 num_read++;
290 if ( c == '\n' )
291 break;
293 if ( c == '\r' )
294 continue;
296 buffer[count++] = c;
299 buffer[MIN(count, buffer_size - 1)] = 0;
301 return errno ? -1 : num_read;
304 /* Performance optimized version of the previous function. */
305 int fast_readline(int fd, char *buf, int buf_size, void *parameters,
306 int (*callback)(int n, const char *buf, void *parameters))
308 char *p, *next;
309 int rc, pos = 0;
310 int count = 0;
312 while ( 1 )
314 next = NULL;
316 rc = read(fd, &buf[pos], buf_size - pos - 1);
317 if (rc >= 0)
318 buf[pos+rc] = '\0';
320 if ( (p = strchr(buf, '\r')) != NULL)
322 *p = '\0';
323 next = ++p;
325 else
326 p = buf;
328 if ( (p = strchr(p, '\n')) != NULL)
330 *p = '\0';
331 next = ++p;
334 rc = callback(count, buf, parameters);
335 if (rc < 0)
336 return rc;
338 count++;
339 if (next)
341 pos = buf_size - ((long)next - (long)buf) - 1;
342 memmove(buf, next, pos);
344 else
345 break ;
348 return 0;
351 #ifdef HAVE_LCD_BITMAP
353 #if LCD_DEPTH == 16
354 #define BMP_COMPRESSION 3 /* BI_BITFIELDS */
355 #define BMP_NUMCOLORS 3
356 #else
357 #define BMP_COMPRESSION 0 /* BI_RGB */
358 #if LCD_DEPTH <= 8
359 #define BMP_NUMCOLORS (1 << LCD_DEPTH)
360 #else
361 #define BMP_NUMCOLORS 0
362 #endif
363 #endif
365 #if LCD_DEPTH == 1
366 #define BMP_BPP 1
367 #define BMP_LINESIZE ((LCD_WIDTH/8 + 3) & ~3)
368 #elif LCD_DEPTH <= 4
369 #define BMP_BPP 4
370 #define BMP_LINESIZE ((LCD_WIDTH/2 + 3) & ~3)
371 #elif LCD_DEPTH <= 8
372 #define BMP_BPP 8
373 #define BMP_LINESIZE ((LCD_WIDTH + 3) & ~3)
374 #elif LCD_DEPTH <= 16
375 #define BMP_BPP 16
376 #define BMP_LINESIZE ((LCD_WIDTH*2 + 3) & ~3)
377 #else
378 #define BMP_BPP 24
379 #define BMP_LINESIZE ((LCD_WIDTH*3 + 3) & ~3)
380 #endif
382 #define BMP_HEADERSIZE (54 + 4 * BMP_NUMCOLORS)
383 #define BMP_DATASIZE (BMP_LINESIZE * LCD_HEIGHT)
384 #define BMP_TOTALSIZE (BMP_HEADERSIZE + BMP_DATASIZE)
386 #define LE16_CONST(x) (x)&0xff, ((x)>>8)&0xff
387 #define LE32_CONST(x) (x)&0xff, ((x)>>8)&0xff, ((x)>>16)&0xff, ((x)>>24)&0xff
389 static const unsigned char bmpheader[] =
391 0x42, 0x4d, /* 'BM' */
392 LE32_CONST(BMP_TOTALSIZE), /* Total file size */
393 0x00, 0x00, 0x00, 0x00, /* Reserved */
394 LE32_CONST(BMP_HEADERSIZE), /* Offset to start of pixel data */
396 0x28, 0x00, 0x00, 0x00, /* Size of (2nd) header */
397 LE32_CONST(LCD_WIDTH), /* Width in pixels */
398 LE32_CONST(LCD_HEIGHT), /* Height in pixels */
399 0x01, 0x00, /* Number of planes (always 1) */
400 LE16_CONST(BMP_BPP), /* Bits per pixel 1/4/8/16/24 */
401 LE32_CONST(BMP_COMPRESSION),/* Compression mode */
402 LE32_CONST(BMP_DATASIZE), /* Size of bitmap data */
403 0xc4, 0x0e, 0x00, 0x00, /* Horizontal resolution (pixels/meter) */
404 0xc4, 0x0e, 0x00, 0x00, /* Vertical resolution (pixels/meter) */
405 LE32_CONST(BMP_NUMCOLORS), /* Number of used colours */
406 LE32_CONST(BMP_NUMCOLORS), /* Number of important colours */
408 #if LCD_DEPTH == 1
409 #ifdef MROBE_100
410 2, 2, 94, 0x00, /* Colour #0 */
411 3, 6, 241, 0x00 /* Colour #1 */
412 #else
413 0x90, 0xee, 0x90, 0x00, /* Colour #0 */
414 0x00, 0x00, 0x00, 0x00 /* Colour #1 */
415 #endif
416 #elif LCD_DEPTH == 2
417 0xe6, 0xd8, 0xad, 0x00, /* Colour #0 */
418 0x99, 0x90, 0x73, 0x00, /* Colour #1 */
419 0x4c, 0x48, 0x39, 0x00, /* Colour #2 */
420 0x00, 0x00, 0x00, 0x00 /* Colour #3 */
421 #elif LCD_DEPTH == 16
422 0x00, 0xf8, 0x00, 0x00, /* red bitfield mask */
423 0xe0, 0x07, 0x00, 0x00, /* green bitfield mask */
424 0x1f, 0x00, 0x00, 0x00 /* blue bitfield mask */
425 #endif
428 static void (*screen_dump_hook)(int fh) = NULL;
430 void screen_dump(void)
432 int fh;
433 char filename[MAX_PATH];
434 int bx, by;
435 #if LCD_DEPTH == 1
436 static unsigned char line_block[8][BMP_LINESIZE];
437 #elif LCD_DEPTH == 2
438 #if LCD_PIXELFORMAT == HORIZONTAL_PACKING
439 static unsigned char line_block[BMP_LINESIZE];
440 #elif LCD_PIXELFORMAT == VERTICAL_PACKING
441 static unsigned char line_block[4][BMP_LINESIZE];
442 #elif LCD_PIXELFORMAT == VERTICAL_INTERLEAVED
443 static unsigned char line_block[8][BMP_LINESIZE];
444 #endif
445 #elif LCD_DEPTH == 16
446 static unsigned short line_block[BMP_LINESIZE/2];
447 #endif
449 #if CONFIG_RTC
450 create_datetime_filename(filename, "", "dump ", ".bmp", false);
451 #else
452 create_numbered_filename(filename, "", "dump_", ".bmp", 4
453 IF_CNFN_NUM_(, NULL));
454 #endif
456 fh = creat(filename);
457 if (fh < 0)
458 return;
460 if (screen_dump_hook)
462 screen_dump_hook(fh);
464 else
466 write(fh, bmpheader, sizeof(bmpheader));
468 /* BMP image goes bottom up */
469 #if LCD_DEPTH == 1
470 for (by = LCD_FBHEIGHT - 1; by >= 0; by--)
472 unsigned char *src = &lcd_framebuffer[by][0];
473 unsigned char *dst = &line_block[0][0];
475 memset(line_block, 0, sizeof(line_block));
476 for (bx = LCD_WIDTH/8; bx > 0; bx--)
478 unsigned dst_mask = 0x80;
479 int ix;
481 for (ix = 8; ix > 0; ix--)
483 unsigned char *dst_blk = dst;
484 unsigned src_byte = *src++;
485 int iy;
487 for (iy = 8; iy > 0; iy--)
489 if (src_byte & 0x80)
490 *dst_blk |= dst_mask;
491 src_byte <<= 1;
492 dst_blk += BMP_LINESIZE;
494 dst_mask >>= 1;
496 dst++;
499 write(fh, line_block, sizeof(line_block));
501 #elif LCD_DEPTH == 2
502 #if LCD_PIXELFORMAT == HORIZONTAL_PACKING
503 for (by = LCD_FBHEIGHT - 1; by >= 0; by--)
505 unsigned char *src = &lcd_framebuffer[by][0];
506 unsigned char *dst = line_block;
508 memset(line_block, 0, sizeof(line_block));
509 for (bx = LCD_FBWIDTH; bx > 0; bx--)
511 unsigned src_byte = *src++;
513 *dst++ = ((src_byte >> 2) & 0x30) | ((src_byte >> 4) & 0x03);
514 *dst++ = ((src_byte << 2) & 0x30) | (src_byte & 0x03);
517 write(fh, line_block, sizeof(line_block));
519 #elif LCD_PIXELFORMAT == VERTICAL_PACKING
520 for (by = LCD_FBHEIGHT - 1; by >= 0; by--)
522 unsigned char *src = &lcd_framebuffer[by][0];
523 unsigned char *dst = &line_block[3][0];
525 memset(line_block, 0, sizeof(line_block));
526 for (bx = LCD_WIDTH/2; bx > 0; bx--)
528 unsigned char *dst_blk = dst++;
529 unsigned src_byte0 = *src++ << 4;
530 unsigned src_byte1 = *src++;
531 int iy;
533 for (iy = 4; iy > 0; iy--)
535 *dst_blk = (src_byte0 & 0x30) | (src_byte1 & 0x03);
536 src_byte0 >>= 2;
537 src_byte1 >>= 2;
538 dst_blk -= BMP_LINESIZE;
542 write(fh, line_block, sizeof(line_block));
544 #elif LCD_PIXELFORMAT == VERTICAL_INTERLEAVED
545 for (by = LCD_FBHEIGHT - 1; by >= 0; by--)
547 const fb_data *src = &lcd_framebuffer[by][0];
548 unsigned char *dst = &line_block[7][0];
550 memset(line_block, 0, sizeof(line_block));
551 for (bx = LCD_WIDTH/2; bx > 0; bx--)
553 unsigned char *dst_blk = dst++;
554 unsigned src_data0 = *src++ << 4;
555 unsigned src_data1 = *src++;
556 int iy;
558 for (iy = 8; iy > 0; iy--)
560 *dst_blk = (src_data0 & 0x10) | (src_data1 & 0x01)
561 | ((src_data0 & 0x1000) | (src_data1 & 0x0100)) >> 7;
562 src_data0 >>= 1;
563 src_data1 >>= 1;
564 dst_blk -= BMP_LINESIZE;
568 write(fh, line_block, sizeof(line_block));
570 #endif
571 #elif LCD_DEPTH == 16
572 for (by = LCD_HEIGHT - 1; by >= 0; by--)
574 unsigned short *src = &lcd_framebuffer[by][0];
575 unsigned short *dst = line_block;
577 memset(line_block, 0, sizeof(line_block));
578 for (bx = LCD_WIDTH; bx > 0; bx--)
580 #if (LCD_PIXELFORMAT == RGB565SWAPPED)
581 /* iPod LCD data is big endian although the CPU is not */
582 *dst++ = htobe16(*src++);
583 #else
584 *dst++ = htole16(*src++);
585 #endif
588 write(fh, line_block, sizeof(line_block));
590 #endif /* LCD_DEPTH */
593 close(fh);
596 void screen_dump_set_hook(void (*hook)(int fh))
598 screen_dump_hook = hook;
601 #endif /* HAVE_LCD_BITMAP */
603 /* parse a line from a configuration file. the line format is:
605 name: value
607 Any whitespace before setting name or value (after ':') is ignored.
608 A # as first non-whitespace character discards the whole line.
609 Function sets pointers to null-terminated setting name and value.
610 Returns false if no valid config entry was found.
613 bool settings_parseline(char* line, char** name, char** value)
615 char* ptr;
617 while ( isspace(*line) )
618 line++;
620 if ( *line == '#' )
621 return false;
623 ptr = strchr(line, ':');
624 if ( !ptr )
625 return false;
627 *name = line;
628 *ptr = 0;
629 ptr++;
630 while (isspace(*ptr))
631 ptr++;
632 *value = ptr;
633 return true;
636 static void system_flush(void)
638 tree_flush();
639 call_ata_idle_notifys(true); /*doesnt work on usb and shutdown from ata thread */
642 static void system_restore(void)
644 tree_restore();
647 static bool clean_shutdown(void (*callback)(void *), void *parameter)
649 #ifdef SIMULATOR
650 (void)callback;
651 (void)parameter;
652 bookmark_autobookmark();
653 call_ata_idle_notifys(true);
654 exit(0);
655 #else
656 long msg_id = -1;
657 int i;
659 scrobbler_poweroff();
661 #if CONFIG_CHARGING && !defined(HAVE_POWEROFF_WHILE_CHARGING)
662 if(!charger_inserted())
663 #endif
665 bool batt_safe = battery_level_safe();
666 int audio_stat = audio_status();
668 FOR_NB_SCREENS(i)
669 screens[i].clear_display();
671 if (batt_safe)
673 #ifdef HAVE_TAGCACHE
674 if (!tagcache_prepare_shutdown())
676 cancel_shutdown();
677 gui_syncsplash(HZ, ID2P(LANG_TAGCACHE_BUSY));
678 return false;
680 #endif
681 if (battery_level() > 10)
682 gui_syncsplash(0, str(LANG_SHUTTINGDOWN));
683 else
685 msg_id = LANG_WARNING_BATTERY_LOW;
686 gui_syncsplash(0, "%s %s",
687 str(LANG_WARNING_BATTERY_LOW),
688 str(LANG_SHUTTINGDOWN));
691 else
693 msg_id = LANG_WARNING_BATTERY_EMPTY;
694 gui_syncsplash(0, "%s %s",
695 str(LANG_WARNING_BATTERY_EMPTY),
696 str(LANG_SHUTTINGDOWN));
699 if (global_settings.fade_on_stop
700 && (audio_stat & AUDIO_STATUS_PLAY))
702 fade(false, false);
705 if (batt_safe) /* do not save on critical battery */
707 #if defined(HAVE_RECORDING) && CONFIG_CODEC == SWCODEC
708 if (audio_stat & AUDIO_STATUS_RECORD)
710 rec_command(RECORDING_CMD_STOP);
711 /* wait for stop to complete */
712 while (audio_status() & AUDIO_STATUS_RECORD)
713 sleep(1);
715 #endif
716 bookmark_autobookmark();
718 /* audio_stop_recording == audio_stop for HWCODEC */
719 audio_stop();
721 if (callback != NULL)
722 callback(parameter);
724 #if CONFIG_CODEC != SWCODEC
725 /* wait for audio_stop or audio_stop_recording to complete */
726 while (audio_status())
727 sleep(1);
728 #endif
730 #if defined(HAVE_RECORDING) && CONFIG_CODEC == SWCODEC
731 audio_close_recording();
732 #endif
734 if(global_settings.talk_menu)
736 bool enqueue = false;
737 if(msg_id != -1)
739 talk_id(msg_id, enqueue);
740 enqueue = true;
742 talk_id(LANG_SHUTTINGDOWN, enqueue);
743 #if CONFIG_CODEC == SWCODEC
744 voice_wait();
745 #endif
748 system_flush();
749 #ifdef HAVE_EEPROM_SETTINGS
750 if (firmware_settings.initialized)
752 firmware_settings.disk_clean = true;
753 firmware_settings.bl_version = 0;
754 eeprom_settings_store();
756 #endif
758 #ifdef HAVE_DIRCACHE
759 else
760 dircache_disable();
761 #endif
763 shutdown_hw();
765 #endif
766 return false;
769 bool list_stop_handler(void)
771 bool ret = false;
773 /* Stop the music if it is playing */
774 if(audio_status())
776 if (!global_settings.party_mode)
778 if (global_settings.fade_on_stop)
779 fade(false, false);
780 bookmark_autobookmark();
781 audio_stop();
782 ret = true; /* bookmarking can make a refresh necessary */
785 #if CONFIG_CHARGING
786 #if (CONFIG_KEYPAD == RECORDER_PAD) && !defined(HAVE_SW_POWEROFF)
787 else
789 if (charger_inserted())
790 charging_splash();
791 else
792 shutdown_screen(); /* won't return if shutdown actually happens */
794 ret = true; /* screen is dirty, caller needs to refresh */
796 #endif
797 #ifndef HAVE_POWEROFF_WHILE_CHARGING
799 static long last_off = 0;
801 if (TIME_BEFORE(current_tick, last_off + HZ/2))
803 if (charger_inserted())
805 charging_splash();
806 ret = true; /* screen is dirty, caller needs to refresh */
809 last_off = current_tick;
811 #endif
812 #endif /* CONFIG_CHARGING */
813 return ret;
816 #if CONFIG_CHARGING
817 static bool waiting_to_resume_play = false;
818 static long play_resume_tick;
820 static void car_adapter_mode_processing(bool inserted)
822 if (global_settings.car_adapter_mode)
824 if(inserted)
827 * Just got plugged in, delay & resume if we were playing
829 if (audio_status() & AUDIO_STATUS_PAUSE)
831 /* delay resume a bit while the engine is cranking */
832 play_resume_tick = current_tick + HZ*5;
833 waiting_to_resume_play = true;
836 else
839 * Just got unplugged, pause if playing
841 if ((audio_status() & AUDIO_STATUS_PLAY) &&
842 !(audio_status() & AUDIO_STATUS_PAUSE))
844 if (global_settings.fade_on_stop)
845 fade(false, false);
846 else
847 audio_pause();
849 waiting_to_resume_play = false;
854 static void car_adapter_tick(void)
856 if (waiting_to_resume_play)
858 if (TIME_AFTER(current_tick, play_resume_tick))
860 if (audio_status() & AUDIO_STATUS_PAUSE)
862 queue_broadcast(SYS_CAR_ADAPTER_RESUME, 0);
864 waiting_to_resume_play = false;
869 void car_adapter_mode_init(void)
871 tick_add_task(car_adapter_tick);
873 #endif
875 #ifdef HAVE_HEADPHONE_DETECTION
876 static void unplug_change(bool inserted)
878 static bool headphone_caused_pause = false;
880 if (global_settings.unplug_mode)
882 int audio_stat = audio_status();
883 if (inserted)
885 if ((audio_stat & AUDIO_STATUS_PLAY) &&
886 headphone_caused_pause &&
887 global_settings.unplug_mode > 1 )
888 audio_resume();
889 backlight_on();
890 headphone_caused_pause = false;
891 } else {
892 if ((audio_stat & AUDIO_STATUS_PLAY) &&
893 !(audio_stat & AUDIO_STATUS_PAUSE))
895 headphone_caused_pause = true;
896 audio_pause();
898 if (global_settings.unplug_rw)
900 if (audio_current_track()->elapsed >
901 (unsigned long)(global_settings.unplug_rw*1000))
902 audio_ff_rewind(audio_current_track()->elapsed -
903 (global_settings.unplug_rw*1000));
904 else
905 audio_ff_rewind(0);
911 #endif
913 long default_event_handler_ex(long event, void (*callback)(void *), void *parameter)
915 switch(event)
917 case SYS_BATTERY_UPDATE:
918 if(global_settings.talk_battery_level)
920 talk_ids(true, VOICE_PAUSE, VOICE_PAUSE,
921 LANG_BATTERY_TIME,
922 TALK_ID(battery_level(), UNIT_PERCENT),
923 VOICE_PAUSE);
924 talk_force_enqueue_next();
926 break;
927 case SYS_USB_CONNECTED:
928 if (callback != NULL)
929 callback(parameter);
930 #ifdef HAVE_MMC
931 if (!mmc_touched() ||
932 (mmc_remove_request() == SYS_HOTSWAP_EXTRACTED))
933 #endif
935 scrobbler_flush_cache();
936 system_flush();
937 #ifdef BOOTFILE
938 #if !defined(USB_NONE) && !defined(USB_IPODSTYLE)
939 check_bootfile(false); /* gets initial size */
940 #endif
941 #endif
942 usb_screen();
943 #ifdef BOOTFILE
944 #if !defined(USB_NONE) && !defined(USB_IPODSTYLE)
945 check_bootfile(true);
946 #endif
947 #endif
948 system_restore();
950 return SYS_USB_CONNECTED;
951 case SYS_POWEROFF:
952 if (!clean_shutdown(callback, parameter))
953 return SYS_POWEROFF;
954 break;
955 #if CONFIG_CHARGING
956 case SYS_CHARGER_CONNECTED:
957 car_adapter_mode_processing(true);
958 return SYS_CHARGER_CONNECTED;
960 case SYS_CHARGER_DISCONNECTED:
961 car_adapter_mode_processing(false);
962 return SYS_CHARGER_DISCONNECTED;
964 case SYS_CAR_ADAPTER_RESUME:
965 audio_resume();
966 return SYS_CAR_ADAPTER_RESUME;
967 #endif
968 #ifdef HAVE_HEADPHONE_DETECTION
969 case SYS_PHONE_PLUGGED:
970 unplug_change(true);
971 return SYS_PHONE_PLUGGED;
973 case SYS_PHONE_UNPLUGGED:
974 unplug_change(false);
975 return SYS_PHONE_UNPLUGGED;
976 #endif
978 return 0;
981 long default_event_handler(long event)
983 return default_event_handler_ex(event, NULL, NULL);
986 int show_logo( void )
988 #ifdef HAVE_LCD_BITMAP
989 char version[32];
990 int font_h, font_w;
992 snprintf(version, sizeof(version), "Ver. %s", appsversion);
994 lcd_clear_display();
995 lcd_bitmap(rockboxlogo, 0, 10, BMPWIDTH_rockboxlogo, BMPHEIGHT_rockboxlogo);
996 lcd_setfont(FONT_SYSFIXED);
997 lcd_getstringsize((unsigned char *)"A", &font_w, &font_h);
998 lcd_putsxy((LCD_WIDTH/2) - ((strlen(version)*font_w)/2),
999 LCD_HEIGHT-font_h, (unsigned char *)version);
1000 lcd_setfont(FONT_UI);
1002 #else
1003 char *rockbox = " ROCKbox!";
1005 lcd_clear_display();
1006 lcd_double_height(true);
1007 lcd_puts(0, 0, rockbox);
1008 lcd_puts_scroll(0, 1, appsversion);
1009 #endif
1010 lcd_update();
1012 #ifdef HAVE_REMOTE_LCD
1013 lcd_remote_clear_display();
1014 lcd_remote_bitmap(remote_rockboxlogo, 0, 10, BMPWIDTH_remote_rockboxlogo,
1015 BMPHEIGHT_remote_rockboxlogo);
1016 lcd_remote_setfont(FONT_SYSFIXED);
1017 lcd_remote_getstringsize((unsigned char *)"A", &font_w, &font_h);
1018 lcd_remote_putsxy((LCD_REMOTE_WIDTH/2) - ((strlen(version)*font_w)/2),
1019 LCD_REMOTE_HEIGHT-font_h, (unsigned char *)version);
1020 lcd_remote_setfont(FONT_UI);
1021 lcd_remote_update();
1022 #endif
1024 return 0;
1027 #if CONFIG_CODEC == SWCODEC
1028 int get_replaygain_mode(bool have_track_gain, bool have_album_gain)
1030 int type;
1032 bool track = ((global_settings.replaygain_type == REPLAYGAIN_TRACK)
1033 || ((global_settings.replaygain_type == REPLAYGAIN_SHUFFLE)
1034 && global_settings.playlist_shuffle));
1036 type = (!track && have_album_gain) ? REPLAYGAIN_ALBUM
1037 : have_track_gain ? REPLAYGAIN_TRACK : -1;
1039 return type;
1041 #endif
1043 #ifdef BOOTFILE
1044 #if !defined(USB_NONE) && !defined(USB_IPODSTYLE)
1046 memorize/compare details about the BOOTFILE
1047 we don't use dircache because it may not be up to date after
1048 USB disconnect (scanning in the background)
1050 void check_bootfile(bool do_rolo)
1052 static unsigned short wrtdate = 0;
1053 static unsigned short wrttime = 0;
1054 DIR* dir = NULL;
1055 struct dirent* entry = NULL;
1057 /* 1. open BOOTDIR and find the BOOTFILE dir entry */
1058 dir = opendir(BOOTDIR);
1060 if(!dir) return; /* do we want an error splash? */
1062 /* loop all files in BOOTDIR */
1063 while(0 != (entry = readdir(dir)))
1065 if(!strcasecmp(entry->d_name, BOOTFILE))
1067 /* found the bootfile */
1068 if(wrtdate && do_rolo)
1070 if((entry->wrtdate != wrtdate) ||
1071 (entry->wrttime != wrttime))
1073 static const char *lines[] = { ID2P(LANG_BOOT_CHANGED),
1074 ID2P(LANG_REBOOT_NOW) };
1075 static const struct text_message message={ lines, 2 };
1076 button_clear_queue(); /* Empty the keyboard buffer */
1077 if(gui_syncyesno_run(&message, NULL, NULL) == YESNO_YES)
1078 rolo_load(BOOTDIR "/" BOOTFILE);
1081 wrtdate = entry->wrtdate;
1082 wrttime = entry->wrttime;
1085 closedir(dir);
1087 #endif
1088 #endif
1090 /* check range, set volume and save settings */
1091 void setvol(void)
1093 const int min_vol = sound_min(SOUND_VOLUME);
1094 const int max_vol = sound_max(SOUND_VOLUME);
1095 if (global_settings.volume < min_vol)
1096 global_settings.volume = min_vol;
1097 if (global_settings.volume > max_vol)
1098 global_settings.volume = max_vol;
1099 sound_set_volume(global_settings.volume);
1100 settings_save();
1103 char* strrsplt(char* str, int c)
1105 char* s = strrchr(str, c);
1107 if (s != NULL)
1109 *s++ = '\0';
1111 else
1113 s = str;
1116 return s;
1119 /* Test file existence, using dircache of possible */
1120 bool file_exists(const char *file)
1122 int fd;
1124 if (!file || strlen(file) <= 0)
1125 return false;
1127 #ifdef HAVE_DIRCACHE
1128 if (dircache_is_enabled())
1129 return (dircache_get_entry_ptr(file) != NULL);
1130 #endif
1132 fd = open(file, O_RDONLY);
1133 if (fd < 0)
1134 return false;
1135 close(fd);
1136 return true;
1139 bool dir_exists(const char *path)
1141 DIR* d = opendir(path);
1142 if (!d)
1143 return false;
1144 closedir(d);
1145 return true;
1149 * removes the extension of filename (if it doesn't start with a .)
1150 * puts the result in buffer
1152 char *strip_extension(char* buffer, int buffer_size, const char *filename)
1154 char *dot = strrchr(filename, '.');
1155 int len;
1157 if (buffer_size <= 0)
1159 return NULL;
1162 buffer_size--; /* Make room for end nil */
1164 if (dot != 0 && filename[0] != '.')
1166 len = dot - filename;
1167 len = MIN(len, buffer_size);
1168 strncpy(buffer, filename, len);
1170 else
1172 len = buffer_size;
1173 strncpy(buffer, filename, buffer_size);
1176 buffer[len] = 0;
1178 return buffer;
1180 #endif /* !defined(__PCTOOL__) */
1182 #ifdef HAVE_LCD_COLOR
1184 * Helper function to convert a string of 6 hex digits to a native colour
1187 static int hex2dec(int c)
1189 return (((c) >= '0' && ((c) <= '9')) ? (c) - '0' :
1190 (toupper(c)) - 'A' + 10);
1193 int hex_to_rgb(const char* hex, int* color)
1195 int red, green, blue;
1196 int i = 0;
1198 while ((i < 6) && (isxdigit(hex[i])))
1199 i++;
1201 if (i < 6)
1202 return -1;
1204 red = (hex2dec(hex[0]) << 4) | hex2dec(hex[1]);
1205 green = (hex2dec(hex[2]) << 4) | hex2dec(hex[3]);
1206 blue = (hex2dec(hex[4]) << 4) | hex2dec(hex[5]);
1208 *color = LCD_RGBPACK(red,green,blue);
1210 return 0;
1212 #endif /* HAVE_LCD_COLOR */
1214 #ifdef HAVE_LCD_BITMAP
1215 /* A simplified scanf - used (at time of writing) by wps parsing functions.
1217 fmt - char array specifying the format of each list option. Valid values
1218 are: d - int
1219 s - string (sets pointer to string, without copying)
1220 c - hex colour (RGB888 - e.g. ff00ff)
1221 g - greyscale "colour" (0-3)
1222 set_vals - if not NULL 1 is set in the bitplace if the item was read OK
1223 0 if not read.
1224 first item is LSB, (max 32 items! )
1225 Stops parseing if an item is invalid unless the item == '-'
1226 sep - list separator (e.g. ',' or '|')
1227 str - string to parse, must be terminated by 0 or sep
1228 ... - pointers to store the parsed values
1230 return value - pointer to char after parsed data, 0 if there was an error.
1234 /* '0'-'3' are ASCII 0x30 to 0x33 */
1235 #define is0123(x) (((x) & 0xfc) == 0x30)
1237 const char* parse_list(const char *fmt, uint32_t *set_vals,
1238 const char sep, const char* str, ...)
1240 va_list ap;
1241 const char* p = str, *f = fmt;
1242 const char** s;
1243 int* d;
1244 bool set;
1245 int i=0;
1247 va_start(ap, str);
1248 if (set_vals)
1249 *set_vals = 0;
1250 while (*fmt)
1252 /* Check for separator, if we're not at the start */
1253 if (f != fmt)
1255 if (*p != sep)
1256 goto err;
1257 p++;
1259 set = false;
1260 switch (*fmt++)
1262 case 's': /* string - return a pointer to it (not a copy) */
1263 s = va_arg(ap, const char **);
1265 *s = p;
1266 while (*p && *p != sep)
1267 p++;
1268 set = (s[0][0]!='-') && (s[0][1]!=sep) ;
1269 break;
1271 case 'd': /* int */
1272 d = va_arg(ap, int*);
1273 if (!isdigit(*p))
1275 if (!set_vals || *p != '-')
1276 goto err;
1277 while (*p && *p != sep)
1278 p++;
1280 else
1282 *d = *p++ - '0';
1283 while (isdigit(*p))
1284 *d = (*d * 10) + (*p++ - '0');
1285 set = true;
1288 break;
1290 #ifdef HAVE_LCD_COLOR
1291 case 'c': /* colour (rrggbb - e.g. f3c1a8) */
1292 d = va_arg(ap, int*);
1294 if (hex_to_rgb(p, d) < 0)
1296 if (!set_vals || *p != '-')
1297 goto err;
1298 while (*p && *p != sep)
1299 p++;
1301 else
1303 p += 6;
1304 set = true;
1307 break;
1308 #endif
1310 #if LCD_DEPTH == 2 || (defined(HAVE_REMOTE_LCD) && LCD_REMOTE_DEPTH == 2)
1311 case 'g': /* greyscale colour (0-3) */
1312 d = va_arg(ap, int*);
1314 if (is0123(*p))
1316 *d = *p++ - '0';
1317 set = true;
1319 else if (!set_vals || *p != '-')
1320 goto err;
1321 else
1323 while (*p && *p != sep)
1324 p++;
1327 break;
1328 #endif
1330 default: /* Unknown format type */
1331 goto err;
1332 break;
1334 if (set_vals && set)
1335 *set_vals |= (1<<i);
1336 i++;
1339 va_end(ap);
1340 return p;
1342 err:
1343 va_end(ap);
1344 return 0;
1346 #endif