Fix panic after usb extraction if lastfm logging is enabled.
[maemo-rb.git] / apps / misc.c
blob69c62da2383505e504738c0dc341b0cd7b204065
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 <stdio.h>
24 #include <stdarg.h>
25 #include <errno.h>
26 #include "string-extra.h"
27 #include "config.h"
28 #include "misc.h"
29 #include "system.h"
30 #include "lcd.h"
31 #include "file.h"
32 #include "filefuncs.h"
33 #ifndef __PCTOOL__
34 #include "lang.h"
35 #include "dir.h"
36 #include "lcd-remote.h"
37 #include "timefuncs.h"
38 #include "screens.h"
39 #include "usb_screen.h"
40 #include "talk.h"
41 #include "audio.h"
42 #include "mp3_playback.h"
43 #include "settings.h"
44 #include "storage.h"
45 #include "ata_idle_notify.h"
46 #include "kernel.h"
47 #include "power.h"
48 #include "powermgmt.h"
49 #include "backlight.h"
50 #include "version.h"
51 #include "font.h"
52 #include "splash.h"
53 #include "tagcache.h"
54 #include "scrobbler.h"
55 #include "sound.h"
56 #include "playlist.h"
57 #include "yesno.h"
58 #include "viewport.h"
60 #include "debug.h"
62 #if CONFIG_TUNER
63 #include "radio.h"
64 #endif
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 "bookmark.h"
83 #include "wps.h"
84 #include "playback.h"
85 #if CONFIG_CODEC == SWCODEC
86 #include "voice_thread.h"
87 #endif
89 #ifdef BOOTFILE
90 #if !defined(USB_NONE) && !defined(USB_HANDLED_BY_OF) \
91 || defined(HAVE_HOTSWAP_STORAGE_AS_MAIN)
92 #include "rolo.h"
93 #endif
94 #endif
96 /* units used with output_dyn_value */
97 const unsigned char * const byte_units[] =
99 ID2P(LANG_BYTE),
100 ID2P(LANG_KILOBYTE),
101 ID2P(LANG_MEGABYTE),
102 ID2P(LANG_GIGABYTE)
105 const unsigned char * const * const kbyte_units = &byte_units[1];
107 /* Format a large-range value for output, using the appropriate unit so that
108 * the displayed value is in the range 1 <= display < 1000 (1024 for "binary"
109 * units) if possible, and 3 significant digits are shown. If a buffer is
110 * given, the result is snprintf()'d into that buffer, otherwise the result is
111 * voiced.*/
112 char *output_dyn_value(char *buf, int buf_size, int value,
113 const unsigned char * const *units, bool bin_scale)
115 int scale = bin_scale ? 1024 : 1000;
116 int fraction = 0;
117 int unit_no = 0;
118 char tbuf[5];
120 while (value >= scale)
122 fraction = value % scale;
123 value /= scale;
124 unit_no++;
126 if (bin_scale)
127 fraction = fraction * 1000 / 1024;
129 if (value >= 100 || !unit_no)
130 tbuf[0] = '\0';
131 else if (value >= 10)
132 snprintf(tbuf, sizeof(tbuf), "%01d", fraction / 100);
133 else
134 snprintf(tbuf, sizeof(tbuf), "%02d", fraction / 10);
136 if (buf)
138 if (*tbuf)
139 snprintf(buf, buf_size, "%d%s%s%s", value, str(LANG_POINT),
140 tbuf, P2STR(units[unit_no]));
141 else
142 snprintf(buf, buf_size, "%d%s", value, P2STR(units[unit_no]));
144 else
146 talk_fractional(tbuf, value, P2ID(units[unit_no]));
148 return buf;
151 /* Ask the user if they really want to erase the current dynamic playlist
152 * returns true if the playlist should be replaced */
153 bool warn_on_pl_erase(void)
155 if (global_settings.warnon_erase_dynplaylist &&
156 !global_settings.party_mode &&
157 playlist_modified(NULL))
159 static const char *lines[] =
160 {ID2P(LANG_WARN_ERASEDYNPLAYLIST_PROMPT)};
161 static const struct text_message message={lines, 1};
163 return (gui_syncyesno_run(&message, NULL, NULL) == YESNO_YES);
165 else
166 return true;
170 /* Performance optimized version of the read_line() (see below) function. */
171 int fast_readline(int fd, char *buf, int buf_size, void *parameters,
172 int (*callback)(int n, char *buf, void *parameters))
174 char *p, *next;
175 int rc, pos = 0;
176 int count = 0;
178 while ( 1 )
180 next = NULL;
182 rc = read(fd, &buf[pos], buf_size - pos - 1);
183 if (rc >= 0)
184 buf[pos+rc] = '\0';
186 if ( (p = strchr(buf, '\n')) != NULL)
188 *p = '\0';
189 next = ++p;
192 rc = callback(count, buf, parameters);
193 if (rc < 0)
194 return rc;
196 count++;
197 if (next)
199 pos = buf_size - ((long)next - (long)buf) - 1;
200 memmove(buf, next, pos);
202 else
203 break ;
206 return 0;
209 /* parse a line from a configuration file. the line format is:
211 name: value
213 Any whitespace before setting name or value (after ':') is ignored.
214 A # as first non-whitespace character discards the whole line.
215 Function sets pointers to null-terminated setting name and value.
216 Returns false if no valid config entry was found.
219 bool settings_parseline(char* line, char** name, char** value)
221 char* ptr;
223 line = skip_whitespace(line);
225 if ( *line == '#' )
226 return false;
228 ptr = strchr(line, ':');
229 if ( !ptr )
230 return false;
232 *name = line;
233 *ptr = 0;
234 ptr++;
235 ptr = skip_whitespace(ptr);
236 *value = ptr;
237 return true;
240 static void system_flush(void)
242 playlist_shutdown();
243 tree_flush();
244 call_storage_idle_notifys(true); /*doesnt work on usb and shutdown from ata thread */
247 static void system_restore(void)
249 tree_restore();
252 static bool clean_shutdown(void (*callback)(void *), void *parameter)
254 long msg_id = -1;
255 int i;
257 scrobbler_poweroff();
259 #if CONFIG_CHARGING && !defined(HAVE_POWEROFF_WHILE_CHARGING)
260 if(!charger_inserted())
261 #endif
263 bool batt_safe = battery_level_safe();
264 #if CONFIG_CODEC != SWCODEC || defined(HAVE_RECORDING)
265 int audio_stat = audio_status();
266 #endif
268 FOR_NB_SCREENS(i)
270 screens[i].clear_display();
271 screens[i].update();
274 if (batt_safe)
276 #ifdef HAVE_TAGCACHE
277 if (!tagcache_prepare_shutdown())
279 cancel_shutdown();
280 splash(HZ, ID2P(LANG_TAGCACHE_BUSY));
281 return false;
283 #endif
284 if (battery_level() > 10)
285 splash(0, str(LANG_SHUTTINGDOWN));
286 else
288 msg_id = LANG_WARNING_BATTERY_LOW;
289 splashf(0, "%s %s", str(LANG_WARNING_BATTERY_LOW),
290 str(LANG_SHUTTINGDOWN));
293 else
295 msg_id = LANG_WARNING_BATTERY_EMPTY;
296 splashf(0, "%s %s", str(LANG_WARNING_BATTERY_EMPTY),
297 str(LANG_SHUTTINGDOWN));
299 #if CONFIG_CODEC != SWCODEC
300 if (global_settings.fade_on_stop
301 && (audio_stat & AUDIO_STATUS_PLAY))
303 fade(false, false);
305 #endif
307 if (batt_safe) /* do not save on critical battery */
309 #if defined(HAVE_RECORDING) && CONFIG_CODEC == SWCODEC
310 if (audio_stat & AUDIO_STATUS_RECORD)
312 rec_command(RECORDING_CMD_STOP);
313 /* wait for stop to complete */
314 while (audio_status() & AUDIO_STATUS_RECORD)
315 sleep(1);
317 #endif
318 bookmark_autobookmark(false);
320 /* audio_stop_recording == audio_stop for HWCODEC */
321 audio_stop();
323 if (callback != NULL)
324 callback(parameter);
326 #if CONFIG_CODEC != SWCODEC
327 /* wait for audio_stop or audio_stop_recording to complete */
328 while (audio_status())
329 sleep(1);
330 #endif
332 #if defined(HAVE_RECORDING) && CONFIG_CODEC == SWCODEC
333 audio_close_recording();
334 #endif
336 if(global_settings.talk_menu)
338 bool enqueue = false;
339 if(msg_id != -1)
341 talk_id(msg_id, enqueue);
342 enqueue = true;
344 talk_id(LANG_SHUTTINGDOWN, enqueue);
345 #if CONFIG_CODEC == SWCODEC
346 voice_wait();
347 #endif
350 system_flush();
351 #ifdef HAVE_EEPROM_SETTINGS
352 if (firmware_settings.initialized)
354 firmware_settings.disk_clean = true;
355 firmware_settings.bl_version = 0;
356 eeprom_settings_store();
358 #endif
360 #ifdef HAVE_DIRCACHE
361 else
362 dircache_disable();
363 #endif
365 shutdown_hw();
367 return false;
370 bool list_stop_handler(void)
372 bool ret = false;
374 #if CONFIG_TUNER
375 radio_stop();
376 #endif
378 /* Stop the music if it is playing */
379 if(audio_status())
381 if (!global_settings.party_mode)
383 #if CONFIG_CODEC != SWCODEC
384 if (global_settings.fade_on_stop)
385 fade(false, false);
386 #endif
387 bookmark_autobookmark(true);
388 audio_stop();
389 ret = true; /* bookmarking can make a refresh necessary */
392 #if CONFIG_CHARGING
393 #if (CONFIG_KEYPAD == RECORDER_PAD) && !defined(HAVE_SW_POWEROFF)
394 else
396 if (charger_inserted())
397 charging_splash();
398 else
399 shutdown_screen(); /* won't return if shutdown actually happens */
401 ret = true; /* screen is dirty, caller needs to refresh */
403 #endif
404 #ifndef HAVE_POWEROFF_WHILE_CHARGING
406 static long last_off = 0;
408 if (TIME_BEFORE(current_tick, last_off + HZ/2))
410 if (charger_inserted())
412 charging_splash();
413 ret = true; /* screen is dirty, caller needs to refresh */
416 last_off = current_tick;
418 #endif
419 #endif /* CONFIG_CHARGING */
420 return ret;
423 #if CONFIG_CHARGING
424 static bool waiting_to_resume_play = false;
425 static long play_resume_tick;
427 static void car_adapter_mode_processing(bool inserted)
429 if (global_settings.car_adapter_mode)
431 if(inserted)
434 * Just got plugged in, delay & resume if we were playing
436 if (audio_status() & AUDIO_STATUS_PAUSE)
438 /* delay resume a bit while the engine is cranking */
439 play_resume_tick = current_tick + HZ*5;
440 waiting_to_resume_play = true;
443 else
446 * Just got unplugged, pause if playing
448 if ((audio_status() & AUDIO_STATUS_PLAY) &&
449 !(audio_status() & AUDIO_STATUS_PAUSE))
451 pause_action(true, true);
453 waiting_to_resume_play = false;
458 static void car_adapter_tick(void)
460 if (waiting_to_resume_play)
462 if (TIME_AFTER(current_tick, play_resume_tick))
464 if (audio_status() & AUDIO_STATUS_PAUSE)
466 queue_broadcast(SYS_CAR_ADAPTER_RESUME, 0);
468 waiting_to_resume_play = false;
473 void car_adapter_mode_init(void)
475 tick_add_task(car_adapter_tick);
477 #endif
479 #ifdef HAVE_HEADPHONE_DETECTION
480 static void unplug_change(bool inserted)
482 static bool headphone_caused_pause = false;
484 if (global_settings.unplug_mode)
486 int audio_stat = audio_status();
487 if (inserted)
489 backlight_on();
490 if ((audio_stat & AUDIO_STATUS_PLAY) &&
491 headphone_caused_pause &&
492 global_settings.unplug_mode > 1 )
493 unpause_action(true, true);
494 headphone_caused_pause = false;
495 } else {
496 if ((audio_stat & AUDIO_STATUS_PLAY) &&
497 !(audio_stat & AUDIO_STATUS_PAUSE))
499 headphone_caused_pause = true;
500 pause_action(false, false);
505 #endif
507 long default_event_handler_ex(long event, void (*callback)(void *), void *parameter)
509 #if CONFIG_PLATFORM & (PLATFORM_ANDROID|PLATFORM_MAEMO)
510 static bool resume = false;
511 #endif
513 switch(event)
515 case SYS_BATTERY_UPDATE:
516 if(global_settings.talk_battery_level)
518 talk_ids(true, VOICE_PAUSE, VOICE_PAUSE,
519 LANG_BATTERY_TIME,
520 TALK_ID(battery_level(), UNIT_PERCENT),
521 VOICE_PAUSE);
522 talk_force_enqueue_next();
524 break;
525 case SYS_USB_CONNECTED:
526 if (callback != NULL)
527 callback(parameter);
528 #if (CONFIG_STORAGE & STORAGE_MMC) && (defined(ARCHOS_ONDIOSP) || defined(ARCHOS_ONDIOFM))
529 if (!mmc_touched() ||
530 (mmc_remove_request() == SYS_HOTSWAP_EXTRACTED))
531 #endif
533 system_flush();
534 #ifdef BOOTFILE
535 #if !defined(USB_NONE) && !defined(USB_HANDLED_BY_OF)
536 check_bootfile(false); /* gets initial size */
537 #endif
538 #endif
539 gui_usb_screen_run(false);
540 #ifdef BOOTFILE
541 #if !defined(USB_NONE) && !defined(USB_HANDLED_BY_OF)
542 check_bootfile(true);
543 #endif
544 #endif
545 system_restore();
547 return SYS_USB_CONNECTED;
549 case SYS_POWEROFF:
550 if (!clean_shutdown(callback, parameter))
551 return SYS_POWEROFF;
552 break;
553 #if CONFIG_CHARGING
554 case SYS_CHARGER_CONNECTED:
555 car_adapter_mode_processing(true);
556 return SYS_CHARGER_CONNECTED;
558 case SYS_CHARGER_DISCONNECTED:
559 car_adapter_mode_processing(false);
560 /*reset rockbox battery runtime*/
561 global_status.runtime = 0;
562 return SYS_CHARGER_DISCONNECTED;
564 case SYS_CAR_ADAPTER_RESUME:
565 unpause_action(true, true);
566 return SYS_CAR_ADAPTER_RESUME;
567 #endif
568 #ifdef HAVE_HOTSWAP_STORAGE_AS_MAIN
569 case SYS_FS_CHANGED:
571 /* simple sanity: assume rockbox is on the first hotswappable
572 * driver, abort out if that one isn't inserted */
573 int i;
574 for (i = 0; i < NUM_DRIVES; i++)
576 if (storage_removable(i) && !storage_present(i))
577 return SYS_FS_CHANGED;
579 system_flush();
580 check_bootfile(true); /* state gotten in main.c:init() */
581 system_restore();
583 return SYS_FS_CHANGED;
584 #endif
585 #ifdef HAVE_HEADPHONE_DETECTION
586 case SYS_PHONE_PLUGGED:
587 unplug_change(true);
588 return SYS_PHONE_PLUGGED;
590 case SYS_PHONE_UNPLUGGED:
591 unplug_change(false);
592 return SYS_PHONE_UNPLUGGED;
593 #endif
594 #ifdef IPOD_ACCESSORY_PROTOCOL
595 case SYS_IAP_PERIODIC:
596 iap_periodic();
597 return SYS_IAP_PERIODIC;
598 case SYS_IAP_HANDLEPKT:
599 iap_handlepkt();
600 return SYS_IAP_HANDLEPKT;
601 #endif
602 #if CONFIG_PLATFORM & (PLATFORM_ANDROID|PLATFORM_MAEMO)
603 /* stop playback if we receive a call */
604 case SYS_CALL_INCOMING:
605 resume = audio_status() == AUDIO_STATUS_PLAY;
606 list_stop_handler();
607 return SYS_CALL_INCOMING;
608 /* resume playback if needed */
609 case SYS_CALL_HUNG_UP:
610 if (resume && playlist_resume() != -1)
612 playlist_start(global_status.resume_index,
613 global_status.resume_offset);
615 resume = false;
616 return SYS_CALL_HUNG_UP;
617 #endif
618 #if (CONFIG_PLATFORM & PLATFORM_HOSTED) && defined(PLATFORM_HAS_VOLUME_CHANGE)
619 case SYS_VOLUME_CHANGED:
621 static bool firstvolume = true;
622 /* kludge: since this events go to the button_queue,
623 * event data is available in the last button data */
624 int volume = button_get_data();
625 DEBUGF("SYS_VOLUME_CHANGED: %d\n", volume);
626 if (global_settings.volume != volume) {
627 global_settings.volume = volume;
628 if (firstvolume) {
629 setvol();
630 firstvolume = false;
633 return 0;
635 #endif
636 #ifdef HAVE_MULTIMEDIA_KEYS
637 /* multimedia keys on keyboards, headsets */
638 case BUTTON_MULTIMEDIA_PLAYPAUSE:
640 int status = audio_status();
641 if (status & AUDIO_STATUS_PLAY)
643 if (status & AUDIO_STATUS_PAUSE)
644 unpause_action(true, true);
645 else
646 pause_action(true, true);
648 else
649 if (playlist_resume() != -1)
651 playlist_start(global_status.resume_index,
652 global_status.resume_offset);
654 return event;
656 case BUTTON_MULTIMEDIA_NEXT:
657 audio_next();
658 return event;
659 case BUTTON_MULTIMEDIA_PREV:
660 audio_prev();
661 return event;
662 case BUTTON_MULTIMEDIA_STOP:
663 list_stop_handler();
664 return event;
665 case BUTTON_MULTIMEDIA_REW:
666 case BUTTON_MULTIMEDIA_FFWD:
667 /* not supported yet, needs to be done in the WPS */
668 return 0;
669 #endif
671 return 0;
674 long default_event_handler(long event)
676 return default_event_handler_ex(event, NULL, NULL);
679 int show_logo( void )
681 #ifdef HAVE_LCD_BITMAP
682 char version[32];
683 int font_h, font_w;
685 snprintf(version, sizeof(version), "Ver. %s", rbversion);
687 lcd_clear_display();
688 #if defined(SANSA_CLIP) || defined(SANSA_CLIPV2) || defined(SANSA_CLIPPLUS)
689 /* display the logo in the blue area of the screen */
690 lcd_setfont(FONT_SYSFIXED);
691 lcd_getstringsize((unsigned char *)"A", &font_w, &font_h);
692 lcd_putsxy((LCD_WIDTH/2) - ((strlen(version)*font_w)/2),
693 0, (unsigned char *)version);
694 lcd_bitmap(rockboxlogo, (LCD_WIDTH - BMPWIDTH_rockboxlogo) / 2, 16,
695 BMPWIDTH_rockboxlogo, BMPHEIGHT_rockboxlogo);
696 #else
697 lcd_bitmap(rockboxlogo, (LCD_WIDTH - BMPWIDTH_rockboxlogo) / 2, 10,
698 BMPWIDTH_rockboxlogo, BMPHEIGHT_rockboxlogo);
699 lcd_setfont(FONT_SYSFIXED);
700 lcd_getstringsize((unsigned char *)"A", &font_w, &font_h);
701 lcd_putsxy((LCD_WIDTH/2) - ((strlen(version)*font_w)/2),
702 LCD_HEIGHT-font_h, (unsigned char *)version);
703 #endif
704 lcd_setfont(FONT_UI);
706 #else
707 char *rockbox = " ROCKbox!";
709 lcd_clear_display();
710 lcd_double_height(true);
711 lcd_puts(0, 0, rockbox);
712 lcd_puts_scroll(0, 1, rbversion);
713 #endif
714 lcd_update();
716 #ifdef HAVE_REMOTE_LCD
717 lcd_remote_clear_display();
718 lcd_remote_bitmap(remote_rockboxlogo, 0, 10, BMPWIDTH_remote_rockboxlogo,
719 BMPHEIGHT_remote_rockboxlogo);
720 lcd_remote_setfont(FONT_SYSFIXED);
721 lcd_remote_getstringsize((unsigned char *)"A", &font_w, &font_h);
722 lcd_remote_putsxy((LCD_REMOTE_WIDTH/2) - ((strlen(version)*font_w)/2),
723 LCD_REMOTE_HEIGHT-font_h, (unsigned char *)version);
724 lcd_remote_setfont(FONT_UI);
725 lcd_remote_update();
726 #endif
728 return 0;
731 #ifdef BOOTFILE
732 #if !defined(USB_NONE) && !defined(USB_HANDLED_BY_OF) || defined(HAVE_HOTSWAP_STORAGE_AS_MAIN)
734 memorize/compare details about the BOOTFILE
735 we don't use dircache because it may not be up to date after
736 USB disconnect (scanning in the background)
738 void check_bootfile(bool do_rolo)
740 static unsigned short wrtdate = 0;
741 static unsigned short wrttime = 0;
742 DIR* dir = NULL;
743 struct dirent* entry = NULL;
745 /* 1. open BOOTDIR and find the BOOTFILE dir entry */
746 dir = opendir(BOOTDIR);
748 if(!dir) return; /* do we want an error splash? */
750 /* loop all files in BOOTDIR */
751 while(0 != (entry = readdir(dir)))
753 if(!strcasecmp(entry->d_name, BOOTFILE))
755 struct dirinfo info = dir_get_info(dir, entry);
756 /* found the bootfile */
757 if(wrtdate && do_rolo)
759 if((info.wrtdate != wrtdate) ||
760 (info.wrttime != wrttime))
762 static const char *lines[] = { ID2P(LANG_BOOT_CHANGED),
763 ID2P(LANG_REBOOT_NOW) };
764 static const struct text_message message={ lines, 2 };
765 button_clear_queue(); /* Empty the keyboard buffer */
766 if(gui_syncyesno_run(&message, NULL, NULL) == YESNO_YES)
768 audio_hard_stop();
769 rolo_load(BOOTDIR "/" BOOTFILE);
773 wrtdate = info.wrtdate;
774 wrttime = info.wrttime;
777 closedir(dir);
779 #endif
780 #endif
782 /* check range, set volume and save settings */
783 void setvol(void)
785 const int min_vol = sound_min(SOUND_VOLUME);
786 const int max_vol = sound_max(SOUND_VOLUME);
787 if (global_settings.volume < min_vol)
788 global_settings.volume = min_vol;
789 if (global_settings.volume > max_vol)
790 global_settings.volume = max_vol;
791 sound_set_volume(global_settings.volume);
792 global_status.last_volume_change = current_tick;
793 settings_save();
796 char* strrsplt(char* str, int c)
798 char* s = strrchr(str, c);
800 if (s != NULL)
802 *s++ = '\0';
804 else
806 s = str;
809 return s;
813 * removes the extension of filename (if it doesn't start with a .)
814 * puts the result in buffer
816 char *strip_extension(char* buffer, int buffer_size, const char *filename)
818 char *dot = strrchr(filename, '.');
819 int len;
821 if (buffer_size <= 0)
823 return NULL;
826 buffer_size--; /* Make room for end nil */
828 if (dot != 0 && filename[0] != '.')
830 len = dot - filename;
831 len = MIN(len, buffer_size);
833 else
835 len = buffer_size;
838 strlcpy(buffer, filename, len + 1);
840 return buffer;
843 #if CONFIG_CODEC == SWCODEC
844 /* Play a standard sound */
845 void system_sound_play(enum system_sound sound)
847 static const struct beep_params
849 int *setting;
850 unsigned short frequency;
851 unsigned short duration;
852 unsigned short amplitude;
853 } beep_params[] =
855 [SOUND_KEYCLICK] =
856 { &global_settings.keyclick,
857 4000, KEYCLICK_DURATION, 2500 },
858 [SOUND_TRACK_SKIP] =
859 { &global_settings.beep,
860 2000, 100, 2500 },
861 [SOUND_TRACK_NO_MORE] =
862 { &global_settings.beep,
863 1000, 100, 1500 },
866 const struct beep_params *params = &beep_params[sound];
868 if (*params->setting)
870 beep_play(params->frequency, params->duration,
871 params->amplitude * *params->setting);
875 /* Produce keyclick based upon button and global settings */
876 void keyclick_click(int button)
878 /* Settings filters */
879 if (global_settings.keyclick &&
880 (global_settings.keyclick_repeats || !(button & BUTTON_REPEAT)))
882 /* Button filters */
883 if (button != BUTTON_NONE && !(button & BUTTON_REL)
884 && !(button & (SYS_EVENT|BUTTON_MULTIMEDIA)) )
886 system_sound_play(SOUND_KEYCLICK);
890 #endif /* CONFIG_CODEC == SWCODEC */
892 #endif /* !defined(__PCTOOL__) */
894 /* Read (up to) a line of text from fd into buffer and return number of bytes
895 * read (which may be larger than the number of bytes stored in buffer). If
896 * an error occurs, -1 is returned (and buffer contains whatever could be
897 * read). A line is terminated by a LF char. Neither LF nor CR chars are
898 * stored in buffer.
900 int read_line(int fd, char* buffer, int buffer_size)
902 int count = 0;
903 int num_read = 0;
905 errno = 0;
907 while (count < buffer_size)
909 unsigned char c;
911 if (1 != read(fd, &c, 1))
912 break;
914 num_read++;
916 if ( c == '\n' )
917 break;
919 if ( c == '\r' )
920 continue;
922 buffer[count++] = c;
925 buffer[MIN(count, buffer_size - 1)] = 0;
927 return errno ? -1 : num_read;
931 char* skip_whitespace(char* const str)
933 char *s = str;
935 while (isspace(*s))
936 s++;
938 return s;
941 /* Format time into buf.
943 * buf - buffer to format to.
944 * buf_size - size of buffer.
945 * t - time to format, in milliseconds.
947 void format_time(char* buf, int buf_size, long t)
949 int const time = abs(t / 1000);
950 int const hours = time / 3600;
951 int const minutes = time / 60 - hours * 60;
952 int const seconds = time % 60;
953 const char * const sign = &"-"[t < 0 ? 0 : 1];
955 if ( hours == 0 )
957 snprintf(buf, buf_size, "%s%d:%02d", sign, minutes, seconds);
959 else
961 snprintf(buf, buf_size, "%s%d:%02d:%02d", sign, hours, minutes,
962 seconds);
967 /** Open a UTF-8 file and set file descriptor to first byte after BOM.
968 * If no BOM is present this behaves like open().
969 * If the file is opened for writing and O_TRUNC is set, write a BOM to
970 * the opened file and leave the file pointer set after the BOM.
972 #define BOM "\xef\xbb\xbf"
973 #define BOM_SIZE 3
975 int open_utf8(const char* pathname, int flags)
977 int fd;
978 unsigned char bom[BOM_SIZE];
980 fd = open(pathname, flags, 0666);
981 if(fd < 0)
982 return fd;
984 if(flags & (O_TRUNC | O_WRONLY))
986 write(fd, BOM, BOM_SIZE);
988 else
990 read(fd, bom, BOM_SIZE);
991 /* check for BOM */
992 if(memcmp(bom, BOM, BOM_SIZE))
993 lseek(fd, 0, SEEK_SET);
995 return fd;
999 #ifdef HAVE_LCD_COLOR
1001 * Helper function to convert a string of 6 hex digits to a native colour
1004 static int hex2dec(int c)
1006 return (((c) >= '0' && ((c) <= '9')) ? (c) - '0' :
1007 (toupper(c)) - 'A' + 10);
1010 int hex_to_rgb(const char* hex, int* color)
1012 int red, green, blue;
1013 int i = 0;
1015 while ((i < 6) && (isxdigit(hex[i])))
1016 i++;
1018 if (i < 6)
1019 return -1;
1021 red = (hex2dec(hex[0]) << 4) | hex2dec(hex[1]);
1022 green = (hex2dec(hex[2]) << 4) | hex2dec(hex[3]);
1023 blue = (hex2dec(hex[4]) << 4) | hex2dec(hex[5]);
1025 *color = LCD_RGBPACK(red,green,blue);
1027 return 0;
1029 #endif /* HAVE_LCD_COLOR */
1031 #ifdef HAVE_LCD_BITMAP
1032 /* '0'-'3' are ASCII 0x30 to 0x33 */
1033 #define is0123(x) (((x) & 0xfc) == 0x30)
1034 #if !defined(__PCTOOL__) || defined(CHECKWPS)
1035 bool parse_color(enum screen_type screen, char *text, int *value)
1037 (void)text; (void)value; /* silence warnings on mono bitmap */
1038 (void)screen;
1040 #ifdef HAVE_LCD_COLOR
1041 if (screens[screen].depth > 2)
1043 if (hex_to_rgb(text, value) < 0)
1044 return false;
1045 else
1046 return true;
1048 #endif
1050 #if LCD_DEPTH == 2 || (defined(HAVE_REMOTE_LCD) && LCD_REMOTE_DEPTH == 2)
1051 if (screens[screen].depth == 2)
1053 if (text[1] != '\0' || !is0123(*text))
1054 return false;
1055 *value = *text - '0';
1056 return true;
1058 #endif
1059 return false;
1061 #endif /* !defined(__PCTOOL__) || defined(CHECKWPS) */
1063 /* only used in USB HID and set_time screen */
1064 #if defined(USB_ENABLE_HID) || (CONFIG_RTC != 0)
1065 int clamp_value_wrap(int value, int max, int min)
1067 if (value > max)
1068 return min;
1069 if (value < min)
1070 return max;
1071 return value;
1073 #endif
1074 #endif
1075 #define MAX_ACTIVITY_DEPTH 12
1076 static enum current_activity
1077 current_activity[MAX_ACTIVITY_DEPTH] = {ACTIVITY_UNKNOWN};
1078 static int current_activity_top = 0;
1079 void push_current_activity(enum current_activity screen)
1081 current_activity[current_activity_top++] = screen;
1083 void pop_current_activity(void)
1085 current_activity_top--;
1087 enum current_activity get_current_activity(void)
1089 return current_activity[current_activity_top?current_activity_top-1:0];