Merge branch 'master' into pandora-port
[maemo-rb.git] / apps / misc.c
blobfa34c21f4e0e1ac5e15ca58198710d83a2042ae3
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 #if CONFIG_TUNER
62 #include "radio.h"
63 #endif
65 #ifdef IPOD_ACCESSORY_PROTOCOL
66 #include "iap.h"
67 #endif
69 #if (CONFIG_STORAGE & STORAGE_MMC)
70 #include "ata_mmc.h"
71 #endif
72 #include "tree.h"
73 #include "eeprom_settings.h"
74 #if defined(HAVE_RECORDING) && !defined(__PCTOOL__)
75 #include "recording.h"
76 #endif
77 #if defined(HAVE_LCD_BITMAP) && !defined(__PCTOOL__)
78 #include "bmp.h"
79 #include "icons.h"
80 #endif /* End HAVE_LCD_BITMAP */
81 #include "bookmark.h"
82 #include "wps.h"
83 #include "playback.h"
85 #ifdef BOOTFILE
86 #if !defined(USB_NONE) && !defined(USB_HANDLED_BY_OF) \
87 || defined(HAVE_HOTSWAP_STORAGE_AS_MAIN)
88 #include "rolo.h"
89 #endif
90 #endif
92 /* units used with output_dyn_value */
93 const unsigned char * const byte_units[] =
95 ID2P(LANG_BYTE),
96 ID2P(LANG_KILOBYTE),
97 ID2P(LANG_MEGABYTE),
98 ID2P(LANG_GIGABYTE)
101 const unsigned char * const * const kbyte_units = &byte_units[1];
103 /* Format a large-range value for output, using the appropriate unit so that
104 * the displayed value is in the range 1 <= display < 1000 (1024 for "binary"
105 * units) if possible, and 3 significant digits are shown. If a buffer is
106 * given, the result is snprintf()'d into that buffer, otherwise the result is
107 * voiced.*/
108 char *output_dyn_value(char *buf, int buf_size, int value,
109 const unsigned char * const *units, bool bin_scale)
111 int scale = bin_scale ? 1024 : 1000;
112 int fraction = 0;
113 int unit_no = 0;
114 char tbuf[5];
116 while (value >= scale)
118 fraction = value % scale;
119 value /= scale;
120 unit_no++;
122 if (bin_scale)
123 fraction = fraction * 1000 / 1024;
125 if (value >= 100 || !unit_no)
126 tbuf[0] = '\0';
127 else if (value >= 10)
128 snprintf(tbuf, sizeof(tbuf), "%01d", fraction / 100);
129 else
130 snprintf(tbuf, sizeof(tbuf), "%02d", fraction / 10);
132 if (buf)
134 if (*tbuf)
135 snprintf(buf, buf_size, "%d%s%s%s", value, str(LANG_POINT),
136 tbuf, P2STR(units[unit_no]));
137 else
138 snprintf(buf, buf_size, "%d%s", value, P2STR(units[unit_no]));
140 else
142 talk_fractional(tbuf, value, P2ID(units[unit_no]));
144 return buf;
147 /* Ask the user if they really want to erase the current dynamic playlist
148 * returns true if the playlist should be replaced */
149 bool warn_on_pl_erase(void)
151 if (global_settings.warnon_erase_dynplaylist &&
152 !global_settings.party_mode &&
153 playlist_modified(NULL))
155 static const char *lines[] =
156 {ID2P(LANG_WARN_ERASEDYNPLAYLIST_PROMPT)};
157 static const struct text_message message={lines, 1};
159 return (gui_syncyesno_run(&message, NULL, NULL) == YESNO_YES);
161 else
162 return true;
166 /* Performance optimized version of the read_line() (see below) function. */
167 int fast_readline(int fd, char *buf, int buf_size, void *parameters,
168 int (*callback)(int n, const char *buf, void *parameters))
170 char *p, *next;
171 int rc, pos = 0;
172 int count = 0;
174 while ( 1 )
176 next = NULL;
178 rc = read(fd, &buf[pos], buf_size - pos - 1);
179 if (rc >= 0)
180 buf[pos+rc] = '\0';
182 if ( (p = strchr(buf, '\r')) != NULL)
184 *p = '\0';
185 next = ++p;
187 else
188 p = buf;
190 if ( (p = strchr(p, '\n')) != NULL)
192 *p = '\0';
193 next = ++p;
196 rc = callback(count, buf, parameters);
197 if (rc < 0)
198 return rc;
200 count++;
201 if (next)
203 pos = buf_size - ((long)next - (long)buf) - 1;
204 memmove(buf, next, pos);
206 else
207 break ;
210 return 0;
213 /* parse a line from a configuration file. the line format is:
215 name: value
217 Any whitespace before setting name or value (after ':') is ignored.
218 A # as first non-whitespace character discards the whole line.
219 Function sets pointers to null-terminated setting name and value.
220 Returns false if no valid config entry was found.
223 bool settings_parseline(char* line, char** name, char** value)
225 char* ptr;
227 line = skip_whitespace(line);
229 if ( *line == '#' )
230 return false;
232 ptr = strchr(line, ':');
233 if ( !ptr )
234 return false;
236 *name = line;
237 *ptr = 0;
238 ptr++;
239 ptr = skip_whitespace(ptr);
240 *value = ptr;
241 return true;
244 static void system_flush(void)
246 scrobbler_shutdown();
247 playlist_shutdown();
248 tree_flush();
249 call_storage_idle_notifys(true); /*doesnt work on usb and shutdown from ata thread */
252 static void system_restore(void)
254 tree_restore();
255 scrobbler_init();
258 static bool clean_shutdown(void (*callback)(void *), void *parameter)
260 #if (CONFIG_PLATFORM & PLATFORM_ANDROID)
261 (void)callback;
262 (void)parameter;
263 bookmark_autobookmark(false);
264 call_storage_idle_notifys(true);
265 #else
266 long msg_id = -1;
267 int i;
269 scrobbler_poweroff();
271 #if CONFIG_CHARGING && !defined(HAVE_POWEROFF_WHILE_CHARGING)
272 if(!charger_inserted())
273 #endif
275 bool batt_safe = battery_level_safe();
276 int audio_stat = audio_status();
278 FOR_NB_SCREENS(i)
280 screens[i].clear_display();
281 screens[i].update();
284 if (batt_safe)
286 #ifdef HAVE_TAGCACHE
287 if (!tagcache_prepare_shutdown())
289 cancel_shutdown();
290 splash(HZ, ID2P(LANG_TAGCACHE_BUSY));
291 return false;
293 #endif
294 if (battery_level() > 10)
295 splash(0, str(LANG_SHUTTINGDOWN));
296 else
298 msg_id = LANG_WARNING_BATTERY_LOW;
299 splashf(0, "%s %s", str(LANG_WARNING_BATTERY_LOW),
300 str(LANG_SHUTTINGDOWN));
303 else
305 msg_id = LANG_WARNING_BATTERY_EMPTY;
306 splashf(0, "%s %s", str(LANG_WARNING_BATTERY_EMPTY),
307 str(LANG_SHUTTINGDOWN));
310 if (global_settings.fade_on_stop
311 && (audio_stat & AUDIO_STATUS_PLAY))
313 fade(false, false);
316 if (batt_safe) /* do not save on critical battery */
318 #if defined(HAVE_RECORDING) && CONFIG_CODEC == SWCODEC
319 if (audio_stat & AUDIO_STATUS_RECORD)
321 rec_command(RECORDING_CMD_STOP);
322 /* wait for stop to complete */
323 while (audio_status() & AUDIO_STATUS_RECORD)
324 sleep(1);
326 #endif
327 bookmark_autobookmark(false);
329 /* audio_stop_recording == audio_stop for HWCODEC */
330 audio_stop();
332 if (callback != NULL)
333 callback(parameter);
335 #if CONFIG_CODEC != SWCODEC
336 /* wait for audio_stop or audio_stop_recording to complete */
337 while (audio_status())
338 sleep(1);
339 #endif
341 #if defined(HAVE_RECORDING) && CONFIG_CODEC == SWCODEC
342 audio_close_recording();
343 #endif
345 if(global_settings.talk_menu)
347 bool enqueue = false;
348 if(msg_id != -1)
350 talk_id(msg_id, enqueue);
351 enqueue = true;
353 talk_id(LANG_SHUTTINGDOWN, enqueue);
354 #if CONFIG_CODEC == SWCODEC
355 voice_wait();
356 #endif
359 system_flush();
360 #ifdef HAVE_EEPROM_SETTINGS
361 if (firmware_settings.initialized)
363 firmware_settings.disk_clean = true;
364 firmware_settings.bl_version = 0;
365 eeprom_settings_store();
367 #endif
369 #ifdef HAVE_DIRCACHE
370 else
371 dircache_disable();
372 #endif
374 shutdown_hw();
376 #endif
377 return false;
380 bool list_stop_handler(void)
382 bool ret = false;
384 #if CONFIG_TUNER
385 radio_stop();
386 #endif
388 /* Stop the music if it is playing */
389 if(audio_status())
391 if (!global_settings.party_mode)
393 if (global_settings.fade_on_stop)
394 fade(false, false);
395 bookmark_autobookmark(true);
396 audio_stop();
397 ret = true; /* bookmarking can make a refresh necessary */
400 #if CONFIG_CHARGING
401 #if (CONFIG_KEYPAD == RECORDER_PAD) && !defined(HAVE_SW_POWEROFF)
402 else
404 if (charger_inserted())
405 charging_splash();
406 else
407 shutdown_screen(); /* won't return if shutdown actually happens */
409 ret = true; /* screen is dirty, caller needs to refresh */
411 #endif
412 #ifndef HAVE_POWEROFF_WHILE_CHARGING
414 static long last_off = 0;
416 if (TIME_BEFORE(current_tick, last_off + HZ/2))
418 if (charger_inserted())
420 charging_splash();
421 ret = true; /* screen is dirty, caller needs to refresh */
424 last_off = current_tick;
426 #endif
427 #endif /* CONFIG_CHARGING */
428 return ret;
431 #if CONFIG_CHARGING
432 static bool waiting_to_resume_play = false;
433 static long play_resume_tick;
435 static void car_adapter_mode_processing(bool inserted)
437 if (global_settings.car_adapter_mode)
439 if(inserted)
442 * Just got plugged in, delay & resume if we were playing
444 if (audio_status() & AUDIO_STATUS_PAUSE)
446 /* delay resume a bit while the engine is cranking */
447 play_resume_tick = current_tick + HZ*5;
448 waiting_to_resume_play = true;
451 else
454 * Just got unplugged, pause if playing
456 if ((audio_status() & AUDIO_STATUS_PLAY) &&
457 !(audio_status() & AUDIO_STATUS_PAUSE))
459 if (global_settings.fade_on_stop)
460 fade(false, false);
461 else
462 audio_pause();
464 waiting_to_resume_play = false;
469 static void car_adapter_tick(void)
471 if (waiting_to_resume_play)
473 if (TIME_AFTER(current_tick, play_resume_tick))
475 if (audio_status() & AUDIO_STATUS_PAUSE)
477 queue_broadcast(SYS_CAR_ADAPTER_RESUME, 0);
479 waiting_to_resume_play = false;
484 void car_adapter_mode_init(void)
486 tick_add_task(car_adapter_tick);
488 #endif
490 #ifdef HAVE_HEADPHONE_DETECTION
491 static void unplug_change(bool inserted)
493 static bool headphone_caused_pause = false;
495 if (global_settings.unplug_mode)
497 int audio_stat = audio_status();
498 if (inserted)
500 if ((audio_stat & AUDIO_STATUS_PLAY) &&
501 headphone_caused_pause &&
502 global_settings.unplug_mode > 1 )
503 audio_resume();
504 backlight_on();
505 headphone_caused_pause = false;
506 } else {
507 if ((audio_stat & AUDIO_STATUS_PLAY) &&
508 !(audio_stat & AUDIO_STATUS_PAUSE))
510 headphone_caused_pause = true;
511 audio_pause();
513 if (global_settings.unplug_rw)
515 if (audio_current_track()->elapsed >
516 (unsigned long)(global_settings.unplug_rw*1000))
517 audio_ff_rewind(audio_current_track()->elapsed -
518 (global_settings.unplug_rw*1000));
519 else
520 audio_ff_rewind(0);
526 #endif
528 long default_event_handler_ex(long event, void (*callback)(void *), void *parameter)
530 #if CONFIG_PLATFORM & (PLATFORM_ANDROID|PLATFORM_MAEMO)
531 static bool resume = false;
532 #endif
534 switch(event)
536 case SYS_BATTERY_UPDATE:
537 if(global_settings.talk_battery_level)
539 talk_ids(true, VOICE_PAUSE, VOICE_PAUSE,
540 LANG_BATTERY_TIME,
541 TALK_ID(battery_level(), UNIT_PERCENT),
542 VOICE_PAUSE);
543 talk_force_enqueue_next();
545 break;
546 case SYS_USB_CONNECTED:
547 if (callback != NULL)
548 callback(parameter);
549 #if (CONFIG_STORAGE & STORAGE_MMC)
550 if (!mmc_touched() ||
551 (mmc_remove_request() == SYS_HOTSWAP_EXTRACTED))
552 #endif
554 system_flush();
555 #ifdef BOOTFILE
556 #if !defined(USB_NONE) && !defined(USB_HANDLED_BY_OF)
557 check_bootfile(false); /* gets initial size */
558 #endif
559 #endif
560 gui_usb_screen_run(false);
561 #ifdef BOOTFILE
562 #if !defined(USB_NONE) && !defined(USB_HANDLED_BY_OF)
563 check_bootfile(true);
564 #endif
565 #endif
566 system_restore();
568 return SYS_USB_CONNECTED;
570 case SYS_POWEROFF:
571 if (!clean_shutdown(callback, parameter))
572 return SYS_POWEROFF;
573 break;
574 #if CONFIG_CHARGING
575 case SYS_CHARGER_CONNECTED:
576 car_adapter_mode_processing(true);
577 return SYS_CHARGER_CONNECTED;
579 case SYS_CHARGER_DISCONNECTED:
580 car_adapter_mode_processing(false);
581 /*reset rockbox battery runtime*/
582 global_status.runtime = 0;
583 return SYS_CHARGER_DISCONNECTED;
585 case SYS_CAR_ADAPTER_RESUME:
586 audio_resume();
587 return SYS_CAR_ADAPTER_RESUME;
588 #endif
589 #ifdef HAVE_HOTSWAP_STORAGE_AS_MAIN
590 case SYS_FS_CHANGED:
592 /* simple sanity: assume rockbox is on the first hotswappable
593 * driver, abort out if that one isn't inserted */
594 int i;
595 for (i = 0; i < NUM_DRIVES; i++)
597 if (storage_removable(i) && !storage_present(i))
598 return SYS_FS_CHANGED;
600 system_flush();
601 check_bootfile(true); /* state gotten in main.c:init() */
602 system_restore();
604 return SYS_FS_CHANGED;
605 #endif
606 #ifdef HAVE_HEADPHONE_DETECTION
607 case SYS_PHONE_PLUGGED:
608 unplug_change(true);
609 return SYS_PHONE_PLUGGED;
611 case SYS_PHONE_UNPLUGGED:
612 unplug_change(false);
613 return SYS_PHONE_UNPLUGGED;
614 #endif
615 #ifdef IPOD_ACCESSORY_PROTOCOL
616 case SYS_IAP_PERIODIC:
617 iap_periodic();
618 return SYS_IAP_PERIODIC;
619 case SYS_IAP_HANDLEPKT:
620 iap_handlepkt();
621 return SYS_IAP_HANDLEPKT;
622 #endif
623 #if CONFIG_PLATFORM & (PLATFORM_ANDROID|PLATFORM_MAEMO)
624 /* stop playback if we receive a call */
625 case SYS_CALL_INCOMING:
626 resume = audio_status() == AUDIO_STATUS_PLAY;
627 list_stop_handler();
628 return SYS_CALL_INCOMING;
629 /* resume playback if needed */
630 case SYS_CALL_HUNG_UP:
631 if (resume && playlist_resume() != -1)
633 playlist_start(global_status.resume_index,
634 global_status.resume_offset);
636 resume = false;
637 return SYS_CALL_HUNG_UP;
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 audio_resume();
648 else
649 audio_pause();
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, 0, 16, BMPWIDTH_rockboxlogo, BMPHEIGHT_rockboxlogo);
698 #else
699 lcd_bitmap(rockboxlogo, 0, 10, BMPWIDTH_rockboxlogo, BMPHEIGHT_rockboxlogo);
700 lcd_setfont(FONT_SYSFIXED);
701 lcd_getstringsize((unsigned char *)"A", &font_w, &font_h);
702 lcd_putsxy((LCD_WIDTH/2) - ((strlen(version)*font_w)/2),
703 LCD_HEIGHT-font_h, (unsigned char *)version);
704 #endif
705 lcd_setfont(FONT_UI);
707 #else
708 char *rockbox = " ROCKbox!";
710 lcd_clear_display();
711 lcd_double_height(true);
712 lcd_puts(0, 0, rockbox);
713 lcd_puts_scroll(0, 1, rbversion);
714 #endif
715 lcd_update();
717 #ifdef HAVE_REMOTE_LCD
718 lcd_remote_clear_display();
719 lcd_remote_bitmap(remote_rockboxlogo, 0, 10, BMPWIDTH_remote_rockboxlogo,
720 BMPHEIGHT_remote_rockboxlogo);
721 lcd_remote_setfont(FONT_SYSFIXED);
722 lcd_remote_getstringsize((unsigned char *)"A", &font_w, &font_h);
723 lcd_remote_putsxy((LCD_REMOTE_WIDTH/2) - ((strlen(version)*font_w)/2),
724 LCD_REMOTE_HEIGHT-font_h, (unsigned char *)version);
725 lcd_remote_setfont(FONT_UI);
726 lcd_remote_update();
727 #endif
729 return 0;
732 #ifdef BOOTFILE
733 #if !defined(USB_NONE) && !defined(USB_HANDLED_BY_OF) || defined(HAVE_HOTSWAP_STORAGE_AS_MAIN)
735 memorize/compare details about the BOOTFILE
736 we don't use dircache because it may not be up to date after
737 USB disconnect (scanning in the background)
739 void check_bootfile(bool do_rolo)
741 static unsigned short wrtdate = 0;
742 static unsigned short wrttime = 0;
743 DIR* dir = NULL;
744 struct dirent* entry = NULL;
746 /* 1. open BOOTDIR and find the BOOTFILE dir entry */
747 dir = opendir(BOOTDIR);
749 if(!dir) return; /* do we want an error splash? */
751 /* loop all files in BOOTDIR */
752 while(0 != (entry = readdir(dir)))
754 if(!strcasecmp(entry->d_name, BOOTFILE))
756 struct dirinfo info = dir_get_info(dir, entry);
757 /* found the bootfile */
758 if(wrtdate && do_rolo)
760 if((info.wrtdate != wrtdate) ||
761 (info.wrttime != wrttime))
763 static const char *lines[] = { ID2P(LANG_BOOT_CHANGED),
764 ID2P(LANG_REBOOT_NOW) };
765 static const struct text_message message={ lines, 2 };
766 button_clear_queue(); /* Empty the keyboard buffer */
767 if(gui_syncyesno_run(&message, NULL, NULL) == YESNO_YES)
768 rolo_load(BOOTDIR "/" BOOTFILE);
771 wrtdate = info.wrtdate;
772 wrttime = info.wrttime;
775 closedir(dir);
777 #endif
778 #endif
780 /* check range, set volume and save settings */
781 void setvol(void)
783 const int min_vol = sound_min(SOUND_VOLUME);
784 const int max_vol = sound_max(SOUND_VOLUME);
785 if (global_settings.volume < min_vol)
786 global_settings.volume = min_vol;
787 if (global_settings.volume > max_vol)
788 global_settings.volume = max_vol;
789 sound_set_volume(global_settings.volume);
790 global_status.last_volume_change = current_tick;
791 settings_save();
794 char* strrsplt(char* str, int c)
796 char* s = strrchr(str, c);
798 if (s != NULL)
800 *s++ = '\0';
802 else
804 s = str;
807 return s;
811 * removes the extension of filename (if it doesn't start with a .)
812 * puts the result in buffer
814 char *strip_extension(char* buffer, int buffer_size, const char *filename)
816 char *dot = strrchr(filename, '.');
817 int len;
819 if (buffer_size <= 0)
821 return NULL;
824 buffer_size--; /* Make room for end nil */
826 if (dot != 0 && filename[0] != '.')
828 len = dot - filename;
829 len = MIN(len, buffer_size);
831 else
833 len = buffer_size;
836 strlcpy(buffer, filename, len + 1);
838 return buffer;
840 #endif /* !defined(__PCTOOL__) */
842 /* Read (up to) a line of text from fd into buffer and return number of bytes
843 * read (which may be larger than the number of bytes stored in buffer). If
844 * an error occurs, -1 is returned (and buffer contains whatever could be
845 * read). A line is terminated by a LF char. Neither LF nor CR chars are
846 * stored in buffer.
848 int read_line(int fd, char* buffer, int buffer_size)
850 int count = 0;
851 int num_read = 0;
853 errno = 0;
855 while (count < buffer_size)
857 unsigned char c;
859 if (1 != read(fd, &c, 1))
860 break;
862 num_read++;
864 if ( c == '\n' )
865 break;
867 if ( c == '\r' )
868 continue;
870 buffer[count++] = c;
873 buffer[MIN(count, buffer_size - 1)] = 0;
875 return errno ? -1 : num_read;
879 char* skip_whitespace(char* const str)
881 char *s = str;
883 while (isspace(*s))
884 s++;
886 return s;
889 /* Format time into buf.
891 * buf - buffer to format to.
892 * buf_size - size of buffer.
893 * t - time to format, in milliseconds.
895 void format_time(char* buf, int buf_size, long t)
897 int const time = abs(t / 1000);
898 int const hours = time / 3600;
899 int const minutes = time / 60 - hours * 60;
900 int const seconds = time % 60;
901 const char * const sign = &"-"[t < 0 ? 0 : 1];
903 if ( hours == 0 )
905 snprintf(buf, buf_size, "%s%d:%02d", sign, minutes, seconds);
907 else
909 snprintf(buf, buf_size, "%s%d:%02d:%02d", sign, hours, minutes,
910 seconds);
915 /** Open a UTF-8 file and set file descriptor to first byte after BOM.
916 * If no BOM is present this behaves like open().
917 * If the file is opened for writing and O_TRUNC is set, write a BOM to
918 * the opened file and leave the file pointer set after the BOM.
920 #define BOM "\xef\xbb\xbf"
921 #define BOM_SIZE 3
923 int open_utf8(const char* pathname, int flags)
925 int fd;
926 unsigned char bom[BOM_SIZE];
928 fd = open(pathname, flags, 0666);
929 if(fd < 0)
930 return fd;
932 if(flags & (O_TRUNC | O_WRONLY))
934 write(fd, BOM, BOM_SIZE);
936 else
938 read(fd, bom, BOM_SIZE);
939 /* check for BOM */
940 if(memcmp(bom, BOM, BOM_SIZE))
941 lseek(fd, 0, SEEK_SET);
943 return fd;
947 #ifdef HAVE_LCD_COLOR
949 * Helper function to convert a string of 6 hex digits to a native colour
952 static int hex2dec(int c)
954 return (((c) >= '0' && ((c) <= '9')) ? (c) - '0' :
955 (toupper(c)) - 'A' + 10);
958 int hex_to_rgb(const char* hex, int* color)
960 int red, green, blue;
961 int i = 0;
963 while ((i < 6) && (isxdigit(hex[i])))
964 i++;
966 if (i < 6)
967 return -1;
969 red = (hex2dec(hex[0]) << 4) | hex2dec(hex[1]);
970 green = (hex2dec(hex[2]) << 4) | hex2dec(hex[3]);
971 blue = (hex2dec(hex[4]) << 4) | hex2dec(hex[5]);
973 *color = LCD_RGBPACK(red,green,blue);
975 return 0;
977 #endif /* HAVE_LCD_COLOR */
979 #ifdef HAVE_LCD_BITMAP
980 /* '0'-'3' are ASCII 0x30 to 0x33 */
981 #define is0123(x) (((x) & 0xfc) == 0x30)
982 #if !defined(__PCTOOL__) || defined(CHECKWPS)
983 bool parse_color(enum screen_type screen, char *text, int *value)
985 (void)text; (void)value; /* silence warnings on mono bitmap */
986 (void)screen;
988 #ifdef HAVE_LCD_COLOR
989 if (screens[screen].depth > 2)
991 if (hex_to_rgb(text, value) < 0)
992 return false;
993 else
994 return true;
996 #endif
998 #if LCD_DEPTH == 2 || (defined(HAVE_REMOTE_LCD) && LCD_REMOTE_DEPTH == 2)
999 if (screens[screen].depth == 2)
1001 if (text[1] != '\0' || !is0123(*text))
1002 return false;
1003 *value = *text - '0';
1004 return true;
1006 #endif
1007 return false;
1009 #endif /* !defined(__PCTOOL__) || defined(CHECKWPS) */
1011 /* only used in USB HID and set_time screen */
1012 #if defined(USB_ENABLE_HID) || (CONFIG_RTC != 0)
1013 int clamp_value_wrap(int value, int max, int min)
1015 if (value > max)
1016 return min;
1017 if (value < min)
1018 return max;
1019 return value;
1021 #endif
1022 #endif