Hopefully fix red now and reduce binsize for HWCODEC targets. This change implements...
[kugel-rb.git] / apps / misc.c
blob0d25e2aa963bcbafefb0e3e40bafe69f0f1903a6
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 long msg_id = -1;
261 int i;
263 scrobbler_poweroff();
265 #if CONFIG_CHARGING && !defined(HAVE_POWEROFF_WHILE_CHARGING)
266 if(!charger_inserted())
267 #endif
269 bool batt_safe = battery_level_safe();
270 int audio_stat = audio_status();
272 FOR_NB_SCREENS(i)
274 screens[i].clear_display();
275 screens[i].update();
278 if (batt_safe)
280 #ifdef HAVE_TAGCACHE
281 if (!tagcache_prepare_shutdown())
283 cancel_shutdown();
284 splash(HZ, ID2P(LANG_TAGCACHE_BUSY));
285 return false;
287 #endif
288 if (battery_level() > 10)
289 splash(0, str(LANG_SHUTTINGDOWN));
290 else
292 msg_id = LANG_WARNING_BATTERY_LOW;
293 splashf(0, "%s %s", str(LANG_WARNING_BATTERY_LOW),
294 str(LANG_SHUTTINGDOWN));
297 else
299 msg_id = LANG_WARNING_BATTERY_EMPTY;
300 splashf(0, "%s %s", str(LANG_WARNING_BATTERY_EMPTY),
301 str(LANG_SHUTTINGDOWN));
304 if (global_settings.fade_on_stop
305 && (audio_stat & AUDIO_STATUS_PLAY))
307 fade(false, false);
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 (global_settings.fade_on_stop)
387 fade(false, false);
388 bookmark_autobookmark(true);
389 audio_stop();
390 ret = true; /* bookmarking can make a refresh necessary */
393 #if CONFIG_CHARGING
394 #if (CONFIG_KEYPAD == RECORDER_PAD) && !defined(HAVE_SW_POWEROFF)
395 else
397 if (charger_inserted())
398 charging_splash();
399 else
400 shutdown_screen(); /* won't return if shutdown actually happens */
402 ret = true; /* screen is dirty, caller needs to refresh */
404 #endif
405 #ifndef HAVE_POWEROFF_WHILE_CHARGING
407 static long last_off = 0;
409 if (TIME_BEFORE(current_tick, last_off + HZ/2))
411 if (charger_inserted())
413 charging_splash();
414 ret = true; /* screen is dirty, caller needs to refresh */
417 last_off = current_tick;
419 #endif
420 #endif /* CONFIG_CHARGING */
421 return ret;
424 #if CONFIG_CHARGING
425 static bool waiting_to_resume_play = false;
426 static long play_resume_tick;
428 static void car_adapter_mode_processing(bool inserted)
430 if (global_settings.car_adapter_mode)
432 if(inserted)
435 * Just got plugged in, delay & resume if we were playing
437 if (audio_status() & AUDIO_STATUS_PAUSE)
439 /* delay resume a bit while the engine is cranking */
440 play_resume_tick = current_tick + HZ*5;
441 waiting_to_resume_play = true;
444 else
447 * Just got unplugged, pause if playing
449 if ((audio_status() & AUDIO_STATUS_PLAY) &&
450 !(audio_status() & AUDIO_STATUS_PAUSE))
452 if (global_settings.fade_on_stop)
453 fade(false, false);
454 else
455 audio_pause();
457 waiting_to_resume_play = false;
462 static void car_adapter_tick(void)
464 if (waiting_to_resume_play)
466 if (TIME_AFTER(current_tick, play_resume_tick))
468 if (audio_status() & AUDIO_STATUS_PAUSE)
470 queue_broadcast(SYS_CAR_ADAPTER_RESUME, 0);
472 waiting_to_resume_play = false;
477 void car_adapter_mode_init(void)
479 tick_add_task(car_adapter_tick);
481 #endif
483 #ifdef HAVE_HEADPHONE_DETECTION
484 static void unplug_change(bool inserted)
486 static bool headphone_caused_pause = false;
488 if (global_settings.unplug_mode)
490 int audio_stat = audio_status();
491 if (inserted)
493 if ((audio_stat & AUDIO_STATUS_PLAY) &&
494 headphone_caused_pause &&
495 global_settings.unplug_mode > 1 )
496 audio_resume();
497 backlight_on();
498 headphone_caused_pause = false;
499 } else {
500 if ((audio_stat & AUDIO_STATUS_PLAY) &&
501 !(audio_stat & AUDIO_STATUS_PAUSE))
503 headphone_caused_pause = true;
504 audio_pause();
506 if (global_settings.unplug_rw)
508 if (audio_current_track()->elapsed >
509 (unsigned long)(global_settings.unplug_rw*1000))
510 audio_ff_rewind(audio_current_track()->elapsed -
511 (global_settings.unplug_rw*1000));
512 else
513 audio_ff_rewind(0);
519 #endif
521 long default_event_handler_ex(long event, void (*callback)(void *), void *parameter)
523 #if CONFIG_PLATFORM & (PLATFORM_ANDROID|PLATFORM_MAEMO)
524 static bool resume = false;
525 #endif
527 switch(event)
529 case SYS_BATTERY_UPDATE:
530 if(global_settings.talk_battery_level)
532 talk_ids(true, VOICE_PAUSE, VOICE_PAUSE,
533 LANG_BATTERY_TIME,
534 TALK_ID(battery_level(), UNIT_PERCENT),
535 VOICE_PAUSE);
536 talk_force_enqueue_next();
538 break;
539 case SYS_USB_CONNECTED:
540 if (callback != NULL)
541 callback(parameter);
542 #if (CONFIG_STORAGE & STORAGE_MMC)
543 if (!mmc_touched() ||
544 (mmc_remove_request() == SYS_HOTSWAP_EXTRACTED))
545 #endif
547 system_flush();
548 #ifdef BOOTFILE
549 #if !defined(USB_NONE) && !defined(USB_HANDLED_BY_OF)
550 check_bootfile(false); /* gets initial size */
551 #endif
552 #endif
553 gui_usb_screen_run(false);
554 #ifdef BOOTFILE
555 #if !defined(USB_NONE) && !defined(USB_HANDLED_BY_OF)
556 check_bootfile(true);
557 #endif
558 #endif
559 system_restore();
561 return SYS_USB_CONNECTED;
563 case SYS_POWEROFF:
564 if (!clean_shutdown(callback, parameter))
565 return SYS_POWEROFF;
566 break;
567 #if CONFIG_CHARGING
568 case SYS_CHARGER_CONNECTED:
569 car_adapter_mode_processing(true);
570 return SYS_CHARGER_CONNECTED;
572 case SYS_CHARGER_DISCONNECTED:
573 car_adapter_mode_processing(false);
574 /*reset rockbox battery runtime*/
575 global_status.runtime = 0;
576 return SYS_CHARGER_DISCONNECTED;
578 case SYS_CAR_ADAPTER_RESUME:
579 audio_resume();
580 return SYS_CAR_ADAPTER_RESUME;
581 #endif
582 #ifdef HAVE_HOTSWAP_STORAGE_AS_MAIN
583 case SYS_FS_CHANGED:
585 /* simple sanity: assume rockbox is on the first hotswappable
586 * driver, abort out if that one isn't inserted */
587 int i;
588 for (i = 0; i < NUM_DRIVES; i++)
590 if (storage_removable(i) && !storage_present(i))
591 return SYS_FS_CHANGED;
593 system_flush();
594 check_bootfile(true); /* state gotten in main.c:init() */
595 system_restore();
597 return SYS_FS_CHANGED;
598 #endif
599 #ifdef HAVE_HEADPHONE_DETECTION
600 case SYS_PHONE_PLUGGED:
601 unplug_change(true);
602 return SYS_PHONE_PLUGGED;
604 case SYS_PHONE_UNPLUGGED:
605 unplug_change(false);
606 return SYS_PHONE_UNPLUGGED;
607 #endif
608 #ifdef IPOD_ACCESSORY_PROTOCOL
609 case SYS_IAP_PERIODIC:
610 iap_periodic();
611 return SYS_IAP_PERIODIC;
612 case SYS_IAP_HANDLEPKT:
613 iap_handlepkt();
614 return SYS_IAP_HANDLEPKT;
615 #endif
616 #if CONFIG_PLATFORM & (PLATFORM_ANDROID|PLATFORM_MAEMO)
617 /* stop playback if we receive a call */
618 case SYS_CALL_INCOMING:
619 resume = audio_status() == AUDIO_STATUS_PLAY;
620 list_stop_handler();
621 return SYS_CALL_INCOMING;
622 /* resume playback if needed */
623 case SYS_CALL_HUNG_UP:
624 if (resume && playlist_resume() != -1)
626 playlist_start(global_status.resume_index,
627 global_status.resume_offset);
629 resume = false;
630 return SYS_CALL_HUNG_UP;
631 #endif
632 #if (CONFIG_PLATFORM & PLATFORM_HOSTED) && defined(PLATFORM_HAS_VOLUME_CHANGE)
633 case SYS_VOLUME_CHANGED:
635 int volume = hosted_get_volume();
636 if (global_settings.volume != volume)
637 global_settings.volume = volume;
638 return 0;
640 #endif
641 #ifdef HAVE_MULTIMEDIA_KEYS
642 /* multimedia keys on keyboards, headsets */
643 case BUTTON_MULTIMEDIA_PLAYPAUSE:
645 int status = audio_status();
646 if (status & AUDIO_STATUS_PLAY)
648 if (status & AUDIO_STATUS_PAUSE)
649 audio_resume();
650 else
651 audio_pause();
653 else
654 if (playlist_resume() != -1)
656 playlist_start(global_status.resume_index,
657 global_status.resume_offset);
659 return event;
661 case BUTTON_MULTIMEDIA_NEXT:
662 audio_next();
663 return event;
664 case BUTTON_MULTIMEDIA_PREV:
665 audio_prev();
666 return event;
667 case BUTTON_MULTIMEDIA_STOP:
668 list_stop_handler();
669 return event;
670 case BUTTON_MULTIMEDIA_REW:
671 case BUTTON_MULTIMEDIA_FFWD:
672 /* not supported yet, needs to be done in the WPS */
673 return 0;
674 #endif
676 return 0;
679 long default_event_handler(long event)
681 return default_event_handler_ex(event, NULL, NULL);
684 int show_logo( void )
686 #ifdef HAVE_LCD_BITMAP
687 char version[32];
688 int font_h, font_w;
690 snprintf(version, sizeof(version), "Ver. %s", rbversion);
692 lcd_clear_display();
693 #if defined(SANSA_CLIP) || defined(SANSA_CLIPV2) || defined(SANSA_CLIPPLUS)
694 /* display the logo in the blue area of the screen */
695 lcd_setfont(FONT_SYSFIXED);
696 lcd_getstringsize((unsigned char *)"A", &font_w, &font_h);
697 lcd_putsxy((LCD_WIDTH/2) - ((strlen(version)*font_w)/2),
698 0, (unsigned char *)version);
699 lcd_bitmap(rockboxlogo, 0, 16, BMPWIDTH_rockboxlogo, BMPHEIGHT_rockboxlogo);
700 #else
701 lcd_bitmap(rockboxlogo, 0, 10, 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;
842 #endif /* !defined(__PCTOOL__) */
844 /* Read (up to) a line of text from fd into buffer and return number of bytes
845 * read (which may be larger than the number of bytes stored in buffer). If
846 * an error occurs, -1 is returned (and buffer contains whatever could be
847 * read). A line is terminated by a LF char. Neither LF nor CR chars are
848 * stored in buffer.
850 int read_line(int fd, char* buffer, int buffer_size)
852 int count = 0;
853 int num_read = 0;
855 errno = 0;
857 while (count < buffer_size)
859 unsigned char c;
861 if (1 != read(fd, &c, 1))
862 break;
864 num_read++;
866 if ( c == '\n' )
867 break;
869 if ( c == '\r' )
870 continue;
872 buffer[count++] = c;
875 buffer[MIN(count, buffer_size - 1)] = 0;
877 return errno ? -1 : num_read;
881 char* skip_whitespace(char* const str)
883 char *s = str;
885 while (isspace(*s))
886 s++;
888 return s;
891 /* Format time into buf.
893 * buf - buffer to format to.
894 * buf_size - size of buffer.
895 * t - time to format, in milliseconds.
897 void format_time(char* buf, int buf_size, long t)
899 int const time = abs(t / 1000);
900 int const hours = time / 3600;
901 int const minutes = time / 60 - hours * 60;
902 int const seconds = time % 60;
903 const char * const sign = &"-"[t < 0 ? 0 : 1];
905 if ( hours == 0 )
907 snprintf(buf, buf_size, "%s%d:%02d", sign, minutes, seconds);
909 else
911 snprintf(buf, buf_size, "%s%d:%02d:%02d", sign, hours, minutes,
912 seconds);
917 /** Open a UTF-8 file and set file descriptor to first byte after BOM.
918 * If no BOM is present this behaves like open().
919 * If the file is opened for writing and O_TRUNC is set, write a BOM to
920 * the opened file and leave the file pointer set after the BOM.
922 #define BOM "\xef\xbb\xbf"
923 #define BOM_SIZE 3
925 int open_utf8(const char* pathname, int flags)
927 int fd;
928 unsigned char bom[BOM_SIZE];
930 fd = open(pathname, flags, 0666);
931 if(fd < 0)
932 return fd;
934 if(flags & (O_TRUNC | O_WRONLY))
936 write(fd, BOM, BOM_SIZE);
938 else
940 read(fd, bom, BOM_SIZE);
941 /* check for BOM */
942 if(memcmp(bom, BOM, BOM_SIZE))
943 lseek(fd, 0, SEEK_SET);
945 return fd;
949 #ifdef HAVE_LCD_COLOR
951 * Helper function to convert a string of 6 hex digits to a native colour
954 static int hex2dec(int c)
956 return (((c) >= '0' && ((c) <= '9')) ? (c) - '0' :
957 (toupper(c)) - 'A' + 10);
960 int hex_to_rgb(const char* hex, int* color)
962 int red, green, blue;
963 int i = 0;
965 while ((i < 6) && (isxdigit(hex[i])))
966 i++;
968 if (i < 6)
969 return -1;
971 red = (hex2dec(hex[0]) << 4) | hex2dec(hex[1]);
972 green = (hex2dec(hex[2]) << 4) | hex2dec(hex[3]);
973 blue = (hex2dec(hex[4]) << 4) | hex2dec(hex[5]);
975 *color = LCD_RGBPACK(red,green,blue);
977 return 0;
979 #endif /* HAVE_LCD_COLOR */
981 #ifdef HAVE_LCD_BITMAP
982 /* '0'-'3' are ASCII 0x30 to 0x33 */
983 #define is0123(x) (((x) & 0xfc) == 0x30)
984 #if !defined(__PCTOOL__) || defined(CHECKWPS)
985 bool parse_color(enum screen_type screen, char *text, int *value)
987 (void)text; (void)value; /* silence warnings on mono bitmap */
988 (void)screen;
990 #ifdef HAVE_LCD_COLOR
991 if (screens[screen].depth > 2)
993 if (hex_to_rgb(text, value) < 0)
994 return false;
995 else
996 return true;
998 #endif
1000 #if LCD_DEPTH == 2 || (defined(HAVE_REMOTE_LCD) && LCD_REMOTE_DEPTH == 2)
1001 if (screens[screen].depth == 2)
1003 if (text[1] != '\0' || !is0123(*text))
1004 return false;
1005 *value = *text - '0';
1006 return true;
1008 #endif
1009 return false;
1011 #endif /* !defined(__PCTOOL__) || defined(CHECKWPS) */
1013 /* only used in USB HID and set_time screen */
1014 #if defined(USB_ENABLE_HID) || (CONFIG_RTC != 0)
1015 int clamp_value_wrap(int value, int max, int min)
1017 if (value > max)
1018 return min;
1019 if (value < min)
1020 return max;
1021 return value;
1023 #endif
1024 #endif