Don't objcopy simulator plugins.
[kugel-rb.git] / apps / misc.c
blob9559b0c44f34698d42a6319896208e2cae601dc2
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 #if (CONFIG_STORAGE & STORAGE_MMC)
65 #include "ata_mmc.h"
66 #endif
67 #include "tree.h"
68 #include "eeprom_settings.h"
69 #if defined(HAVE_RECORDING) && !defined(__PCTOOL__)
70 #include "recording.h"
71 #endif
72 #if defined(HAVE_LCD_BITMAP) && !defined(__PCTOOL__)
73 #include "bmp.h"
74 #include "icons.h"
75 #endif /* End HAVE_LCD_BITMAP */
76 #include "gui/gwps-common.h"
77 #include "bookmark.h"
79 #include "playback.h"
81 #ifdef BOOTFILE
82 #if !defined(USB_NONE) && !defined(USB_IPODSTYLE)
83 #include "rolo.h"
84 #include "yesno.h"
85 #endif
86 #endif
88 /* Format a large-range value for output, using the appropriate unit so that
89 * the displayed value is in the range 1 <= display < 1000 (1024 for "binary"
90 * units) if possible, and 3 significant digits are shown. If a buffer is
91 * given, the result is snprintf()'d into that buffer, otherwise the result is
92 * voiced.*/
93 char *output_dyn_value(char *buf, int buf_size, int value,
94 const unsigned char **units, bool bin_scale)
96 int scale = bin_scale ? 1024 : 1000;
97 int fraction = 0;
98 int unit_no = 0;
99 char tbuf[5];
101 while (value >= scale)
103 fraction = value % scale;
104 value /= scale;
105 unit_no++;
107 if (bin_scale)
108 fraction = fraction * 1000 / 1024;
110 if (value >= 100 || !unit_no)
111 tbuf[0] = '\0';
112 else if (value >= 10)
113 snprintf(tbuf, sizeof(tbuf), "%01d", fraction / 100);
114 else
115 snprintf(tbuf, sizeof(tbuf), "%02d", fraction / 10);
117 if (buf)
119 if (strlen(tbuf))
120 snprintf(buf, buf_size, "%d%s%s%s", value, str(LANG_POINT),
121 tbuf, P2STR(units[unit_no]));
122 else
123 snprintf(buf, buf_size, "%d%s", value, P2STR(units[unit_no]));
125 else
127 talk_fractional(tbuf, value, P2ID(units[unit_no]));
129 return buf;
132 /* Create a filename with a number part in a way that the number is 1
133 * higher than the highest numbered file matching the same pattern.
134 * It is allowed that buffer and path point to the same memory location,
135 * saving a strcpy(). Path must always be given without trailing slash.
136 * "num" can point to an int specifying the number to use or NULL or a value
137 * less than zero to number automatically. The final number used will also
138 * be returned in *num. If *num is >= 0 then *num will be incremented by
139 * one. */
140 char *create_numbered_filename(char *buffer, const char *path,
141 const char *prefix, const char *suffix,
142 int numberlen IF_CNFN_NUM_(, int *num))
144 DIR *dir;
145 struct dirent *entry;
146 int max_num;
147 int pathlen;
148 int prefixlen = strlen(prefix);
149 char fmtstring[12];
151 if (buffer != path)
152 strncpy(buffer, path, MAX_PATH);
154 pathlen = strlen(buffer);
156 #ifdef IF_CNFN_NUM
157 if (num && *num >= 0)
159 /* number specified */
160 max_num = *num;
162 else
163 #endif
165 /* automatic numbering */
166 max_num = 0;
168 dir = opendir(pathlen ? buffer : "/");
169 if (!dir)
170 return NULL;
172 while ((entry = readdir(dir)))
174 int curr_num;
176 if (strncasecmp((char *)entry->d_name, prefix, prefixlen)
177 || strcasecmp((char *)entry->d_name + prefixlen + numberlen, suffix))
178 continue;
180 curr_num = atoi((char *)entry->d_name + prefixlen);
181 if (curr_num > max_num)
182 max_num = curr_num;
185 closedir(dir);
188 max_num++;
190 snprintf(fmtstring, sizeof(fmtstring), "/%%s%%0%dd%%s", numberlen);
191 snprintf(buffer + pathlen, MAX_PATH - pathlen, fmtstring, prefix,
192 max_num, suffix);
194 #ifdef IF_CNFN_NUM
195 if (num)
196 *num = max_num;
197 #endif
199 return buffer;
203 #if CONFIG_RTC
204 /* Create a filename with a date+time part.
205 It is allowed that buffer and path point to the same memory location,
206 saving a strcpy(). Path must always be given without trailing slash.
207 unique_time as true makes the function wait until the current time has
208 changed. */
209 char *create_datetime_filename(char *buffer, const char *path,
210 const char *prefix, const char *suffix,
211 bool unique_time)
213 struct tm *tm = get_time();
214 static struct tm last_tm;
215 int pathlen;
217 while (unique_time && !memcmp(get_time(), &last_tm, sizeof (struct tm)))
218 sleep(HZ/10);
220 last_tm = *tm;
222 if (buffer != path)
223 strncpy(buffer, path, MAX_PATH);
225 pathlen = strlen(buffer);
226 snprintf(buffer + pathlen, MAX_PATH - pathlen,
227 "/%s%02d%02d%02d-%02d%02d%02d%s", prefix,
228 tm->tm_year % 100, tm->tm_mon + 1, tm->tm_mday,
229 tm->tm_hour, tm->tm_min, tm->tm_sec, suffix);
231 return buffer;
233 #endif /* CONFIG_RTC */
235 /* Ask the user if they really want to erase the current dynamic playlist
236 * returns true if the playlist should be replaced */
237 bool warn_on_pl_erase(void)
239 if (global_settings.warnon_erase_dynplaylist &&
240 !global_settings.party_mode &&
241 playlist_modified(NULL))
243 static const char *lines[] =
244 {ID2P(LANG_WARN_ERASEDYNPLAYLIST_PROMPT)};
245 static const struct text_message message={lines, 1};
247 return (gui_syncyesno_run(&message, NULL, NULL) == YESNO_YES);
249 else
250 return true;
253 /* Read (up to) a line of text from fd into buffer and return number of bytes
254 * read (which may be larger than the number of bytes stored in buffer). If
255 * an error occurs, -1 is returned (and buffer contains whatever could be
256 * read). A line is terminated by a LF char. Neither LF nor CR chars are
257 * stored in buffer.
259 int read_line(int fd, char* buffer, int buffer_size)
261 int count = 0;
262 int num_read = 0;
264 errno = 0;
266 while (count < buffer_size)
268 unsigned char c;
270 if (1 != read(fd, &c, 1))
271 break;
273 num_read++;
275 if ( c == '\n' )
276 break;
278 if ( c == '\r' )
279 continue;
281 buffer[count++] = c;
284 buffer[MIN(count, buffer_size - 1)] = 0;
286 return errno ? -1 : num_read;
289 /* Performance optimized version of the previous function. */
290 int fast_readline(int fd, char *buf, int buf_size, void *parameters,
291 int (*callback)(int n, const char *buf, void *parameters))
293 char *p, *next;
294 int rc, pos = 0;
295 int count = 0;
297 while ( 1 )
299 next = NULL;
301 rc = read(fd, &buf[pos], buf_size - pos - 1);
302 if (rc >= 0)
303 buf[pos+rc] = '\0';
305 if ( (p = strchr(buf, '\r')) != NULL)
307 *p = '\0';
308 next = ++p;
310 else
311 p = buf;
313 if ( (p = strchr(p, '\n')) != NULL)
315 *p = '\0';
316 next = ++p;
319 rc = callback(count, buf, parameters);
320 if (rc < 0)
321 return rc;
323 count++;
324 if (next)
326 pos = buf_size - ((long)next - (long)buf) - 1;
327 memmove(buf, next, pos);
329 else
330 break ;
333 return 0;
336 #ifdef HAVE_LCD_BITMAP
338 #if LCD_DEPTH == 16
339 #define BMP_COMPRESSION 3 /* BI_BITFIELDS */
340 #define BMP_NUMCOLORS 3
341 #else
342 #define BMP_COMPRESSION 0 /* BI_RGB */
343 #if LCD_DEPTH <= 8
344 #define BMP_NUMCOLORS (1 << LCD_DEPTH)
345 #else
346 #define BMP_NUMCOLORS 0
347 #endif
348 #endif
350 #if LCD_DEPTH == 1
351 #define BMP_BPP 1
352 #define BMP_LINESIZE ((LCD_WIDTH/8 + 3) & ~3)
353 #elif LCD_DEPTH <= 4
354 #define BMP_BPP 4
355 #define BMP_LINESIZE ((LCD_WIDTH/2 + 3) & ~3)
356 #elif LCD_DEPTH <= 8
357 #define BMP_BPP 8
358 #define BMP_LINESIZE ((LCD_WIDTH + 3) & ~3)
359 #elif LCD_DEPTH <= 16
360 #define BMP_BPP 16
361 #define BMP_LINESIZE ((LCD_WIDTH*2 + 3) & ~3)
362 #else
363 #define BMP_BPP 24
364 #define BMP_LINESIZE ((LCD_WIDTH*3 + 3) & ~3)
365 #endif
367 #define BMP_HEADERSIZE (54 + 4 * BMP_NUMCOLORS)
368 #define BMP_DATASIZE (BMP_LINESIZE * LCD_HEIGHT)
369 #define BMP_TOTALSIZE (BMP_HEADERSIZE + BMP_DATASIZE)
371 #define LE16_CONST(x) (x)&0xff, ((x)>>8)&0xff
372 #define LE32_CONST(x) (x)&0xff, ((x)>>8)&0xff, ((x)>>16)&0xff, ((x)>>24)&0xff
374 static const unsigned char bmpheader[] =
376 0x42, 0x4d, /* 'BM' */
377 LE32_CONST(BMP_TOTALSIZE), /* Total file size */
378 0x00, 0x00, 0x00, 0x00, /* Reserved */
379 LE32_CONST(BMP_HEADERSIZE), /* Offset to start of pixel data */
381 0x28, 0x00, 0x00, 0x00, /* Size of (2nd) header */
382 LE32_CONST(LCD_WIDTH), /* Width in pixels */
383 LE32_CONST(LCD_HEIGHT), /* Height in pixels */
384 0x01, 0x00, /* Number of planes (always 1) */
385 LE16_CONST(BMP_BPP), /* Bits per pixel 1/4/8/16/24 */
386 LE32_CONST(BMP_COMPRESSION),/* Compression mode */
387 LE32_CONST(BMP_DATASIZE), /* Size of bitmap data */
388 0xc4, 0x0e, 0x00, 0x00, /* Horizontal resolution (pixels/meter) */
389 0xc4, 0x0e, 0x00, 0x00, /* Vertical resolution (pixels/meter) */
390 LE32_CONST(BMP_NUMCOLORS), /* Number of used colours */
391 LE32_CONST(BMP_NUMCOLORS), /* Number of important colours */
393 #if LCD_DEPTH == 1
394 #ifdef MROBE_100
395 2, 2, 94, 0x00, /* Colour #0 */
396 3, 6, 241, 0x00 /* Colour #1 */
397 #else
398 0x90, 0xee, 0x90, 0x00, /* Colour #0 */
399 0x00, 0x00, 0x00, 0x00 /* Colour #1 */
400 #endif
401 #elif LCD_DEPTH == 2
402 0xe6, 0xd8, 0xad, 0x00, /* Colour #0 */
403 0x99, 0x90, 0x73, 0x00, /* Colour #1 */
404 0x4c, 0x48, 0x39, 0x00, /* Colour #2 */
405 0x00, 0x00, 0x00, 0x00 /* Colour #3 */
406 #elif LCD_DEPTH == 16
407 0x00, 0xf8, 0x00, 0x00, /* red bitfield mask */
408 0xe0, 0x07, 0x00, 0x00, /* green bitfield mask */
409 0x1f, 0x00, 0x00, 0x00 /* blue bitfield mask */
410 #endif
413 static void (*screen_dump_hook)(int fh) = NULL;
415 void screen_dump(void)
417 int fh;
418 char filename[MAX_PATH];
419 int bx, by;
420 #if LCD_DEPTH == 1
421 static unsigned char line_block[8][BMP_LINESIZE];
422 #elif LCD_DEPTH == 2
423 #if LCD_PIXELFORMAT == HORIZONTAL_PACKING
424 static unsigned char line_block[BMP_LINESIZE];
425 #elif LCD_PIXELFORMAT == VERTICAL_PACKING
426 static unsigned char line_block[4][BMP_LINESIZE];
427 #elif LCD_PIXELFORMAT == VERTICAL_INTERLEAVED
428 static unsigned char line_block[8][BMP_LINESIZE];
429 #endif
430 #elif LCD_DEPTH == 16
431 static unsigned short line_block[BMP_LINESIZE/2];
432 #endif
434 #if CONFIG_RTC
435 create_datetime_filename(filename, "", "dump ", ".bmp", false);
436 #else
437 create_numbered_filename(filename, "", "dump_", ".bmp", 4
438 IF_CNFN_NUM_(, NULL));
439 #endif
441 fh = creat(filename);
442 if (fh < 0)
443 return;
445 if (screen_dump_hook)
447 screen_dump_hook(fh);
449 else
451 write(fh, bmpheader, sizeof(bmpheader));
453 /* BMP image goes bottom up */
454 #if LCD_DEPTH == 1
455 for (by = LCD_FBHEIGHT - 1; by >= 0; by--)
457 unsigned char *src = &lcd_framebuffer[by][0];
458 unsigned char *dst = &line_block[0][0];
460 memset(line_block, 0, sizeof(line_block));
461 for (bx = LCD_WIDTH/8; bx > 0; bx--)
463 unsigned dst_mask = 0x80;
464 int ix;
466 for (ix = 8; ix > 0; ix--)
468 unsigned char *dst_blk = dst;
469 unsigned src_byte = *src++;
470 int iy;
472 for (iy = 8; iy > 0; iy--)
474 if (src_byte & 0x80)
475 *dst_blk |= dst_mask;
476 src_byte <<= 1;
477 dst_blk += BMP_LINESIZE;
479 dst_mask >>= 1;
481 dst++;
484 write(fh, line_block, sizeof(line_block));
486 #elif LCD_DEPTH == 2
487 #if LCD_PIXELFORMAT == HORIZONTAL_PACKING
488 for (by = LCD_FBHEIGHT - 1; by >= 0; by--)
490 unsigned char *src = &lcd_framebuffer[by][0];
491 unsigned char *dst = line_block;
493 memset(line_block, 0, sizeof(line_block));
494 for (bx = LCD_FBWIDTH; bx > 0; bx--)
496 unsigned src_byte = *src++;
498 *dst++ = ((src_byte >> 2) & 0x30) | ((src_byte >> 4) & 0x03);
499 *dst++ = ((src_byte << 2) & 0x30) | (src_byte & 0x03);
502 write(fh, line_block, sizeof(line_block));
504 #elif LCD_PIXELFORMAT == VERTICAL_PACKING
505 for (by = LCD_FBHEIGHT - 1; by >= 0; by--)
507 unsigned char *src = &lcd_framebuffer[by][0];
508 unsigned char *dst = &line_block[3][0];
510 memset(line_block, 0, sizeof(line_block));
511 for (bx = LCD_WIDTH/2; bx > 0; bx--)
513 unsigned char *dst_blk = dst++;
514 unsigned src_byte0 = *src++ << 4;
515 unsigned src_byte1 = *src++;
516 int iy;
518 for (iy = 4; iy > 0; iy--)
520 *dst_blk = (src_byte0 & 0x30) | (src_byte1 & 0x03);
521 src_byte0 >>= 2;
522 src_byte1 >>= 2;
523 dst_blk -= BMP_LINESIZE;
527 write(fh, line_block, sizeof(line_block));
529 #elif LCD_PIXELFORMAT == VERTICAL_INTERLEAVED
530 for (by = LCD_FBHEIGHT - 1; by >= 0; by--)
532 const fb_data *src = &lcd_framebuffer[by][0];
533 unsigned char *dst = &line_block[7][0];
535 memset(line_block, 0, sizeof(line_block));
536 for (bx = LCD_WIDTH/2; bx > 0; bx--)
538 unsigned char *dst_blk = dst++;
539 unsigned src_data0 = *src++ << 4;
540 unsigned src_data1 = *src++;
541 int iy;
543 for (iy = 8; iy > 0; iy--)
545 *dst_blk = (src_data0 & 0x10) | (src_data1 & 0x01)
546 | ((src_data0 & 0x1000) | (src_data1 & 0x0100)) >> 7;
547 src_data0 >>= 1;
548 src_data1 >>= 1;
549 dst_blk -= BMP_LINESIZE;
553 write(fh, line_block, sizeof(line_block));
555 #endif
556 #elif LCD_DEPTH == 16
557 for (by = LCD_HEIGHT - 1; by >= 0; by--)
559 unsigned short *src = &lcd_framebuffer[by][0];
560 unsigned short *dst = line_block;
562 memset(line_block, 0, sizeof(line_block));
563 for (bx = LCD_WIDTH; bx > 0; bx--)
565 #if (LCD_PIXELFORMAT == RGB565SWAPPED)
566 /* iPod LCD data is big endian although the CPU is not */
567 *dst++ = htobe16(*src++);
568 #else
569 *dst++ = htole16(*src++);
570 #endif
573 write(fh, line_block, sizeof(line_block));
575 #endif /* LCD_DEPTH */
578 close(fh);
581 void screen_dump_set_hook(void (*hook)(int fh))
583 screen_dump_hook = hook;
586 #endif /* HAVE_LCD_BITMAP */
588 /* parse a line from a configuration file. the line format is:
590 name: value
592 Any whitespace before setting name or value (after ':') is ignored.
593 A # as first non-whitespace character discards the whole line.
594 Function sets pointers to null-terminated setting name and value.
595 Returns false if no valid config entry was found.
598 bool settings_parseline(char* line, char** name, char** value)
600 char* ptr;
602 while ( isspace(*line) )
603 line++;
605 if ( *line == '#' )
606 return false;
608 ptr = strchr(line, ':');
609 if ( !ptr )
610 return false;
612 *name = line;
613 *ptr = 0;
614 ptr++;
615 while (isspace(*ptr))
616 ptr++;
617 *value = ptr;
618 return true;
621 static void system_flush(void)
623 scrobbler_shutdown();
624 playlist_shutdown();
625 tree_flush();
626 call_storage_idle_notifys(true); /*doesnt work on usb and shutdown from ata thread */
629 static void system_restore(void)
631 tree_restore();
632 scrobbler_init();
635 static bool clean_shutdown(void (*callback)(void *), void *parameter)
637 #ifdef SIMULATOR
638 (void)callback;
639 (void)parameter;
640 bookmark_autobookmark();
641 call_storage_idle_notifys(true);
642 exit(0);
643 #else
644 long msg_id = -1;
645 int i;
647 scrobbler_poweroff();
649 #if CONFIG_CHARGING && !defined(HAVE_POWEROFF_WHILE_CHARGING)
650 if(!charger_inserted())
651 #endif
653 bool batt_safe = battery_level_safe();
654 int audio_stat = audio_status();
656 FOR_NB_SCREENS(i)
657 screens[i].clear_display();
659 if (batt_safe)
661 #ifdef HAVE_TAGCACHE
662 if (!tagcache_prepare_shutdown())
664 cancel_shutdown();
665 splash(HZ, ID2P(LANG_TAGCACHE_BUSY));
666 return false;
668 #endif
669 if (battery_level() > 10)
670 splash(0, str(LANG_SHUTTINGDOWN));
671 else
673 msg_id = LANG_WARNING_BATTERY_LOW;
674 splashf(0, "%s %s", str(LANG_WARNING_BATTERY_LOW),
675 str(LANG_SHUTTINGDOWN));
678 else
680 msg_id = LANG_WARNING_BATTERY_EMPTY;
681 splashf(0, "%s %s", str(LANG_WARNING_BATTERY_EMPTY),
682 str(LANG_SHUTTINGDOWN));
685 if (global_settings.fade_on_stop
686 && (audio_stat & AUDIO_STATUS_PLAY))
688 fade(false, false);
691 if (batt_safe) /* do not save on critical battery */
693 #if defined(HAVE_RECORDING) && CONFIG_CODEC == SWCODEC
694 if (audio_stat & AUDIO_STATUS_RECORD)
696 rec_command(RECORDING_CMD_STOP);
697 /* wait for stop to complete */
698 while (audio_status() & AUDIO_STATUS_RECORD)
699 sleep(1);
701 #endif
702 bookmark_autobookmark();
704 /* audio_stop_recording == audio_stop for HWCODEC */
705 audio_stop();
707 if (callback != NULL)
708 callback(parameter);
710 #if CONFIG_CODEC != SWCODEC
711 /* wait for audio_stop or audio_stop_recording to complete */
712 while (audio_status())
713 sleep(1);
714 #endif
716 #if defined(HAVE_RECORDING) && CONFIG_CODEC == SWCODEC
717 audio_close_recording();
718 #endif
720 if(global_settings.talk_menu)
722 bool enqueue = false;
723 if(msg_id != -1)
725 talk_id(msg_id, enqueue);
726 enqueue = true;
728 talk_id(LANG_SHUTTINGDOWN, enqueue);
729 #if CONFIG_CODEC == SWCODEC
730 voice_wait();
731 #endif
734 system_flush();
735 #ifdef HAVE_EEPROM_SETTINGS
736 if (firmware_settings.initialized)
738 firmware_settings.disk_clean = true;
739 firmware_settings.bl_version = 0;
740 eeprom_settings_store();
742 #endif
744 #ifdef HAVE_DIRCACHE
745 else
746 dircache_disable();
747 #endif
749 shutdown_hw();
751 #endif
752 return false;
755 bool list_stop_handler(void)
757 bool ret = false;
759 /* Stop the music if it is playing */
760 if(audio_status())
762 if (!global_settings.party_mode)
764 if (global_settings.fade_on_stop)
765 fade(false, false);
766 bookmark_autobookmark();
767 audio_stop();
768 ret = true; /* bookmarking can make a refresh necessary */
771 #if CONFIG_CHARGING
772 #if (CONFIG_KEYPAD == RECORDER_PAD) && !defined(HAVE_SW_POWEROFF)
773 else
775 if (charger_inserted())
776 charging_splash();
777 else
778 shutdown_screen(); /* won't return if shutdown actually happens */
780 ret = true; /* screen is dirty, caller needs to refresh */
782 #endif
783 #ifndef HAVE_POWEROFF_WHILE_CHARGING
785 static long last_off = 0;
787 if (TIME_BEFORE(current_tick, last_off + HZ/2))
789 if (charger_inserted())
791 charging_splash();
792 ret = true; /* screen is dirty, caller needs to refresh */
795 last_off = current_tick;
797 #endif
798 #endif /* CONFIG_CHARGING */
799 return ret;
802 #if CONFIG_CHARGING
803 static bool waiting_to_resume_play = false;
804 static long play_resume_tick;
806 static void car_adapter_mode_processing(bool inserted)
808 if (global_settings.car_adapter_mode)
810 if(inserted)
813 * Just got plugged in, delay & resume if we were playing
815 if (audio_status() & AUDIO_STATUS_PAUSE)
817 /* delay resume a bit while the engine is cranking */
818 play_resume_tick = current_tick + HZ*5;
819 waiting_to_resume_play = true;
822 else
825 * Just got unplugged, pause if playing
827 if ((audio_status() & AUDIO_STATUS_PLAY) &&
828 !(audio_status() & AUDIO_STATUS_PAUSE))
830 if (global_settings.fade_on_stop)
831 fade(false, false);
832 else
833 audio_pause();
835 waiting_to_resume_play = false;
840 static void car_adapter_tick(void)
842 if (waiting_to_resume_play)
844 if (TIME_AFTER(current_tick, play_resume_tick))
846 if (audio_status() & AUDIO_STATUS_PAUSE)
848 queue_broadcast(SYS_CAR_ADAPTER_RESUME, 0);
850 waiting_to_resume_play = false;
855 void car_adapter_mode_init(void)
857 tick_add_task(car_adapter_tick);
859 #endif
861 #ifdef HAVE_HEADPHONE_DETECTION
862 static void unplug_change(bool inserted)
864 static bool headphone_caused_pause = false;
866 if (global_settings.unplug_mode)
868 int audio_stat = audio_status();
869 if (inserted)
871 if ((audio_stat & AUDIO_STATUS_PLAY) &&
872 headphone_caused_pause &&
873 global_settings.unplug_mode > 1 )
874 audio_resume();
875 backlight_on();
876 headphone_caused_pause = false;
877 } else {
878 if ((audio_stat & AUDIO_STATUS_PLAY) &&
879 !(audio_stat & AUDIO_STATUS_PAUSE))
881 headphone_caused_pause = true;
882 audio_pause();
884 if (global_settings.unplug_rw)
886 if (audio_current_track()->elapsed >
887 (unsigned long)(global_settings.unplug_rw*1000))
888 audio_ff_rewind(audio_current_track()->elapsed -
889 (global_settings.unplug_rw*1000));
890 else
891 audio_ff_rewind(0);
897 #endif
899 long default_event_handler_ex(long event, void (*callback)(void *), void *parameter)
901 switch(event)
903 case SYS_BATTERY_UPDATE:
904 if(global_settings.talk_battery_level)
906 talk_ids(true, VOICE_PAUSE, VOICE_PAUSE,
907 LANG_BATTERY_TIME,
908 TALK_ID(battery_level(), UNIT_PERCENT),
909 VOICE_PAUSE);
910 talk_force_enqueue_next();
912 break;
913 case SYS_USB_CONNECTED:
914 if (callback != NULL)
915 callback(parameter);
916 #if (CONFIG_STORAGE & STORAGE_MMC)
917 if (!mmc_touched() ||
918 (mmc_remove_request() == SYS_HOTSWAP_EXTRACTED))
919 #endif
921 system_flush();
922 #ifdef BOOTFILE
923 #if !defined(USB_NONE) && !defined(USB_IPODSTYLE)
924 check_bootfile(false); /* gets initial size */
925 #endif
926 #endif
927 usb_screen();
928 #ifdef BOOTFILE
929 #if !defined(USB_NONE) && !defined(USB_IPODSTYLE)
930 check_bootfile(true);
931 #endif
932 #endif
933 system_restore();
935 return SYS_USB_CONNECTED;
936 case SYS_POWEROFF:
937 if (!clean_shutdown(callback, parameter))
938 return SYS_POWEROFF;
939 break;
940 #if CONFIG_CHARGING
941 case SYS_CHARGER_CONNECTED:
942 car_adapter_mode_processing(true);
943 return SYS_CHARGER_CONNECTED;
945 case SYS_CHARGER_DISCONNECTED:
946 car_adapter_mode_processing(false);
947 return SYS_CHARGER_DISCONNECTED;
949 case SYS_CAR_ADAPTER_RESUME:
950 audio_resume();
951 return SYS_CAR_ADAPTER_RESUME;
952 #endif
953 #ifdef HAVE_HEADPHONE_DETECTION
954 case SYS_PHONE_PLUGGED:
955 unplug_change(true);
956 return SYS_PHONE_PLUGGED;
958 case SYS_PHONE_UNPLUGGED:
959 unplug_change(false);
960 return SYS_PHONE_UNPLUGGED;
961 #endif
963 return 0;
966 long default_event_handler(long event)
968 return default_event_handler_ex(event, NULL, NULL);
971 int show_logo( void )
973 #ifdef HAVE_LCD_BITMAP
974 char version[32];
975 int font_h, font_w;
977 snprintf(version, sizeof(version), "Ver. %s", appsversion);
979 lcd_clear_display();
980 lcd_bitmap(rockboxlogo, 0, 10, BMPWIDTH_rockboxlogo, BMPHEIGHT_rockboxlogo);
981 lcd_setfont(FONT_SYSFIXED);
982 lcd_getstringsize((unsigned char *)"A", &font_w, &font_h);
983 lcd_putsxy((LCD_WIDTH/2) - ((strlen(version)*font_w)/2),
984 LCD_HEIGHT-font_h, (unsigned char *)version);
985 lcd_setfont(FONT_UI);
987 #else
988 char *rockbox = " ROCKbox!";
990 lcd_clear_display();
991 lcd_double_height(true);
992 lcd_puts(0, 0, rockbox);
993 lcd_puts_scroll(0, 1, appsversion);
994 #endif
995 lcd_update();
997 #ifdef HAVE_REMOTE_LCD
998 lcd_remote_clear_display();
999 lcd_remote_bitmap(remote_rockboxlogo, 0, 10, BMPWIDTH_remote_rockboxlogo,
1000 BMPHEIGHT_remote_rockboxlogo);
1001 lcd_remote_setfont(FONT_SYSFIXED);
1002 lcd_remote_getstringsize((unsigned char *)"A", &font_w, &font_h);
1003 lcd_remote_putsxy((LCD_REMOTE_WIDTH/2) - ((strlen(version)*font_w)/2),
1004 LCD_REMOTE_HEIGHT-font_h, (unsigned char *)version);
1005 lcd_remote_setfont(FONT_UI);
1006 lcd_remote_update();
1007 #endif
1009 return 0;
1012 #if CONFIG_CODEC == SWCODEC
1013 int get_replaygain_mode(bool have_track_gain, bool have_album_gain)
1015 int type;
1017 bool track = ((global_settings.replaygain_type == REPLAYGAIN_TRACK)
1018 || ((global_settings.replaygain_type == REPLAYGAIN_SHUFFLE)
1019 && global_settings.playlist_shuffle));
1021 type = (!track && have_album_gain) ? REPLAYGAIN_ALBUM
1022 : have_track_gain ? REPLAYGAIN_TRACK : -1;
1024 return type;
1026 #endif
1028 #ifdef BOOTFILE
1029 #if !defined(USB_NONE) && !defined(USB_IPODSTYLE)
1031 memorize/compare details about the BOOTFILE
1032 we don't use dircache because it may not be up to date after
1033 USB disconnect (scanning in the background)
1035 void check_bootfile(bool do_rolo)
1037 static unsigned short wrtdate = 0;
1038 static unsigned short wrttime = 0;
1039 DIR* dir = NULL;
1040 struct dirent* entry = NULL;
1042 /* 1. open BOOTDIR and find the BOOTFILE dir entry */
1043 dir = opendir(BOOTDIR);
1045 if(!dir) return; /* do we want an error splash? */
1047 /* loop all files in BOOTDIR */
1048 while(0 != (entry = readdir(dir)))
1050 if(!strcasecmp(entry->d_name, BOOTFILE))
1052 /* found the bootfile */
1053 if(wrtdate && do_rolo)
1055 if((entry->wrtdate != wrtdate) ||
1056 (entry->wrttime != wrttime))
1058 static const char *lines[] = { ID2P(LANG_BOOT_CHANGED),
1059 ID2P(LANG_REBOOT_NOW) };
1060 static const struct text_message message={ lines, 2 };
1061 button_clear_queue(); /* Empty the keyboard buffer */
1062 if(gui_syncyesno_run(&message, NULL, NULL) == YESNO_YES)
1063 rolo_load(BOOTDIR "/" BOOTFILE);
1066 wrtdate = entry->wrtdate;
1067 wrttime = entry->wrttime;
1070 closedir(dir);
1072 #endif
1073 #endif
1075 /* check range, set volume and save settings */
1076 void setvol(void)
1078 const int min_vol = sound_min(SOUND_VOLUME);
1079 const int max_vol = sound_max(SOUND_VOLUME);
1080 if (global_settings.volume < min_vol)
1081 global_settings.volume = min_vol;
1082 if (global_settings.volume > max_vol)
1083 global_settings.volume = max_vol;
1084 sound_set_volume(global_settings.volume);
1085 settings_save();
1088 char* strrsplt(char* str, int c)
1090 char* s = strrchr(str, c);
1092 if (s != NULL)
1094 *s++ = '\0';
1096 else
1098 s = str;
1101 return s;
1104 /* Test file existence, using dircache of possible */
1105 bool file_exists(const char *file)
1107 int fd;
1109 if (!file || strlen(file) <= 0)
1110 return false;
1112 #ifdef HAVE_DIRCACHE
1113 if (dircache_is_enabled())
1114 return (dircache_get_entry_ptr(file) != NULL);
1115 #endif
1117 fd = open(file, O_RDONLY);
1118 if (fd < 0)
1119 return false;
1120 close(fd);
1121 return true;
1124 bool dir_exists(const char *path)
1126 DIR* d = opendir(path);
1127 if (!d)
1128 return false;
1129 closedir(d);
1130 return true;
1134 * removes the extension of filename (if it doesn't start with a .)
1135 * puts the result in buffer
1137 char *strip_extension(char* buffer, int buffer_size, const char *filename)
1139 char *dot = strrchr(filename, '.');
1140 int len;
1142 if (buffer_size <= 0)
1144 return NULL;
1147 buffer_size--; /* Make room for end nil */
1149 if (dot != 0 && filename[0] != '.')
1151 len = dot - filename;
1152 len = MIN(len, buffer_size);
1153 strncpy(buffer, filename, len);
1155 else
1157 len = buffer_size;
1158 strncpy(buffer, filename, buffer_size);
1161 buffer[len] = 0;
1163 return buffer;
1165 #endif /* !defined(__PCTOOL__) */
1167 /* Format time into buf.
1169 * buf - buffer to format to.
1170 * buf_size - size of buffer.
1171 * t - time to format, in milliseconds.
1173 void format_time(char* buf, int buf_size, long t)
1175 if ( t < 3600000 )
1177 snprintf(buf, buf_size, "%d:%02d",
1178 (int) (t / 60000), (int) (t % 60000 / 1000));
1180 else
1182 snprintf(buf, buf_size, "%d:%02d:%02d",
1183 (int) (t / 3600000), (int) (t % 3600000 / 60000),
1184 (int) (t % 60000 / 1000));
1189 /** Open a UTF-8 file and set file descriptor to first byte after BOM.
1190 * If no BOM is present this behaves like open().
1191 * If the file is opened for writing and O_TRUNC is set, write a BOM to
1192 * the opened file and leave the file pointer set after the BOM.
1194 #define BOM "\xef\xbb\xbf"
1195 #define BOM_SIZE 3
1197 int open_utf8(const char* pathname, int flags)
1199 int fd;
1200 unsigned char bom[BOM_SIZE];
1202 fd = open(pathname, flags);
1203 if(fd < 0)
1204 return fd;
1206 if(flags & (O_TRUNC | O_WRONLY))
1208 write(fd, BOM, BOM_SIZE);
1210 else
1212 read(fd, bom, BOM_SIZE);
1213 /* check for BOM */
1214 if(memcmp(bom, BOM, BOM_SIZE))
1215 lseek(fd, 0, SEEK_SET);
1217 return fd;
1221 #ifdef HAVE_LCD_COLOR
1223 * Helper function to convert a string of 6 hex digits to a native colour
1226 static int hex2dec(int c)
1228 return (((c) >= '0' && ((c) <= '9')) ? (c) - '0' :
1229 (toupper(c)) - 'A' + 10);
1232 int hex_to_rgb(const char* hex, int* color)
1234 int red, green, blue;
1235 int i = 0;
1237 while ((i < 6) && (isxdigit(hex[i])))
1238 i++;
1240 if (i < 6)
1241 return -1;
1243 red = (hex2dec(hex[0]) << 4) | hex2dec(hex[1]);
1244 green = (hex2dec(hex[2]) << 4) | hex2dec(hex[3]);
1245 blue = (hex2dec(hex[4]) << 4) | hex2dec(hex[5]);
1247 *color = LCD_RGBPACK(red,green,blue);
1249 return 0;
1251 #endif /* HAVE_LCD_COLOR */
1253 #ifdef HAVE_LCD_BITMAP
1254 /* A simplified scanf - used (at time of writing) by wps parsing functions.
1256 fmt - char array specifying the format of each list option. Valid values
1257 are: d - int
1258 s - string (sets pointer to string, without copying)
1259 c - hex colour (RGB888 - e.g. ff00ff)
1260 g - greyscale "colour" (0-3)
1261 set_vals - if not NULL 1 is set in the bitplace if the item was read OK
1262 0 if not read.
1263 first item is LSB, (max 32 items! )
1264 Stops parseing if an item is invalid unless the item == '-'
1265 sep - list separator (e.g. ',' or '|')
1266 str - string to parse, must be terminated by 0 or sep
1267 ... - pointers to store the parsed values
1269 return value - pointer to char after parsed data, 0 if there was an error.
1273 /* '0'-'3' are ASCII 0x30 to 0x33 */
1274 #define is0123(x) (((x) & 0xfc) == 0x30)
1276 const char* parse_list(const char *fmt, uint32_t *set_vals,
1277 const char sep, const char* str, ...)
1279 va_list ap;
1280 const char* p = str, *f = fmt;
1281 const char** s;
1282 int* d;
1283 bool set;
1284 int i=0;
1286 va_start(ap, str);
1287 if (set_vals)
1288 *set_vals = 0;
1289 while (*fmt)
1291 /* Check for separator, if we're not at the start */
1292 if (f != fmt)
1294 if (*p != sep)
1295 goto err;
1296 p++;
1298 set = false;
1299 switch (*fmt++)
1301 case 's': /* string - return a pointer to it (not a copy) */
1302 s = va_arg(ap, const char **);
1304 *s = p;
1305 while (*p && *p != sep)
1306 p++;
1307 set = (s[0][0]!='-') && (s[0][1]!=sep) ;
1308 break;
1310 case 'd': /* int */
1311 d = va_arg(ap, int*);
1312 if (!isdigit(*p))
1314 if (!set_vals || *p != '-')
1315 goto err;
1316 while (*p && *p != sep)
1317 p++;
1319 else
1321 *d = *p++ - '0';
1322 while (isdigit(*p))
1323 *d = (*d * 10) + (*p++ - '0');
1324 set = true;
1327 break;
1329 #ifdef HAVE_LCD_COLOR
1330 case 'c': /* colour (rrggbb - e.g. f3c1a8) */
1331 d = va_arg(ap, int*);
1333 if (hex_to_rgb(p, d) < 0)
1335 if (!set_vals || *p != '-')
1336 goto err;
1337 while (*p && *p != sep)
1338 p++;
1340 else
1342 p += 6;
1343 set = true;
1346 break;
1347 #endif
1349 #if LCD_DEPTH == 2 || (defined(HAVE_REMOTE_LCD) && LCD_REMOTE_DEPTH == 2)
1350 case 'g': /* greyscale colour (0-3) */
1351 d = va_arg(ap, int*);
1353 if (is0123(*p))
1355 *d = *p++ - '0';
1356 set = true;
1358 else if (!set_vals || *p != '-')
1359 goto err;
1360 else
1362 while (*p && *p != sep)
1363 p++;
1366 break;
1367 #endif
1369 default: /* Unknown format type */
1370 goto err;
1371 break;
1373 if (set_vals && set)
1374 *set_vals |= (1<<i);
1375 i++;
1378 va_end(ap);
1379 return p;
1381 err:
1382 va_end(ap);
1383 return 0;
1385 #endif