Remove DEBUGF tht slipped in
[kugel-rb.git] / apps / misc.c
blob1d83640dc4e96083942de910c3db8448bd98be8e
1 /***************************************************************************
2 * __________ __ ___.
3 * Open \______ \ ____ ____ | | _\_ |__ _______ ___
4 * Source | _// _ \_/ ___\| |/ /| __ \ / _ \ \/ /
5 * Jukebox | | ( <_> ) \___| < | \_\ ( <_> > < <
6 * Firmware |____|_ /\____/ \___ >__|_ \|___ /\____/__/\_ \
7 * \/ \/ \/ \/ \/
8 * $Id$
10 * Copyright (C) 2002 by Daniel Stenberg
12 * All files in this archive are subject to the GNU General Public License.
13 * See the file COPYING in the source tree root for full license agreement.
15 * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
16 * KIND, either express or implied.
18 ****************************************************************************/
19 #include <stdlib.h>
20 #include <ctype.h>
21 #include "config.h"
22 #include "lcd.h"
23 #include "file.h"
24 #ifdef __PCTOOL__
25 #include <stdarg.h>
26 #else
27 #include "sprintf.h"
28 #include "lang.h"
29 #include "string.h"
30 #include "dir.h"
31 #include "lcd-remote.h"
32 #include "errno.h"
33 #include "system.h"
34 #include "timefuncs.h"
35 #include "screens.h"
36 #include "talk.h"
37 #include "mpeg.h"
38 #include "audio.h"
39 #include "mp3_playback.h"
40 #include "settings.h"
41 #include "ata.h"
42 #include "ata_idle_notify.h"
43 #include "kernel.h"
44 #include "power.h"
45 #include "powermgmt.h"
46 #include "backlight.h"
47 #include "atoi.h"
48 #include "version.h"
49 #include "font.h"
50 #include "splash.h"
51 #include "tagcache.h"
52 #include "scrobbler.h"
53 #include "sound.h"
55 #ifdef HAVE_MMC
56 #include "ata_mmc.h"
57 #endif
58 #include "tree.h"
59 #include "eeprom_settings.h"
60 #if defined(HAVE_RECORDING) && !defined(__PCTOOL__)
61 #include "recording.h"
62 #endif
63 #if defined(HAVE_LCD_BITMAP) && !defined(__PCTOOL__)
64 #include "bmp.h"
65 #include "icons.h"
66 #endif /* End HAVE_LCD_BITMAP */
67 #include "gui/gwps-common.h"
68 #include "bookmark.h"
70 #include "misc.h"
71 #include "playback.h"
73 #ifdef BOOTFILE
74 #if !defined(USB_NONE) && !defined(USB_IPODSTYLE)
75 #include "textarea.h"
76 #include "rolo.h"
77 #include "yesno.h"
78 #endif
79 #endif
81 /* Format a large-range value for output, using the appropriate unit so that
82 * the displayed value is in the range 1 <= display < 1000 (1024 for "binary"
83 * units) if possible, and 3 significant digits are shown. If a buffer is
84 * given, the result is snprintf()'d into that buffer, otherwise the result is
85 * voiced.*/
86 char *output_dyn_value(char *buf, int buf_size, int value,
87 const unsigned char **units, bool bin_scale)
89 int scale = bin_scale ? 1024 : 1000;
90 int fraction = 0;
91 int unit_no = 0;
92 int i;
93 char tbuf[5];
95 while (value >= scale)
97 fraction = value % scale;
98 value /= scale;
99 unit_no++;
101 if (bin_scale)
102 fraction = fraction * 1000 / 1024;
104 if (value >= 100 || !unit_no)
105 tbuf[0] = '\0';
106 else if (value >= 10)
107 snprintf(tbuf, sizeof(tbuf), "%01d", fraction / 100);
108 else
109 snprintf(tbuf, sizeof(tbuf), "%02d", fraction / 10);
111 if (buf)
113 if (strlen(tbuf))
114 snprintf(buf, buf_size, "%d%s%s%s", value, str(LANG_POINT),
115 tbuf, P2STR(units[unit_no]));
116 else
117 snprintf(buf, buf_size, "%d%s", value, P2STR(units[unit_no]));
119 else
121 /* strip trailing zeros from the fraction */
122 for (i = strlen(tbuf) - 1; (i >= 0) && (tbuf[i] == '0'); i--)
123 tbuf[i] = '\0';
125 talk_number(value, true);
126 if (tbuf[0] != 0)
128 talk_id(LANG_POINT, true);
129 talk_spell(tbuf, true);
131 talk_id(P2ID(units[unit_no]), true);
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;
206 /* Format time into buf.
208 * buf - buffer to format to.
209 * buf_size - size of buffer.
210 * t - time to format, in milliseconds.
212 void format_time(char* buf, int buf_size, long t)
214 if ( t < 3600000 )
216 snprintf(buf, buf_size, "%d:%02d",
217 (int) (t / 60000), (int) (t % 60000 / 1000));
219 else
221 snprintf(buf, buf_size, "%d:%02d:%02d",
222 (int) (t / 3600000), (int) (t % 3600000 / 60000),
223 (int) (t % 60000 / 1000));
227 #if CONFIG_RTC
228 /* Create a filename with a date+time part.
229 It is allowed that buffer and path point to the same memory location,
230 saving a strcpy(). Path must always be given without trailing slash.
231 unique_time as true makes the function wait until the current time has
232 changed. */
233 char *create_datetime_filename(char *buffer, const char *path,
234 const char *prefix, const char *suffix,
235 bool unique_time)
237 struct tm *tm = get_time();
238 static struct tm last_tm;
239 int pathlen;
241 while (unique_time && !memcmp(get_time(), &last_tm, sizeof (struct tm)))
242 sleep(HZ/10);
244 last_tm = *tm;
246 if (buffer != path)
247 strncpy(buffer, path, MAX_PATH);
249 pathlen = strlen(buffer);
250 snprintf(buffer + pathlen, MAX_PATH - pathlen,
251 "/%s%02d%02d%02d-%02d%02d%02d%s", prefix,
252 tm->tm_year % 100, tm->tm_mon + 1, tm->tm_mday,
253 tm->tm_hour, tm->tm_min, tm->tm_sec, suffix);
255 return buffer;
257 #endif /* CONFIG_RTC */
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 tree_flush();
630 call_ata_idle_notifys(true); /*doesnt work on usb and shutdown from ata thread */
633 static void system_restore(void)
635 tree_restore();
638 static bool clean_shutdown(void (*callback)(void *), void *parameter)
640 #ifdef SIMULATOR
641 (void)callback;
642 (void)parameter;
643 bookmark_autobookmark();
644 call_ata_idle_notifys(true);
645 exit(0);
646 #else
647 long msg_id = -1;
648 int i;
650 scrobbler_poweroff();
652 #if CONFIG_CHARGING && !defined(HAVE_POWEROFF_WHILE_CHARGING)
653 if(!charger_inserted())
654 #endif
656 bool batt_safe = battery_level_safe();
657 int audio_stat = audio_status();
659 FOR_NB_SCREENS(i)
660 screens[i].clear_display();
662 if (batt_safe)
664 #ifdef HAVE_TAGCACHE
665 if (!tagcache_prepare_shutdown())
667 cancel_shutdown();
668 gui_syncsplash(HZ, ID2P(LANG_TAGCACHE_BUSY));
669 return false;
671 #endif
672 if (battery_level() > 10)
673 gui_syncsplash(0, str(LANG_SHUTTINGDOWN));
674 else
676 msg_id = LANG_WARNING_BATTERY_LOW;
677 gui_syncsplash(0, "%s %s",
678 str(LANG_WARNING_BATTERY_LOW),
679 str(LANG_SHUTTINGDOWN));
682 else
684 msg_id = LANG_WARNING_BATTERY_EMPTY;
685 gui_syncsplash(0, "%s %s",
686 str(LANG_WARNING_BATTERY_EMPTY),
687 str(LANG_SHUTTINGDOWN));
690 if (global_settings.fade_on_stop
691 && (audio_stat & AUDIO_STATUS_PLAY))
693 fade(0);
696 if (batt_safe) /* do not save on critical battery */
698 #if defined(HAVE_RECORDING) && CONFIG_CODEC == SWCODEC
699 if (audio_stat & AUDIO_STATUS_RECORD)
701 rec_command(RECORDING_CMD_STOP);
702 /* wait for stop to complete */
703 while (audio_status() & AUDIO_STATUS_RECORD)
704 sleep(1);
706 #endif
707 bookmark_autobookmark();
709 /* audio_stop_recording == audio_stop for HWCODEC */
710 audio_stop();
712 if (callback != NULL)
713 callback(parameter);
715 #if CONFIG_CODEC != SWCODEC
716 /* wait for audio_stop or audio_stop_recording to complete */
717 while (audio_status())
718 sleep(1);
719 #endif
721 #if defined(HAVE_RECORDING) && CONFIG_CODEC == SWCODEC
722 audio_close_recording();
723 #endif
725 if(global_settings.talk_menu)
727 bool enqueue = false;
728 if(msg_id != -1)
730 talk_id(msg_id, enqueue);
731 enqueue = true;
733 talk_id(LANG_SHUTTINGDOWN, enqueue);
734 #if CONFIG_CODEC == SWCODEC
735 voice_wait();
736 #endif
739 system_flush();
740 #ifdef HAVE_EEPROM_SETTINGS
741 if (firmware_settings.initialized)
743 firmware_settings.disk_clean = true;
744 firmware_settings.bl_version = 0;
745 eeprom_settings_store();
747 #endif
749 #ifdef HAVE_DIRCACHE
750 else
751 dircache_disable();
752 #endif
754 shutdown_hw();
756 #endif
757 return false;
760 bool list_stop_handler(void)
762 bool ret = false;
764 /* Stop the music if it is playing */
765 if(audio_status())
767 if (!global_settings.party_mode)
769 if (global_settings.fade_on_stop)
770 fade(0);
771 bookmark_autobookmark();
772 audio_stop();
773 ret = true; /* bookmarking can make a refresh necessary */
776 #if CONFIG_CHARGING
777 #if (CONFIG_KEYPAD == RECORDER_PAD) && !defined(HAVE_SW_POWEROFF)
778 else
780 if (charger_inserted())
781 charging_splash();
782 else
783 shutdown_screen(); /* won't return if shutdown actually happens */
785 ret = true; /* screen is dirty, caller needs to refresh */
787 #endif
788 #ifndef HAVE_POWEROFF_WHILE_CHARGING
790 static long last_off = 0;
792 if (TIME_BEFORE(current_tick, last_off + HZ/2))
794 if (charger_inserted())
796 charging_splash();
797 ret = true; /* screen is dirty, caller needs to refresh */
800 last_off = current_tick;
802 #endif
803 #endif /* CONFIG_CHARGING */
804 return ret;
807 #if CONFIG_CHARGING
808 static bool waiting_to_resume_play = false;
809 static long play_resume_tick;
811 static void car_adapter_mode_processing(bool inserted)
813 if (global_settings.car_adapter_mode)
815 if(inserted)
818 * Just got plugged in, delay & resume if we were playing
820 if (audio_status() & AUDIO_STATUS_PAUSE)
822 /* delay resume a bit while the engine is cranking */
823 play_resume_tick = current_tick + HZ*5;
824 waiting_to_resume_play = true;
827 else
830 * Just got unplugged, pause if playing
832 if ((audio_status() & AUDIO_STATUS_PLAY) &&
833 !(audio_status() & AUDIO_STATUS_PAUSE))
835 if (global_settings.fade_on_stop)
836 fade(0);
837 else
838 audio_pause();
840 waiting_to_resume_play = false;
845 static void car_adapter_tick(void)
847 if (waiting_to_resume_play)
849 if (TIME_AFTER(current_tick, play_resume_tick))
851 if (audio_status() & AUDIO_STATUS_PAUSE)
853 queue_broadcast(SYS_CAR_ADAPTER_RESUME, 0);
855 waiting_to_resume_play = false;
860 void car_adapter_mode_init(void)
862 tick_add_task(car_adapter_tick);
864 #endif
866 #ifdef HAVE_HEADPHONE_DETECTION
867 static void unplug_change(bool inserted)
869 static bool headphone_caused_pause = false;
871 if (global_settings.unplug_mode)
873 int audio_stat = audio_status();
874 if (inserted)
876 if ((audio_stat & AUDIO_STATUS_PLAY) &&
877 headphone_caused_pause &&
878 global_settings.unplug_mode > 1 )
879 audio_resume();
880 backlight_on();
881 headphone_caused_pause = false;
882 } else {
883 if ((audio_stat & AUDIO_STATUS_PLAY) &&
884 !(audio_stat & AUDIO_STATUS_PAUSE))
886 headphone_caused_pause = true;
887 audio_pause();
889 if (global_settings.unplug_rw)
891 if (audio_current_track()->elapsed >
892 (unsigned long)(global_settings.unplug_rw*1000))
893 audio_ff_rewind(audio_current_track()->elapsed -
894 (global_settings.unplug_rw*1000));
895 else
896 audio_ff_rewind(0);
902 #endif
904 long default_event_handler_ex(long event, void (*callback)(void *), void *parameter)
906 switch(event)
908 case SYS_BATTERY_UPDATE:
909 if(global_settings.talk_battery_level)
911 talk_ids(true, VOICE_PAUSE, VOICE_PAUSE,
912 LANG_BATTERY_TIME,
913 TALK_ID(battery_level(), UNIT_PERCENT),
914 VOICE_PAUSE);
915 talk_force_enqueue_next();
917 break;
918 case SYS_USB_CONNECTED:
919 if (callback != NULL)
920 callback(parameter);
921 #ifdef HAVE_MMC
922 if (!mmc_touched() ||
923 (mmc_remove_request() == SYS_HOTSWAP_EXTRACTED))
924 #endif
926 scrobbler_flush_cache();
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
969 return 0;
972 long default_event_handler(long event)
974 return default_event_handler_ex(event, NULL, NULL);
977 int show_logo( void )
979 #ifdef HAVE_LCD_BITMAP
980 char version[32];
981 int font_h, font_w;
983 snprintf(version, sizeof(version), "Ver. %s", appsversion);
985 lcd_clear_display();
986 lcd_bitmap(rockboxlogo, 0, 10, BMPWIDTH_rockboxlogo, BMPHEIGHT_rockboxlogo);
987 lcd_setfont(FONT_SYSFIXED);
988 lcd_getstringsize((unsigned char *)"A", &font_w, &font_h);
989 lcd_putsxy((LCD_WIDTH/2) - ((strlen(version)*font_w)/2),
990 LCD_HEIGHT-font_h, (unsigned char *)version);
991 lcd_setfont(FONT_UI);
993 #else
994 char *rockbox = " ROCKbox!";
996 lcd_clear_display();
997 lcd_double_height(true);
998 lcd_puts(0, 0, rockbox);
999 lcd_puts_scroll(0, 1, appsversion);
1000 #endif
1001 lcd_update();
1003 #ifdef HAVE_REMOTE_LCD
1004 lcd_remote_clear_display();
1005 lcd_remote_bitmap(remote_rockboxlogo, 0, 10, BMPWIDTH_remote_rockboxlogo,
1006 BMPHEIGHT_remote_rockboxlogo);
1007 lcd_remote_setfont(FONT_SYSFIXED);
1008 lcd_remote_getstringsize((unsigned char *)"A", &font_w, &font_h);
1009 lcd_remote_putsxy((LCD_REMOTE_WIDTH/2) - ((strlen(version)*font_w)/2),
1010 LCD_REMOTE_HEIGHT-font_h, (unsigned char *)version);
1011 lcd_remote_setfont(FONT_UI);
1012 lcd_remote_update();
1013 #endif
1015 return 0;
1018 #if CONFIG_CODEC == SWCODEC
1019 int get_replaygain_mode(bool have_track_gain, bool have_album_gain)
1021 int type;
1023 bool track = ((global_settings.replaygain_type == REPLAYGAIN_TRACK)
1024 || ((global_settings.replaygain_type == REPLAYGAIN_SHUFFLE)
1025 && global_settings.playlist_shuffle));
1027 type = (!track && have_album_gain) ? REPLAYGAIN_ALBUM
1028 : have_track_gain ? REPLAYGAIN_TRACK : -1;
1030 return type;
1032 #endif
1034 #ifdef BOOTFILE
1035 #if !defined(USB_NONE) && !defined(USB_IPODSTYLE)
1037 memorize/compare details about the BOOTFILE
1038 we don't use dircache because it may not be up to date after
1039 USB disconnect (scanning in the background)
1041 void check_bootfile(bool do_rolo)
1043 static unsigned short wrtdate = 0;
1044 static unsigned short wrttime = 0;
1045 DIR* dir = NULL;
1046 struct dirent* entry = NULL;
1048 /* 1. open BOOTDIR and find the BOOTFILE dir entry */
1049 dir = opendir(BOOTDIR);
1051 if(!dir) return; /* do we want an error splash? */
1053 /* loop all files in BOOTDIR */
1054 while(0 != (entry = readdir(dir)))
1056 if(!strcasecmp(entry->d_name, BOOTFILE))
1058 /* found the bootfile */
1059 if(wrtdate && do_rolo)
1061 if((entry->wrtdate != wrtdate) ||
1062 (entry->wrttime != wrttime))
1064 char *lines[] = { ID2P(LANG_BOOT_CHANGED),
1065 ID2P(LANG_REBOOT_NOW) };
1066 struct text_message message={ lines, 2 };
1067 button_clear_queue(); /* Empty the keyboard buffer */
1068 if(gui_syncyesno_run(&message, NULL, NULL) == YESNO_YES)
1069 rolo_load(BOOTDIR "/" BOOTFILE);
1072 wrtdate = entry->wrtdate;
1073 wrttime = entry->wrttime;
1076 closedir(dir);
1078 #endif
1079 #endif
1081 /* check range, set volume and save settings */
1082 void setvol(void)
1084 const int min_vol = sound_min(SOUND_VOLUME);
1085 const int max_vol = sound_max(SOUND_VOLUME);
1086 if (global_settings.volume < min_vol)
1087 global_settings.volume = min_vol;
1088 if (global_settings.volume > max_vol)
1089 global_settings.volume = max_vol;
1090 sound_set_volume(global_settings.volume);
1091 settings_save();
1094 char* strrsplt(char* str, int c)
1096 char* s = strrchr(str, c);
1098 if (s != NULL)
1100 *s++ = '\0';
1102 else
1104 s = str;
1107 return s;
1110 /* Test file existence, using dircache of possible */
1111 bool file_exists(const char *file)
1113 int fd;
1115 if (!file || strlen(file) <= 0)
1116 return false;
1118 #ifdef HAVE_DIRCACHE
1119 if (dircache_is_enabled())
1120 return (dircache_get_entry_ptr(file) != NULL);
1121 #endif
1123 fd = open(file, O_RDONLY);
1124 if (fd < 0)
1125 return false;
1126 close(fd);
1127 return true;
1130 bool dir_exists(const char *path)
1132 DIR* d = opendir(path);
1133 if (!d)
1134 return false;
1135 closedir(d);
1136 return true;
1140 * removes the extension of filename (if it doesn't start with a .)
1141 * puts the result in buffer
1143 char *strip_extension(char* buffer, int buffer_size, const char *filename)
1145 char *dot = strrchr(filename, '.');
1146 int len;
1148 if (buffer_size <= 0)
1150 return NULL;
1153 buffer_size--; /* Make room for end nil */
1155 if (dot != 0 && filename[0] != '.')
1157 len = dot - filename;
1158 len = MIN(len, buffer_size);
1159 strncpy(buffer, filename, len);
1161 else
1163 len = buffer_size;
1164 strncpy(buffer, filename, buffer_size);
1167 buffer[len] = 0;
1169 return buffer;
1171 #endif /* !defined(__PCTOOL__) */
1173 #ifdef HAVE_LCD_COLOR
1175 * Helper function to convert a string of 6 hex digits to a native colour
1178 static int hex2dec(int c)
1180 return (((c) >= '0' && ((c) <= '9')) ? (c) - '0' :
1181 (toupper(c)) - 'A' + 10);
1184 int hex_to_rgb(const char* hex, int* color)
1186 int red, green, blue;
1187 int i = 0;
1189 while ((i < 6) && (isxdigit(hex[i])))
1190 i++;
1192 if (i < 6)
1193 return -1;
1195 red = (hex2dec(hex[0]) << 4) | hex2dec(hex[1]);
1196 green = (hex2dec(hex[2]) << 4) | hex2dec(hex[3]);
1197 blue = (hex2dec(hex[4]) << 4) | hex2dec(hex[5]);
1199 *color = LCD_RGBPACK(red,green,blue);
1201 return 0;
1203 #endif /* HAVE_LCD_COLOR */
1205 #ifdef HAVE_LCD_BITMAP
1206 /* A simplified scanf - used (at time of writing) by wps parsing functions.
1208 fmt - char array specifying the format of each list option. Valid values
1209 are: d - int
1210 s - string (sets pointer to string, without copying)
1211 c - hex colour (RGB888 - e.g. ff00ff)
1212 g - greyscale "colour" (0-3)
1214 sep - list separator (e.g. ',' or '|')
1215 str - string to parse, must be terminated by 0 or sep
1216 ... - pointers to store the parsed values
1218 return value - pointer to char after parsed data, 0 if there was an error.
1222 /* '0'-'3' are ASCII 0x30 to 0x33 */
1223 #define is0123(x) (((x) & 0xfc) == 0x30)
1225 const char* parse_list(const char *fmt, const char sep, const char* str, ...)
1227 va_list ap;
1228 const char* p = str;
1229 const char** s;
1230 int* d;
1232 va_start(ap, str);
1234 while (*fmt)
1236 /* Check for separator, if we're not at the start */
1237 if (p != str)
1239 if (*p != sep)
1240 goto err;
1241 p++;
1244 switch (*fmt++)
1246 case 's': /* string - return a pointer to it (not a copy) */
1247 s = va_arg(ap, const char **);
1249 *s = p;
1250 while (*p && *p != sep)
1251 p++;
1253 break;
1255 case 'd': /* int */
1256 d = va_arg(ap, int*);
1257 if (!isdigit(*p))
1258 goto err;
1260 *d = *p++ - '0';
1262 while (isdigit(*p))
1263 *d = (*d * 10) + (*p++ - '0');
1265 break;
1267 #ifdef HAVE_LCD_COLOR
1268 case 'c': /* colour (rrggbb - e.g. f3c1a8) */
1269 d = va_arg(ap, int*);
1271 if (hex_to_rgb(p, d) < 0)
1272 goto err;
1274 p += 6;
1276 break;
1277 #endif
1279 #if LCD_DEPTH == 2 || (defined(HAVE_REMOTE_LCD) && LCD_REMOTE_DEPTH == 2)
1280 case 'g': /* greyscale colour (0-3) */
1281 d = va_arg(ap, int*);
1283 if (is0123(*p))
1284 *d = *p++ - '0';
1285 else
1286 goto err;
1288 break;
1289 #endif
1291 default: /* Unknown format type */
1292 goto err;
1293 break;
1297 va_end(ap);
1298 return p;
1300 err:
1301 va_end(ap);
1302 return 0;
1304 #endif