Update the Czech translation.
[kugel-rb.git] / apps / misc.c
blob22f71507ba6415ba436e3cd6f72bb37feb1afcb0
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 "lcd.h"
30 #include "file.h"
31 #include "filefuncs.h"
32 #ifndef __PCTOOL__
33 #include "lang.h"
34 #include "dir.h"
35 #include "lcd-remote.h"
36 #include "system.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 #if CONFIG_TUNER
61 #include "radio.h"
62 #endif
64 #ifdef IPOD_ACCESSORY_PROTOCOL
65 #include "iap.h"
66 #endif
68 #if (CONFIG_STORAGE & STORAGE_MMC)
69 #include "ata_mmc.h"
70 #endif
71 #include "tree.h"
72 #include "eeprom_settings.h"
73 #if defined(HAVE_RECORDING) && !defined(__PCTOOL__)
74 #include "recording.h"
75 #endif
76 #if defined(HAVE_LCD_BITMAP) && !defined(__PCTOOL__)
77 #include "bmp.h"
78 #include "icons.h"
79 #endif /* End HAVE_LCD_BITMAP */
80 #include "bookmark.h"
81 #include "wps.h"
82 #include "playback.h"
84 #ifdef BOOTFILE
85 #if !defined(USB_NONE) && !defined(USB_HANDLED_BY_OF) \
86 || defined(HAVE_HOTSWAP_STORAGE_AS_MAIN)
87 #include "rolo.h"
88 #endif
89 #endif
91 /* units used with output_dyn_value */
92 const unsigned char * const byte_units[] =
94 ID2P(LANG_BYTE),
95 ID2P(LANG_KILOBYTE),
96 ID2P(LANG_MEGABYTE),
97 ID2P(LANG_GIGABYTE)
100 const unsigned char * const * const kbyte_units = &byte_units[1];
102 /* Format a large-range value for output, using the appropriate unit so that
103 * the displayed value is in the range 1 <= display < 1000 (1024 for "binary"
104 * units) if possible, and 3 significant digits are shown. If a buffer is
105 * given, the result is snprintf()'d into that buffer, otherwise the result is
106 * voiced.*/
107 char *output_dyn_value(char *buf, int buf_size, int value,
108 const unsigned char * const *units, bool bin_scale)
110 int scale = bin_scale ? 1024 : 1000;
111 int fraction = 0;
112 int unit_no = 0;
113 char tbuf[5];
115 while (value >= scale)
117 fraction = value % scale;
118 value /= scale;
119 unit_no++;
121 if (bin_scale)
122 fraction = fraction * 1000 / 1024;
124 if (value >= 100 || !unit_no)
125 tbuf[0] = '\0';
126 else if (value >= 10)
127 snprintf(tbuf, sizeof(tbuf), "%01d", fraction / 100);
128 else
129 snprintf(tbuf, sizeof(tbuf), "%02d", fraction / 10);
131 if (buf)
133 if (*tbuf)
134 snprintf(buf, buf_size, "%d%s%s%s", value, str(LANG_POINT),
135 tbuf, P2STR(units[unit_no]));
136 else
137 snprintf(buf, buf_size, "%d%s", value, P2STR(units[unit_no]));
139 else
141 talk_fractional(tbuf, value, P2ID(units[unit_no]));
143 return buf;
146 /* Ask the user if they really want to erase the current dynamic playlist
147 * returns true if the playlist should be replaced */
148 bool warn_on_pl_erase(void)
150 if (global_settings.warnon_erase_dynplaylist &&
151 !global_settings.party_mode &&
152 playlist_modified(NULL))
154 static const char *lines[] =
155 {ID2P(LANG_WARN_ERASEDYNPLAYLIST_PROMPT)};
156 static const struct text_message message={lines, 1};
158 return (gui_syncyesno_run(&message, NULL, NULL) == YESNO_YES);
160 else
161 return true;
165 /* Performance optimized version of the read_line() (see below) function. */
166 int fast_readline(int fd, char *buf, int buf_size, void *parameters,
167 int (*callback)(int n, const char *buf, void *parameters))
169 char *p, *next;
170 int rc, pos = 0;
171 int count = 0;
173 while ( 1 )
175 next = NULL;
177 rc = read(fd, &buf[pos], buf_size - pos - 1);
178 if (rc >= 0)
179 buf[pos+rc] = '\0';
181 if ( (p = strchr(buf, '\r')) != NULL)
183 *p = '\0';
184 next = ++p;
186 else
187 p = buf;
189 if ( (p = strchr(p, '\n')) != NULL)
191 *p = '\0';
192 next = ++p;
195 rc = callback(count, buf, parameters);
196 if (rc < 0)
197 return rc;
199 count++;
200 if (next)
202 pos = buf_size - ((long)next - (long)buf) - 1;
203 memmove(buf, next, pos);
205 else
206 break ;
209 return 0;
212 /* parse a line from a configuration file. the line format is:
214 name: value
216 Any whitespace before setting name or value (after ':') is ignored.
217 A # as first non-whitespace character discards the whole line.
218 Function sets pointers to null-terminated setting name and value.
219 Returns false if no valid config entry was found.
222 bool settings_parseline(char* line, char** name, char** value)
224 char* ptr;
226 line = skip_whitespace(line);
228 if ( *line == '#' )
229 return false;
231 ptr = strchr(line, ':');
232 if ( !ptr )
233 return false;
235 *name = line;
236 *ptr = 0;
237 ptr++;
238 ptr = skip_whitespace(ptr);
239 *value = ptr;
240 return true;
243 static void system_flush(void)
245 scrobbler_shutdown();
246 playlist_shutdown();
247 tree_flush();
248 call_storage_idle_notifys(true); /*doesnt work on usb and shutdown from ata thread */
251 static void system_restore(void)
253 tree_restore();
254 scrobbler_init();
257 static bool clean_shutdown(void (*callback)(void *), void *parameter)
259 #if (CONFIG_PLATFORM & PLATFORM_HOSTED)
260 (void)callback;
261 (void)parameter;
262 bookmark_autobookmark(false);
263 call_storage_idle_notifys(true);
264 #else
265 long msg_id = -1;
266 int i;
268 scrobbler_poweroff();
270 #if CONFIG_CHARGING && !defined(HAVE_POWEROFF_WHILE_CHARGING)
271 if(!charger_inserted())
272 #endif
274 bool batt_safe = battery_level_safe();
275 int audio_stat = audio_status();
277 FOR_NB_SCREENS(i)
279 screens[i].clear_display();
280 screens[i].update();
283 if (batt_safe)
285 #ifdef HAVE_TAGCACHE
286 if (!tagcache_prepare_shutdown())
288 cancel_shutdown();
289 splash(HZ, ID2P(LANG_TAGCACHE_BUSY));
290 return false;
292 #endif
293 if (battery_level() > 10)
294 splash(0, str(LANG_SHUTTINGDOWN));
295 else
297 msg_id = LANG_WARNING_BATTERY_LOW;
298 splashf(0, "%s %s", str(LANG_WARNING_BATTERY_LOW),
299 str(LANG_SHUTTINGDOWN));
302 else
304 msg_id = LANG_WARNING_BATTERY_EMPTY;
305 splashf(0, "%s %s", str(LANG_WARNING_BATTERY_EMPTY),
306 str(LANG_SHUTTINGDOWN));
309 if (global_settings.fade_on_stop
310 && (audio_stat & AUDIO_STATUS_PLAY))
312 fade(false, false);
315 if (batt_safe) /* do not save on critical battery */
317 #if defined(HAVE_RECORDING) && CONFIG_CODEC == SWCODEC
318 if (audio_stat & AUDIO_STATUS_RECORD)
320 rec_command(RECORDING_CMD_STOP);
321 /* wait for stop to complete */
322 while (audio_status() & AUDIO_STATUS_RECORD)
323 sleep(1);
325 #endif
326 bookmark_autobookmark(false);
328 /* audio_stop_recording == audio_stop for HWCODEC */
329 audio_stop();
331 if (callback != NULL)
332 callback(parameter);
334 #if CONFIG_CODEC != SWCODEC
335 /* wait for audio_stop or audio_stop_recording to complete */
336 while (audio_status())
337 sleep(1);
338 #endif
340 #if defined(HAVE_RECORDING) && CONFIG_CODEC == SWCODEC
341 audio_close_recording();
342 #endif
344 if(global_settings.talk_menu)
346 bool enqueue = false;
347 if(msg_id != -1)
349 talk_id(msg_id, enqueue);
350 enqueue = true;
352 talk_id(LANG_SHUTTINGDOWN, enqueue);
353 #if CONFIG_CODEC == SWCODEC
354 voice_wait();
355 #endif
358 system_flush();
359 #ifdef HAVE_EEPROM_SETTINGS
360 if (firmware_settings.initialized)
362 firmware_settings.disk_clean = true;
363 firmware_settings.bl_version = 0;
364 eeprom_settings_store();
366 #endif
368 #ifdef HAVE_DIRCACHE
369 else
370 dircache_disable();
371 #endif
373 shutdown_hw();
375 #endif
376 return false;
379 bool list_stop_handler(void)
381 bool ret = false;
383 #if CONFIG_TUNER
384 radio_stop();
385 #endif
387 /* Stop the music if it is playing */
388 if(audio_status())
390 if (!global_settings.party_mode)
392 if (global_settings.fade_on_stop)
393 fade(false, false);
394 bookmark_autobookmark(true);
395 audio_stop();
396 ret = true; /* bookmarking can make a refresh necessary */
399 #if CONFIG_CHARGING
400 #if (CONFIG_KEYPAD == RECORDER_PAD) && !defined(HAVE_SW_POWEROFF)
401 else
403 if (charger_inserted())
404 charging_splash();
405 else
406 shutdown_screen(); /* won't return if shutdown actually happens */
408 ret = true; /* screen is dirty, caller needs to refresh */
410 #endif
411 #ifndef HAVE_POWEROFF_WHILE_CHARGING
413 static long last_off = 0;
415 if (TIME_BEFORE(current_tick, last_off + HZ/2))
417 if (charger_inserted())
419 charging_splash();
420 ret = true; /* screen is dirty, caller needs to refresh */
423 last_off = current_tick;
425 #endif
426 #endif /* CONFIG_CHARGING */
427 return ret;
430 #if CONFIG_CHARGING
431 static bool waiting_to_resume_play = false;
432 static long play_resume_tick;
434 static void car_adapter_mode_processing(bool inserted)
436 if (global_settings.car_adapter_mode)
438 if(inserted)
441 * Just got plugged in, delay & resume if we were playing
443 if (audio_status() & AUDIO_STATUS_PAUSE)
445 /* delay resume a bit while the engine is cranking */
446 play_resume_tick = current_tick + HZ*5;
447 waiting_to_resume_play = true;
450 else
453 * Just got unplugged, pause if playing
455 if ((audio_status() & AUDIO_STATUS_PLAY) &&
456 !(audio_status() & AUDIO_STATUS_PAUSE))
458 if (global_settings.fade_on_stop)
459 fade(false, false);
460 else
461 audio_pause();
463 waiting_to_resume_play = false;
468 static void car_adapter_tick(void)
470 if (waiting_to_resume_play)
472 if (TIME_AFTER(current_tick, play_resume_tick))
474 if (audio_status() & AUDIO_STATUS_PAUSE)
476 queue_broadcast(SYS_CAR_ADAPTER_RESUME, 0);
478 waiting_to_resume_play = false;
483 void car_adapter_mode_init(void)
485 tick_add_task(car_adapter_tick);
487 #endif
489 #ifdef HAVE_HEADPHONE_DETECTION
490 static void unplug_change(bool inserted)
492 static bool headphone_caused_pause = false;
494 if (global_settings.unplug_mode)
496 int audio_stat = audio_status();
497 if (inserted)
499 if ((audio_stat & AUDIO_STATUS_PLAY) &&
500 headphone_caused_pause &&
501 global_settings.unplug_mode > 1 )
502 audio_resume();
503 backlight_on();
504 headphone_caused_pause = false;
505 } else {
506 if ((audio_stat & AUDIO_STATUS_PLAY) &&
507 !(audio_stat & AUDIO_STATUS_PAUSE))
509 headphone_caused_pause = true;
510 audio_pause();
512 if (global_settings.unplug_rw)
514 if (audio_current_track()->elapsed >
515 (unsigned long)(global_settings.unplug_rw*1000))
516 audio_ff_rewind(audio_current_track()->elapsed -
517 (global_settings.unplug_rw*1000));
518 else
519 audio_ff_rewind(0);
525 #endif
527 long default_event_handler_ex(long event, void (*callback)(void *), void *parameter)
529 #if CONFIG_PLATFORM & PLATFORM_ANDROID
530 static bool resume = false;
531 #endif
533 switch(event)
535 case SYS_BATTERY_UPDATE:
536 if(global_settings.talk_battery_level)
538 talk_ids(true, VOICE_PAUSE, VOICE_PAUSE,
539 LANG_BATTERY_TIME,
540 TALK_ID(battery_level(), UNIT_PERCENT),
541 VOICE_PAUSE);
542 talk_force_enqueue_next();
544 break;
545 case SYS_USB_CONNECTED:
546 if (callback != NULL)
547 callback(parameter);
548 #if (CONFIG_STORAGE & STORAGE_MMC)
549 if (!mmc_touched() ||
550 (mmc_remove_request() == SYS_HOTSWAP_EXTRACTED))
551 #endif
553 system_flush();
554 #ifdef BOOTFILE
555 #if !defined(USB_NONE) && !defined(USB_HANDLED_BY_OF)
556 check_bootfile(false); /* gets initial size */
557 #endif
558 #endif
559 gui_usb_screen_run(false);
560 #ifdef BOOTFILE
561 #if !defined(USB_NONE) && !defined(USB_HANDLED_BY_OF)
562 check_bootfile(true);
563 #endif
564 #endif
565 system_restore();
567 return SYS_USB_CONNECTED;
569 case SYS_POWEROFF:
570 if (!clean_shutdown(callback, parameter))
571 return SYS_POWEROFF;
572 break;
573 #if CONFIG_CHARGING
574 case SYS_CHARGER_CONNECTED:
575 car_adapter_mode_processing(true);
576 return SYS_CHARGER_CONNECTED;
578 case SYS_CHARGER_DISCONNECTED:
579 car_adapter_mode_processing(false);
580 /*reset rockbox battery runtime*/
581 global_status.runtime = 0;
582 return SYS_CHARGER_DISCONNECTED;
584 case SYS_CAR_ADAPTER_RESUME:
585 audio_resume();
586 return SYS_CAR_ADAPTER_RESUME;
587 #endif
588 #ifdef HAVE_HOTSWAP_STORAGE_AS_MAIN
589 case SYS_FS_CHANGED:
591 /* simple sanity: assume rockbox is on the first hotswappable
592 * driver, abort out if that one isn't inserted */
593 int i;
594 for (i = 0; i < NUM_DRIVES; i++)
596 if (storage_removable(i) && !storage_present(i))
597 return SYS_FS_CHANGED;
599 system_flush();
600 check_bootfile(true); /* state gotten in main.c:init() */
601 system_restore();
603 return SYS_FS_CHANGED;
604 #endif
605 #ifdef HAVE_HEADPHONE_DETECTION
606 case SYS_PHONE_PLUGGED:
607 unplug_change(true);
608 return SYS_PHONE_PLUGGED;
610 case SYS_PHONE_UNPLUGGED:
611 unplug_change(false);
612 return SYS_PHONE_UNPLUGGED;
613 #endif
614 #ifdef IPOD_ACCESSORY_PROTOCOL
615 case SYS_IAP_PERIODIC:
616 iap_periodic();
617 return SYS_IAP_PERIODIC;
618 case SYS_IAP_HANDLEPKT:
619 iap_handlepkt();
620 return SYS_IAP_HANDLEPKT;
621 #endif
622 #if CONFIG_PLATFORM & PLATFORM_ANDROID
623 /* stop playback if we receive a call */
624 case SYS_CALL_INCOMING:
625 resume = audio_status() == AUDIO_STATUS_PLAY;
626 list_stop_handler();
627 return SYS_CALL_INCOMING;
628 /* resume playback if needed */
629 case SYS_CALL_HUNG_UP:
630 if (resume && playlist_resume() != -1)
632 playlist_start(global_status.resume_index,
633 global_status.resume_offset);
635 resume = false;
636 return SYS_CALL_HUNG_UP;
637 #endif
638 #ifdef HAVE_MULTIMEDIA_KEYS
639 /* multimedia keys on keyboards, headsets */
640 case BUTTON_MULTIMEDIA_PLAYPAUSE:
642 int status = audio_status();
643 if (status & AUDIO_STATUS_PLAY)
645 if (status & AUDIO_STATUS_PAUSE)
646 audio_resume();
647 else
648 audio_pause();
650 else
651 if (playlist_resume() != -1)
653 playlist_start(global_status.resume_index,
654 global_status.resume_offset);
656 return event;
658 case BUTTON_MULTIMEDIA_NEXT:
659 audio_next();
660 return event;
661 case BUTTON_MULTIMEDIA_PREV:
662 audio_prev();
663 return event;
664 case BUTTON_MULTIMEDIA_STOP:
665 list_stop_handler();
666 return event;
667 case BUTTON_MULTIMEDIA_REW:
668 case BUTTON_MULTIMEDIA_FFWD:
669 /* not supported yet, needs to be done in the WPS */
670 return 0;
671 #endif
673 return 0;
676 long default_event_handler(long event)
678 return default_event_handler_ex(event, NULL, NULL);
681 int show_logo( void )
683 #ifdef HAVE_LCD_BITMAP
684 char version[32];
685 int font_h, font_w;
687 snprintf(version, sizeof(version), "Ver. %s", rbversion);
689 lcd_clear_display();
690 #if defined(SANSA_CLIP) || defined(SANSA_CLIPV2) || defined(SANSA_CLIPPLUS)
691 /* display the logo in the blue area of the screen */
692 lcd_setfont(FONT_SYSFIXED);
693 lcd_getstringsize((unsigned char *)"A", &font_w, &font_h);
694 lcd_putsxy((LCD_WIDTH/2) - ((strlen(version)*font_w)/2),
695 0, (unsigned char *)version);
696 lcd_bitmap(rockboxlogo, 0, 16, BMPWIDTH_rockboxlogo, BMPHEIGHT_rockboxlogo);
697 #else
698 lcd_bitmap(rockboxlogo, 0, 10, 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)
767 rolo_load(BOOTDIR "/" BOOTFILE);
770 wrtdate = info.wrtdate;
771 wrttime = info.wrttime;
774 closedir(dir);
776 #endif
777 #endif
779 /* check range, set volume and save settings */
780 void setvol(void)
782 const int min_vol = sound_min(SOUND_VOLUME);
783 const int max_vol = sound_max(SOUND_VOLUME);
784 if (global_settings.volume < min_vol)
785 global_settings.volume = min_vol;
786 if (global_settings.volume > max_vol)
787 global_settings.volume = max_vol;
788 sound_set_volume(global_settings.volume);
789 global_status.last_volume_change = current_tick;
790 settings_save();
793 char* strrsplt(char* str, int c)
795 char* s = strrchr(str, c);
797 if (s != NULL)
799 *s++ = '\0';
801 else
803 s = str;
806 return s;
810 * removes the extension of filename (if it doesn't start with a .)
811 * puts the result in buffer
813 char *strip_extension(char* buffer, int buffer_size, const char *filename)
815 char *dot = strrchr(filename, '.');
816 int len;
818 if (buffer_size <= 0)
820 return NULL;
823 buffer_size--; /* Make room for end nil */
825 if (dot != 0 && filename[0] != '.')
827 len = dot - filename;
828 len = MIN(len, buffer_size);
830 else
832 len = buffer_size;
835 strlcpy(buffer, filename, len + 1);
837 return buffer;
839 #endif /* !defined(__PCTOOL__) */
841 /* Read (up to) a line of text from fd into buffer and return number of bytes
842 * read (which may be larger than the number of bytes stored in buffer). If
843 * an error occurs, -1 is returned (and buffer contains whatever could be
844 * read). A line is terminated by a LF char. Neither LF nor CR chars are
845 * stored in buffer.
847 int read_line(int fd, char* buffer, int buffer_size)
849 int count = 0;
850 int num_read = 0;
852 errno = 0;
854 while (count < buffer_size)
856 unsigned char c;
858 if (1 != read(fd, &c, 1))
859 break;
861 num_read++;
863 if ( c == '\n' )
864 break;
866 if ( c == '\r' )
867 continue;
869 buffer[count++] = c;
872 buffer[MIN(count, buffer_size - 1)] = 0;
874 return errno ? -1 : num_read;
878 char* skip_whitespace(char* const str)
880 char *s = str;
882 while (isspace(*s))
883 s++;
885 return s;
888 /* Format time into buf.
890 * buf - buffer to format to.
891 * buf_size - size of buffer.
892 * t - time to format, in milliseconds.
894 void format_time(char* buf, int buf_size, long t)
896 if ( t < 3600000 )
898 snprintf(buf, buf_size, "%d:%02d",
899 (int) (t / 60000), (int) (t % 60000 / 1000));
901 else
903 snprintf(buf, buf_size, "%d:%02d:%02d",
904 (int) (t / 3600000), (int) (t % 3600000 / 60000),
905 (int) (t % 60000 / 1000));
910 /** Open a UTF-8 file and set file descriptor to first byte after BOM.
911 * If no BOM is present this behaves like open().
912 * If the file is opened for writing and O_TRUNC is set, write a BOM to
913 * the opened file and leave the file pointer set after the BOM.
915 #define BOM "\xef\xbb\xbf"
916 #define BOM_SIZE 3
918 int open_utf8(const char* pathname, int flags)
920 int fd;
921 unsigned char bom[BOM_SIZE];
923 fd = open(pathname, flags, 0666);
924 if(fd < 0)
925 return fd;
927 if(flags & (O_TRUNC | O_WRONLY))
929 write(fd, BOM, BOM_SIZE);
931 else
933 read(fd, bom, BOM_SIZE);
934 /* check for BOM */
935 if(memcmp(bom, BOM, BOM_SIZE))
936 lseek(fd, 0, SEEK_SET);
938 return fd;
942 #ifdef HAVE_LCD_COLOR
944 * Helper function to convert a string of 6 hex digits to a native colour
947 static int hex2dec(int c)
949 return (((c) >= '0' && ((c) <= '9')) ? (c) - '0' :
950 (toupper(c)) - 'A' + 10);
953 int hex_to_rgb(const char* hex, int* color)
955 int red, green, blue;
956 int i = 0;
958 while ((i < 6) && (isxdigit(hex[i])))
959 i++;
961 if (i < 6)
962 return -1;
964 red = (hex2dec(hex[0]) << 4) | hex2dec(hex[1]);
965 green = (hex2dec(hex[2]) << 4) | hex2dec(hex[3]);
966 blue = (hex2dec(hex[4]) << 4) | hex2dec(hex[5]);
968 *color = LCD_RGBPACK(red,green,blue);
970 return 0;
972 #endif /* HAVE_LCD_COLOR */
974 #ifdef HAVE_LCD_BITMAP
975 /* '0'-'3' are ASCII 0x30 to 0x33 */
976 #define is0123(x) (((x) & 0xfc) == 0x30)
977 #if !defined(__PCTOOL__) || defined(CHECKWPS)
978 bool parse_color(enum screen_type screen, char *text, int *value)
980 (void)text; (void)value; /* silence warnings on mono bitmap */
981 (void)screen;
983 #ifdef HAVE_LCD_COLOR
984 if (screens[screen].depth > 2)
986 if (hex_to_rgb(text, value) < 0)
987 return false;
988 else
989 return true;
991 #endif
993 #if LCD_DEPTH == 2 || (defined(HAVE_REMOTE_LCD) && LCD_REMOTE_DEPTH == 2)
994 if (screens[screen].depth == 2)
996 if (text[1] != '\0' || !is0123(*text))
997 return false;
998 *value = *text - '0';
999 return true;
1001 #endif
1002 return false;
1004 #endif /* !defined(__PCTOOL__) || defined(CHECKWPS) */
1006 /* only used in USB HID and set_time screen */
1007 #if defined(USB_ENABLE_HID) || (CONFIG_RTC != 0)
1008 int clamp_value_wrap(int value, int max, int min)
1010 if (value > max)
1011 return min;
1012 if (value < min)
1013 return max;
1014 return value;
1016 #endif
1017 #endif