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