Get cuesheets working again (hopefully fixes FS#10460), on swcodec only read the...
[kugel-rb.git] / apps / misc.c
blobe6f8ca840baa09bbe2b1b0227b32afeebd37e0a9
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)
303 screens[i].clear_display();
304 screens[i].update();
307 if (batt_safe)
309 #ifdef HAVE_TAGCACHE
310 if (!tagcache_prepare_shutdown())
312 cancel_shutdown();
313 splash(HZ, ID2P(LANG_TAGCACHE_BUSY));
314 return false;
316 #endif
317 if (battery_level() > 10)
318 splash(0, str(LANG_SHUTTINGDOWN));
319 else
321 msg_id = LANG_WARNING_BATTERY_LOW;
322 splashf(0, "%s %s", str(LANG_WARNING_BATTERY_LOW),
323 str(LANG_SHUTTINGDOWN));
326 else
328 msg_id = LANG_WARNING_BATTERY_EMPTY;
329 splashf(0, "%s %s", str(LANG_WARNING_BATTERY_EMPTY),
330 str(LANG_SHUTTINGDOWN));
333 if (global_settings.fade_on_stop
334 && (audio_stat & AUDIO_STATUS_PLAY))
336 fade(false, false);
339 if (batt_safe) /* do not save on critical battery */
341 #if defined(HAVE_RECORDING) && CONFIG_CODEC == SWCODEC
342 if (audio_stat & AUDIO_STATUS_RECORD)
344 rec_command(RECORDING_CMD_STOP);
345 /* wait for stop to complete */
346 while (audio_status() & AUDIO_STATUS_RECORD)
347 sleep(1);
349 #endif
350 bookmark_autobookmark();
352 /* audio_stop_recording == audio_stop for HWCODEC */
353 audio_stop();
355 if (callback != NULL)
356 callback(parameter);
358 #if CONFIG_CODEC != SWCODEC
359 /* wait for audio_stop or audio_stop_recording to complete */
360 while (audio_status())
361 sleep(1);
362 #endif
364 #if defined(HAVE_RECORDING) && CONFIG_CODEC == SWCODEC
365 audio_close_recording();
366 #endif
368 if(global_settings.talk_menu)
370 bool enqueue = false;
371 if(msg_id != -1)
373 talk_id(msg_id, enqueue);
374 enqueue = true;
376 talk_id(LANG_SHUTTINGDOWN, enqueue);
377 #if CONFIG_CODEC == SWCODEC
378 voice_wait();
379 #endif
382 system_flush();
383 #ifdef HAVE_EEPROM_SETTINGS
384 if (firmware_settings.initialized)
386 firmware_settings.disk_clean = true;
387 firmware_settings.bl_version = 0;
388 eeprom_settings_store();
390 #endif
392 #ifdef HAVE_DIRCACHE
393 else
394 dircache_disable();
395 #endif
397 shutdown_hw();
399 #endif
400 return false;
403 bool list_stop_handler(void)
405 bool ret = false;
407 /* Stop the music if it is playing */
408 if(audio_status())
410 if (!global_settings.party_mode)
412 if (global_settings.fade_on_stop)
413 fade(false, false);
414 bookmark_autobookmark();
415 audio_stop();
416 ret = true; /* bookmarking can make a refresh necessary */
419 #if CONFIG_CHARGING
420 #if (CONFIG_KEYPAD == RECORDER_PAD) && !defined(HAVE_SW_POWEROFF)
421 else
423 if (charger_inserted())
424 charging_splash();
425 else
426 shutdown_screen(); /* won't return if shutdown actually happens */
428 ret = true; /* screen is dirty, caller needs to refresh */
430 #endif
431 #ifndef HAVE_POWEROFF_WHILE_CHARGING
433 static long last_off = 0;
435 if (TIME_BEFORE(current_tick, last_off + HZ/2))
437 if (charger_inserted())
439 charging_splash();
440 ret = true; /* screen is dirty, caller needs to refresh */
443 last_off = current_tick;
445 #endif
446 #endif /* CONFIG_CHARGING */
447 return ret;
450 #if CONFIG_CHARGING
451 static bool waiting_to_resume_play = false;
452 static long play_resume_tick;
454 static void car_adapter_mode_processing(bool inserted)
456 if (global_settings.car_adapter_mode)
458 if(inserted)
461 * Just got plugged in, delay & resume if we were playing
463 if (audio_status() & AUDIO_STATUS_PAUSE)
465 /* delay resume a bit while the engine is cranking */
466 play_resume_tick = current_tick + HZ*5;
467 waiting_to_resume_play = true;
470 else
473 * Just got unplugged, pause if playing
475 if ((audio_status() & AUDIO_STATUS_PLAY) &&
476 !(audio_status() & AUDIO_STATUS_PAUSE))
478 if (global_settings.fade_on_stop)
479 fade(false, false);
480 else
481 audio_pause();
483 waiting_to_resume_play = false;
488 static void car_adapter_tick(void)
490 if (waiting_to_resume_play)
492 if (TIME_AFTER(current_tick, play_resume_tick))
494 if (audio_status() & AUDIO_STATUS_PAUSE)
496 queue_broadcast(SYS_CAR_ADAPTER_RESUME, 0);
498 waiting_to_resume_play = false;
503 void car_adapter_mode_init(void)
505 tick_add_task(car_adapter_tick);
507 #endif
509 #ifdef HAVE_HEADPHONE_DETECTION
510 static void unplug_change(bool inserted)
512 static bool headphone_caused_pause = false;
514 if (global_settings.unplug_mode)
516 int audio_stat = audio_status();
517 if (inserted)
519 if ((audio_stat & AUDIO_STATUS_PLAY) &&
520 headphone_caused_pause &&
521 global_settings.unplug_mode > 1 )
522 audio_resume();
523 backlight_on();
524 headphone_caused_pause = false;
525 } else {
526 if ((audio_stat & AUDIO_STATUS_PLAY) &&
527 !(audio_stat & AUDIO_STATUS_PAUSE))
529 headphone_caused_pause = true;
530 audio_pause();
532 if (global_settings.unplug_rw)
534 if (audio_current_track()->elapsed >
535 (unsigned long)(global_settings.unplug_rw*1000))
536 audio_ff_rewind(audio_current_track()->elapsed -
537 (global_settings.unplug_rw*1000));
538 else
539 audio_ff_rewind(0);
545 #endif
547 long default_event_handler_ex(long event, void (*callback)(void *), void *parameter)
549 switch(event)
551 case SYS_BATTERY_UPDATE:
552 if(global_settings.talk_battery_level)
554 talk_ids(true, VOICE_PAUSE, VOICE_PAUSE,
555 LANG_BATTERY_TIME,
556 TALK_ID(battery_level(), UNIT_PERCENT),
557 VOICE_PAUSE);
558 talk_force_enqueue_next();
560 break;
561 case SYS_USB_CONNECTED:
562 if (callback != NULL)
563 callback(parameter);
564 #if (CONFIG_STORAGE & STORAGE_MMC)
565 if (!mmc_touched() ||
566 (mmc_remove_request() == SYS_HOTSWAP_EXTRACTED))
567 #endif
569 system_flush();
570 #ifdef BOOTFILE
571 #if !defined(USB_NONE) && !defined(USB_HANDLED_BY_OF)
572 check_bootfile(false); /* gets initial size */
573 #endif
574 #endif
575 usb_screen();
576 #ifdef BOOTFILE
577 #if !defined(USB_NONE) && !defined(USB_HANDLED_BY_OF)
578 check_bootfile(true);
579 #endif
580 #endif
581 system_restore();
583 return SYS_USB_CONNECTED;
584 case SYS_POWEROFF:
585 if (!clean_shutdown(callback, parameter))
586 return SYS_POWEROFF;
587 break;
588 #if CONFIG_CHARGING
589 case SYS_CHARGER_CONNECTED:
590 car_adapter_mode_processing(true);
591 return SYS_CHARGER_CONNECTED;
593 case SYS_CHARGER_DISCONNECTED:
594 car_adapter_mode_processing(false);
595 return SYS_CHARGER_DISCONNECTED;
597 case SYS_CAR_ADAPTER_RESUME:
598 audio_resume();
599 return SYS_CAR_ADAPTER_RESUME;
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
619 return 0;
622 long default_event_handler(long event)
624 return default_event_handler_ex(event, NULL, NULL);
627 int show_logo( void )
629 #ifdef HAVE_LCD_BITMAP
630 char version[32];
631 int font_h, font_w;
633 snprintf(version, sizeof(version), "Ver. %s", appsversion);
635 lcd_clear_display();
636 #ifdef SANSA_CLIP /* display the logo in the blue area of the screen */
637 lcd_setfont(FONT_SYSFIXED);
638 lcd_getstringsize((unsigned char *)"A", &font_w, &font_h);
639 lcd_putsxy((LCD_WIDTH/2) - ((strlen(version)*font_w)/2),
640 0, (unsigned char *)version);
641 lcd_bitmap(rockboxlogo, 0, 16, BMPWIDTH_rockboxlogo, BMPHEIGHT_rockboxlogo);
642 #else
643 lcd_bitmap(rockboxlogo, 0, 10, BMPWIDTH_rockboxlogo, BMPHEIGHT_rockboxlogo);
644 lcd_setfont(FONT_SYSFIXED);
645 lcd_getstringsize((unsigned char *)"A", &font_w, &font_h);
646 lcd_putsxy((LCD_WIDTH/2) - ((strlen(version)*font_w)/2),
647 LCD_HEIGHT-font_h, (unsigned char *)version);
648 #endif
649 lcd_setfont(FONT_UI);
651 #else
652 char *rockbox = " ROCKbox!";
654 lcd_clear_display();
655 lcd_double_height(true);
656 lcd_puts(0, 0, rockbox);
657 lcd_puts_scroll(0, 1, appsversion);
658 #endif
659 lcd_update();
661 #ifdef HAVE_REMOTE_LCD
662 lcd_remote_clear_display();
663 lcd_remote_bitmap(remote_rockboxlogo, 0, 10, BMPWIDTH_remote_rockboxlogo,
664 BMPHEIGHT_remote_rockboxlogo);
665 lcd_remote_setfont(FONT_SYSFIXED);
666 lcd_remote_getstringsize((unsigned char *)"A", &font_w, &font_h);
667 lcd_remote_putsxy((LCD_REMOTE_WIDTH/2) - ((strlen(version)*font_w)/2),
668 LCD_REMOTE_HEIGHT-font_h, (unsigned char *)version);
669 lcd_remote_setfont(FONT_UI);
670 lcd_remote_update();
671 #endif
673 return 0;
676 #if CONFIG_CODEC == SWCODEC
677 int get_replaygain_mode(bool have_track_gain, bool have_album_gain)
679 int type;
681 bool track = ((global_settings.replaygain_type == REPLAYGAIN_TRACK)
682 || ((global_settings.replaygain_type == REPLAYGAIN_SHUFFLE)
683 && global_settings.playlist_shuffle));
685 type = (!track && have_album_gain) ? REPLAYGAIN_ALBUM
686 : have_track_gain ? REPLAYGAIN_TRACK : -1;
688 return type;
690 #endif
692 #ifdef BOOTFILE
693 #if !defined(USB_NONE) && !defined(USB_HANDLED_BY_OF)
695 memorize/compare details about the BOOTFILE
696 we don't use dircache because it may not be up to date after
697 USB disconnect (scanning in the background)
699 void check_bootfile(bool do_rolo)
701 static unsigned short wrtdate = 0;
702 static unsigned short wrttime = 0;
703 DIR* dir = NULL;
704 struct dirent* entry = NULL;
706 /* 1. open BOOTDIR and find the BOOTFILE dir entry */
707 dir = opendir(BOOTDIR);
709 if(!dir) return; /* do we want an error splash? */
711 /* loop all files in BOOTDIR */
712 while(0 != (entry = readdir(dir)))
714 if(!strcasecmp(entry->d_name, BOOTFILE))
716 /* found the bootfile */
717 if(wrtdate && do_rolo)
719 if((entry->wrtdate != wrtdate) ||
720 (entry->wrttime != wrttime))
722 static const char *lines[] = { ID2P(LANG_BOOT_CHANGED),
723 ID2P(LANG_REBOOT_NOW) };
724 static const struct text_message message={ lines, 2 };
725 button_clear_queue(); /* Empty the keyboard buffer */
726 if(gui_syncyesno_run(&message, NULL, NULL) == YESNO_YES)
727 rolo_load(BOOTDIR "/" BOOTFILE);
730 wrtdate = entry->wrtdate;
731 wrttime = entry->wrttime;
734 closedir(dir);
736 #endif
737 #endif
739 /* check range, set volume and save settings */
740 void setvol(void)
742 const int min_vol = sound_min(SOUND_VOLUME);
743 const int max_vol = sound_max(SOUND_VOLUME);
744 if (global_settings.volume < min_vol)
745 global_settings.volume = min_vol;
746 if (global_settings.volume > max_vol)
747 global_settings.volume = max_vol;
748 sound_set_volume(global_settings.volume);
749 settings_save();
752 char* strrsplt(char* str, int c)
754 char* s = strrchr(str, c);
756 if (s != NULL)
758 *s++ = '\0';
760 else
762 s = str;
765 return s;
768 /* Test file existence, using dircache of possible */
769 bool file_exists(const char *file)
771 int fd;
773 if (!file || strlen(file) <= 0)
774 return false;
776 #ifdef HAVE_DIRCACHE
777 if (dircache_is_enabled())
778 return (dircache_get_entry_ptr(file) != NULL);
779 #endif
781 fd = open(file, O_RDONLY);
782 if (fd < 0)
783 return false;
784 close(fd);
785 return true;
788 bool dir_exists(const char *path)
790 DIR* d = opendir(path);
791 if (!d)
792 return false;
793 closedir(d);
794 return true;
798 * removes the extension of filename (if it doesn't start with a .)
799 * puts the result in buffer
801 char *strip_extension(char* buffer, int buffer_size, const char *filename)
803 char *dot = strrchr(filename, '.');
804 int len;
806 if (buffer_size <= 0)
808 return NULL;
811 buffer_size--; /* Make room for end nil */
813 if (dot != 0 && filename[0] != '.')
815 len = dot - filename;
816 len = MIN(len, buffer_size);
818 else
820 len = buffer_size;
823 strlcpy(buffer, filename, len + 1);
825 return buffer;
827 #endif /* !defined(__PCTOOL__) */
829 char* skip_whitespace(char* const str)
831 char *s = str;
833 while (isspace(*s))
834 s++;
836 return s;
839 /* Format time into buf.
841 * buf - buffer to format to.
842 * buf_size - size of buffer.
843 * t - time to format, in milliseconds.
845 void format_time(char* buf, int buf_size, long t)
847 if ( t < 3600000 )
849 snprintf(buf, buf_size, "%d:%02d",
850 (int) (t / 60000), (int) (t % 60000 / 1000));
852 else
854 snprintf(buf, buf_size, "%d:%02d:%02d",
855 (int) (t / 3600000), (int) (t % 3600000 / 60000),
856 (int) (t % 60000 / 1000));
861 /** Open a UTF-8 file and set file descriptor to first byte after BOM.
862 * If no BOM is present this behaves like open().
863 * If the file is opened for writing and O_TRUNC is set, write a BOM to
864 * the opened file and leave the file pointer set after the BOM.
866 #define BOM "\xef\xbb\xbf"
867 #define BOM_SIZE 3
869 int open_utf8(const char* pathname, int flags)
871 int fd;
872 unsigned char bom[BOM_SIZE];
874 fd = open(pathname, flags);
875 if(fd < 0)
876 return fd;
878 if(flags & (O_TRUNC | O_WRONLY))
880 write(fd, BOM, BOM_SIZE);
882 else
884 read(fd, bom, BOM_SIZE);
885 /* check for BOM */
886 if(memcmp(bom, BOM, BOM_SIZE))
887 lseek(fd, 0, SEEK_SET);
889 return fd;
893 #ifdef HAVE_LCD_COLOR
895 * Helper function to convert a string of 6 hex digits to a native colour
898 static int hex2dec(int c)
900 return (((c) >= '0' && ((c) <= '9')) ? (c) - '0' :
901 (toupper(c)) - 'A' + 10);
904 int hex_to_rgb(const char* hex, int* color)
906 int red, green, blue;
907 int i = 0;
909 while ((i < 6) && (isxdigit(hex[i])))
910 i++;
912 if (i < 6)
913 return -1;
915 red = (hex2dec(hex[0]) << 4) | hex2dec(hex[1]);
916 green = (hex2dec(hex[2]) << 4) | hex2dec(hex[3]);
917 blue = (hex2dec(hex[4]) << 4) | hex2dec(hex[5]);
919 *color = LCD_RGBPACK(red,green,blue);
921 return 0;
923 #endif /* HAVE_LCD_COLOR */
925 #ifdef HAVE_LCD_BITMAP
926 /* A simplified scanf - used (at time of writing) by wps parsing functions.
928 fmt - char array specifying the format of each list option. Valid values
929 are: d - int
930 s - string (sets pointer to string, without copying)
931 c - hex colour (RGB888 - e.g. ff00ff)
932 g - greyscale "colour" (0-3)
933 set_vals - if not NULL 1 is set in the bitplace if the item was read OK
934 0 if not read.
935 first item is LSB, (max 32 items! )
936 Stops parseing if an item is invalid unless the item == '-'
937 sep - list separator (e.g. ',' or '|')
938 str - string to parse, must be terminated by 0 or sep
939 ... - pointers to store the parsed values
941 return value - pointer to char after parsed data, 0 if there was an error.
945 /* '0'-'3' are ASCII 0x30 to 0x33 */
946 #define is0123(x) (((x) & 0xfc) == 0x30)
948 const char* parse_list(const char *fmt, uint32_t *set_vals,
949 const char sep, const char* str, ...)
951 va_list ap;
952 const char* p = str, *f = fmt;
953 const char** s;
954 int* d;
955 bool set;
956 int i=0;
958 va_start(ap, str);
959 if (set_vals)
960 *set_vals = 0;
961 while (*fmt)
963 /* Check for separator, if we're not at the start */
964 if (f != fmt)
966 if (*p != sep)
967 goto err;
968 p++;
970 set = false;
971 switch (*fmt++)
973 case 's': /* string - return a pointer to it (not a copy) */
974 s = va_arg(ap, const char **);
976 *s = p;
977 while (*p && *p != sep)
978 p++;
979 set = (s[0][0]!='-') && (s[0][1]!=sep) ;
980 break;
982 case 'd': /* int */
983 d = va_arg(ap, int*);
984 if (!isdigit(*p))
986 if (!set_vals || *p != '-')
987 goto err;
988 while (*p && *p != sep)
989 p++;
991 else
993 *d = *p++ - '0';
994 while (isdigit(*p))
995 *d = (*d * 10) + (*p++ - '0');
996 set = true;
999 break;
1001 #ifdef HAVE_LCD_COLOR
1002 case 'c': /* colour (rrggbb - e.g. f3c1a8) */
1003 d = va_arg(ap, int*);
1005 if (hex_to_rgb(p, d) < 0)
1007 if (!set_vals || *p != '-')
1008 goto err;
1009 while (*p && *p != sep)
1010 p++;
1012 else
1014 p += 6;
1015 set = true;
1018 break;
1019 #endif
1021 #if LCD_DEPTH == 2 || (defined(HAVE_REMOTE_LCD) && LCD_REMOTE_DEPTH == 2)
1022 case 'g': /* greyscale colour (0-3) */
1023 d = va_arg(ap, int*);
1025 if (is0123(*p))
1027 *d = *p++ - '0';
1028 set = true;
1030 else if (!set_vals || *p != '-')
1031 goto err;
1032 else
1034 while (*p && *p != sep)
1035 p++;
1038 break;
1039 #endif
1041 default: /* Unknown format type */
1042 goto err;
1043 break;
1045 if (set_vals && set)
1046 *set_vals |= BIT_N(i);
1047 i++;
1050 va_end(ap);
1051 return p;
1053 err:
1054 va_end(ap);
1055 return 0;
1057 #endif