Merge branch 'master' into sim-target-tree
[kugel-rb.git] / apps / misc.c
blob07b4c947a216298fd9069daf8b71c4ba52d408e7
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 CONFIG_CHARGING >= CHARGING_MONITOR
268 if(!charging_state())
269 #else
270 if(!charger_inserted())
271 #endif
272 #endif
274 bool batt_safe = battery_level_safe();
275 int audio_stat = audio_status();
277 FOR_NB_SCREENS(i)
279 screens[i].clear_display();
280 screens[i].update();
283 if (batt_safe)
285 #ifdef HAVE_TAGCACHE
286 if (!tagcache_prepare_shutdown())
288 cancel_shutdown();
289 splash(HZ, ID2P(LANG_TAGCACHE_BUSY));
290 return false;
292 #endif
293 if (battery_level() > 10)
294 splash(0, str(LANG_SHUTTINGDOWN));
295 else
297 msg_id = LANG_WARNING_BATTERY_LOW;
298 splashf(0, "%s %s", str(LANG_WARNING_BATTERY_LOW),
299 str(LANG_SHUTTINGDOWN));
302 else
304 msg_id = LANG_WARNING_BATTERY_EMPTY;
305 splashf(0, "%s %s", str(LANG_WARNING_BATTERY_EMPTY),
306 str(LANG_SHUTTINGDOWN));
309 if (global_settings.fade_on_stop
310 && (audio_stat & AUDIO_STATUS_PLAY))
312 fade(false, false);
315 if (batt_safe) /* do not save on critical battery */
317 #if defined(HAVE_RECORDING) && CONFIG_CODEC == SWCODEC
318 if (audio_stat & AUDIO_STATUS_RECORD)
320 rec_command(RECORDING_CMD_STOP);
321 /* wait for stop to complete */
322 while (audio_status() & AUDIO_STATUS_RECORD)
323 sleep(1);
325 #endif
326 bookmark_autobookmark(false);
328 /* audio_stop_recording == audio_stop for HWCODEC */
329 audio_stop();
331 if (callback != NULL)
332 callback(parameter);
334 #if CONFIG_CODEC != SWCODEC
335 /* wait for audio_stop or audio_stop_recording to complete */
336 while (audio_status())
337 sleep(1);
338 #endif
340 #if defined(HAVE_RECORDING) && CONFIG_CODEC == SWCODEC
341 audio_close_recording();
342 #endif
344 if(global_settings.talk_menu)
346 bool enqueue = false;
347 if(msg_id != -1)
349 talk_id(msg_id, enqueue);
350 enqueue = true;
352 talk_id(LANG_SHUTTINGDOWN, enqueue);
353 #if CONFIG_CODEC == SWCODEC
354 voice_wait();
355 #endif
358 system_flush();
359 #ifdef HAVE_EEPROM_SETTINGS
360 if (firmware_settings.initialized)
362 firmware_settings.disk_clean = true;
363 firmware_settings.bl_version = 0;
364 eeprom_settings_store();
366 #endif
368 #ifdef HAVE_DIRCACHE
369 else
370 dircache_disable();
371 #endif
373 shutdown_hw();
375 #endif
376 return false;
379 bool list_stop_handler(void)
381 bool ret = false;
383 /* Stop the music if it is playing */
384 if(audio_status())
386 if (!global_settings.party_mode)
388 if (global_settings.fade_on_stop)
389 fade(false, false);
390 bookmark_autobookmark(true);
391 audio_stop();
392 ret = true; /* bookmarking can make a refresh necessary */
395 #if CONFIG_CHARGING
396 #if (CONFIG_KEYPAD == RECORDER_PAD) && !defined(HAVE_SW_POWEROFF)
397 else
399 if (charger_inserted())
400 charging_splash();
401 else
402 shutdown_screen(); /* won't return if shutdown actually happens */
404 ret = true; /* screen is dirty, caller needs to refresh */
406 #endif
407 #ifndef HAVE_POWEROFF_WHILE_CHARGING
409 static long last_off = 0;
411 if (TIME_BEFORE(current_tick, last_off + HZ/2))
413 #if CONFIG_CHARGING >= CHARGING_MONITOR
414 if (charging_state())
415 #else
416 if (charger_inserted())
417 #endif
419 charging_splash();
420 ret = true; /* screen is dirty, caller needs to refresh */
423 last_off = current_tick;
425 #endif
426 #endif /* CONFIG_CHARGING */
427 return ret;
430 #if CONFIG_CHARGING
431 static bool waiting_to_resume_play = false;
432 static long play_resume_tick;
434 static void car_adapter_mode_processing(bool inserted)
436 if (global_settings.car_adapter_mode)
438 if(inserted)
441 * Just got plugged in, delay & resume if we were playing
443 if (audio_status() & AUDIO_STATUS_PAUSE)
445 /* delay resume a bit while the engine is cranking */
446 play_resume_tick = current_tick + HZ*5;
447 waiting_to_resume_play = true;
450 else
453 * Just got unplugged, pause if playing
455 if ((audio_status() & AUDIO_STATUS_PLAY) &&
456 !(audio_status() & AUDIO_STATUS_PAUSE))
458 if (global_settings.fade_on_stop)
459 fade(false, false);
460 else
461 audio_pause();
463 waiting_to_resume_play = false;
468 static void car_adapter_tick(void)
470 if (waiting_to_resume_play)
472 if (TIME_AFTER(current_tick, play_resume_tick))
474 if (audio_status() & AUDIO_STATUS_PAUSE)
476 queue_broadcast(SYS_CAR_ADAPTER_RESUME, 0);
478 waiting_to_resume_play = false;
483 void car_adapter_mode_init(void)
485 tick_add_task(car_adapter_tick);
487 #endif
489 #ifdef HAVE_HEADPHONE_DETECTION
490 static void unplug_change(bool inserted)
492 static bool headphone_caused_pause = false;
494 if (global_settings.unplug_mode)
496 int audio_stat = audio_status();
497 if (inserted)
499 if ((audio_stat & AUDIO_STATUS_PLAY) &&
500 headphone_caused_pause &&
501 global_settings.unplug_mode > 1 )
502 audio_resume();
503 backlight_on();
504 headphone_caused_pause = false;
505 } else {
506 if ((audio_stat & AUDIO_STATUS_PLAY) &&
507 !(audio_stat & AUDIO_STATUS_PAUSE))
509 headphone_caused_pause = true;
510 audio_pause();
512 if (global_settings.unplug_rw)
514 if (audio_current_track()->elapsed >
515 (unsigned long)(global_settings.unplug_rw*1000))
516 audio_ff_rewind(audio_current_track()->elapsed -
517 (global_settings.unplug_rw*1000));
518 else
519 audio_ff_rewind(0);
525 #endif
527 long default_event_handler_ex(long event, void (*callback)(void *), void *parameter)
529 switch(event)
531 case SYS_BATTERY_UPDATE:
532 if(global_settings.talk_battery_level)
534 talk_ids(true, VOICE_PAUSE, VOICE_PAUSE,
535 LANG_BATTERY_TIME,
536 TALK_ID(battery_level(), UNIT_PERCENT),
537 VOICE_PAUSE);
538 talk_force_enqueue_next();
540 break;
541 case SYS_USB_CONNECTED:
542 if (callback != NULL)
543 callback(parameter);
544 #if (CONFIG_STORAGE & STORAGE_MMC)
545 if (!mmc_touched() ||
546 (mmc_remove_request() == SYS_HOTSWAP_EXTRACTED))
547 #endif
549 system_flush();
550 #ifdef BOOTFILE
551 #if !defined(USB_NONE) && !defined(USB_HANDLED_BY_OF)
552 check_bootfile(false); /* gets initial size */
553 #endif
554 #endif
555 gui_usb_screen_run();
556 #ifdef BOOTFILE
557 #if !defined(USB_NONE) && !defined(USB_HANDLED_BY_OF)
558 check_bootfile(true);
559 #endif
560 #endif
561 system_restore();
563 return SYS_USB_CONNECTED;
565 case SYS_POWEROFF:
566 if (!clean_shutdown(callback, parameter))
567 return SYS_POWEROFF;
568 break;
569 #if CONFIG_CHARGING
570 case SYS_CHARGER_CONNECTED:
571 car_adapter_mode_processing(true);
572 return SYS_CHARGER_CONNECTED;
574 case SYS_CHARGER_DISCONNECTED:
575 car_adapter_mode_processing(false);
576 /*reset rockbox battery runtime*/
577 global_status.runtime = 0;
578 return SYS_CHARGER_DISCONNECTED;
580 case SYS_CAR_ADAPTER_RESUME:
581 audio_resume();
582 return SYS_CAR_ADAPTER_RESUME;
583 #endif
584 #ifdef HAVE_HOTSWAP_STORAGE_AS_MAIN
585 case SYS_FS_CHANGED:
587 /* simple sanity: assume rockbox is on the first hotswappable
588 * driver, abort out if that one isn't inserted */
589 int i;
590 for (i = 0; i < NUM_DRIVES; i++)
592 if (storage_removable(i) && !storage_present(i))
593 return SYS_FS_CHANGED;
595 system_flush();
596 check_bootfile(true); /* state gotten in main.c:init() */
597 system_restore();
599 return SYS_FS_CHANGED;
600 #endif
601 #ifdef HAVE_HEADPHONE_DETECTION
602 case SYS_PHONE_PLUGGED:
603 unplug_change(true);
604 return SYS_PHONE_PLUGGED;
606 case SYS_PHONE_UNPLUGGED:
607 unplug_change(false);
608 return SYS_PHONE_UNPLUGGED;
609 #endif
610 #ifdef IPOD_ACCESSORY_PROTOCOL
611 case SYS_IAP_PERIODIC:
612 iap_periodic();
613 return SYS_IAP_PERIODIC;
614 case SYS_IAP_HANDLEPKT:
615 iap_handlepkt();
616 return SYS_IAP_HANDLEPKT;
617 #endif
619 return 0;
622 long default_event_handler(long event)
624 return default_event_handler_ex(event, NULL, NULL);
627 int show_logo( void )
629 #ifdef HAVE_LCD_BITMAP
630 char version[32];
631 int font_h, font_w;
633 snprintf(version, sizeof(version), "Ver. %s", appsversion);
635 lcd_clear_display();
636 #if defined(SANSA_CLIP) || defined(SANSA_CLIPV2) || defined(SANSA_CLIPPLUS)
637 /* 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 #ifdef BOOTFILE
678 #if !defined(USB_NONE) && !defined(USB_HANDLED_BY_OF) || defined(HAVE_HOTSWAP_STORAGE_AS_MAIN)
680 memorize/compare details about the BOOTFILE
681 we don't use dircache because it may not be up to date after
682 USB disconnect (scanning in the background)
684 void check_bootfile(bool do_rolo)
686 static unsigned short wrtdate = 0;
687 static unsigned short wrttime = 0;
688 DIR* dir = NULL;
689 struct dirent* entry = NULL;
691 /* 1. open BOOTDIR and find the BOOTFILE dir entry */
692 dir = opendir(BOOTDIR);
694 if(!dir) return; /* do we want an error splash? */
696 /* loop all files in BOOTDIR */
697 while(0 != (entry = readdir(dir)))
699 if(!strcasecmp(entry->d_name, BOOTFILE))
701 /* found the bootfile */
702 if(wrtdate && do_rolo)
704 if((entry->wrtdate != wrtdate) ||
705 (entry->wrttime != wrttime))
707 static const char *lines[] = { ID2P(LANG_BOOT_CHANGED),
708 ID2P(LANG_REBOOT_NOW) };
709 static const struct text_message message={ lines, 2 };
710 button_clear_queue(); /* Empty the keyboard buffer */
711 if(gui_syncyesno_run(&message, NULL, NULL) == YESNO_YES)
712 rolo_load(BOOTDIR "/" BOOTFILE);
715 wrtdate = entry->wrtdate;
716 wrttime = entry->wrttime;
719 closedir(dir);
721 #endif
722 #endif
724 /* check range, set volume and save settings */
725 void setvol(void)
727 const int min_vol = sound_min(SOUND_VOLUME);
728 const int max_vol = sound_max(SOUND_VOLUME);
729 if (global_settings.volume < min_vol)
730 global_settings.volume = min_vol;
731 if (global_settings.volume > max_vol)
732 global_settings.volume = max_vol;
733 sound_set_volume(global_settings.volume);
734 global_status.last_volume_change = current_tick;
735 settings_save();
738 char* strrsplt(char* str, int c)
740 char* s = strrchr(str, c);
742 if (s != NULL)
744 *s++ = '\0';
746 else
748 s = str;
751 return s;
754 /* Test file existence, using dircache of possible */
755 bool file_exists(const char *file)
757 int fd;
759 if (!file || strlen(file) <= 0)
760 return false;
762 #ifdef HAVE_DIRCACHE
763 if (dircache_is_enabled())
764 return (dircache_get_entry_ptr(file) != NULL);
765 #endif
767 fd = open(file, O_RDONLY);
768 if (fd < 0)
769 return false;
770 close(fd);
771 return true;
774 bool dir_exists(const char *path)
776 DIR* d = opendir(path);
777 if (!d)
778 return false;
779 closedir(d);
780 return true;
784 * removes the extension of filename (if it doesn't start with a .)
785 * puts the result in buffer
787 char *strip_extension(char* buffer, int buffer_size, const char *filename)
789 char *dot = strrchr(filename, '.');
790 int len;
792 if (buffer_size <= 0)
794 return NULL;
797 buffer_size--; /* Make room for end nil */
799 if (dot != 0 && filename[0] != '.')
801 len = dot - filename;
802 len = MIN(len, buffer_size);
804 else
806 len = buffer_size;
809 strlcpy(buffer, filename, len + 1);
811 return buffer;
813 #endif /* !defined(__PCTOOL__) */
815 /* Read (up to) a line of text from fd into buffer and return number of bytes
816 * read (which may be larger than the number of bytes stored in buffer). If
817 * an error occurs, -1 is returned (and buffer contains whatever could be
818 * read). A line is terminated by a LF char. Neither LF nor CR chars are
819 * stored in buffer.
821 int read_line(int fd, char* buffer, int buffer_size)
823 int count = 0;
824 int num_read = 0;
826 errno = 0;
828 while (count < buffer_size)
830 unsigned char c;
832 if (1 != read(fd, &c, 1))
833 break;
835 num_read++;
837 if ( c == '\n' )
838 break;
840 if ( c == '\r' )
841 continue;
843 buffer[count++] = c;
846 buffer[MIN(count, buffer_size - 1)] = 0;
848 return errno ? -1 : num_read;
852 char* skip_whitespace(char* const str)
854 char *s = str;
856 while (isspace(*s))
857 s++;
859 return s;
862 /* Format time into buf.
864 * buf - buffer to format to.
865 * buf_size - size of buffer.
866 * t - time to format, in milliseconds.
868 void format_time(char* buf, int buf_size, long t)
870 if ( t < 3600000 )
872 snprintf(buf, buf_size, "%d:%02d",
873 (int) (t / 60000), (int) (t % 60000 / 1000));
875 else
877 snprintf(buf, buf_size, "%d:%02d:%02d",
878 (int) (t / 3600000), (int) (t % 3600000 / 60000),
879 (int) (t % 60000 / 1000));
884 /** Open a UTF-8 file and set file descriptor to first byte after BOM.
885 * If no BOM is present this behaves like open().
886 * If the file is opened for writing and O_TRUNC is set, write a BOM to
887 * the opened file and leave the file pointer set after the BOM.
889 #define BOM "\xef\xbb\xbf"
890 #define BOM_SIZE 3
892 int open_utf8(const char* pathname, int flags)
894 int fd;
895 unsigned char bom[BOM_SIZE];
897 fd = open(pathname, flags);
898 if(fd < 0)
899 return fd;
901 if(flags & (O_TRUNC | O_WRONLY))
903 write(fd, BOM, BOM_SIZE);
905 else
907 read(fd, bom, BOM_SIZE);
908 /* check for BOM */
909 if(memcmp(bom, BOM, BOM_SIZE))
910 lseek(fd, 0, SEEK_SET);
912 return fd;
916 #ifdef HAVE_LCD_COLOR
918 * Helper function to convert a string of 6 hex digits to a native colour
921 static int hex2dec(int c)
923 return (((c) >= '0' && ((c) <= '9')) ? (c) - '0' :
924 (toupper(c)) - 'A' + 10);
927 int hex_to_rgb(const char* hex, int* color)
929 int red, green, blue;
930 int i = 0;
932 while ((i < 6) && (isxdigit(hex[i])))
933 i++;
935 if (i < 6)
936 return -1;
938 red = (hex2dec(hex[0]) << 4) | hex2dec(hex[1]);
939 green = (hex2dec(hex[2]) << 4) | hex2dec(hex[3]);
940 blue = (hex2dec(hex[4]) << 4) | hex2dec(hex[5]);
942 *color = LCD_RGBPACK(red,green,blue);
944 return 0;
946 #endif /* HAVE_LCD_COLOR */
948 #ifdef HAVE_LCD_BITMAP
949 /* A simplified scanf - used (at time of writing) by wps parsing functions.
951 fmt - char array specifying the format of each list option. Valid values
952 are: d - int
953 s - string (sets pointer to string, without copying)
954 c - hex colour (RGB888 - e.g. ff00ff)
955 g - greyscale "colour" (0-3)
956 set_vals - if not NULL 1 is set in the bitplace if the item was read OK
957 0 if not read.
958 first item is LSB, (max 32 items! )
959 Stops parseing if an item is invalid unless the item == '-'
960 sep - list separator (e.g. ',' or '|')
961 str - string to parse, must be terminated by 0 or sep
962 ... - pointers to store the parsed values
964 return value - pointer to char after parsed data, 0 if there was an error.
968 /* '0'-'3' are ASCII 0x30 to 0x33 */
969 #define is0123(x) (((x) & 0xfc) == 0x30)
971 const char* parse_list(const char *fmt, uint32_t *set_vals,
972 const char sep, const char* str, ...)
974 va_list ap;
975 const char* p = str, *f = fmt;
976 const char** s;
977 int* d;
978 bool set, is_negative;
979 int i=0;
981 va_start(ap, str);
982 if (set_vals)
983 *set_vals = 0;
984 while (*fmt)
986 /* Check for separator, if we're not at the start */
987 if (f != fmt)
989 if (*p != sep)
990 goto err;
991 p++;
993 set = false;
994 switch (*fmt++)
996 case 's': /* string - return a pointer to it (not a copy) */
997 s = va_arg(ap, const char **);
999 *s = p;
1000 while (*p && *p != sep)
1001 p++;
1002 set = (s[0][0]!='-') && (s[0][1]!=sep) ;
1003 break;
1005 case 'd': /* int */
1006 is_negative = false;
1007 d = va_arg(ap, int*);
1008 if (*p == '-' && isdigit(*(p+1)))
1010 is_negative = true;
1011 p++;
1013 if (!isdigit(*p))
1015 if (!set_vals || *p != '-')
1016 goto err;
1017 while (*p && *p != sep)
1018 p++;
1020 else
1022 *d = *p++ - '0';
1023 while (isdigit(*p))
1024 *d = (*d * 10) + (*p++ - '0');
1025 set = true;
1026 if (is_negative)
1027 *d *= -1;
1030 break;
1032 #ifdef HAVE_LCD_COLOR
1033 case 'c': /* colour (rrggbb - e.g. f3c1a8) */
1034 d = va_arg(ap, int*);
1036 if (hex_to_rgb(p, d) < 0)
1038 if (!set_vals || *p != '-')
1039 goto err;
1040 while (*p && *p != sep)
1041 p++;
1043 else
1045 p += 6;
1046 set = true;
1049 break;
1050 #endif
1052 #if LCD_DEPTH == 2 || (defined(HAVE_REMOTE_LCD) && LCD_REMOTE_DEPTH == 2)
1053 case 'g': /* greyscale colour (0-3) */
1054 d = va_arg(ap, int*);
1056 if (is0123(*p))
1058 *d = *p++ - '0';
1059 set = true;
1061 else if (!set_vals || *p != '-')
1062 goto err;
1063 else
1065 while (*p && *p != sep)
1066 p++;
1069 break;
1070 #endif
1072 default: /* Unknown format type */
1073 goto err;
1074 break;
1076 if (set_vals && set)
1077 *set_vals |= BIT_N(i);
1078 i++;
1081 va_end(ap);
1082 return p;
1084 err:
1085 va_end(ap);
1086 return NULL;
1089 /* only used in USB HID and set_time screen */
1090 #if defined(USB_ENABLE_HID) || (CONFIG_RTC != 0)
1091 int clamp_value_wrap(int value, int max, int min)
1093 if (value > max)
1094 return min;
1095 if (value < min)
1096 return max;
1097 return value;
1099 #endif
1100 #endif