Clarify comment and clean up a bit (FS#10227 by Tomer Shalev)
[kugel-rb.git] / apps / misc.c
blob930afe34f8e3aee04f9fed3c243f66b4db401671
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 "gui/gwps-common.h"
79 #include "bookmark.h"
81 #include "playback.h"
83 #ifdef BOOTFILE
84 #if !defined(USB_NONE) && !defined(USB_HANDLED_BY_OF)
85 #include "rolo.h"
86 #include "yesno.h"
87 #endif
88 #endif
90 /* Format a large-range value for output, using the appropriate unit so that
91 * the displayed value is in the range 1 <= display < 1000 (1024 for "binary"
92 * units) if possible, and 3 significant digits are shown. If a buffer is
93 * given, the result is snprintf()'d into that buffer, otherwise the result is
94 * voiced.*/
95 char *output_dyn_value(char *buf, int buf_size, int value,
96 const unsigned char **units, bool bin_scale)
98 int scale = bin_scale ? 1024 : 1000;
99 int fraction = 0;
100 int unit_no = 0;
101 char tbuf[5];
103 while (value >= scale)
105 fraction = value % scale;
106 value /= scale;
107 unit_no++;
109 if (bin_scale)
110 fraction = fraction * 1000 / 1024;
112 if (value >= 100 || !unit_no)
113 tbuf[0] = '\0';
114 else if (value >= 10)
115 snprintf(tbuf, sizeof(tbuf), "%01d", fraction / 100);
116 else
117 snprintf(tbuf, sizeof(tbuf), "%02d", fraction / 10);
119 if (buf)
121 if (strlen(tbuf))
122 snprintf(buf, buf_size, "%d%s%s%s", value, str(LANG_POINT),
123 tbuf, P2STR(units[unit_no]));
124 else
125 snprintf(buf, buf_size, "%d%s", value, P2STR(units[unit_no]));
127 else
129 talk_fractional(tbuf, value, P2ID(units[unit_no]));
131 return buf;
134 /* Ask the user if they really want to erase the current dynamic playlist
135 * returns true if the playlist should be replaced */
136 bool warn_on_pl_erase(void)
138 if (global_settings.warnon_erase_dynplaylist &&
139 !global_settings.party_mode &&
140 playlist_modified(NULL))
142 static const char *lines[] =
143 {ID2P(LANG_WARN_ERASEDYNPLAYLIST_PROMPT)};
144 static const struct text_message message={lines, 1};
146 return (gui_syncyesno_run(&message, NULL, NULL) == YESNO_YES);
148 else
149 return true;
152 /* Read (up to) a line of text from fd into buffer and return number of bytes
153 * read (which may be larger than the number of bytes stored in buffer). If
154 * an error occurs, -1 is returned (and buffer contains whatever could be
155 * read). A line is terminated by a LF char. Neither LF nor CR chars are
156 * stored in buffer.
158 int read_line(int fd, char* buffer, int buffer_size)
160 int count = 0;
161 int num_read = 0;
163 errno = 0;
165 while (count < buffer_size)
167 unsigned char c;
169 if (1 != read(fd, &c, 1))
170 break;
172 num_read++;
174 if ( c == '\n' )
175 break;
177 if ( c == '\r' )
178 continue;
180 buffer[count++] = c;
183 buffer[MIN(count, buffer_size - 1)] = 0;
185 return errno ? -1 : num_read;
188 /* Performance optimized version of the previous function. */
189 int fast_readline(int fd, char *buf, int buf_size, void *parameters,
190 int (*callback)(int n, const char *buf, void *parameters))
192 char *p, *next;
193 int rc, pos = 0;
194 int count = 0;
196 while ( 1 )
198 next = NULL;
200 rc = read(fd, &buf[pos], buf_size - pos - 1);
201 if (rc >= 0)
202 buf[pos+rc] = '\0';
204 if ( (p = strchr(buf, '\r')) != NULL)
206 *p = '\0';
207 next = ++p;
209 else
210 p = buf;
212 if ( (p = strchr(p, '\n')) != NULL)
214 *p = '\0';
215 next = ++p;
218 rc = callback(count, buf, parameters);
219 if (rc < 0)
220 return rc;
222 count++;
223 if (next)
225 pos = buf_size - ((long)next - (long)buf) - 1;
226 memmove(buf, next, pos);
228 else
229 break ;
232 return 0;
235 /* parse a line from a configuration file. the line format is:
237 name: value
239 Any whitespace before setting name or value (after ':') is ignored.
240 A # as first non-whitespace character discards the whole line.
241 Function sets pointers to null-terminated setting name and value.
242 Returns false if no valid config entry was found.
245 bool settings_parseline(char* line, char** name, char** value)
247 char* ptr;
249 line = skip_whitespace(line);
251 if ( *line == '#' )
252 return false;
254 ptr = strchr(line, ':');
255 if ( !ptr )
256 return false;
258 *name = line;
259 *ptr = 0;
260 ptr++;
261 ptr = skip_whitespace(ptr);
262 *value = ptr;
263 return true;
266 static void system_flush(void)
268 scrobbler_shutdown();
269 playlist_shutdown();
270 tree_flush();
271 call_storage_idle_notifys(true); /*doesnt work on usb and shutdown from ata thread */
274 static void system_restore(void)
276 tree_restore();
277 scrobbler_init();
280 static bool clean_shutdown(void (*callback)(void *), void *parameter)
282 #ifdef SIMULATOR
283 (void)callback;
284 (void)parameter;
285 bookmark_autobookmark();
286 call_storage_idle_notifys(true);
287 exit(0);
288 #else
289 long msg_id = -1;
290 int i;
292 scrobbler_poweroff();
294 #if CONFIG_CHARGING && !defined(HAVE_POWEROFF_WHILE_CHARGING)
295 if(!charger_inserted())
296 #endif
298 bool batt_safe = battery_level_safe();
299 int audio_stat = audio_status();
301 FOR_NB_SCREENS(i)
302 screens[i].clear_display();
304 if (batt_safe)
306 #ifdef HAVE_TAGCACHE
307 if (!tagcache_prepare_shutdown())
309 cancel_shutdown();
310 splash(HZ, ID2P(LANG_TAGCACHE_BUSY));
311 return false;
313 #endif
314 if (battery_level() > 10)
315 splash(0, str(LANG_SHUTTINGDOWN));
316 else
318 msg_id = LANG_WARNING_BATTERY_LOW;
319 splashf(0, "%s %s", str(LANG_WARNING_BATTERY_LOW),
320 str(LANG_SHUTTINGDOWN));
323 else
325 msg_id = LANG_WARNING_BATTERY_EMPTY;
326 splashf(0, "%s %s", str(LANG_WARNING_BATTERY_EMPTY),
327 str(LANG_SHUTTINGDOWN));
330 if (global_settings.fade_on_stop
331 && (audio_stat & AUDIO_STATUS_PLAY))
333 fade(false, false);
336 if (batt_safe) /* do not save on critical battery */
338 #if defined(HAVE_RECORDING) && CONFIG_CODEC == SWCODEC
339 if (audio_stat & AUDIO_STATUS_RECORD)
341 rec_command(RECORDING_CMD_STOP);
342 /* wait for stop to complete */
343 while (audio_status() & AUDIO_STATUS_RECORD)
344 sleep(1);
346 #endif
347 bookmark_autobookmark();
349 /* audio_stop_recording == audio_stop for HWCODEC */
350 audio_stop();
352 if (callback != NULL)
353 callback(parameter);
355 #if CONFIG_CODEC != SWCODEC
356 /* wait for audio_stop or audio_stop_recording to complete */
357 while (audio_status())
358 sleep(1);
359 #endif
361 #if defined(HAVE_RECORDING) && CONFIG_CODEC == SWCODEC
362 audio_close_recording();
363 #endif
365 if(global_settings.talk_menu)
367 bool enqueue = false;
368 if(msg_id != -1)
370 talk_id(msg_id, enqueue);
371 enqueue = true;
373 talk_id(LANG_SHUTTINGDOWN, enqueue);
374 #if CONFIG_CODEC == SWCODEC
375 voice_wait();
376 #endif
379 system_flush();
380 #ifdef HAVE_EEPROM_SETTINGS
381 if (firmware_settings.initialized)
383 firmware_settings.disk_clean = true;
384 firmware_settings.bl_version = 0;
385 eeprom_settings_store();
387 #endif
389 #ifdef HAVE_DIRCACHE
390 else
391 dircache_disable();
392 #endif
394 shutdown_hw();
396 #endif
397 return false;
400 bool list_stop_handler(void)
402 bool ret = false;
404 /* Stop the music if it is playing */
405 if(audio_status())
407 if (!global_settings.party_mode)
409 if (global_settings.fade_on_stop)
410 fade(false, false);
411 bookmark_autobookmark();
412 audio_stop();
413 ret = true; /* bookmarking can make a refresh necessary */
416 #if CONFIG_CHARGING
417 #if (CONFIG_KEYPAD == RECORDER_PAD) && !defined(HAVE_SW_POWEROFF)
418 else
420 if (charger_inserted())
421 charging_splash();
422 else
423 shutdown_screen(); /* won't return if shutdown actually happens */
425 ret = true; /* screen is dirty, caller needs to refresh */
427 #endif
428 #ifndef HAVE_POWEROFF_WHILE_CHARGING
430 static long last_off = 0;
432 if (TIME_BEFORE(current_tick, last_off + HZ/2))
434 if (charger_inserted())
436 charging_splash();
437 ret = true; /* screen is dirty, caller needs to refresh */
440 last_off = current_tick;
442 #endif
443 #endif /* CONFIG_CHARGING */
444 return ret;
447 #if CONFIG_CHARGING
448 static bool waiting_to_resume_play = false;
449 static long play_resume_tick;
451 static void car_adapter_mode_processing(bool inserted)
453 if (global_settings.car_adapter_mode)
455 if(inserted)
458 * Just got plugged in, delay & resume if we were playing
460 if (audio_status() & AUDIO_STATUS_PAUSE)
462 /* delay resume a bit while the engine is cranking */
463 play_resume_tick = current_tick + HZ*5;
464 waiting_to_resume_play = true;
467 else
470 * Just got unplugged, pause if playing
472 if ((audio_status() & AUDIO_STATUS_PLAY) &&
473 !(audio_status() & AUDIO_STATUS_PAUSE))
475 if (global_settings.fade_on_stop)
476 fade(false, false);
477 else
478 audio_pause();
480 waiting_to_resume_play = false;
485 static void car_adapter_tick(void)
487 if (waiting_to_resume_play)
489 if (TIME_AFTER(current_tick, play_resume_tick))
491 if (audio_status() & AUDIO_STATUS_PAUSE)
493 queue_broadcast(SYS_CAR_ADAPTER_RESUME, 0);
495 waiting_to_resume_play = false;
500 void car_adapter_mode_init(void)
502 tick_add_task(car_adapter_tick);
504 #endif
506 #ifdef HAVE_HEADPHONE_DETECTION
507 static void unplug_change(bool inserted)
509 static bool headphone_caused_pause = false;
511 if (global_settings.unplug_mode)
513 int audio_stat = audio_status();
514 if (inserted)
516 if ((audio_stat & AUDIO_STATUS_PLAY) &&
517 headphone_caused_pause &&
518 global_settings.unplug_mode > 1 )
519 audio_resume();
520 backlight_on();
521 headphone_caused_pause = false;
522 } else {
523 if ((audio_stat & AUDIO_STATUS_PLAY) &&
524 !(audio_stat & AUDIO_STATUS_PAUSE))
526 headphone_caused_pause = true;
527 audio_pause();
529 if (global_settings.unplug_rw)
531 if (audio_current_track()->elapsed >
532 (unsigned long)(global_settings.unplug_rw*1000))
533 audio_ff_rewind(audio_current_track()->elapsed -
534 (global_settings.unplug_rw*1000));
535 else
536 audio_ff_rewind(0);
542 #endif
544 long default_event_handler_ex(long event, void (*callback)(void *), void *parameter)
546 switch(event)
548 case SYS_BATTERY_UPDATE:
549 if(global_settings.talk_battery_level)
551 talk_ids(true, VOICE_PAUSE, VOICE_PAUSE,
552 LANG_BATTERY_TIME,
553 TALK_ID(battery_level(), UNIT_PERCENT),
554 VOICE_PAUSE);
555 talk_force_enqueue_next();
557 break;
558 case SYS_USB_CONNECTED:
559 if (callback != NULL)
560 callback(parameter);
561 #if (CONFIG_STORAGE & STORAGE_MMC)
562 if (!mmc_touched() ||
563 (mmc_remove_request() == SYS_HOTSWAP_EXTRACTED))
564 #endif
566 system_flush();
567 #ifdef BOOTFILE
568 #if !defined(USB_NONE) && !defined(USB_HANDLED_BY_OF)
569 check_bootfile(false); /* gets initial size */
570 #endif
571 #endif
572 usb_screen();
573 #ifdef BOOTFILE
574 #if !defined(USB_NONE) && !defined(USB_HANDLED_BY_OF)
575 check_bootfile(true);
576 #endif
577 #endif
578 system_restore();
580 return SYS_USB_CONNECTED;
581 case SYS_POWEROFF:
582 if (!clean_shutdown(callback, parameter))
583 return SYS_POWEROFF;
584 break;
585 #if CONFIG_CHARGING
586 case SYS_CHARGER_CONNECTED:
587 car_adapter_mode_processing(true);
588 return SYS_CHARGER_CONNECTED;
590 case SYS_CHARGER_DISCONNECTED:
591 car_adapter_mode_processing(false);
592 return SYS_CHARGER_DISCONNECTED;
594 case SYS_CAR_ADAPTER_RESUME:
595 audio_resume();
596 return SYS_CAR_ADAPTER_RESUME;
597 #endif
598 #ifdef HAVE_HEADPHONE_DETECTION
599 case SYS_PHONE_PLUGGED:
600 unplug_change(true);
601 return SYS_PHONE_PLUGGED;
603 case SYS_PHONE_UNPLUGGED:
604 unplug_change(false);
605 return SYS_PHONE_UNPLUGGED;
606 #endif
607 #ifdef IPOD_ACCESSORY_PROTOCOL
608 case SYS_IAP_PERIODIC:
609 iap_periodic();
610 return SYS_IAP_PERIODIC;
611 case SYS_IAP_HANDLEPKT:
612 iap_handlepkt();
613 return SYS_IAP_HANDLEPKT;
614 #endif
616 return 0;
619 long default_event_handler(long event)
621 return default_event_handler_ex(event, NULL, NULL);
624 int show_logo( void )
626 #ifdef HAVE_LCD_BITMAP
627 char version[32];
628 int font_h, font_w;
630 snprintf(version, sizeof(version), "Ver. %s", appsversion);
632 lcd_clear_display();
633 #ifdef SANSA_CLIP /* display the logo in the blue area of the screen */
634 lcd_setfont(FONT_SYSFIXED);
635 lcd_getstringsize((unsigned char *)"A", &font_w, &font_h);
636 lcd_putsxy((LCD_WIDTH/2) - ((strlen(version)*font_w)/2),
637 0, (unsigned char *)version);
638 lcd_bitmap(rockboxlogo, 0, 16, BMPWIDTH_rockboxlogo, BMPHEIGHT_rockboxlogo);
639 #else
640 lcd_bitmap(rockboxlogo, 0, 10, BMPWIDTH_rockboxlogo, BMPHEIGHT_rockboxlogo);
641 lcd_setfont(FONT_SYSFIXED);
642 lcd_getstringsize((unsigned char *)"A", &font_w, &font_h);
643 lcd_putsxy((LCD_WIDTH/2) - ((strlen(version)*font_w)/2),
644 LCD_HEIGHT-font_h, (unsigned char *)version);
645 #endif
646 lcd_setfont(FONT_UI);
648 #else
649 char *rockbox = " ROCKbox!";
651 lcd_clear_display();
652 lcd_double_height(true);
653 lcd_puts(0, 0, rockbox);
654 lcd_puts_scroll(0, 1, appsversion);
655 #endif
656 lcd_update();
658 #ifdef HAVE_REMOTE_LCD
659 lcd_remote_clear_display();
660 lcd_remote_bitmap(remote_rockboxlogo, 0, 10, BMPWIDTH_remote_rockboxlogo,
661 BMPHEIGHT_remote_rockboxlogo);
662 lcd_remote_setfont(FONT_SYSFIXED);
663 lcd_remote_getstringsize((unsigned char *)"A", &font_w, &font_h);
664 lcd_remote_putsxy((LCD_REMOTE_WIDTH/2) - ((strlen(version)*font_w)/2),
665 LCD_REMOTE_HEIGHT-font_h, (unsigned char *)version);
666 lcd_remote_setfont(FONT_UI);
667 lcd_remote_update();
668 #endif
670 return 0;
673 #if CONFIG_CODEC == SWCODEC
674 int get_replaygain_mode(bool have_track_gain, bool have_album_gain)
676 int type;
678 bool track = ((global_settings.replaygain_type == REPLAYGAIN_TRACK)
679 || ((global_settings.replaygain_type == REPLAYGAIN_SHUFFLE)
680 && global_settings.playlist_shuffle));
682 type = (!track && have_album_gain) ? REPLAYGAIN_ALBUM
683 : have_track_gain ? REPLAYGAIN_TRACK : -1;
685 return type;
687 #endif
689 #ifdef BOOTFILE
690 #if !defined(USB_NONE) && !defined(USB_HANDLED_BY_OF)
692 memorize/compare details about the BOOTFILE
693 we don't use dircache because it may not be up to date after
694 USB disconnect (scanning in the background)
696 void check_bootfile(bool do_rolo)
698 static unsigned short wrtdate = 0;
699 static unsigned short wrttime = 0;
700 DIR* dir = NULL;
701 struct dirent* entry = NULL;
703 /* 1. open BOOTDIR and find the BOOTFILE dir entry */
704 dir = opendir(BOOTDIR);
706 if(!dir) return; /* do we want an error splash? */
708 /* loop all files in BOOTDIR */
709 while(0 != (entry = readdir(dir)))
711 if(!strcasecmp(entry->d_name, BOOTFILE))
713 /* found the bootfile */
714 if(wrtdate && do_rolo)
716 if((entry->wrtdate != wrtdate) ||
717 (entry->wrttime != wrttime))
719 static const char *lines[] = { ID2P(LANG_BOOT_CHANGED),
720 ID2P(LANG_REBOOT_NOW) };
721 static const struct text_message message={ lines, 2 };
722 button_clear_queue(); /* Empty the keyboard buffer */
723 if(gui_syncyesno_run(&message, NULL, NULL) == YESNO_YES)
724 rolo_load(BOOTDIR "/" BOOTFILE);
727 wrtdate = entry->wrtdate;
728 wrttime = entry->wrttime;
731 closedir(dir);
733 #endif
734 #endif
736 /* check range, set volume and save settings */
737 void setvol(void)
739 const int min_vol = sound_min(SOUND_VOLUME);
740 const int max_vol = sound_max(SOUND_VOLUME);
741 if (global_settings.volume < min_vol)
742 global_settings.volume = min_vol;
743 if (global_settings.volume > max_vol)
744 global_settings.volume = max_vol;
745 sound_set_volume(global_settings.volume);
746 settings_save();
749 char* strrsplt(char* str, int c)
751 char* s = strrchr(str, c);
753 if (s != NULL)
755 *s++ = '\0';
757 else
759 s = str;
762 return s;
765 /* Test file existence, using dircache of possible */
766 bool file_exists(const char *file)
768 int fd;
770 if (!file || strlen(file) <= 0)
771 return false;
773 #ifdef HAVE_DIRCACHE
774 if (dircache_is_enabled())
775 return (dircache_get_entry_ptr(file) != NULL);
776 #endif
778 fd = open(file, O_RDONLY);
779 if (fd < 0)
780 return false;
781 close(fd);
782 return true;
785 bool dir_exists(const char *path)
787 DIR* d = opendir(path);
788 if (!d)
789 return false;
790 closedir(d);
791 return true;
795 * removes the extension of filename (if it doesn't start with a .)
796 * puts the result in buffer
798 char *strip_extension(char* buffer, int buffer_size, const char *filename)
800 char *dot = strrchr(filename, '.');
801 int len;
803 if (buffer_size <= 0)
805 return NULL;
808 buffer_size--; /* Make room for end nil */
810 if (dot != 0 && filename[0] != '.')
812 len = dot - filename;
813 len = MIN(len, buffer_size);
814 strncpy(buffer, filename, len);
816 else
818 len = buffer_size;
819 strncpy(buffer, filename, buffer_size);
822 buffer[len] = 0;
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 |= (1<<i);
1046 i++;
1049 va_end(ap);
1050 return p;
1052 err:
1053 va_end(ap);
1054 return 0;
1056 #endif