GCC suggests parentheses so give it some (aka fix yellow).
[kugel-rb.git] / apps / misc.c
blobb1d795708c1fb09fbd35360fe70f696c8106149b
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 /* LCD_DEPTH != 16 */
348 #define BMP_COMPRESSION 0 /* BI_RGB */
349 #if LCD_DEPTH <= 8
350 #ifdef HAVE_LCD_SPLIT
351 #define BMP_NUMCOLORS (2 << LCD_DEPTH)
352 #else
353 #define BMP_NUMCOLORS (1 << LCD_DEPTH)
354 #endif
355 #else /* LCD_DEPTH > 8 */
356 #define BMP_NUMCOLORS 0
357 #endif /* LCD_DEPTH > 8 */
358 #endif /* LCD_DEPTH != 16 */
360 #if LCD_DEPTH <= 4
361 #define BMP_BPP 4
362 #define BMP_LINESIZE ((LCD_WIDTH/2 + 3) & ~3)
363 #elif LCD_DEPTH <= 8
364 #define BMP_BPP 8
365 #define BMP_LINESIZE ((LCD_WIDTH + 3) & ~3)
366 #elif LCD_DEPTH <= 16
367 #define BMP_BPP 16
368 #define BMP_LINESIZE ((LCD_WIDTH*2 + 3) & ~3)
369 #else
370 #define BMP_BPP 24
371 #define BMP_LINESIZE ((LCD_WIDTH*3 + 3) & ~3)
372 #endif
374 #define BMP_HEADERSIZE (54 + 4 * BMP_NUMCOLORS)
375 #define BMP_DATASIZE (BMP_LINESIZE * LCD_HEIGHT)
376 #define BMP_TOTALSIZE (BMP_HEADERSIZE + BMP_DATASIZE)
378 #define LE16_CONST(x) (x)&0xff, ((x)>>8)&0xff
379 #define LE32_CONST(x) (x)&0xff, ((x)>>8)&0xff, ((x)>>16)&0xff, ((x)>>24)&0xff
381 static const unsigned char bmpheader[] =
383 0x42, 0x4d, /* 'BM' */
384 LE32_CONST(BMP_TOTALSIZE), /* Total file size */
385 0x00, 0x00, 0x00, 0x00, /* Reserved */
386 LE32_CONST(BMP_HEADERSIZE), /* Offset to start of pixel data */
388 0x28, 0x00, 0x00, 0x00, /* Size of (2nd) header */
389 LE32_CONST(LCD_WIDTH), /* Width in pixels */
390 LE32_CONST(LCD_HEIGHT+LCD_SPLIT_LINES), /* Height in pixels */
391 0x01, 0x00, /* Number of planes (always 1) */
392 LE16_CONST(BMP_BPP), /* Bits per pixel 1/4/8/16/24 */
393 LE32_CONST(BMP_COMPRESSION),/* Compression mode */
394 LE32_CONST(BMP_DATASIZE), /* Size of bitmap data */
395 0xc4, 0x0e, 0x00, 0x00, /* Horizontal resolution (pixels/meter) */
396 0xc4, 0x0e, 0x00, 0x00, /* Vertical resolution (pixels/meter) */
397 LE32_CONST(BMP_NUMCOLORS), /* Number of used colours */
398 LE32_CONST(BMP_NUMCOLORS), /* Number of important colours */
400 #if LCD_DEPTH == 1
401 #ifdef HAVE_NEGATIVE_LCD
402 BMP_COLOR(LCD_BL_DARKCOLOR),
403 BMP_COLOR(LCD_BL_BRIGHTCOLOR),
404 #ifdef HAVE_LCD_SPLIT
405 BMP_COLOR(LCD_BL_DARKCOLOR_2),
406 BMP_COLOR(LCD_BL_BRIGHTCOLOR_2),
407 #endif
408 #else /* positive display */
409 BMP_COLOR(LCD_BL_BRIGHTCOLOR),
410 BMP_COLOR(LCD_BL_DARKCOLOR),
411 #endif /* positive display */
412 #elif LCD_DEPTH == 2
413 BMP_COLOR(LCD_BL_BRIGHTCOLOR),
414 BMP_COLOR_MIX(LCD_BL_BRIGHTCOLOR, LCD_BL_DARKCOLOR, 1, 3),
415 BMP_COLOR_MIX(LCD_BL_BRIGHTCOLOR, LCD_BL_DARKCOLOR, 2, 3),
416 BMP_COLOR(LCD_BL_DARKCOLOR),
417 #elif LCD_DEPTH == 16
418 0x00, 0xf8, 0x00, 0x00, /* red bitfield mask */
419 0xe0, 0x07, 0x00, 0x00, /* green bitfield mask */
420 0x1f, 0x00, 0x00, 0x00, /* blue bitfield mask */
421 #endif
424 static void (*screen_dump_hook)(int fh) = NULL;
426 void screen_dump(void)
428 int fd, y;
429 char filename[MAX_PATH];
431 fb_data *src;
432 #if LCD_DEPTH == 1
433 unsigned mask;
434 unsigned val;
435 #elif (LCD_DEPTH == 2) && (LCD_PIXELFORMAT != HORIZONTAL_PACKING)
436 int shift;
437 unsigned val;
438 #endif
439 #if LCD_DEPTH <= 8
440 unsigned char *dst, *dst_end;
441 unsigned char linebuf[BMP_LINESIZE];
442 #elif LCD_DEPTH <= 16
443 unsigned short *dst, *dst_end;
444 unsigned short linebuf[BMP_LINESIZE/2];
445 #endif
447 #if CONFIG_RTC
448 create_datetime_filename(filename, "", "dump ", ".bmp", false);
449 #else
450 create_numbered_filename(filename, "", "dump_", ".bmp", 4
451 IF_CNFN_NUM_(, NULL));
452 #endif
454 fd = creat(filename);
455 if (fd < 0)
456 return;
458 if (screen_dump_hook)
460 screen_dump_hook(fd);
462 else
464 write(fd, bmpheader, sizeof(bmpheader));
466 /* BMP image goes bottom up */
467 for (y = LCD_HEIGHT - 1; y >= 0; y--)
469 memset(linebuf, 0, BMP_LINESIZE);
471 #if defined(HAVE_LCD_SPLIT) && (LCD_SPLIT_LINES == 2)
472 if (y == LCD_SPLIT_POS - 1)
474 write(fd, linebuf, BMP_LINESIZE);
475 write(fd, linebuf, BMP_LINESIZE);
477 #endif
478 dst = linebuf;
480 #if LCD_DEPTH == 1
481 dst_end = dst + LCD_WIDTH/2;
482 src = lcd_framebuffer[y >> 3];
483 mask = 1 << (y & 7);
487 val = (*src++ & mask) ? 0x10 : 0;
488 val |= (*src++ & mask) ? 0x01 : 0;
489 #ifdef HAVE_LCD_SPLIT
490 if (y < LCD_SPLIT_POS)
491 val |= 0x22;
492 #endif
493 *dst++ = val;
495 while (dst < dst_end);
497 #elif LCD_DEPTH == 2
498 dst_end = dst + LCD_WIDTH/2;
500 #if LCD_PIXELFORMAT == HORIZONTAL_PACKING
501 src = lcd_framebuffer[y];
505 unsigned data = *src++;
507 *dst++ = ((data >> 2) & 0x30) | ((data >> 4) & 0x03);
508 *dst++ = ((data << 2) & 0x30) | (data & 0x03);
510 while (dst < dst_end);
512 #elif LCD_PIXELFORMAT == VERTICAL_PACKING
513 src = lcd_framebuffer[y >> 2];
514 shift = 2 * (y & 3);
518 val = ((*src++ >> shift) & 3) << 4;
519 val |= ((*src++ >> shift) & 3);
520 *dst++ = val;
522 while (dst < dst_end);
524 #elif LCD_PIXELFORMAT == VERTICAL_INTERLEAVED
525 src = lcd_framebuffer[y >> 3];
526 shift = y & 7;
530 unsigned data = (*src++ >> shift) & 0x0101;
532 val = (((data >> 7) | data) & 3) << 4;
533 data = (*src++ >> shift) & 0x0101;
534 val |= ((data >> 7) | data) & 3;
535 *dst++ = val;
537 while (dst < dst_end);
539 #endif
540 #elif LCD_DEPTH == 16
541 dst_end = dst + LCD_WIDTH;
542 src = lcd_framebuffer[y];
546 #if (LCD_PIXELFORMAT == RGB565SWAPPED)
547 /* iPod LCD data is big endian although the CPU is not */
548 *dst++ = htobe16(*src++);
549 #else
550 *dst++ = htole16(*src++);
551 #endif
553 while (dst < dst_end);
555 #endif /* LCD_DEPTH */
556 write(fd, linebuf, BMP_LINESIZE);
559 close(fd);
562 void screen_dump_set_hook(void (*hook)(int fh))
564 screen_dump_hook = hook;
567 #endif /* HAVE_LCD_BITMAP */
569 /* parse a line from a configuration file. the line format is:
571 name: value
573 Any whitespace before setting name or value (after ':') is ignored.
574 A # as first non-whitespace character discards the whole line.
575 Function sets pointers to null-terminated setting name and value.
576 Returns false if no valid config entry was found.
579 bool settings_parseline(char* line, char** name, char** value)
581 char* ptr;
583 line = skip_whitespace(line);
585 if ( *line == '#' )
586 return false;
588 ptr = strchr(line, ':');
589 if ( !ptr )
590 return false;
592 *name = line;
593 *ptr = 0;
594 ptr++;
595 ptr = skip_whitespace(ptr);
596 *value = ptr;
597 return true;
600 static void system_flush(void)
602 scrobbler_shutdown();
603 playlist_shutdown();
604 tree_flush();
605 call_storage_idle_notifys(true); /*doesnt work on usb and shutdown from ata thread */
608 static void system_restore(void)
610 tree_restore();
611 scrobbler_init();
614 static bool clean_shutdown(void (*callback)(void *), void *parameter)
616 #ifdef SIMULATOR
617 (void)callback;
618 (void)parameter;
619 bookmark_autobookmark();
620 call_storage_idle_notifys(true);
621 exit(0);
622 #else
623 long msg_id = -1;
624 int i;
626 scrobbler_poweroff();
628 #if CONFIG_CHARGING && !defined(HAVE_POWEROFF_WHILE_CHARGING)
629 if(!charger_inserted())
630 #endif
632 bool batt_safe = battery_level_safe();
633 int audio_stat = audio_status();
635 FOR_NB_SCREENS(i)
636 screens[i].clear_display();
638 if (batt_safe)
640 #ifdef HAVE_TAGCACHE
641 if (!tagcache_prepare_shutdown())
643 cancel_shutdown();
644 splash(HZ, ID2P(LANG_TAGCACHE_BUSY));
645 return false;
647 #endif
648 if (battery_level() > 10)
649 splash(0, str(LANG_SHUTTINGDOWN));
650 else
652 msg_id = LANG_WARNING_BATTERY_LOW;
653 splashf(0, "%s %s", str(LANG_WARNING_BATTERY_LOW),
654 str(LANG_SHUTTINGDOWN));
657 else
659 msg_id = LANG_WARNING_BATTERY_EMPTY;
660 splashf(0, "%s %s", str(LANG_WARNING_BATTERY_EMPTY),
661 str(LANG_SHUTTINGDOWN));
664 if (global_settings.fade_on_stop
665 && (audio_stat & AUDIO_STATUS_PLAY))
667 fade(false, false);
670 if (batt_safe) /* do not save on critical battery */
672 #if defined(HAVE_RECORDING) && CONFIG_CODEC == SWCODEC
673 if (audio_stat & AUDIO_STATUS_RECORD)
675 rec_command(RECORDING_CMD_STOP);
676 /* wait for stop to complete */
677 while (audio_status() & AUDIO_STATUS_RECORD)
678 sleep(1);
680 #endif
681 bookmark_autobookmark();
683 /* audio_stop_recording == audio_stop for HWCODEC */
684 audio_stop();
686 if (callback != NULL)
687 callback(parameter);
689 #if CONFIG_CODEC != SWCODEC
690 /* wait for audio_stop or audio_stop_recording to complete */
691 while (audio_status())
692 sleep(1);
693 #endif
695 #if defined(HAVE_RECORDING) && CONFIG_CODEC == SWCODEC
696 audio_close_recording();
697 #endif
699 if(global_settings.talk_menu)
701 bool enqueue = false;
702 if(msg_id != -1)
704 talk_id(msg_id, enqueue);
705 enqueue = true;
707 talk_id(LANG_SHUTTINGDOWN, enqueue);
708 #if CONFIG_CODEC == SWCODEC
709 voice_wait();
710 #endif
713 system_flush();
714 #ifdef HAVE_EEPROM_SETTINGS
715 if (firmware_settings.initialized)
717 firmware_settings.disk_clean = true;
718 firmware_settings.bl_version = 0;
719 eeprom_settings_store();
721 #endif
723 #ifdef HAVE_DIRCACHE
724 else
725 dircache_disable();
726 #endif
728 shutdown_hw();
730 #endif
731 return false;
734 bool list_stop_handler(void)
736 bool ret = false;
738 /* Stop the music if it is playing */
739 if(audio_status())
741 if (!global_settings.party_mode)
743 if (global_settings.fade_on_stop)
744 fade(false, false);
745 bookmark_autobookmark();
746 audio_stop();
747 ret = true; /* bookmarking can make a refresh necessary */
750 #if CONFIG_CHARGING
751 #if (CONFIG_KEYPAD == RECORDER_PAD) && !defined(HAVE_SW_POWEROFF)
752 else
754 if (charger_inserted())
755 charging_splash();
756 else
757 shutdown_screen(); /* won't return if shutdown actually happens */
759 ret = true; /* screen is dirty, caller needs to refresh */
761 #endif
762 #ifndef HAVE_POWEROFF_WHILE_CHARGING
764 static long last_off = 0;
766 if (TIME_BEFORE(current_tick, last_off + HZ/2))
768 if (charger_inserted())
770 charging_splash();
771 ret = true; /* screen is dirty, caller needs to refresh */
774 last_off = current_tick;
776 #endif
777 #endif /* CONFIG_CHARGING */
778 return ret;
781 #if CONFIG_CHARGING
782 static bool waiting_to_resume_play = false;
783 static long play_resume_tick;
785 static void car_adapter_mode_processing(bool inserted)
787 if (global_settings.car_adapter_mode)
789 if(inserted)
792 * Just got plugged in, delay & resume if we were playing
794 if (audio_status() & AUDIO_STATUS_PAUSE)
796 /* delay resume a bit while the engine is cranking */
797 play_resume_tick = current_tick + HZ*5;
798 waiting_to_resume_play = true;
801 else
804 * Just got unplugged, pause if playing
806 if ((audio_status() & AUDIO_STATUS_PLAY) &&
807 !(audio_status() & AUDIO_STATUS_PAUSE))
809 if (global_settings.fade_on_stop)
810 fade(false, false);
811 else
812 audio_pause();
814 waiting_to_resume_play = false;
819 static void car_adapter_tick(void)
821 if (waiting_to_resume_play)
823 if (TIME_AFTER(current_tick, play_resume_tick))
825 if (audio_status() & AUDIO_STATUS_PAUSE)
827 queue_broadcast(SYS_CAR_ADAPTER_RESUME, 0);
829 waiting_to_resume_play = false;
834 void car_adapter_mode_init(void)
836 tick_add_task(car_adapter_tick);
838 #endif
840 #ifdef HAVE_HEADPHONE_DETECTION
841 static void unplug_change(bool inserted)
843 static bool headphone_caused_pause = false;
845 if (global_settings.unplug_mode)
847 int audio_stat = audio_status();
848 if (inserted)
850 if ((audio_stat & AUDIO_STATUS_PLAY) &&
851 headphone_caused_pause &&
852 global_settings.unplug_mode > 1 )
853 audio_resume();
854 backlight_on();
855 headphone_caused_pause = false;
856 } else {
857 if ((audio_stat & AUDIO_STATUS_PLAY) &&
858 !(audio_stat & AUDIO_STATUS_PAUSE))
860 headphone_caused_pause = true;
861 audio_pause();
863 if (global_settings.unplug_rw)
865 if (audio_current_track()->elapsed >
866 (unsigned long)(global_settings.unplug_rw*1000))
867 audio_ff_rewind(audio_current_track()->elapsed -
868 (global_settings.unplug_rw*1000));
869 else
870 audio_ff_rewind(0);
876 #endif
878 long default_event_handler_ex(long event, void (*callback)(void *), void *parameter)
880 switch(event)
882 case SYS_BATTERY_UPDATE:
883 if(global_settings.talk_battery_level)
885 talk_ids(true, VOICE_PAUSE, VOICE_PAUSE,
886 LANG_BATTERY_TIME,
887 TALK_ID(battery_level(), UNIT_PERCENT),
888 VOICE_PAUSE);
889 talk_force_enqueue_next();
891 break;
892 case SYS_USB_CONNECTED:
893 if (callback != NULL)
894 callback(parameter);
895 #if (CONFIG_STORAGE & STORAGE_MMC)
896 if (!mmc_touched() ||
897 (mmc_remove_request() == SYS_HOTSWAP_EXTRACTED))
898 #endif
900 system_flush();
901 #ifdef BOOTFILE
902 #if !defined(USB_NONE) && !defined(USB_IPODSTYLE)
903 check_bootfile(false); /* gets initial size */
904 #endif
905 #endif
906 usb_screen();
907 #ifdef BOOTFILE
908 #if !defined(USB_NONE) && !defined(USB_IPODSTYLE)
909 check_bootfile(true);
910 #endif
911 #endif
912 system_restore();
914 return SYS_USB_CONNECTED;
915 case SYS_POWEROFF:
916 if (!clean_shutdown(callback, parameter))
917 return SYS_POWEROFF;
918 break;
919 #if CONFIG_CHARGING
920 case SYS_CHARGER_CONNECTED:
921 car_adapter_mode_processing(true);
922 return SYS_CHARGER_CONNECTED;
924 case SYS_CHARGER_DISCONNECTED:
925 car_adapter_mode_processing(false);
926 return SYS_CHARGER_DISCONNECTED;
928 case SYS_CAR_ADAPTER_RESUME:
929 audio_resume();
930 return SYS_CAR_ADAPTER_RESUME;
931 #endif
932 #ifdef HAVE_HEADPHONE_DETECTION
933 case SYS_PHONE_PLUGGED:
934 unplug_change(true);
935 return SYS_PHONE_PLUGGED;
937 case SYS_PHONE_UNPLUGGED:
938 unplug_change(false);
939 return SYS_PHONE_UNPLUGGED;
940 #endif
941 #ifdef IPOD_ACCESSORY_PROTOCOL
942 case SYS_IAP_PERIODIC:
943 iap_periodic();
944 return SYS_IAP_PERIODIC;
945 case SYS_IAP_HANDLEPKT:
946 iap_handlepkt();
947 return SYS_IAP_HANDLEPKT;
948 #endif
950 return 0;
953 long default_event_handler(long event)
955 return default_event_handler_ex(event, NULL, NULL);
958 int show_logo( void )
960 #ifdef HAVE_LCD_BITMAP
961 char version[32];
962 int font_h, font_w;
964 snprintf(version, sizeof(version), "Ver. %s", appsversion);
966 lcd_clear_display();
967 #ifdef SANSA_CLIP /* display the logo in the blue area of the screen */
968 lcd_setfont(FONT_SYSFIXED);
969 lcd_getstringsize((unsigned char *)"A", &font_w, &font_h);
970 lcd_putsxy((LCD_WIDTH/2) - ((strlen(version)*font_w)/2),
971 0, (unsigned char *)version);
972 lcd_bitmap(rockboxlogo, 0, 16, BMPWIDTH_rockboxlogo, BMPHEIGHT_rockboxlogo);
973 #else
974 lcd_bitmap(rockboxlogo, 0, 10, BMPWIDTH_rockboxlogo, BMPHEIGHT_rockboxlogo);
975 lcd_setfont(FONT_SYSFIXED);
976 lcd_getstringsize((unsigned char *)"A", &font_w, &font_h);
977 lcd_putsxy((LCD_WIDTH/2) - ((strlen(version)*font_w)/2),
978 LCD_HEIGHT-font_h, (unsigned char *)version);
979 #endif
980 lcd_setfont(FONT_UI);
982 #else
983 char *rockbox = " ROCKbox!";
985 lcd_clear_display();
986 lcd_double_height(true);
987 lcd_puts(0, 0, rockbox);
988 lcd_puts_scroll(0, 1, appsversion);
989 #endif
990 lcd_update();
992 #ifdef HAVE_REMOTE_LCD
993 lcd_remote_clear_display();
994 lcd_remote_bitmap(remote_rockboxlogo, 0, 10, BMPWIDTH_remote_rockboxlogo,
995 BMPHEIGHT_remote_rockboxlogo);
996 lcd_remote_setfont(FONT_SYSFIXED);
997 lcd_remote_getstringsize((unsigned char *)"A", &font_w, &font_h);
998 lcd_remote_putsxy((LCD_REMOTE_WIDTH/2) - ((strlen(version)*font_w)/2),
999 LCD_REMOTE_HEIGHT-font_h, (unsigned char *)version);
1000 lcd_remote_setfont(FONT_UI);
1001 lcd_remote_update();
1002 #endif
1004 return 0;
1007 #if CONFIG_CODEC == SWCODEC
1008 int get_replaygain_mode(bool have_track_gain, bool have_album_gain)
1010 int type;
1012 bool track = ((global_settings.replaygain_type == REPLAYGAIN_TRACK)
1013 || ((global_settings.replaygain_type == REPLAYGAIN_SHUFFLE)
1014 && global_settings.playlist_shuffle));
1016 type = (!track && have_album_gain) ? REPLAYGAIN_ALBUM
1017 : have_track_gain ? REPLAYGAIN_TRACK : -1;
1019 return type;
1021 #endif
1023 #ifdef BOOTFILE
1024 #if !defined(USB_NONE) && !defined(USB_IPODSTYLE)
1026 memorize/compare details about the BOOTFILE
1027 we don't use dircache because it may not be up to date after
1028 USB disconnect (scanning in the background)
1030 void check_bootfile(bool do_rolo)
1032 static unsigned short wrtdate = 0;
1033 static unsigned short wrttime = 0;
1034 DIR* dir = NULL;
1035 struct dirent* entry = NULL;
1037 /* 1. open BOOTDIR and find the BOOTFILE dir entry */
1038 dir = opendir(BOOTDIR);
1040 if(!dir) return; /* do we want an error splash? */
1042 /* loop all files in BOOTDIR */
1043 while(0 != (entry = readdir(dir)))
1045 if(!strcasecmp(entry->d_name, BOOTFILE))
1047 /* found the bootfile */
1048 if(wrtdate && do_rolo)
1050 if((entry->wrtdate != wrtdate) ||
1051 (entry->wrttime != wrttime))
1053 static const char *lines[] = { ID2P(LANG_BOOT_CHANGED),
1054 ID2P(LANG_REBOOT_NOW) };
1055 static const struct text_message message={ lines, 2 };
1056 button_clear_queue(); /* Empty the keyboard buffer */
1057 if(gui_syncyesno_run(&message, NULL, NULL) == YESNO_YES)
1058 rolo_load(BOOTDIR "/" BOOTFILE);
1061 wrtdate = entry->wrtdate;
1062 wrttime = entry->wrttime;
1065 closedir(dir);
1067 #endif
1068 #endif
1070 /* check range, set volume and save settings */
1071 void setvol(void)
1073 const int min_vol = sound_min(SOUND_VOLUME);
1074 const int max_vol = sound_max(SOUND_VOLUME);
1075 if (global_settings.volume < min_vol)
1076 global_settings.volume = min_vol;
1077 if (global_settings.volume > max_vol)
1078 global_settings.volume = max_vol;
1079 sound_set_volume(global_settings.volume);
1080 settings_save();
1083 char* strrsplt(char* str, int c)
1085 char* s = strrchr(str, c);
1087 if (s != NULL)
1089 *s++ = '\0';
1091 else
1093 s = str;
1096 return s;
1099 char* skip_whitespace(char* const str)
1101 char *s = str;
1103 while (isspace(*s))
1104 s++;
1106 return s;
1109 /* Test file existence, using dircache of possible */
1110 bool file_exists(const char *file)
1112 int fd;
1114 if (!file || strlen(file) <= 0)
1115 return false;
1117 #ifdef HAVE_DIRCACHE
1118 if (dircache_is_enabled())
1119 return (dircache_get_entry_ptr(file) != NULL);
1120 #endif
1122 fd = open(file, O_RDONLY);
1123 if (fd < 0)
1124 return false;
1125 close(fd);
1126 return true;
1129 bool dir_exists(const char *path)
1131 DIR* d = opendir(path);
1132 if (!d)
1133 return false;
1134 closedir(d);
1135 return true;
1139 * removes the extension of filename (if it doesn't start with a .)
1140 * puts the result in buffer
1142 char *strip_extension(char* buffer, int buffer_size, const char *filename)
1144 char *dot = strrchr(filename, '.');
1145 int len;
1147 if (buffer_size <= 0)
1149 return NULL;
1152 buffer_size--; /* Make room for end nil */
1154 if (dot != 0 && filename[0] != '.')
1156 len = dot - filename;
1157 len = MIN(len, buffer_size);
1158 strncpy(buffer, filename, len);
1160 else
1162 len = buffer_size;
1163 strncpy(buffer, filename, buffer_size);
1166 buffer[len] = 0;
1168 return buffer;
1170 #endif /* !defined(__PCTOOL__) */
1172 /* Format time into buf.
1174 * buf - buffer to format to.
1175 * buf_size - size of buffer.
1176 * t - time to format, in milliseconds.
1178 void format_time(char* buf, int buf_size, long t)
1180 if ( t < 3600000 )
1182 snprintf(buf, buf_size, "%d:%02d",
1183 (int) (t / 60000), (int) (t % 60000 / 1000));
1185 else
1187 snprintf(buf, buf_size, "%d:%02d:%02d",
1188 (int) (t / 3600000), (int) (t % 3600000 / 60000),
1189 (int) (t % 60000 / 1000));
1194 /** Open a UTF-8 file and set file descriptor to first byte after BOM.
1195 * If no BOM is present this behaves like open().
1196 * If the file is opened for writing and O_TRUNC is set, write a BOM to
1197 * the opened file and leave the file pointer set after the BOM.
1199 #define BOM "\xef\xbb\xbf"
1200 #define BOM_SIZE 3
1202 int open_utf8(const char* pathname, int flags)
1204 int fd;
1205 unsigned char bom[BOM_SIZE];
1207 fd = open(pathname, flags);
1208 if(fd < 0)
1209 return fd;
1211 if(flags & (O_TRUNC | O_WRONLY))
1213 write(fd, BOM, BOM_SIZE);
1215 else
1217 read(fd, bom, BOM_SIZE);
1218 /* check for BOM */
1219 if(memcmp(bom, BOM, BOM_SIZE))
1220 lseek(fd, 0, SEEK_SET);
1222 return fd;
1226 #ifdef HAVE_LCD_COLOR
1228 * Helper function to convert a string of 6 hex digits to a native colour
1231 static int hex2dec(int c)
1233 return (((c) >= '0' && ((c) <= '9')) ? (c) - '0' :
1234 (toupper(c)) - 'A' + 10);
1237 int hex_to_rgb(const char* hex, int* color)
1239 int red, green, blue;
1240 int i = 0;
1242 while ((i < 6) && (isxdigit(hex[i])))
1243 i++;
1245 if (i < 6)
1246 return -1;
1248 red = (hex2dec(hex[0]) << 4) | hex2dec(hex[1]);
1249 green = (hex2dec(hex[2]) << 4) | hex2dec(hex[3]);
1250 blue = (hex2dec(hex[4]) << 4) | hex2dec(hex[5]);
1252 *color = LCD_RGBPACK(red,green,blue);
1254 return 0;
1256 #endif /* HAVE_LCD_COLOR */
1258 #ifdef HAVE_LCD_BITMAP
1259 /* A simplified scanf - used (at time of writing) by wps parsing functions.
1261 fmt - char array specifying the format of each list option. Valid values
1262 are: d - int
1263 s - string (sets pointer to string, without copying)
1264 c - hex colour (RGB888 - e.g. ff00ff)
1265 g - greyscale "colour" (0-3)
1266 set_vals - if not NULL 1 is set in the bitplace if the item was read OK
1267 0 if not read.
1268 first item is LSB, (max 32 items! )
1269 Stops parseing if an item is invalid unless the item == '-'
1270 sep - list separator (e.g. ',' or '|')
1271 str - string to parse, must be terminated by 0 or sep
1272 ... - pointers to store the parsed values
1274 return value - pointer to char after parsed data, 0 if there was an error.
1278 /* '0'-'3' are ASCII 0x30 to 0x33 */
1279 #define is0123(x) (((x) & 0xfc) == 0x30)
1281 const char* parse_list(const char *fmt, uint32_t *set_vals,
1282 const char sep, const char* str, ...)
1284 va_list ap;
1285 const char* p = str, *f = fmt;
1286 const char** s;
1287 int* d;
1288 bool set;
1289 int i=0;
1291 va_start(ap, str);
1292 if (set_vals)
1293 *set_vals = 0;
1294 while (*fmt)
1296 /* Check for separator, if we're not at the start */
1297 if (f != fmt)
1299 if (*p != sep)
1300 goto err;
1301 p++;
1303 set = false;
1304 switch (*fmt++)
1306 case 's': /* string - return a pointer to it (not a copy) */
1307 s = va_arg(ap, const char **);
1309 *s = p;
1310 while (*p && *p != sep)
1311 p++;
1312 set = (s[0][0]!='-') && (s[0][1]!=sep) ;
1313 break;
1315 case 'd': /* int */
1316 d = va_arg(ap, int*);
1317 if (!isdigit(*p))
1319 if (!set_vals || *p != '-')
1320 goto err;
1321 while (*p && *p != sep)
1322 p++;
1324 else
1326 *d = *p++ - '0';
1327 while (isdigit(*p))
1328 *d = (*d * 10) + (*p++ - '0');
1329 set = true;
1332 break;
1334 #ifdef HAVE_LCD_COLOR
1335 case 'c': /* colour (rrggbb - e.g. f3c1a8) */
1336 d = va_arg(ap, int*);
1338 if (hex_to_rgb(p, d) < 0)
1340 if (!set_vals || *p != '-')
1341 goto err;
1342 while (*p && *p != sep)
1343 p++;
1345 else
1347 p += 6;
1348 set = true;
1351 break;
1352 #endif
1354 #if LCD_DEPTH == 2 || (defined(HAVE_REMOTE_LCD) && LCD_REMOTE_DEPTH == 2)
1355 case 'g': /* greyscale colour (0-3) */
1356 d = va_arg(ap, int*);
1358 if (is0123(*p))
1360 *d = *p++ - '0';
1361 set = true;
1363 else if (!set_vals || *p != '-')
1364 goto err;
1365 else
1367 while (*p && *p != sep)
1368 p++;
1371 break;
1372 #endif
1374 default: /* Unknown format type */
1375 goto err;
1376 break;
1378 if (set_vals && set)
1379 *set_vals |= (1<<i);
1380 i++;
1383 va_end(ap);
1384 return p;
1386 err:
1387 va_end(ap);
1388 return 0;
1390 #endif