e200v2: make buttons and scrollwheel work. Still ugly as we need to disable interrupt...
[kugel-rb.git] / apps / misc.c
blob872d91592d0cad3efd625f41e27e67d96e7fea10
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 <stdint.h>
29 #include <stdarg.h>
30 #include <stdio.h>
31 #ifdef WPSEDITOR
32 #include "string.h"
33 #endif
34 #else
35 #include "sprintf.h"
36 #include "appevents.h"
37 #include "lang.h"
38 #include "string.h"
39 #include "dir.h"
40 #include "lcd-remote.h"
41 #include "errno.h"
42 #include "system.h"
43 #include "timefuncs.h"
44 #include "screens.h"
45 #include "talk.h"
46 #include "mpeg.h"
47 #include "audio.h"
48 #include "mp3_playback.h"
49 #include "settings.h"
50 #include "storage.h"
51 #include "ata_idle_notify.h"
52 #include "kernel.h"
53 #include "power.h"
54 #include "powermgmt.h"
55 #include "backlight.h"
56 #include "version.h"
57 #include "font.h"
58 #include "splash.h"
59 #include "tagcache.h"
60 #include "scrobbler.h"
61 #include "sound.h"
62 #include "playlist.h"
63 #include "yesno.h"
64 #include "viewport.h"
66 #ifdef IPOD_ACCESSORY_PROTOCOL
67 #include "iap.h"
68 #endif
70 #if (CONFIG_STORAGE & STORAGE_MMC)
71 #include "ata_mmc.h"
72 #endif
73 #include "tree.h"
74 #include "eeprom_settings.h"
75 #if defined(HAVE_RECORDING) && !defined(__PCTOOL__)
76 #include "recording.h"
77 #endif
78 #if defined(HAVE_LCD_BITMAP) && !defined(__PCTOOL__)
79 #include "bmp.h"
80 #include "icons.h"
81 #endif /* End HAVE_LCD_BITMAP */
82 #include "gui/gwps-common.h"
83 #include "bookmark.h"
85 #include "playback.h"
87 #ifdef BOOTFILE
88 #if !defined(USB_NONE) && !defined(USB_IPODSTYLE)
89 #include "rolo.h"
90 #include "yesno.h"
91 #endif
92 #endif
94 /* Format a large-range value for output, using the appropriate unit so that
95 * the displayed value is in the range 1 <= display < 1000 (1024 for "binary"
96 * units) if possible, and 3 significant digits are shown. If a buffer is
97 * given, the result is snprintf()'d into that buffer, otherwise the result is
98 * voiced.*/
99 char *output_dyn_value(char *buf, int buf_size, int value,
100 const unsigned char **units, bool bin_scale)
102 int scale = bin_scale ? 1024 : 1000;
103 int fraction = 0;
104 int unit_no = 0;
105 char tbuf[5];
107 while (value >= scale)
109 fraction = value % scale;
110 value /= scale;
111 unit_no++;
113 if (bin_scale)
114 fraction = fraction * 1000 / 1024;
116 if (value >= 100 || !unit_no)
117 tbuf[0] = '\0';
118 else if (value >= 10)
119 snprintf(tbuf, sizeof(tbuf), "%01d", fraction / 100);
120 else
121 snprintf(tbuf, sizeof(tbuf), "%02d", fraction / 10);
123 if (buf)
125 if (strlen(tbuf))
126 snprintf(buf, buf_size, "%d%s%s%s", value, str(LANG_POINT),
127 tbuf, P2STR(units[unit_no]));
128 else
129 snprintf(buf, buf_size, "%d%s", value, P2STR(units[unit_no]));
131 else
133 talk_fractional(tbuf, value, P2ID(units[unit_no]));
135 return buf;
138 /* Ask the user if they really want to erase the current dynamic playlist
139 * returns true if the playlist should be replaced */
140 bool warn_on_pl_erase(void)
142 if (global_settings.warnon_erase_dynplaylist &&
143 !global_settings.party_mode &&
144 playlist_modified(NULL))
146 static const char *lines[] =
147 {ID2P(LANG_WARN_ERASEDYNPLAYLIST_PROMPT)};
148 static const struct text_message message={lines, 1};
150 return (gui_syncyesno_run(&message, NULL, NULL) == YESNO_YES);
152 else
153 return true;
156 /* Read (up to) a line of text from fd into buffer and return number of bytes
157 * read (which may be larger than the number of bytes stored in buffer). If
158 * an error occurs, -1 is returned (and buffer contains whatever could be
159 * read). A line is terminated by a LF char. Neither LF nor CR chars are
160 * stored in buffer.
162 int read_line(int fd, char* buffer, int buffer_size)
164 int count = 0;
165 int num_read = 0;
167 errno = 0;
169 while (count < buffer_size)
171 unsigned char c;
173 if (1 != read(fd, &c, 1))
174 break;
176 num_read++;
178 if ( c == '\n' )
179 break;
181 if ( c == '\r' )
182 continue;
184 buffer[count++] = c;
187 buffer[MIN(count, buffer_size - 1)] = 0;
189 return errno ? -1 : num_read;
192 /* Performance optimized version of the previous function. */
193 int fast_readline(int fd, char *buf, int buf_size, void *parameters,
194 int (*callback)(int n, const char *buf, void *parameters))
196 char *p, *next;
197 int rc, pos = 0;
198 int count = 0;
200 while ( 1 )
202 next = NULL;
204 rc = read(fd, &buf[pos], buf_size - pos - 1);
205 if (rc >= 0)
206 buf[pos+rc] = '\0';
208 if ( (p = strchr(buf, '\r')) != NULL)
210 *p = '\0';
211 next = ++p;
213 else
214 p = buf;
216 if ( (p = strchr(p, '\n')) != NULL)
218 *p = '\0';
219 next = ++p;
222 rc = callback(count, buf, parameters);
223 if (rc < 0)
224 return rc;
226 count++;
227 if (next)
229 pos = buf_size - ((long)next - (long)buf) - 1;
230 memmove(buf, next, pos);
232 else
233 break ;
236 return 0;
239 /* parse a line from a configuration file. the line format is:
241 name: value
243 Any whitespace before setting name or value (after ':') is ignored.
244 A # as first non-whitespace character discards the whole line.
245 Function sets pointers to null-terminated setting name and value.
246 Returns false if no valid config entry was found.
249 bool settings_parseline(char* line, char** name, char** value)
251 char* ptr;
253 line = skip_whitespace(line);
255 if ( *line == '#' )
256 return false;
258 ptr = strchr(line, ':');
259 if ( !ptr )
260 return false;
262 *name = line;
263 *ptr = 0;
264 ptr++;
265 ptr = skip_whitespace(ptr);
266 *value = ptr;
267 return true;
270 static void system_flush(void)
272 scrobbler_shutdown();
273 playlist_shutdown();
274 tree_flush();
275 call_storage_idle_notifys(true); /*doesnt work on usb and shutdown from ata thread */
278 static void system_restore(void)
280 tree_restore();
281 scrobbler_init();
284 static bool clean_shutdown(void (*callback)(void *), void *parameter)
286 #ifdef SIMULATOR
287 (void)callback;
288 (void)parameter;
289 bookmark_autobookmark();
290 call_storage_idle_notifys(true);
291 exit(0);
292 #else
293 long msg_id = -1;
294 int i;
296 scrobbler_poweroff();
298 #if CONFIG_CHARGING && !defined(HAVE_POWEROFF_WHILE_CHARGING)
299 if(!charger_inserted())
300 #endif
302 bool batt_safe = battery_level_safe();
303 int audio_stat = audio_status();
305 FOR_NB_SCREENS(i)
306 screens[i].clear_display();
308 if (batt_safe)
310 #ifdef HAVE_TAGCACHE
311 if (!tagcache_prepare_shutdown())
313 cancel_shutdown();
314 splash(HZ, ID2P(LANG_TAGCACHE_BUSY));
315 return false;
317 #endif
318 if (battery_level() > 10)
319 splash(0, str(LANG_SHUTTINGDOWN));
320 else
322 msg_id = LANG_WARNING_BATTERY_LOW;
323 splashf(0, "%s %s", str(LANG_WARNING_BATTERY_LOW),
324 str(LANG_SHUTTINGDOWN));
327 else
329 msg_id = LANG_WARNING_BATTERY_EMPTY;
330 splashf(0, "%s %s", str(LANG_WARNING_BATTERY_EMPTY),
331 str(LANG_SHUTTINGDOWN));
334 if (global_settings.fade_on_stop
335 && (audio_stat & AUDIO_STATUS_PLAY))
337 fade(false, false);
340 if (batt_safe) /* do not save on critical battery */
342 #if defined(HAVE_RECORDING) && CONFIG_CODEC == SWCODEC
343 if (audio_stat & AUDIO_STATUS_RECORD)
345 rec_command(RECORDING_CMD_STOP);
346 /* wait for stop to complete */
347 while (audio_status() & AUDIO_STATUS_RECORD)
348 sleep(1);
350 #endif
351 bookmark_autobookmark();
353 /* audio_stop_recording == audio_stop for HWCODEC */
354 audio_stop();
356 if (callback != NULL)
357 callback(parameter);
359 #if CONFIG_CODEC != SWCODEC
360 /* wait for audio_stop or audio_stop_recording to complete */
361 while (audio_status())
362 sleep(1);
363 #endif
365 #if defined(HAVE_RECORDING) && CONFIG_CODEC == SWCODEC
366 audio_close_recording();
367 #endif
369 if(global_settings.talk_menu)
371 bool enqueue = false;
372 if(msg_id != -1)
374 talk_id(msg_id, enqueue);
375 enqueue = true;
377 talk_id(LANG_SHUTTINGDOWN, enqueue);
378 #if CONFIG_CODEC == SWCODEC
379 voice_wait();
380 #endif
383 system_flush();
384 #ifdef HAVE_EEPROM_SETTINGS
385 if (firmware_settings.initialized)
387 firmware_settings.disk_clean = true;
388 firmware_settings.bl_version = 0;
389 eeprom_settings_store();
391 #endif
393 #ifdef HAVE_DIRCACHE
394 else
395 dircache_disable();
396 #endif
398 shutdown_hw();
400 #endif
401 return false;
404 bool list_stop_handler(void)
406 bool ret = false;
408 /* Stop the music if it is playing */
409 if(audio_status())
411 if (!global_settings.party_mode)
413 if (global_settings.fade_on_stop)
414 fade(false, false);
415 bookmark_autobookmark();
416 audio_stop();
417 ret = true; /* bookmarking can make a refresh necessary */
420 #if CONFIG_CHARGING
421 #if (CONFIG_KEYPAD == RECORDER_PAD) && !defined(HAVE_SW_POWEROFF)
422 else
424 if (charger_inserted())
425 charging_splash();
426 else
427 shutdown_screen(); /* won't return if shutdown actually happens */
429 ret = true; /* screen is dirty, caller needs to refresh */
431 #endif
432 #ifndef HAVE_POWEROFF_WHILE_CHARGING
434 static long last_off = 0;
436 if (TIME_BEFORE(current_tick, last_off + HZ/2))
438 if (charger_inserted())
440 charging_splash();
441 ret = true; /* screen is dirty, caller needs to refresh */
444 last_off = current_tick;
446 #endif
447 #endif /* CONFIG_CHARGING */
448 return ret;
451 #if CONFIG_CHARGING
452 static bool waiting_to_resume_play = false;
453 static long play_resume_tick;
455 static void car_adapter_mode_processing(bool inserted)
457 if (global_settings.car_adapter_mode)
459 if(inserted)
462 * Just got plugged in, delay & resume if we were playing
464 if (audio_status() & AUDIO_STATUS_PAUSE)
466 /* delay resume a bit while the engine is cranking */
467 play_resume_tick = current_tick + HZ*5;
468 waiting_to_resume_play = true;
471 else
474 * Just got unplugged, pause if playing
476 if ((audio_status() & AUDIO_STATUS_PLAY) &&
477 !(audio_status() & AUDIO_STATUS_PAUSE))
479 if (global_settings.fade_on_stop)
480 fade(false, false);
481 else
482 audio_pause();
484 waiting_to_resume_play = false;
489 static void car_adapter_tick(void)
491 if (waiting_to_resume_play)
493 if (TIME_AFTER(current_tick, play_resume_tick))
495 if (audio_status() & AUDIO_STATUS_PAUSE)
497 queue_broadcast(SYS_CAR_ADAPTER_RESUME, 0);
499 waiting_to_resume_play = false;
504 void car_adapter_mode_init(void)
506 tick_add_task(car_adapter_tick);
508 #endif
510 #ifdef HAVE_HEADPHONE_DETECTION
511 static void unplug_change(bool inserted)
513 static bool headphone_caused_pause = false;
515 if (global_settings.unplug_mode)
517 int audio_stat = audio_status();
518 if (inserted)
520 if ((audio_stat & AUDIO_STATUS_PLAY) &&
521 headphone_caused_pause &&
522 global_settings.unplug_mode > 1 )
523 audio_resume();
524 backlight_on();
525 headphone_caused_pause = false;
526 } else {
527 if ((audio_stat & AUDIO_STATUS_PLAY) &&
528 !(audio_stat & AUDIO_STATUS_PAUSE))
530 headphone_caused_pause = true;
531 audio_pause();
533 if (global_settings.unplug_rw)
535 if (audio_current_track()->elapsed >
536 (unsigned long)(global_settings.unplug_rw*1000))
537 audio_ff_rewind(audio_current_track()->elapsed -
538 (global_settings.unplug_rw*1000));
539 else
540 audio_ff_rewind(0);
546 #endif
548 long default_event_handler_ex(long event, void (*callback)(void *), void *parameter)
550 switch(event)
552 case SYS_BATTERY_UPDATE:
553 if(global_settings.talk_battery_level)
555 talk_ids(true, VOICE_PAUSE, VOICE_PAUSE,
556 LANG_BATTERY_TIME,
557 TALK_ID(battery_level(), UNIT_PERCENT),
558 VOICE_PAUSE);
559 talk_force_enqueue_next();
561 break;
562 case SYS_USB_CONNECTED:
563 if (callback != NULL)
564 callback(parameter);
565 #if (CONFIG_STORAGE & STORAGE_MMC)
566 if (!mmc_touched() ||
567 (mmc_remove_request() == SYS_HOTSWAP_EXTRACTED))
568 #endif
570 system_flush();
571 #ifdef BOOTFILE
572 #if !defined(USB_NONE) && !defined(USB_IPODSTYLE)
573 check_bootfile(false); /* gets initial size */
574 #endif
575 #endif
576 usb_screen();
577 #ifdef BOOTFILE
578 #if !defined(USB_NONE) && !defined(USB_IPODSTYLE)
579 check_bootfile(true);
580 #endif
581 #endif
582 system_restore();
584 return SYS_USB_CONNECTED;
585 case SYS_POWEROFF:
586 if (!clean_shutdown(callback, parameter))
587 return SYS_POWEROFF;
588 break;
589 #if CONFIG_CHARGING
590 case SYS_CHARGER_CONNECTED:
591 car_adapter_mode_processing(true);
592 return SYS_CHARGER_CONNECTED;
594 case SYS_CHARGER_DISCONNECTED:
595 car_adapter_mode_processing(false);
596 return SYS_CHARGER_DISCONNECTED;
598 case SYS_CAR_ADAPTER_RESUME:
599 audio_resume();
600 return SYS_CAR_ADAPTER_RESUME;
601 #endif
602 #ifdef HAVE_HEADPHONE_DETECTION
603 case SYS_PHONE_PLUGGED:
604 unplug_change(true);
605 return SYS_PHONE_PLUGGED;
607 case SYS_PHONE_UNPLUGGED:
608 unplug_change(false);
609 return SYS_PHONE_UNPLUGGED;
610 #endif
611 #ifdef IPOD_ACCESSORY_PROTOCOL
612 case SYS_IAP_PERIODIC:
613 iap_periodic();
614 return SYS_IAP_PERIODIC;
615 case SYS_IAP_HANDLEPKT:
616 iap_handlepkt();
617 return SYS_IAP_HANDLEPKT;
618 #endif
620 return 0;
623 long default_event_handler(long event)
625 return default_event_handler_ex(event, NULL, NULL);
628 int show_logo( void )
630 #ifdef HAVE_LCD_BITMAP
631 char version[32];
632 int font_h, font_w;
634 snprintf(version, sizeof(version), "Ver. %s", appsversion);
636 lcd_clear_display();
637 #ifdef SANSA_CLIP /* display the logo in the blue area of the screen */
638 lcd_setfont(FONT_SYSFIXED);
639 lcd_getstringsize((unsigned char *)"A", &font_w, &font_h);
640 lcd_putsxy((LCD_WIDTH/2) - ((strlen(version)*font_w)/2),
641 0, (unsigned char *)version);
642 lcd_bitmap(rockboxlogo, 0, 16, BMPWIDTH_rockboxlogo, BMPHEIGHT_rockboxlogo);
643 #else
644 lcd_bitmap(rockboxlogo, 0, 10, BMPWIDTH_rockboxlogo, BMPHEIGHT_rockboxlogo);
645 lcd_setfont(FONT_SYSFIXED);
646 lcd_getstringsize((unsigned char *)"A", &font_w, &font_h);
647 lcd_putsxy((LCD_WIDTH/2) - ((strlen(version)*font_w)/2),
648 LCD_HEIGHT-font_h, (unsigned char *)version);
649 #endif
650 lcd_setfont(FONT_UI);
652 #else
653 char *rockbox = " ROCKbox!";
655 lcd_clear_display();
656 lcd_double_height(true);
657 lcd_puts(0, 0, rockbox);
658 lcd_puts_scroll(0, 1, appsversion);
659 #endif
660 lcd_update();
662 #ifdef HAVE_REMOTE_LCD
663 lcd_remote_clear_display();
664 lcd_remote_bitmap(remote_rockboxlogo, 0, 10, BMPWIDTH_remote_rockboxlogo,
665 BMPHEIGHT_remote_rockboxlogo);
666 lcd_remote_setfont(FONT_SYSFIXED);
667 lcd_remote_getstringsize((unsigned char *)"A", &font_w, &font_h);
668 lcd_remote_putsxy((LCD_REMOTE_WIDTH/2) - ((strlen(version)*font_w)/2),
669 LCD_REMOTE_HEIGHT-font_h, (unsigned char *)version);
670 lcd_remote_setfont(FONT_UI);
671 lcd_remote_update();
672 #endif
674 return 0;
677 #if CONFIG_CODEC == SWCODEC
678 int get_replaygain_mode(bool have_track_gain, bool have_album_gain)
680 int type;
682 bool track = ((global_settings.replaygain_type == REPLAYGAIN_TRACK)
683 || ((global_settings.replaygain_type == REPLAYGAIN_SHUFFLE)
684 && global_settings.playlist_shuffle));
686 type = (!track && have_album_gain) ? REPLAYGAIN_ALBUM
687 : have_track_gain ? REPLAYGAIN_TRACK : -1;
689 return type;
691 #endif
693 #ifdef BOOTFILE
694 #if !defined(USB_NONE) && !defined(USB_IPODSTYLE)
696 memorize/compare details about the BOOTFILE
697 we don't use dircache because it may not be up to date after
698 USB disconnect (scanning in the background)
700 void check_bootfile(bool do_rolo)
702 static unsigned short wrtdate = 0;
703 static unsigned short wrttime = 0;
704 DIR* dir = NULL;
705 struct dirent* entry = NULL;
707 /* 1. open BOOTDIR and find the BOOTFILE dir entry */
708 dir = opendir(BOOTDIR);
710 if(!dir) return; /* do we want an error splash? */
712 /* loop all files in BOOTDIR */
713 while(0 != (entry = readdir(dir)))
715 if(!strcasecmp(entry->d_name, BOOTFILE))
717 /* found the bootfile */
718 if(wrtdate && do_rolo)
720 if((entry->wrtdate != wrtdate) ||
721 (entry->wrttime != wrttime))
723 static const char *lines[] = { ID2P(LANG_BOOT_CHANGED),
724 ID2P(LANG_REBOOT_NOW) };
725 static const struct text_message message={ lines, 2 };
726 button_clear_queue(); /* Empty the keyboard buffer */
727 if(gui_syncyesno_run(&message, NULL, NULL) == YESNO_YES)
728 rolo_load(BOOTDIR "/" BOOTFILE);
731 wrtdate = entry->wrtdate;
732 wrttime = entry->wrttime;
735 closedir(dir);
737 #endif
738 #endif
740 /* check range, set volume and save settings */
741 void setvol(void)
743 const int min_vol = sound_min(SOUND_VOLUME);
744 const int max_vol = sound_max(SOUND_VOLUME);
745 if (global_settings.volume < min_vol)
746 global_settings.volume = min_vol;
747 if (global_settings.volume > max_vol)
748 global_settings.volume = max_vol;
749 sound_set_volume(global_settings.volume);
750 settings_save();
753 char* strrsplt(char* str, int c)
755 char* s = strrchr(str, c);
757 if (s != NULL)
759 *s++ = '\0';
761 else
763 s = str;
766 return s;
769 char* skip_whitespace(char* const str)
771 char *s = str;
773 while (isspace(*s))
774 s++;
776 return s;
779 /* Test file existence, using dircache of possible */
780 bool file_exists(const char *file)
782 int fd;
784 if (!file || strlen(file) <= 0)
785 return false;
787 #ifdef HAVE_DIRCACHE
788 if (dircache_is_enabled())
789 return (dircache_get_entry_ptr(file) != NULL);
790 #endif
792 fd = open(file, O_RDONLY);
793 if (fd < 0)
794 return false;
795 close(fd);
796 return true;
799 bool dir_exists(const char *path)
801 DIR* d = opendir(path);
802 if (!d)
803 return false;
804 closedir(d);
805 return true;
809 * removes the extension of filename (if it doesn't start with a .)
810 * puts the result in buffer
812 char *strip_extension(char* buffer, int buffer_size, const char *filename)
814 char *dot = strrchr(filename, '.');
815 int len;
817 if (buffer_size <= 0)
819 return NULL;
822 buffer_size--; /* Make room for end nil */
824 if (dot != 0 && filename[0] != '.')
826 len = dot - filename;
827 len = MIN(len, buffer_size);
828 strncpy(buffer, filename, len);
830 else
832 len = buffer_size;
833 strncpy(buffer, filename, buffer_size);
836 buffer[len] = 0;
838 return buffer;
840 #endif /* !defined(__PCTOOL__) */
842 /* Format time into buf.
844 * buf - buffer to format to.
845 * buf_size - size of buffer.
846 * t - time to format, in milliseconds.
848 void format_time(char* buf, int buf_size, long t)
850 if ( t < 3600000 )
852 snprintf(buf, buf_size, "%d:%02d",
853 (int) (t / 60000), (int) (t % 60000 / 1000));
855 else
857 snprintf(buf, buf_size, "%d:%02d:%02d",
858 (int) (t / 3600000), (int) (t % 3600000 / 60000),
859 (int) (t % 60000 / 1000));
864 /** Open a UTF-8 file and set file descriptor to first byte after BOM.
865 * If no BOM is present this behaves like open().
866 * If the file is opened for writing and O_TRUNC is set, write a BOM to
867 * the opened file and leave the file pointer set after the BOM.
869 #define BOM "\xef\xbb\xbf"
870 #define BOM_SIZE 3
872 int open_utf8(const char* pathname, int flags)
874 int fd;
875 unsigned char bom[BOM_SIZE];
877 fd = open(pathname, flags);
878 if(fd < 0)
879 return fd;
881 if(flags & (O_TRUNC | O_WRONLY))
883 write(fd, BOM, BOM_SIZE);
885 else
887 read(fd, bom, BOM_SIZE);
888 /* check for BOM */
889 if(memcmp(bom, BOM, BOM_SIZE))
890 lseek(fd, 0, SEEK_SET);
892 return fd;
896 #ifdef HAVE_LCD_COLOR
898 * Helper function to convert a string of 6 hex digits to a native colour
901 static int hex2dec(int c)
903 return (((c) >= '0' && ((c) <= '9')) ? (c) - '0' :
904 (toupper(c)) - 'A' + 10);
907 int hex_to_rgb(const char* hex, int* color)
909 int red, green, blue;
910 int i = 0;
912 while ((i < 6) && (isxdigit(hex[i])))
913 i++;
915 if (i < 6)
916 return -1;
918 red = (hex2dec(hex[0]) << 4) | hex2dec(hex[1]);
919 green = (hex2dec(hex[2]) << 4) | hex2dec(hex[3]);
920 blue = (hex2dec(hex[4]) << 4) | hex2dec(hex[5]);
922 *color = LCD_RGBPACK(red,green,blue);
924 return 0;
926 #endif /* HAVE_LCD_COLOR */
928 #ifdef HAVE_LCD_BITMAP
929 /* A simplified scanf - used (at time of writing) by wps parsing functions.
931 fmt - char array specifying the format of each list option. Valid values
932 are: d - int
933 s - string (sets pointer to string, without copying)
934 c - hex colour (RGB888 - e.g. ff00ff)
935 g - greyscale "colour" (0-3)
936 set_vals - if not NULL 1 is set in the bitplace if the item was read OK
937 0 if not read.
938 first item is LSB, (max 32 items! )
939 Stops parseing if an item is invalid unless the item == '-'
940 sep - list separator (e.g. ',' or '|')
941 str - string to parse, must be terminated by 0 or sep
942 ... - pointers to store the parsed values
944 return value - pointer to char after parsed data, 0 if there was an error.
948 /* '0'-'3' are ASCII 0x30 to 0x33 */
949 #define is0123(x) (((x) & 0xfc) == 0x30)
951 const char* parse_list(const char *fmt, uint32_t *set_vals,
952 const char sep, const char* str, ...)
954 va_list ap;
955 const char* p = str, *f = fmt;
956 const char** s;
957 int* d;
958 bool set;
959 int i=0;
961 va_start(ap, str);
962 if (set_vals)
963 *set_vals = 0;
964 while (*fmt)
966 /* Check for separator, if we're not at the start */
967 if (f != fmt)
969 if (*p != sep)
970 goto err;
971 p++;
973 set = false;
974 switch (*fmt++)
976 case 's': /* string - return a pointer to it (not a copy) */
977 s = va_arg(ap, const char **);
979 *s = p;
980 while (*p && *p != sep)
981 p++;
982 set = (s[0][0]!='-') && (s[0][1]!=sep) ;
983 break;
985 case 'd': /* int */
986 d = va_arg(ap, int*);
987 if (!isdigit(*p))
989 if (!set_vals || *p != '-')
990 goto err;
991 while (*p && *p != sep)
992 p++;
994 else
996 *d = *p++ - '0';
997 while (isdigit(*p))
998 *d = (*d * 10) + (*p++ - '0');
999 set = true;
1002 break;
1004 #ifdef HAVE_LCD_COLOR
1005 case 'c': /* colour (rrggbb - e.g. f3c1a8) */
1006 d = va_arg(ap, int*);
1008 if (hex_to_rgb(p, d) < 0)
1010 if (!set_vals || *p != '-')
1011 goto err;
1012 while (*p && *p != sep)
1013 p++;
1015 else
1017 p += 6;
1018 set = true;
1021 break;
1022 #endif
1024 #if LCD_DEPTH == 2 || (defined(HAVE_REMOTE_LCD) && LCD_REMOTE_DEPTH == 2)
1025 case 'g': /* greyscale colour (0-3) */
1026 d = va_arg(ap, int*);
1028 if (is0123(*p))
1030 *d = *p++ - '0';
1031 set = true;
1033 else if (!set_vals || *p != '-')
1034 goto err;
1035 else
1037 while (*p && *p != sep)
1038 p++;
1041 break;
1042 #endif
1044 default: /* Unknown format type */
1045 goto err;
1046 break;
1048 if (set_vals && set)
1049 *set_vals |= (1<<i);
1050 i++;
1053 va_end(ap);
1054 return p;
1056 err:
1057 va_end(ap);
1058 return 0;
1060 #endif