Give test_codec the ability to checksum files or folders of files, usefull to verify...
[kugel-rb.git] / apps / misc.c
blob6677c5f9b9a81b8a4a31395a423c777c8ad0c8db
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 "lang.h"
34 #include "dir.h"
35 #include "lcd-remote.h"
36 #include "errno.h"
37 #include "system.h"
38 #include "timefuncs.h"
39 #include "screens.h"
40 #include "usb_screen.h"
41 #include "talk.h"
42 #include "audio.h"
43 #include "mp3_playback.h"
44 #include "settings.h"
45 #include "storage.h"
46 #include "ata_idle_notify.h"
47 #include "kernel.h"
48 #include "power.h"
49 #include "powermgmt.h"
50 #include "backlight.h"
51 #include "version.h"
52 #include "font.h"
53 #include "splash.h"
54 #include "tagcache.h"
55 #include "scrobbler.h"
56 #include "sound.h"
57 #include "playlist.h"
58 #include "yesno.h"
59 #include "viewport.h"
61 #ifdef IPOD_ACCESSORY_PROTOCOL
62 #include "iap.h"
63 #endif
65 #if (CONFIG_STORAGE & STORAGE_MMC)
66 #include "ata_mmc.h"
67 #endif
68 #include "tree.h"
69 #include "eeprom_settings.h"
70 #if defined(HAVE_RECORDING) && !defined(__PCTOOL__)
71 #include "recording.h"
72 #endif
73 #if defined(HAVE_LCD_BITMAP) && !defined(__PCTOOL__)
74 #include "bmp.h"
75 #include "icons.h"
76 #endif /* End HAVE_LCD_BITMAP */
77 #include "bookmark.h"
78 #include "wps.h"
79 #include "playback.h"
81 #ifdef BOOTFILE
82 #if !defined(USB_NONE) && !defined(USB_HANDLED_BY_OF)
83 #include "rolo.h"
84 #endif
85 #endif
87 /* units used with output_dyn_value */
88 const unsigned char * const byte_units[] =
90 ID2P(LANG_BYTE),
91 ID2P(LANG_KILOBYTE),
92 ID2P(LANG_MEGABYTE),
93 ID2P(LANG_GIGABYTE)
96 const unsigned char * const * const kbyte_units = &byte_units[1];
98 /* Format a large-range value for output, using the appropriate unit so that
99 * the displayed value is in the range 1 <= display < 1000 (1024 for "binary"
100 * units) if possible, and 3 significant digits are shown. If a buffer is
101 * given, the result is snprintf()'d into that buffer, otherwise the result is
102 * voiced.*/
103 char *output_dyn_value(char *buf, int buf_size, int value,
104 const unsigned char * const *units, bool bin_scale)
106 int scale = bin_scale ? 1024 : 1000;
107 int fraction = 0;
108 int unit_no = 0;
109 char tbuf[5];
111 while (value >= scale)
113 fraction = value % scale;
114 value /= scale;
115 unit_no++;
117 if (bin_scale)
118 fraction = fraction * 1000 / 1024;
120 if (value >= 100 || !unit_no)
121 tbuf[0] = '\0';
122 else if (value >= 10)
123 snprintf(tbuf, sizeof(tbuf), "%01d", fraction / 100);
124 else
125 snprintf(tbuf, sizeof(tbuf), "%02d", fraction / 10);
127 if (buf)
129 if (strlen(tbuf))
130 snprintf(buf, buf_size, "%d%s%s%s", value, str(LANG_POINT),
131 tbuf, P2STR(units[unit_no]));
132 else
133 snprintf(buf, buf_size, "%d%s", value, P2STR(units[unit_no]));
135 else
137 talk_fractional(tbuf, value, P2ID(units[unit_no]));
139 return buf;
142 /* Ask the user if they really want to erase the current dynamic playlist
143 * returns true if the playlist should be replaced */
144 bool warn_on_pl_erase(void)
146 if (global_settings.warnon_erase_dynplaylist &&
147 !global_settings.party_mode &&
148 playlist_modified(NULL))
150 static const char *lines[] =
151 {ID2P(LANG_WARN_ERASEDYNPLAYLIST_PROMPT)};
152 static const struct text_message message={lines, 1};
154 return (gui_syncyesno_run(&message, NULL, NULL) == YESNO_YES);
156 else
157 return true;
160 /* Read (up to) a line of text from fd into buffer and return number of bytes
161 * read (which may be larger than the number of bytes stored in buffer). If
162 * an error occurs, -1 is returned (and buffer contains whatever could be
163 * read). A line is terminated by a LF char. Neither LF nor CR chars are
164 * stored in buffer.
166 int read_line(int fd, char* buffer, int buffer_size)
168 int count = 0;
169 int num_read = 0;
171 errno = 0;
173 while (count < buffer_size)
175 unsigned char c;
177 if (1 != read(fd, &c, 1))
178 break;
180 num_read++;
182 if ( c == '\n' )
183 break;
185 if ( c == '\r' )
186 continue;
188 buffer[count++] = c;
191 buffer[MIN(count, buffer_size - 1)] = 0;
193 return errno ? -1 : num_read;
196 /* Performance optimized version of the previous function. */
197 int fast_readline(int fd, char *buf, int buf_size, void *parameters,
198 int (*callback)(int n, const char *buf, void *parameters))
200 char *p, *next;
201 int rc, pos = 0;
202 int count = 0;
204 while ( 1 )
206 next = NULL;
208 rc = read(fd, &buf[pos], buf_size - pos - 1);
209 if (rc >= 0)
210 buf[pos+rc] = '\0';
212 if ( (p = strchr(buf, '\r')) != NULL)
214 *p = '\0';
215 next = ++p;
217 else
218 p = buf;
220 if ( (p = strchr(p, '\n')) != NULL)
222 *p = '\0';
223 next = ++p;
226 rc = callback(count, buf, parameters);
227 if (rc < 0)
228 return rc;
230 count++;
231 if (next)
233 pos = buf_size - ((long)next - (long)buf) - 1;
234 memmove(buf, next, pos);
236 else
237 break ;
240 return 0;
243 /* parse a line from a configuration file. the line format is:
245 name: value
247 Any whitespace before setting name or value (after ':') is ignored.
248 A # as first non-whitespace character discards the whole line.
249 Function sets pointers to null-terminated setting name and value.
250 Returns false if no valid config entry was found.
253 bool settings_parseline(char* line, char** name, char** value)
255 char* ptr;
257 line = skip_whitespace(line);
259 if ( *line == '#' )
260 return false;
262 ptr = strchr(line, ':');
263 if ( !ptr )
264 return false;
266 *name = line;
267 *ptr = 0;
268 ptr++;
269 ptr = skip_whitespace(ptr);
270 *value = ptr;
271 return true;
274 static void system_flush(void)
276 scrobbler_shutdown();
277 playlist_shutdown();
278 tree_flush();
279 call_storage_idle_notifys(true); /*doesnt work on usb and shutdown from ata thread */
282 static void system_restore(void)
284 tree_restore();
285 scrobbler_init();
288 static bool clean_shutdown(void (*callback)(void *), void *parameter)
290 #ifdef SIMULATOR
291 (void)callback;
292 (void)parameter;
293 bookmark_autobookmark();
294 call_storage_idle_notifys(true);
295 exit(0);
296 #else
297 long msg_id = -1;
298 int i;
300 scrobbler_poweroff();
302 #if CONFIG_CHARGING && !defined(HAVE_POWEROFF_WHILE_CHARGING)
303 if(!charger_inserted())
304 #endif
306 bool batt_safe = battery_level_safe();
307 int audio_stat = audio_status();
309 FOR_NB_SCREENS(i)
311 screens[i].clear_display();
312 screens[i].update();
315 if (batt_safe)
317 #ifdef HAVE_TAGCACHE
318 if (!tagcache_prepare_shutdown())
320 cancel_shutdown();
321 splash(HZ, ID2P(LANG_TAGCACHE_BUSY));
322 return false;
324 #endif
325 if (battery_level() > 10)
326 splash(0, str(LANG_SHUTTINGDOWN));
327 else
329 msg_id = LANG_WARNING_BATTERY_LOW;
330 splashf(0, "%s %s", str(LANG_WARNING_BATTERY_LOW),
331 str(LANG_SHUTTINGDOWN));
334 else
336 msg_id = LANG_WARNING_BATTERY_EMPTY;
337 splashf(0, "%s %s", str(LANG_WARNING_BATTERY_EMPTY),
338 str(LANG_SHUTTINGDOWN));
341 if (global_settings.fade_on_stop
342 && (audio_stat & AUDIO_STATUS_PLAY))
344 fade(false, false);
347 if (batt_safe) /* do not save on critical battery */
349 #if defined(HAVE_RECORDING) && CONFIG_CODEC == SWCODEC
350 if (audio_stat & AUDIO_STATUS_RECORD)
352 rec_command(RECORDING_CMD_STOP);
353 /* wait for stop to complete */
354 while (audio_status() & AUDIO_STATUS_RECORD)
355 sleep(1);
357 #endif
358 bookmark_autobookmark();
360 /* audio_stop_recording == audio_stop for HWCODEC */
361 audio_stop();
363 if (callback != NULL)
364 callback(parameter);
366 #if CONFIG_CODEC != SWCODEC
367 /* wait for audio_stop or audio_stop_recording to complete */
368 while (audio_status())
369 sleep(1);
370 #endif
372 #if defined(HAVE_RECORDING) && CONFIG_CODEC == SWCODEC
373 audio_close_recording();
374 #endif
376 if(global_settings.talk_menu)
378 bool enqueue = false;
379 if(msg_id != -1)
381 talk_id(msg_id, enqueue);
382 enqueue = true;
384 talk_id(LANG_SHUTTINGDOWN, enqueue);
385 #if CONFIG_CODEC == SWCODEC
386 voice_wait();
387 #endif
390 system_flush();
391 #ifdef HAVE_EEPROM_SETTINGS
392 if (firmware_settings.initialized)
394 firmware_settings.disk_clean = true;
395 firmware_settings.bl_version = 0;
396 eeprom_settings_store();
398 #endif
400 #ifdef HAVE_DIRCACHE
401 else
402 dircache_disable();
403 #endif
405 shutdown_hw();
407 #endif
408 return false;
411 bool list_stop_handler(void)
413 bool ret = false;
415 /* Stop the music if it is playing */
416 if(audio_status())
418 if (!global_settings.party_mode)
420 if (global_settings.fade_on_stop)
421 fade(false, false);
422 bookmark_autobookmark();
423 audio_stop();
424 ret = true; /* bookmarking can make a refresh necessary */
427 #if CONFIG_CHARGING
428 #if (CONFIG_KEYPAD == RECORDER_PAD) && !defined(HAVE_SW_POWEROFF)
429 else
431 if (charger_inserted())
432 charging_splash();
433 else
434 shutdown_screen(); /* won't return if shutdown actually happens */
436 ret = true; /* screen is dirty, caller needs to refresh */
438 #endif
439 #ifndef HAVE_POWEROFF_WHILE_CHARGING
441 static long last_off = 0;
443 if (TIME_BEFORE(current_tick, last_off + HZ/2))
445 if (charger_inserted())
447 charging_splash();
448 ret = true; /* screen is dirty, caller needs to refresh */
451 last_off = current_tick;
453 #endif
454 #endif /* CONFIG_CHARGING */
455 return ret;
458 #if CONFIG_CHARGING
459 static bool waiting_to_resume_play = false;
460 static long play_resume_tick;
462 static void car_adapter_mode_processing(bool inserted)
464 if (global_settings.car_adapter_mode)
466 if(inserted)
469 * Just got plugged in, delay & resume if we were playing
471 if (audio_status() & AUDIO_STATUS_PAUSE)
473 /* delay resume a bit while the engine is cranking */
474 play_resume_tick = current_tick + HZ*5;
475 waiting_to_resume_play = true;
478 else
481 * Just got unplugged, pause if playing
483 if ((audio_status() & AUDIO_STATUS_PLAY) &&
484 !(audio_status() & AUDIO_STATUS_PAUSE))
486 if (global_settings.fade_on_stop)
487 fade(false, false);
488 else
489 audio_pause();
491 waiting_to_resume_play = false;
496 static void car_adapter_tick(void)
498 if (waiting_to_resume_play)
500 if (TIME_AFTER(current_tick, play_resume_tick))
502 if (audio_status() & AUDIO_STATUS_PAUSE)
504 queue_broadcast(SYS_CAR_ADAPTER_RESUME, 0);
506 waiting_to_resume_play = false;
511 void car_adapter_mode_init(void)
513 tick_add_task(car_adapter_tick);
515 #endif
517 #ifdef HAVE_HEADPHONE_DETECTION
518 static void unplug_change(bool inserted)
520 static bool headphone_caused_pause = false;
522 if (global_settings.unplug_mode)
524 int audio_stat = audio_status();
525 if (inserted)
527 if ((audio_stat & AUDIO_STATUS_PLAY) &&
528 headphone_caused_pause &&
529 global_settings.unplug_mode > 1 )
530 audio_resume();
531 backlight_on();
532 headphone_caused_pause = false;
533 } else {
534 if ((audio_stat & AUDIO_STATUS_PLAY) &&
535 !(audio_stat & AUDIO_STATUS_PAUSE))
537 headphone_caused_pause = true;
538 audio_pause();
540 if (global_settings.unplug_rw)
542 if (audio_current_track()->elapsed >
543 (unsigned long)(global_settings.unplug_rw*1000))
544 audio_ff_rewind(audio_current_track()->elapsed -
545 (global_settings.unplug_rw*1000));
546 else
547 audio_ff_rewind(0);
553 #endif
555 long default_event_handler_ex(long event, void (*callback)(void *), void *parameter)
557 switch(event)
559 case SYS_BATTERY_UPDATE:
560 if(global_settings.talk_battery_level)
562 talk_ids(true, VOICE_PAUSE, VOICE_PAUSE,
563 LANG_BATTERY_TIME,
564 TALK_ID(battery_level(), UNIT_PERCENT),
565 VOICE_PAUSE);
566 talk_force_enqueue_next();
568 break;
569 case SYS_USB_CONNECTED:
570 if (callback != NULL)
571 callback(parameter);
572 #if (CONFIG_STORAGE & STORAGE_MMC)
573 if (!mmc_touched() ||
574 (mmc_remove_request() == SYS_HOTSWAP_EXTRACTED))
575 #endif
577 system_flush();
578 #ifdef BOOTFILE
579 #if !defined(USB_NONE) && !defined(USB_HANDLED_BY_OF)
580 check_bootfile(false); /* gets initial size */
581 #endif
582 #endif
583 gui_usb_screen_run();
584 #ifdef BOOTFILE
585 #if !defined(USB_NONE) && !defined(USB_HANDLED_BY_OF)
586 check_bootfile(true);
587 #endif
588 #endif
589 system_restore();
591 return SYS_USB_CONNECTED;
592 case SYS_POWEROFF:
593 if (!clean_shutdown(callback, parameter))
594 return SYS_POWEROFF;
595 break;
596 #if CONFIG_CHARGING
597 case SYS_CHARGER_CONNECTED:
598 car_adapter_mode_processing(true);
599 return SYS_CHARGER_CONNECTED;
601 case SYS_CHARGER_DISCONNECTED:
602 car_adapter_mode_processing(false);
603 return SYS_CHARGER_DISCONNECTED;
605 case SYS_CAR_ADAPTER_RESUME:
606 audio_resume();
607 return SYS_CAR_ADAPTER_RESUME;
608 #endif
609 #ifdef HAVE_HEADPHONE_DETECTION
610 case SYS_PHONE_PLUGGED:
611 unplug_change(true);
612 return SYS_PHONE_PLUGGED;
614 case SYS_PHONE_UNPLUGGED:
615 unplug_change(false);
616 return SYS_PHONE_UNPLUGGED;
617 #endif
618 #ifdef IPOD_ACCESSORY_PROTOCOL
619 case SYS_IAP_PERIODIC:
620 iap_periodic();
621 return SYS_IAP_PERIODIC;
622 case SYS_IAP_HANDLEPKT:
623 iap_handlepkt();
624 return SYS_IAP_HANDLEPKT;
625 #endif
627 return 0;
630 long default_event_handler(long event)
632 return default_event_handler_ex(event, NULL, NULL);
635 int show_logo( void )
637 #ifdef HAVE_LCD_BITMAP
638 char version[32];
639 int font_h, font_w;
641 snprintf(version, sizeof(version), "Ver. %s", appsversion);
643 lcd_clear_display();
644 #ifdef SANSA_CLIP /* display the logo in the blue area of the screen */
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 0, (unsigned char *)version);
649 lcd_bitmap(rockboxlogo, 0, 16, BMPWIDTH_rockboxlogo, BMPHEIGHT_rockboxlogo);
650 #else
651 lcd_bitmap(rockboxlogo, 0, 10, BMPWIDTH_rockboxlogo, BMPHEIGHT_rockboxlogo);
652 lcd_setfont(FONT_SYSFIXED);
653 lcd_getstringsize((unsigned char *)"A", &font_w, &font_h);
654 lcd_putsxy((LCD_WIDTH/2) - ((strlen(version)*font_w)/2),
655 LCD_HEIGHT-font_h, (unsigned char *)version);
656 #endif
657 lcd_setfont(FONT_UI);
659 #else
660 char *rockbox = " ROCKbox!";
662 lcd_clear_display();
663 lcd_double_height(true);
664 lcd_puts(0, 0, rockbox);
665 lcd_puts_scroll(0, 1, appsversion);
666 #endif
667 lcd_update();
669 #ifdef HAVE_REMOTE_LCD
670 lcd_remote_clear_display();
671 lcd_remote_bitmap(remote_rockboxlogo, 0, 10, BMPWIDTH_remote_rockboxlogo,
672 BMPHEIGHT_remote_rockboxlogo);
673 lcd_remote_setfont(FONT_SYSFIXED);
674 lcd_remote_getstringsize((unsigned char *)"A", &font_w, &font_h);
675 lcd_remote_putsxy((LCD_REMOTE_WIDTH/2) - ((strlen(version)*font_w)/2),
676 LCD_REMOTE_HEIGHT-font_h, (unsigned char *)version);
677 lcd_remote_setfont(FONT_UI);
678 lcd_remote_update();
679 #endif
681 return 0;
684 #ifdef BOOTFILE
685 #if !defined(USB_NONE) && !defined(USB_HANDLED_BY_OF)
687 memorize/compare details about the BOOTFILE
688 we don't use dircache because it may not be up to date after
689 USB disconnect (scanning in the background)
691 void check_bootfile(bool do_rolo)
693 static unsigned short wrtdate = 0;
694 static unsigned short wrttime = 0;
695 DIR* dir = NULL;
696 struct dirent* entry = NULL;
698 /* 1. open BOOTDIR and find the BOOTFILE dir entry */
699 dir = opendir(BOOTDIR);
701 if(!dir) return; /* do we want an error splash? */
703 /* loop all files in BOOTDIR */
704 while(0 != (entry = readdir(dir)))
706 if(!strcasecmp(entry->d_name, BOOTFILE))
708 /* found the bootfile */
709 if(wrtdate && do_rolo)
711 if((entry->wrtdate != wrtdate) ||
712 (entry->wrttime != wrttime))
714 static const char *lines[] = { ID2P(LANG_BOOT_CHANGED),
715 ID2P(LANG_REBOOT_NOW) };
716 static const struct text_message message={ lines, 2 };
717 button_clear_queue(); /* Empty the keyboard buffer */
718 if(gui_syncyesno_run(&message, NULL, NULL) == YESNO_YES)
719 rolo_load(BOOTDIR "/" BOOTFILE);
722 wrtdate = entry->wrtdate;
723 wrttime = entry->wrttime;
726 closedir(dir);
728 #endif
729 #endif
731 /* check range, set volume and save settings */
732 void setvol(void)
734 const int min_vol = sound_min(SOUND_VOLUME);
735 const int max_vol = sound_max(SOUND_VOLUME);
736 if (global_settings.volume < min_vol)
737 global_settings.volume = min_vol;
738 if (global_settings.volume > max_vol)
739 global_settings.volume = max_vol;
740 sound_set_volume(global_settings.volume);
741 global_status.last_volume_change = current_tick;
742 settings_save();
745 char* strrsplt(char* str, int c)
747 char* s = strrchr(str, c);
749 if (s != NULL)
751 *s++ = '\0';
753 else
755 s = str;
758 return s;
761 /* Test file existence, using dircache of possible */
762 bool file_exists(const char *file)
764 int fd;
766 if (!file || strlen(file) <= 0)
767 return false;
769 #ifdef HAVE_DIRCACHE
770 if (dircache_is_enabled())
771 return (dircache_get_entry_ptr(file) != NULL);
772 #endif
774 fd = open(file, O_RDONLY);
775 if (fd < 0)
776 return false;
777 close(fd);
778 return true;
781 bool dir_exists(const char *path)
783 DIR* d = opendir(path);
784 if (!d)
785 return false;
786 closedir(d);
787 return true;
791 * removes the extension of filename (if it doesn't start with a .)
792 * puts the result in buffer
794 char *strip_extension(char* buffer, int buffer_size, const char *filename)
796 char *dot = strrchr(filename, '.');
797 int len;
799 if (buffer_size <= 0)
801 return NULL;
804 buffer_size--; /* Make room for end nil */
806 if (dot != 0 && filename[0] != '.')
808 len = dot - filename;
809 len = MIN(len, buffer_size);
811 else
813 len = buffer_size;
816 strlcpy(buffer, filename, len + 1);
818 return buffer;
820 #endif /* !defined(__PCTOOL__) */
822 char* skip_whitespace(char* const str)
824 char *s = str;
826 while (isspace(*s))
827 s++;
829 return s;
832 /* Format time into buf.
834 * buf - buffer to format to.
835 * buf_size - size of buffer.
836 * t - time to format, in milliseconds.
838 void format_time(char* buf, int buf_size, long t)
840 if ( t < 3600000 )
842 snprintf(buf, buf_size, "%d:%02d",
843 (int) (t / 60000), (int) (t % 60000 / 1000));
845 else
847 snprintf(buf, buf_size, "%d:%02d:%02d",
848 (int) (t / 3600000), (int) (t % 3600000 / 60000),
849 (int) (t % 60000 / 1000));
854 /** Open a UTF-8 file and set file descriptor to first byte after BOM.
855 * If no BOM is present this behaves like open().
856 * If the file is opened for writing and O_TRUNC is set, write a BOM to
857 * the opened file and leave the file pointer set after the BOM.
859 #define BOM "\xef\xbb\xbf"
860 #define BOM_SIZE 3
862 int open_utf8(const char* pathname, int flags)
864 int fd;
865 unsigned char bom[BOM_SIZE];
867 fd = open(pathname, flags);
868 if(fd < 0)
869 return fd;
871 if(flags & (O_TRUNC | O_WRONLY))
873 write(fd, BOM, BOM_SIZE);
875 else
877 read(fd, bom, BOM_SIZE);
878 /* check for BOM */
879 if(memcmp(bom, BOM, BOM_SIZE))
880 lseek(fd, 0, SEEK_SET);
882 return fd;
886 #ifdef HAVE_LCD_COLOR
888 * Helper function to convert a string of 6 hex digits to a native colour
891 static int hex2dec(int c)
893 return (((c) >= '0' && ((c) <= '9')) ? (c) - '0' :
894 (toupper(c)) - 'A' + 10);
897 int hex_to_rgb(const char* hex, int* color)
899 int red, green, blue;
900 int i = 0;
902 while ((i < 6) && (isxdigit(hex[i])))
903 i++;
905 if (i < 6)
906 return -1;
908 red = (hex2dec(hex[0]) << 4) | hex2dec(hex[1]);
909 green = (hex2dec(hex[2]) << 4) | hex2dec(hex[3]);
910 blue = (hex2dec(hex[4]) << 4) | hex2dec(hex[5]);
912 *color = LCD_RGBPACK(red,green,blue);
914 return 0;
916 #endif /* HAVE_LCD_COLOR */
918 #ifdef HAVE_LCD_BITMAP
919 /* A simplified scanf - used (at time of writing) by wps parsing functions.
921 fmt - char array specifying the format of each list option. Valid values
922 are: d - int
923 s - string (sets pointer to string, without copying)
924 c - hex colour (RGB888 - e.g. ff00ff)
925 g - greyscale "colour" (0-3)
926 set_vals - if not NULL 1 is set in the bitplace if the item was read OK
927 0 if not read.
928 first item is LSB, (max 32 items! )
929 Stops parseing if an item is invalid unless the item == '-'
930 sep - list separator (e.g. ',' or '|')
931 str - string to parse, must be terminated by 0 or sep
932 ... - pointers to store the parsed values
934 return value - pointer to char after parsed data, 0 if there was an error.
938 /* '0'-'3' are ASCII 0x30 to 0x33 */
939 #define is0123(x) (((x) & 0xfc) == 0x30)
941 const char* parse_list(const char *fmt, uint32_t *set_vals,
942 const char sep, const char* str, ...)
944 va_list ap;
945 const char* p = str, *f = fmt;
946 const char** s;
947 int* d;
948 bool set, is_negative;
949 int i=0;
951 va_start(ap, str);
952 if (set_vals)
953 *set_vals = 0;
954 while (*fmt)
956 /* Check for separator, if we're not at the start */
957 if (f != fmt)
959 if (*p != sep)
960 goto err;
961 p++;
963 set = false;
964 switch (*fmt++)
966 case 's': /* string - return a pointer to it (not a copy) */
967 s = va_arg(ap, const char **);
969 *s = p;
970 while (*p && *p != sep)
971 p++;
972 set = (s[0][0]!='-') && (s[0][1]!=sep) ;
973 break;
975 case 'd': /* int */
976 is_negative = false;
977 d = va_arg(ap, int*);
978 if (*p == '-' && isdigit(*(p+1)))
980 is_negative = true;
981 p++;
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;
996 if (is_negative)
997 *d *= -1;
1000 break;
1002 #ifdef HAVE_LCD_COLOR
1003 case 'c': /* colour (rrggbb - e.g. f3c1a8) */
1004 d = va_arg(ap, int*);
1006 if (hex_to_rgb(p, d) < 0)
1008 if (!set_vals || *p != '-')
1009 goto err;
1010 while (*p && *p != sep)
1011 p++;
1013 else
1015 p += 6;
1016 set = true;
1019 break;
1020 #endif
1022 #if LCD_DEPTH == 2 || (defined(HAVE_REMOTE_LCD) && LCD_REMOTE_DEPTH == 2)
1023 case 'g': /* greyscale colour (0-3) */
1024 d = va_arg(ap, int*);
1026 if (is0123(*p))
1028 *d = *p++ - '0';
1029 set = true;
1031 else if (!set_vals || *p != '-')
1032 goto err;
1033 else
1035 while (*p && *p != sep)
1036 p++;
1039 break;
1040 #endif
1042 default: /* Unknown format type */
1043 goto err;
1044 break;
1046 if (set_vals && set)
1047 *set_vals |= BIT_N(i);
1048 i++;
1051 va_end(ap);
1052 return p;
1054 err:
1055 va_end(ap);
1056 return 0;
1059 /* only used in USB HID and set_time screen */
1060 #if defined(USB_ENABLE_HID) || (CONFIG_RTC != 0)
1061 int clamp_value_wrap(int value, int max, int min)
1063 if (value > max)
1064 return min;
1065 if (value < min)
1066 return max;
1067 return value;
1069 #endif
1070 #endif