Remove hosted_get_volume(), as event data is available in button_get_data().
[maemo-rb.git] / apps / misc.c
blobb57e84efb31fd5411618f15a07b9d76c67334a70
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 "system.h"
38 #include "timefuncs.h"
39 #include "screens.h"
40 #include "usb_screen.h"
41 #include "talk.h"
42 #include "audio.h"
43 #include "mp3_playback.h"
44 #include "settings.h"
45 #include "storage.h"
46 #include "ata_idle_notify.h"
47 #include "kernel.h"
48 #include "power.h"
49 #include "powermgmt.h"
50 #include "backlight.h"
51 #include "version.h"
52 #include "font.h"
53 #include "splash.h"
54 #include "tagcache.h"
55 #include "scrobbler.h"
56 #include "sound.h"
57 #include "playlist.h"
58 #include "yesno.h"
59 #include "viewport.h"
61 #include "debug.h"
63 #if CONFIG_TUNER
64 #include "radio.h"
65 #endif
67 #ifdef IPOD_ACCESSORY_PROTOCOL
68 #include "iap.h"
69 #endif
71 #if (CONFIG_STORAGE & STORAGE_MMC)
72 #include "ata_mmc.h"
73 #endif
74 #include "tree.h"
75 #include "eeprom_settings.h"
76 #if defined(HAVE_RECORDING) && !defined(__PCTOOL__)
77 #include "recording.h"
78 #endif
79 #if defined(HAVE_LCD_BITMAP) && !defined(__PCTOOL__)
80 #include "bmp.h"
81 #include "icons.h"
82 #endif /* End HAVE_LCD_BITMAP */
83 #include "bookmark.h"
84 #include "wps.h"
85 #include "playback.h"
86 #if CONFIG_CODEC == SWCODEC
87 #include "voice_thread.h"
88 #endif
90 #ifdef BOOTFILE
91 #if !defined(USB_NONE) && !defined(USB_HANDLED_BY_OF) \
92 || defined(HAVE_HOTSWAP_STORAGE_AS_MAIN)
93 #include "rolo.h"
94 #endif
95 #endif
97 /* units used with output_dyn_value */
98 const unsigned char * const byte_units[] =
100 ID2P(LANG_BYTE),
101 ID2P(LANG_KILOBYTE),
102 ID2P(LANG_MEGABYTE),
103 ID2P(LANG_GIGABYTE)
106 const unsigned char * const * const kbyte_units = &byte_units[1];
108 /* Format a large-range value for output, using the appropriate unit so that
109 * the displayed value is in the range 1 <= display < 1000 (1024 for "binary"
110 * units) if possible, and 3 significant digits are shown. If a buffer is
111 * given, the result is snprintf()'d into that buffer, otherwise the result is
112 * voiced.*/
113 char *output_dyn_value(char *buf, int buf_size, int value,
114 const unsigned char * const *units, bool bin_scale)
116 int scale = bin_scale ? 1024 : 1000;
117 int fraction = 0;
118 int unit_no = 0;
119 char tbuf[5];
121 while (value >= scale)
123 fraction = value % scale;
124 value /= scale;
125 unit_no++;
127 if (bin_scale)
128 fraction = fraction * 1000 / 1024;
130 if (value >= 100 || !unit_no)
131 tbuf[0] = '\0';
132 else if (value >= 10)
133 snprintf(tbuf, sizeof(tbuf), "%01d", fraction / 100);
134 else
135 snprintf(tbuf, sizeof(tbuf), "%02d", fraction / 10);
137 if (buf)
139 if (*tbuf)
140 snprintf(buf, buf_size, "%d%s%s%s", value, str(LANG_POINT),
141 tbuf, P2STR(units[unit_no]));
142 else
143 snprintf(buf, buf_size, "%d%s", value, P2STR(units[unit_no]));
145 else
147 talk_fractional(tbuf, value, P2ID(units[unit_no]));
149 return buf;
152 /* Ask the user if they really want to erase the current dynamic playlist
153 * returns true if the playlist should be replaced */
154 bool warn_on_pl_erase(void)
156 if (global_settings.warnon_erase_dynplaylist &&
157 !global_settings.party_mode &&
158 playlist_modified(NULL))
160 static const char *lines[] =
161 {ID2P(LANG_WARN_ERASEDYNPLAYLIST_PROMPT)};
162 static const struct text_message message={lines, 1};
164 return (gui_syncyesno_run(&message, NULL, NULL) == YESNO_YES);
166 else
167 return true;
171 /* Performance optimized version of the read_line() (see below) function. */
172 int fast_readline(int fd, char *buf, int buf_size, void *parameters,
173 int (*callback)(int n, char *buf, void *parameters))
175 char *p, *next;
176 int rc, pos = 0;
177 int count = 0;
179 while ( 1 )
181 next = NULL;
183 rc = read(fd, &buf[pos], buf_size - pos - 1);
184 if (rc >= 0)
185 buf[pos+rc] = '\0';
187 if ( (p = strchr(buf, '\n')) != NULL)
189 *p = '\0';
190 next = ++p;
193 rc = callback(count, buf, parameters);
194 if (rc < 0)
195 return rc;
197 count++;
198 if (next)
200 pos = buf_size - ((long)next - (long)buf) - 1;
201 memmove(buf, next, pos);
203 else
204 break ;
207 return 0;
210 /* parse a line from a configuration file. the line format is:
212 name: value
214 Any whitespace before setting name or value (after ':') is ignored.
215 A # as first non-whitespace character discards the whole line.
216 Function sets pointers to null-terminated setting name and value.
217 Returns false if no valid config entry was found.
220 bool settings_parseline(char* line, char** name, char** value)
222 char* ptr;
224 line = skip_whitespace(line);
226 if ( *line == '#' )
227 return false;
229 ptr = strchr(line, ':');
230 if ( !ptr )
231 return false;
233 *name = line;
234 *ptr = 0;
235 ptr++;
236 ptr = skip_whitespace(ptr);
237 *value = ptr;
238 return true;
241 static void system_flush(void)
243 scrobbler_shutdown();
244 playlist_shutdown();
245 tree_flush();
246 call_storage_idle_notifys(true); /*doesnt work on usb and shutdown from ata thread */
249 static void system_restore(void)
251 tree_restore();
252 scrobbler_init();
255 static bool clean_shutdown(void (*callback)(void *), void *parameter)
257 long msg_id = -1;
258 int i;
260 scrobbler_poweroff();
262 #if CONFIG_CHARGING && !defined(HAVE_POWEROFF_WHILE_CHARGING)
263 if(!charger_inserted())
264 #endif
266 bool batt_safe = battery_level_safe();
267 #if CONFIG_CODEC != SWCODEC || defined(HAVE_RECORDING)
268 int audio_stat = audio_status();
269 #endif
271 FOR_NB_SCREENS(i)
273 screens[i].clear_display();
274 screens[i].update();
277 if (batt_safe)
279 #ifdef HAVE_TAGCACHE
280 if (!tagcache_prepare_shutdown())
282 cancel_shutdown();
283 splash(HZ, ID2P(LANG_TAGCACHE_BUSY));
284 return false;
286 #endif
287 if (battery_level() > 10)
288 splash(0, str(LANG_SHUTTINGDOWN));
289 else
291 msg_id = LANG_WARNING_BATTERY_LOW;
292 splashf(0, "%s %s", str(LANG_WARNING_BATTERY_LOW),
293 str(LANG_SHUTTINGDOWN));
296 else
298 msg_id = LANG_WARNING_BATTERY_EMPTY;
299 splashf(0, "%s %s", str(LANG_WARNING_BATTERY_EMPTY),
300 str(LANG_SHUTTINGDOWN));
302 #if CONFIG_CODEC != SWCODEC
303 if (global_settings.fade_on_stop
304 && (audio_stat & AUDIO_STATUS_PLAY))
306 fade(false, false);
308 #endif
310 if (batt_safe) /* do not save on critical battery */
312 #if defined(HAVE_RECORDING) && CONFIG_CODEC == SWCODEC
313 if (audio_stat & AUDIO_STATUS_RECORD)
315 rec_command(RECORDING_CMD_STOP);
316 /* wait for stop to complete */
317 while (audio_status() & AUDIO_STATUS_RECORD)
318 sleep(1);
320 #endif
321 bookmark_autobookmark(false);
323 /* audio_stop_recording == audio_stop for HWCODEC */
324 audio_stop();
326 if (callback != NULL)
327 callback(parameter);
329 #if CONFIG_CODEC != SWCODEC
330 /* wait for audio_stop or audio_stop_recording to complete */
331 while (audio_status())
332 sleep(1);
333 #endif
335 #if defined(HAVE_RECORDING) && CONFIG_CODEC == SWCODEC
336 audio_close_recording();
337 #endif
339 if(global_settings.talk_menu)
341 bool enqueue = false;
342 if(msg_id != -1)
344 talk_id(msg_id, enqueue);
345 enqueue = true;
347 talk_id(LANG_SHUTTINGDOWN, enqueue);
348 #if CONFIG_CODEC == SWCODEC
349 voice_wait();
350 #endif
353 system_flush();
354 #ifdef HAVE_EEPROM_SETTINGS
355 if (firmware_settings.initialized)
357 firmware_settings.disk_clean = true;
358 firmware_settings.bl_version = 0;
359 eeprom_settings_store();
361 #endif
363 #ifdef HAVE_DIRCACHE
364 else
365 dircache_disable();
366 #endif
368 shutdown_hw();
370 return false;
373 bool list_stop_handler(void)
375 bool ret = false;
377 #if CONFIG_TUNER
378 radio_stop();
379 #endif
381 /* Stop the music if it is playing */
382 if(audio_status())
384 if (!global_settings.party_mode)
386 #if CONFIG_CODEC != SWCODEC
387 if (global_settings.fade_on_stop)
388 fade(false, false);
389 #endif
390 bookmark_autobookmark(true);
391 audio_stop();
392 ret = true; /* bookmarking can make a refresh necessary */
395 #if CONFIG_CHARGING
396 #if (CONFIG_KEYPAD == RECORDER_PAD) && !defined(HAVE_SW_POWEROFF)
397 else
399 if (charger_inserted())
400 charging_splash();
401 else
402 shutdown_screen(); /* won't return if shutdown actually happens */
404 ret = true; /* screen is dirty, caller needs to refresh */
406 #endif
407 #ifndef HAVE_POWEROFF_WHILE_CHARGING
409 static long last_off = 0;
411 if (TIME_BEFORE(current_tick, last_off + HZ/2))
413 if (charger_inserted())
415 charging_splash();
416 ret = true; /* screen is dirty, caller needs to refresh */
419 last_off = current_tick;
421 #endif
422 #endif /* CONFIG_CHARGING */
423 return ret;
426 #if CONFIG_CHARGING
427 static bool waiting_to_resume_play = false;
428 static long play_resume_tick;
430 static void car_adapter_mode_processing(bool inserted)
432 if (global_settings.car_adapter_mode)
434 if(inserted)
437 * Just got plugged in, delay & resume if we were playing
439 if (audio_status() & AUDIO_STATUS_PAUSE)
441 /* delay resume a bit while the engine is cranking */
442 play_resume_tick = current_tick + HZ*5;
443 waiting_to_resume_play = true;
446 else
449 * Just got unplugged, pause if playing
451 if ((audio_status() & AUDIO_STATUS_PLAY) &&
452 !(audio_status() & AUDIO_STATUS_PAUSE))
454 pause_action(true, true);
456 waiting_to_resume_play = false;
461 static void car_adapter_tick(void)
463 if (waiting_to_resume_play)
465 if (TIME_AFTER(current_tick, play_resume_tick))
467 if (audio_status() & AUDIO_STATUS_PAUSE)
469 queue_broadcast(SYS_CAR_ADAPTER_RESUME, 0);
471 waiting_to_resume_play = false;
476 void car_adapter_mode_init(void)
478 tick_add_task(car_adapter_tick);
480 #endif
482 #ifdef HAVE_HEADPHONE_DETECTION
483 static void unplug_change(bool inserted)
485 static bool headphone_caused_pause = false;
487 if (global_settings.unplug_mode)
489 int audio_stat = audio_status();
490 if (inserted)
492 backlight_on();
493 if ((audio_stat & AUDIO_STATUS_PLAY) &&
494 headphone_caused_pause &&
495 global_settings.unplug_mode > 1 )
496 unpause_action(true, true);
497 headphone_caused_pause = false;
498 } else {
499 if ((audio_stat & AUDIO_STATUS_PLAY) &&
500 !(audio_stat & AUDIO_STATUS_PAUSE))
502 headphone_caused_pause = true;
503 pause_action(false, false);
508 #endif
510 long default_event_handler_ex(long event, void (*callback)(void *), void *parameter)
512 #if CONFIG_PLATFORM & (PLATFORM_ANDROID|PLATFORM_MAEMO)
513 static bool resume = false;
514 #endif
516 switch(event)
518 case SYS_BATTERY_UPDATE:
519 if(global_settings.talk_battery_level)
521 talk_ids(true, VOICE_PAUSE, VOICE_PAUSE,
522 LANG_BATTERY_TIME,
523 TALK_ID(battery_level(), UNIT_PERCENT),
524 VOICE_PAUSE);
525 talk_force_enqueue_next();
527 break;
528 case SYS_USB_CONNECTED:
529 if (callback != NULL)
530 callback(parameter);
531 #if (CONFIG_STORAGE & STORAGE_MMC) && (defined(ARCHOS_ONDIOSP) || defined(ARCHOS_ONDIOFM))
532 if (!mmc_touched() ||
533 (mmc_remove_request() == SYS_HOTSWAP_EXTRACTED))
534 #endif
536 system_flush();
537 #ifdef BOOTFILE
538 #if !defined(USB_NONE) && !defined(USB_HANDLED_BY_OF)
539 check_bootfile(false); /* gets initial size */
540 #endif
541 #endif
542 gui_usb_screen_run(false);
543 #ifdef BOOTFILE
544 #if !defined(USB_NONE) && !defined(USB_HANDLED_BY_OF)
545 check_bootfile(true);
546 #endif
547 #endif
548 system_restore();
550 return SYS_USB_CONNECTED;
552 case SYS_POWEROFF:
553 if (!clean_shutdown(callback, parameter))
554 return SYS_POWEROFF;
555 break;
556 #if CONFIG_CHARGING
557 case SYS_CHARGER_CONNECTED:
558 car_adapter_mode_processing(true);
559 return SYS_CHARGER_CONNECTED;
561 case SYS_CHARGER_DISCONNECTED:
562 car_adapter_mode_processing(false);
563 /*reset rockbox battery runtime*/
564 global_status.runtime = 0;
565 return SYS_CHARGER_DISCONNECTED;
567 case SYS_CAR_ADAPTER_RESUME:
568 unpause_action(true, true);
569 return SYS_CAR_ADAPTER_RESUME;
570 #endif
571 #ifdef HAVE_HOTSWAP_STORAGE_AS_MAIN
572 case SYS_FS_CHANGED:
574 /* simple sanity: assume rockbox is on the first hotswappable
575 * driver, abort out if that one isn't inserted */
576 int i;
577 for (i = 0; i < NUM_DRIVES; i++)
579 if (storage_removable(i) && !storage_present(i))
580 return SYS_FS_CHANGED;
582 system_flush();
583 check_bootfile(true); /* state gotten in main.c:init() */
584 system_restore();
586 return SYS_FS_CHANGED;
587 #endif
588 #ifdef HAVE_HEADPHONE_DETECTION
589 case SYS_PHONE_PLUGGED:
590 unplug_change(true);
591 return SYS_PHONE_PLUGGED;
593 case SYS_PHONE_UNPLUGGED:
594 unplug_change(false);
595 return SYS_PHONE_UNPLUGGED;
596 #endif
597 #ifdef IPOD_ACCESSORY_PROTOCOL
598 case SYS_IAP_PERIODIC:
599 iap_periodic();
600 return SYS_IAP_PERIODIC;
601 case SYS_IAP_HANDLEPKT:
602 iap_handlepkt();
603 return SYS_IAP_HANDLEPKT;
604 #endif
605 #if CONFIG_PLATFORM & (PLATFORM_ANDROID|PLATFORM_MAEMO)
606 /* stop playback if we receive a call */
607 case SYS_CALL_INCOMING:
608 resume = audio_status() == AUDIO_STATUS_PLAY;
609 list_stop_handler();
610 return SYS_CALL_INCOMING;
611 /* resume playback if needed */
612 case SYS_CALL_HUNG_UP:
613 if (resume && playlist_resume() != -1)
615 playlist_start(global_status.resume_index,
616 global_status.resume_offset);
618 resume = false;
619 return SYS_CALL_HUNG_UP;
620 #endif
621 #if (CONFIG_PLATFORM & PLATFORM_HOSTED) && defined(PLATFORM_HAS_VOLUME_CHANGE)
622 case SYS_VOLUME_CHANGED:
624 static bool firstvolume = true;
625 /* kludge: since this events go to the button_queue,
626 * event data is available in the last button data */
627 int volume = button_get_data();
628 DEBUGF("SYS_VOLUME_CHANGED: %d\n", volume);
629 if (global_settings.volume != volume) {
630 global_settings.volume = volume;
631 if (firstvolume) {
632 setvol();
633 firstvolume = false;
636 return 0;
638 #endif
639 #ifdef HAVE_MULTIMEDIA_KEYS
640 /* multimedia keys on keyboards, headsets */
641 case BUTTON_MULTIMEDIA_PLAYPAUSE:
643 int status = audio_status();
644 if (status & AUDIO_STATUS_PLAY)
646 if (status & AUDIO_STATUS_PAUSE)
647 unpause_action(true, true);
648 else
649 pause_action(true, true);
651 else
652 if (playlist_resume() != -1)
654 playlist_start(global_status.resume_index,
655 global_status.resume_offset);
657 return event;
659 case BUTTON_MULTIMEDIA_NEXT:
660 audio_next();
661 return event;
662 case BUTTON_MULTIMEDIA_PREV:
663 audio_prev();
664 return event;
665 case BUTTON_MULTIMEDIA_STOP:
666 list_stop_handler();
667 return event;
668 case BUTTON_MULTIMEDIA_REW:
669 case BUTTON_MULTIMEDIA_FFWD:
670 /* not supported yet, needs to be done in the WPS */
671 return 0;
672 #endif
674 return 0;
677 long default_event_handler(long event)
679 return default_event_handler_ex(event, NULL, NULL);
682 int show_logo( void )
684 #ifdef HAVE_LCD_BITMAP
685 char version[32];
686 int font_h, font_w;
688 snprintf(version, sizeof(version), "Ver. %s", rbversion);
690 lcd_clear_display();
691 #if defined(SANSA_CLIP) || defined(SANSA_CLIPV2) || defined(SANSA_CLIPPLUS)
692 /* display the logo in the blue area of the screen */
693 lcd_setfont(FONT_SYSFIXED);
694 lcd_getstringsize((unsigned char *)"A", &font_w, &font_h);
695 lcd_putsxy((LCD_WIDTH/2) - ((strlen(version)*font_w)/2),
696 0, (unsigned char *)version);
697 lcd_bitmap(rockboxlogo, (LCD_WIDTH - BMPWIDTH_rockboxlogo) / 2, 16,
698 BMPWIDTH_rockboxlogo, BMPHEIGHT_rockboxlogo);
699 #else
700 lcd_bitmap(rockboxlogo, (LCD_WIDTH - BMPWIDTH_rockboxlogo) / 2, 10,
701 BMPWIDTH_rockboxlogo, BMPHEIGHT_rockboxlogo);
702 lcd_setfont(FONT_SYSFIXED);
703 lcd_getstringsize((unsigned char *)"A", &font_w, &font_h);
704 lcd_putsxy((LCD_WIDTH/2) - ((strlen(version)*font_w)/2),
705 LCD_HEIGHT-font_h, (unsigned char *)version);
706 #endif
707 lcd_setfont(FONT_UI);
709 #else
710 char *rockbox = " ROCKbox!";
712 lcd_clear_display();
713 lcd_double_height(true);
714 lcd_puts(0, 0, rockbox);
715 lcd_puts_scroll(0, 1, rbversion);
716 #endif
717 lcd_update();
719 #ifdef HAVE_REMOTE_LCD
720 lcd_remote_clear_display();
721 lcd_remote_bitmap(remote_rockboxlogo, 0, 10, BMPWIDTH_remote_rockboxlogo,
722 BMPHEIGHT_remote_rockboxlogo);
723 lcd_remote_setfont(FONT_SYSFIXED);
724 lcd_remote_getstringsize((unsigned char *)"A", &font_w, &font_h);
725 lcd_remote_putsxy((LCD_REMOTE_WIDTH/2) - ((strlen(version)*font_w)/2),
726 LCD_REMOTE_HEIGHT-font_h, (unsigned char *)version);
727 lcd_remote_setfont(FONT_UI);
728 lcd_remote_update();
729 #endif
731 return 0;
734 #ifdef BOOTFILE
735 #if !defined(USB_NONE) && !defined(USB_HANDLED_BY_OF) || defined(HAVE_HOTSWAP_STORAGE_AS_MAIN)
737 memorize/compare details about the BOOTFILE
738 we don't use dircache because it may not be up to date after
739 USB disconnect (scanning in the background)
741 void check_bootfile(bool do_rolo)
743 static unsigned short wrtdate = 0;
744 static unsigned short wrttime = 0;
745 DIR* dir = NULL;
746 struct dirent* entry = NULL;
748 /* 1. open BOOTDIR and find the BOOTFILE dir entry */
749 dir = opendir(BOOTDIR);
751 if(!dir) return; /* do we want an error splash? */
753 /* loop all files in BOOTDIR */
754 while(0 != (entry = readdir(dir)))
756 if(!strcasecmp(entry->d_name, BOOTFILE))
758 struct dirinfo info = dir_get_info(dir, entry);
759 /* found the bootfile */
760 if(wrtdate && do_rolo)
762 if((info.wrtdate != wrtdate) ||
763 (info.wrttime != wrttime))
765 static const char *lines[] = { ID2P(LANG_BOOT_CHANGED),
766 ID2P(LANG_REBOOT_NOW) };
767 static const struct text_message message={ lines, 2 };
768 button_clear_queue(); /* Empty the keyboard buffer */
769 if(gui_syncyesno_run(&message, NULL, NULL) == YESNO_YES)
770 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];