Sansa clip+: do not set GPIO B7 in the display driver, it's already used for FM radio I2C
[kugel-rb.git] / apps / misc.c
blobe4a5c42d0d1889171119eae1b9284a8193f7657a
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"
87 #ifdef BOOTFILE
88 #if !defined(USB_NONE) && !defined(USB_HANDLED_BY_OF) \
89 || defined(HAVE_HOTSWAP_STORAGE_AS_MAIN)
90 #include "rolo.h"
91 #endif
92 #endif
94 /* units used with output_dyn_value */
95 const unsigned char * const byte_units[] =
97 ID2P(LANG_BYTE),
98 ID2P(LANG_KILOBYTE),
99 ID2P(LANG_MEGABYTE),
100 ID2P(LANG_GIGABYTE)
103 const unsigned char * const * const kbyte_units = &byte_units[1];
105 /* Format a large-range value for output, using the appropriate unit so that
106 * the displayed value is in the range 1 <= display < 1000 (1024 for "binary"
107 * units) if possible, and 3 significant digits are shown. If a buffer is
108 * given, the result is snprintf()'d into that buffer, otherwise the result is
109 * voiced.*/
110 char *output_dyn_value(char *buf, int buf_size, int value,
111 const unsigned char * const *units, bool bin_scale)
113 int scale = bin_scale ? 1024 : 1000;
114 int fraction = 0;
115 int unit_no = 0;
116 char tbuf[5];
118 while (value >= scale)
120 fraction = value % scale;
121 value /= scale;
122 unit_no++;
124 if (bin_scale)
125 fraction = fraction * 1000 / 1024;
127 if (value >= 100 || !unit_no)
128 tbuf[0] = '\0';
129 else if (value >= 10)
130 snprintf(tbuf, sizeof(tbuf), "%01d", fraction / 100);
131 else
132 snprintf(tbuf, sizeof(tbuf), "%02d", fraction / 10);
134 if (buf)
136 if (*tbuf)
137 snprintf(buf, buf_size, "%d%s%s%s", value, str(LANG_POINT),
138 tbuf, P2STR(units[unit_no]));
139 else
140 snprintf(buf, buf_size, "%d%s", value, P2STR(units[unit_no]));
142 else
144 talk_fractional(tbuf, value, P2ID(units[unit_no]));
146 return buf;
149 /* Ask the user if they really want to erase the current dynamic playlist
150 * returns true if the playlist should be replaced */
151 bool warn_on_pl_erase(void)
153 if (global_settings.warnon_erase_dynplaylist &&
154 !global_settings.party_mode &&
155 playlist_modified(NULL))
157 static const char *lines[] =
158 {ID2P(LANG_WARN_ERASEDYNPLAYLIST_PROMPT)};
159 static const struct text_message message={lines, 1};
161 return (gui_syncyesno_run(&message, NULL, NULL) == YESNO_YES);
163 else
164 return true;
168 /* Performance optimized version of the read_line() (see below) function. */
169 int fast_readline(int fd, char *buf, int buf_size, void *parameters,
170 int (*callback)(int n, const char *buf, void *parameters))
172 char *p, *next;
173 int rc, pos = 0;
174 int count = 0;
176 while ( 1 )
178 next = NULL;
180 rc = read(fd, &buf[pos], buf_size - pos - 1);
181 if (rc >= 0)
182 buf[pos+rc] = '\0';
184 if ( (p = strchr(buf, '\r')) != NULL)
186 *p = '\0';
187 next = ++p;
189 else
190 p = buf;
192 if ( (p = strchr(p, '\n')) != NULL)
194 *p = '\0';
195 next = ++p;
198 rc = callback(count, buf, parameters);
199 if (rc < 0)
200 return rc;
202 count++;
203 if (next)
205 pos = buf_size - ((long)next - (long)buf) - 1;
206 memmove(buf, next, pos);
208 else
209 break ;
212 return 0;
215 /* parse a line from a configuration file. the line format is:
217 name: value
219 Any whitespace before setting name or value (after ':') is ignored.
220 A # as first non-whitespace character discards the whole line.
221 Function sets pointers to null-terminated setting name and value.
222 Returns false if no valid config entry was found.
225 bool settings_parseline(char* line, char** name, char** value)
227 char* ptr;
229 line = skip_whitespace(line);
231 if ( *line == '#' )
232 return false;
234 ptr = strchr(line, ':');
235 if ( !ptr )
236 return false;
238 *name = line;
239 *ptr = 0;
240 ptr++;
241 ptr = skip_whitespace(ptr);
242 *value = ptr;
243 return true;
246 static void system_flush(void)
248 scrobbler_shutdown();
249 playlist_shutdown();
250 tree_flush();
251 call_storage_idle_notifys(true); /*doesnt work on usb and shutdown from ata thread */
254 static void system_restore(void)
256 tree_restore();
257 scrobbler_init();
260 static bool clean_shutdown(void (*callback)(void *), void *parameter)
262 long msg_id = -1;
263 int i;
265 scrobbler_poweroff();
267 #if CONFIG_CHARGING && !defined(HAVE_POWEROFF_WHILE_CHARGING)
268 if(!charger_inserted())
269 #endif
271 bool batt_safe = battery_level_safe();
272 int audio_stat = audio_status();
274 FOR_NB_SCREENS(i)
276 screens[i].clear_display();
277 screens[i].update();
280 if (batt_safe)
282 #ifdef HAVE_TAGCACHE
283 if (!tagcache_prepare_shutdown())
285 cancel_shutdown();
286 splash(HZ, ID2P(LANG_TAGCACHE_BUSY));
287 return false;
289 #endif
290 if (battery_level() > 10)
291 splash(0, str(LANG_SHUTTINGDOWN));
292 else
294 msg_id = LANG_WARNING_BATTERY_LOW;
295 splashf(0, "%s %s", str(LANG_WARNING_BATTERY_LOW),
296 str(LANG_SHUTTINGDOWN));
299 else
301 msg_id = LANG_WARNING_BATTERY_EMPTY;
302 splashf(0, "%s %s", str(LANG_WARNING_BATTERY_EMPTY),
303 str(LANG_SHUTTINGDOWN));
306 if (global_settings.fade_on_stop
307 && (audio_stat & AUDIO_STATUS_PLAY))
309 fade(false, false);
312 if (batt_safe) /* do not save on critical battery */
314 #if defined(HAVE_RECORDING) && CONFIG_CODEC == SWCODEC
315 if (audio_stat & AUDIO_STATUS_RECORD)
317 rec_command(RECORDING_CMD_STOP);
318 /* wait for stop to complete */
319 while (audio_status() & AUDIO_STATUS_RECORD)
320 sleep(1);
322 #endif
323 bookmark_autobookmark(false);
325 /* audio_stop_recording == audio_stop for HWCODEC */
326 audio_stop();
328 if (callback != NULL)
329 callback(parameter);
331 #if CONFIG_CODEC != SWCODEC
332 /* wait for audio_stop or audio_stop_recording to complete */
333 while (audio_status())
334 sleep(1);
335 #endif
337 #if defined(HAVE_RECORDING) && CONFIG_CODEC == SWCODEC
338 audio_close_recording();
339 #endif
341 if(global_settings.talk_menu)
343 bool enqueue = false;
344 if(msg_id != -1)
346 talk_id(msg_id, enqueue);
347 enqueue = true;
349 talk_id(LANG_SHUTTINGDOWN, enqueue);
350 #if CONFIG_CODEC == SWCODEC
351 voice_wait();
352 #endif
355 system_flush();
356 #ifdef HAVE_EEPROM_SETTINGS
357 if (firmware_settings.initialized)
359 firmware_settings.disk_clean = true;
360 firmware_settings.bl_version = 0;
361 eeprom_settings_store();
363 #endif
365 #ifdef HAVE_DIRCACHE
366 else
367 dircache_disable();
368 #endif
370 shutdown_hw();
372 return false;
375 bool list_stop_handler(void)
377 bool ret = false;
379 #if CONFIG_TUNER
380 radio_stop();
381 #endif
383 /* Stop the music if it is playing */
384 if(audio_status())
386 if (!global_settings.party_mode)
388 if (global_settings.fade_on_stop)
389 fade(false, false);
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 if (global_settings.fade_on_stop)
455 fade(false, false);
456 else
457 audio_pause();
459 waiting_to_resume_play = false;
464 static void car_adapter_tick(void)
466 if (waiting_to_resume_play)
468 if (TIME_AFTER(current_tick, play_resume_tick))
470 if (audio_status() & AUDIO_STATUS_PAUSE)
472 queue_broadcast(SYS_CAR_ADAPTER_RESUME, 0);
474 waiting_to_resume_play = false;
479 void car_adapter_mode_init(void)
481 tick_add_task(car_adapter_tick);
483 #endif
485 #ifdef HAVE_HEADPHONE_DETECTION
486 static void unplug_change(bool inserted)
488 static bool headphone_caused_pause = false;
490 if (global_settings.unplug_mode)
492 int audio_stat = audio_status();
493 if (inserted)
495 if ((audio_stat & AUDIO_STATUS_PLAY) &&
496 headphone_caused_pause &&
497 global_settings.unplug_mode > 1 )
498 audio_resume();
499 backlight_on();
500 headphone_caused_pause = false;
501 } else {
502 if ((audio_stat & AUDIO_STATUS_PLAY) &&
503 !(audio_stat & AUDIO_STATUS_PAUSE))
505 headphone_caused_pause = true;
506 audio_pause();
508 if (global_settings.unplug_rw)
510 if (audio_current_track()->elapsed >
511 (unsigned long)(global_settings.unplug_rw*1000))
512 audio_ff_rewind(audio_current_track()->elapsed -
513 (global_settings.unplug_rw*1000));
514 else
515 audio_ff_rewind(0);
521 #endif
523 long default_event_handler_ex(long event, void (*callback)(void *), void *parameter)
525 #if CONFIG_PLATFORM & (PLATFORM_ANDROID|PLATFORM_MAEMO)
526 static bool resume = false;
527 #endif
529 switch(event)
531 case SYS_BATTERY_UPDATE:
532 if(global_settings.talk_battery_level)
534 talk_ids(true, VOICE_PAUSE, VOICE_PAUSE,
535 LANG_BATTERY_TIME,
536 TALK_ID(battery_level(), UNIT_PERCENT),
537 VOICE_PAUSE);
538 talk_force_enqueue_next();
540 break;
541 case SYS_USB_CONNECTED:
542 if (callback != NULL)
543 callback(parameter);
544 #if (CONFIG_STORAGE & STORAGE_MMC)
545 if (!mmc_touched() ||
546 (mmc_remove_request() == SYS_HOTSWAP_EXTRACTED))
547 #endif
549 system_flush();
550 #ifdef BOOTFILE
551 #if !defined(USB_NONE) && !defined(USB_HANDLED_BY_OF)
552 check_bootfile(false); /* gets initial size */
553 #endif
554 #endif
555 gui_usb_screen_run(false);
556 #ifdef BOOTFILE
557 #if !defined(USB_NONE) && !defined(USB_HANDLED_BY_OF)
558 check_bootfile(true);
559 #endif
560 #endif
561 system_restore();
563 return SYS_USB_CONNECTED;
565 case SYS_POWEROFF:
566 if (!clean_shutdown(callback, parameter))
567 return SYS_POWEROFF;
568 break;
569 #if CONFIG_CHARGING
570 case SYS_CHARGER_CONNECTED:
571 car_adapter_mode_processing(true);
572 return SYS_CHARGER_CONNECTED;
574 case SYS_CHARGER_DISCONNECTED:
575 car_adapter_mode_processing(false);
576 /*reset rockbox battery runtime*/
577 global_status.runtime = 0;
578 return SYS_CHARGER_DISCONNECTED;
580 case SYS_CAR_ADAPTER_RESUME:
581 audio_resume();
582 return SYS_CAR_ADAPTER_RESUME;
583 #endif
584 #ifdef HAVE_HOTSWAP_STORAGE_AS_MAIN
585 case SYS_FS_CHANGED:
587 /* simple sanity: assume rockbox is on the first hotswappable
588 * driver, abort out if that one isn't inserted */
589 int i;
590 for (i = 0; i < NUM_DRIVES; i++)
592 if (storage_removable(i) && !storage_present(i))
593 return SYS_FS_CHANGED;
595 system_flush();
596 check_bootfile(true); /* state gotten in main.c:init() */
597 system_restore();
599 return SYS_FS_CHANGED;
600 #endif
601 #ifdef HAVE_HEADPHONE_DETECTION
602 case SYS_PHONE_PLUGGED:
603 unplug_change(true);
604 return SYS_PHONE_PLUGGED;
606 case SYS_PHONE_UNPLUGGED:
607 unplug_change(false);
608 return SYS_PHONE_UNPLUGGED;
609 #endif
610 #ifdef IPOD_ACCESSORY_PROTOCOL
611 case SYS_IAP_PERIODIC:
612 iap_periodic();
613 return SYS_IAP_PERIODIC;
614 case SYS_IAP_HANDLEPKT:
615 iap_handlepkt();
616 return SYS_IAP_HANDLEPKT;
617 #endif
618 #if CONFIG_PLATFORM & (PLATFORM_ANDROID|PLATFORM_MAEMO)
619 /* stop playback if we receive a call */
620 case SYS_CALL_INCOMING:
621 resume = audio_status() == AUDIO_STATUS_PLAY;
622 list_stop_handler();
623 return SYS_CALL_INCOMING;
624 /* resume playback if needed */
625 case SYS_CALL_HUNG_UP:
626 if (resume && playlist_resume() != -1)
628 playlist_start(global_status.resume_index,
629 global_status.resume_offset);
631 resume = false;
632 return SYS_CALL_HUNG_UP;
633 #endif
634 #if (CONFIG_PLATFORM & PLATFORM_HOSTED) && defined(PLATFORM_HAS_VOLUME_CHANGE)
635 case SYS_VOLUME_CHANGED:
637 static bool firstvolume = true;
638 int volume = hosted_get_volume();
639 DEBUGF("SYS_VOLUME_CHANGED: %d\n", volume);
640 if (global_settings.volume != volume) {
641 global_settings.volume = volume;
642 if (firstvolume) {
643 setvol();
644 firstvolume = false;
647 return 0;
649 #endif
650 #ifdef HAVE_MULTIMEDIA_KEYS
651 /* multimedia keys on keyboards, headsets */
652 case BUTTON_MULTIMEDIA_PLAYPAUSE:
654 int status = audio_status();
655 if (status & AUDIO_STATUS_PLAY)
657 if (status & AUDIO_STATUS_PAUSE)
658 audio_resume();
659 else
660 audio_pause();
662 else
663 if (playlist_resume() != -1)
665 playlist_start(global_status.resume_index,
666 global_status.resume_offset);
668 return event;
670 case BUTTON_MULTIMEDIA_NEXT:
671 audio_next();
672 return event;
673 case BUTTON_MULTIMEDIA_PREV:
674 audio_prev();
675 return event;
676 case BUTTON_MULTIMEDIA_STOP:
677 list_stop_handler();
678 return event;
679 case BUTTON_MULTIMEDIA_REW:
680 case BUTTON_MULTIMEDIA_FFWD:
681 /* not supported yet, needs to be done in the WPS */
682 return 0;
683 #endif
685 return 0;
688 long default_event_handler(long event)
690 return default_event_handler_ex(event, NULL, NULL);
693 int show_logo( void )
695 #ifdef HAVE_LCD_BITMAP
696 char version[32];
697 int font_h, font_w;
699 snprintf(version, sizeof(version), "Ver. %s", rbversion);
701 lcd_clear_display();
702 #if defined(SANSA_CLIP) || defined(SANSA_CLIPV2) || defined(SANSA_CLIPPLUS)
703 /* display the logo in the blue area of the screen */
704 lcd_setfont(FONT_SYSFIXED);
705 lcd_getstringsize((unsigned char *)"A", &font_w, &font_h);
706 lcd_putsxy((LCD_WIDTH/2) - ((strlen(version)*font_w)/2),
707 0, (unsigned char *)version);
708 lcd_bitmap(rockboxlogo, 0, 16, BMPWIDTH_rockboxlogo, BMPHEIGHT_rockboxlogo);
709 #else
710 lcd_bitmap(rockboxlogo, 0, 10, BMPWIDTH_rockboxlogo, BMPHEIGHT_rockboxlogo);
711 lcd_setfont(FONT_SYSFIXED);
712 lcd_getstringsize((unsigned char *)"A", &font_w, &font_h);
713 lcd_putsxy((LCD_WIDTH/2) - ((strlen(version)*font_w)/2),
714 LCD_HEIGHT-font_h, (unsigned char *)version);
715 #endif
716 lcd_setfont(FONT_UI);
718 #else
719 char *rockbox = " ROCKbox!";
721 lcd_clear_display();
722 lcd_double_height(true);
723 lcd_puts(0, 0, rockbox);
724 lcd_puts_scroll(0, 1, rbversion);
725 #endif
726 lcd_update();
728 #ifdef HAVE_REMOTE_LCD
729 lcd_remote_clear_display();
730 lcd_remote_bitmap(remote_rockboxlogo, 0, 10, BMPWIDTH_remote_rockboxlogo,
731 BMPHEIGHT_remote_rockboxlogo);
732 lcd_remote_setfont(FONT_SYSFIXED);
733 lcd_remote_getstringsize((unsigned char *)"A", &font_w, &font_h);
734 lcd_remote_putsxy((LCD_REMOTE_WIDTH/2) - ((strlen(version)*font_w)/2),
735 LCD_REMOTE_HEIGHT-font_h, (unsigned char *)version);
736 lcd_remote_setfont(FONT_UI);
737 lcd_remote_update();
738 #endif
740 return 0;
743 #ifdef BOOTFILE
744 #if !defined(USB_NONE) && !defined(USB_HANDLED_BY_OF) || defined(HAVE_HOTSWAP_STORAGE_AS_MAIN)
746 memorize/compare details about the BOOTFILE
747 we don't use dircache because it may not be up to date after
748 USB disconnect (scanning in the background)
750 void check_bootfile(bool do_rolo)
752 static unsigned short wrtdate = 0;
753 static unsigned short wrttime = 0;
754 DIR* dir = NULL;
755 struct dirent* entry = NULL;
757 /* 1. open BOOTDIR and find the BOOTFILE dir entry */
758 dir = opendir(BOOTDIR);
760 if(!dir) return; /* do we want an error splash? */
762 /* loop all files in BOOTDIR */
763 while(0 != (entry = readdir(dir)))
765 if(!strcasecmp(entry->d_name, BOOTFILE))
767 struct dirinfo info = dir_get_info(dir, entry);
768 /* found the bootfile */
769 if(wrtdate && do_rolo)
771 if((info.wrtdate != wrtdate) ||
772 (info.wrttime != wrttime))
774 static const char *lines[] = { ID2P(LANG_BOOT_CHANGED),
775 ID2P(LANG_REBOOT_NOW) };
776 static const struct text_message message={ lines, 2 };
777 button_clear_queue(); /* Empty the keyboard buffer */
778 if(gui_syncyesno_run(&message, NULL, NULL) == YESNO_YES)
779 rolo_load(BOOTDIR "/" BOOTFILE);
782 wrtdate = info.wrtdate;
783 wrttime = info.wrttime;
786 closedir(dir);
788 #endif
789 #endif
791 /* check range, set volume and save settings */
792 void setvol(void)
794 const int min_vol = sound_min(SOUND_VOLUME);
795 const int max_vol = sound_max(SOUND_VOLUME);
796 if (global_settings.volume < min_vol)
797 global_settings.volume = min_vol;
798 if (global_settings.volume > max_vol)
799 global_settings.volume = max_vol;
800 sound_set_volume(global_settings.volume);
801 global_status.last_volume_change = current_tick;
802 settings_save();
805 char* strrsplt(char* str, int c)
807 char* s = strrchr(str, c);
809 if (s != NULL)
811 *s++ = '\0';
813 else
815 s = str;
818 return s;
822 * removes the extension of filename (if it doesn't start with a .)
823 * puts the result in buffer
825 char *strip_extension(char* buffer, int buffer_size, const char *filename)
827 char *dot = strrchr(filename, '.');
828 int len;
830 if (buffer_size <= 0)
832 return NULL;
835 buffer_size--; /* Make room for end nil */
837 if (dot != 0 && filename[0] != '.')
839 len = dot - filename;
840 len = MIN(len, buffer_size);
842 else
844 len = buffer_size;
847 strlcpy(buffer, filename, len + 1);
849 return buffer;
851 #endif /* !defined(__PCTOOL__) */
853 /* Read (up to) a line of text from fd into buffer and return number of bytes
854 * read (which may be larger than the number of bytes stored in buffer). If
855 * an error occurs, -1 is returned (and buffer contains whatever could be
856 * read). A line is terminated by a LF char. Neither LF nor CR chars are
857 * stored in buffer.
859 int read_line(int fd, char* buffer, int buffer_size)
861 int count = 0;
862 int num_read = 0;
864 errno = 0;
866 while (count < buffer_size)
868 unsigned char c;
870 if (1 != read(fd, &c, 1))
871 break;
873 num_read++;
875 if ( c == '\n' )
876 break;
878 if ( c == '\r' )
879 continue;
881 buffer[count++] = c;
884 buffer[MIN(count, buffer_size - 1)] = 0;
886 return errno ? -1 : num_read;
890 char* skip_whitespace(char* const str)
892 char *s = str;
894 while (isspace(*s))
895 s++;
897 return s;
900 /* Format time into buf.
902 * buf - buffer to format to.
903 * buf_size - size of buffer.
904 * t - time to format, in milliseconds.
906 void format_time(char* buf, int buf_size, long t)
908 int const time = abs(t / 1000);
909 int const hours = time / 3600;
910 int const minutes = time / 60 - hours * 60;
911 int const seconds = time % 60;
912 const char * const sign = &"-"[t < 0 ? 0 : 1];
914 if ( hours == 0 )
916 snprintf(buf, buf_size, "%s%d:%02d", sign, minutes, seconds);
918 else
920 snprintf(buf, buf_size, "%s%d:%02d:%02d", sign, hours, minutes,
921 seconds);
926 /** Open a UTF-8 file and set file descriptor to first byte after BOM.
927 * If no BOM is present this behaves like open().
928 * If the file is opened for writing and O_TRUNC is set, write a BOM to
929 * the opened file and leave the file pointer set after the BOM.
931 #define BOM "\xef\xbb\xbf"
932 #define BOM_SIZE 3
934 int open_utf8(const char* pathname, int flags)
936 int fd;
937 unsigned char bom[BOM_SIZE];
939 fd = open(pathname, flags, 0666);
940 if(fd < 0)
941 return fd;
943 if(flags & (O_TRUNC | O_WRONLY))
945 write(fd, BOM, BOM_SIZE);
947 else
949 read(fd, bom, BOM_SIZE);
950 /* check for BOM */
951 if(memcmp(bom, BOM, BOM_SIZE))
952 lseek(fd, 0, SEEK_SET);
954 return fd;
958 #ifdef HAVE_LCD_COLOR
960 * Helper function to convert a string of 6 hex digits to a native colour
963 static int hex2dec(int c)
965 return (((c) >= '0' && ((c) <= '9')) ? (c) - '0' :
966 (toupper(c)) - 'A' + 10);
969 int hex_to_rgb(const char* hex, int* color)
971 int red, green, blue;
972 int i = 0;
974 while ((i < 6) && (isxdigit(hex[i])))
975 i++;
977 if (i < 6)
978 return -1;
980 red = (hex2dec(hex[0]) << 4) | hex2dec(hex[1]);
981 green = (hex2dec(hex[2]) << 4) | hex2dec(hex[3]);
982 blue = (hex2dec(hex[4]) << 4) | hex2dec(hex[5]);
984 *color = LCD_RGBPACK(red,green,blue);
986 return 0;
988 #endif /* HAVE_LCD_COLOR */
990 #ifdef HAVE_LCD_BITMAP
991 /* '0'-'3' are ASCII 0x30 to 0x33 */
992 #define is0123(x) (((x) & 0xfc) == 0x30)
993 #if !defined(__PCTOOL__) || defined(CHECKWPS)
994 bool parse_color(enum screen_type screen, char *text, int *value)
996 (void)text; (void)value; /* silence warnings on mono bitmap */
997 (void)screen;
999 #ifdef HAVE_LCD_COLOR
1000 if (screens[screen].depth > 2)
1002 if (hex_to_rgb(text, value) < 0)
1003 return false;
1004 else
1005 return true;
1007 #endif
1009 #if LCD_DEPTH == 2 || (defined(HAVE_REMOTE_LCD) && LCD_REMOTE_DEPTH == 2)
1010 if (screens[screen].depth == 2)
1012 if (text[1] != '\0' || !is0123(*text))
1013 return false;
1014 *value = *text - '0';
1015 return true;
1017 #endif
1018 return false;
1020 #endif /* !defined(__PCTOOL__) || defined(CHECKWPS) */
1022 /* only used in USB HID and set_time screen */
1023 #if defined(USB_ENABLE_HID) || (CONFIG_RTC != 0)
1024 int clamp_value_wrap(int value, int max, int min)
1026 if (value > max)
1027 return min;
1028 if (value < min)
1029 return max;
1030 return value;
1032 #endif
1033 #endif