Fixed m200v4 red build.
[kugel-rb.git] / apps / misc.c
blob8b734115497f1a03597bd9f1992a7e478830827e
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 "misc.h"
25 #include "lcd.h"
26 #include "file.h"
27 #ifdef __PCTOOL__
28 #include <stdint.h>
29 #include <stdarg.h>
30 #include <stdio.h>
31 #ifdef WPSEDITOR
32 #include "string.h"
33 #endif
34 #else
35 #include "sprintf.h"
36 #include "lang.h"
37 #include "string.h"
38 #include "dir.h"
39 #include "lcd-remote.h"
40 #include "errno.h"
41 #include "system.h"
42 #include "timefuncs.h"
43 #include "screens.h"
44 #include "talk.h"
45 #include "mpeg.h"
46 #include "audio.h"
47 #include "mp3_playback.h"
48 #include "settings.h"
49 #include "storage.h"
50 #include "ata_idle_notify.h"
51 #include "kernel.h"
52 #include "power.h"
53 #include "powermgmt.h"
54 #include "backlight.h"
55 #include "version.h"
56 #include "font.h"
57 #include "splash.h"
58 #include "tagcache.h"
59 #include "scrobbler.h"
60 #include "sound.h"
61 #include "playlist.h"
62 #include "yesno.h"
64 #ifdef IPOD_ACCESSORY_PROTOCOL
65 #include "iap.h"
66 #endif
68 #if (CONFIG_STORAGE & STORAGE_MMC)
69 #include "ata_mmc.h"
70 #endif
71 #include "tree.h"
72 #include "eeprom_settings.h"
73 #if defined(HAVE_RECORDING) && !defined(__PCTOOL__)
74 #include "recording.h"
75 #endif
76 #if defined(HAVE_LCD_BITMAP) && !defined(__PCTOOL__)
77 #include "bmp.h"
78 #include "icons.h"
79 #endif /* End HAVE_LCD_BITMAP */
80 #include "gui/gwps-common.h"
81 #include "bookmark.h"
83 #include "playback.h"
85 #ifdef BOOTFILE
86 #if !defined(USB_NONE) && !defined(USB_IPODSTYLE)
87 #include "rolo.h"
88 #include "yesno.h"
89 #endif
90 #endif
92 /* Format a large-range value for output, using the appropriate unit so that
93 * the displayed value is in the range 1 <= display < 1000 (1024 for "binary"
94 * units) if possible, and 3 significant digits are shown. If a buffer is
95 * given, the result is snprintf()'d into that buffer, otherwise the result is
96 * voiced.*/
97 char *output_dyn_value(char *buf, int buf_size, int value,
98 const unsigned char **units, bool bin_scale)
100 int scale = bin_scale ? 1024 : 1000;
101 int fraction = 0;
102 int unit_no = 0;
103 char tbuf[5];
105 while (value >= scale)
107 fraction = value % scale;
108 value /= scale;
109 unit_no++;
111 if (bin_scale)
112 fraction = fraction * 1000 / 1024;
114 if (value >= 100 || !unit_no)
115 tbuf[0] = '\0';
116 else if (value >= 10)
117 snprintf(tbuf, sizeof(tbuf), "%01d", fraction / 100);
118 else
119 snprintf(tbuf, sizeof(tbuf), "%02d", fraction / 10);
121 if (buf)
123 if (strlen(tbuf))
124 snprintf(buf, buf_size, "%d%s%s%s", value, str(LANG_POINT),
125 tbuf, P2STR(units[unit_no]));
126 else
127 snprintf(buf, buf_size, "%d%s", value, P2STR(units[unit_no]));
129 else
131 talk_fractional(tbuf, value, P2ID(units[unit_no]));
133 return buf;
136 /* Create a filename with a number part in a way that the number is 1
137 * higher than the highest numbered file matching the same pattern.
138 * It is allowed that buffer and path point to the same memory location,
139 * saving a strcpy(). Path must always be given without trailing slash.
140 * "num" can point to an int specifying the number to use or NULL or a value
141 * less than zero to number automatically. The final number used will also
142 * be returned in *num. If *num is >= 0 then *num will be incremented by
143 * one. */
144 char *create_numbered_filename(char *buffer, const char *path,
145 const char *prefix, const char *suffix,
146 int numberlen IF_CNFN_NUM_(, int *num))
148 DIR *dir;
149 struct dirent *entry;
150 int max_num;
151 int pathlen;
152 int prefixlen = strlen(prefix);
153 char fmtstring[12];
155 if (buffer != path)
156 strncpy(buffer, path, MAX_PATH);
158 pathlen = strlen(buffer);
160 #ifdef IF_CNFN_NUM
161 if (num && *num >= 0)
163 /* number specified */
164 max_num = *num;
166 else
167 #endif
169 /* automatic numbering */
170 max_num = 0;
172 dir = opendir(pathlen ? buffer : "/");
173 if (!dir)
174 return NULL;
176 while ((entry = readdir(dir)))
178 int curr_num;
180 if (strncasecmp((char *)entry->d_name, prefix, prefixlen)
181 || strcasecmp((char *)entry->d_name + prefixlen + numberlen, suffix))
182 continue;
184 curr_num = atoi((char *)entry->d_name + prefixlen);
185 if (curr_num > max_num)
186 max_num = curr_num;
189 closedir(dir);
192 max_num++;
194 snprintf(fmtstring, sizeof(fmtstring), "/%%s%%0%dd%%s", numberlen);
195 snprintf(buffer + pathlen, MAX_PATH - pathlen, fmtstring, prefix,
196 max_num, suffix);
198 #ifdef IF_CNFN_NUM
199 if (num)
200 *num = max_num;
201 #endif
203 return buffer;
207 #if CONFIG_RTC
208 /* Create a filename with a date+time part.
209 It is allowed that buffer and path point to the same memory location,
210 saving a strcpy(). Path must always be given without trailing slash.
211 unique_time as true makes the function wait until the current time has
212 changed. */
213 char *create_datetime_filename(char *buffer, const char *path,
214 const char *prefix, const char *suffix,
215 bool unique_time)
217 struct tm *tm = get_time();
218 static struct tm last_tm;
219 int pathlen;
221 while (unique_time && !memcmp(get_time(), &last_tm, sizeof (struct tm)))
222 sleep(HZ/10);
224 last_tm = *tm;
226 if (buffer != path)
227 strncpy(buffer, path, MAX_PATH);
229 pathlen = strlen(buffer);
230 snprintf(buffer + pathlen, MAX_PATH - pathlen,
231 "/%s%02d%02d%02d-%02d%02d%02d%s", prefix,
232 tm->tm_year % 100, tm->tm_mon + 1, tm->tm_mday,
233 tm->tm_hour, tm->tm_min, tm->tm_sec, suffix);
235 return buffer;
237 #endif /* CONFIG_RTC */
239 /* Ask the user if they really want to erase the current dynamic playlist
240 * returns true if the playlist should be replaced */
241 bool warn_on_pl_erase(void)
243 if (global_settings.warnon_erase_dynplaylist &&
244 !global_settings.party_mode &&
245 playlist_modified(NULL))
247 static const char *lines[] =
248 {ID2P(LANG_WARN_ERASEDYNPLAYLIST_PROMPT)};
249 static const struct text_message message={lines, 1};
251 return (gui_syncyesno_run(&message, NULL, NULL) == YESNO_YES);
253 else
254 return true;
257 /* Read (up to) a line of text from fd into buffer and return number of bytes
258 * read (which may be larger than the number of bytes stored in buffer). If
259 * an error occurs, -1 is returned (and buffer contains whatever could be
260 * read). A line is terminated by a LF char. Neither LF nor CR chars are
261 * stored in buffer.
263 int read_line(int fd, char* buffer, int buffer_size)
265 int count = 0;
266 int num_read = 0;
268 errno = 0;
270 while (count < buffer_size)
272 unsigned char c;
274 if (1 != read(fd, &c, 1))
275 break;
277 num_read++;
279 if ( c == '\n' )
280 break;
282 if ( c == '\r' )
283 continue;
285 buffer[count++] = c;
288 buffer[MIN(count, buffer_size - 1)] = 0;
290 return errno ? -1 : num_read;
293 /* Performance optimized version of the previous function. */
294 int fast_readline(int fd, char *buf, int buf_size, void *parameters,
295 int (*callback)(int n, const char *buf, void *parameters))
297 char *p, *next;
298 int rc, pos = 0;
299 int count = 0;
301 while ( 1 )
303 next = NULL;
305 rc = read(fd, &buf[pos], buf_size - pos - 1);
306 if (rc >= 0)
307 buf[pos+rc] = '\0';
309 if ( (p = strchr(buf, '\r')) != NULL)
311 *p = '\0';
312 next = ++p;
314 else
315 p = buf;
317 if ( (p = strchr(p, '\n')) != NULL)
319 *p = '\0';
320 next = ++p;
323 rc = callback(count, buf, parameters);
324 if (rc < 0)
325 return rc;
327 count++;
328 if (next)
330 pos = buf_size - ((long)next - (long)buf) - 1;
331 memmove(buf, next, pos);
333 else
334 break ;
337 return 0;
340 #ifdef HAVE_LCD_BITMAP
342 #if LCD_DEPTH == 16
343 #define BMP_COMPRESSION 3 /* BI_BITFIELDS */
344 #define BMP_NUMCOLORS 3
345 #else
346 #define BMP_COMPRESSION 0 /* BI_RGB */
347 #if LCD_DEPTH <= 8
348 #define BMP_NUMCOLORS (1 << LCD_DEPTH)
349 #else
350 #define BMP_NUMCOLORS 0
351 #endif
352 #endif
354 #if LCD_DEPTH == 1
355 #define BMP_BPP 1
356 #define BMP_LINESIZE ((LCD_WIDTH/8 + 3) & ~3)
357 #elif LCD_DEPTH <= 4
358 #define BMP_BPP 4
359 #define BMP_LINESIZE ((LCD_WIDTH/2 + 3) & ~3)
360 #elif LCD_DEPTH <= 8
361 #define BMP_BPP 8
362 #define BMP_LINESIZE ((LCD_WIDTH + 3) & ~3)
363 #elif LCD_DEPTH <= 16
364 #define BMP_BPP 16
365 #define BMP_LINESIZE ((LCD_WIDTH*2 + 3) & ~3)
366 #else
367 #define BMP_BPP 24
368 #define BMP_LINESIZE ((LCD_WIDTH*3 + 3) & ~3)
369 #endif
371 #define BMP_HEADERSIZE (54 + 4 * BMP_NUMCOLORS)
372 #define BMP_DATASIZE (BMP_LINESIZE * LCD_HEIGHT)
373 #define BMP_TOTALSIZE (BMP_HEADERSIZE + BMP_DATASIZE)
375 #define LE16_CONST(x) (x)&0xff, ((x)>>8)&0xff
376 #define LE32_CONST(x) (x)&0xff, ((x)>>8)&0xff, ((x)>>16)&0xff, ((x)>>24)&0xff
378 static const unsigned char bmpheader[] =
380 0x42, 0x4d, /* 'BM' */
381 LE32_CONST(BMP_TOTALSIZE), /* Total file size */
382 0x00, 0x00, 0x00, 0x00, /* Reserved */
383 LE32_CONST(BMP_HEADERSIZE), /* Offset to start of pixel data */
385 0x28, 0x00, 0x00, 0x00, /* Size of (2nd) header */
386 LE32_CONST(LCD_WIDTH), /* Width in pixels */
387 LE32_CONST(LCD_HEIGHT), /* Height in pixels */
388 0x01, 0x00, /* Number of planes (always 1) */
389 LE16_CONST(BMP_BPP), /* Bits per pixel 1/4/8/16/24 */
390 LE32_CONST(BMP_COMPRESSION),/* Compression mode */
391 LE32_CONST(BMP_DATASIZE), /* Size of bitmap data */
392 0xc4, 0x0e, 0x00, 0x00, /* Horizontal resolution (pixels/meter) */
393 0xc4, 0x0e, 0x00, 0x00, /* Vertical resolution (pixels/meter) */
394 LE32_CONST(BMP_NUMCOLORS), /* Number of used colours */
395 LE32_CONST(BMP_NUMCOLORS), /* Number of important colours */
397 #if LCD_DEPTH == 1
398 #ifdef MROBE_100
399 2, 2, 94, 0x00, /* Colour #0 */
400 3, 6, 241, 0x00 /* Colour #1 */
401 #else
402 0x90, 0xee, 0x90, 0x00, /* Colour #0 */
403 0x00, 0x00, 0x00, 0x00 /* Colour #1 */
404 #endif
405 #elif LCD_DEPTH == 2
406 0xe6, 0xd8, 0xad, 0x00, /* Colour #0 */
407 0x99, 0x90, 0x73, 0x00, /* Colour #1 */
408 0x4c, 0x48, 0x39, 0x00, /* Colour #2 */
409 0x00, 0x00, 0x00, 0x00 /* Colour #3 */
410 #elif LCD_DEPTH == 16
411 0x00, 0xf8, 0x00, 0x00, /* red bitfield mask */
412 0xe0, 0x07, 0x00, 0x00, /* green bitfield mask */
413 0x1f, 0x00, 0x00, 0x00 /* blue bitfield mask */
414 #endif
417 static void (*screen_dump_hook)(int fh) = NULL;
419 void screen_dump(void)
421 int fh;
422 char filename[MAX_PATH];
423 int bx, by;
424 #if LCD_DEPTH == 1
425 static unsigned char line_block[8][BMP_LINESIZE];
426 #elif LCD_DEPTH == 2
427 #if LCD_PIXELFORMAT == HORIZONTAL_PACKING
428 static unsigned char line_block[BMP_LINESIZE];
429 #elif LCD_PIXELFORMAT == VERTICAL_PACKING
430 static unsigned char line_block[4][BMP_LINESIZE];
431 #elif LCD_PIXELFORMAT == VERTICAL_INTERLEAVED
432 static unsigned char line_block[8][BMP_LINESIZE];
433 #endif
434 #elif LCD_DEPTH == 16
435 static unsigned short line_block[BMP_LINESIZE/2];
436 #endif
438 #if CONFIG_RTC
439 create_datetime_filename(filename, "", "dump ", ".bmp", false);
440 #else
441 create_numbered_filename(filename, "", "dump_", ".bmp", 4
442 IF_CNFN_NUM_(, NULL));
443 #endif
445 fh = creat(filename);
446 if (fh < 0)
447 return;
449 if (screen_dump_hook)
451 screen_dump_hook(fh);
453 else
455 write(fh, bmpheader, sizeof(bmpheader));
457 /* BMP image goes bottom up */
458 #if LCD_DEPTH == 1
459 for (by = LCD_FBHEIGHT - 1; by >= 0; by--)
461 unsigned char *src = &lcd_framebuffer[by][0];
462 unsigned char *dst = &line_block[0][0];
464 memset(line_block, 0, sizeof(line_block));
465 for (bx = LCD_WIDTH/8; bx > 0; bx--)
467 unsigned dst_mask = 0x80;
468 int ix;
470 for (ix = 8; ix > 0; ix--)
472 unsigned char *dst_blk = dst;
473 unsigned src_byte = *src++;
474 int iy;
476 for (iy = 8; iy > 0; iy--)
478 if (src_byte & 0x80)
479 *dst_blk |= dst_mask;
480 src_byte <<= 1;
481 dst_blk += BMP_LINESIZE;
483 dst_mask >>= 1;
485 dst++;
488 write(fh, line_block, sizeof(line_block));
490 #elif LCD_DEPTH == 2
491 #if LCD_PIXELFORMAT == HORIZONTAL_PACKING
492 for (by = LCD_FBHEIGHT - 1; by >= 0; by--)
494 unsigned char *src = &lcd_framebuffer[by][0];
495 unsigned char *dst = line_block;
497 memset(line_block, 0, sizeof(line_block));
498 for (bx = LCD_FBWIDTH; bx > 0; bx--)
500 unsigned src_byte = *src++;
502 *dst++ = ((src_byte >> 2) & 0x30) | ((src_byte >> 4) & 0x03);
503 *dst++ = ((src_byte << 2) & 0x30) | (src_byte & 0x03);
506 write(fh, line_block, sizeof(line_block));
508 #elif LCD_PIXELFORMAT == VERTICAL_PACKING
509 for (by = LCD_FBHEIGHT - 1; by >= 0; by--)
511 unsigned char *src = &lcd_framebuffer[by][0];
512 unsigned char *dst = &line_block[3][0];
514 memset(line_block, 0, sizeof(line_block));
515 for (bx = LCD_WIDTH/2; bx > 0; bx--)
517 unsigned char *dst_blk = dst++;
518 unsigned src_byte0 = *src++ << 4;
519 unsigned src_byte1 = *src++;
520 int iy;
522 for (iy = 4; iy > 0; iy--)
524 *dst_blk = (src_byte0 & 0x30) | (src_byte1 & 0x03);
525 src_byte0 >>= 2;
526 src_byte1 >>= 2;
527 dst_blk -= BMP_LINESIZE;
531 write(fh, line_block, sizeof(line_block));
533 #elif LCD_PIXELFORMAT == VERTICAL_INTERLEAVED
534 for (by = LCD_FBHEIGHT - 1; by >= 0; by--)
536 const fb_data *src = &lcd_framebuffer[by][0];
537 unsigned char *dst = &line_block[7][0];
539 memset(line_block, 0, sizeof(line_block));
540 for (bx = LCD_WIDTH/2; bx > 0; bx--)
542 unsigned char *dst_blk = dst++;
543 unsigned src_data0 = *src++ << 4;
544 unsigned src_data1 = *src++;
545 int iy;
547 for (iy = 8; iy > 0; iy--)
549 *dst_blk = (src_data0 & 0x10) | (src_data1 & 0x01)
550 | ((src_data0 & 0x1000) | (src_data1 & 0x0100)) >> 7;
551 src_data0 >>= 1;
552 src_data1 >>= 1;
553 dst_blk -= BMP_LINESIZE;
557 write(fh, line_block, sizeof(line_block));
559 #endif
560 #elif LCD_DEPTH == 16
561 for (by = LCD_HEIGHT - 1; by >= 0; by--)
563 unsigned short *src = &lcd_framebuffer[by][0];
564 unsigned short *dst = line_block;
566 memset(line_block, 0, sizeof(line_block));
567 for (bx = LCD_WIDTH; bx > 0; bx--)
569 #if (LCD_PIXELFORMAT == RGB565SWAPPED)
570 /* iPod LCD data is big endian although the CPU is not */
571 *dst++ = htobe16(*src++);
572 #else
573 *dst++ = htole16(*src++);
574 #endif
577 write(fh, line_block, sizeof(line_block));
579 #endif /* LCD_DEPTH */
582 close(fh);
585 void screen_dump_set_hook(void (*hook)(int fh))
587 screen_dump_hook = hook;
590 #endif /* HAVE_LCD_BITMAP */
592 /* parse a line from a configuration file. the line format is:
594 name: value
596 Any whitespace before setting name or value (after ':') is ignored.
597 A # as first non-whitespace character discards the whole line.
598 Function sets pointers to null-terminated setting name and value.
599 Returns false if no valid config entry was found.
602 bool settings_parseline(char* line, char** name, char** value)
604 char* ptr;
606 while ( isspace(*line) )
607 line++;
609 if ( *line == '#' )
610 return false;
612 ptr = strchr(line, ':');
613 if ( !ptr )
614 return false;
616 *name = line;
617 *ptr = 0;
618 ptr++;
619 while (isspace(*ptr))
620 ptr++;
621 *value = ptr;
622 return true;
625 static void system_flush(void)
627 scrobbler_shutdown();
628 playlist_shutdown();
629 tree_flush();
630 call_storage_idle_notifys(true); /*doesnt work on usb and shutdown from ata thread */
633 static void system_restore(void)
635 tree_restore();
636 scrobbler_init();
639 static bool clean_shutdown(void (*callback)(void *), void *parameter)
641 #ifdef SIMULATOR
642 (void)callback;
643 (void)parameter;
644 bookmark_autobookmark();
645 call_storage_idle_notifys(true);
646 exit(0);
647 #else
648 long msg_id = -1;
649 int i;
651 scrobbler_poweroff();
653 #if CONFIG_CHARGING && !defined(HAVE_POWEROFF_WHILE_CHARGING)
654 if(!charger_inserted())
655 #endif
657 bool batt_safe = battery_level_safe();
658 int audio_stat = audio_status();
660 FOR_NB_SCREENS(i)
661 screens[i].clear_display();
663 if (batt_safe)
665 #ifdef HAVE_TAGCACHE
666 if (!tagcache_prepare_shutdown())
668 cancel_shutdown();
669 splash(HZ, ID2P(LANG_TAGCACHE_BUSY));
670 return false;
672 #endif
673 if (battery_level() > 10)
674 splash(0, str(LANG_SHUTTINGDOWN));
675 else
677 msg_id = LANG_WARNING_BATTERY_LOW;
678 splashf(0, "%s %s", str(LANG_WARNING_BATTERY_LOW),
679 str(LANG_SHUTTINGDOWN));
682 else
684 msg_id = LANG_WARNING_BATTERY_EMPTY;
685 splashf(0, "%s %s", str(LANG_WARNING_BATTERY_EMPTY),
686 str(LANG_SHUTTINGDOWN));
689 if (global_settings.fade_on_stop
690 && (audio_stat & AUDIO_STATUS_PLAY))
692 fade(false, false);
695 if (batt_safe) /* do not save on critical battery */
697 #if defined(HAVE_RECORDING) && CONFIG_CODEC == SWCODEC
698 if (audio_stat & AUDIO_STATUS_RECORD)
700 rec_command(RECORDING_CMD_STOP);
701 /* wait for stop to complete */
702 while (audio_status() & AUDIO_STATUS_RECORD)
703 sleep(1);
705 #endif
706 bookmark_autobookmark();
708 /* audio_stop_recording == audio_stop for HWCODEC */
709 audio_stop();
711 if (callback != NULL)
712 callback(parameter);
714 #if CONFIG_CODEC != SWCODEC
715 /* wait for audio_stop or audio_stop_recording to complete */
716 while (audio_status())
717 sleep(1);
718 #endif
720 #if defined(HAVE_RECORDING) && CONFIG_CODEC == SWCODEC
721 audio_close_recording();
722 #endif
724 if(global_settings.talk_menu)
726 bool enqueue = false;
727 if(msg_id != -1)
729 talk_id(msg_id, enqueue);
730 enqueue = true;
732 talk_id(LANG_SHUTTINGDOWN, enqueue);
733 #if CONFIG_CODEC == SWCODEC
734 voice_wait();
735 #endif
738 system_flush();
739 #ifdef HAVE_EEPROM_SETTINGS
740 if (firmware_settings.initialized)
742 firmware_settings.disk_clean = true;
743 firmware_settings.bl_version = 0;
744 eeprom_settings_store();
746 #endif
748 #ifdef HAVE_DIRCACHE
749 else
750 dircache_disable();
751 #endif
753 shutdown_hw();
755 #endif
756 return false;
759 bool list_stop_handler(void)
761 bool ret = false;
763 /* Stop the music if it is playing */
764 if(audio_status())
766 if (!global_settings.party_mode)
768 if (global_settings.fade_on_stop)
769 fade(false, false);
770 bookmark_autobookmark();
771 audio_stop();
772 ret = true; /* bookmarking can make a refresh necessary */
775 #if CONFIG_CHARGING
776 #if (CONFIG_KEYPAD == RECORDER_PAD) && !defined(HAVE_SW_POWEROFF)
777 else
779 if (charger_inserted())
780 charging_splash();
781 else
782 shutdown_screen(); /* won't return if shutdown actually happens */
784 ret = true; /* screen is dirty, caller needs to refresh */
786 #endif
787 #ifndef HAVE_POWEROFF_WHILE_CHARGING
789 static long last_off = 0;
791 if (TIME_BEFORE(current_tick, last_off + HZ/2))
793 if (charger_inserted())
795 charging_splash();
796 ret = true; /* screen is dirty, caller needs to refresh */
799 last_off = current_tick;
801 #endif
802 #endif /* CONFIG_CHARGING */
803 return ret;
806 #if CONFIG_CHARGING
807 static bool waiting_to_resume_play = false;
808 static long play_resume_tick;
810 static void car_adapter_mode_processing(bool inserted)
812 if (global_settings.car_adapter_mode)
814 if(inserted)
817 * Just got plugged in, delay & resume if we were playing
819 if (audio_status() & AUDIO_STATUS_PAUSE)
821 /* delay resume a bit while the engine is cranking */
822 play_resume_tick = current_tick + HZ*5;
823 waiting_to_resume_play = true;
826 else
829 * Just got unplugged, pause if playing
831 if ((audio_status() & AUDIO_STATUS_PLAY) &&
832 !(audio_status() & AUDIO_STATUS_PAUSE))
834 if (global_settings.fade_on_stop)
835 fade(false, false);
836 else
837 audio_pause();
839 waiting_to_resume_play = false;
844 static void car_adapter_tick(void)
846 if (waiting_to_resume_play)
848 if (TIME_AFTER(current_tick, play_resume_tick))
850 if (audio_status() & AUDIO_STATUS_PAUSE)
852 queue_broadcast(SYS_CAR_ADAPTER_RESUME, 0);
854 waiting_to_resume_play = false;
859 void car_adapter_mode_init(void)
861 tick_add_task(car_adapter_tick);
863 #endif
865 #ifdef HAVE_HEADPHONE_DETECTION
866 static void unplug_change(bool inserted)
868 static bool headphone_caused_pause = false;
870 if (global_settings.unplug_mode)
872 int audio_stat = audio_status();
873 if (inserted)
875 if ((audio_stat & AUDIO_STATUS_PLAY) &&
876 headphone_caused_pause &&
877 global_settings.unplug_mode > 1 )
878 audio_resume();
879 backlight_on();
880 headphone_caused_pause = false;
881 } else {
882 if ((audio_stat & AUDIO_STATUS_PLAY) &&
883 !(audio_stat & AUDIO_STATUS_PAUSE))
885 headphone_caused_pause = true;
886 audio_pause();
888 if (global_settings.unplug_rw)
890 if (audio_current_track()->elapsed >
891 (unsigned long)(global_settings.unplug_rw*1000))
892 audio_ff_rewind(audio_current_track()->elapsed -
893 (global_settings.unplug_rw*1000));
894 else
895 audio_ff_rewind(0);
901 #endif
903 long default_event_handler_ex(long event, void (*callback)(void *), void *parameter)
905 switch(event)
907 case SYS_BATTERY_UPDATE:
908 if(global_settings.talk_battery_level)
910 talk_ids(true, VOICE_PAUSE, VOICE_PAUSE,
911 LANG_BATTERY_TIME,
912 TALK_ID(battery_level(), UNIT_PERCENT),
913 VOICE_PAUSE);
914 talk_force_enqueue_next();
916 break;
917 case SYS_USB_CONNECTED:
918 if (callback != NULL)
919 callback(parameter);
920 #if (CONFIG_STORAGE & STORAGE_MMC)
921 if (!mmc_touched() ||
922 (mmc_remove_request() == SYS_HOTSWAP_EXTRACTED))
923 #endif
925 system_flush();
926 #ifdef BOOTFILE
927 #if !defined(USB_NONE) && !defined(USB_IPODSTYLE)
928 check_bootfile(false); /* gets initial size */
929 #endif
930 #endif
931 usb_screen();
932 #ifdef BOOTFILE
933 #if !defined(USB_NONE) && !defined(USB_IPODSTYLE)
934 check_bootfile(true);
935 #endif
936 #endif
937 system_restore();
939 return SYS_USB_CONNECTED;
940 case SYS_POWEROFF:
941 if (!clean_shutdown(callback, parameter))
942 return SYS_POWEROFF;
943 break;
944 #if CONFIG_CHARGING
945 case SYS_CHARGER_CONNECTED:
946 car_adapter_mode_processing(true);
947 return SYS_CHARGER_CONNECTED;
949 case SYS_CHARGER_DISCONNECTED:
950 car_adapter_mode_processing(false);
951 return SYS_CHARGER_DISCONNECTED;
953 case SYS_CAR_ADAPTER_RESUME:
954 audio_resume();
955 return SYS_CAR_ADAPTER_RESUME;
956 #endif
957 #ifdef HAVE_HEADPHONE_DETECTION
958 case SYS_PHONE_PLUGGED:
959 unplug_change(true);
960 return SYS_PHONE_PLUGGED;
962 case SYS_PHONE_UNPLUGGED:
963 unplug_change(false);
964 return SYS_PHONE_UNPLUGGED;
965 #endif
966 #ifdef IPOD_ACCESSORY_PROTOCOL
967 case SYS_IAP_PERIODIC:
968 iap_periodic();
969 return SYS_IAP_PERIODIC;
970 case SYS_IAP_HANDLEPKT:
971 iap_handlepkt();
972 return SYS_IAP_HANDLEPKT;
973 #endif
975 return 0;
978 long default_event_handler(long event)
980 return default_event_handler_ex(event, NULL, NULL);
983 int show_logo( void )
985 #ifdef HAVE_LCD_BITMAP
986 char version[32];
987 int font_h, font_w;
989 snprintf(version, sizeof(version), "Ver. %s", appsversion);
991 lcd_clear_display();
992 #ifdef SANSA_CLIP /* display the logo in the blue area of the screen */
993 lcd_setfont(FONT_SYSFIXED);
994 lcd_getstringsize((unsigned char *)"A", &font_w, &font_h);
995 lcd_putsxy((LCD_WIDTH/2) - ((strlen(version)*font_w)/2),
996 0, (unsigned char *)version);
997 lcd_bitmap(rockboxlogo, 0, 16, BMPWIDTH_rockboxlogo, BMPHEIGHT_rockboxlogo);
998 #else
999 lcd_bitmap(rockboxlogo, 0, 10, BMPWIDTH_rockboxlogo, BMPHEIGHT_rockboxlogo);
1000 lcd_setfont(FONT_SYSFIXED);
1001 lcd_getstringsize((unsigned char *)"A", &font_w, &font_h);
1002 lcd_putsxy((LCD_WIDTH/2) - ((strlen(version)*font_w)/2),
1003 LCD_HEIGHT-font_h, (unsigned char *)version);
1004 #endif
1005 lcd_setfont(FONT_UI);
1007 #else
1008 char *rockbox = " ROCKbox!";
1010 lcd_clear_display();
1011 lcd_double_height(true);
1012 lcd_puts(0, 0, rockbox);
1013 lcd_puts_scroll(0, 1, appsversion);
1014 #endif
1015 lcd_update();
1017 #ifdef HAVE_REMOTE_LCD
1018 lcd_remote_clear_display();
1019 lcd_remote_bitmap(remote_rockboxlogo, 0, 10, BMPWIDTH_remote_rockboxlogo,
1020 BMPHEIGHT_remote_rockboxlogo);
1021 lcd_remote_setfont(FONT_SYSFIXED);
1022 lcd_remote_getstringsize((unsigned char *)"A", &font_w, &font_h);
1023 lcd_remote_putsxy((LCD_REMOTE_WIDTH/2) - ((strlen(version)*font_w)/2),
1024 LCD_REMOTE_HEIGHT-font_h, (unsigned char *)version);
1025 lcd_remote_setfont(FONT_UI);
1026 lcd_remote_update();
1027 #endif
1029 return 0;
1032 #if CONFIG_CODEC == SWCODEC
1033 int get_replaygain_mode(bool have_track_gain, bool have_album_gain)
1035 int type;
1037 bool track = ((global_settings.replaygain_type == REPLAYGAIN_TRACK)
1038 || ((global_settings.replaygain_type == REPLAYGAIN_SHUFFLE)
1039 && global_settings.playlist_shuffle));
1041 type = (!track && have_album_gain) ? REPLAYGAIN_ALBUM
1042 : have_track_gain ? REPLAYGAIN_TRACK : -1;
1044 return type;
1046 #endif
1048 #ifdef BOOTFILE
1049 #if !defined(USB_NONE) && !defined(USB_IPODSTYLE)
1051 memorize/compare details about the BOOTFILE
1052 we don't use dircache because it may not be up to date after
1053 USB disconnect (scanning in the background)
1055 void check_bootfile(bool do_rolo)
1057 static unsigned short wrtdate = 0;
1058 static unsigned short wrttime = 0;
1059 DIR* dir = NULL;
1060 struct dirent* entry = NULL;
1062 /* 1. open BOOTDIR and find the BOOTFILE dir entry */
1063 dir = opendir(BOOTDIR);
1065 if(!dir) return; /* do we want an error splash? */
1067 /* loop all files in BOOTDIR */
1068 while(0 != (entry = readdir(dir)))
1070 if(!strcasecmp(entry->d_name, BOOTFILE))
1072 /* found the bootfile */
1073 if(wrtdate && do_rolo)
1075 if((entry->wrtdate != wrtdate) ||
1076 (entry->wrttime != wrttime))
1078 static const char *lines[] = { ID2P(LANG_BOOT_CHANGED),
1079 ID2P(LANG_REBOOT_NOW) };
1080 static const struct text_message message={ lines, 2 };
1081 button_clear_queue(); /* Empty the keyboard buffer */
1082 if(gui_syncyesno_run(&message, NULL, NULL) == YESNO_YES)
1083 rolo_load(BOOTDIR "/" BOOTFILE);
1086 wrtdate = entry->wrtdate;
1087 wrttime = entry->wrttime;
1090 closedir(dir);
1092 #endif
1093 #endif
1095 /* check range, set volume and save settings */
1096 void setvol(void)
1098 const int min_vol = sound_min(SOUND_VOLUME);
1099 const int max_vol = sound_max(SOUND_VOLUME);
1100 if (global_settings.volume < min_vol)
1101 global_settings.volume = min_vol;
1102 if (global_settings.volume > max_vol)
1103 global_settings.volume = max_vol;
1104 sound_set_volume(global_settings.volume);
1105 settings_save();
1108 char* strrsplt(char* str, int c)
1110 char* s = strrchr(str, c);
1112 if (s != NULL)
1114 *s++ = '\0';
1116 else
1118 s = str;
1121 return s;
1124 /* Test file existence, using dircache of possible */
1125 bool file_exists(const char *file)
1127 int fd;
1129 if (!file || strlen(file) <= 0)
1130 return false;
1132 #ifdef HAVE_DIRCACHE
1133 if (dircache_is_enabled())
1134 return (dircache_get_entry_ptr(file) != NULL);
1135 #endif
1137 fd = open(file, O_RDONLY);
1138 if (fd < 0)
1139 return false;
1140 close(fd);
1141 return true;
1144 bool dir_exists(const char *path)
1146 DIR* d = opendir(path);
1147 if (!d)
1148 return false;
1149 closedir(d);
1150 return true;
1154 * removes the extension of filename (if it doesn't start with a .)
1155 * puts the result in buffer
1157 char *strip_extension(char* buffer, int buffer_size, const char *filename)
1159 char *dot = strrchr(filename, '.');
1160 int len;
1162 if (buffer_size <= 0)
1164 return NULL;
1167 buffer_size--; /* Make room for end nil */
1169 if (dot != 0 && filename[0] != '.')
1171 len = dot - filename;
1172 len = MIN(len, buffer_size);
1173 strncpy(buffer, filename, len);
1175 else
1177 len = buffer_size;
1178 strncpy(buffer, filename, buffer_size);
1181 buffer[len] = 0;
1183 return buffer;
1185 #endif /* !defined(__PCTOOL__) */
1187 /* Format time into buf.
1189 * buf - buffer to format to.
1190 * buf_size - size of buffer.
1191 * t - time to format, in milliseconds.
1193 void format_time(char* buf, int buf_size, long t)
1195 if ( t < 3600000 )
1197 snprintf(buf, buf_size, "%d:%02d",
1198 (int) (t / 60000), (int) (t % 60000 / 1000));
1200 else
1202 snprintf(buf, buf_size, "%d:%02d:%02d",
1203 (int) (t / 3600000), (int) (t % 3600000 / 60000),
1204 (int) (t % 60000 / 1000));
1209 /** Open a UTF-8 file and set file descriptor to first byte after BOM.
1210 * If no BOM is present this behaves like open().
1211 * If the file is opened for writing and O_TRUNC is set, write a BOM to
1212 * the opened file and leave the file pointer set after the BOM.
1214 #define BOM "\xef\xbb\xbf"
1215 #define BOM_SIZE 3
1217 int open_utf8(const char* pathname, int flags)
1219 int fd;
1220 unsigned char bom[BOM_SIZE];
1222 fd = open(pathname, flags);
1223 if(fd < 0)
1224 return fd;
1226 if(flags & (O_TRUNC | O_WRONLY))
1228 write(fd, BOM, BOM_SIZE);
1230 else
1232 read(fd, bom, BOM_SIZE);
1233 /* check for BOM */
1234 if(memcmp(bom, BOM, BOM_SIZE))
1235 lseek(fd, 0, SEEK_SET);
1237 return fd;
1241 #ifdef HAVE_LCD_COLOR
1243 * Helper function to convert a string of 6 hex digits to a native colour
1246 static int hex2dec(int c)
1248 return (((c) >= '0' && ((c) <= '9')) ? (c) - '0' :
1249 (toupper(c)) - 'A' + 10);
1252 int hex_to_rgb(const char* hex, int* color)
1254 int red, green, blue;
1255 int i = 0;
1257 while ((i < 6) && (isxdigit(hex[i])))
1258 i++;
1260 if (i < 6)
1261 return -1;
1263 red = (hex2dec(hex[0]) << 4) | hex2dec(hex[1]);
1264 green = (hex2dec(hex[2]) << 4) | hex2dec(hex[3]);
1265 blue = (hex2dec(hex[4]) << 4) | hex2dec(hex[5]);
1267 *color = LCD_RGBPACK(red,green,blue);
1269 return 0;
1271 #endif /* HAVE_LCD_COLOR */
1273 #ifdef HAVE_LCD_BITMAP
1274 /* A simplified scanf - used (at time of writing) by wps parsing functions.
1276 fmt - char array specifying the format of each list option. Valid values
1277 are: d - int
1278 s - string (sets pointer to string, without copying)
1279 c - hex colour (RGB888 - e.g. ff00ff)
1280 g - greyscale "colour" (0-3)
1281 set_vals - if not NULL 1 is set in the bitplace if the item was read OK
1282 0 if not read.
1283 first item is LSB, (max 32 items! )
1284 Stops parseing if an item is invalid unless the item == '-'
1285 sep - list separator (e.g. ',' or '|')
1286 str - string to parse, must be terminated by 0 or sep
1287 ... - pointers to store the parsed values
1289 return value - pointer to char after parsed data, 0 if there was an error.
1293 /* '0'-'3' are ASCII 0x30 to 0x33 */
1294 #define is0123(x) (((x) & 0xfc) == 0x30)
1296 const char* parse_list(const char *fmt, uint32_t *set_vals,
1297 const char sep, const char* str, ...)
1299 va_list ap;
1300 const char* p = str, *f = fmt;
1301 const char** s;
1302 int* d;
1303 bool set;
1304 int i=0;
1306 va_start(ap, str);
1307 if (set_vals)
1308 *set_vals = 0;
1309 while (*fmt)
1311 /* Check for separator, if we're not at the start */
1312 if (f != fmt)
1314 if (*p != sep)
1315 goto err;
1316 p++;
1318 set = false;
1319 switch (*fmt++)
1321 case 's': /* string - return a pointer to it (not a copy) */
1322 s = va_arg(ap, const char **);
1324 *s = p;
1325 while (*p && *p != sep)
1326 p++;
1327 set = (s[0][0]!='-') && (s[0][1]!=sep) ;
1328 break;
1330 case 'd': /* int */
1331 d = va_arg(ap, int*);
1332 if (!isdigit(*p))
1334 if (!set_vals || *p != '-')
1335 goto err;
1336 while (*p && *p != sep)
1337 p++;
1339 else
1341 *d = *p++ - '0';
1342 while (isdigit(*p))
1343 *d = (*d * 10) + (*p++ - '0');
1344 set = true;
1347 break;
1349 #ifdef HAVE_LCD_COLOR
1350 case 'c': /* colour (rrggbb - e.g. f3c1a8) */
1351 d = va_arg(ap, int*);
1353 if (hex_to_rgb(p, d) < 0)
1355 if (!set_vals || *p != '-')
1356 goto err;
1357 while (*p && *p != sep)
1358 p++;
1360 else
1362 p += 6;
1363 set = true;
1366 break;
1367 #endif
1369 #if LCD_DEPTH == 2 || (defined(HAVE_REMOTE_LCD) && LCD_REMOTE_DEPTH == 2)
1370 case 'g': /* greyscale colour (0-3) */
1371 d = va_arg(ap, int*);
1373 if (is0123(*p))
1375 *d = *p++ - '0';
1376 set = true;
1378 else if (!set_vals || *p != '-')
1379 goto err;
1380 else
1382 while (*p && *p != sep)
1383 p++;
1386 break;
1387 #endif
1389 default: /* Unknown format type */
1390 goto err;
1391 break;
1393 if (set_vals && set)
1394 *set_vals |= (1<<i);
1395 i++;
1398 va_end(ap);
1399 return p;
1401 err:
1402 va_end(ap);
1403 return 0;
1405 #endif