Add Sansa Fuzev2 to the target tree. Bootloader builds, but is completely untested.
[kugel-rb.git] / apps / misc.c
blob8c60e3255926b78c67b0fc2f7ff71e64a5770ffe
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 || defined(HAVE_HOTSWAP_STORAGE_AS_MAIN)
84 #include "rolo.h"
85 #endif
86 #endif
88 /* units used with output_dyn_value */
89 const unsigned char * const byte_units[] =
91 ID2P(LANG_BYTE),
92 ID2P(LANG_KILOBYTE),
93 ID2P(LANG_MEGABYTE),
94 ID2P(LANG_GIGABYTE)
97 const unsigned char * const * const kbyte_units = &byte_units[1];
99 /* Format a large-range value for output, using the appropriate unit so that
100 * the displayed value is in the range 1 <= display < 1000 (1024 for "binary"
101 * units) if possible, and 3 significant digits are shown. If a buffer is
102 * given, the result is snprintf()'d into that buffer, otherwise the result is
103 * voiced.*/
104 char *output_dyn_value(char *buf, int buf_size, int value,
105 const unsigned char * const *units, bool bin_scale)
107 int scale = bin_scale ? 1024 : 1000;
108 int fraction = 0;
109 int unit_no = 0;
110 char tbuf[5];
112 while (value >= scale)
114 fraction = value % scale;
115 value /= scale;
116 unit_no++;
118 if (bin_scale)
119 fraction = fraction * 1000 / 1024;
121 if (value >= 100 || !unit_no)
122 tbuf[0] = '\0';
123 else if (value >= 10)
124 snprintf(tbuf, sizeof(tbuf), "%01d", fraction / 100);
125 else
126 snprintf(tbuf, sizeof(tbuf), "%02d", fraction / 10);
128 if (buf)
130 if (strlen(tbuf))
131 snprintf(buf, buf_size, "%d%s%s%s", value, str(LANG_POINT),
132 tbuf, P2STR(units[unit_no]));
133 else
134 snprintf(buf, buf_size, "%d%s", value, P2STR(units[unit_no]));
136 else
138 talk_fractional(tbuf, value, P2ID(units[unit_no]));
140 return buf;
143 /* Ask the user if they really want to erase the current dynamic playlist
144 * returns true if the playlist should be replaced */
145 bool warn_on_pl_erase(void)
147 if (global_settings.warnon_erase_dynplaylist &&
148 !global_settings.party_mode &&
149 playlist_modified(NULL))
151 static const char *lines[] =
152 {ID2P(LANG_WARN_ERASEDYNPLAYLIST_PROMPT)};
153 static const struct text_message message={lines, 1};
155 return (gui_syncyesno_run(&message, NULL, NULL) == YESNO_YES);
157 else
158 return true;
161 /* Read (up to) a line of text from fd into buffer and return number of bytes
162 * read (which may be larger than the number of bytes stored in buffer). If
163 * an error occurs, -1 is returned (and buffer contains whatever could be
164 * read). A line is terminated by a LF char. Neither LF nor CR chars are
165 * stored in buffer.
167 int read_line(int fd, char* buffer, int buffer_size)
169 int count = 0;
170 int num_read = 0;
172 errno = 0;
174 while (count < buffer_size)
176 unsigned char c;
178 if (1 != read(fd, &c, 1))
179 break;
181 num_read++;
183 if ( c == '\n' )
184 break;
186 if ( c == '\r' )
187 continue;
189 buffer[count++] = c;
192 buffer[MIN(count, buffer_size - 1)] = 0;
194 return errno ? -1 : num_read;
197 /* Performance optimized version of the previous function. */
198 int fast_readline(int fd, char *buf, int buf_size, void *parameters,
199 int (*callback)(int n, const char *buf, void *parameters))
201 char *p, *next;
202 int rc, pos = 0;
203 int count = 0;
205 while ( 1 )
207 next = NULL;
209 rc = read(fd, &buf[pos], buf_size - pos - 1);
210 if (rc >= 0)
211 buf[pos+rc] = '\0';
213 if ( (p = strchr(buf, '\r')) != NULL)
215 *p = '\0';
216 next = ++p;
218 else
219 p = buf;
221 if ( (p = strchr(p, '\n')) != NULL)
223 *p = '\0';
224 next = ++p;
227 rc = callback(count, buf, parameters);
228 if (rc < 0)
229 return rc;
231 count++;
232 if (next)
234 pos = buf_size - ((long)next - (long)buf) - 1;
235 memmove(buf, next, pos);
237 else
238 break ;
241 return 0;
244 /* parse a line from a configuration file. the line format is:
246 name: value
248 Any whitespace before setting name or value (after ':') is ignored.
249 A # as first non-whitespace character discards the whole line.
250 Function sets pointers to null-terminated setting name and value.
251 Returns false if no valid config entry was found.
254 bool settings_parseline(char* line, char** name, char** value)
256 char* ptr;
258 line = skip_whitespace(line);
260 if ( *line == '#' )
261 return false;
263 ptr = strchr(line, ':');
264 if ( !ptr )
265 return false;
267 *name = line;
268 *ptr = 0;
269 ptr++;
270 ptr = skip_whitespace(ptr);
271 *value = ptr;
272 return true;
275 static void system_flush(void)
277 scrobbler_shutdown();
278 playlist_shutdown();
279 tree_flush();
280 call_storage_idle_notifys(true); /*doesnt work on usb and shutdown from ata thread */
283 static void system_restore(void)
285 tree_restore();
286 scrobbler_init();
289 static bool clean_shutdown(void (*callback)(void *), void *parameter)
291 #ifdef SIMULATOR
292 (void)callback;
293 (void)parameter;
294 bookmark_autobookmark();
295 call_storage_idle_notifys(true);
296 exit(0);
297 #else
298 long msg_id = -1;
299 int i;
301 scrobbler_poweroff();
303 #if CONFIG_CHARGING && !defined(HAVE_POWEROFF_WHILE_CHARGING)
304 if(!charger_inserted())
305 #endif
307 bool batt_safe = battery_level_safe();
308 int audio_stat = audio_status();
310 FOR_NB_SCREENS(i)
312 screens[i].clear_display();
313 screens[i].update();
316 if (batt_safe)
318 #ifdef HAVE_TAGCACHE
319 if (!tagcache_prepare_shutdown())
321 cancel_shutdown();
322 splash(HZ, ID2P(LANG_TAGCACHE_BUSY));
323 return false;
325 #endif
326 if (battery_level() > 10)
327 splash(0, str(LANG_SHUTTINGDOWN));
328 else
330 msg_id = LANG_WARNING_BATTERY_LOW;
331 splashf(0, "%s %s", str(LANG_WARNING_BATTERY_LOW),
332 str(LANG_SHUTTINGDOWN));
335 else
337 msg_id = LANG_WARNING_BATTERY_EMPTY;
338 splashf(0, "%s %s", str(LANG_WARNING_BATTERY_EMPTY),
339 str(LANG_SHUTTINGDOWN));
342 if (global_settings.fade_on_stop
343 && (audio_stat & AUDIO_STATUS_PLAY))
345 fade(false, false);
348 if (batt_safe) /* do not save on critical battery */
350 #if defined(HAVE_RECORDING) && CONFIG_CODEC == SWCODEC
351 if (audio_stat & AUDIO_STATUS_RECORD)
353 rec_command(RECORDING_CMD_STOP);
354 /* wait for stop to complete */
355 while (audio_status() & AUDIO_STATUS_RECORD)
356 sleep(1);
358 #endif
359 bookmark_autobookmark();
361 /* audio_stop_recording == audio_stop for HWCODEC */
362 audio_stop();
364 if (callback != NULL)
365 callback(parameter);
367 #if CONFIG_CODEC != SWCODEC
368 /* wait for audio_stop or audio_stop_recording to complete */
369 while (audio_status())
370 sleep(1);
371 #endif
373 #if defined(HAVE_RECORDING) && CONFIG_CODEC == SWCODEC
374 audio_close_recording();
375 #endif
377 if(global_settings.talk_menu)
379 bool enqueue = false;
380 if(msg_id != -1)
382 talk_id(msg_id, enqueue);
383 enqueue = true;
385 talk_id(LANG_SHUTTINGDOWN, enqueue);
386 #if CONFIG_CODEC == SWCODEC
387 voice_wait();
388 #endif
391 system_flush();
392 #ifdef HAVE_EEPROM_SETTINGS
393 if (firmware_settings.initialized)
395 firmware_settings.disk_clean = true;
396 firmware_settings.bl_version = 0;
397 eeprom_settings_store();
399 #endif
401 #ifdef HAVE_DIRCACHE
402 else
403 dircache_disable();
404 #endif
406 shutdown_hw();
408 #endif
409 return false;
412 bool list_stop_handler(void)
414 bool ret = false;
416 /* Stop the music if it is playing */
417 if(audio_status())
419 if (!global_settings.party_mode)
421 if (global_settings.fade_on_stop)
422 fade(false, false);
423 bookmark_autobookmark();
424 audio_stop();
425 ret = true; /* bookmarking can make a refresh necessary */
428 #if CONFIG_CHARGING
429 #if (CONFIG_KEYPAD == RECORDER_PAD) && !defined(HAVE_SW_POWEROFF)
430 else
432 if (charger_inserted())
433 charging_splash();
434 else
435 shutdown_screen(); /* won't return if shutdown actually happens */
437 ret = true; /* screen is dirty, caller needs to refresh */
439 #endif
440 #ifndef HAVE_POWEROFF_WHILE_CHARGING
442 static long last_off = 0;
444 if (TIME_BEFORE(current_tick, last_off + HZ/2))
446 if (charger_inserted())
448 charging_splash();
449 ret = true; /* screen is dirty, caller needs to refresh */
452 last_off = current_tick;
454 #endif
455 #endif /* CONFIG_CHARGING */
456 return ret;
459 #if CONFIG_CHARGING
460 static bool waiting_to_resume_play = false;
461 static long play_resume_tick;
463 static void car_adapter_mode_processing(bool inserted)
465 if (global_settings.car_adapter_mode)
467 if(inserted)
470 * Just got plugged in, delay & resume if we were playing
472 if (audio_status() & AUDIO_STATUS_PAUSE)
474 /* delay resume a bit while the engine is cranking */
475 play_resume_tick = current_tick + HZ*5;
476 waiting_to_resume_play = true;
479 else
482 * Just got unplugged, pause if playing
484 if ((audio_status() & AUDIO_STATUS_PLAY) &&
485 !(audio_status() & AUDIO_STATUS_PAUSE))
487 if (global_settings.fade_on_stop)
488 fade(false, false);
489 else
490 audio_pause();
492 waiting_to_resume_play = false;
497 static void car_adapter_tick(void)
499 if (waiting_to_resume_play)
501 if (TIME_AFTER(current_tick, play_resume_tick))
503 if (audio_status() & AUDIO_STATUS_PAUSE)
505 queue_broadcast(SYS_CAR_ADAPTER_RESUME, 0);
507 waiting_to_resume_play = false;
512 void car_adapter_mode_init(void)
514 tick_add_task(car_adapter_tick);
516 #endif
518 #ifdef HAVE_HEADPHONE_DETECTION
519 static void unplug_change(bool inserted)
521 static bool headphone_caused_pause = false;
523 if (global_settings.unplug_mode)
525 int audio_stat = audio_status();
526 if (inserted)
528 if ((audio_stat & AUDIO_STATUS_PLAY) &&
529 headphone_caused_pause &&
530 global_settings.unplug_mode > 1 )
531 audio_resume();
532 backlight_on();
533 headphone_caused_pause = false;
534 } else {
535 if ((audio_stat & AUDIO_STATUS_PLAY) &&
536 !(audio_stat & AUDIO_STATUS_PAUSE))
538 headphone_caused_pause = true;
539 audio_pause();
541 if (global_settings.unplug_rw)
543 if (audio_current_track()->elapsed >
544 (unsigned long)(global_settings.unplug_rw*1000))
545 audio_ff_rewind(audio_current_track()->elapsed -
546 (global_settings.unplug_rw*1000));
547 else
548 audio_ff_rewind(0);
554 #endif
556 long default_event_handler_ex(long event, void (*callback)(void *), void *parameter)
558 switch(event)
560 case SYS_BATTERY_UPDATE:
561 if(global_settings.talk_battery_level)
563 talk_ids(true, VOICE_PAUSE, VOICE_PAUSE,
564 LANG_BATTERY_TIME,
565 TALK_ID(battery_level(), UNIT_PERCENT),
566 VOICE_PAUSE);
567 talk_force_enqueue_next();
569 break;
570 case SYS_USB_CONNECTED:
571 if (callback != NULL)
572 callback(parameter);
573 #if (CONFIG_STORAGE & STORAGE_MMC)
574 if (!mmc_touched() ||
575 (mmc_remove_request() == SYS_HOTSWAP_EXTRACTED))
576 #endif
578 system_flush();
579 #ifdef BOOTFILE
580 #if !defined(USB_NONE) && !defined(USB_HANDLED_BY_OF)
581 check_bootfile(false); /* gets initial size */
582 #endif
583 #endif
584 gui_usb_screen_run();
585 #ifdef BOOTFILE
586 #if !defined(USB_NONE) && !defined(USB_HANDLED_BY_OF)
587 check_bootfile(true);
588 #endif
589 #endif
590 system_restore();
592 return SYS_USB_CONNECTED;
593 case SYS_POWEROFF:
594 if (!clean_shutdown(callback, parameter))
595 return SYS_POWEROFF;
596 break;
597 #if CONFIG_CHARGING
598 case SYS_CHARGER_CONNECTED:
599 car_adapter_mode_processing(true);
600 return SYS_CHARGER_CONNECTED;
602 case SYS_CHARGER_DISCONNECTED:
603 car_adapter_mode_processing(false);
604 return SYS_CHARGER_DISCONNECTED;
606 case SYS_CAR_ADAPTER_RESUME:
607 audio_resume();
608 return SYS_CAR_ADAPTER_RESUME;
609 #endif
610 #ifdef HAVE_HOTSWAP_STORAGE_AS_MAIN
611 case SYS_FS_CHANGED:
613 /* simple sanity: assume rockbox is on the first hotswappable
614 * driver, abort out if that one isn't inserted */
615 int i;
616 for (i = 0; i < NUM_DRIVES; i++)
618 if (storage_removable(i) && !storage_present(i))
619 return SYS_FS_CHANGED;
621 system_flush();
622 check_bootfile(true); /* state gotten in main.c:init() */
623 system_restore();
625 return SYS_FS_CHANGED;
626 #endif
627 #ifdef HAVE_HEADPHONE_DETECTION
628 case SYS_PHONE_PLUGGED:
629 unplug_change(true);
630 return SYS_PHONE_PLUGGED;
632 case SYS_PHONE_UNPLUGGED:
633 unplug_change(false);
634 return SYS_PHONE_UNPLUGGED;
635 #endif
636 #ifdef IPOD_ACCESSORY_PROTOCOL
637 case SYS_IAP_PERIODIC:
638 iap_periodic();
639 return SYS_IAP_PERIODIC;
640 case SYS_IAP_HANDLEPKT:
641 iap_handlepkt();
642 return SYS_IAP_HANDLEPKT;
643 #endif
645 return 0;
648 long default_event_handler(long event)
650 return default_event_handler_ex(event, NULL, NULL);
653 int show_logo( void )
655 #ifdef HAVE_LCD_BITMAP
656 char version[32];
657 int font_h, font_w;
659 snprintf(version, sizeof(version), "Ver. %s", appsversion);
661 lcd_clear_display();
662 #if defined(SANSA_CLIP) || defined(SANSA_CLIPV2) || defined(SANSA_CLIPPLUS)
663 /* display the logo in the blue area of the screen */
664 lcd_setfont(FONT_SYSFIXED);
665 lcd_getstringsize((unsigned char *)"A", &font_w, &font_h);
666 lcd_putsxy((LCD_WIDTH/2) - ((strlen(version)*font_w)/2),
667 0, (unsigned char *)version);
668 lcd_bitmap(rockboxlogo, 0, 16, BMPWIDTH_rockboxlogo, BMPHEIGHT_rockboxlogo);
669 #else
670 lcd_bitmap(rockboxlogo, 0, 10, BMPWIDTH_rockboxlogo, BMPHEIGHT_rockboxlogo);
671 lcd_setfont(FONT_SYSFIXED);
672 lcd_getstringsize((unsigned char *)"A", &font_w, &font_h);
673 lcd_putsxy((LCD_WIDTH/2) - ((strlen(version)*font_w)/2),
674 LCD_HEIGHT-font_h, (unsigned char *)version);
675 #endif
676 lcd_setfont(FONT_UI);
678 #else
679 char *rockbox = " ROCKbox!";
681 lcd_clear_display();
682 lcd_double_height(true);
683 lcd_puts(0, 0, rockbox);
684 lcd_puts_scroll(0, 1, appsversion);
685 #endif
686 lcd_update();
688 #ifdef HAVE_REMOTE_LCD
689 lcd_remote_clear_display();
690 lcd_remote_bitmap(remote_rockboxlogo, 0, 10, BMPWIDTH_remote_rockboxlogo,
691 BMPHEIGHT_remote_rockboxlogo);
692 lcd_remote_setfont(FONT_SYSFIXED);
693 lcd_remote_getstringsize((unsigned char *)"A", &font_w, &font_h);
694 lcd_remote_putsxy((LCD_REMOTE_WIDTH/2) - ((strlen(version)*font_w)/2),
695 LCD_REMOTE_HEIGHT-font_h, (unsigned char *)version);
696 lcd_remote_setfont(FONT_UI);
697 lcd_remote_update();
698 #endif
700 return 0;
703 #ifdef BOOTFILE
704 #if !defined(USB_NONE) && !defined(USB_HANDLED_BY_OF) || defined(HAVE_HOTSWAP_STORAGE_AS_MAIN)
706 memorize/compare details about the BOOTFILE
707 we don't use dircache because it may not be up to date after
708 USB disconnect (scanning in the background)
710 void check_bootfile(bool do_rolo)
712 static unsigned short wrtdate = 0;
713 static unsigned short wrttime = 0;
714 DIR* dir = NULL;
715 struct dirent* entry = NULL;
717 /* 1. open BOOTDIR and find the BOOTFILE dir entry */
718 dir = opendir(BOOTDIR);
720 if(!dir) return; /* do we want an error splash? */
722 /* loop all files in BOOTDIR */
723 while(0 != (entry = readdir(dir)))
725 if(!strcasecmp(entry->d_name, BOOTFILE))
727 /* found the bootfile */
728 if(wrtdate && do_rolo)
730 if((entry->wrtdate != wrtdate) ||
731 (entry->wrttime != wrttime))
733 static const char *lines[] = { ID2P(LANG_BOOT_CHANGED),
734 ID2P(LANG_REBOOT_NOW) };
735 static const struct text_message message={ lines, 2 };
736 button_clear_queue(); /* Empty the keyboard buffer */
737 if(gui_syncyesno_run(&message, NULL, NULL) == YESNO_YES)
738 rolo_load(BOOTDIR "/" BOOTFILE);
741 wrtdate = entry->wrtdate;
742 wrttime = entry->wrttime;
745 closedir(dir);
747 #endif
748 #endif
750 /* check range, set volume and save settings */
751 void setvol(void)
753 const int min_vol = sound_min(SOUND_VOLUME);
754 const int max_vol = sound_max(SOUND_VOLUME);
755 if (global_settings.volume < min_vol)
756 global_settings.volume = min_vol;
757 if (global_settings.volume > max_vol)
758 global_settings.volume = max_vol;
759 sound_set_volume(global_settings.volume);
760 global_status.last_volume_change = current_tick;
761 settings_save();
764 char* strrsplt(char* str, int c)
766 char* s = strrchr(str, c);
768 if (s != NULL)
770 *s++ = '\0';
772 else
774 s = str;
777 return s;
780 /* Test file existence, using dircache of possible */
781 bool file_exists(const char *file)
783 int fd;
785 if (!file || strlen(file) <= 0)
786 return false;
788 #ifdef HAVE_DIRCACHE
789 if (dircache_is_enabled())
790 return (dircache_get_entry_ptr(file) != NULL);
791 #endif
793 fd = open(file, O_RDONLY);
794 if (fd < 0)
795 return false;
796 close(fd);
797 return true;
800 bool dir_exists(const char *path)
802 DIR* d = opendir(path);
803 if (!d)
804 return false;
805 closedir(d);
806 return true;
810 * removes the extension of filename (if it doesn't start with a .)
811 * puts the result in buffer
813 char *strip_extension(char* buffer, int buffer_size, const char *filename)
815 char *dot = strrchr(filename, '.');
816 int len;
818 if (buffer_size <= 0)
820 return NULL;
823 buffer_size--; /* Make room for end nil */
825 if (dot != 0 && filename[0] != '.')
827 len = dot - filename;
828 len = MIN(len, buffer_size);
830 else
832 len = buffer_size;
835 strlcpy(buffer, filename, len + 1);
837 return buffer;
839 #endif /* !defined(__PCTOOL__) */
841 char* skip_whitespace(char* const str)
843 char *s = str;
845 while (isspace(*s))
846 s++;
848 return s;
851 /* Format time into buf.
853 * buf - buffer to format to.
854 * buf_size - size of buffer.
855 * t - time to format, in milliseconds.
857 void format_time(char* buf, int buf_size, long t)
859 if ( t < 3600000 )
861 snprintf(buf, buf_size, "%d:%02d",
862 (int) (t / 60000), (int) (t % 60000 / 1000));
864 else
866 snprintf(buf, buf_size, "%d:%02d:%02d",
867 (int) (t / 3600000), (int) (t % 3600000 / 60000),
868 (int) (t % 60000 / 1000));
873 /** Open a UTF-8 file and set file descriptor to first byte after BOM.
874 * If no BOM is present this behaves like open().
875 * If the file is opened for writing and O_TRUNC is set, write a BOM to
876 * the opened file and leave the file pointer set after the BOM.
878 #define BOM "\xef\xbb\xbf"
879 #define BOM_SIZE 3
881 int open_utf8(const char* pathname, int flags)
883 int fd;
884 unsigned char bom[BOM_SIZE];
886 fd = open(pathname, flags);
887 if(fd < 0)
888 return fd;
890 if(flags & (O_TRUNC | O_WRONLY))
892 write(fd, BOM, BOM_SIZE);
894 else
896 read(fd, bom, BOM_SIZE);
897 /* check for BOM */
898 if(memcmp(bom, BOM, BOM_SIZE))
899 lseek(fd, 0, SEEK_SET);
901 return fd;
905 #ifdef HAVE_LCD_COLOR
907 * Helper function to convert a string of 6 hex digits to a native colour
910 static int hex2dec(int c)
912 return (((c) >= '0' && ((c) <= '9')) ? (c) - '0' :
913 (toupper(c)) - 'A' + 10);
916 int hex_to_rgb(const char* hex, int* color)
918 int red, green, blue;
919 int i = 0;
921 while ((i < 6) && (isxdigit(hex[i])))
922 i++;
924 if (i < 6)
925 return -1;
927 red = (hex2dec(hex[0]) << 4) | hex2dec(hex[1]);
928 green = (hex2dec(hex[2]) << 4) | hex2dec(hex[3]);
929 blue = (hex2dec(hex[4]) << 4) | hex2dec(hex[5]);
931 *color = LCD_RGBPACK(red,green,blue);
933 return 0;
935 #endif /* HAVE_LCD_COLOR */
937 #ifdef HAVE_LCD_BITMAP
938 /* A simplified scanf - used (at time of writing) by wps parsing functions.
940 fmt - char array specifying the format of each list option. Valid values
941 are: d - int
942 s - string (sets pointer to string, without copying)
943 c - hex colour (RGB888 - e.g. ff00ff)
944 g - greyscale "colour" (0-3)
945 set_vals - if not NULL 1 is set in the bitplace if the item was read OK
946 0 if not read.
947 first item is LSB, (max 32 items! )
948 Stops parseing if an item is invalid unless the item == '-'
949 sep - list separator (e.g. ',' or '|')
950 str - string to parse, must be terminated by 0 or sep
951 ... - pointers to store the parsed values
953 return value - pointer to char after parsed data, 0 if there was an error.
957 /* '0'-'3' are ASCII 0x30 to 0x33 */
958 #define is0123(x) (((x) & 0xfc) == 0x30)
960 const char* parse_list(const char *fmt, uint32_t *set_vals,
961 const char sep, const char* str, ...)
963 va_list ap;
964 const char* p = str, *f = fmt;
965 const char** s;
966 int* d;
967 bool set, is_negative;
968 int i=0;
970 va_start(ap, str);
971 if (set_vals)
972 *set_vals = 0;
973 while (*fmt)
975 /* Check for separator, if we're not at the start */
976 if (f != fmt)
978 if (*p != sep)
979 goto err;
980 p++;
982 set = false;
983 switch (*fmt++)
985 case 's': /* string - return a pointer to it (not a copy) */
986 s = va_arg(ap, const char **);
988 *s = p;
989 while (*p && *p != sep)
990 p++;
991 set = (s[0][0]!='-') && (s[0][1]!=sep) ;
992 break;
994 case 'd': /* int */
995 is_negative = false;
996 d = va_arg(ap, int*);
997 if (*p == '-' && isdigit(*(p+1)))
999 is_negative = true;
1000 p++;
1002 if (!isdigit(*p))
1004 if (!set_vals || *p != '-')
1005 goto err;
1006 while (*p && *p != sep)
1007 p++;
1009 else
1011 *d = *p++ - '0';
1012 while (isdigit(*p))
1013 *d = (*d * 10) + (*p++ - '0');
1014 set = true;
1015 if (is_negative)
1016 *d *= -1;
1019 break;
1021 #ifdef HAVE_LCD_COLOR
1022 case 'c': /* colour (rrggbb - e.g. f3c1a8) */
1023 d = va_arg(ap, int*);
1025 if (hex_to_rgb(p, d) < 0)
1027 if (!set_vals || *p != '-')
1028 goto err;
1029 while (*p && *p != sep)
1030 p++;
1032 else
1034 p += 6;
1035 set = true;
1038 break;
1039 #endif
1041 #if LCD_DEPTH == 2 || (defined(HAVE_REMOTE_LCD) && LCD_REMOTE_DEPTH == 2)
1042 case 'g': /* greyscale colour (0-3) */
1043 d = va_arg(ap, int*);
1045 if (is0123(*p))
1047 *d = *p++ - '0';
1048 set = true;
1050 else if (!set_vals || *p != '-')
1051 goto err;
1052 else
1054 while (*p && *p != sep)
1055 p++;
1058 break;
1059 #endif
1061 default: /* Unknown format type */
1062 goto err;
1063 break;
1065 if (set_vals && set)
1066 *set_vals |= BIT_N(i);
1067 i++;
1070 va_end(ap);
1071 return p;
1073 err:
1074 va_end(ap);
1075 return NULL;
1078 /* only used in USB HID and set_time screen */
1079 #if defined(USB_ENABLE_HID) || (CONFIG_RTC != 0)
1080 int clamp_value_wrap(int value, int max, int min)
1082 if (value > max)
1083 return min;
1084 if (value < min)
1085 return max;
1086 return value;
1088 #endif
1089 #endif