processEvents before starting autodetection.
[Rockbox.git] / apps / misc.c
blob23341a82e8ffb3297b6360f725a387b6c9ecf44a
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 "textarea.h"
77 #include "rolo.h"
78 #include "yesno.h"
79 #endif
80 #endif
82 /* Format a large-range value for output, using the appropriate unit so that
83 * the displayed value is in the range 1 <= display < 1000 (1024 for "binary"
84 * units) if possible, and 3 significant digits are shown. If a buffer is
85 * given, the result is snprintf()'d into that buffer, otherwise the result is
86 * voiced.*/
87 char *output_dyn_value(char *buf, int buf_size, int value,
88 const unsigned char **units, bool bin_scale)
90 int scale = bin_scale ? 1024 : 1000;
91 int fraction = 0;
92 int unit_no = 0;
93 char tbuf[5];
95 while (value >= scale)
97 fraction = value % scale;
98 value /= scale;
99 unit_no++;
101 if (bin_scale)
102 fraction = fraction * 1000 / 1024;
104 if (value >= 100 || !unit_no)
105 tbuf[0] = '\0';
106 else if (value >= 10)
107 snprintf(tbuf, sizeof(tbuf), "%01d", fraction / 100);
108 else
109 snprintf(tbuf, sizeof(tbuf), "%02d", fraction / 10);
111 if (buf)
113 if (strlen(tbuf))
114 snprintf(buf, buf_size, "%d%s%s%s", value, str(LANG_POINT),
115 tbuf, P2STR(units[unit_no]));
116 else
117 snprintf(buf, buf_size, "%d%s", value, P2STR(units[unit_no]));
119 else
121 talk_fractional(tbuf, value, P2ID(units[unit_no]));
123 return buf;
126 /* Create a filename with a number part in a way that the number is 1
127 * higher than the highest numbered file matching the same pattern.
128 * It is allowed that buffer and path point to the same memory location,
129 * saving a strcpy(). Path must always be given without trailing slash.
130 * "num" can point to an int specifying the number to use or NULL or a value
131 * less than zero to number automatically. The final number used will also
132 * be returned in *num. If *num is >= 0 then *num will be incremented by
133 * one. */
134 char *create_numbered_filename(char *buffer, const char *path,
135 const char *prefix, const char *suffix,
136 int numberlen IF_CNFN_NUM_(, int *num))
138 DIR *dir;
139 struct dirent *entry;
140 int max_num;
141 int pathlen;
142 int prefixlen = strlen(prefix);
143 char fmtstring[12];
145 if (buffer != path)
146 strncpy(buffer, path, MAX_PATH);
148 pathlen = strlen(buffer);
150 #ifdef IF_CNFN_NUM
151 if (num && *num >= 0)
153 /* number specified */
154 max_num = *num;
156 else
157 #endif
159 /* automatic numbering */
160 max_num = 0;
162 dir = opendir(pathlen ? buffer : "/");
163 if (!dir)
164 return NULL;
166 while ((entry = readdir(dir)))
168 int curr_num;
170 if (strncasecmp((char *)entry->d_name, prefix, prefixlen)
171 || strcasecmp((char *)entry->d_name + prefixlen + numberlen, suffix))
172 continue;
174 curr_num = atoi((char *)entry->d_name + prefixlen);
175 if (curr_num > max_num)
176 max_num = curr_num;
179 closedir(dir);
182 max_num++;
184 snprintf(fmtstring, sizeof(fmtstring), "/%%s%%0%dd%%s", numberlen);
185 snprintf(buffer + pathlen, MAX_PATH - pathlen, fmtstring, prefix,
186 max_num, suffix);
188 #ifdef IF_CNFN_NUM
189 if (num)
190 *num = max_num;
191 #endif
193 return buffer;
196 /* Format time into buf.
198 * buf - buffer to format to.
199 * buf_size - size of buffer.
200 * t - time to format, in milliseconds.
202 void format_time(char* buf, int buf_size, long t)
204 if ( t < 3600000 )
206 snprintf(buf, buf_size, "%d:%02d",
207 (int) (t / 60000), (int) (t % 60000 / 1000));
209 else
211 snprintf(buf, buf_size, "%d:%02d:%02d",
212 (int) (t / 3600000), (int) (t % 3600000 / 60000),
213 (int) (t % 60000 / 1000));
217 #if CONFIG_RTC
218 /* Create a filename with a date+time part.
219 It is allowed that buffer and path point to the same memory location,
220 saving a strcpy(). Path must always be given without trailing slash.
221 unique_time as true makes the function wait until the current time has
222 changed. */
223 char *create_datetime_filename(char *buffer, const char *path,
224 const char *prefix, const char *suffix,
225 bool unique_time)
227 struct tm *tm = get_time();
228 static struct tm last_tm;
229 int pathlen;
231 while (unique_time && !memcmp(get_time(), &last_tm, sizeof (struct tm)))
232 sleep(HZ/10);
234 last_tm = *tm;
236 if (buffer != path)
237 strncpy(buffer, path, MAX_PATH);
239 pathlen = strlen(buffer);
240 snprintf(buffer + pathlen, MAX_PATH - pathlen,
241 "/%s%02d%02d%02d-%02d%02d%02d%s", prefix,
242 tm->tm_year % 100, tm->tm_mon + 1, tm->tm_mday,
243 tm->tm_hour, tm->tm_min, tm->tm_sec, suffix);
245 return buffer;
247 #endif /* CONFIG_RTC */
249 /* Ask the user if they really want to erase the current dynamic playlist
250 * returns true if the playlist should be replaced */
251 bool warn_on_pl_erase(void)
253 if (global_settings.warnon_erase_dynplaylist &&
254 !global_settings.party_mode &&
255 playlist_modified(NULL))
257 static const char *lines[] =
258 {ID2P(LANG_WARN_ERASEDYNPLAYLIST_PROMPT)};
259 static const struct text_message message={lines, 1};
261 return (gui_syncyesno_run(&message, NULL, NULL) == YESNO_YES);
263 else
264 return true;
267 /* Read (up to) a line of text from fd into buffer and return number of bytes
268 * read (which may be larger than the number of bytes stored in buffer). If
269 * an error occurs, -1 is returned (and buffer contains whatever could be
270 * read). A line is terminated by a LF char. Neither LF nor CR chars are
271 * stored in buffer.
273 int read_line(int fd, char* buffer, int buffer_size)
275 int count = 0;
276 int num_read = 0;
278 errno = 0;
280 while (count < buffer_size)
282 unsigned char c;
284 if (1 != read(fd, &c, 1))
285 break;
287 num_read++;
289 if ( c == '\n' )
290 break;
292 if ( c == '\r' )
293 continue;
295 buffer[count++] = c;
298 buffer[MIN(count, buffer_size - 1)] = 0;
300 return errno ? -1 : num_read;
303 /* Performance optimized version of the previous function. */
304 int fast_readline(int fd, char *buf, int buf_size, void *parameters,
305 int (*callback)(int n, const char *buf, void *parameters))
307 char *p, *next;
308 int rc, pos = 0;
309 int count = 0;
311 while ( 1 )
313 next = NULL;
315 rc = read(fd, &buf[pos], buf_size - pos - 1);
316 if (rc >= 0)
317 buf[pos+rc] = '\0';
319 if ( (p = strchr(buf, '\r')) != NULL)
321 *p = '\0';
322 next = ++p;
324 else
325 p = buf;
327 if ( (p = strchr(p, '\n')) != NULL)
329 *p = '\0';
330 next = ++p;
333 rc = callback(count, buf, parameters);
334 if (rc < 0)
335 return rc;
337 count++;
338 if (next)
340 pos = buf_size - ((long)next - (long)buf) - 1;
341 memmove(buf, next, pos);
343 else
344 break ;
347 return 0;
350 #ifdef HAVE_LCD_BITMAP
352 #if LCD_DEPTH == 16
353 #define BMP_COMPRESSION 3 /* BI_BITFIELDS */
354 #define BMP_NUMCOLORS 3
355 #else
356 #define BMP_COMPRESSION 0 /* BI_RGB */
357 #if LCD_DEPTH <= 8
358 #define BMP_NUMCOLORS (1 << LCD_DEPTH)
359 #else
360 #define BMP_NUMCOLORS 0
361 #endif
362 #endif
364 #if LCD_DEPTH == 1
365 #define BMP_BPP 1
366 #define BMP_LINESIZE ((LCD_WIDTH/8 + 3) & ~3)
367 #elif LCD_DEPTH <= 4
368 #define BMP_BPP 4
369 #define BMP_LINESIZE ((LCD_WIDTH/2 + 3) & ~3)
370 #elif LCD_DEPTH <= 8
371 #define BMP_BPP 8
372 #define BMP_LINESIZE ((LCD_WIDTH + 3) & ~3)
373 #elif LCD_DEPTH <= 16
374 #define BMP_BPP 16
375 #define BMP_LINESIZE ((LCD_WIDTH*2 + 3) & ~3)
376 #else
377 #define BMP_BPP 24
378 #define BMP_LINESIZE ((LCD_WIDTH*3 + 3) & ~3)
379 #endif
381 #define BMP_HEADERSIZE (54 + 4 * BMP_NUMCOLORS)
382 #define BMP_DATASIZE (BMP_LINESIZE * LCD_HEIGHT)
383 #define BMP_TOTALSIZE (BMP_HEADERSIZE + BMP_DATASIZE)
385 #define LE16_CONST(x) (x)&0xff, ((x)>>8)&0xff
386 #define LE32_CONST(x) (x)&0xff, ((x)>>8)&0xff, ((x)>>16)&0xff, ((x)>>24)&0xff
388 static const unsigned char bmpheader[] =
390 0x42, 0x4d, /* 'BM' */
391 LE32_CONST(BMP_TOTALSIZE), /* Total file size */
392 0x00, 0x00, 0x00, 0x00, /* Reserved */
393 LE32_CONST(BMP_HEADERSIZE), /* Offset to start of pixel data */
395 0x28, 0x00, 0x00, 0x00, /* Size of (2nd) header */
396 LE32_CONST(LCD_WIDTH), /* Width in pixels */
397 LE32_CONST(LCD_HEIGHT), /* Height in pixels */
398 0x01, 0x00, /* Number of planes (always 1) */
399 LE16_CONST(BMP_BPP), /* Bits per pixel 1/4/8/16/24 */
400 LE32_CONST(BMP_COMPRESSION),/* Compression mode */
401 LE32_CONST(BMP_DATASIZE), /* Size of bitmap data */
402 0xc4, 0x0e, 0x00, 0x00, /* Horizontal resolution (pixels/meter) */
403 0xc4, 0x0e, 0x00, 0x00, /* Vertical resolution (pixels/meter) */
404 LE32_CONST(BMP_NUMCOLORS), /* Number of used colours */
405 LE32_CONST(BMP_NUMCOLORS), /* Number of important colours */
407 #if LCD_DEPTH == 1
408 #ifdef MROBE_100
409 2, 2, 94, 0x00, /* Colour #0 */
410 3, 6, 241, 0x00 /* Colour #1 */
411 #else
412 0x90, 0xee, 0x90, 0x00, /* Colour #0 */
413 0x00, 0x00, 0x00, 0x00 /* Colour #1 */
414 #endif
415 #elif LCD_DEPTH == 2
416 0xe6, 0xd8, 0xad, 0x00, /* Colour #0 */
417 0x99, 0x90, 0x73, 0x00, /* Colour #1 */
418 0x4c, 0x48, 0x39, 0x00, /* Colour #2 */
419 0x00, 0x00, 0x00, 0x00 /* Colour #3 */
420 #elif LCD_DEPTH == 16
421 0x00, 0xf8, 0x00, 0x00, /* red bitfield mask */
422 0xe0, 0x07, 0x00, 0x00, /* green bitfield mask */
423 0x1f, 0x00, 0x00, 0x00 /* blue bitfield mask */
424 #endif
427 static void (*screen_dump_hook)(int fh) = NULL;
429 void screen_dump(void)
431 int fh;
432 char filename[MAX_PATH];
433 int bx, by;
434 #if LCD_DEPTH == 1
435 static unsigned char line_block[8][BMP_LINESIZE];
436 #elif LCD_DEPTH == 2
437 #if LCD_PIXELFORMAT == HORIZONTAL_PACKING
438 static unsigned char line_block[BMP_LINESIZE];
439 #elif LCD_PIXELFORMAT == VERTICAL_PACKING
440 static unsigned char line_block[4][BMP_LINESIZE];
441 #elif LCD_PIXELFORMAT == VERTICAL_INTERLEAVED
442 static unsigned char line_block[8][BMP_LINESIZE];
443 #endif
444 #elif LCD_DEPTH == 16
445 static unsigned short line_block[BMP_LINESIZE/2];
446 #endif
448 #if CONFIG_RTC
449 create_datetime_filename(filename, "", "dump ", ".bmp", false);
450 #else
451 create_numbered_filename(filename, "", "dump_", ".bmp", 4
452 IF_CNFN_NUM_(, NULL));
453 #endif
455 fh = creat(filename);
456 if (fh < 0)
457 return;
459 if (screen_dump_hook)
461 screen_dump_hook(fh);
463 else
465 write(fh, bmpheader, sizeof(bmpheader));
467 /* BMP image goes bottom up */
468 #if LCD_DEPTH == 1
469 for (by = LCD_FBHEIGHT - 1; by >= 0; by--)
471 unsigned char *src = &lcd_framebuffer[by][0];
472 unsigned char *dst = &line_block[0][0];
474 memset(line_block, 0, sizeof(line_block));
475 for (bx = LCD_WIDTH/8; bx > 0; bx--)
477 unsigned dst_mask = 0x80;
478 int ix;
480 for (ix = 8; ix > 0; ix--)
482 unsigned char *dst_blk = dst;
483 unsigned src_byte = *src++;
484 int iy;
486 for (iy = 8; iy > 0; iy--)
488 if (src_byte & 0x80)
489 *dst_blk |= dst_mask;
490 src_byte <<= 1;
491 dst_blk += BMP_LINESIZE;
493 dst_mask >>= 1;
495 dst++;
498 write(fh, line_block, sizeof(line_block));
500 #elif LCD_DEPTH == 2
501 #if LCD_PIXELFORMAT == HORIZONTAL_PACKING
502 for (by = LCD_FBHEIGHT - 1; by >= 0; by--)
504 unsigned char *src = &lcd_framebuffer[by][0];
505 unsigned char *dst = line_block;
507 memset(line_block, 0, sizeof(line_block));
508 for (bx = LCD_FBWIDTH; bx > 0; bx--)
510 unsigned src_byte = *src++;
512 *dst++ = ((src_byte >> 2) & 0x30) | ((src_byte >> 4) & 0x03);
513 *dst++ = ((src_byte << 2) & 0x30) | (src_byte & 0x03);
516 write(fh, line_block, sizeof(line_block));
518 #elif LCD_PIXELFORMAT == VERTICAL_PACKING
519 for (by = LCD_FBHEIGHT - 1; by >= 0; by--)
521 unsigned char *src = &lcd_framebuffer[by][0];
522 unsigned char *dst = &line_block[3][0];
524 memset(line_block, 0, sizeof(line_block));
525 for (bx = LCD_WIDTH/2; bx > 0; bx--)
527 unsigned char *dst_blk = dst++;
528 unsigned src_byte0 = *src++ << 4;
529 unsigned src_byte1 = *src++;
530 int iy;
532 for (iy = 4; iy > 0; iy--)
534 *dst_blk = (src_byte0 & 0x30) | (src_byte1 & 0x03);
535 src_byte0 >>= 2;
536 src_byte1 >>= 2;
537 dst_blk -= BMP_LINESIZE;
541 write(fh, line_block, sizeof(line_block));
543 #elif LCD_PIXELFORMAT == VERTICAL_INTERLEAVED
544 for (by = LCD_FBHEIGHT - 1; by >= 0; by--)
546 const fb_data *src = &lcd_framebuffer[by][0];
547 unsigned char *dst = &line_block[7][0];
549 memset(line_block, 0, sizeof(line_block));
550 for (bx = LCD_WIDTH/2; bx > 0; bx--)
552 unsigned char *dst_blk = dst++;
553 unsigned src_data0 = *src++ << 4;
554 unsigned src_data1 = *src++;
555 int iy;
557 for (iy = 8; iy > 0; iy--)
559 *dst_blk = (src_data0 & 0x10) | (src_data1 & 0x01)
560 | ((src_data0 & 0x1000) | (src_data1 & 0x0100)) >> 7;
561 src_data0 >>= 1;
562 src_data1 >>= 1;
563 dst_blk -= BMP_LINESIZE;
567 write(fh, line_block, sizeof(line_block));
569 #endif
570 #elif LCD_DEPTH == 16
571 for (by = LCD_HEIGHT - 1; by >= 0; by--)
573 unsigned short *src = &lcd_framebuffer[by][0];
574 unsigned short *dst = line_block;
576 memset(line_block, 0, sizeof(line_block));
577 for (bx = LCD_WIDTH; bx > 0; bx--)
579 #if (LCD_PIXELFORMAT == RGB565SWAPPED)
580 /* iPod LCD data is big endian although the CPU is not */
581 *dst++ = htobe16(*src++);
582 #else
583 *dst++ = htole16(*src++);
584 #endif
587 write(fh, line_block, sizeof(line_block));
589 #endif /* LCD_DEPTH */
592 close(fh);
595 void screen_dump_set_hook(void (*hook)(int fh))
597 screen_dump_hook = hook;
600 #endif /* HAVE_LCD_BITMAP */
602 /* parse a line from a configuration file. the line format is:
604 name: value
606 Any whitespace before setting name or value (after ':') is ignored.
607 A # as first non-whitespace character discards the whole line.
608 Function sets pointers to null-terminated setting name and value.
609 Returns false if no valid config entry was found.
612 bool settings_parseline(char* line, char** name, char** value)
614 char* ptr;
616 while ( isspace(*line) )
617 line++;
619 if ( *line == '#' )
620 return false;
622 ptr = strchr(line, ':');
623 if ( !ptr )
624 return false;
626 *name = line;
627 *ptr = 0;
628 ptr++;
629 while (isspace(*ptr))
630 ptr++;
631 *value = ptr;
632 return true;
635 static void system_flush(void)
637 tree_flush();
638 call_ata_idle_notifys(true); /*doesnt work on usb and shutdown from ata thread */
641 static void system_restore(void)
643 tree_restore();
646 static bool clean_shutdown(void (*callback)(void *), void *parameter)
648 #ifdef SIMULATOR
649 (void)callback;
650 (void)parameter;
651 bookmark_autobookmark();
652 call_ata_idle_notifys(true);
653 exit(0);
654 #else
655 long msg_id = -1;
656 int i;
658 scrobbler_poweroff();
660 #if CONFIG_CHARGING && !defined(HAVE_POWEROFF_WHILE_CHARGING)
661 if(!charger_inserted())
662 #endif
664 bool batt_safe = battery_level_safe();
665 int audio_stat = audio_status();
667 FOR_NB_SCREENS(i)
668 screens[i].clear_display();
670 if (batt_safe)
672 #ifdef HAVE_TAGCACHE
673 if (!tagcache_prepare_shutdown())
675 cancel_shutdown();
676 gui_syncsplash(HZ, ID2P(LANG_TAGCACHE_BUSY));
677 return false;
679 #endif
680 if (battery_level() > 10)
681 gui_syncsplash(0, str(LANG_SHUTTINGDOWN));
682 else
684 msg_id = LANG_WARNING_BATTERY_LOW;
685 gui_syncsplash(0, "%s %s",
686 str(LANG_WARNING_BATTERY_LOW),
687 str(LANG_SHUTTINGDOWN));
690 else
692 msg_id = LANG_WARNING_BATTERY_EMPTY;
693 gui_syncsplash(0, "%s %s",
694 str(LANG_WARNING_BATTERY_EMPTY),
695 str(LANG_SHUTTINGDOWN));
698 if (global_settings.fade_on_stop
699 && (audio_stat & AUDIO_STATUS_PLAY))
701 fade(0);
704 if (batt_safe) /* do not save on critical battery */
706 #if defined(HAVE_RECORDING) && CONFIG_CODEC == SWCODEC
707 if (audio_stat & AUDIO_STATUS_RECORD)
709 rec_command(RECORDING_CMD_STOP);
710 /* wait for stop to complete */
711 while (audio_status() & AUDIO_STATUS_RECORD)
712 sleep(1);
714 #endif
715 bookmark_autobookmark();
717 /* audio_stop_recording == audio_stop for HWCODEC */
718 audio_stop();
720 if (callback != NULL)
721 callback(parameter);
723 #if CONFIG_CODEC != SWCODEC
724 /* wait for audio_stop or audio_stop_recording to complete */
725 while (audio_status())
726 sleep(1);
727 #endif
729 #if defined(HAVE_RECORDING) && CONFIG_CODEC == SWCODEC
730 audio_close_recording();
731 #endif
733 if(global_settings.talk_menu)
735 bool enqueue = false;
736 if(msg_id != -1)
738 talk_id(msg_id, enqueue);
739 enqueue = true;
741 talk_id(LANG_SHUTTINGDOWN, enqueue);
742 #if CONFIG_CODEC == SWCODEC
743 voice_wait();
744 #endif
747 system_flush();
748 #ifdef HAVE_EEPROM_SETTINGS
749 if (firmware_settings.initialized)
751 firmware_settings.disk_clean = true;
752 firmware_settings.bl_version = 0;
753 eeprom_settings_store();
755 #endif
757 #ifdef HAVE_DIRCACHE
758 else
759 dircache_disable();
760 #endif
762 shutdown_hw();
764 #endif
765 return false;
768 bool list_stop_handler(void)
770 bool ret = false;
772 /* Stop the music if it is playing */
773 if(audio_status())
775 if (!global_settings.party_mode)
777 if (global_settings.fade_on_stop)
778 fade(0);
779 bookmark_autobookmark();
780 audio_stop();
781 ret = true; /* bookmarking can make a refresh necessary */
784 #if CONFIG_CHARGING
785 #if (CONFIG_KEYPAD == RECORDER_PAD) && !defined(HAVE_SW_POWEROFF)
786 else
788 if (charger_inserted())
789 charging_splash();
790 else
791 shutdown_screen(); /* won't return if shutdown actually happens */
793 ret = true; /* screen is dirty, caller needs to refresh */
795 #endif
796 #ifndef HAVE_POWEROFF_WHILE_CHARGING
798 static long last_off = 0;
800 if (TIME_BEFORE(current_tick, last_off + HZ/2))
802 if (charger_inserted())
804 charging_splash();
805 ret = true; /* screen is dirty, caller needs to refresh */
808 last_off = current_tick;
810 #endif
811 #endif /* CONFIG_CHARGING */
812 return ret;
815 #if CONFIG_CHARGING
816 static bool waiting_to_resume_play = false;
817 static long play_resume_tick;
819 static void car_adapter_mode_processing(bool inserted)
821 if (global_settings.car_adapter_mode)
823 if(inserted)
826 * Just got plugged in, delay & resume if we were playing
828 if (audio_status() & AUDIO_STATUS_PAUSE)
830 /* delay resume a bit while the engine is cranking */
831 play_resume_tick = current_tick + HZ*5;
832 waiting_to_resume_play = true;
835 else
838 * Just got unplugged, pause if playing
840 if ((audio_status() & AUDIO_STATUS_PLAY) &&
841 !(audio_status() & AUDIO_STATUS_PAUSE))
843 if (global_settings.fade_on_stop)
844 fade(0);
845 else
846 audio_pause();
848 waiting_to_resume_play = false;
853 static void car_adapter_tick(void)
855 if (waiting_to_resume_play)
857 if (TIME_AFTER(current_tick, play_resume_tick))
859 if (audio_status() & AUDIO_STATUS_PAUSE)
861 queue_broadcast(SYS_CAR_ADAPTER_RESUME, 0);
863 waiting_to_resume_play = false;
868 void car_adapter_mode_init(void)
870 tick_add_task(car_adapter_tick);
872 #endif
874 #ifdef HAVE_HEADPHONE_DETECTION
875 static void unplug_change(bool inserted)
877 static bool headphone_caused_pause = false;
879 if (global_settings.unplug_mode)
881 int audio_stat = audio_status();
882 if (inserted)
884 if ((audio_stat & AUDIO_STATUS_PLAY) &&
885 headphone_caused_pause &&
886 global_settings.unplug_mode > 1 )
887 audio_resume();
888 backlight_on();
889 headphone_caused_pause = false;
890 } else {
891 if ((audio_stat & AUDIO_STATUS_PLAY) &&
892 !(audio_stat & AUDIO_STATUS_PAUSE))
894 headphone_caused_pause = true;
895 audio_pause();
897 if (global_settings.unplug_rw)
899 if (audio_current_track()->elapsed >
900 (unsigned long)(global_settings.unplug_rw*1000))
901 audio_ff_rewind(audio_current_track()->elapsed -
902 (global_settings.unplug_rw*1000));
903 else
904 audio_ff_rewind(0);
910 #endif
912 long default_event_handler_ex(long event, void (*callback)(void *), void *parameter)
914 switch(event)
916 case SYS_BATTERY_UPDATE:
917 if(global_settings.talk_battery_level)
919 talk_ids(true, VOICE_PAUSE, VOICE_PAUSE,
920 LANG_BATTERY_TIME,
921 TALK_ID(battery_level(), UNIT_PERCENT),
922 VOICE_PAUSE);
923 talk_force_enqueue_next();
925 break;
926 case SYS_USB_CONNECTED:
927 if (callback != NULL)
928 callback(parameter);
929 #ifdef HAVE_MMC
930 if (!mmc_touched() ||
931 (mmc_remove_request() == SYS_HOTSWAP_EXTRACTED))
932 #endif
934 scrobbler_flush_cache();
935 system_flush();
936 #ifdef BOOTFILE
937 #if !defined(USB_NONE) && !defined(USB_IPODSTYLE)
938 check_bootfile(false); /* gets initial size */
939 #endif
940 #endif
941 usb_screen();
942 #ifdef BOOTFILE
943 #if !defined(USB_NONE) && !defined(USB_IPODSTYLE)
944 check_bootfile(true);
945 #endif
946 #endif
947 system_restore();
949 return SYS_USB_CONNECTED;
950 case SYS_POWEROFF:
951 if (!clean_shutdown(callback, parameter))
952 return SYS_POWEROFF;
953 break;
954 #if CONFIG_CHARGING
955 case SYS_CHARGER_CONNECTED:
956 car_adapter_mode_processing(true);
957 return SYS_CHARGER_CONNECTED;
959 case SYS_CHARGER_DISCONNECTED:
960 car_adapter_mode_processing(false);
961 return SYS_CHARGER_DISCONNECTED;
963 case SYS_CAR_ADAPTER_RESUME:
964 audio_resume();
965 return SYS_CAR_ADAPTER_RESUME;
966 #endif
967 #ifdef HAVE_HEADPHONE_DETECTION
968 case SYS_PHONE_PLUGGED:
969 unplug_change(true);
970 return SYS_PHONE_PLUGGED;
972 case SYS_PHONE_UNPLUGGED:
973 unplug_change(false);
974 return SYS_PHONE_UNPLUGGED;
975 #endif
977 return 0;
980 long default_event_handler(long event)
982 return default_event_handler_ex(event, NULL, NULL);
985 int show_logo( void )
987 #ifdef HAVE_LCD_BITMAP
988 char version[32];
989 int font_h, font_w;
991 snprintf(version, sizeof(version), "Ver. %s", appsversion);
993 lcd_clear_display();
994 lcd_bitmap(rockboxlogo, 0, 10, BMPWIDTH_rockboxlogo, BMPHEIGHT_rockboxlogo);
995 lcd_setfont(FONT_SYSFIXED);
996 lcd_getstringsize((unsigned char *)"A", &font_w, &font_h);
997 lcd_putsxy((LCD_WIDTH/2) - ((strlen(version)*font_w)/2),
998 LCD_HEIGHT-font_h, (unsigned char *)version);
999 lcd_setfont(FONT_UI);
1001 #else
1002 char *rockbox = " ROCKbox!";
1004 lcd_clear_display();
1005 lcd_double_height(true);
1006 lcd_puts(0, 0, rockbox);
1007 lcd_puts_scroll(0, 1, appsversion);
1008 #endif
1009 lcd_update();
1011 #ifdef HAVE_REMOTE_LCD
1012 lcd_remote_clear_display();
1013 lcd_remote_bitmap(remote_rockboxlogo, 0, 10, BMPWIDTH_remote_rockboxlogo,
1014 BMPHEIGHT_remote_rockboxlogo);
1015 lcd_remote_setfont(FONT_SYSFIXED);
1016 lcd_remote_getstringsize((unsigned char *)"A", &font_w, &font_h);
1017 lcd_remote_putsxy((LCD_REMOTE_WIDTH/2) - ((strlen(version)*font_w)/2),
1018 LCD_REMOTE_HEIGHT-font_h, (unsigned char *)version);
1019 lcd_remote_setfont(FONT_UI);
1020 lcd_remote_update();
1021 #endif
1023 return 0;
1026 #if CONFIG_CODEC == SWCODEC
1027 int get_replaygain_mode(bool have_track_gain, bool have_album_gain)
1029 int type;
1031 bool track = ((global_settings.replaygain_type == REPLAYGAIN_TRACK)
1032 || ((global_settings.replaygain_type == REPLAYGAIN_SHUFFLE)
1033 && global_settings.playlist_shuffle));
1035 type = (!track && have_album_gain) ? REPLAYGAIN_ALBUM
1036 : have_track_gain ? REPLAYGAIN_TRACK : -1;
1038 return type;
1040 #endif
1042 #ifdef BOOTFILE
1043 #if !defined(USB_NONE) && !defined(USB_IPODSTYLE)
1045 memorize/compare details about the BOOTFILE
1046 we don't use dircache because it may not be up to date after
1047 USB disconnect (scanning in the background)
1049 void check_bootfile(bool do_rolo)
1051 static unsigned short wrtdate = 0;
1052 static unsigned short wrttime = 0;
1053 DIR* dir = NULL;
1054 struct dirent* entry = NULL;
1056 /* 1. open BOOTDIR and find the BOOTFILE dir entry */
1057 dir = opendir(BOOTDIR);
1059 if(!dir) return; /* do we want an error splash? */
1061 /* loop all files in BOOTDIR */
1062 while(0 != (entry = readdir(dir)))
1064 if(!strcasecmp(entry->d_name, BOOTFILE))
1066 /* found the bootfile */
1067 if(wrtdate && do_rolo)
1069 if((entry->wrtdate != wrtdate) ||
1070 (entry->wrttime != wrttime))
1072 static const char *lines[] = { ID2P(LANG_BOOT_CHANGED),
1073 ID2P(LANG_REBOOT_NOW) };
1074 static const struct text_message message={ lines, 2 };
1075 button_clear_queue(); /* Empty the keyboard buffer */
1076 if(gui_syncyesno_run(&message, NULL, NULL) == YESNO_YES)
1077 rolo_load(BOOTDIR "/" BOOTFILE);
1080 wrtdate = entry->wrtdate;
1081 wrttime = entry->wrttime;
1084 closedir(dir);
1086 #endif
1087 #endif
1089 /* check range, set volume and save settings */
1090 void setvol(void)
1092 const int min_vol = sound_min(SOUND_VOLUME);
1093 const int max_vol = sound_max(SOUND_VOLUME);
1094 if (global_settings.volume < min_vol)
1095 global_settings.volume = min_vol;
1096 if (global_settings.volume > max_vol)
1097 global_settings.volume = max_vol;
1098 sound_set_volume(global_settings.volume);
1099 settings_save();
1102 char* strrsplt(char* str, int c)
1104 char* s = strrchr(str, c);
1106 if (s != NULL)
1108 *s++ = '\0';
1110 else
1112 s = str;
1115 return s;
1118 /* Test file existence, using dircache of possible */
1119 bool file_exists(const char *file)
1121 int fd;
1123 if (!file || strlen(file) <= 0)
1124 return false;
1126 #ifdef HAVE_DIRCACHE
1127 if (dircache_is_enabled())
1128 return (dircache_get_entry_ptr(file) != NULL);
1129 #endif
1131 fd = open(file, O_RDONLY);
1132 if (fd < 0)
1133 return false;
1134 close(fd);
1135 return true;
1138 bool dir_exists(const char *path)
1140 DIR* d = opendir(path);
1141 if (!d)
1142 return false;
1143 closedir(d);
1144 return true;
1148 * removes the extension of filename (if it doesn't start with a .)
1149 * puts the result in buffer
1151 char *strip_extension(char* buffer, int buffer_size, const char *filename)
1153 char *dot = strrchr(filename, '.');
1154 int len;
1156 if (buffer_size <= 0)
1158 return NULL;
1161 buffer_size--; /* Make room for end nil */
1163 if (dot != 0 && filename[0] != '.')
1165 len = dot - filename;
1166 len = MIN(len, buffer_size);
1167 strncpy(buffer, filename, len);
1169 else
1171 len = buffer_size;
1172 strncpy(buffer, filename, buffer_size);
1175 buffer[len] = 0;
1177 return buffer;
1179 #endif /* !defined(__PCTOOL__) */
1181 #ifdef HAVE_LCD_COLOR
1183 * Helper function to convert a string of 6 hex digits to a native colour
1186 static int hex2dec(int c)
1188 return (((c) >= '0' && ((c) <= '9')) ? (c) - '0' :
1189 (toupper(c)) - 'A' + 10);
1192 int hex_to_rgb(const char* hex, int* color)
1194 int red, green, blue;
1195 int i = 0;
1197 while ((i < 6) && (isxdigit(hex[i])))
1198 i++;
1200 if (i < 6)
1201 return -1;
1203 red = (hex2dec(hex[0]) << 4) | hex2dec(hex[1]);
1204 green = (hex2dec(hex[2]) << 4) | hex2dec(hex[3]);
1205 blue = (hex2dec(hex[4]) << 4) | hex2dec(hex[5]);
1207 *color = LCD_RGBPACK(red,green,blue);
1209 return 0;
1211 #endif /* HAVE_LCD_COLOR */
1213 #ifdef HAVE_LCD_BITMAP
1214 /* A simplified scanf - used (at time of writing) by wps parsing functions.
1216 fmt - char array specifying the format of each list option. Valid values
1217 are: d - int
1218 s - string (sets pointer to string, without copying)
1219 c - hex colour (RGB888 - e.g. ff00ff)
1220 g - greyscale "colour" (0-3)
1222 sep - list separator (e.g. ',' or '|')
1223 str - string to parse, must be terminated by 0 or sep
1224 ... - pointers to store the parsed values
1226 return value - pointer to char after parsed data, 0 if there was an error.
1230 /* '0'-'3' are ASCII 0x30 to 0x33 */
1231 #define is0123(x) (((x) & 0xfc) == 0x30)
1233 const char* parse_list(const char *fmt, const char sep, const char* str, ...)
1235 va_list ap;
1236 const char* p = str;
1237 const char** s;
1238 int* d;
1240 va_start(ap, str);
1242 while (*fmt)
1244 /* Check for separator, if we're not at the start */
1245 if (p != str)
1247 if (*p != sep)
1248 goto err;
1249 p++;
1252 switch (*fmt++)
1254 case 's': /* string - return a pointer to it (not a copy) */
1255 s = va_arg(ap, const char **);
1257 *s = p;
1258 while (*p && *p != sep)
1259 p++;
1261 break;
1263 case 'd': /* int */
1264 d = va_arg(ap, int*);
1265 if (!isdigit(*p))
1266 goto err;
1268 *d = *p++ - '0';
1270 while (isdigit(*p))
1271 *d = (*d * 10) + (*p++ - '0');
1273 break;
1275 #ifdef HAVE_LCD_COLOR
1276 case 'c': /* colour (rrggbb - e.g. f3c1a8) */
1277 d = va_arg(ap, int*);
1279 if (hex_to_rgb(p, d) < 0)
1280 goto err;
1282 p += 6;
1284 break;
1285 #endif
1287 #if LCD_DEPTH == 2 || (defined(HAVE_REMOTE_LCD) && LCD_REMOTE_DEPTH == 2)
1288 case 'g': /* greyscale colour (0-3) */
1289 d = va_arg(ap, int*);
1291 if (is0123(*p))
1292 *d = *p++ - '0';
1293 else
1294 goto err;
1296 break;
1297 #endif
1299 default: /* Unknown format type */
1300 goto err;
1301 break;
1305 va_end(ap);
1306 return p;
1308 err:
1309 va_end(ap);
1310 return 0;
1312 #endif