Meizu: update backlight brightness curve so backlight is still on at the minimum...
[kugel-rb.git] / apps / misc.c
blob2e7051cbd38c4aa499264bc3877c78559cc87db7
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 "appevents.h"
34 #include "lang.h"
35 #include "dir.h"
36 #include "lcd-remote.h"
37 #include "errno.h"
38 #include "system.h"
39 #include "timefuncs.h"
40 #include "screens.h"
41 #include "talk.h"
42 #include "mpeg.h"
43 #include "audio.h"
44 #include "mp3_playback.h"
45 #include "settings.h"
46 #include "storage.h"
47 #include "ata_idle_notify.h"
48 #include "kernel.h"
49 #include "power.h"
50 #include "powermgmt.h"
51 #include "backlight.h"
52 #include "version.h"
53 #include "font.h"
54 #include "splash.h"
55 #include "tagcache.h"
56 #include "scrobbler.h"
57 #include "sound.h"
58 #include "playlist.h"
59 #include "yesno.h"
60 #include "viewport.h"
62 #ifdef IPOD_ACCESSORY_PROTOCOL
63 #include "iap.h"
64 #endif
66 #if (CONFIG_STORAGE & STORAGE_MMC)
67 #include "ata_mmc.h"
68 #endif
69 #include "tree.h"
70 #include "eeprom_settings.h"
71 #if defined(HAVE_RECORDING) && !defined(__PCTOOL__)
72 #include "recording.h"
73 #endif
74 #if defined(HAVE_LCD_BITMAP) && !defined(__PCTOOL__)
75 #include "bmp.h"
76 #include "icons.h"
77 #endif /* End HAVE_LCD_BITMAP */
78 #include "bookmark.h"
79 #include "music_screen.h"
80 #include "playback.h"
82 #ifdef BOOTFILE
83 #if !defined(USB_NONE) && !defined(USB_HANDLED_BY_OF)
84 #include "rolo.h"
85 #include "yesno.h"
86 #endif
87 #endif
89 /* Format a large-range value for output, using the appropriate unit so that
90 * the displayed value is in the range 1 <= display < 1000 (1024 for "binary"
91 * units) if possible, and 3 significant digits are shown. If a buffer is
92 * given, the result is snprintf()'d into that buffer, otherwise the result is
93 * voiced.*/
94 char *output_dyn_value(char *buf, int buf_size, int value,
95 const unsigned char **units, bool bin_scale)
97 int scale = bin_scale ? 1024 : 1000;
98 int fraction = 0;
99 int unit_no = 0;
100 char tbuf[5];
102 while (value >= scale)
104 fraction = value % scale;
105 value /= scale;
106 unit_no++;
108 if (bin_scale)
109 fraction = fraction * 1000 / 1024;
111 if (value >= 100 || !unit_no)
112 tbuf[0] = '\0';
113 else if (value >= 10)
114 snprintf(tbuf, sizeof(tbuf), "%01d", fraction / 100);
115 else
116 snprintf(tbuf, sizeof(tbuf), "%02d", fraction / 10);
118 if (buf)
120 if (strlen(tbuf))
121 snprintf(buf, buf_size, "%d%s%s%s", value, str(LANG_POINT),
122 tbuf, P2STR(units[unit_no]));
123 else
124 snprintf(buf, buf_size, "%d%s", value, P2STR(units[unit_no]));
126 else
128 talk_fractional(tbuf, value, P2ID(units[unit_no]));
130 return buf;
133 /* Ask the user if they really want to erase the current dynamic playlist
134 * returns true if the playlist should be replaced */
135 bool warn_on_pl_erase(void)
137 if (global_settings.warnon_erase_dynplaylist &&
138 !global_settings.party_mode &&
139 playlist_modified(NULL))
141 static const char *lines[] =
142 {ID2P(LANG_WARN_ERASEDYNPLAYLIST_PROMPT)};
143 static const struct text_message message={lines, 1};
145 return (gui_syncyesno_run(&message, NULL, NULL) == YESNO_YES);
147 else
148 return true;
151 /* Read (up to) a line of text from fd into buffer and return number of bytes
152 * read (which may be larger than the number of bytes stored in buffer). If
153 * an error occurs, -1 is returned (and buffer contains whatever could be
154 * read). A line is terminated by a LF char. Neither LF nor CR chars are
155 * stored in buffer.
157 int read_line(int fd, char* buffer, int buffer_size)
159 int count = 0;
160 int num_read = 0;
162 errno = 0;
164 while (count < buffer_size)
166 unsigned char c;
168 if (1 != read(fd, &c, 1))
169 break;
171 num_read++;
173 if ( c == '\n' )
174 break;
176 if ( c == '\r' )
177 continue;
179 buffer[count++] = c;
182 buffer[MIN(count, buffer_size - 1)] = 0;
184 return errno ? -1 : num_read;
187 /* Performance optimized version of the previous function. */
188 int fast_readline(int fd, char *buf, int buf_size, void *parameters,
189 int (*callback)(int n, const char *buf, void *parameters))
191 char *p, *next;
192 int rc, pos = 0;
193 int count = 0;
195 while ( 1 )
197 next = NULL;
199 rc = read(fd, &buf[pos], buf_size - pos - 1);
200 if (rc >= 0)
201 buf[pos+rc] = '\0';
203 if ( (p = strchr(buf, '\r')) != NULL)
205 *p = '\0';
206 next = ++p;
208 else
209 p = buf;
211 if ( (p = strchr(p, '\n')) != NULL)
213 *p = '\0';
214 next = ++p;
217 rc = callback(count, buf, parameters);
218 if (rc < 0)
219 return rc;
221 count++;
222 if (next)
224 pos = buf_size - ((long)next - (long)buf) - 1;
225 memmove(buf, next, pos);
227 else
228 break ;
231 return 0;
234 /* parse a line from a configuration file. the line format is:
236 name: value
238 Any whitespace before setting name or value (after ':') is ignored.
239 A # as first non-whitespace character discards the whole line.
240 Function sets pointers to null-terminated setting name and value.
241 Returns false if no valid config entry was found.
244 bool settings_parseline(char* line, char** name, char** value)
246 char* ptr;
248 line = skip_whitespace(line);
250 if ( *line == '#' )
251 return false;
253 ptr = strchr(line, ':');
254 if ( !ptr )
255 return false;
257 *name = line;
258 *ptr = 0;
259 ptr++;
260 ptr = skip_whitespace(ptr);
261 *value = ptr;
262 return true;
265 static void system_flush(void)
267 scrobbler_shutdown();
268 playlist_shutdown();
269 tree_flush();
270 call_storage_idle_notifys(true); /*doesnt work on usb and shutdown from ata thread */
273 static void system_restore(void)
275 tree_restore();
276 scrobbler_init();
279 static bool clean_shutdown(void (*callback)(void *), void *parameter)
281 #ifdef SIMULATOR
282 (void)callback;
283 (void)parameter;
284 bookmark_autobookmark();
285 call_storage_idle_notifys(true);
286 exit(0);
287 #else
288 long msg_id = -1;
289 int i;
291 scrobbler_poweroff();
293 #if CONFIG_CHARGING && !defined(HAVE_POWEROFF_WHILE_CHARGING)
294 if(!charger_inserted())
295 #endif
297 bool batt_safe = battery_level_safe();
298 int audio_stat = audio_status();
300 FOR_NB_SCREENS(i)
302 screens[i].clear_display();
303 screens[i].update();
306 if (batt_safe)
308 #ifdef HAVE_TAGCACHE
309 if (!tagcache_prepare_shutdown())
311 cancel_shutdown();
312 splash(HZ, ID2P(LANG_TAGCACHE_BUSY));
313 return false;
315 #endif
316 if (battery_level() > 10)
317 splash(0, str(LANG_SHUTTINGDOWN));
318 else
320 msg_id = LANG_WARNING_BATTERY_LOW;
321 splashf(0, "%s %s", str(LANG_WARNING_BATTERY_LOW),
322 str(LANG_SHUTTINGDOWN));
325 else
327 msg_id = LANG_WARNING_BATTERY_EMPTY;
328 splashf(0, "%s %s", str(LANG_WARNING_BATTERY_EMPTY),
329 str(LANG_SHUTTINGDOWN));
332 if (global_settings.fade_on_stop
333 && (audio_stat & AUDIO_STATUS_PLAY))
335 fade(false, false);
338 if (batt_safe) /* do not save on critical battery */
340 #if defined(HAVE_RECORDING) && CONFIG_CODEC == SWCODEC
341 if (audio_stat & AUDIO_STATUS_RECORD)
343 rec_command(RECORDING_CMD_STOP);
344 /* wait for stop to complete */
345 while (audio_status() & AUDIO_STATUS_RECORD)
346 sleep(1);
348 #endif
349 bookmark_autobookmark();
351 /* audio_stop_recording == audio_stop for HWCODEC */
352 audio_stop();
354 if (callback != NULL)
355 callback(parameter);
357 #if CONFIG_CODEC != SWCODEC
358 /* wait for audio_stop or audio_stop_recording to complete */
359 while (audio_status())
360 sleep(1);
361 #endif
363 #if defined(HAVE_RECORDING) && CONFIG_CODEC == SWCODEC
364 audio_close_recording();
365 #endif
367 if(global_settings.talk_menu)
369 bool enqueue = false;
370 if(msg_id != -1)
372 talk_id(msg_id, enqueue);
373 enqueue = true;
375 talk_id(LANG_SHUTTINGDOWN, enqueue);
376 #if CONFIG_CODEC == SWCODEC
377 voice_wait();
378 #endif
381 system_flush();
382 #ifdef HAVE_EEPROM_SETTINGS
383 if (firmware_settings.initialized)
385 firmware_settings.disk_clean = true;
386 firmware_settings.bl_version = 0;
387 eeprom_settings_store();
389 #endif
391 #ifdef HAVE_DIRCACHE
392 else
393 dircache_disable();
394 #endif
396 shutdown_hw();
398 #endif
399 return false;
402 bool list_stop_handler(void)
404 bool ret = false;
406 /* Stop the music if it is playing */
407 if(audio_status())
409 if (!global_settings.party_mode)
411 if (global_settings.fade_on_stop)
412 fade(false, false);
413 bookmark_autobookmark();
414 audio_stop();
415 ret = true; /* bookmarking can make a refresh necessary */
418 #if CONFIG_CHARGING
419 #if (CONFIG_KEYPAD == RECORDER_PAD) && !defined(HAVE_SW_POWEROFF)
420 else
422 if (charger_inserted())
423 charging_splash();
424 else
425 shutdown_screen(); /* won't return if shutdown actually happens */
427 ret = true; /* screen is dirty, caller needs to refresh */
429 #endif
430 #ifndef HAVE_POWEROFF_WHILE_CHARGING
432 static long last_off = 0;
434 if (TIME_BEFORE(current_tick, last_off + HZ/2))
436 if (charger_inserted())
438 charging_splash();
439 ret = true; /* screen is dirty, caller needs to refresh */
442 last_off = current_tick;
444 #endif
445 #endif /* CONFIG_CHARGING */
446 return ret;
449 #if CONFIG_CHARGING
450 static bool waiting_to_resume_play = false;
451 static long play_resume_tick;
453 static void car_adapter_mode_processing(bool inserted)
455 if (global_settings.car_adapter_mode)
457 if(inserted)
460 * Just got plugged in, delay & resume if we were playing
462 if (audio_status() & AUDIO_STATUS_PAUSE)
464 /* delay resume a bit while the engine is cranking */
465 play_resume_tick = current_tick + HZ*5;
466 waiting_to_resume_play = true;
469 else
472 * Just got unplugged, pause if playing
474 if ((audio_status() & AUDIO_STATUS_PLAY) &&
475 !(audio_status() & AUDIO_STATUS_PAUSE))
477 if (global_settings.fade_on_stop)
478 fade(false, false);
479 else
480 audio_pause();
482 waiting_to_resume_play = false;
487 static void car_adapter_tick(void)
489 if (waiting_to_resume_play)
491 if (TIME_AFTER(current_tick, play_resume_tick))
493 if (audio_status() & AUDIO_STATUS_PAUSE)
495 queue_broadcast(SYS_CAR_ADAPTER_RESUME, 0);
497 waiting_to_resume_play = false;
502 void car_adapter_mode_init(void)
504 tick_add_task(car_adapter_tick);
506 #endif
508 #ifdef HAVE_HEADPHONE_DETECTION
509 static void unplug_change(bool inserted)
511 static bool headphone_caused_pause = false;
513 if (global_settings.unplug_mode)
515 int audio_stat = audio_status();
516 if (inserted)
518 if ((audio_stat & AUDIO_STATUS_PLAY) &&
519 headphone_caused_pause &&
520 global_settings.unplug_mode > 1 )
521 audio_resume();
522 backlight_on();
523 headphone_caused_pause = false;
524 } else {
525 if ((audio_stat & AUDIO_STATUS_PLAY) &&
526 !(audio_stat & AUDIO_STATUS_PAUSE))
528 headphone_caused_pause = true;
529 audio_pause();
531 if (global_settings.unplug_rw)
533 if (audio_current_track()->elapsed >
534 (unsigned long)(global_settings.unplug_rw*1000))
535 audio_ff_rewind(audio_current_track()->elapsed -
536 (global_settings.unplug_rw*1000));
537 else
538 audio_ff_rewind(0);
544 #endif
546 long default_event_handler_ex(long event, void (*callback)(void *), void *parameter)
548 switch(event)
550 case SYS_BATTERY_UPDATE:
551 if(global_settings.talk_battery_level)
553 talk_ids(true, VOICE_PAUSE, VOICE_PAUSE,
554 LANG_BATTERY_TIME,
555 TALK_ID(battery_level(), UNIT_PERCENT),
556 VOICE_PAUSE);
557 talk_force_enqueue_next();
559 break;
560 case SYS_USB_CONNECTED:
561 if (callback != NULL)
562 callback(parameter);
563 #if (CONFIG_STORAGE & STORAGE_MMC)
564 if (!mmc_touched() ||
565 (mmc_remove_request() == SYS_HOTSWAP_EXTRACTED))
566 #endif
568 system_flush();
569 #ifdef BOOTFILE
570 #if !defined(USB_NONE) && !defined(USB_HANDLED_BY_OF)
571 check_bootfile(false); /* gets initial size */
572 #endif
573 #endif
574 usb_screen();
575 #ifdef BOOTFILE
576 #if !defined(USB_NONE) && !defined(USB_HANDLED_BY_OF)
577 check_bootfile(true);
578 #endif
579 #endif
580 system_restore();
582 return SYS_USB_CONNECTED;
583 case SYS_POWEROFF:
584 if (!clean_shutdown(callback, parameter))
585 return SYS_POWEROFF;
586 break;
587 #if CONFIG_CHARGING
588 case SYS_CHARGER_CONNECTED:
589 car_adapter_mode_processing(true);
590 return SYS_CHARGER_CONNECTED;
592 case SYS_CHARGER_DISCONNECTED:
593 car_adapter_mode_processing(false);
594 return SYS_CHARGER_DISCONNECTED;
596 case SYS_CAR_ADAPTER_RESUME:
597 audio_resume();
598 return SYS_CAR_ADAPTER_RESUME;
599 #endif
600 #ifdef HAVE_HEADPHONE_DETECTION
601 case SYS_PHONE_PLUGGED:
602 unplug_change(true);
603 return SYS_PHONE_PLUGGED;
605 case SYS_PHONE_UNPLUGGED:
606 unplug_change(false);
607 return SYS_PHONE_UNPLUGGED;
608 #endif
609 #ifdef IPOD_ACCESSORY_PROTOCOL
610 case SYS_IAP_PERIODIC:
611 iap_periodic();
612 return SYS_IAP_PERIODIC;
613 case SYS_IAP_HANDLEPKT:
614 iap_handlepkt();
615 return SYS_IAP_HANDLEPKT;
616 #endif
618 return 0;
621 long default_event_handler(long event)
623 return default_event_handler_ex(event, NULL, NULL);
626 int show_logo( void )
628 #ifdef HAVE_LCD_BITMAP
629 char version[32];
630 int font_h, font_w;
632 snprintf(version, sizeof(version), "Ver. %s", appsversion);
634 lcd_clear_display();
635 #ifdef SANSA_CLIP /* display the logo in the blue area of the screen */
636 lcd_setfont(FONT_SYSFIXED);
637 lcd_getstringsize((unsigned char *)"A", &font_w, &font_h);
638 lcd_putsxy((LCD_WIDTH/2) - ((strlen(version)*font_w)/2),
639 0, (unsigned char *)version);
640 lcd_bitmap(rockboxlogo, 0, 16, BMPWIDTH_rockboxlogo, BMPHEIGHT_rockboxlogo);
641 #else
642 lcd_bitmap(rockboxlogo, 0, 10, BMPWIDTH_rockboxlogo, BMPHEIGHT_rockboxlogo);
643 lcd_setfont(FONT_SYSFIXED);
644 lcd_getstringsize((unsigned char *)"A", &font_w, &font_h);
645 lcd_putsxy((LCD_WIDTH/2) - ((strlen(version)*font_w)/2),
646 LCD_HEIGHT-font_h, (unsigned char *)version);
647 #endif
648 lcd_setfont(FONT_UI);
650 #else
651 char *rockbox = " ROCKbox!";
653 lcd_clear_display();
654 lcd_double_height(true);
655 lcd_puts(0, 0, rockbox);
656 lcd_puts_scroll(0, 1, appsversion);
657 #endif
658 lcd_update();
660 #ifdef HAVE_REMOTE_LCD
661 lcd_remote_clear_display();
662 lcd_remote_bitmap(remote_rockboxlogo, 0, 10, BMPWIDTH_remote_rockboxlogo,
663 BMPHEIGHT_remote_rockboxlogo);
664 lcd_remote_setfont(FONT_SYSFIXED);
665 lcd_remote_getstringsize((unsigned char *)"A", &font_w, &font_h);
666 lcd_remote_putsxy((LCD_REMOTE_WIDTH/2) - ((strlen(version)*font_w)/2),
667 LCD_REMOTE_HEIGHT-font_h, (unsigned char *)version);
668 lcd_remote_setfont(FONT_UI);
669 lcd_remote_update();
670 #endif
672 return 0;
675 #if CONFIG_CODEC == SWCODEC
676 int get_replaygain_mode(bool have_track_gain, bool have_album_gain)
678 int type;
680 bool track = ((global_settings.replaygain_type == REPLAYGAIN_TRACK)
681 || ((global_settings.replaygain_type == REPLAYGAIN_SHUFFLE)
682 && global_settings.playlist_shuffle));
684 type = (!track && have_album_gain) ? REPLAYGAIN_ALBUM
685 : have_track_gain ? REPLAYGAIN_TRACK : -1;
687 return type;
689 #endif
691 #ifdef BOOTFILE
692 #if !defined(USB_NONE) && !defined(USB_HANDLED_BY_OF)
694 memorize/compare details about the BOOTFILE
695 we don't use dircache because it may not be up to date after
696 USB disconnect (scanning in the background)
698 void check_bootfile(bool do_rolo)
700 static unsigned short wrtdate = 0;
701 static unsigned short wrttime = 0;
702 DIR* dir = NULL;
703 struct dirent* entry = NULL;
705 /* 1. open BOOTDIR and find the BOOTFILE dir entry */
706 dir = opendir(BOOTDIR);
708 if(!dir) return; /* do we want an error splash? */
710 /* loop all files in BOOTDIR */
711 while(0 != (entry = readdir(dir)))
713 if(!strcasecmp(entry->d_name, BOOTFILE))
715 /* found the bootfile */
716 if(wrtdate && do_rolo)
718 if((entry->wrtdate != wrtdate) ||
719 (entry->wrttime != wrttime))
721 static const char *lines[] = { ID2P(LANG_BOOT_CHANGED),
722 ID2P(LANG_REBOOT_NOW) };
723 static const struct text_message message={ lines, 2 };
724 button_clear_queue(); /* Empty the keyboard buffer */
725 if(gui_syncyesno_run(&message, NULL, NULL) == YESNO_YES)
726 rolo_load(BOOTDIR "/" BOOTFILE);
729 wrtdate = entry->wrtdate;
730 wrttime = entry->wrttime;
733 closedir(dir);
735 #endif
736 #endif
738 /* check range, set volume and save settings */
739 void setvol(void)
741 const int min_vol = sound_min(SOUND_VOLUME);
742 const int max_vol = sound_max(SOUND_VOLUME);
743 if (global_settings.volume < min_vol)
744 global_settings.volume = min_vol;
745 if (global_settings.volume > max_vol)
746 global_settings.volume = max_vol;
747 sound_set_volume(global_settings.volume);
748 settings_save();
751 char* strrsplt(char* str, int c)
753 char* s = strrchr(str, c);
755 if (s != NULL)
757 *s++ = '\0';
759 else
761 s = str;
764 return s;
767 /* Test file existence, using dircache of possible */
768 bool file_exists(const char *file)
770 int fd;
772 if (!file || strlen(file) <= 0)
773 return false;
775 #ifdef HAVE_DIRCACHE
776 if (dircache_is_enabled())
777 return (dircache_get_entry_ptr(file) != NULL);
778 #endif
780 fd = open(file, O_RDONLY);
781 if (fd < 0)
782 return false;
783 close(fd);
784 return true;
787 bool dir_exists(const char *path)
789 DIR* d = opendir(path);
790 if (!d)
791 return false;
792 closedir(d);
793 return true;
797 * removes the extension of filename (if it doesn't start with a .)
798 * puts the result in buffer
800 char *strip_extension(char* buffer, int buffer_size, const char *filename)
802 char *dot = strrchr(filename, '.');
803 int len;
805 if (buffer_size <= 0)
807 return NULL;
810 buffer_size--; /* Make room for end nil */
812 if (dot != 0 && filename[0] != '.')
814 len = dot - filename;
815 len = MIN(len, buffer_size);
817 else
819 len = buffer_size;
822 strlcpy(buffer, filename, len + 1);
824 return buffer;
826 #endif /* !defined(__PCTOOL__) */
828 char* skip_whitespace(char* const str)
830 char *s = str;
832 while (isspace(*s))
833 s++;
835 return s;
838 /* Format time into buf.
840 * buf - buffer to format to.
841 * buf_size - size of buffer.
842 * t - time to format, in milliseconds.
844 void format_time(char* buf, int buf_size, long t)
846 if ( t < 3600000 )
848 snprintf(buf, buf_size, "%d:%02d",
849 (int) (t / 60000), (int) (t % 60000 / 1000));
851 else
853 snprintf(buf, buf_size, "%d:%02d:%02d",
854 (int) (t / 3600000), (int) (t % 3600000 / 60000),
855 (int) (t % 60000 / 1000));
860 /** Open a UTF-8 file and set file descriptor to first byte after BOM.
861 * If no BOM is present this behaves like open().
862 * If the file is opened for writing and O_TRUNC is set, write a BOM to
863 * the opened file and leave the file pointer set after the BOM.
865 #define BOM "\xef\xbb\xbf"
866 #define BOM_SIZE 3
868 int open_utf8(const char* pathname, int flags)
870 int fd;
871 unsigned char bom[BOM_SIZE];
873 fd = open(pathname, flags);
874 if(fd < 0)
875 return fd;
877 if(flags & (O_TRUNC | O_WRONLY))
879 write(fd, BOM, BOM_SIZE);
881 else
883 read(fd, bom, BOM_SIZE);
884 /* check for BOM */
885 if(memcmp(bom, BOM, BOM_SIZE))
886 lseek(fd, 0, SEEK_SET);
888 return fd;
892 #ifdef HAVE_LCD_COLOR
894 * Helper function to convert a string of 6 hex digits to a native colour
897 static int hex2dec(int c)
899 return (((c) >= '0' && ((c) <= '9')) ? (c) - '0' :
900 (toupper(c)) - 'A' + 10);
903 int hex_to_rgb(const char* hex, int* color)
905 int red, green, blue;
906 int i = 0;
908 while ((i < 6) && (isxdigit(hex[i])))
909 i++;
911 if (i < 6)
912 return -1;
914 red = (hex2dec(hex[0]) << 4) | hex2dec(hex[1]);
915 green = (hex2dec(hex[2]) << 4) | hex2dec(hex[3]);
916 blue = (hex2dec(hex[4]) << 4) | hex2dec(hex[5]);
918 *color = LCD_RGBPACK(red,green,blue);
920 return 0;
922 #endif /* HAVE_LCD_COLOR */
924 #ifdef HAVE_LCD_BITMAP
925 /* A simplified scanf - used (at time of writing) by wps parsing functions.
927 fmt - char array specifying the format of each list option. Valid values
928 are: d - int
929 s - string (sets pointer to string, without copying)
930 c - hex colour (RGB888 - e.g. ff00ff)
931 g - greyscale "colour" (0-3)
932 set_vals - if not NULL 1 is set in the bitplace if the item was read OK
933 0 if not read.
934 first item is LSB, (max 32 items! )
935 Stops parseing if an item is invalid unless the item == '-'
936 sep - list separator (e.g. ',' or '|')
937 str - string to parse, must be terminated by 0 or sep
938 ... - pointers to store the parsed values
940 return value - pointer to char after parsed data, 0 if there was an error.
944 /* '0'-'3' are ASCII 0x30 to 0x33 */
945 #define is0123(x) (((x) & 0xfc) == 0x30)
947 const char* parse_list(const char *fmt, uint32_t *set_vals,
948 const char sep, const char* str, ...)
950 va_list ap;
951 const char* p = str, *f = fmt;
952 const char** s;
953 int* d;
954 bool set;
955 int i=0;
957 va_start(ap, str);
958 if (set_vals)
959 *set_vals = 0;
960 while (*fmt)
962 /* Check for separator, if we're not at the start */
963 if (f != fmt)
965 if (*p != sep)
966 goto err;
967 p++;
969 set = false;
970 switch (*fmt++)
972 case 's': /* string - return a pointer to it (not a copy) */
973 s = va_arg(ap, const char **);
975 *s = p;
976 while (*p && *p != sep)
977 p++;
978 set = (s[0][0]!='-') && (s[0][1]!=sep) ;
979 break;
981 case 'd': /* int */
982 d = va_arg(ap, int*);
983 if (!isdigit(*p))
985 if (!set_vals || *p != '-')
986 goto err;
987 while (*p && *p != sep)
988 p++;
990 else
992 *d = *p++ - '0';
993 while (isdigit(*p))
994 *d = (*d * 10) + (*p++ - '0');
995 set = true;
998 break;
1000 #ifdef HAVE_LCD_COLOR
1001 case 'c': /* colour (rrggbb - e.g. f3c1a8) */
1002 d = va_arg(ap, int*);
1004 if (hex_to_rgb(p, d) < 0)
1006 if (!set_vals || *p != '-')
1007 goto err;
1008 while (*p && *p != sep)
1009 p++;
1011 else
1013 p += 6;
1014 set = true;
1017 break;
1018 #endif
1020 #if LCD_DEPTH == 2 || (defined(HAVE_REMOTE_LCD) && LCD_REMOTE_DEPTH == 2)
1021 case 'g': /* greyscale colour (0-3) */
1022 d = va_arg(ap, int*);
1024 if (is0123(*p))
1026 *d = *p++ - '0';
1027 set = true;
1029 else if (!set_vals || *p != '-')
1030 goto err;
1031 else
1033 while (*p && *p != sep)
1034 p++;
1037 break;
1038 #endif
1040 default: /* Unknown format type */
1041 goto err;
1042 break;
1044 if (set_vals && set)
1045 *set_vals |= BIT_N(i);
1046 i++;
1049 va_end(ap);
1050 return p;
1052 err:
1053 va_end(ap);
1054 return 0;
1056 #endif