Update the discussion of themeing in the manual, and put a note in the wps tags appen...
[kugel-rb.git] / apps / misc.c
blob3dfc2892ca61265e0a525ee11914f2571947882a
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 <stdio.h>
24 #include <stdarg.h>
25 #include <errno.h>
26 #include "string-extra.h"
27 #include "config.h"
28 #include "misc.h"
29 #include "lcd.h"
30 #include "file.h"
31 #ifndef __PCTOOL__
32 #include "lang.h"
33 #include "dir.h"
34 #include "lcd-remote.h"
35 #include "system.h"
36 #include "timefuncs.h"
37 #include "screens.h"
38 #include "usb_screen.h"
39 #include "talk.h"
40 #include "audio.h"
41 #include "mp3_playback.h"
42 #include "settings.h"
43 #include "storage.h"
44 #include "ata_idle_notify.h"
45 #include "kernel.h"
46 #include "power.h"
47 #include "powermgmt.h"
48 #include "backlight.h"
49 #include "version.h"
50 #include "font.h"
51 #include "splash.h"
52 #include "tagcache.h"
53 #include "scrobbler.h"
54 #include "sound.h"
55 #include "playlist.h"
56 #include "yesno.h"
57 #include "viewport.h"
59 #ifdef IPOD_ACCESSORY_PROTOCOL
60 #include "iap.h"
61 #endif
63 #if (CONFIG_STORAGE & STORAGE_MMC)
64 #include "ata_mmc.h"
65 #endif
66 #include "tree.h"
67 #include "eeprom_settings.h"
68 #if defined(HAVE_RECORDING) && !defined(__PCTOOL__)
69 #include "recording.h"
70 #endif
71 #if defined(HAVE_LCD_BITMAP) && !defined(__PCTOOL__)
72 #include "bmp.h"
73 #include "icons.h"
74 #endif /* End HAVE_LCD_BITMAP */
75 #include "bookmark.h"
76 #include "wps.h"
77 #include "playback.h"
79 #ifdef BOOTFILE
80 #if !defined(USB_NONE) && !defined(USB_HANDLED_BY_OF) \
81 || defined(HAVE_HOTSWAP_STORAGE_AS_MAIN)
82 #include "rolo.h"
83 #endif
84 #endif
86 /* units used with output_dyn_value */
87 const unsigned char * const byte_units[] =
89 ID2P(LANG_BYTE),
90 ID2P(LANG_KILOBYTE),
91 ID2P(LANG_MEGABYTE),
92 ID2P(LANG_GIGABYTE)
95 const unsigned char * const * const kbyte_units = &byte_units[1];
97 /* Format a large-range value for output, using the appropriate unit so that
98 * the displayed value is in the range 1 <= display < 1000 (1024 for "binary"
99 * units) if possible, and 3 significant digits are shown. If a buffer is
100 * given, the result is snprintf()'d into that buffer, otherwise the result is
101 * voiced.*/
102 char *output_dyn_value(char *buf, int buf_size, int value,
103 const unsigned char * const *units, bool bin_scale)
105 int scale = bin_scale ? 1024 : 1000;
106 int fraction = 0;
107 int unit_no = 0;
108 char tbuf[5];
110 while (value >= scale)
112 fraction = value % scale;
113 value /= scale;
114 unit_no++;
116 if (bin_scale)
117 fraction = fraction * 1000 / 1024;
119 if (value >= 100 || !unit_no)
120 tbuf[0] = '\0';
121 else if (value >= 10)
122 snprintf(tbuf, sizeof(tbuf), "%01d", fraction / 100);
123 else
124 snprintf(tbuf, sizeof(tbuf), "%02d", fraction / 10);
126 if (buf)
128 if (strlen(tbuf))
129 snprintf(buf, buf_size, "%d%s%s%s", value, str(LANG_POINT),
130 tbuf, P2STR(units[unit_no]));
131 else
132 snprintf(buf, buf_size, "%d%s", value, P2STR(units[unit_no]));
134 else
136 talk_fractional(tbuf, value, P2ID(units[unit_no]));
138 return buf;
141 /* Ask the user if they really want to erase the current dynamic playlist
142 * returns true if the playlist should be replaced */
143 bool warn_on_pl_erase(void)
145 if (global_settings.warnon_erase_dynplaylist &&
146 !global_settings.party_mode &&
147 playlist_modified(NULL))
149 static const char *lines[] =
150 {ID2P(LANG_WARN_ERASEDYNPLAYLIST_PROMPT)};
151 static const struct text_message message={lines, 1};
153 return (gui_syncyesno_run(&message, NULL, NULL) == YESNO_YES);
155 else
156 return true;
160 /* Performance optimized version of the read_line() (see below) function. */
161 int fast_readline(int fd, char *buf, int buf_size, void *parameters,
162 int (*callback)(int n, const char *buf, void *parameters))
164 char *p, *next;
165 int rc, pos = 0;
166 int count = 0;
168 while ( 1 )
170 next = NULL;
172 rc = read(fd, &buf[pos], buf_size - pos - 1);
173 if (rc >= 0)
174 buf[pos+rc] = '\0';
176 if ( (p = strchr(buf, '\r')) != NULL)
178 *p = '\0';
179 next = ++p;
181 else
182 p = buf;
184 if ( (p = strchr(p, '\n')) != NULL)
186 *p = '\0';
187 next = ++p;
190 rc = callback(count, buf, parameters);
191 if (rc < 0)
192 return rc;
194 count++;
195 if (next)
197 pos = buf_size - ((long)next - (long)buf) - 1;
198 memmove(buf, next, pos);
200 else
201 break ;
204 return 0;
207 /* parse a line from a configuration file. the line format is:
209 name: value
211 Any whitespace before setting name or value (after ':') is ignored.
212 A # as first non-whitespace character discards the whole line.
213 Function sets pointers to null-terminated setting name and value.
214 Returns false if no valid config entry was found.
217 bool settings_parseline(char* line, char** name, char** value)
219 char* ptr;
221 line = skip_whitespace(line);
223 if ( *line == '#' )
224 return false;
226 ptr = strchr(line, ':');
227 if ( !ptr )
228 return false;
230 *name = line;
231 *ptr = 0;
232 ptr++;
233 ptr = skip_whitespace(ptr);
234 *value = ptr;
235 return true;
238 static void system_flush(void)
240 scrobbler_shutdown();
241 playlist_shutdown();
242 tree_flush();
243 call_storage_idle_notifys(true); /*doesnt work on usb and shutdown from ata thread */
246 static void system_restore(void)
248 tree_restore();
249 scrobbler_init();
252 static bool clean_shutdown(void (*callback)(void *), void *parameter)
254 #ifdef SIMULATOR
255 (void)callback;
256 (void)parameter;
257 bookmark_autobookmark(false);
258 call_storage_idle_notifys(true);
259 exit(0);
260 #else
261 long msg_id = -1;
262 int i;
264 scrobbler_poweroff();
266 #if CONFIG_CHARGING && !defined(HAVE_POWEROFF_WHILE_CHARGING)
267 if(!charger_inserted())
268 #endif
270 bool batt_safe = battery_level_safe();
271 int audio_stat = audio_status();
273 FOR_NB_SCREENS(i)
275 screens[i].clear_display();
276 screens[i].update();
279 if (batt_safe)
281 #ifdef HAVE_TAGCACHE
282 if (!tagcache_prepare_shutdown())
284 cancel_shutdown();
285 splash(HZ, ID2P(LANG_TAGCACHE_BUSY));
286 return false;
288 #endif
289 if (battery_level() > 10)
290 splash(0, str(LANG_SHUTTINGDOWN));
291 else
293 msg_id = LANG_WARNING_BATTERY_LOW;
294 splashf(0, "%s %s", str(LANG_WARNING_BATTERY_LOW),
295 str(LANG_SHUTTINGDOWN));
298 else
300 msg_id = LANG_WARNING_BATTERY_EMPTY;
301 splashf(0, "%s %s", str(LANG_WARNING_BATTERY_EMPTY),
302 str(LANG_SHUTTINGDOWN));
305 if (global_settings.fade_on_stop
306 && (audio_stat & AUDIO_STATUS_PLAY))
308 fade(false, false);
311 if (batt_safe) /* do not save on critical battery */
313 #if defined(HAVE_RECORDING) && CONFIG_CODEC == SWCODEC
314 if (audio_stat & AUDIO_STATUS_RECORD)
316 rec_command(RECORDING_CMD_STOP);
317 /* wait for stop to complete */
318 while (audio_status() & AUDIO_STATUS_RECORD)
319 sleep(1);
321 #endif
322 bookmark_autobookmark(false);
324 /* audio_stop_recording == audio_stop for HWCODEC */
325 audio_stop();
327 if (callback != NULL)
328 callback(parameter);
330 #if CONFIG_CODEC != SWCODEC
331 /* wait for audio_stop or audio_stop_recording to complete */
332 while (audio_status())
333 sleep(1);
334 #endif
336 #if defined(HAVE_RECORDING) && CONFIG_CODEC == SWCODEC
337 audio_close_recording();
338 #endif
340 if(global_settings.talk_menu)
342 bool enqueue = false;
343 if(msg_id != -1)
345 talk_id(msg_id, enqueue);
346 enqueue = true;
348 talk_id(LANG_SHUTTINGDOWN, enqueue);
349 #if CONFIG_CODEC == SWCODEC
350 voice_wait();
351 #endif
354 system_flush();
355 #ifdef HAVE_EEPROM_SETTINGS
356 if (firmware_settings.initialized)
358 firmware_settings.disk_clean = true;
359 firmware_settings.bl_version = 0;
360 eeprom_settings_store();
362 #endif
364 #ifdef HAVE_DIRCACHE
365 else
366 dircache_disable();
367 #endif
369 shutdown_hw();
371 #endif
372 return false;
375 bool list_stop_handler(void)
377 bool ret = false;
379 /* Stop the music if it is playing */
380 if(audio_status())
382 if (!global_settings.party_mode)
384 if (global_settings.fade_on_stop)
385 fade(false, false);
386 bookmark_autobookmark(true);
387 audio_stop();
388 ret = true; /* bookmarking can make a refresh necessary */
391 #if CONFIG_CHARGING
392 #if (CONFIG_KEYPAD == RECORDER_PAD) && !defined(HAVE_SW_POWEROFF)
393 else
395 if (charger_inserted())
396 charging_splash();
397 else
398 shutdown_screen(); /* won't return if shutdown actually happens */
400 ret = true; /* screen is dirty, caller needs to refresh */
402 #endif
403 #ifndef HAVE_POWEROFF_WHILE_CHARGING
405 static long last_off = 0;
407 if (TIME_BEFORE(current_tick, last_off + HZ/2))
409 if (charger_inserted())
411 charging_splash();
412 ret = true; /* screen is dirty, caller needs to refresh */
415 last_off = current_tick;
417 #endif
418 #endif /* CONFIG_CHARGING */
419 return ret;
422 #if CONFIG_CHARGING
423 static bool waiting_to_resume_play = false;
424 static long play_resume_tick;
426 static void car_adapter_mode_processing(bool inserted)
428 if (global_settings.car_adapter_mode)
430 if(inserted)
433 * Just got plugged in, delay & resume if we were playing
435 if (audio_status() & AUDIO_STATUS_PAUSE)
437 /* delay resume a bit while the engine is cranking */
438 play_resume_tick = current_tick + HZ*5;
439 waiting_to_resume_play = true;
442 else
445 * Just got unplugged, pause if playing
447 if ((audio_status() & AUDIO_STATUS_PLAY) &&
448 !(audio_status() & AUDIO_STATUS_PAUSE))
450 if (global_settings.fade_on_stop)
451 fade(false, false);
452 else
453 audio_pause();
455 waiting_to_resume_play = false;
460 static void car_adapter_tick(void)
462 if (waiting_to_resume_play)
464 if (TIME_AFTER(current_tick, play_resume_tick))
466 if (audio_status() & AUDIO_STATUS_PAUSE)
468 queue_broadcast(SYS_CAR_ADAPTER_RESUME, 0);
470 waiting_to_resume_play = false;
475 void car_adapter_mode_init(void)
477 tick_add_task(car_adapter_tick);
479 #endif
481 #ifdef HAVE_HEADPHONE_DETECTION
482 static void unplug_change(bool inserted)
484 static bool headphone_caused_pause = false;
486 if (global_settings.unplug_mode)
488 int audio_stat = audio_status();
489 if (inserted)
491 if ((audio_stat & AUDIO_STATUS_PLAY) &&
492 headphone_caused_pause &&
493 global_settings.unplug_mode > 1 )
494 audio_resume();
495 backlight_on();
496 headphone_caused_pause = false;
497 } else {
498 if ((audio_stat & AUDIO_STATUS_PLAY) &&
499 !(audio_stat & AUDIO_STATUS_PAUSE))
501 headphone_caused_pause = true;
502 audio_pause();
504 if (global_settings.unplug_rw)
506 if (audio_current_track()->elapsed >
507 (unsigned long)(global_settings.unplug_rw*1000))
508 audio_ff_rewind(audio_current_track()->elapsed -
509 (global_settings.unplug_rw*1000));
510 else
511 audio_ff_rewind(0);
517 #endif
519 long default_event_handler_ex(long event, void (*callback)(void *), void *parameter)
521 switch(event)
523 case SYS_BATTERY_UPDATE:
524 if(global_settings.talk_battery_level)
526 talk_ids(true, VOICE_PAUSE, VOICE_PAUSE,
527 LANG_BATTERY_TIME,
528 TALK_ID(battery_level(), UNIT_PERCENT),
529 VOICE_PAUSE);
530 talk_force_enqueue_next();
532 break;
533 case SYS_USB_CONNECTED:
534 if (callback != NULL)
535 callback(parameter);
536 #if (CONFIG_STORAGE & STORAGE_MMC)
537 if (!mmc_touched() ||
538 (mmc_remove_request() == SYS_HOTSWAP_EXTRACTED))
539 #endif
541 system_flush();
542 #ifdef BOOTFILE
543 #if !defined(USB_NONE) && !defined(USB_HANDLED_BY_OF)
544 check_bootfile(false); /* gets initial size */
545 #endif
546 #endif
547 gui_usb_screen_run();
548 #ifdef BOOTFILE
549 #if !defined(USB_NONE) && !defined(USB_HANDLED_BY_OF)
550 check_bootfile(true);
551 #endif
552 #endif
553 system_restore();
555 return SYS_USB_CONNECTED;
557 case SYS_POWEROFF:
558 if (!clean_shutdown(callback, parameter))
559 return SYS_POWEROFF;
560 break;
561 #if CONFIG_CHARGING
562 case SYS_CHARGER_CONNECTED:
563 car_adapter_mode_processing(true);
564 return SYS_CHARGER_CONNECTED;
566 case SYS_CHARGER_DISCONNECTED:
567 car_adapter_mode_processing(false);
568 /*reset rockbox battery runtime*/
569 global_status.runtime = 0;
570 return SYS_CHARGER_DISCONNECTED;
572 case SYS_CAR_ADAPTER_RESUME:
573 audio_resume();
574 return SYS_CAR_ADAPTER_RESUME;
575 #endif
576 #ifdef HAVE_HOTSWAP_STORAGE_AS_MAIN
577 case SYS_FS_CHANGED:
579 /* simple sanity: assume rockbox is on the first hotswappable
580 * driver, abort out if that one isn't inserted */
581 int i;
582 for (i = 0; i < NUM_DRIVES; i++)
584 if (storage_removable(i) && !storage_present(i))
585 return SYS_FS_CHANGED;
587 system_flush();
588 check_bootfile(true); /* state gotten in main.c:init() */
589 system_restore();
591 return SYS_FS_CHANGED;
592 #endif
593 #ifdef HAVE_HEADPHONE_DETECTION
594 case SYS_PHONE_PLUGGED:
595 unplug_change(true);
596 return SYS_PHONE_PLUGGED;
598 case SYS_PHONE_UNPLUGGED:
599 unplug_change(false);
600 return SYS_PHONE_UNPLUGGED;
601 #endif
602 #ifdef IPOD_ACCESSORY_PROTOCOL
603 case SYS_IAP_PERIODIC:
604 iap_periodic();
605 return SYS_IAP_PERIODIC;
606 case SYS_IAP_HANDLEPKT:
607 iap_handlepkt();
608 return SYS_IAP_HANDLEPKT;
609 #endif
611 return 0;
614 long default_event_handler(long event)
616 return default_event_handler_ex(event, NULL, NULL);
619 int show_logo( void )
621 #ifdef HAVE_LCD_BITMAP
622 char version[32];
623 int font_h, font_w;
625 snprintf(version, sizeof(version), "Ver. %s", appsversion);
627 lcd_clear_display();
628 #if defined(SANSA_CLIP) || defined(SANSA_CLIPV2) || defined(SANSA_CLIPPLUS)
629 /* display the logo in the blue area of the screen */
630 lcd_setfont(FONT_SYSFIXED);
631 lcd_getstringsize((unsigned char *)"A", &font_w, &font_h);
632 lcd_putsxy((LCD_WIDTH/2) - ((strlen(version)*font_w)/2),
633 0, (unsigned char *)version);
634 lcd_bitmap(rockboxlogo, 0, 16, BMPWIDTH_rockboxlogo, BMPHEIGHT_rockboxlogo);
635 #else
636 lcd_bitmap(rockboxlogo, 0, 10, BMPWIDTH_rockboxlogo, BMPHEIGHT_rockboxlogo);
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 LCD_HEIGHT-font_h, (unsigned char *)version);
641 #endif
642 lcd_setfont(FONT_UI);
644 #else
645 char *rockbox = " ROCKbox!";
647 lcd_clear_display();
648 lcd_double_height(true);
649 lcd_puts(0, 0, rockbox);
650 lcd_puts_scroll(0, 1, appsversion);
651 #endif
652 lcd_update();
654 #ifdef HAVE_REMOTE_LCD
655 lcd_remote_clear_display();
656 lcd_remote_bitmap(remote_rockboxlogo, 0, 10, BMPWIDTH_remote_rockboxlogo,
657 BMPHEIGHT_remote_rockboxlogo);
658 lcd_remote_setfont(FONT_SYSFIXED);
659 lcd_remote_getstringsize((unsigned char *)"A", &font_w, &font_h);
660 lcd_remote_putsxy((LCD_REMOTE_WIDTH/2) - ((strlen(version)*font_w)/2),
661 LCD_REMOTE_HEIGHT-font_h, (unsigned char *)version);
662 lcd_remote_setfont(FONT_UI);
663 lcd_remote_update();
664 #endif
666 return 0;
669 #ifdef BOOTFILE
670 #if !defined(USB_NONE) && !defined(USB_HANDLED_BY_OF) || defined(HAVE_HOTSWAP_STORAGE_AS_MAIN)
672 memorize/compare details about the BOOTFILE
673 we don't use dircache because it may not be up to date after
674 USB disconnect (scanning in the background)
676 void check_bootfile(bool do_rolo)
678 static unsigned short wrtdate = 0;
679 static unsigned short wrttime = 0;
680 DIR* dir = NULL;
681 struct dirent* entry = NULL;
683 /* 1. open BOOTDIR and find the BOOTFILE dir entry */
684 dir = opendir(BOOTDIR);
686 if(!dir) return; /* do we want an error splash? */
688 /* loop all files in BOOTDIR */
689 while(0 != (entry = readdir(dir)))
691 if(!strcasecmp(entry->d_name, BOOTFILE))
693 /* found the bootfile */
694 if(wrtdate && do_rolo)
696 if((entry->wrtdate != wrtdate) ||
697 (entry->wrttime != wrttime))
699 static const char *lines[] = { ID2P(LANG_BOOT_CHANGED),
700 ID2P(LANG_REBOOT_NOW) };
701 static const struct text_message message={ lines, 2 };
702 button_clear_queue(); /* Empty the keyboard buffer */
703 if(gui_syncyesno_run(&message, NULL, NULL) == YESNO_YES)
704 rolo_load(BOOTDIR "/" BOOTFILE);
707 wrtdate = entry->wrtdate;
708 wrttime = entry->wrttime;
711 closedir(dir);
713 #endif
714 #endif
716 /* check range, set volume and save settings */
717 void setvol(void)
719 const int min_vol = sound_min(SOUND_VOLUME);
720 const int max_vol = sound_max(SOUND_VOLUME);
721 if (global_settings.volume < min_vol)
722 global_settings.volume = min_vol;
723 if (global_settings.volume > max_vol)
724 global_settings.volume = max_vol;
725 sound_set_volume(global_settings.volume);
726 global_status.last_volume_change = current_tick;
727 settings_save();
730 char* strrsplt(char* str, int c)
732 char* s = strrchr(str, c);
734 if (s != NULL)
736 *s++ = '\0';
738 else
740 s = str;
743 return s;
746 /* Test file existence, using dircache of possible */
747 bool file_exists(const char *file)
749 int fd;
751 if (!file || strlen(file) <= 0)
752 return false;
754 #ifdef HAVE_DIRCACHE
755 if (dircache_is_enabled())
756 return (dircache_get_entry_ptr(file) != NULL);
757 #endif
759 fd = open(file, O_RDONLY);
760 if (fd < 0)
761 return false;
762 close(fd);
763 return true;
766 bool dir_exists(const char *path)
768 DIR* d = opendir(path);
769 if (!d)
770 return false;
771 closedir(d);
772 return true;
776 * removes the extension of filename (if it doesn't start with a .)
777 * puts the result in buffer
779 char *strip_extension(char* buffer, int buffer_size, const char *filename)
781 char *dot = strrchr(filename, '.');
782 int len;
784 if (buffer_size <= 0)
786 return NULL;
789 buffer_size--; /* Make room for end nil */
791 if (dot != 0 && filename[0] != '.')
793 len = dot - filename;
794 len = MIN(len, buffer_size);
796 else
798 len = buffer_size;
801 strlcpy(buffer, filename, len + 1);
803 return buffer;
805 #endif /* !defined(__PCTOOL__) */
807 /* Read (up to) a line of text from fd into buffer and return number of bytes
808 * read (which may be larger than the number of bytes stored in buffer). If
809 * an error occurs, -1 is returned (and buffer contains whatever could be
810 * read). A line is terminated by a LF char. Neither LF nor CR chars are
811 * stored in buffer.
813 int read_line(int fd, char* buffer, int buffer_size)
815 int count = 0;
816 int num_read = 0;
818 errno = 0;
820 while (count < buffer_size)
822 unsigned char c;
824 if (1 != read(fd, &c, 1))
825 break;
827 num_read++;
829 if ( c == '\n' )
830 break;
832 if ( c == '\r' )
833 continue;
835 buffer[count++] = c;
838 buffer[MIN(count, buffer_size - 1)] = 0;
840 return errno ? -1 : num_read;
844 char* skip_whitespace(char* const str)
846 char *s = str;
848 while (isspace(*s))
849 s++;
851 return s;
854 /* Format time into buf.
856 * buf - buffer to format to.
857 * buf_size - size of buffer.
858 * t - time to format, in milliseconds.
860 void format_time(char* buf, int buf_size, long t)
862 if ( t < 3600000 )
864 snprintf(buf, buf_size, "%d:%02d",
865 (int) (t / 60000), (int) (t % 60000 / 1000));
867 else
869 snprintf(buf, buf_size, "%d:%02d:%02d",
870 (int) (t / 3600000), (int) (t % 3600000 / 60000),
871 (int) (t % 60000 / 1000));
876 /** Open a UTF-8 file and set file descriptor to first byte after BOM.
877 * If no BOM is present this behaves like open().
878 * If the file is opened for writing and O_TRUNC is set, write a BOM to
879 * the opened file and leave the file pointer set after the BOM.
881 #define BOM "\xef\xbb\xbf"
882 #define BOM_SIZE 3
884 int open_utf8(const char* pathname, int flags)
886 int fd;
887 unsigned char bom[BOM_SIZE];
889 fd = open(pathname, flags);
890 if(fd < 0)
891 return fd;
893 if(flags & (O_TRUNC | O_WRONLY))
895 write(fd, BOM, BOM_SIZE);
897 else
899 read(fd, bom, BOM_SIZE);
900 /* check for BOM */
901 if(memcmp(bom, BOM, BOM_SIZE))
902 lseek(fd, 0, SEEK_SET);
904 return fd;
908 #ifdef HAVE_LCD_COLOR
910 * Helper function to convert a string of 6 hex digits to a native colour
913 static int hex2dec(int c)
915 return (((c) >= '0' && ((c) <= '9')) ? (c) - '0' :
916 (toupper(c)) - 'A' + 10);
919 int hex_to_rgb(const char* hex, int* color)
921 int red, green, blue;
922 int i = 0;
924 while ((i < 6) && (isxdigit(hex[i])))
925 i++;
927 if (i < 6)
928 return -1;
930 red = (hex2dec(hex[0]) << 4) | hex2dec(hex[1]);
931 green = (hex2dec(hex[2]) << 4) | hex2dec(hex[3]);
932 blue = (hex2dec(hex[4]) << 4) | hex2dec(hex[5]);
934 *color = LCD_RGBPACK(red,green,blue);
936 return 0;
938 #endif /* HAVE_LCD_COLOR */
940 #ifdef HAVE_LCD_BITMAP
941 /* A simplified scanf - used (at time of writing) by wps parsing functions.
943 fmt - char array specifying the format of each list option. Valid values
944 are: d - int
945 s - string (sets pointer to string, without copying)
946 c - hex colour (RGB888 - e.g. ff00ff)
947 g - greyscale "colour" (0-3)
948 set_vals - if not NULL 1 is set in the bitplace if the item was read OK
949 0 if not read.
950 first item is LSB, (max 32 items! )
951 Stops parseing if an item is invalid unless the item == '-'
952 sep - list separator (e.g. ',' or '|')
953 str - string to parse, must be terminated by 0 or sep
954 ... - pointers to store the parsed values
956 return value - pointer to char after parsed data, 0 if there was an error.
960 /* '0'-'3' are ASCII 0x30 to 0x33 */
961 #define is0123(x) (((x) & 0xfc) == 0x30)
963 const char* parse_list(const char *fmt, uint32_t *set_vals,
964 const char sep, const char* str, ...)
966 va_list ap;
967 const char* p = str, *f = fmt;
968 const char** s;
969 int* d;
970 bool set, is_negative;
971 int i=0;
973 va_start(ap, str);
974 if (set_vals)
975 *set_vals = 0;
976 while (*fmt)
978 /* Check for separator, if we're not at the start */
979 if (f != fmt)
981 if (*p != sep)
982 goto err;
983 p++;
985 set = false;
986 switch (*fmt++)
988 case 's': /* string - return a pointer to it (not a copy) */
989 s = va_arg(ap, const char **);
991 *s = p;
992 while (*p && *p != sep)
993 p++;
994 set = (s[0][0]!='-') && (s[0][1]!=sep) ;
995 break;
997 case 'd': /* int */
998 is_negative = false;
999 d = va_arg(ap, int*);
1000 if (*p == '-' && isdigit(*(p+1)))
1002 is_negative = true;
1003 p++;
1005 if (!isdigit(*p))
1007 if (!set_vals || *p != '-')
1008 goto err;
1009 while (*p && *p != sep)
1010 p++;
1012 else
1014 *d = *p++ - '0';
1015 while (isdigit(*p))
1016 *d = (*d * 10) + (*p++ - '0');
1017 set = true;
1018 if (is_negative)
1019 *d *= -1;
1022 break;
1024 #ifdef HAVE_LCD_COLOR
1025 case 'c': /* colour (rrggbb - e.g. f3c1a8) */
1026 d = va_arg(ap, int*);
1028 if (hex_to_rgb(p, d) < 0)
1030 if (!set_vals || *p != '-')
1031 goto err;
1032 while (*p && *p != sep)
1033 p++;
1035 else
1037 p += 6;
1038 set = true;
1041 break;
1042 #endif
1044 #if LCD_DEPTH == 2 || (defined(HAVE_REMOTE_LCD) && LCD_REMOTE_DEPTH == 2)
1045 case 'g': /* greyscale colour (0-3) */
1046 d = va_arg(ap, int*);
1048 if (is0123(*p))
1050 *d = *p++ - '0';
1051 set = true;
1053 else if (!set_vals || *p != '-')
1054 goto err;
1055 else
1057 while (*p && *p != sep)
1058 p++;
1061 break;
1062 #endif
1064 default: /* Unknown format type */
1065 goto err;
1066 break;
1068 if (set_vals && set)
1069 *set_vals |= BIT_N(i);
1070 i++;
1073 va_end(ap);
1074 return p;
1076 err:
1077 va_end(ap);
1078 return NULL;
1081 /* only used in USB HID and set_time screen */
1082 #if defined(USB_ENABLE_HID) || (CONFIG_RTC != 0)
1083 int clamp_value_wrap(int value, int max, int min)
1085 if (value > max)
1086 return min;
1087 if (value < min)
1088 return max;
1089 return value;
1091 #endif
1092 #endif