Sliding puzzle: Fix graphics size and help text for M3. * Bubbles: Better (larger...
[kugel-rb.git] / apps / misc.c
blob8b6773dd6f723571ea9b99694669f9880b604e82
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 "lang.h"
22 #include "string.h"
23 #include "config.h"
24 #include "file.h"
25 #include "dir.h"
26 #include "lcd.h"
27 #include "lcd-remote.h"
28 #include "sprintf.h"
29 #include "errno.h"
30 #include "system.h"
31 #include "timefuncs.h"
32 #include "screens.h"
33 #include "talk.h"
34 #include "mpeg.h"
35 #include "audio.h"
36 #include "mp3_playback.h"
37 #include "settings.h"
38 #include "ata.h"
39 #include "ata_idle_notify.h"
40 #include "kernel.h"
41 #include "power.h"
42 #include "powermgmt.h"
43 #include "backlight.h"
44 #include "atoi.h"
45 #include "version.h"
46 #include "font.h"
47 #include "splash.h"
48 #include "tagcache.h"
49 #include "scrobbler.h"
50 #include "sound.h"
51 #ifdef HAVE_MMC
52 #include "ata_mmc.h"
53 #endif
54 #include "tree.h"
55 #include "eeprom_settings.h"
56 #ifdef HAVE_RECORDING
57 #include "recording.h"
58 #endif
59 #ifdef HAVE_LCD_BITMAP
60 #include "bmp.h"
61 #include "icons.h"
62 #endif /* End HAVE_LCD_BITMAP */
63 #include "gui/gwps-common.h"
64 #include "bookmark.h"
66 #include "misc.h"
67 #include "playback.h"
69 #ifdef BOOTFILE
70 #if !defined(USB_NONE) && !defined(USB_IPODSTYLE)
71 #include "textarea.h"
72 #include "rolo.h"
73 #include "yesno.h"
74 #endif
75 #endif
77 /* Format a large-range value for output, using the appropriate unit so that
78 * the displayed value is in the range 1 <= display < 1000 (1024 for "binary"
79 * units) if possible, and 3 significant digits are shown. If a buffer is
80 * given, the result is snprintf()'d into that buffer, otherwise the result is
81 * voiced.*/
82 char *output_dyn_value(char *buf, int buf_size, int value,
83 const unsigned char **units, bool bin_scale)
85 int scale = bin_scale ? 1024 : 1000;
86 int fraction = 0;
87 int unit_no = 0;
88 int i;
89 char tbuf[5];
91 while (value >= scale)
93 fraction = value % scale;
94 value /= scale;
95 unit_no++;
97 if (bin_scale)
98 fraction = fraction * 1000 / 1024;
100 if (value >= 100 || !unit_no)
101 tbuf[0] = '\0';
102 else if (value >= 10)
103 snprintf(tbuf, sizeof(tbuf), "%01d", fraction / 100);
104 else
105 snprintf(tbuf, sizeof(tbuf), "%02d", fraction / 10);
107 if (buf)
109 if (strlen(tbuf))
110 snprintf(buf, buf_size, "%d%s%s%s", value, str(LANG_POINT),
111 tbuf, P2STR(units[unit_no]));
112 else
113 snprintf(buf, buf_size, "%d%s", value, P2STR(units[unit_no]));
115 else
117 /* strip trailing zeros from the fraction */
118 for (i = strlen(tbuf) - 1; (i >= 0) && (tbuf[i] == '0'); i--)
119 tbuf[i] = '\0';
121 talk_number(value, true);
122 if (tbuf[0] != 0)
124 talk_id(LANG_POINT, true);
125 talk_spell(tbuf, true);
127 talk_id(P2ID(units[unit_no]), true);
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;
202 /* Format time into buf.
204 * buf - buffer to format to.
205 * buf_size - size of buffer.
206 * t - time to format, in milliseconds.
208 void format_time(char* buf, int buf_size, long t)
210 if ( t < 3600000 )
212 snprintf(buf, buf_size, "%d:%02d",
213 (int) (t / 60000), (int) (t % 60000 / 1000));
215 else
217 snprintf(buf, buf_size, "%d:%02d:%02d",
218 (int) (t / 3600000), (int) (t % 3600000 / 60000),
219 (int) (t % 60000 / 1000));
223 #if CONFIG_RTC
224 /* Create a filename with a date+time part.
225 It is allowed that buffer and path point to the same memory location,
226 saving a strcpy(). Path must always be given without trailing slash.
227 unique_time as true makes the function wait until the current time has
228 changed. */
229 char *create_datetime_filename(char *buffer, const char *path,
230 const char *prefix, const char *suffix,
231 bool unique_time)
233 struct tm *tm = get_time();
234 static struct tm last_tm;
235 int pathlen;
237 while (unique_time && !memcmp(get_time(), &last_tm, sizeof (struct tm)))
238 sleep(HZ/10);
240 last_tm = *tm;
242 if (buffer != path)
243 strncpy(buffer, path, MAX_PATH);
245 pathlen = strlen(buffer);
246 snprintf(buffer + pathlen, MAX_PATH - pathlen,
247 "/%s%02d%02d%02d-%02d%02d%02d%s", prefix,
248 tm->tm_year % 100, tm->tm_mon + 1, tm->tm_mday,
249 tm->tm_hour, tm->tm_min, tm->tm_sec, suffix);
251 return buffer;
253 #endif /* CONFIG_RTC */
255 /* Read (up to) a line of text from fd into buffer and return number of bytes
256 * read (which may be larger than the number of bytes stored in buffer). If
257 * an error occurs, -1 is returned (and buffer contains whatever could be
258 * read). A line is terminated by a LF char. Neither LF nor CR chars are
259 * stored in buffer.
261 int read_line(int fd, char* buffer, int buffer_size)
263 int count = 0;
264 int num_read = 0;
266 errno = 0;
268 while (count < buffer_size)
270 unsigned char c;
272 if (1 != read(fd, &c, 1))
273 break;
275 num_read++;
277 if ( c == '\n' )
278 break;
280 if ( c == '\r' )
281 continue;
283 buffer[count++] = c;
286 buffer[MIN(count, buffer_size - 1)] = 0;
288 return errno ? -1 : num_read;
291 /* Performance optimized version of the previous function. */
292 int fast_readline(int fd, char *buf, int buf_size, void *parameters,
293 int (*callback)(int n, const char *buf, void *parameters))
295 char *p, *next;
296 int rc, pos = 0;
297 int count = 0;
299 while ( 1 )
301 next = NULL;
303 rc = read(fd, &buf[pos], buf_size - pos - 1);
304 if (rc >= 0)
305 buf[pos+rc] = '\0';
307 if ( (p = strchr(buf, '\r')) != NULL)
309 *p = '\0';
310 next = ++p;
312 else
313 p = buf;
315 if ( (p = strchr(p, '\n')) != NULL)
317 *p = '\0';
318 next = ++p;
321 rc = callback(count, buf, parameters);
322 if (rc < 0)
323 return rc;
325 count++;
326 if (next)
328 pos = buf_size - ((long)next - (long)buf) - 1;
329 memmove(buf, next, pos);
331 else
332 break ;
335 return 0;
338 #ifdef HAVE_LCD_BITMAP
340 #if LCD_DEPTH == 16
341 #define BMP_COMPRESSION 3 /* BI_BITFIELDS */
342 #define BMP_NUMCOLORS 3
343 #else
344 #define BMP_COMPRESSION 0 /* BI_RGB */
345 #if LCD_DEPTH <= 8
346 #define BMP_NUMCOLORS (1 << LCD_DEPTH)
347 #else
348 #define BMP_NUMCOLORS 0
349 #endif
350 #endif
352 #if LCD_DEPTH == 1
353 #define BMP_BPP 1
354 #define BMP_LINESIZE ((LCD_WIDTH/8 + 3) & ~3)
355 #elif LCD_DEPTH <= 4
356 #define BMP_BPP 4
357 #define BMP_LINESIZE ((LCD_WIDTH/2 + 3) & ~3)
358 #elif LCD_DEPTH <= 8
359 #define BMP_BPP 8
360 #define BMP_LINESIZE ((LCD_WIDTH + 3) & ~3)
361 #elif LCD_DEPTH <= 16
362 #define BMP_BPP 16
363 #define BMP_LINESIZE ((LCD_WIDTH*2 + 3) & ~3)
364 #else
365 #define BMP_BPP 24
366 #define BMP_LINESIZE ((LCD_WIDTH*3 + 3) & ~3)
367 #endif
369 #define BMP_HEADERSIZE (54 + 4 * BMP_NUMCOLORS)
370 #define BMP_DATASIZE (BMP_LINESIZE * LCD_HEIGHT)
371 #define BMP_TOTALSIZE (BMP_HEADERSIZE + BMP_DATASIZE)
373 #define LE16_CONST(x) (x)&0xff, ((x)>>8)&0xff
374 #define LE32_CONST(x) (x)&0xff, ((x)>>8)&0xff, ((x)>>16)&0xff, ((x)>>24)&0xff
376 static const unsigned char bmpheader[] =
378 0x42, 0x4d, /* 'BM' */
379 LE32_CONST(BMP_TOTALSIZE), /* Total file size */
380 0x00, 0x00, 0x00, 0x00, /* Reserved */
381 LE32_CONST(BMP_HEADERSIZE), /* Offset to start of pixel data */
383 0x28, 0x00, 0x00, 0x00, /* Size of (2nd) header */
384 LE32_CONST(LCD_WIDTH), /* Width in pixels */
385 LE32_CONST(LCD_HEIGHT), /* Height in pixels */
386 0x01, 0x00, /* Number of planes (always 1) */
387 LE16_CONST(BMP_BPP), /* Bits per pixel 1/4/8/16/24 */
388 LE32_CONST(BMP_COMPRESSION),/* Compression mode */
389 LE32_CONST(BMP_DATASIZE), /* Size of bitmap data */
390 0xc4, 0x0e, 0x00, 0x00, /* Horizontal resolution (pixels/meter) */
391 0xc4, 0x0e, 0x00, 0x00, /* Vertical resolution (pixels/meter) */
392 LE32_CONST(BMP_NUMCOLORS), /* Number of used colours */
393 LE32_CONST(BMP_NUMCOLORS), /* Number of important colours */
395 #if LCD_DEPTH == 1
396 #ifdef MROBE_100
397 2, 2, 94, 0x00, /* Colour #0 */
398 3, 6, 241, 0x00 /* Colour #1 */
399 #else
400 0x90, 0xee, 0x90, 0x00, /* Colour #0 */
401 0x00, 0x00, 0x00, 0x00 /* Colour #1 */
402 #endif
403 #elif LCD_DEPTH == 2
404 0xe6, 0xd8, 0xad, 0x00, /* Colour #0 */
405 0x99, 0x90, 0x73, 0x00, /* Colour #1 */
406 0x4c, 0x48, 0x39, 0x00, /* Colour #2 */
407 0x00, 0x00, 0x00, 0x00 /* Colour #3 */
408 #elif LCD_DEPTH == 16
409 0x00, 0xf8, 0x00, 0x00, /* red bitfield mask */
410 0xe0, 0x07, 0x00, 0x00, /* green bitfield mask */
411 0x1f, 0x00, 0x00, 0x00 /* blue bitfield mask */
412 #endif
415 static void (*screen_dump_hook)(int fh) = NULL;
417 void screen_dump(void)
419 int fh;
420 char filename[MAX_PATH];
421 int bx, by;
422 #if LCD_DEPTH == 1
423 static unsigned char line_block[8][BMP_LINESIZE];
424 #elif LCD_DEPTH == 2
425 #if LCD_PIXELFORMAT == HORIZONTAL_PACKING
426 static unsigned char line_block[BMP_LINESIZE];
427 #elif LCD_PIXELFORMAT == VERTICAL_PACKING
428 static unsigned char line_block[4][BMP_LINESIZE];
429 #elif LCD_PIXELFORMAT == VERTICAL_INTERLEAVED
430 static unsigned char line_block[8][BMP_LINESIZE];
431 #endif
432 #elif LCD_DEPTH == 16
433 static unsigned short line_block[BMP_LINESIZE/2];
434 #endif
436 #if CONFIG_RTC
437 create_datetime_filename(filename, "", "dump ", ".bmp", false);
438 #else
439 create_numbered_filename(filename, "", "dump_", ".bmp", 4
440 IF_CNFN_NUM_(, NULL));
441 #endif
443 fh = creat(filename);
444 if (fh < 0)
445 return;
447 if (screen_dump_hook)
449 screen_dump_hook(fh);
451 else
453 write(fh, bmpheader, sizeof(bmpheader));
455 /* BMP image goes bottom up */
456 #if LCD_DEPTH == 1
457 for (by = LCD_FBHEIGHT - 1; by >= 0; by--)
459 unsigned char *src = &lcd_framebuffer[by][0];
460 unsigned char *dst = &line_block[0][0];
462 memset(line_block, 0, sizeof(line_block));
463 for (bx = LCD_WIDTH/8; bx > 0; bx--)
465 unsigned dst_mask = 0x80;
466 int ix;
468 for (ix = 8; ix > 0; ix--)
470 unsigned char *dst_blk = dst;
471 unsigned src_byte = *src++;
472 int iy;
474 for (iy = 8; iy > 0; iy--)
476 if (src_byte & 0x80)
477 *dst_blk |= dst_mask;
478 src_byte <<= 1;
479 dst_blk += BMP_LINESIZE;
481 dst_mask >>= 1;
483 dst++;
486 write(fh, line_block, sizeof(line_block));
488 #elif LCD_DEPTH == 2
489 #if LCD_PIXELFORMAT == HORIZONTAL_PACKING
490 for (by = LCD_FBHEIGHT - 1; by >= 0; by--)
492 unsigned char *src = &lcd_framebuffer[by][0];
493 unsigned char *dst = line_block;
495 memset(line_block, 0, sizeof(line_block));
496 for (bx = LCD_FBWIDTH; bx > 0; bx--)
498 unsigned src_byte = *src++;
500 *dst++ = ((src_byte >> 2) & 0x30) | ((src_byte >> 4) & 0x03);
501 *dst++ = ((src_byte << 2) & 0x30) | (src_byte & 0x03);
504 write(fh, line_block, sizeof(line_block));
506 #elif LCD_PIXELFORMAT == VERTICAL_PACKING
507 for (by = LCD_FBHEIGHT - 1; by >= 0; by--)
509 unsigned char *src = &lcd_framebuffer[by][0];
510 unsigned char *dst = &line_block[3][0];
512 memset(line_block, 0, sizeof(line_block));
513 for (bx = LCD_WIDTH/2; bx > 0; bx--)
515 unsigned char *dst_blk = dst++;
516 unsigned src_byte0 = *src++ << 4;
517 unsigned src_byte1 = *src++;
518 int iy;
520 for (iy = 4; iy > 0; iy--)
522 *dst_blk = (src_byte0 & 0x30) | (src_byte1 & 0x03);
523 src_byte0 >>= 2;
524 src_byte1 >>= 2;
525 dst_blk -= BMP_LINESIZE;
529 write(fh, line_block, sizeof(line_block));
531 #elif LCD_PIXELFORMAT == VERTICAL_INTERLEAVED
532 for (by = LCD_FBHEIGHT - 1; by >= 0; by--)
534 const fb_data *src = &lcd_framebuffer[by][0];
535 unsigned char *dst = &line_block[7][0];
537 memset(line_block, 0, sizeof(line_block));
538 for (bx = LCD_WIDTH/2; bx > 0; bx--)
540 unsigned char *dst_blk = dst++;
541 unsigned src_data0 = *src++ << 4;
542 unsigned src_data1 = *src++;
543 int iy;
545 for (iy = 8; iy > 0; iy--)
547 *dst_blk = (src_data0 & 0x10) | (src_data1 & 0x01)
548 | ((src_data0 & 0x1000) | (src_data1 & 0x0100)) >> 7;
549 src_data0 >>= 1;
550 src_data1 >>= 1;
551 dst_blk -= BMP_LINESIZE;
555 write(fh, line_block, sizeof(line_block));
557 #endif
558 #elif LCD_DEPTH == 16
559 for (by = LCD_HEIGHT - 1; by >= 0; by--)
561 unsigned short *src = &lcd_framebuffer[by][0];
562 unsigned short *dst = line_block;
564 memset(line_block, 0, sizeof(line_block));
565 for (bx = LCD_WIDTH; bx > 0; bx--)
567 #if (LCD_PIXELFORMAT == RGB565SWAPPED)
568 /* iPod LCD data is big endian although the CPU is not */
569 *dst++ = htobe16(*src++);
570 #else
571 *dst++ = htole16(*src++);
572 #endif
575 write(fh, line_block, sizeof(line_block));
577 #endif /* LCD_DEPTH */
580 close(fh);
583 void screen_dump_set_hook(void (*hook)(int fh))
585 screen_dump_hook = hook;
588 #endif /* HAVE_LCD_BITMAP */
590 /* parse a line from a configuration file. the line format is:
592 name: value
594 Any whitespace before setting name or value (after ':') is ignored.
595 A # as first non-whitespace character discards the whole line.
596 Function sets pointers to null-terminated setting name and value.
597 Returns false if no valid config entry was found.
600 bool settings_parseline(char* line, char** name, char** value)
602 char* ptr;
604 while ( isspace(*line) )
605 line++;
607 if ( *line == '#' )
608 return false;
610 ptr = strchr(line, ':');
611 if ( !ptr )
612 return false;
614 *name = line;
615 *ptr = 0;
616 ptr++;
617 while (isspace(*ptr))
618 ptr++;
619 *value = ptr;
620 return true;
623 static void system_flush(void)
625 tree_flush();
626 call_ata_idle_notifys(true); /*doesnt work on usb and shutdown from ata thread */
629 static void system_restore(void)
631 tree_restore();
634 static bool clean_shutdown(void (*callback)(void *), void *parameter)
636 #ifdef SIMULATOR
637 (void)callback;
638 (void)parameter;
639 bookmark_autobookmark();
640 call_ata_idle_notifys(true);
641 exit(0);
642 #else
643 long msg_id = -1;
644 int i;
646 scrobbler_poweroff();
648 #if CONFIG_CHARGING && !defined(HAVE_POWEROFF_WHILE_CHARGING)
649 if(!charger_inserted())
650 #endif
652 bool batt_safe = battery_level_safe();
653 int audio_stat = audio_status();
655 FOR_NB_SCREENS(i)
656 screens[i].clear_display();
658 if (batt_safe)
660 #ifdef HAVE_TAGCACHE
661 if (!tagcache_prepare_shutdown())
663 cancel_shutdown();
664 gui_syncsplash(HZ, ID2P(LANG_TAGCACHE_BUSY));
665 return false;
667 #endif
668 if (battery_level() > 10)
669 gui_syncsplash(0, str(LANG_SHUTTINGDOWN));
670 else
672 msg_id = LANG_WARNING_BATTERY_LOW;
673 gui_syncsplash(0, "%s %s",
674 str(LANG_WARNING_BATTERY_LOW),
675 str(LANG_SHUTTINGDOWN));
678 else
680 msg_id = LANG_WARNING_BATTERY_EMPTY;
681 gui_syncsplash(0, "%s %s",
682 str(LANG_WARNING_BATTERY_EMPTY),
683 str(LANG_SHUTTINGDOWN));
686 if (global_settings.fade_on_stop
687 && (audio_stat & AUDIO_STATUS_PLAY))
689 fade(0);
692 if (batt_safe) /* do not save on critical battery */
694 #if defined(HAVE_RECORDING) && CONFIG_CODEC == SWCODEC
695 if (audio_stat & AUDIO_STATUS_RECORD)
697 rec_command(RECORDING_CMD_STOP);
698 /* wait for stop to complete */
699 while (audio_status() & AUDIO_STATUS_RECORD)
700 sleep(1);
702 #endif
703 bookmark_autobookmark();
705 /* audio_stop_recording == audio_stop for HWCODEC */
706 audio_stop();
708 if (callback != NULL)
709 callback(parameter);
711 #if CONFIG_CODEC != SWCODEC
712 /* wait for audio_stop or audio_stop_recording to complete */
713 while (audio_status())
714 sleep(1);
715 #endif
717 #if defined(HAVE_RECORDING) && CONFIG_CODEC == SWCODEC
718 audio_close_recording();
719 #endif
721 if(global_settings.talk_menu)
723 bool enqueue = false;
724 if(msg_id != -1)
726 talk_id(msg_id, enqueue);
727 enqueue = true;
729 talk_id(LANG_SHUTTINGDOWN, enqueue);
730 #if CONFIG_CODEC == SWCODEC
731 voice_wait();
732 #endif
735 system_flush();
736 #ifdef HAVE_EEPROM_SETTINGS
737 if (firmware_settings.initialized)
739 firmware_settings.disk_clean = true;
740 firmware_settings.bl_version = 0;
741 eeprom_settings_store();
743 #endif
745 #ifdef HAVE_DIRCACHE
746 else
747 dircache_disable();
748 #endif
750 shutdown_hw();
752 #endif
753 return false;
756 bool list_stop_handler(void)
758 bool ret = false;
760 /* Stop the music if it is playing */
761 if(audio_status())
763 if (!global_settings.party_mode)
765 if (global_settings.fade_on_stop)
766 fade(0);
767 bookmark_autobookmark();
768 audio_stop();
769 ret = true; /* bookmarking can make a refresh necessary */
772 #if CONFIG_CHARGING
773 #if (CONFIG_KEYPAD == RECORDER_PAD) && !defined(HAVE_SW_POWEROFF)
774 else
776 if (charger_inserted())
777 charging_splash();
778 else
779 shutdown_screen(); /* won't return if shutdown actually happens */
781 ret = true; /* screen is dirty, caller needs to refresh */
783 #endif
784 #ifndef HAVE_POWEROFF_WHILE_CHARGING
786 static long last_off = 0;
788 if (TIME_BEFORE(current_tick, last_off + HZ/2))
790 if (charger_inserted())
792 charging_splash();
793 ret = true; /* screen is dirty, caller needs to refresh */
796 last_off = current_tick;
798 #endif
799 #endif /* CONFIG_CHARGING */
800 return ret;
803 #if CONFIG_CHARGING
804 static bool waiting_to_resume_play = false;
805 static long play_resume_tick;
807 static void car_adapter_mode_processing(bool inserted)
809 if (global_settings.car_adapter_mode)
811 if(inserted)
814 * Just got plugged in, delay & resume if we were playing
816 if (audio_status() & AUDIO_STATUS_PAUSE)
818 /* delay resume a bit while the engine is cranking */
819 play_resume_tick = current_tick + HZ*5;
820 waiting_to_resume_play = true;
823 else
826 * Just got unplugged, pause if playing
828 if ((audio_status() & AUDIO_STATUS_PLAY) &&
829 !(audio_status() & AUDIO_STATUS_PAUSE))
831 if (global_settings.fade_on_stop)
832 fade(0);
833 else
834 audio_pause();
836 waiting_to_resume_play = false;
841 static void car_adapter_tick(void)
843 if (waiting_to_resume_play)
845 if (TIME_AFTER(current_tick, play_resume_tick))
847 if (audio_status() & AUDIO_STATUS_PAUSE)
849 queue_broadcast(SYS_CAR_ADAPTER_RESUME, 0);
851 waiting_to_resume_play = false;
856 void car_adapter_mode_init(void)
858 tick_add_task(car_adapter_tick);
860 #endif
862 #ifdef HAVE_HEADPHONE_DETECTION
863 static void unplug_change(bool inserted)
865 static bool headphone_caused_pause = false;
867 if (global_settings.unplug_mode)
869 int audio_stat = audio_status();
870 if (inserted)
872 if ((audio_stat & AUDIO_STATUS_PLAY) &&
873 headphone_caused_pause &&
874 global_settings.unplug_mode > 1 )
875 audio_resume();
876 backlight_on();
877 headphone_caused_pause = false;
878 } else {
879 if ((audio_stat & AUDIO_STATUS_PLAY) &&
880 !(audio_stat & AUDIO_STATUS_PAUSE))
882 headphone_caused_pause = true;
883 audio_pause();
885 if (global_settings.unplug_rw)
887 if (audio_current_track()->elapsed >
888 (unsigned long)(global_settings.unplug_rw*1000))
889 audio_ff_rewind(audio_current_track()->elapsed -
890 (global_settings.unplug_rw*1000));
891 else
892 audio_ff_rewind(0);
898 #endif
900 long default_event_handler_ex(long event, void (*callback)(void *), void *parameter)
902 switch(event)
904 case SYS_BATTERY_UPDATE:
905 if(global_settings.talk_battery_level)
907 talk_ids(true, VOICE_PAUSE, VOICE_PAUSE,
908 LANG_BATTERY_TIME,
909 TALK_ID(battery_level(), UNIT_PERCENT),
910 VOICE_PAUSE);
911 talk_force_enqueue_next();
913 break;
914 case SYS_USB_CONNECTED:
915 if (callback != NULL)
916 callback(parameter);
917 #ifdef HAVE_MMC
918 if (!mmc_touched() ||
919 (mmc_remove_request() == SYS_HOTSWAP_EXTRACTED))
920 #endif
922 scrobbler_flush_cache();
923 system_flush();
924 #ifdef BOOTFILE
925 #if !defined(USB_NONE) && !defined(USB_IPODSTYLE)
926 check_bootfile(false); /* gets initial size */
927 #endif
928 #endif
929 usb_screen();
930 #ifdef BOOTFILE
931 #if !defined(USB_NONE) && !defined(USB_IPODSTYLE)
932 check_bootfile(true);
933 #endif
934 #endif
935 system_restore();
937 return SYS_USB_CONNECTED;
938 case SYS_POWEROFF:
939 if (!clean_shutdown(callback, parameter))
940 return SYS_POWEROFF;
941 break;
942 #if CONFIG_CHARGING
943 case SYS_CHARGER_CONNECTED:
944 car_adapter_mode_processing(true);
945 return SYS_CHARGER_CONNECTED;
947 case SYS_CHARGER_DISCONNECTED:
948 car_adapter_mode_processing(false);
949 return SYS_CHARGER_DISCONNECTED;
951 case SYS_CAR_ADAPTER_RESUME:
952 audio_resume();
953 return SYS_CAR_ADAPTER_RESUME;
954 #endif
955 #ifdef HAVE_HEADPHONE_DETECTION
956 case SYS_PHONE_PLUGGED:
957 unplug_change(true);
958 return SYS_PHONE_PLUGGED;
960 case SYS_PHONE_UNPLUGGED:
961 unplug_change(false);
962 return SYS_PHONE_UNPLUGGED;
963 #endif
965 return 0;
968 long default_event_handler(long event)
970 return default_event_handler_ex(event, NULL, NULL);
973 int show_logo( void )
975 #ifdef HAVE_LCD_BITMAP
976 char version[32];
977 int font_h, font_w;
979 snprintf(version, sizeof(version), "Ver. %s", appsversion);
981 lcd_clear_display();
982 lcd_bitmap(rockboxlogo, 0, 10, BMPWIDTH_rockboxlogo, BMPHEIGHT_rockboxlogo);
983 lcd_setfont(FONT_SYSFIXED);
984 lcd_getstringsize((unsigned char *)"A", &font_w, &font_h);
985 lcd_putsxy((LCD_WIDTH/2) - ((strlen(version)*font_w)/2),
986 LCD_HEIGHT-font_h, (unsigned char *)version);
987 lcd_setfont(FONT_UI);
989 #else
990 char *rockbox = " ROCKbox!";
992 lcd_clear_display();
993 lcd_double_height(true);
994 lcd_puts(0, 0, rockbox);
995 lcd_puts_scroll(0, 1, appsversion);
996 #endif
997 lcd_update();
999 #ifdef HAVE_REMOTE_LCD
1000 lcd_remote_clear_display();
1001 lcd_remote_bitmap(remote_rockboxlogo, 0, 10, BMPWIDTH_remote_rockboxlogo,
1002 BMPHEIGHT_remote_rockboxlogo);
1003 lcd_remote_setfont(FONT_SYSFIXED);
1004 lcd_remote_getstringsize((unsigned char *)"A", &font_w, &font_h);
1005 lcd_remote_putsxy((LCD_REMOTE_WIDTH/2) - ((strlen(version)*font_w)/2),
1006 LCD_REMOTE_HEIGHT-font_h, (unsigned char *)version);
1007 lcd_remote_setfont(FONT_UI);
1008 lcd_remote_update();
1009 #endif
1011 return 0;
1014 #if CONFIG_CODEC == SWCODEC
1015 int get_replaygain_mode(bool have_track_gain, bool have_album_gain)
1017 int type;
1019 bool track = ((global_settings.replaygain_type == REPLAYGAIN_TRACK)
1020 || ((global_settings.replaygain_type == REPLAYGAIN_SHUFFLE)
1021 && global_settings.playlist_shuffle));
1023 type = (!track && have_album_gain) ? REPLAYGAIN_ALBUM
1024 : have_track_gain ? REPLAYGAIN_TRACK : -1;
1026 return type;
1028 #endif
1030 #ifdef BOOTFILE
1031 #if !defined(USB_NONE) && !defined(USB_IPODSTYLE)
1033 memorize/compare details about the BOOTFILE
1034 we don't use dircache because it may not be up to date after
1035 USB disconnect (scanning in the background)
1037 void check_bootfile(bool do_rolo)
1039 static unsigned short wrtdate = 0;
1040 static unsigned short wrttime = 0;
1041 DIR* dir = NULL;
1042 struct dirent* entry = NULL;
1044 /* 1. open BOOTDIR and find the BOOTFILE dir entry */
1045 dir = opendir(BOOTDIR);
1047 if(!dir) return; /* do we want an error splash? */
1049 /* loop all files in BOOTDIR */
1050 while(0 != (entry = readdir(dir)))
1052 if(!strcasecmp(entry->d_name, BOOTFILE))
1054 /* found the bootfile */
1055 if(wrtdate && do_rolo)
1057 if((entry->wrtdate != wrtdate) ||
1058 (entry->wrttime != wrttime))
1060 char *lines[] = { ID2P(LANG_BOOT_CHANGED),
1061 ID2P(LANG_REBOOT_NOW) };
1062 struct text_message message={ lines, 2 };
1063 button_clear_queue(); /* Empty the keyboard buffer */
1064 if(gui_syncyesno_run(&message, NULL, NULL) == YESNO_YES)
1065 rolo_load(BOOTDIR "/" BOOTFILE);
1068 wrtdate = entry->wrtdate;
1069 wrttime = entry->wrttime;
1072 closedir(dir);
1074 #endif
1075 #endif
1077 /* check range, set volume and save settings */
1078 void setvol(void)
1080 const int min_vol = sound_min(SOUND_VOLUME);
1081 const int max_vol = sound_max(SOUND_VOLUME);
1082 if (global_settings.volume < min_vol)
1083 global_settings.volume = min_vol;
1084 if (global_settings.volume > max_vol)
1085 global_settings.volume = max_vol;
1086 sound_set_volume(global_settings.volume);
1087 settings_save();
1090 #ifdef HAVE_LCD_COLOR
1092 * Helper function to convert a string of 6 hex digits to a native colour
1095 static int hex2dec(int c)
1097 return (((c) >= '0' && ((c) <= '9')) ? (c) - '0' :
1098 (toupper(c)) - 'A' + 10);
1101 int hex_to_rgb(const char* hex, int* color)
1103 int red, green, blue;
1104 int i = 0;
1106 while ((i < 6) && (isxdigit(hex[i])))
1107 i++;
1109 if (i < 6)
1110 return -1;
1112 red = (hex2dec(hex[0]) << 4) | hex2dec(hex[1]);
1113 green = (hex2dec(hex[2]) << 4) | hex2dec(hex[3]);
1114 blue = (hex2dec(hex[4]) << 4) | hex2dec(hex[5]);
1116 *color = LCD_RGBPACK(red,green,blue);
1118 return 0;
1120 #endif /* HAVE_LCD_COLOR */
1122 char* strrsplt(char* str, int c)
1124 char* s = strrchr(str, c);
1126 if (s != NULL)
1128 *s++ = '\0';
1130 else
1132 s = str;
1135 return s;
1138 /* Test file existence, using dircache of possible */
1139 bool file_exists(const char *file)
1141 int fd;
1143 if (!file || strlen(file) <= 0)
1144 return false;
1146 #ifdef HAVE_DIRCACHE
1147 if (dircache_is_enabled())
1148 return (dircache_get_entry_ptr(file) != NULL);
1149 #endif
1151 fd = open(file, O_RDONLY);
1152 if (fd < 0)
1153 return false;
1154 close(fd);
1155 return true;
1158 bool dir_exists(const char *path)
1160 DIR* d = opendir(path);
1161 if (!d)
1162 return false;
1163 closedir(d);
1164 return true;
1168 * removes the extension of filename (if it doesn't start with a .)
1169 * puts the result in buffer
1171 char *strip_extension(char* buffer, int buffer_size, const char *filename)
1173 char *dot = strrchr(filename, '.');
1174 int len;
1176 if (buffer_size <= 0)
1178 return NULL;
1181 buffer_size--; /* Make room for end nil */
1183 if (dot != 0 && filename[0] != '.')
1185 len = dot - filename;
1186 len = MIN(len, buffer_size);
1187 strncpy(buffer, filename, len);
1189 else
1191 len = buffer_size;
1192 strncpy(buffer, filename, buffer_size);
1195 buffer[len] = 0;
1197 return buffer;
1200 #ifdef HAVE_LCD_BITMAP
1201 /* A simplified scanf - used (at time of writing) by wps parsing functions.
1203 fmt - char array specifying the format of each list option. Valid values
1204 are: d - int
1205 s - string (sets pointer to string, without copying)
1206 c - hex colour (RGB888 - e.g. ff00ff)
1207 g - greyscale "colour" (0-3)
1209 sep - list separator (e.g. ',' or '|')
1210 str - string to parse, must be terminated by 0 or sep
1211 ... - pointers to store the parsed values
1213 return value - pointer to char after parsed data, 0 if there was an error.
1217 /* '0'-'3' are ASCII 0x30 to 0x33 */
1218 #define is0123(x) (((x) & 0xfc) == 0x30)
1220 const char* parse_list(const char *fmt, const char sep, const char* str, ...)
1222 va_list ap;
1223 const char* p = str;
1224 const char** s;
1225 int* d;
1227 va_start(ap, str);
1229 while (*fmt)
1231 /* Check for separator, if we're not at the start */
1232 if (p != str)
1234 if (*p != sep)
1235 goto err;
1236 p++;
1239 switch (*fmt++)
1241 case 's': /* string - return a pointer to it (not a copy) */
1242 s = va_arg(ap, const char **);
1244 *s = p;
1245 while (*p && *p != sep)
1246 p++;
1248 break;
1250 case 'd': /* int */
1251 d = va_arg(ap, int*);
1252 if (!isdigit(*p))
1253 goto err;
1255 *d = *p++ - '0';
1257 while (isdigit(*p))
1258 *d = (*d * 10) + (*p++ - '0');
1260 break;
1262 #ifdef HAVE_LCD_COLOR
1263 case 'c': /* colour (rrggbb - e.g. f3c1a8) */
1264 d = va_arg(ap, int*);
1266 if (hex_to_rgb(p, d) < 0)
1267 goto err;
1269 p += 6;
1271 break;
1272 #endif
1274 #if LCD_DEPTH == 2 || (defined(HAVE_REMOTE_LCD) && LCD_REMOTE_DEPTH == 2)
1275 case 'g': /* greyscale colour (0-3) */
1276 d = va_arg(ap, int*);
1278 if (is0123(*p))
1279 *d = *p++ - '0';
1280 else
1281 goto err;
1283 break;
1284 #endif
1286 default: /* Unknown format type */
1287 goto err;
1288 break;
1292 va_end(ap);
1293 return p;
1295 err:
1296 va_end(ap);
1297 return 0;
1299 #endif