Reverting parts of r19760 that was mistakenly committed.
[kugel-rb.git] / apps / misc.c
blob1410d47244891acd6a13856b17ffe2e89f44953a
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 "appevents.h"
37 #include "lang.h"
38 #include "string.h"
39 #include "dir.h"
40 #include "lcd-remote.h"
41 #include "errno.h"
42 #include "system.h"
43 #include "timefuncs.h"
44 #include "screens.h"
45 #include "talk.h"
46 #include "mpeg.h"
47 #include "audio.h"
48 #include "mp3_playback.h"
49 #include "settings.h"
50 #include "storage.h"
51 #include "ata_idle_notify.h"
52 #include "kernel.h"
53 #include "power.h"
54 #include "powermgmt.h"
55 #include "backlight.h"
56 #include "version.h"
57 #include "font.h"
58 #include "splash.h"
59 #include "tagcache.h"
60 #include "scrobbler.h"
61 #include "sound.h"
62 #include "playlist.h"
63 #include "yesno.h"
64 #include "viewport.h"
66 #ifdef IPOD_ACCESSORY_PROTOCOL
67 #include "iap.h"
68 #endif
70 #if (CONFIG_STORAGE & STORAGE_MMC)
71 #include "ata_mmc.h"
72 #endif
73 #include "tree.h"
74 #include "eeprom_settings.h"
75 #if defined(HAVE_RECORDING) && !defined(__PCTOOL__)
76 #include "recording.h"
77 #endif
78 #if defined(HAVE_LCD_BITMAP) && !defined(__PCTOOL__)
79 #include "bmp.h"
80 #include "icons.h"
81 #endif /* End HAVE_LCD_BITMAP */
82 #include "gui/gwps-common.h"
83 #include "bookmark.h"
85 #include "playback.h"
87 #ifdef BOOTFILE
88 #if !defined(USB_NONE) && !defined(USB_IPODSTYLE)
89 #include "rolo.h"
90 #include "yesno.h"
91 #endif
92 #endif
94 /* Format a large-range value for output, using the appropriate unit so that
95 * the displayed value is in the range 1 <= display < 1000 (1024 for "binary"
96 * units) if possible, and 3 significant digits are shown. If a buffer is
97 * given, the result is snprintf()'d into that buffer, otherwise the result is
98 * voiced.*/
99 char *output_dyn_value(char *buf, int buf_size, int value,
100 const unsigned char **units, bool bin_scale)
102 int scale = bin_scale ? 1024 : 1000;
103 int fraction = 0;
104 int unit_no = 0;
105 char tbuf[5];
107 while (value >= scale)
109 fraction = value % scale;
110 value /= scale;
111 unit_no++;
113 if (bin_scale)
114 fraction = fraction * 1000 / 1024;
116 if (value >= 100 || !unit_no)
117 tbuf[0] = '\0';
118 else if (value >= 10)
119 snprintf(tbuf, sizeof(tbuf), "%01d", fraction / 100);
120 else
121 snprintf(tbuf, sizeof(tbuf), "%02d", fraction / 10);
123 if (buf)
125 if (strlen(tbuf))
126 snprintf(buf, buf_size, "%d%s%s%s", value, str(LANG_POINT),
127 tbuf, P2STR(units[unit_no]));
128 else
129 snprintf(buf, buf_size, "%d%s", value, P2STR(units[unit_no]));
131 else
133 talk_fractional(tbuf, value, P2ID(units[unit_no]));
135 return buf;
138 /* Create a filename with a number part in a way that the number is 1
139 * higher than the highest numbered file matching the same pattern.
140 * It is allowed that buffer and path point to the same memory location,
141 * saving a strcpy(). Path must always be given without trailing slash.
142 * "num" can point to an int specifying the number to use or NULL or a value
143 * less than zero to number automatically. The final number used will also
144 * be returned in *num. If *num is >= 0 then *num will be incremented by
145 * one. */
146 char *create_numbered_filename(char *buffer, const char *path,
147 const char *prefix, const char *suffix,
148 int numberlen IF_CNFN_NUM_(, int *num))
150 DIR *dir;
151 struct dirent *entry;
152 int max_num;
153 int pathlen;
154 int prefixlen = strlen(prefix);
155 char fmtstring[12];
157 if (buffer != path)
158 strncpy(buffer, path, MAX_PATH);
160 pathlen = strlen(buffer);
162 #ifdef IF_CNFN_NUM
163 if (num && *num >= 0)
165 /* number specified */
166 max_num = *num;
168 else
169 #endif
171 /* automatic numbering */
172 max_num = 0;
174 dir = opendir(pathlen ? buffer : "/");
175 if (!dir)
176 return NULL;
178 while ((entry = readdir(dir)))
180 int curr_num;
182 if (strncasecmp((char *)entry->d_name, prefix, prefixlen)
183 || strcasecmp((char *)entry->d_name + prefixlen + numberlen, suffix))
184 continue;
186 curr_num = atoi((char *)entry->d_name + prefixlen);
187 if (curr_num > max_num)
188 max_num = curr_num;
191 closedir(dir);
194 max_num++;
196 snprintf(fmtstring, sizeof(fmtstring), "/%%s%%0%dd%%s", numberlen);
197 snprintf(buffer + pathlen, MAX_PATH - pathlen, fmtstring, prefix,
198 max_num, suffix);
200 #ifdef IF_CNFN_NUM
201 if (num)
202 *num = max_num;
203 #endif
205 return buffer;
209 #if CONFIG_RTC
210 /* Create a filename with a date+time part.
211 It is allowed that buffer and path point to the same memory location,
212 saving a strcpy(). Path must always be given without trailing slash.
213 unique_time as true makes the function wait until the current time has
214 changed. */
215 char *create_datetime_filename(char *buffer, const char *path,
216 const char *prefix, const char *suffix,
217 bool unique_time)
219 struct tm *tm = get_time();
220 static struct tm last_tm;
221 int pathlen;
223 while (unique_time && !memcmp(get_time(), &last_tm, sizeof (struct tm)))
224 sleep(HZ/10);
226 last_tm = *tm;
228 if (buffer != path)
229 strncpy(buffer, path, MAX_PATH);
231 pathlen = strlen(buffer);
232 snprintf(buffer + pathlen, MAX_PATH - pathlen,
233 "/%s%02d%02d%02d-%02d%02d%02d%s", prefix,
234 tm->tm_year % 100, tm->tm_mon + 1, tm->tm_mday,
235 tm->tm_hour, tm->tm_min, tm->tm_sec, suffix);
237 return buffer;
239 #endif /* CONFIG_RTC */
241 /* Ask the user if they really want to erase the current dynamic playlist
242 * returns true if the playlist should be replaced */
243 bool warn_on_pl_erase(void)
245 if (global_settings.warnon_erase_dynplaylist &&
246 !global_settings.party_mode &&
247 playlist_modified(NULL))
249 static const char *lines[] =
250 {ID2P(LANG_WARN_ERASEDYNPLAYLIST_PROMPT)};
251 static const struct text_message message={lines, 1};
253 return (gui_syncyesno_run(&message, NULL, NULL) == YESNO_YES);
255 else
256 return true;
259 /* Read (up to) a line of text from fd into buffer and return number of bytes
260 * read (which may be larger than the number of bytes stored in buffer). If
261 * an error occurs, -1 is returned (and buffer contains whatever could be
262 * read). A line is terminated by a LF char. Neither LF nor CR chars are
263 * stored in buffer.
265 int read_line(int fd, char* buffer, int buffer_size)
267 int count = 0;
268 int num_read = 0;
270 errno = 0;
272 while (count < buffer_size)
274 unsigned char c;
276 if (1 != read(fd, &c, 1))
277 break;
279 num_read++;
281 if ( c == '\n' )
282 break;
284 if ( c == '\r' )
285 continue;
287 buffer[count++] = c;
290 buffer[MIN(count, buffer_size - 1)] = 0;
292 return errno ? -1 : num_read;
295 /* Performance optimized version of the previous function. */
296 int fast_readline(int fd, char *buf, int buf_size, void *parameters,
297 int (*callback)(int n, const char *buf, void *parameters))
299 char *p, *next;
300 int rc, pos = 0;
301 int count = 0;
303 while ( 1 )
305 next = NULL;
307 rc = read(fd, &buf[pos], buf_size - pos - 1);
308 if (rc >= 0)
309 buf[pos+rc] = '\0';
311 if ( (p = strchr(buf, '\r')) != NULL)
313 *p = '\0';
314 next = ++p;
316 else
317 p = buf;
319 if ( (p = strchr(p, '\n')) != NULL)
321 *p = '\0';
322 next = ++p;
325 rc = callback(count, buf, parameters);
326 if (rc < 0)
327 return rc;
329 count++;
330 if (next)
332 pos = buf_size - ((long)next - (long)buf) - 1;
333 memmove(buf, next, pos);
335 else
336 break ;
339 return 0;
342 #ifdef HAVE_LCD_BITMAP
344 #if LCD_DEPTH == 16
345 #define BMP_COMPRESSION 3 /* BI_BITFIELDS */
346 #define BMP_NUMCOLORS 3
347 #else
348 #define BMP_COMPRESSION 0 /* BI_RGB */
349 #if LCD_DEPTH <= 8
350 #define BMP_NUMCOLORS (1 << LCD_DEPTH)
351 #else
352 #define BMP_NUMCOLORS 0
353 #endif
354 #endif
356 #if LCD_DEPTH == 1
357 #define BMP_BPP 1
358 #define BMP_LINESIZE ((LCD_WIDTH/8 + 3) & ~3)
359 #elif LCD_DEPTH <= 4
360 #define BMP_BPP 4
361 #define BMP_LINESIZE ((LCD_WIDTH/2 + 3) & ~3)
362 #elif LCD_DEPTH <= 8
363 #define BMP_BPP 8
364 #define BMP_LINESIZE ((LCD_WIDTH + 3) & ~3)
365 #elif LCD_DEPTH <= 16
366 #define BMP_BPP 16
367 #define BMP_LINESIZE ((LCD_WIDTH*2 + 3) & ~3)
368 #else
369 #define BMP_BPP 24
370 #define BMP_LINESIZE ((LCD_WIDTH*3 + 3) & ~3)
371 #endif
373 #define BMP_HEADERSIZE (54 + 4 * BMP_NUMCOLORS)
374 #define BMP_DATASIZE (BMP_LINESIZE * LCD_HEIGHT)
375 #define BMP_TOTALSIZE (BMP_HEADERSIZE + BMP_DATASIZE)
377 #define LE16_CONST(x) (x)&0xff, ((x)>>8)&0xff
378 #define LE32_CONST(x) (x)&0xff, ((x)>>8)&0xff, ((x)>>16)&0xff, ((x)>>24)&0xff
380 static const unsigned char bmpheader[] =
382 0x42, 0x4d, /* 'BM' */
383 LE32_CONST(BMP_TOTALSIZE), /* Total file size */
384 0x00, 0x00, 0x00, 0x00, /* Reserved */
385 LE32_CONST(BMP_HEADERSIZE), /* Offset to start of pixel data */
387 0x28, 0x00, 0x00, 0x00, /* Size of (2nd) header */
388 LE32_CONST(LCD_WIDTH), /* Width in pixels */
389 LE32_CONST(LCD_HEIGHT), /* Height in pixels */
390 0x01, 0x00, /* Number of planes (always 1) */
391 LE16_CONST(BMP_BPP), /* Bits per pixel 1/4/8/16/24 */
392 LE32_CONST(BMP_COMPRESSION),/* Compression mode */
393 LE32_CONST(BMP_DATASIZE), /* Size of bitmap data */
394 0xc4, 0x0e, 0x00, 0x00, /* Horizontal resolution (pixels/meter) */
395 0xc4, 0x0e, 0x00, 0x00, /* Vertical resolution (pixels/meter) */
396 LE32_CONST(BMP_NUMCOLORS), /* Number of used colours */
397 LE32_CONST(BMP_NUMCOLORS), /* Number of important colours */
399 #if LCD_DEPTH == 1
400 #ifdef MROBE_100
401 2, 2, 94, 0x00, /* Colour #0 */
402 3, 6, 241, 0x00 /* Colour #1 */
403 #else
404 0x90, 0xee, 0x90, 0x00, /* Colour #0 */
405 0x00, 0x00, 0x00, 0x00 /* Colour #1 */
406 #endif
407 #elif LCD_DEPTH == 2
408 0xe6, 0xd8, 0xad, 0x00, /* Colour #0 */
409 0x99, 0x90, 0x73, 0x00, /* Colour #1 */
410 0x4c, 0x48, 0x39, 0x00, /* Colour #2 */
411 0x00, 0x00, 0x00, 0x00 /* Colour #3 */
412 #elif LCD_DEPTH == 16
413 0x00, 0xf8, 0x00, 0x00, /* red bitfield mask */
414 0xe0, 0x07, 0x00, 0x00, /* green bitfield mask */
415 0x1f, 0x00, 0x00, 0x00 /* blue bitfield mask */
416 #endif
419 static void (*screen_dump_hook)(int fh) = NULL;
421 void screen_dump(void)
423 int fh;
424 char filename[MAX_PATH];
425 int bx, by;
426 #if LCD_DEPTH == 1
427 static unsigned char line_block[8][BMP_LINESIZE];
428 #elif LCD_DEPTH == 2
429 #if LCD_PIXELFORMAT == HORIZONTAL_PACKING
430 static unsigned char line_block[BMP_LINESIZE];
431 #elif LCD_PIXELFORMAT == VERTICAL_PACKING
432 static unsigned char line_block[4][BMP_LINESIZE];
433 #elif LCD_PIXELFORMAT == VERTICAL_INTERLEAVED
434 static unsigned char line_block[8][BMP_LINESIZE];
435 #endif
436 #elif LCD_DEPTH == 16
437 static unsigned short line_block[BMP_LINESIZE/2];
438 #endif
440 #if CONFIG_RTC
441 create_datetime_filename(filename, "", "dump ", ".bmp", false);
442 #else
443 create_numbered_filename(filename, "", "dump_", ".bmp", 4
444 IF_CNFN_NUM_(, NULL));
445 #endif
447 fh = creat(filename);
448 if (fh < 0)
449 return;
451 if (screen_dump_hook)
453 screen_dump_hook(fh);
455 else
457 write(fh, bmpheader, sizeof(bmpheader));
459 /* BMP image goes bottom up */
460 #if LCD_DEPTH == 1
461 for (by = LCD_FBHEIGHT - 1; by >= 0; by--)
463 unsigned char *src = &lcd_framebuffer[by][0];
464 unsigned char *dst = &line_block[0][0];
466 memset(line_block, 0, sizeof(line_block));
467 for (bx = LCD_WIDTH/8; bx > 0; bx--)
469 unsigned dst_mask = 0x80;
470 int ix;
472 for (ix = 8; ix > 0; ix--)
474 unsigned char *dst_blk = dst;
475 unsigned src_byte = *src++;
476 int iy;
478 for (iy = 8; iy > 0; iy--)
480 if (src_byte & 0x80)
481 *dst_blk |= dst_mask;
482 src_byte <<= 1;
483 dst_blk += BMP_LINESIZE;
485 dst_mask >>= 1;
487 dst++;
490 write(fh, line_block, sizeof(line_block));
492 #elif LCD_DEPTH == 2
493 #if LCD_PIXELFORMAT == HORIZONTAL_PACKING
494 for (by = LCD_FBHEIGHT - 1; by >= 0; by--)
496 unsigned char *src = &lcd_framebuffer[by][0];
497 unsigned char *dst = line_block;
499 memset(line_block, 0, sizeof(line_block));
500 for (bx = LCD_FBWIDTH; bx > 0; bx--)
502 unsigned src_byte = *src++;
504 *dst++ = ((src_byte >> 2) & 0x30) | ((src_byte >> 4) & 0x03);
505 *dst++ = ((src_byte << 2) & 0x30) | (src_byte & 0x03);
508 write(fh, line_block, sizeof(line_block));
510 #elif LCD_PIXELFORMAT == VERTICAL_PACKING
511 for (by = LCD_FBHEIGHT - 1; by >= 0; by--)
513 unsigned char *src = &lcd_framebuffer[by][0];
514 unsigned char *dst = &line_block[3][0];
516 memset(line_block, 0, sizeof(line_block));
517 for (bx = LCD_WIDTH/2; bx > 0; bx--)
519 unsigned char *dst_blk = dst++;
520 unsigned src_byte0 = *src++ << 4;
521 unsigned src_byte1 = *src++;
522 int iy;
524 for (iy = 4; iy > 0; iy--)
526 *dst_blk = (src_byte0 & 0x30) | (src_byte1 & 0x03);
527 src_byte0 >>= 2;
528 src_byte1 >>= 2;
529 dst_blk -= BMP_LINESIZE;
533 write(fh, line_block, sizeof(line_block));
535 #elif LCD_PIXELFORMAT == VERTICAL_INTERLEAVED
536 for (by = LCD_FBHEIGHT - 1; by >= 0; by--)
538 const fb_data *src = &lcd_framebuffer[by][0];
539 unsigned char *dst = &line_block[7][0];
541 memset(line_block, 0, sizeof(line_block));
542 for (bx = LCD_WIDTH/2; bx > 0; bx--)
544 unsigned char *dst_blk = dst++;
545 unsigned src_data0 = *src++ << 4;
546 unsigned src_data1 = *src++;
547 int iy;
549 for (iy = 8; iy > 0; iy--)
551 *dst_blk = (src_data0 & 0x10) | (src_data1 & 0x01)
552 | ((src_data0 & 0x1000) | (src_data1 & 0x0100)) >> 7;
553 src_data0 >>= 1;
554 src_data1 >>= 1;
555 dst_blk -= BMP_LINESIZE;
559 write(fh, line_block, sizeof(line_block));
561 #endif
562 #elif LCD_DEPTH == 16
563 for (by = LCD_HEIGHT - 1; by >= 0; by--)
565 unsigned short *src = &lcd_framebuffer[by][0];
566 unsigned short *dst = line_block;
568 memset(line_block, 0, sizeof(line_block));
569 for (bx = LCD_WIDTH; bx > 0; bx--)
571 #if (LCD_PIXELFORMAT == RGB565SWAPPED)
572 /* iPod LCD data is big endian although the CPU is not */
573 *dst++ = htobe16(*src++);
574 #else
575 *dst++ = htole16(*src++);
576 #endif
579 write(fh, line_block, sizeof(line_block));
581 #endif /* LCD_DEPTH */
584 close(fh);
587 void screen_dump_set_hook(void (*hook)(int fh))
589 screen_dump_hook = hook;
592 #endif /* HAVE_LCD_BITMAP */
594 /* parse a line from a configuration file. the line format is:
596 name: value
598 Any whitespace before setting name or value (after ':') is ignored.
599 A # as first non-whitespace character discards the whole line.
600 Function sets pointers to null-terminated setting name and value.
601 Returns false if no valid config entry was found.
604 bool settings_parseline(char* line, char** name, char** value)
606 char* ptr;
608 while ( isspace(*line) )
609 line++;
611 if ( *line == '#' )
612 return false;
614 ptr = strchr(line, ':');
615 if ( !ptr )
616 return false;
618 *name = line;
619 *ptr = 0;
620 ptr++;
621 while (isspace(*ptr))
622 ptr++;
623 *value = ptr;
624 return true;
627 static void system_flush(void)
629 scrobbler_shutdown();
630 playlist_shutdown();
631 tree_flush();
632 call_storage_idle_notifys(true); /*doesnt work on usb and shutdown from ata thread */
635 static void system_restore(void)
637 tree_restore();
638 scrobbler_init();
641 static bool clean_shutdown(void (*callback)(void *), void *parameter)
643 #ifdef SIMULATOR
644 (void)callback;
645 (void)parameter;
646 bookmark_autobookmark();
647 call_storage_idle_notifys(true);
648 exit(0);
649 #else
650 long msg_id = -1;
651 int i;
653 scrobbler_poweroff();
655 #if CONFIG_CHARGING && !defined(HAVE_POWEROFF_WHILE_CHARGING)
656 if(!charger_inserted())
657 #endif
659 bool batt_safe = battery_level_safe();
660 int audio_stat = audio_status();
662 FOR_NB_SCREENS(i)
663 screens[i].clear_display();
665 if (batt_safe)
667 #ifdef HAVE_TAGCACHE
668 if (!tagcache_prepare_shutdown())
670 cancel_shutdown();
671 splash(HZ, ID2P(LANG_TAGCACHE_BUSY));
672 return false;
674 #endif
675 if (battery_level() > 10)
676 splash(0, str(LANG_SHUTTINGDOWN));
677 else
679 msg_id = LANG_WARNING_BATTERY_LOW;
680 splashf(0, "%s %s", str(LANG_WARNING_BATTERY_LOW),
681 str(LANG_SHUTTINGDOWN));
684 else
686 msg_id = LANG_WARNING_BATTERY_EMPTY;
687 splashf(0, "%s %s", str(LANG_WARNING_BATTERY_EMPTY),
688 str(LANG_SHUTTINGDOWN));
691 if (global_settings.fade_on_stop
692 && (audio_stat & AUDIO_STATUS_PLAY))
694 fade(false, false);
697 if (batt_safe) /* do not save on critical battery */
699 #if defined(HAVE_RECORDING) && CONFIG_CODEC == SWCODEC
700 if (audio_stat & AUDIO_STATUS_RECORD)
702 rec_command(RECORDING_CMD_STOP);
703 /* wait for stop to complete */
704 while (audio_status() & AUDIO_STATUS_RECORD)
705 sleep(1);
707 #endif
708 bookmark_autobookmark();
710 /* audio_stop_recording == audio_stop for HWCODEC */
711 audio_stop();
713 if (callback != NULL)
714 callback(parameter);
716 #if CONFIG_CODEC != SWCODEC
717 /* wait for audio_stop or audio_stop_recording to complete */
718 while (audio_status())
719 sleep(1);
720 #endif
722 #if defined(HAVE_RECORDING) && CONFIG_CODEC == SWCODEC
723 audio_close_recording();
724 #endif
726 if(global_settings.talk_menu)
728 bool enqueue = false;
729 if(msg_id != -1)
731 talk_id(msg_id, enqueue);
732 enqueue = true;
734 talk_id(LANG_SHUTTINGDOWN, enqueue);
735 #if CONFIG_CODEC == SWCODEC
736 voice_wait();
737 #endif
740 system_flush();
741 #ifdef HAVE_EEPROM_SETTINGS
742 if (firmware_settings.initialized)
744 firmware_settings.disk_clean = true;
745 firmware_settings.bl_version = 0;
746 eeprom_settings_store();
748 #endif
750 #ifdef HAVE_DIRCACHE
751 else
752 dircache_disable();
753 #endif
755 shutdown_hw();
757 #endif
758 return false;
761 bool list_stop_handler(void)
763 bool ret = false;
765 /* Stop the music if it is playing */
766 if(audio_status())
768 if (!global_settings.party_mode)
770 if (global_settings.fade_on_stop)
771 fade(false, false);
772 bookmark_autobookmark();
773 audio_stop();
774 ret = true; /* bookmarking can make a refresh necessary */
777 #if CONFIG_CHARGING
778 #if (CONFIG_KEYPAD == RECORDER_PAD) && !defined(HAVE_SW_POWEROFF)
779 else
781 if (charger_inserted())
782 charging_splash();
783 else
784 shutdown_screen(); /* won't return if shutdown actually happens */
786 ret = true; /* screen is dirty, caller needs to refresh */
788 #endif
789 #ifndef HAVE_POWEROFF_WHILE_CHARGING
791 static long last_off = 0;
793 if (TIME_BEFORE(current_tick, last_off + HZ/2))
795 if (charger_inserted())
797 charging_splash();
798 ret = true; /* screen is dirty, caller needs to refresh */
801 last_off = current_tick;
803 #endif
804 #endif /* CONFIG_CHARGING */
805 return ret;
808 #if CONFIG_CHARGING
809 static bool waiting_to_resume_play = false;
810 static long play_resume_tick;
812 static void car_adapter_mode_processing(bool inserted)
814 if (global_settings.car_adapter_mode)
816 if(inserted)
819 * Just got plugged in, delay & resume if we were playing
821 if (audio_status() & AUDIO_STATUS_PAUSE)
823 /* delay resume a bit while the engine is cranking */
824 play_resume_tick = current_tick + HZ*5;
825 waiting_to_resume_play = true;
828 else
831 * Just got unplugged, pause if playing
833 if ((audio_status() & AUDIO_STATUS_PLAY) &&
834 !(audio_status() & AUDIO_STATUS_PAUSE))
836 if (global_settings.fade_on_stop)
837 fade(false, false);
838 else
839 audio_pause();
841 waiting_to_resume_play = false;
846 static void car_adapter_tick(void)
848 if (waiting_to_resume_play)
850 if (TIME_AFTER(current_tick, play_resume_tick))
852 if (audio_status() & AUDIO_STATUS_PAUSE)
854 queue_broadcast(SYS_CAR_ADAPTER_RESUME, 0);
856 waiting_to_resume_play = false;
861 void car_adapter_mode_init(void)
863 tick_add_task(car_adapter_tick);
865 #endif
867 #ifdef HAVE_HEADPHONE_DETECTION
868 static void unplug_change(bool inserted)
870 static bool headphone_caused_pause = false;
872 if (global_settings.unplug_mode)
874 int audio_stat = audio_status();
875 if (inserted)
877 if ((audio_stat & AUDIO_STATUS_PLAY) &&
878 headphone_caused_pause &&
879 global_settings.unplug_mode > 1 )
880 audio_resume();
881 backlight_on();
882 headphone_caused_pause = false;
883 } else {
884 if ((audio_stat & AUDIO_STATUS_PLAY) &&
885 !(audio_stat & AUDIO_STATUS_PAUSE))
887 headphone_caused_pause = true;
888 audio_pause();
890 if (global_settings.unplug_rw)
892 if (audio_current_track()->elapsed >
893 (unsigned long)(global_settings.unplug_rw*1000))
894 audio_ff_rewind(audio_current_track()->elapsed -
895 (global_settings.unplug_rw*1000));
896 else
897 audio_ff_rewind(0);
903 #endif
905 long default_event_handler_ex(long event, void (*callback)(void *), void *parameter)
907 switch(event)
909 case SYS_BATTERY_UPDATE:
910 if(global_settings.talk_battery_level)
912 talk_ids(true, VOICE_PAUSE, VOICE_PAUSE,
913 LANG_BATTERY_TIME,
914 TALK_ID(battery_level(), UNIT_PERCENT),
915 VOICE_PAUSE);
916 talk_force_enqueue_next();
918 break;
919 case SYS_USB_CONNECTED:
920 if (callback != NULL)
921 callback(parameter);
922 #if (CONFIG_STORAGE & STORAGE_MMC)
923 if (!mmc_touched() ||
924 (mmc_remove_request() == SYS_HOTSWAP_EXTRACTED))
925 #endif
927 system_flush();
928 #ifdef BOOTFILE
929 #if !defined(USB_NONE) && !defined(USB_IPODSTYLE)
930 check_bootfile(false); /* gets initial size */
931 #endif
932 #endif
933 usb_screen();
934 #ifdef BOOTFILE
935 #if !defined(USB_NONE) && !defined(USB_IPODSTYLE)
936 check_bootfile(true);
937 #endif
938 #endif
939 system_restore();
941 return SYS_USB_CONNECTED;
942 case SYS_POWEROFF:
943 if (!clean_shutdown(callback, parameter))
944 return SYS_POWEROFF;
945 break;
946 #if CONFIG_CHARGING
947 case SYS_CHARGER_CONNECTED:
948 car_adapter_mode_processing(true);
949 return SYS_CHARGER_CONNECTED;
951 case SYS_CHARGER_DISCONNECTED:
952 car_adapter_mode_processing(false);
953 return SYS_CHARGER_DISCONNECTED;
955 case SYS_CAR_ADAPTER_RESUME:
956 audio_resume();
957 return SYS_CAR_ADAPTER_RESUME;
958 #endif
959 #ifdef HAVE_HEADPHONE_DETECTION
960 case SYS_PHONE_PLUGGED:
961 unplug_change(true);
962 return SYS_PHONE_PLUGGED;
964 case SYS_PHONE_UNPLUGGED:
965 unplug_change(false);
966 return SYS_PHONE_UNPLUGGED;
967 #endif
968 #ifdef IPOD_ACCESSORY_PROTOCOL
969 case SYS_IAP_PERIODIC:
970 iap_periodic();
971 return SYS_IAP_PERIODIC;
972 case SYS_IAP_HANDLEPKT:
973 iap_handlepkt();
974 return SYS_IAP_HANDLEPKT;
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 #ifdef SANSA_CLIP /* display the logo in the blue area of the screen */
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 0, (unsigned char *)version);
999 lcd_bitmap(rockboxlogo, 0, 16, BMPWIDTH_rockboxlogo, BMPHEIGHT_rockboxlogo);
1000 #else
1001 lcd_bitmap(rockboxlogo, 0, 10, BMPWIDTH_rockboxlogo, BMPHEIGHT_rockboxlogo);
1002 lcd_setfont(FONT_SYSFIXED);
1003 lcd_getstringsize((unsigned char *)"A", &font_w, &font_h);
1004 lcd_putsxy((LCD_WIDTH/2) - ((strlen(version)*font_w)/2),
1005 LCD_HEIGHT-font_h, (unsigned char *)version);
1006 #endif
1007 lcd_setfont(FONT_UI);
1009 #else
1010 char *rockbox = " ROCKbox!";
1012 lcd_clear_display();
1013 lcd_double_height(true);
1014 lcd_puts(0, 0, rockbox);
1015 lcd_puts_scroll(0, 1, appsversion);
1016 #endif
1017 lcd_update();
1019 #ifdef HAVE_REMOTE_LCD
1020 lcd_remote_clear_display();
1021 lcd_remote_bitmap(remote_rockboxlogo, 0, 10, BMPWIDTH_remote_rockboxlogo,
1022 BMPHEIGHT_remote_rockboxlogo);
1023 lcd_remote_setfont(FONT_SYSFIXED);
1024 lcd_remote_getstringsize((unsigned char *)"A", &font_w, &font_h);
1025 lcd_remote_putsxy((LCD_REMOTE_WIDTH/2) - ((strlen(version)*font_w)/2),
1026 LCD_REMOTE_HEIGHT-font_h, (unsigned char *)version);
1027 lcd_remote_setfont(FONT_UI);
1028 lcd_remote_update();
1029 #endif
1031 return 0;
1034 #if CONFIG_CODEC == SWCODEC
1035 int get_replaygain_mode(bool have_track_gain, bool have_album_gain)
1037 int type;
1039 bool track = ((global_settings.replaygain_type == REPLAYGAIN_TRACK)
1040 || ((global_settings.replaygain_type == REPLAYGAIN_SHUFFLE)
1041 && global_settings.playlist_shuffle));
1043 type = (!track && have_album_gain) ? REPLAYGAIN_ALBUM
1044 : have_track_gain ? REPLAYGAIN_TRACK : -1;
1046 return type;
1048 #endif
1050 #ifdef BOOTFILE
1051 #if !defined(USB_NONE) && !defined(USB_IPODSTYLE)
1053 memorize/compare details about the BOOTFILE
1054 we don't use dircache because it may not be up to date after
1055 USB disconnect (scanning in the background)
1057 void check_bootfile(bool do_rolo)
1059 static unsigned short wrtdate = 0;
1060 static unsigned short wrttime = 0;
1061 DIR* dir = NULL;
1062 struct dirent* entry = NULL;
1064 /* 1. open BOOTDIR and find the BOOTFILE dir entry */
1065 dir = opendir(BOOTDIR);
1067 if(!dir) return; /* do we want an error splash? */
1069 /* loop all files in BOOTDIR */
1070 while(0 != (entry = readdir(dir)))
1072 if(!strcasecmp(entry->d_name, BOOTFILE))
1074 /* found the bootfile */
1075 if(wrtdate && do_rolo)
1077 if((entry->wrtdate != wrtdate) ||
1078 (entry->wrttime != wrttime))
1080 static const char *lines[] = { ID2P(LANG_BOOT_CHANGED),
1081 ID2P(LANG_REBOOT_NOW) };
1082 static const struct text_message message={ lines, 2 };
1083 button_clear_queue(); /* Empty the keyboard buffer */
1084 if(gui_syncyesno_run(&message, NULL, NULL) == YESNO_YES)
1085 rolo_load(BOOTDIR "/" BOOTFILE);
1088 wrtdate = entry->wrtdate;
1089 wrttime = entry->wrttime;
1092 closedir(dir);
1094 #endif
1095 #endif
1097 /* check range, set volume and save settings */
1098 void setvol(void)
1100 const int min_vol = sound_min(SOUND_VOLUME);
1101 const int max_vol = sound_max(SOUND_VOLUME);
1102 if (global_settings.volume < min_vol)
1103 global_settings.volume = min_vol;
1104 if (global_settings.volume > max_vol)
1105 global_settings.volume = max_vol;
1106 sound_set_volume(global_settings.volume);
1107 settings_save();
1110 char* strrsplt(char* str, int c)
1112 char* s = strrchr(str, c);
1114 if (s != NULL)
1116 *s++ = '\0';
1118 else
1120 s = str;
1123 return s;
1126 /* Test file existence, using dircache of possible */
1127 bool file_exists(const char *file)
1129 int fd;
1131 if (!file || strlen(file) <= 0)
1132 return false;
1134 #ifdef HAVE_DIRCACHE
1135 if (dircache_is_enabled())
1136 return (dircache_get_entry_ptr(file) != NULL);
1137 #endif
1139 fd = open(file, O_RDONLY);
1140 if (fd < 0)
1141 return false;
1142 close(fd);
1143 return true;
1146 bool dir_exists(const char *path)
1148 DIR* d = opendir(path);
1149 if (!d)
1150 return false;
1151 closedir(d);
1152 return true;
1156 * removes the extension of filename (if it doesn't start with a .)
1157 * puts the result in buffer
1159 char *strip_extension(char* buffer, int buffer_size, const char *filename)
1161 char *dot = strrchr(filename, '.');
1162 int len;
1164 if (buffer_size <= 0)
1166 return NULL;
1169 buffer_size--; /* Make room for end nil */
1171 if (dot != 0 && filename[0] != '.')
1173 len = dot - filename;
1174 len = MIN(len, buffer_size);
1175 strncpy(buffer, filename, len);
1177 else
1179 len = buffer_size;
1180 strncpy(buffer, filename, buffer_size);
1183 buffer[len] = 0;
1185 return buffer;
1187 #endif /* !defined(__PCTOOL__) */
1189 /* Format time into buf.
1191 * buf - buffer to format to.
1192 * buf_size - size of buffer.
1193 * t - time to format, in milliseconds.
1195 void format_time(char* buf, int buf_size, long t)
1197 if ( t < 3600000 )
1199 snprintf(buf, buf_size, "%d:%02d",
1200 (int) (t / 60000), (int) (t % 60000 / 1000));
1202 else
1204 snprintf(buf, buf_size, "%d:%02d:%02d",
1205 (int) (t / 3600000), (int) (t % 3600000 / 60000),
1206 (int) (t % 60000 / 1000));
1211 /** Open a UTF-8 file and set file descriptor to first byte after BOM.
1212 * If no BOM is present this behaves like open().
1213 * If the file is opened for writing and O_TRUNC is set, write a BOM to
1214 * the opened file and leave the file pointer set after the BOM.
1216 #define BOM "\xef\xbb\xbf"
1217 #define BOM_SIZE 3
1219 int open_utf8(const char* pathname, int flags)
1221 int fd;
1222 unsigned char bom[BOM_SIZE];
1224 fd = open(pathname, flags);
1225 if(fd < 0)
1226 return fd;
1228 if(flags & (O_TRUNC | O_WRONLY))
1230 write(fd, BOM, BOM_SIZE);
1232 else
1234 read(fd, bom, BOM_SIZE);
1235 /* check for BOM */
1236 if(memcmp(bom, BOM, BOM_SIZE))
1237 lseek(fd, 0, SEEK_SET);
1239 return fd;
1243 #ifdef HAVE_LCD_COLOR
1245 * Helper function to convert a string of 6 hex digits to a native colour
1248 static int hex2dec(int c)
1250 return (((c) >= '0' && ((c) <= '9')) ? (c) - '0' :
1251 (toupper(c)) - 'A' + 10);
1254 int hex_to_rgb(const char* hex, int* color)
1256 int red, green, blue;
1257 int i = 0;
1259 while ((i < 6) && (isxdigit(hex[i])))
1260 i++;
1262 if (i < 6)
1263 return -1;
1265 red = (hex2dec(hex[0]) << 4) | hex2dec(hex[1]);
1266 green = (hex2dec(hex[2]) << 4) | hex2dec(hex[3]);
1267 blue = (hex2dec(hex[4]) << 4) | hex2dec(hex[5]);
1269 *color = LCD_RGBPACK(red,green,blue);
1271 return 0;
1273 #endif /* HAVE_LCD_COLOR */
1275 #ifdef HAVE_LCD_BITMAP
1276 /* A simplified scanf - used (at time of writing) by wps parsing functions.
1278 fmt - char array specifying the format of each list option. Valid values
1279 are: d - int
1280 s - string (sets pointer to string, without copying)
1281 c - hex colour (RGB888 - e.g. ff00ff)
1282 g - greyscale "colour" (0-3)
1283 set_vals - if not NULL 1 is set in the bitplace if the item was read OK
1284 0 if not read.
1285 first item is LSB, (max 32 items! )
1286 Stops parseing if an item is invalid unless the item == '-'
1287 sep - list separator (e.g. ',' or '|')
1288 str - string to parse, must be terminated by 0 or sep
1289 ... - pointers to store the parsed values
1291 return value - pointer to char after parsed data, 0 if there was an error.
1295 /* '0'-'3' are ASCII 0x30 to 0x33 */
1296 #define is0123(x) (((x) & 0xfc) == 0x30)
1298 const char* parse_list(const char *fmt, uint32_t *set_vals,
1299 const char sep, const char* str, ...)
1301 va_list ap;
1302 const char* p = str, *f = fmt;
1303 const char** s;
1304 int* d;
1305 bool set;
1306 int i=0;
1308 va_start(ap, str);
1309 if (set_vals)
1310 *set_vals = 0;
1311 while (*fmt)
1313 /* Check for separator, if we're not at the start */
1314 if (f != fmt)
1316 if (*p != sep)
1317 goto err;
1318 p++;
1320 set = false;
1321 switch (*fmt++)
1323 case 's': /* string - return a pointer to it (not a copy) */
1324 s = va_arg(ap, const char **);
1326 *s = p;
1327 while (*p && *p != sep)
1328 p++;
1329 set = (s[0][0]!='-') && (s[0][1]!=sep) ;
1330 break;
1332 case 'd': /* int */
1333 d = va_arg(ap, int*);
1334 if (!isdigit(*p))
1336 if (!set_vals || *p != '-')
1337 goto err;
1338 while (*p && *p != sep)
1339 p++;
1341 else
1343 *d = *p++ - '0';
1344 while (isdigit(*p))
1345 *d = (*d * 10) + (*p++ - '0');
1346 set = true;
1349 break;
1351 #ifdef HAVE_LCD_COLOR
1352 case 'c': /* colour (rrggbb - e.g. f3c1a8) */
1353 d = va_arg(ap, int*);
1355 if (hex_to_rgb(p, d) < 0)
1357 if (!set_vals || *p != '-')
1358 goto err;
1359 while (*p && *p != sep)
1360 p++;
1362 else
1364 p += 6;
1365 set = true;
1368 break;
1369 #endif
1371 #if LCD_DEPTH == 2 || (defined(HAVE_REMOTE_LCD) && LCD_REMOTE_DEPTH == 2)
1372 case 'g': /* greyscale colour (0-3) */
1373 d = va_arg(ap, int*);
1375 if (is0123(*p))
1377 *d = *p++ - '0';
1378 set = true;
1380 else if (!set_vals || *p != '-')
1381 goto err;
1382 else
1384 while (*p && *p != sep)
1385 p++;
1388 break;
1389 #endif
1391 default: /* Unknown format type */
1392 goto err;
1393 break;
1395 if (set_vals && set)
1396 *set_vals |= (1<<i);
1397 i++;
1400 va_end(ap);
1401 return p;
1403 err:
1404 va_end(ap);
1405 return 0;
1407 #endif