Const correctness for output_dyn_value and unify some identical constants
[kugel-rb.git] / apps / misc.c
blob4400de1b925a6dd5f53ff887d41eef55e63b7371
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 <string.h>
24 #include "config.h"
25 #include "misc.h"
26 #include "lcd.h"
27 #include "file.h"
28 #ifdef __PCTOOL__
29 #include <stdarg.h>
30 #include <stdio.h>
31 #else
32 #include "sprintf.h"
33 #include "lang.h"
34 #include "dir.h"
35 #include "lcd-remote.h"
36 #include "errno.h"
37 #include "system.h"
38 #include "timefuncs.h"
39 #include "screens.h"
40 #include "talk.h"
41 #include "mpeg.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 #ifdef IPOD_ACCESSORY_PROTOCOL
62 #include "iap.h"
63 #endif
65 #if (CONFIG_STORAGE & STORAGE_MMC)
66 #include "ata_mmc.h"
67 #endif
68 #include "tree.h"
69 #include "eeprom_settings.h"
70 #if defined(HAVE_RECORDING) && !defined(__PCTOOL__)
71 #include "recording.h"
72 #endif
73 #if defined(HAVE_LCD_BITMAP) && !defined(__PCTOOL__)
74 #include "bmp.h"
75 #include "icons.h"
76 #endif /* End HAVE_LCD_BITMAP */
77 #include "bookmark.h"
78 #include "wps.h"
79 #include "playback.h"
81 #ifdef BOOTFILE
82 #if !defined(USB_NONE) && !defined(USB_HANDLED_BY_OF)
83 #include "rolo.h"
84 #endif
85 #endif
87 /* units used with output_dyn_value */
88 const unsigned char * const byte_units[] =
90 ID2P(LANG_BYTE),
91 ID2P(LANG_KILOBYTE),
92 ID2P(LANG_MEGABYTE),
93 ID2P(LANG_GIGABYTE)
96 const unsigned char * const * const kbyte_units = &byte_units[1];
98 /* Format a large-range value for output, using the appropriate unit so that
99 * the displayed value is in the range 1 <= display < 1000 (1024 for "binary"
100 * units) if possible, and 3 significant digits are shown. If a buffer is
101 * given, the result is snprintf()'d into that buffer, otherwise the result is
102 * voiced.*/
103 char *output_dyn_value(char *buf, int buf_size, int value,
104 const unsigned char * const *units, bool bin_scale)
106 int scale = bin_scale ? 1024 : 1000;
107 int fraction = 0;
108 int unit_no = 0;
109 char tbuf[5];
111 while (value >= scale)
113 fraction = value % scale;
114 value /= scale;
115 unit_no++;
117 if (bin_scale)
118 fraction = fraction * 1000 / 1024;
120 if (value >= 100 || !unit_no)
121 tbuf[0] = '\0';
122 else if (value >= 10)
123 snprintf(tbuf, sizeof(tbuf), "%01d", fraction / 100);
124 else
125 snprintf(tbuf, sizeof(tbuf), "%02d", fraction / 10);
127 if (buf)
129 if (strlen(tbuf))
130 snprintf(buf, buf_size, "%d%s%s%s", value, str(LANG_POINT),
131 tbuf, P2STR(units[unit_no]));
132 else
133 snprintf(buf, buf_size, "%d%s", value, P2STR(units[unit_no]));
135 else
137 talk_fractional(tbuf, value, P2ID(units[unit_no]));
139 return buf;
142 /* Ask the user if they really want to erase the current dynamic playlist
143 * returns true if the playlist should be replaced */
144 bool warn_on_pl_erase(void)
146 if (global_settings.warnon_erase_dynplaylist &&
147 !global_settings.party_mode &&
148 playlist_modified(NULL))
150 static const char *lines[] =
151 {ID2P(LANG_WARN_ERASEDYNPLAYLIST_PROMPT)};
152 static const struct text_message message={lines, 1};
154 return (gui_syncyesno_run(&message, NULL, NULL) == YESNO_YES);
156 else
157 return true;
160 /* Read (up to) a line of text from fd into buffer and return number of bytes
161 * read (which may be larger than the number of bytes stored in buffer). If
162 * an error occurs, -1 is returned (and buffer contains whatever could be
163 * read). A line is terminated by a LF char. Neither LF nor CR chars are
164 * stored in buffer.
166 int read_line(int fd, char* buffer, int buffer_size)
168 int count = 0;
169 int num_read = 0;
171 errno = 0;
173 while (count < buffer_size)
175 unsigned char c;
177 if (1 != read(fd, &c, 1))
178 break;
180 num_read++;
182 if ( c == '\n' )
183 break;
185 if ( c == '\r' )
186 continue;
188 buffer[count++] = c;
191 buffer[MIN(count, buffer_size - 1)] = 0;
193 return errno ? -1 : num_read;
196 /* Performance optimized version of the previous function. */
197 int fast_readline(int fd, char *buf, int buf_size, void *parameters,
198 int (*callback)(int n, const char *buf, void *parameters))
200 char *p, *next;
201 int rc, pos = 0;
202 int count = 0;
204 while ( 1 )
206 next = NULL;
208 rc = read(fd, &buf[pos], buf_size - pos - 1);
209 if (rc >= 0)
210 buf[pos+rc] = '\0';
212 if ( (p = strchr(buf, '\r')) != NULL)
214 *p = '\0';
215 next = ++p;
217 else
218 p = buf;
220 if ( (p = strchr(p, '\n')) != NULL)
222 *p = '\0';
223 next = ++p;
226 rc = callback(count, buf, parameters);
227 if (rc < 0)
228 return rc;
230 count++;
231 if (next)
233 pos = buf_size - ((long)next - (long)buf) - 1;
234 memmove(buf, next, pos);
236 else
237 break ;
240 return 0;
243 /* parse a line from a configuration file. the line format is:
245 name: value
247 Any whitespace before setting name or value (after ':') is ignored.
248 A # as first non-whitespace character discards the whole line.
249 Function sets pointers to null-terminated setting name and value.
250 Returns false if no valid config entry was found.
253 bool settings_parseline(char* line, char** name, char** value)
255 char* ptr;
257 line = skip_whitespace(line);
259 if ( *line == '#' )
260 return false;
262 ptr = strchr(line, ':');
263 if ( !ptr )
264 return false;
266 *name = line;
267 *ptr = 0;
268 ptr++;
269 ptr = skip_whitespace(ptr);
270 *value = ptr;
271 return true;
274 static void system_flush(void)
276 scrobbler_shutdown();
277 playlist_shutdown();
278 tree_flush();
279 call_storage_idle_notifys(true); /*doesnt work on usb and shutdown from ata thread */
282 static void system_restore(void)
284 tree_restore();
285 scrobbler_init();
288 static bool clean_shutdown(void (*callback)(void *), void *parameter)
290 #ifdef SIMULATOR
291 (void)callback;
292 (void)parameter;
293 bookmark_autobookmark();
294 call_storage_idle_notifys(true);
295 exit(0);
296 #else
297 long msg_id = -1;
298 int i;
300 scrobbler_poweroff();
302 #if CONFIG_CHARGING && !defined(HAVE_POWEROFF_WHILE_CHARGING)
303 if(!charger_inserted())
304 #endif
306 bool batt_safe = battery_level_safe();
307 int audio_stat = audio_status();
309 FOR_NB_SCREENS(i)
311 screens[i].clear_display();
312 screens[i].update();
315 if (batt_safe)
317 #ifdef HAVE_TAGCACHE
318 if (!tagcache_prepare_shutdown())
320 cancel_shutdown();
321 splash(HZ, ID2P(LANG_TAGCACHE_BUSY));
322 return false;
324 #endif
325 if (battery_level() > 10)
326 splash(0, str(LANG_SHUTTINGDOWN));
327 else
329 msg_id = LANG_WARNING_BATTERY_LOW;
330 splashf(0, "%s %s", str(LANG_WARNING_BATTERY_LOW),
331 str(LANG_SHUTTINGDOWN));
334 else
336 msg_id = LANG_WARNING_BATTERY_EMPTY;
337 splashf(0, "%s %s", str(LANG_WARNING_BATTERY_EMPTY),
338 str(LANG_SHUTTINGDOWN));
341 if (global_settings.fade_on_stop
342 && (audio_stat & AUDIO_STATUS_PLAY))
344 fade(false, false);
347 if (batt_safe) /* do not save on critical battery */
349 #if defined(HAVE_RECORDING) && CONFIG_CODEC == SWCODEC
350 if (audio_stat & AUDIO_STATUS_RECORD)
352 rec_command(RECORDING_CMD_STOP);
353 /* wait for stop to complete */
354 while (audio_status() & AUDIO_STATUS_RECORD)
355 sleep(1);
357 #endif
358 bookmark_autobookmark();
360 /* audio_stop_recording == audio_stop for HWCODEC */
361 audio_stop();
363 if (callback != NULL)
364 callback(parameter);
366 #if CONFIG_CODEC != SWCODEC
367 /* wait for audio_stop or audio_stop_recording to complete */
368 while (audio_status())
369 sleep(1);
370 #endif
372 #if defined(HAVE_RECORDING) && CONFIG_CODEC == SWCODEC
373 audio_close_recording();
374 #endif
376 if(global_settings.talk_menu)
378 bool enqueue = false;
379 if(msg_id != -1)
381 talk_id(msg_id, enqueue);
382 enqueue = true;
384 talk_id(LANG_SHUTTINGDOWN, enqueue);
385 #if CONFIG_CODEC == SWCODEC
386 voice_wait();
387 #endif
390 system_flush();
391 #ifdef HAVE_EEPROM_SETTINGS
392 if (firmware_settings.initialized)
394 firmware_settings.disk_clean = true;
395 firmware_settings.bl_version = 0;
396 eeprom_settings_store();
398 #endif
400 #ifdef HAVE_DIRCACHE
401 else
402 dircache_disable();
403 #endif
405 shutdown_hw();
407 #endif
408 return false;
411 bool list_stop_handler(void)
413 bool ret = false;
415 /* Stop the music if it is playing */
416 if(audio_status())
418 if (!global_settings.party_mode)
420 if (global_settings.fade_on_stop)
421 fade(false, false);
422 bookmark_autobookmark();
423 audio_stop();
424 ret = true; /* bookmarking can make a refresh necessary */
427 #if CONFIG_CHARGING
428 #if (CONFIG_KEYPAD == RECORDER_PAD) && !defined(HAVE_SW_POWEROFF)
429 else
431 if (charger_inserted())
432 charging_splash();
433 else
434 shutdown_screen(); /* won't return if shutdown actually happens */
436 ret = true; /* screen is dirty, caller needs to refresh */
438 #endif
439 #ifndef HAVE_POWEROFF_WHILE_CHARGING
441 static long last_off = 0;
443 if (TIME_BEFORE(current_tick, last_off + HZ/2))
445 if (charger_inserted())
447 charging_splash();
448 ret = true; /* screen is dirty, caller needs to refresh */
451 last_off = current_tick;
453 #endif
454 #endif /* CONFIG_CHARGING */
455 return ret;
458 #if CONFIG_CHARGING
459 static bool waiting_to_resume_play = false;
460 static long play_resume_tick;
462 static void car_adapter_mode_processing(bool inserted)
464 if (global_settings.car_adapter_mode)
466 if(inserted)
469 * Just got plugged in, delay & resume if we were playing
471 if (audio_status() & AUDIO_STATUS_PAUSE)
473 /* delay resume a bit while the engine is cranking */
474 play_resume_tick = current_tick + HZ*5;
475 waiting_to_resume_play = true;
478 else
481 * Just got unplugged, pause if playing
483 if ((audio_status() & AUDIO_STATUS_PLAY) &&
484 !(audio_status() & AUDIO_STATUS_PAUSE))
486 if (global_settings.fade_on_stop)
487 fade(false, false);
488 else
489 audio_pause();
491 waiting_to_resume_play = false;
496 static void car_adapter_tick(void)
498 if (waiting_to_resume_play)
500 if (TIME_AFTER(current_tick, play_resume_tick))
502 if (audio_status() & AUDIO_STATUS_PAUSE)
504 queue_broadcast(SYS_CAR_ADAPTER_RESUME, 0);
506 waiting_to_resume_play = false;
511 void car_adapter_mode_init(void)
513 tick_add_task(car_adapter_tick);
515 #endif
517 #ifdef HAVE_HEADPHONE_DETECTION
518 static void unplug_change(bool inserted)
520 static bool headphone_caused_pause = false;
522 if (global_settings.unplug_mode)
524 int audio_stat = audio_status();
525 if (inserted)
527 if ((audio_stat & AUDIO_STATUS_PLAY) &&
528 headphone_caused_pause &&
529 global_settings.unplug_mode > 1 )
530 audio_resume();
531 backlight_on();
532 headphone_caused_pause = false;
533 } else {
534 if ((audio_stat & AUDIO_STATUS_PLAY) &&
535 !(audio_stat & AUDIO_STATUS_PAUSE))
537 headphone_caused_pause = true;
538 audio_pause();
540 if (global_settings.unplug_rw)
542 if (audio_current_track()->elapsed >
543 (unsigned long)(global_settings.unplug_rw*1000))
544 audio_ff_rewind(audio_current_track()->elapsed -
545 (global_settings.unplug_rw*1000));
546 else
547 audio_ff_rewind(0);
553 #endif
555 long default_event_handler_ex(long event, void (*callback)(void *), void *parameter)
557 switch(event)
559 case SYS_BATTERY_UPDATE:
560 if(global_settings.talk_battery_level)
562 talk_ids(true, VOICE_PAUSE, VOICE_PAUSE,
563 LANG_BATTERY_TIME,
564 TALK_ID(battery_level(), UNIT_PERCENT),
565 VOICE_PAUSE);
566 talk_force_enqueue_next();
568 break;
569 case SYS_USB_CONNECTED:
570 if (callback != NULL)
571 callback(parameter);
572 #if (CONFIG_STORAGE & STORAGE_MMC)
573 if (!mmc_touched() ||
574 (mmc_remove_request() == SYS_HOTSWAP_EXTRACTED))
575 #endif
577 system_flush();
578 #ifdef BOOTFILE
579 #if !defined(USB_NONE) && !defined(USB_HANDLED_BY_OF)
580 check_bootfile(false); /* gets initial size */
581 #endif
582 #endif
583 usb_screen();
584 #ifdef BOOTFILE
585 #if !defined(USB_NONE) && !defined(USB_HANDLED_BY_OF)
586 check_bootfile(true);
587 #endif
588 #endif
589 system_restore();
591 return SYS_USB_CONNECTED;
592 case SYS_POWEROFF:
593 if (!clean_shutdown(callback, parameter))
594 return SYS_POWEROFF;
595 break;
596 #if CONFIG_CHARGING
597 case SYS_CHARGER_CONNECTED:
598 car_adapter_mode_processing(true);
599 return SYS_CHARGER_CONNECTED;
601 case SYS_CHARGER_DISCONNECTED:
602 car_adapter_mode_processing(false);
603 return SYS_CHARGER_DISCONNECTED;
605 case SYS_CAR_ADAPTER_RESUME:
606 audio_resume();
607 return SYS_CAR_ADAPTER_RESUME;
608 #endif
609 #ifdef HAVE_HEADPHONE_DETECTION
610 case SYS_PHONE_PLUGGED:
611 unplug_change(true);
612 return SYS_PHONE_PLUGGED;
614 case SYS_PHONE_UNPLUGGED:
615 unplug_change(false);
616 return SYS_PHONE_UNPLUGGED;
617 #endif
618 #ifdef IPOD_ACCESSORY_PROTOCOL
619 case SYS_IAP_PERIODIC:
620 iap_periodic();
621 return SYS_IAP_PERIODIC;
622 case SYS_IAP_HANDLEPKT:
623 iap_handlepkt();
624 return SYS_IAP_HANDLEPKT;
625 #endif
627 return 0;
630 long default_event_handler(long event)
632 return default_event_handler_ex(event, NULL, NULL);
635 int show_logo( void )
637 #ifdef HAVE_LCD_BITMAP
638 char version[32];
639 int font_h, font_w;
641 snprintf(version, sizeof(version), "Ver. %s", appsversion);
643 lcd_clear_display();
644 #ifdef SANSA_CLIP /* display the logo in the blue area of the screen */
645 lcd_setfont(FONT_SYSFIXED);
646 lcd_getstringsize((unsigned char *)"A", &font_w, &font_h);
647 lcd_putsxy((LCD_WIDTH/2) - ((strlen(version)*font_w)/2),
648 0, (unsigned char *)version);
649 lcd_bitmap(rockboxlogo, 0, 16, BMPWIDTH_rockboxlogo, BMPHEIGHT_rockboxlogo);
650 #else
651 lcd_bitmap(rockboxlogo, 0, 10, BMPWIDTH_rockboxlogo, BMPHEIGHT_rockboxlogo);
652 lcd_setfont(FONT_SYSFIXED);
653 lcd_getstringsize((unsigned char *)"A", &font_w, &font_h);
654 lcd_putsxy((LCD_WIDTH/2) - ((strlen(version)*font_w)/2),
655 LCD_HEIGHT-font_h, (unsigned char *)version);
656 #endif
657 lcd_setfont(FONT_UI);
659 #else
660 char *rockbox = " ROCKbox!";
662 lcd_clear_display();
663 lcd_double_height(true);
664 lcd_puts(0, 0, rockbox);
665 lcd_puts_scroll(0, 1, appsversion);
666 #endif
667 lcd_update();
669 #ifdef HAVE_REMOTE_LCD
670 lcd_remote_clear_display();
671 lcd_remote_bitmap(remote_rockboxlogo, 0, 10, BMPWIDTH_remote_rockboxlogo,
672 BMPHEIGHT_remote_rockboxlogo);
673 lcd_remote_setfont(FONT_SYSFIXED);
674 lcd_remote_getstringsize((unsigned char *)"A", &font_w, &font_h);
675 lcd_remote_putsxy((LCD_REMOTE_WIDTH/2) - ((strlen(version)*font_w)/2),
676 LCD_REMOTE_HEIGHT-font_h, (unsigned char *)version);
677 lcd_remote_setfont(FONT_UI);
678 lcd_remote_update();
679 #endif
681 return 0;
684 #if CONFIG_CODEC == SWCODEC
685 int get_replaygain_mode(bool have_track_gain, bool have_album_gain)
687 int type;
689 bool track = ((global_settings.replaygain_type == REPLAYGAIN_TRACK)
690 || ((global_settings.replaygain_type == REPLAYGAIN_SHUFFLE)
691 && global_settings.playlist_shuffle));
693 type = (!track && have_album_gain) ? REPLAYGAIN_ALBUM
694 : have_track_gain ? REPLAYGAIN_TRACK : -1;
696 return type;
698 #endif
700 #ifdef BOOTFILE
701 #if !defined(USB_NONE) && !defined(USB_HANDLED_BY_OF)
703 memorize/compare details about the BOOTFILE
704 we don't use dircache because it may not be up to date after
705 USB disconnect (scanning in the background)
707 void check_bootfile(bool do_rolo)
709 static unsigned short wrtdate = 0;
710 static unsigned short wrttime = 0;
711 DIR* dir = NULL;
712 struct dirent* entry = NULL;
714 /* 1. open BOOTDIR and find the BOOTFILE dir entry */
715 dir = opendir(BOOTDIR);
717 if(!dir) return; /* do we want an error splash? */
719 /* loop all files in BOOTDIR */
720 while(0 != (entry = readdir(dir)))
722 if(!strcasecmp(entry->d_name, BOOTFILE))
724 /* found the bootfile */
725 if(wrtdate && do_rolo)
727 if((entry->wrtdate != wrtdate) ||
728 (entry->wrttime != wrttime))
730 static const char *lines[] = { ID2P(LANG_BOOT_CHANGED),
731 ID2P(LANG_REBOOT_NOW) };
732 static const struct text_message message={ lines, 2 };
733 button_clear_queue(); /* Empty the keyboard buffer */
734 if(gui_syncyesno_run(&message, NULL, NULL) == YESNO_YES)
735 rolo_load(BOOTDIR "/" BOOTFILE);
738 wrtdate = entry->wrtdate;
739 wrttime = entry->wrttime;
742 closedir(dir);
744 #endif
745 #endif
747 /* check range, set volume and save settings */
748 void setvol(void)
750 const int min_vol = sound_min(SOUND_VOLUME);
751 const int max_vol = sound_max(SOUND_VOLUME);
752 if (global_settings.volume < min_vol)
753 global_settings.volume = min_vol;
754 if (global_settings.volume > max_vol)
755 global_settings.volume = max_vol;
756 sound_set_volume(global_settings.volume);
757 settings_save();
760 char* strrsplt(char* str, int c)
762 char* s = strrchr(str, c);
764 if (s != NULL)
766 *s++ = '\0';
768 else
770 s = str;
773 return s;
776 /* Test file existence, using dircache of possible */
777 bool file_exists(const char *file)
779 int fd;
781 if (!file || strlen(file) <= 0)
782 return false;
784 #ifdef HAVE_DIRCACHE
785 if (dircache_is_enabled())
786 return (dircache_get_entry_ptr(file) != NULL);
787 #endif
789 fd = open(file, O_RDONLY);
790 if (fd < 0)
791 return false;
792 close(fd);
793 return true;
796 bool dir_exists(const char *path)
798 DIR* d = opendir(path);
799 if (!d)
800 return false;
801 closedir(d);
802 return true;
806 * removes the extension of filename (if it doesn't start with a .)
807 * puts the result in buffer
809 char *strip_extension(char* buffer, int buffer_size, const char *filename)
811 char *dot = strrchr(filename, '.');
812 int len;
814 if (buffer_size <= 0)
816 return NULL;
819 buffer_size--; /* Make room for end nil */
821 if (dot != 0 && filename[0] != '.')
823 len = dot - filename;
824 len = MIN(len, buffer_size);
826 else
828 len = buffer_size;
831 strlcpy(buffer, filename, len + 1);
833 return buffer;
835 #endif /* !defined(__PCTOOL__) */
837 char* skip_whitespace(char* const str)
839 char *s = str;
841 while (isspace(*s))
842 s++;
844 return s;
847 /* Format time into buf.
849 * buf - buffer to format to.
850 * buf_size - size of buffer.
851 * t - time to format, in milliseconds.
853 void format_time(char* buf, int buf_size, long t)
855 if ( t < 3600000 )
857 snprintf(buf, buf_size, "%d:%02d",
858 (int) (t / 60000), (int) (t % 60000 / 1000));
860 else
862 snprintf(buf, buf_size, "%d:%02d:%02d",
863 (int) (t / 3600000), (int) (t % 3600000 / 60000),
864 (int) (t % 60000 / 1000));
869 /** Open a UTF-8 file and set file descriptor to first byte after BOM.
870 * If no BOM is present this behaves like open().
871 * If the file is opened for writing and O_TRUNC is set, write a BOM to
872 * the opened file and leave the file pointer set after the BOM.
874 #define BOM "\xef\xbb\xbf"
875 #define BOM_SIZE 3
877 int open_utf8(const char* pathname, int flags)
879 int fd;
880 unsigned char bom[BOM_SIZE];
882 fd = open(pathname, flags);
883 if(fd < 0)
884 return fd;
886 if(flags & (O_TRUNC | O_WRONLY))
888 write(fd, BOM, BOM_SIZE);
890 else
892 read(fd, bom, BOM_SIZE);
893 /* check for BOM */
894 if(memcmp(bom, BOM, BOM_SIZE))
895 lseek(fd, 0, SEEK_SET);
897 return fd;
901 #ifdef HAVE_LCD_COLOR
903 * Helper function to convert a string of 6 hex digits to a native colour
906 static int hex2dec(int c)
908 return (((c) >= '0' && ((c) <= '9')) ? (c) - '0' :
909 (toupper(c)) - 'A' + 10);
912 int hex_to_rgb(const char* hex, int* color)
914 int red, green, blue;
915 int i = 0;
917 while ((i < 6) && (isxdigit(hex[i])))
918 i++;
920 if (i < 6)
921 return -1;
923 red = (hex2dec(hex[0]) << 4) | hex2dec(hex[1]);
924 green = (hex2dec(hex[2]) << 4) | hex2dec(hex[3]);
925 blue = (hex2dec(hex[4]) << 4) | hex2dec(hex[5]);
927 *color = LCD_RGBPACK(red,green,blue);
929 return 0;
931 #endif /* HAVE_LCD_COLOR */
933 #ifdef HAVE_LCD_BITMAP
934 /* A simplified scanf - used (at time of writing) by wps parsing functions.
936 fmt - char array specifying the format of each list option. Valid values
937 are: d - int
938 s - string (sets pointer to string, without copying)
939 c - hex colour (RGB888 - e.g. ff00ff)
940 g - greyscale "colour" (0-3)
941 set_vals - if not NULL 1 is set in the bitplace if the item was read OK
942 0 if not read.
943 first item is LSB, (max 32 items! )
944 Stops parseing if an item is invalid unless the item == '-'
945 sep - list separator (e.g. ',' or '|')
946 str - string to parse, must be terminated by 0 or sep
947 ... - pointers to store the parsed values
949 return value - pointer to char after parsed data, 0 if there was an error.
953 /* '0'-'3' are ASCII 0x30 to 0x33 */
954 #define is0123(x) (((x) & 0xfc) == 0x30)
956 const char* parse_list(const char *fmt, uint32_t *set_vals,
957 const char sep, const char* str, ...)
959 va_list ap;
960 const char* p = str, *f = fmt;
961 const char** s;
962 int* d;
963 bool set;
964 int i=0;
966 va_start(ap, str);
967 if (set_vals)
968 *set_vals = 0;
969 while (*fmt)
971 /* Check for separator, if we're not at the start */
972 if (f != fmt)
974 if (*p != sep)
975 goto err;
976 p++;
978 set = false;
979 switch (*fmt++)
981 case 's': /* string - return a pointer to it (not a copy) */
982 s = va_arg(ap, const char **);
984 *s = p;
985 while (*p && *p != sep)
986 p++;
987 set = (s[0][0]!='-') && (s[0][1]!=sep) ;
988 break;
990 case 'd': /* int */
991 d = va_arg(ap, int*);
992 if (!isdigit(*p))
994 if (!set_vals || *p != '-')
995 goto err;
996 while (*p && *p != sep)
997 p++;
999 else
1001 *d = *p++ - '0';
1002 while (isdigit(*p))
1003 *d = (*d * 10) + (*p++ - '0');
1004 set = true;
1007 break;
1009 #ifdef HAVE_LCD_COLOR
1010 case 'c': /* colour (rrggbb - e.g. f3c1a8) */
1011 d = va_arg(ap, int*);
1013 if (hex_to_rgb(p, d) < 0)
1015 if (!set_vals || *p != '-')
1016 goto err;
1017 while (*p && *p != sep)
1018 p++;
1020 else
1022 p += 6;
1023 set = true;
1026 break;
1027 #endif
1029 #if LCD_DEPTH == 2 || (defined(HAVE_REMOTE_LCD) && LCD_REMOTE_DEPTH == 2)
1030 case 'g': /* greyscale colour (0-3) */
1031 d = va_arg(ap, int*);
1033 if (is0123(*p))
1035 *d = *p++ - '0';
1036 set = true;
1038 else if (!set_vals || *p != '-')
1039 goto err;
1040 else
1042 while (*p && *p != sep)
1043 p++;
1046 break;
1047 #endif
1049 default: /* Unknown format type */
1050 goto err;
1051 break;
1053 if (set_vals && set)
1054 *set_vals |= BIT_N(i);
1055 i++;
1058 va_end(ap);
1059 return p;
1061 err:
1062 va_end(ap);
1063 return 0;
1065 #endif