Don't build 16-point IDCT on greyscale targets, since it's only used for chroma compo...
[kugel-rb.git] / apps / misc.c
blobd7a64b3733076360c1456d994b6c9c7c3ebf0f08
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 "config.h"
24 #include "misc.h"
25 #include "lcd.h"
26 #include "file.h"
27 #ifdef __PCTOOL__
28 #include <stdarg.h>
29 #include <stdio.h>
30 #ifdef WPSEDITOR
31 #include "string.h"
32 #endif
33 #else
34 #include "sprintf.h"
35 #include "appevents.h"
36 #include "lang.h"
37 #include "string.h"
38 #include "dir.h"
39 #include "lcd-remote.h"
40 #include "errno.h"
41 #include "system.h"
42 #include "timefuncs.h"
43 #include "screens.h"
44 #include "talk.h"
45 #include "mpeg.h"
46 #include "audio.h"
47 #include "mp3_playback.h"
48 #include "settings.h"
49 #include "storage.h"
50 #include "ata_idle_notify.h"
51 #include "kernel.h"
52 #include "power.h"
53 #include "powermgmt.h"
54 #include "backlight.h"
55 #include "version.h"
56 #include "font.h"
57 #include "splash.h"
58 #include "tagcache.h"
59 #include "scrobbler.h"
60 #include "sound.h"
61 #include "playlist.h"
62 #include "yesno.h"
63 #include "viewport.h"
65 #ifdef IPOD_ACCESSORY_PROTOCOL
66 #include "iap.h"
67 #endif
69 #if (CONFIG_STORAGE & STORAGE_MMC)
70 #include "ata_mmc.h"
71 #endif
72 #include "tree.h"
73 #include "eeprom_settings.h"
74 #if defined(HAVE_RECORDING) && !defined(__PCTOOL__)
75 #include "recording.h"
76 #endif
77 #if defined(HAVE_LCD_BITMAP) && !defined(__PCTOOL__)
78 #include "bmp.h"
79 #include "icons.h"
80 #endif /* End HAVE_LCD_BITMAP */
81 #include "gui/gwps-common.h"
82 #include "bookmark.h"
84 #include "playback.h"
86 #ifdef BOOTFILE
87 #if !defined(USB_NONE) && !defined(USB_HANDLED_BY_OF)
88 #include "rolo.h"
89 #include "yesno.h"
90 #endif
91 #endif
93 /* Format a large-range value for output, using the appropriate unit so that
94 * the displayed value is in the range 1 <= display < 1000 (1024 for "binary"
95 * units) if possible, and 3 significant digits are shown. If a buffer is
96 * given, the result is snprintf()'d into that buffer, otherwise the result is
97 * voiced.*/
98 char *output_dyn_value(char *buf, int buf_size, int value,
99 const unsigned char **units, bool bin_scale)
101 int scale = bin_scale ? 1024 : 1000;
102 int fraction = 0;
103 int unit_no = 0;
104 char tbuf[5];
106 while (value >= scale)
108 fraction = value % scale;
109 value /= scale;
110 unit_no++;
112 if (bin_scale)
113 fraction = fraction * 1000 / 1024;
115 if (value >= 100 || !unit_no)
116 tbuf[0] = '\0';
117 else if (value >= 10)
118 snprintf(tbuf, sizeof(tbuf), "%01d", fraction / 100);
119 else
120 snprintf(tbuf, sizeof(tbuf), "%02d", fraction / 10);
122 if (buf)
124 if (strlen(tbuf))
125 snprintf(buf, buf_size, "%d%s%s%s", value, str(LANG_POINT),
126 tbuf, P2STR(units[unit_no]));
127 else
128 snprintf(buf, buf_size, "%d%s", value, P2STR(units[unit_no]));
130 else
132 talk_fractional(tbuf, value, P2ID(units[unit_no]));
134 return buf;
137 /* Ask the user if they really want to erase the current dynamic playlist
138 * returns true if the playlist should be replaced */
139 bool warn_on_pl_erase(void)
141 if (global_settings.warnon_erase_dynplaylist &&
142 !global_settings.party_mode &&
143 playlist_modified(NULL))
145 static const char *lines[] =
146 {ID2P(LANG_WARN_ERASEDYNPLAYLIST_PROMPT)};
147 static const struct text_message message={lines, 1};
149 return (gui_syncyesno_run(&message, NULL, NULL) == YESNO_YES);
151 else
152 return true;
155 /* Read (up to) a line of text from fd into buffer and return number of bytes
156 * read (which may be larger than the number of bytes stored in buffer). If
157 * an error occurs, -1 is returned (and buffer contains whatever could be
158 * read). A line is terminated by a LF char. Neither LF nor CR chars are
159 * stored in buffer.
161 int read_line(int fd, char* buffer, int buffer_size)
163 int count = 0;
164 int num_read = 0;
166 errno = 0;
168 while (count < buffer_size)
170 unsigned char c;
172 if (1 != read(fd, &c, 1))
173 break;
175 num_read++;
177 if ( c == '\n' )
178 break;
180 if ( c == '\r' )
181 continue;
183 buffer[count++] = c;
186 buffer[MIN(count, buffer_size - 1)] = 0;
188 return errno ? -1 : num_read;
191 /* Performance optimized version of the previous function. */
192 int fast_readline(int fd, char *buf, int buf_size, void *parameters,
193 int (*callback)(int n, const char *buf, void *parameters))
195 char *p, *next;
196 int rc, pos = 0;
197 int count = 0;
199 while ( 1 )
201 next = NULL;
203 rc = read(fd, &buf[pos], buf_size - pos - 1);
204 if (rc >= 0)
205 buf[pos+rc] = '\0';
207 if ( (p = strchr(buf, '\r')) != NULL)
209 *p = '\0';
210 next = ++p;
212 else
213 p = buf;
215 if ( (p = strchr(p, '\n')) != NULL)
217 *p = '\0';
218 next = ++p;
221 rc = callback(count, buf, parameters);
222 if (rc < 0)
223 return rc;
225 count++;
226 if (next)
228 pos = buf_size - ((long)next - (long)buf) - 1;
229 memmove(buf, next, pos);
231 else
232 break ;
235 return 0;
238 /* parse a line from a configuration file. the line format is:
240 name: value
242 Any whitespace before setting name or value (after ':') is ignored.
243 A # as first non-whitespace character discards the whole line.
244 Function sets pointers to null-terminated setting name and value.
245 Returns false if no valid config entry was found.
248 bool settings_parseline(char* line, char** name, char** value)
250 char* ptr;
252 line = skip_whitespace(line);
254 if ( *line == '#' )
255 return false;
257 ptr = strchr(line, ':');
258 if ( !ptr )
259 return false;
261 *name = line;
262 *ptr = 0;
263 ptr++;
264 ptr = skip_whitespace(ptr);
265 *value = ptr;
266 return true;
269 static void system_flush(void)
271 scrobbler_shutdown();
272 playlist_shutdown();
273 tree_flush();
274 call_storage_idle_notifys(true); /*doesnt work on usb and shutdown from ata thread */
277 static void system_restore(void)
279 tree_restore();
280 scrobbler_init();
283 static bool clean_shutdown(void (*callback)(void *), void *parameter)
285 #ifdef SIMULATOR
286 (void)callback;
287 (void)parameter;
288 bookmark_autobookmark();
289 call_storage_idle_notifys(true);
290 exit(0);
291 #else
292 long msg_id = -1;
293 int i;
295 scrobbler_poweroff();
297 #if CONFIG_CHARGING && !defined(HAVE_POWEROFF_WHILE_CHARGING)
298 if(!charger_inserted())
299 #endif
301 bool batt_safe = battery_level_safe();
302 int audio_stat = audio_status();
304 FOR_NB_SCREENS(i)
305 screens[i].clear_display();
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);
817 strncpy(buffer, filename, len);
819 else
821 len = buffer_size;
822 strncpy(buffer, filename, buffer_size);
825 buffer[len] = 0;
827 return buffer;
829 #endif /* !defined(__PCTOOL__) */
831 char* skip_whitespace(char* const str)
833 char *s = str;
835 while (isspace(*s))
836 s++;
838 return s;
841 /* Format time into buf.
843 * buf - buffer to format to.
844 * buf_size - size of buffer.
845 * t - time to format, in milliseconds.
847 void format_time(char* buf, int buf_size, long t)
849 if ( t < 3600000 )
851 snprintf(buf, buf_size, "%d:%02d",
852 (int) (t / 60000), (int) (t % 60000 / 1000));
854 else
856 snprintf(buf, buf_size, "%d:%02d:%02d",
857 (int) (t / 3600000), (int) (t % 3600000 / 60000),
858 (int) (t % 60000 / 1000));
863 /** Open a UTF-8 file and set file descriptor to first byte after BOM.
864 * If no BOM is present this behaves like open().
865 * If the file is opened for writing and O_TRUNC is set, write a BOM to
866 * the opened file and leave the file pointer set after the BOM.
868 #define BOM "\xef\xbb\xbf"
869 #define BOM_SIZE 3
871 int open_utf8(const char* pathname, int flags)
873 int fd;
874 unsigned char bom[BOM_SIZE];
876 fd = open(pathname, flags);
877 if(fd < 0)
878 return fd;
880 if(flags & (O_TRUNC | O_WRONLY))
882 write(fd, BOM, BOM_SIZE);
884 else
886 read(fd, bom, BOM_SIZE);
887 /* check for BOM */
888 if(memcmp(bom, BOM, BOM_SIZE))
889 lseek(fd, 0, SEEK_SET);
891 return fd;
895 #ifdef HAVE_LCD_COLOR
897 * Helper function to convert a string of 6 hex digits to a native colour
900 static int hex2dec(int c)
902 return (((c) >= '0' && ((c) <= '9')) ? (c) - '0' :
903 (toupper(c)) - 'A' + 10);
906 int hex_to_rgb(const char* hex, int* color)
908 int red, green, blue;
909 int i = 0;
911 while ((i < 6) && (isxdigit(hex[i])))
912 i++;
914 if (i < 6)
915 return -1;
917 red = (hex2dec(hex[0]) << 4) | hex2dec(hex[1]);
918 green = (hex2dec(hex[2]) << 4) | hex2dec(hex[3]);
919 blue = (hex2dec(hex[4]) << 4) | hex2dec(hex[5]);
921 *color = LCD_RGBPACK(red,green,blue);
923 return 0;
925 #endif /* HAVE_LCD_COLOR */
927 #ifdef HAVE_LCD_BITMAP
928 /* A simplified scanf - used (at time of writing) by wps parsing functions.
930 fmt - char array specifying the format of each list option. Valid values
931 are: d - int
932 s - string (sets pointer to string, without copying)
933 c - hex colour (RGB888 - e.g. ff00ff)
934 g - greyscale "colour" (0-3)
935 set_vals - if not NULL 1 is set in the bitplace if the item was read OK
936 0 if not read.
937 first item is LSB, (max 32 items! )
938 Stops parseing if an item is invalid unless the item == '-'
939 sep - list separator (e.g. ',' or '|')
940 str - string to parse, must be terminated by 0 or sep
941 ... - pointers to store the parsed values
943 return value - pointer to char after parsed data, 0 if there was an error.
947 /* '0'-'3' are ASCII 0x30 to 0x33 */
948 #define is0123(x) (((x) & 0xfc) == 0x30)
950 const char* parse_list(const char *fmt, uint32_t *set_vals,
951 const char sep, const char* str, ...)
953 va_list ap;
954 const char* p = str, *f = fmt;
955 const char** s;
956 int* d;
957 bool set;
958 int i=0;
960 va_start(ap, str);
961 if (set_vals)
962 *set_vals = 0;
963 while (*fmt)
965 /* Check for separator, if we're not at the start */
966 if (f != fmt)
968 if (*p != sep)
969 goto err;
970 p++;
972 set = false;
973 switch (*fmt++)
975 case 's': /* string - return a pointer to it (not a copy) */
976 s = va_arg(ap, const char **);
978 *s = p;
979 while (*p && *p != sep)
980 p++;
981 set = (s[0][0]!='-') && (s[0][1]!=sep) ;
982 break;
984 case 'd': /* int */
985 d = va_arg(ap, int*);
986 if (!isdigit(*p))
988 if (!set_vals || *p != '-')
989 goto err;
990 while (*p && *p != sep)
991 p++;
993 else
995 *d = *p++ - '0';
996 while (isdigit(*p))
997 *d = (*d * 10) + (*p++ - '0');
998 set = true;
1001 break;
1003 #ifdef HAVE_LCD_COLOR
1004 case 'c': /* colour (rrggbb - e.g. f3c1a8) */
1005 d = va_arg(ap, int*);
1007 if (hex_to_rgb(p, d) < 0)
1009 if (!set_vals || *p != '-')
1010 goto err;
1011 while (*p && *p != sep)
1012 p++;
1014 else
1016 p += 6;
1017 set = true;
1020 break;
1021 #endif
1023 #if LCD_DEPTH == 2 || (defined(HAVE_REMOTE_LCD) && LCD_REMOTE_DEPTH == 2)
1024 case 'g': /* greyscale colour (0-3) */
1025 d = va_arg(ap, int*);
1027 if (is0123(*p))
1029 *d = *p++ - '0';
1030 set = true;
1032 else if (!set_vals || *p != '-')
1033 goto err;
1034 else
1036 while (*p && *p != sep)
1037 p++;
1040 break;
1041 #endif
1043 default: /* Unknown format type */
1044 goto err;
1045 break;
1047 if (set_vals && set)
1048 *set_vals |= (1<<i);
1049 i++;
1052 va_end(ap);
1053 return p;
1055 err:
1056 va_end(ap);
1057 return 0;
1059 #endif