Codec lib directories renamed, except for demac.
[kugel-rb.git] / apps / misc.c
blob02d8bed2d8e998e95068600f4f8d7d0a24b33f28
1 /***************************************************************************
2 * __________ __ ___.
3 * Open \______ \ ____ ____ | | _\_ |__ _______ ___
4 * Source | _// _ \_/ ___\| |/ /| __ \ / _ \ \/ /
5 * Jukebox | | ( <_> ) \___| < | \_\ ( <_> > < <
6 * Firmware |____|_ /\____/ \___ >__|_ \|___ /\____/__/\_ \
7 * \/ \/ \/ \/ \/
8 * $Id$
10 * Copyright (C) 2002 by Daniel Stenberg
12 * This program is free software; you can redistribute it and/or
13 * modify it under the terms of the GNU General Public License
14 * as published by the Free Software Foundation; either version 2
15 * of the License, or (at your option) any later version.
17 * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
18 * KIND, either express or implied.
20 ****************************************************************************/
21 #include <stdlib.h>
22 #include <ctype.h>
23 #include "config.h"
24 #include "misc.h"
25 #include "lcd.h"
26 #include "file.h"
27 #ifdef __PCTOOL__
28 #include <stdint.h>
29 #include <stdarg.h>
30 #include <stdio.h>
31 #ifdef WPSEDITOR
32 #include "string.h"
33 #endif
34 #else
35 #include "sprintf.h"
36 #include "lang.h"
37 #include "string.h"
38 #include "dir.h"
39 #include "lcd-remote.h"
40 #include "errno.h"
41 #include "system.h"
42 #include "timefuncs.h"
43 #include "screens.h"
44 #include "talk.h"
45 #include "mpeg.h"
46 #include "audio.h"
47 #include "mp3_playback.h"
48 #include "settings.h"
49 #include "storage.h"
50 #include "ata_idle_notify.h"
51 #include "kernel.h"
52 #include "power.h"
53 #include "powermgmt.h"
54 #include "backlight.h"
55 #include "version.h"
56 #include "font.h"
57 #include "splash.h"
58 #include "tagcache.h"
59 #include "scrobbler.h"
60 #include "sound.h"
61 #include "playlist.h"
62 #include "yesno.h"
64 #if (CONFIG_STORAGE & STORAGE_MMC)
65 #include "ata_mmc.h"
66 #endif
67 #include "tree.h"
68 #include "eeprom_settings.h"
69 #if defined(HAVE_RECORDING) && !defined(__PCTOOL__)
70 #include "recording.h"
71 #endif
72 #if defined(HAVE_LCD_BITMAP) && !defined(__PCTOOL__)
73 #include "bmp.h"
74 #include "icons.h"
75 #endif /* End HAVE_LCD_BITMAP */
76 #include "gui/gwps-common.h"
77 #include "bookmark.h"
79 #include "playback.h"
81 #ifdef BOOTFILE
82 #if !defined(USB_NONE) && !defined(USB_IPODSTYLE)
83 #include "rolo.h"
84 #include "yesno.h"
85 #endif
86 #endif
88 /* Format a large-range value for output, using the appropriate unit so that
89 * the displayed value is in the range 1 <= display < 1000 (1024 for "binary"
90 * units) if possible, and 3 significant digits are shown. If a buffer is
91 * given, the result is snprintf()'d into that buffer, otherwise the result is
92 * voiced.*/
93 char *output_dyn_value(char *buf, int buf_size, int value,
94 const unsigned char **units, bool bin_scale)
96 int scale = bin_scale ? 1024 : 1000;
97 int fraction = 0;
98 int unit_no = 0;
99 char tbuf[5];
101 while (value >= scale)
103 fraction = value % scale;
104 value /= scale;
105 unit_no++;
107 if (bin_scale)
108 fraction = fraction * 1000 / 1024;
110 if (value >= 100 || !unit_no)
111 tbuf[0] = '\0';
112 else if (value >= 10)
113 snprintf(tbuf, sizeof(tbuf), "%01d", fraction / 100);
114 else
115 snprintf(tbuf, sizeof(tbuf), "%02d", fraction / 10);
117 if (buf)
119 if (strlen(tbuf))
120 snprintf(buf, buf_size, "%d%s%s%s", value, str(LANG_POINT),
121 tbuf, P2STR(units[unit_no]));
122 else
123 snprintf(buf, buf_size, "%d%s", value, P2STR(units[unit_no]));
125 else
127 talk_fractional(tbuf, value, P2ID(units[unit_no]));
129 return buf;
132 /* Create a filename with a number part in a way that the number is 1
133 * higher than the highest numbered file matching the same pattern.
134 * It is allowed that buffer and path point to the same memory location,
135 * saving a strcpy(). Path must always be given without trailing slash.
136 * "num" can point to an int specifying the number to use or NULL or a value
137 * less than zero to number automatically. The final number used will also
138 * be returned in *num. If *num is >= 0 then *num will be incremented by
139 * one. */
140 char *create_numbered_filename(char *buffer, const char *path,
141 const char *prefix, const char *suffix,
142 int numberlen IF_CNFN_NUM_(, int *num))
144 DIR *dir;
145 struct dirent *entry;
146 int max_num;
147 int pathlen;
148 int prefixlen = strlen(prefix);
149 char fmtstring[12];
151 if (buffer != path)
152 strncpy(buffer, path, MAX_PATH);
154 pathlen = strlen(buffer);
156 #ifdef IF_CNFN_NUM
157 if (num && *num >= 0)
159 /* number specified */
160 max_num = *num;
162 else
163 #endif
165 /* automatic numbering */
166 max_num = 0;
168 dir = opendir(pathlen ? buffer : "/");
169 if (!dir)
170 return NULL;
172 while ((entry = readdir(dir)))
174 int curr_num;
176 if (strncasecmp((char *)entry->d_name, prefix, prefixlen)
177 || strcasecmp((char *)entry->d_name + prefixlen + numberlen, suffix))
178 continue;
180 curr_num = atoi((char *)entry->d_name + prefixlen);
181 if (curr_num > max_num)
182 max_num = curr_num;
185 closedir(dir);
188 max_num++;
190 snprintf(fmtstring, sizeof(fmtstring), "/%%s%%0%dd%%s", numberlen);
191 snprintf(buffer + pathlen, MAX_PATH - pathlen, fmtstring, prefix,
192 max_num, suffix);
194 #ifdef IF_CNFN_NUM
195 if (num)
196 *num = max_num;
197 #endif
199 return buffer;
203 #if CONFIG_RTC
204 /* Create a filename with a date+time part.
205 It is allowed that buffer and path point to the same memory location,
206 saving a strcpy(). Path must always be given without trailing slash.
207 unique_time as true makes the function wait until the current time has
208 changed. */
209 char *create_datetime_filename(char *buffer, const char *path,
210 const char *prefix, const char *suffix,
211 bool unique_time)
213 struct tm *tm = get_time();
214 static struct tm last_tm;
215 int pathlen;
217 while (unique_time && !memcmp(get_time(), &last_tm, sizeof (struct tm)))
218 sleep(HZ/10);
220 last_tm = *tm;
222 if (buffer != path)
223 strncpy(buffer, path, MAX_PATH);
225 pathlen = strlen(buffer);
226 snprintf(buffer + pathlen, MAX_PATH - pathlen,
227 "/%s%02d%02d%02d-%02d%02d%02d%s", prefix,
228 tm->tm_year % 100, tm->tm_mon + 1, tm->tm_mday,
229 tm->tm_hour, tm->tm_min, tm->tm_sec, suffix);
231 return buffer;
233 #endif /* CONFIG_RTC */
235 /* Ask the user if they really want to erase the current dynamic playlist
236 * returns true if the playlist should be replaced */
237 bool warn_on_pl_erase(void)
239 if (global_settings.warnon_erase_dynplaylist &&
240 !global_settings.party_mode &&
241 playlist_modified(NULL))
243 static const char *lines[] =
244 {ID2P(LANG_WARN_ERASEDYNPLAYLIST_PROMPT)};
245 static const struct text_message message={lines, 1};
247 return (gui_syncyesno_run(&message, NULL, NULL) == YESNO_YES);
249 else
250 return true;
253 /* Read (up to) a line of text from fd into buffer and return number of bytes
254 * read (which may be larger than the number of bytes stored in buffer). If
255 * an error occurs, -1 is returned (and buffer contains whatever could be
256 * read). A line is terminated by a LF char. Neither LF nor CR chars are
257 * stored in buffer.
259 int read_line(int fd, char* buffer, int buffer_size)
261 int count = 0;
262 int num_read = 0;
264 errno = 0;
266 while (count < buffer_size)
268 unsigned char c;
270 if (1 != read(fd, &c, 1))
271 break;
273 num_read++;
275 if ( c == '\n' )
276 break;
278 if ( c == '\r' )
279 continue;
281 buffer[count++] = c;
284 buffer[MIN(count, buffer_size - 1)] = 0;
286 return errno ? -1 : num_read;
289 /* Performance optimized version of the previous function. */
290 int fast_readline(int fd, char *buf, int buf_size, void *parameters,
291 int (*callback)(int n, const char *buf, void *parameters))
293 char *p, *next;
294 int rc, pos = 0;
295 int count = 0;
297 while ( 1 )
299 next = NULL;
301 rc = read(fd, &buf[pos], buf_size - pos - 1);
302 if (rc >= 0)
303 buf[pos+rc] = '\0';
305 if ( (p = strchr(buf, '\r')) != NULL)
307 *p = '\0';
308 next = ++p;
310 else
311 p = buf;
313 if ( (p = strchr(p, '\n')) != NULL)
315 *p = '\0';
316 next = ++p;
319 rc = callback(count, buf, parameters);
320 if (rc < 0)
321 return rc;
323 count++;
324 if (next)
326 pos = buf_size - ((long)next - (long)buf) - 1;
327 memmove(buf, next, pos);
329 else
330 break ;
333 return 0;
336 #ifdef HAVE_LCD_BITMAP
338 #if LCD_DEPTH == 16
339 #define BMP_COMPRESSION 3 /* BI_BITFIELDS */
340 #define BMP_NUMCOLORS 3
341 #else
342 #define BMP_COMPRESSION 0 /* BI_RGB */
343 #if LCD_DEPTH <= 8
344 #define BMP_NUMCOLORS (1 << LCD_DEPTH)
345 #else
346 #define BMP_NUMCOLORS 0
347 #endif
348 #endif
350 #if LCD_DEPTH == 1
351 #define BMP_BPP 1
352 #define BMP_LINESIZE ((LCD_WIDTH/8 + 3) & ~3)
353 #elif LCD_DEPTH <= 4
354 #define BMP_BPP 4
355 #define BMP_LINESIZE ((LCD_WIDTH/2 + 3) & ~3)
356 #elif LCD_DEPTH <= 8
357 #define BMP_BPP 8
358 #define BMP_LINESIZE ((LCD_WIDTH + 3) & ~3)
359 #elif LCD_DEPTH <= 16
360 #define BMP_BPP 16
361 #define BMP_LINESIZE ((LCD_WIDTH*2 + 3) & ~3)
362 #else
363 #define BMP_BPP 24
364 #define BMP_LINESIZE ((LCD_WIDTH*3 + 3) & ~3)
365 #endif
367 #define BMP_HEADERSIZE (54 + 4 * BMP_NUMCOLORS)
368 #define BMP_DATASIZE (BMP_LINESIZE * LCD_HEIGHT)
369 #define BMP_TOTALSIZE (BMP_HEADERSIZE + BMP_DATASIZE)
371 #define LE16_CONST(x) (x)&0xff, ((x)>>8)&0xff
372 #define LE32_CONST(x) (x)&0xff, ((x)>>8)&0xff, ((x)>>16)&0xff, ((x)>>24)&0xff
374 static const unsigned char bmpheader[] =
376 0x42, 0x4d, /* 'BM' */
377 LE32_CONST(BMP_TOTALSIZE), /* Total file size */
378 0x00, 0x00, 0x00, 0x00, /* Reserved */
379 LE32_CONST(BMP_HEADERSIZE), /* Offset to start of pixel data */
381 0x28, 0x00, 0x00, 0x00, /* Size of (2nd) header */
382 LE32_CONST(LCD_WIDTH), /* Width in pixels */
383 LE32_CONST(LCD_HEIGHT), /* Height in pixels */
384 0x01, 0x00, /* Number of planes (always 1) */
385 LE16_CONST(BMP_BPP), /* Bits per pixel 1/4/8/16/24 */
386 LE32_CONST(BMP_COMPRESSION),/* Compression mode */
387 LE32_CONST(BMP_DATASIZE), /* Size of bitmap data */
388 0xc4, 0x0e, 0x00, 0x00, /* Horizontal resolution (pixels/meter) */
389 0xc4, 0x0e, 0x00, 0x00, /* Vertical resolution (pixels/meter) */
390 LE32_CONST(BMP_NUMCOLORS), /* Number of used colours */
391 LE32_CONST(BMP_NUMCOLORS), /* Number of important colours */
393 #if LCD_DEPTH == 1
394 #ifdef MROBE_100
395 2, 2, 94, 0x00, /* Colour #0 */
396 3, 6, 241, 0x00 /* Colour #1 */
397 #else
398 0x90, 0xee, 0x90, 0x00, /* Colour #0 */
399 0x00, 0x00, 0x00, 0x00 /* Colour #1 */
400 #endif
401 #elif LCD_DEPTH == 2
402 0xe6, 0xd8, 0xad, 0x00, /* Colour #0 */
403 0x99, 0x90, 0x73, 0x00, /* Colour #1 */
404 0x4c, 0x48, 0x39, 0x00, /* Colour #2 */
405 0x00, 0x00, 0x00, 0x00 /* Colour #3 */
406 #elif LCD_DEPTH == 16
407 0x00, 0xf8, 0x00, 0x00, /* red bitfield mask */
408 0xe0, 0x07, 0x00, 0x00, /* green bitfield mask */
409 0x1f, 0x00, 0x00, 0x00 /* blue bitfield mask */
410 #endif
413 static void (*screen_dump_hook)(int fh) = NULL;
415 void screen_dump(void)
417 int fh;
418 char filename[MAX_PATH];
419 int bx, by;
420 #if LCD_DEPTH == 1
421 static unsigned char line_block[8][BMP_LINESIZE];
422 #elif LCD_DEPTH == 2
423 #if LCD_PIXELFORMAT == HORIZONTAL_PACKING
424 static unsigned char line_block[BMP_LINESIZE];
425 #elif LCD_PIXELFORMAT == VERTICAL_PACKING
426 static unsigned char line_block[4][BMP_LINESIZE];
427 #elif LCD_PIXELFORMAT == VERTICAL_INTERLEAVED
428 static unsigned char line_block[8][BMP_LINESIZE];
429 #endif
430 #elif LCD_DEPTH == 16
431 static unsigned short line_block[BMP_LINESIZE/2];
432 #endif
434 #if CONFIG_RTC
435 create_datetime_filename(filename, "", "dump ", ".bmp", false);
436 #else
437 create_numbered_filename(filename, "", "dump_", ".bmp", 4
438 IF_CNFN_NUM_(, NULL));
439 #endif
441 fh = creat(filename);
442 if (fh < 0)
443 return;
445 if (screen_dump_hook)
447 screen_dump_hook(fh);
449 else
451 write(fh, bmpheader, sizeof(bmpheader));
453 /* BMP image goes bottom up */
454 #if LCD_DEPTH == 1
455 for (by = LCD_FBHEIGHT - 1; by >= 0; by--)
457 unsigned char *src = &lcd_framebuffer[by][0];
458 unsigned char *dst = &line_block[0][0];
460 memset(line_block, 0, sizeof(line_block));
461 for (bx = LCD_WIDTH/8; bx > 0; bx--)
463 unsigned dst_mask = 0x80;
464 int ix;
466 for (ix = 8; ix > 0; ix--)
468 unsigned char *dst_blk = dst;
469 unsigned src_byte = *src++;
470 int iy;
472 for (iy = 8; iy > 0; iy--)
474 if (src_byte & 0x80)
475 *dst_blk |= dst_mask;
476 src_byte <<= 1;
477 dst_blk += BMP_LINESIZE;
479 dst_mask >>= 1;
481 dst++;
484 write(fh, line_block, sizeof(line_block));
486 #elif LCD_DEPTH == 2
487 #if LCD_PIXELFORMAT == HORIZONTAL_PACKING
488 for (by = LCD_FBHEIGHT - 1; by >= 0; by--)
490 unsigned char *src = &lcd_framebuffer[by][0];
491 unsigned char *dst = line_block;
493 memset(line_block, 0, sizeof(line_block));
494 for (bx = LCD_FBWIDTH; bx > 0; bx--)
496 unsigned src_byte = *src++;
498 *dst++ = ((src_byte >> 2) & 0x30) | ((src_byte >> 4) & 0x03);
499 *dst++ = ((src_byte << 2) & 0x30) | (src_byte & 0x03);
502 write(fh, line_block, sizeof(line_block));
504 #elif LCD_PIXELFORMAT == VERTICAL_PACKING
505 for (by = LCD_FBHEIGHT - 1; by >= 0; by--)
507 unsigned char *src = &lcd_framebuffer[by][0];
508 unsigned char *dst = &line_block[3][0];
510 memset(line_block, 0, sizeof(line_block));
511 for (bx = LCD_WIDTH/2; bx > 0; bx--)
513 unsigned char *dst_blk = dst++;
514 unsigned src_byte0 = *src++ << 4;
515 unsigned src_byte1 = *src++;
516 int iy;
518 for (iy = 4; iy > 0; iy--)
520 *dst_blk = (src_byte0 & 0x30) | (src_byte1 & 0x03);
521 src_byte0 >>= 2;
522 src_byte1 >>= 2;
523 dst_blk -= BMP_LINESIZE;
527 write(fh, line_block, sizeof(line_block));
529 #elif LCD_PIXELFORMAT == VERTICAL_INTERLEAVED
530 for (by = LCD_FBHEIGHT - 1; by >= 0; by--)
532 const fb_data *src = &lcd_framebuffer[by][0];
533 unsigned char *dst = &line_block[7][0];
535 memset(line_block, 0, sizeof(line_block));
536 for (bx = LCD_WIDTH/2; bx > 0; bx--)
538 unsigned char *dst_blk = dst++;
539 unsigned src_data0 = *src++ << 4;
540 unsigned src_data1 = *src++;
541 int iy;
543 for (iy = 8; iy > 0; iy--)
545 *dst_blk = (src_data0 & 0x10) | (src_data1 & 0x01)
546 | ((src_data0 & 0x1000) | (src_data1 & 0x0100)) >> 7;
547 src_data0 >>= 1;
548 src_data1 >>= 1;
549 dst_blk -= BMP_LINESIZE;
553 write(fh, line_block, sizeof(line_block));
555 #endif
556 #elif LCD_DEPTH == 16
557 for (by = LCD_HEIGHT - 1; by >= 0; by--)
559 unsigned short *src = &lcd_framebuffer[by][0];
560 unsigned short *dst = line_block;
562 memset(line_block, 0, sizeof(line_block));
563 for (bx = LCD_WIDTH; bx > 0; bx--)
565 #if (LCD_PIXELFORMAT == RGB565SWAPPED)
566 /* iPod LCD data is big endian although the CPU is not */
567 *dst++ = htobe16(*src++);
568 #else
569 *dst++ = htole16(*src++);
570 #endif
573 write(fh, line_block, sizeof(line_block));
575 #endif /* LCD_DEPTH */
578 close(fh);
581 void screen_dump_set_hook(void (*hook)(int fh))
583 screen_dump_hook = hook;
586 #endif /* HAVE_LCD_BITMAP */
588 /* parse a line from a configuration file. the line format is:
590 name: value
592 Any whitespace before setting name or value (after ':') is ignored.
593 A # as first non-whitespace character discards the whole line.
594 Function sets pointers to null-terminated setting name and value.
595 Returns false if no valid config entry was found.
598 bool settings_parseline(char* line, char** name, char** value)
600 char* ptr;
602 while ( isspace(*line) )
603 line++;
605 if ( *line == '#' )
606 return false;
608 ptr = strchr(line, ':');
609 if ( !ptr )
610 return false;
612 *name = line;
613 *ptr = 0;
614 ptr++;
615 while (isspace(*ptr))
616 ptr++;
617 *value = ptr;
618 return true;
621 static void system_flush(void)
623 tree_flush();
624 call_storage_idle_notifys(true); /*doesnt work on usb and shutdown from ata thread */
627 static void system_restore(void)
629 tree_restore();
632 static bool clean_shutdown(void (*callback)(void *), void *parameter)
634 #ifdef SIMULATOR
635 (void)callback;
636 (void)parameter;
637 bookmark_autobookmark();
638 call_storage_idle_notifys(true);
639 exit(0);
640 #else
641 long msg_id = -1;
642 int i;
644 scrobbler_poweroff();
646 #if CONFIG_CHARGING && !defined(HAVE_POWEROFF_WHILE_CHARGING)
647 if(!charger_inserted())
648 #endif
650 bool batt_safe = battery_level_safe();
651 int audio_stat = audio_status();
653 FOR_NB_SCREENS(i)
654 screens[i].clear_display();
656 if (batt_safe)
658 #ifdef HAVE_TAGCACHE
659 if (!tagcache_prepare_shutdown())
661 cancel_shutdown();
662 splash(HZ, ID2P(LANG_TAGCACHE_BUSY));
663 return false;
665 #endif
666 if (battery_level() > 10)
667 splash(0, str(LANG_SHUTTINGDOWN));
668 else
670 msg_id = LANG_WARNING_BATTERY_LOW;
671 splashf(0, "%s %s", str(LANG_WARNING_BATTERY_LOW),
672 str(LANG_SHUTTINGDOWN));
675 else
677 msg_id = LANG_WARNING_BATTERY_EMPTY;
678 splashf(0, "%s %s", str(LANG_WARNING_BATTERY_EMPTY),
679 str(LANG_SHUTTINGDOWN));
682 if (global_settings.fade_on_stop
683 && (audio_stat & AUDIO_STATUS_PLAY))
685 fade(false, false);
688 if (batt_safe) /* do not save on critical battery */
690 #if defined(HAVE_RECORDING) && CONFIG_CODEC == SWCODEC
691 if (audio_stat & AUDIO_STATUS_RECORD)
693 rec_command(RECORDING_CMD_STOP);
694 /* wait for stop to complete */
695 while (audio_status() & AUDIO_STATUS_RECORD)
696 sleep(1);
698 #endif
699 bookmark_autobookmark();
701 /* audio_stop_recording == audio_stop for HWCODEC */
702 audio_stop();
704 if (callback != NULL)
705 callback(parameter);
707 #if CONFIG_CODEC != SWCODEC
708 /* wait for audio_stop or audio_stop_recording to complete */
709 while (audio_status())
710 sleep(1);
711 #endif
713 #if defined(HAVE_RECORDING) && CONFIG_CODEC == SWCODEC
714 audio_close_recording();
715 #endif
717 if(global_settings.talk_menu)
719 bool enqueue = false;
720 if(msg_id != -1)
722 talk_id(msg_id, enqueue);
723 enqueue = true;
725 talk_id(LANG_SHUTTINGDOWN, enqueue);
726 #if CONFIG_CODEC == SWCODEC
727 voice_wait();
728 #endif
731 system_flush();
732 #ifdef HAVE_EEPROM_SETTINGS
733 if (firmware_settings.initialized)
735 firmware_settings.disk_clean = true;
736 firmware_settings.bl_version = 0;
737 eeprom_settings_store();
739 #endif
741 #ifdef HAVE_DIRCACHE
742 else
743 dircache_disable();
744 #endif
746 shutdown_hw();
748 #endif
749 return false;
752 bool list_stop_handler(void)
754 bool ret = false;
756 /* Stop the music if it is playing */
757 if(audio_status())
759 if (!global_settings.party_mode)
761 if (global_settings.fade_on_stop)
762 fade(false, false);
763 bookmark_autobookmark();
764 audio_stop();
765 ret = true; /* bookmarking can make a refresh necessary */
768 #if CONFIG_CHARGING
769 #if (CONFIG_KEYPAD == RECORDER_PAD) && !defined(HAVE_SW_POWEROFF)
770 else
772 if (charger_inserted())
773 charging_splash();
774 else
775 shutdown_screen(); /* won't return if shutdown actually happens */
777 ret = true; /* screen is dirty, caller needs to refresh */
779 #endif
780 #ifndef HAVE_POWEROFF_WHILE_CHARGING
782 static long last_off = 0;
784 if (TIME_BEFORE(current_tick, last_off + HZ/2))
786 if (charger_inserted())
788 charging_splash();
789 ret = true; /* screen is dirty, caller needs to refresh */
792 last_off = current_tick;
794 #endif
795 #endif /* CONFIG_CHARGING */
796 return ret;
799 #if CONFIG_CHARGING
800 static bool waiting_to_resume_play = false;
801 static long play_resume_tick;
803 static void car_adapter_mode_processing(bool inserted)
805 if (global_settings.car_adapter_mode)
807 if(inserted)
810 * Just got plugged in, delay & resume if we were playing
812 if (audio_status() & AUDIO_STATUS_PAUSE)
814 /* delay resume a bit while the engine is cranking */
815 play_resume_tick = current_tick + HZ*5;
816 waiting_to_resume_play = true;
819 else
822 * Just got unplugged, pause if playing
824 if ((audio_status() & AUDIO_STATUS_PLAY) &&
825 !(audio_status() & AUDIO_STATUS_PAUSE))
827 if (global_settings.fade_on_stop)
828 fade(false, false);
829 else
830 audio_pause();
832 waiting_to_resume_play = false;
837 static void car_adapter_tick(void)
839 if (waiting_to_resume_play)
841 if (TIME_AFTER(current_tick, play_resume_tick))
843 if (audio_status() & AUDIO_STATUS_PAUSE)
845 queue_broadcast(SYS_CAR_ADAPTER_RESUME, 0);
847 waiting_to_resume_play = false;
852 void car_adapter_mode_init(void)
854 tick_add_task(car_adapter_tick);
856 #endif
858 #ifdef HAVE_HEADPHONE_DETECTION
859 static void unplug_change(bool inserted)
861 static bool headphone_caused_pause = false;
863 if (global_settings.unplug_mode)
865 int audio_stat = audio_status();
866 if (inserted)
868 if ((audio_stat & AUDIO_STATUS_PLAY) &&
869 headphone_caused_pause &&
870 global_settings.unplug_mode > 1 )
871 audio_resume();
872 backlight_on();
873 headphone_caused_pause = false;
874 } else {
875 if ((audio_stat & AUDIO_STATUS_PLAY) &&
876 !(audio_stat & AUDIO_STATUS_PAUSE))
878 headphone_caused_pause = true;
879 audio_pause();
881 if (global_settings.unplug_rw)
883 if (audio_current_track()->elapsed >
884 (unsigned long)(global_settings.unplug_rw*1000))
885 audio_ff_rewind(audio_current_track()->elapsed -
886 (global_settings.unplug_rw*1000));
887 else
888 audio_ff_rewind(0);
894 #endif
896 long default_event_handler_ex(long event, void (*callback)(void *), void *parameter)
898 switch(event)
900 case SYS_BATTERY_UPDATE:
901 if(global_settings.talk_battery_level)
903 talk_ids(true, VOICE_PAUSE, VOICE_PAUSE,
904 LANG_BATTERY_TIME,
905 TALK_ID(battery_level(), UNIT_PERCENT),
906 VOICE_PAUSE);
907 talk_force_enqueue_next();
909 break;
910 case SYS_USB_CONNECTED:
911 if (callback != NULL)
912 callback(parameter);
913 #if (CONFIG_STORAGE & STORAGE_MMC)
914 if (!mmc_touched() ||
915 (mmc_remove_request() == SYS_HOTSWAP_EXTRACTED))
916 #endif
918 scrobbler_flush_cache();
919 system_flush();
920 #ifdef BOOTFILE
921 #if !defined(USB_NONE) && !defined(USB_IPODSTYLE)
922 check_bootfile(false); /* gets initial size */
923 #endif
924 #endif
925 usb_screen();
926 #ifdef BOOTFILE
927 #if !defined(USB_NONE) && !defined(USB_IPODSTYLE)
928 check_bootfile(true);
929 #endif
930 #endif
931 system_restore();
933 return SYS_USB_CONNECTED;
934 case SYS_POWEROFF:
935 if (!clean_shutdown(callback, parameter))
936 return SYS_POWEROFF;
937 break;
938 #if CONFIG_CHARGING
939 case SYS_CHARGER_CONNECTED:
940 car_adapter_mode_processing(true);
941 return SYS_CHARGER_CONNECTED;
943 case SYS_CHARGER_DISCONNECTED:
944 car_adapter_mode_processing(false);
945 return SYS_CHARGER_DISCONNECTED;
947 case SYS_CAR_ADAPTER_RESUME:
948 audio_resume();
949 return SYS_CAR_ADAPTER_RESUME;
950 #endif
951 #ifdef HAVE_HEADPHONE_DETECTION
952 case SYS_PHONE_PLUGGED:
953 unplug_change(true);
954 return SYS_PHONE_PLUGGED;
956 case SYS_PHONE_UNPLUGGED:
957 unplug_change(false);
958 return SYS_PHONE_UNPLUGGED;
959 #endif
961 return 0;
964 long default_event_handler(long event)
966 return default_event_handler_ex(event, NULL, NULL);
969 int show_logo( void )
971 #ifdef HAVE_LCD_BITMAP
972 char version[32];
973 int font_h, font_w;
975 snprintf(version, sizeof(version), "Ver. %s", appsversion);
977 lcd_clear_display();
978 lcd_bitmap(rockboxlogo, 0, 10, BMPWIDTH_rockboxlogo, BMPHEIGHT_rockboxlogo);
979 lcd_setfont(FONT_SYSFIXED);
980 lcd_getstringsize((unsigned char *)"A", &font_w, &font_h);
981 lcd_putsxy((LCD_WIDTH/2) - ((strlen(version)*font_w)/2),
982 LCD_HEIGHT-font_h, (unsigned char *)version);
983 lcd_setfont(FONT_UI);
985 #else
986 char *rockbox = " ROCKbox!";
988 lcd_clear_display();
989 lcd_double_height(true);
990 lcd_puts(0, 0, rockbox);
991 lcd_puts_scroll(0, 1, appsversion);
992 #endif
993 lcd_update();
995 #ifdef HAVE_REMOTE_LCD
996 lcd_remote_clear_display();
997 lcd_remote_bitmap(remote_rockboxlogo, 0, 10, BMPWIDTH_remote_rockboxlogo,
998 BMPHEIGHT_remote_rockboxlogo);
999 lcd_remote_setfont(FONT_SYSFIXED);
1000 lcd_remote_getstringsize((unsigned char *)"A", &font_w, &font_h);
1001 lcd_remote_putsxy((LCD_REMOTE_WIDTH/2) - ((strlen(version)*font_w)/2),
1002 LCD_REMOTE_HEIGHT-font_h, (unsigned char *)version);
1003 lcd_remote_setfont(FONT_UI);
1004 lcd_remote_update();
1005 #endif
1007 return 0;
1010 #if CONFIG_CODEC == SWCODEC
1011 int get_replaygain_mode(bool have_track_gain, bool have_album_gain)
1013 int type;
1015 bool track = ((global_settings.replaygain_type == REPLAYGAIN_TRACK)
1016 || ((global_settings.replaygain_type == REPLAYGAIN_SHUFFLE)
1017 && global_settings.playlist_shuffle));
1019 type = (!track && have_album_gain) ? REPLAYGAIN_ALBUM
1020 : have_track_gain ? REPLAYGAIN_TRACK : -1;
1022 return type;
1024 #endif
1026 #ifdef BOOTFILE
1027 #if !defined(USB_NONE) && !defined(USB_IPODSTYLE)
1029 memorize/compare details about the BOOTFILE
1030 we don't use dircache because it may not be up to date after
1031 USB disconnect (scanning in the background)
1033 void check_bootfile(bool do_rolo)
1035 static unsigned short wrtdate = 0;
1036 static unsigned short wrttime = 0;
1037 DIR* dir = NULL;
1038 struct dirent* entry = NULL;
1040 /* 1. open BOOTDIR and find the BOOTFILE dir entry */
1041 dir = opendir(BOOTDIR);
1043 if(!dir) return; /* do we want an error splash? */
1045 /* loop all files in BOOTDIR */
1046 while(0 != (entry = readdir(dir)))
1048 if(!strcasecmp(entry->d_name, BOOTFILE))
1050 /* found the bootfile */
1051 if(wrtdate && do_rolo)
1053 if((entry->wrtdate != wrtdate) ||
1054 (entry->wrttime != wrttime))
1056 static const char *lines[] = { ID2P(LANG_BOOT_CHANGED),
1057 ID2P(LANG_REBOOT_NOW) };
1058 static const struct text_message message={ lines, 2 };
1059 button_clear_queue(); /* Empty the keyboard buffer */
1060 if(gui_syncyesno_run(&message, NULL, NULL) == YESNO_YES)
1061 rolo_load(BOOTDIR "/" BOOTFILE);
1064 wrtdate = entry->wrtdate;
1065 wrttime = entry->wrttime;
1068 closedir(dir);
1070 #endif
1071 #endif
1073 /* check range, set volume and save settings */
1074 void setvol(void)
1076 const int min_vol = sound_min(SOUND_VOLUME);
1077 const int max_vol = sound_max(SOUND_VOLUME);
1078 if (global_settings.volume < min_vol)
1079 global_settings.volume = min_vol;
1080 if (global_settings.volume > max_vol)
1081 global_settings.volume = max_vol;
1082 sound_set_volume(global_settings.volume);
1083 settings_save();
1086 char* strrsplt(char* str, int c)
1088 char* s = strrchr(str, c);
1090 if (s != NULL)
1092 *s++ = '\0';
1094 else
1096 s = str;
1099 return s;
1102 /* Test file existence, using dircache of possible */
1103 bool file_exists(const char *file)
1105 int fd;
1107 if (!file || strlen(file) <= 0)
1108 return false;
1110 #ifdef HAVE_DIRCACHE
1111 if (dircache_is_enabled())
1112 return (dircache_get_entry_ptr(file) != NULL);
1113 #endif
1115 fd = open(file, O_RDONLY);
1116 if (fd < 0)
1117 return false;
1118 close(fd);
1119 return true;
1122 bool dir_exists(const char *path)
1124 DIR* d = opendir(path);
1125 if (!d)
1126 return false;
1127 closedir(d);
1128 return true;
1132 * removes the extension of filename (if it doesn't start with a .)
1133 * puts the result in buffer
1135 char *strip_extension(char* buffer, int buffer_size, const char *filename)
1137 char *dot = strrchr(filename, '.');
1138 int len;
1140 if (buffer_size <= 0)
1142 return NULL;
1145 buffer_size--; /* Make room for end nil */
1147 if (dot != 0 && filename[0] != '.')
1149 len = dot - filename;
1150 len = MIN(len, buffer_size);
1151 strncpy(buffer, filename, len);
1153 else
1155 len = buffer_size;
1156 strncpy(buffer, filename, buffer_size);
1159 buffer[len] = 0;
1161 return buffer;
1163 #endif /* !defined(__PCTOOL__) */
1165 /* Format time into buf.
1167 * buf - buffer to format to.
1168 * buf_size - size of buffer.
1169 * t - time to format, in milliseconds.
1171 void format_time(char* buf, int buf_size, long t)
1173 if ( t < 3600000 )
1175 snprintf(buf, buf_size, "%d:%02d",
1176 (int) (t / 60000), (int) (t % 60000 / 1000));
1178 else
1180 snprintf(buf, buf_size, "%d:%02d:%02d",
1181 (int) (t / 3600000), (int) (t % 3600000 / 60000),
1182 (int) (t % 60000 / 1000));
1187 /** Open a UTF-8 file and set file descriptor to first byte after BOM.
1188 * If no BOM is present this behaves like open().
1189 * If the file is opened for writing and O_TRUNC is set, write a BOM to
1190 * the opened file and leave the file pointer set after the BOM.
1192 #define BOM "\xef\xbb\xbf"
1193 #define BOM_SIZE 3
1195 int open_utf8(const char* pathname, int flags)
1197 int fd;
1198 unsigned char bom[BOM_SIZE];
1200 fd = open(pathname, flags);
1201 if(fd < 0)
1202 return fd;
1204 if(flags & (O_TRUNC | O_WRONLY))
1206 write(fd, BOM, BOM_SIZE);
1208 else
1210 read(fd, bom, BOM_SIZE);
1211 /* check for BOM */
1212 if(memcmp(bom, BOM, BOM_SIZE))
1213 lseek(fd, 0, SEEK_SET);
1215 return fd;
1219 #ifdef HAVE_LCD_COLOR
1221 * Helper function to convert a string of 6 hex digits to a native colour
1224 static int hex2dec(int c)
1226 return (((c) >= '0' && ((c) <= '9')) ? (c) - '0' :
1227 (toupper(c)) - 'A' + 10);
1230 int hex_to_rgb(const char* hex, int* color)
1232 int red, green, blue;
1233 int i = 0;
1235 while ((i < 6) && (isxdigit(hex[i])))
1236 i++;
1238 if (i < 6)
1239 return -1;
1241 red = (hex2dec(hex[0]) << 4) | hex2dec(hex[1]);
1242 green = (hex2dec(hex[2]) << 4) | hex2dec(hex[3]);
1243 blue = (hex2dec(hex[4]) << 4) | hex2dec(hex[5]);
1245 *color = LCD_RGBPACK(red,green,blue);
1247 return 0;
1249 #endif /* HAVE_LCD_COLOR */
1251 #ifdef HAVE_LCD_BITMAP
1252 /* A simplified scanf - used (at time of writing) by wps parsing functions.
1254 fmt - char array specifying the format of each list option. Valid values
1255 are: d - int
1256 s - string (sets pointer to string, without copying)
1257 c - hex colour (RGB888 - e.g. ff00ff)
1258 g - greyscale "colour" (0-3)
1259 set_vals - if not NULL 1 is set in the bitplace if the item was read OK
1260 0 if not read.
1261 first item is LSB, (max 32 items! )
1262 Stops parseing if an item is invalid unless the item == '-'
1263 sep - list separator (e.g. ',' or '|')
1264 str - string to parse, must be terminated by 0 or sep
1265 ... - pointers to store the parsed values
1267 return value - pointer to char after parsed data, 0 if there was an error.
1271 /* '0'-'3' are ASCII 0x30 to 0x33 */
1272 #define is0123(x) (((x) & 0xfc) == 0x30)
1274 const char* parse_list(const char *fmt, uint32_t *set_vals,
1275 const char sep, const char* str, ...)
1277 va_list ap;
1278 const char* p = str, *f = fmt;
1279 const char** s;
1280 int* d;
1281 bool set;
1282 int i=0;
1284 va_start(ap, str);
1285 if (set_vals)
1286 *set_vals = 0;
1287 while (*fmt)
1289 /* Check for separator, if we're not at the start */
1290 if (f != fmt)
1292 if (*p != sep)
1293 goto err;
1294 p++;
1296 set = false;
1297 switch (*fmt++)
1299 case 's': /* string - return a pointer to it (not a copy) */
1300 s = va_arg(ap, const char **);
1302 *s = p;
1303 while (*p && *p != sep)
1304 p++;
1305 set = (s[0][0]!='-') && (s[0][1]!=sep) ;
1306 break;
1308 case 'd': /* int */
1309 d = va_arg(ap, int*);
1310 if (!isdigit(*p))
1312 if (!set_vals || *p != '-')
1313 goto err;
1314 while (*p && *p != sep)
1315 p++;
1317 else
1319 *d = *p++ - '0';
1320 while (isdigit(*p))
1321 *d = (*d * 10) + (*p++ - '0');
1322 set = true;
1325 break;
1327 #ifdef HAVE_LCD_COLOR
1328 case 'c': /* colour (rrggbb - e.g. f3c1a8) */
1329 d = va_arg(ap, int*);
1331 if (hex_to_rgb(p, d) < 0)
1333 if (!set_vals || *p != '-')
1334 goto err;
1335 while (*p && *p != sep)
1336 p++;
1338 else
1340 p += 6;
1341 set = true;
1344 break;
1345 #endif
1347 #if LCD_DEPTH == 2 || (defined(HAVE_REMOTE_LCD) && LCD_REMOTE_DEPTH == 2)
1348 case 'g': /* greyscale colour (0-3) */
1349 d = va_arg(ap, int*);
1351 if (is0123(*p))
1353 *d = *p++ - '0';
1354 set = true;
1356 else if (!set_vals || *p != '-')
1357 goto err;
1358 else
1360 while (*p && *p != sep)
1361 p++;
1364 break;
1365 #endif
1367 default: /* Unknown format type */
1368 goto err;
1369 break;
1371 if (set_vals && set)
1372 *set_vals |= (1<<i);
1373 i++;
1376 va_end(ap);
1377 return p;
1379 err:
1380 va_end(ap);
1381 return 0;
1383 #endif