Theme Editor: Fixed rendering behavior of default viewport. Now when other viewports...
[kugel-rb.git] / apps / misc.c
blobbae8dfbd07325f591320721b061ac14e4568f781
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 #if (CONFIG_PLATFORM & PLATFORM_HOSTED)
255 (void)callback;
256 (void)parameter;
257 bookmark_autobookmark(false);
258 call_storage_idle_notifys(true);
259 #else
260 long msg_id = -1;
261 int i;
263 scrobbler_poweroff();
265 #if CONFIG_CHARGING && !defined(HAVE_POWEROFF_WHILE_CHARGING)
266 if(!charger_inserted())
267 #endif
269 bool batt_safe = battery_level_safe();
270 int audio_stat = audio_status();
272 FOR_NB_SCREENS(i)
274 screens[i].clear_display();
275 screens[i].update();
278 if (batt_safe)
280 #ifdef HAVE_TAGCACHE
281 if (!tagcache_prepare_shutdown())
283 cancel_shutdown();
284 splash(HZ, ID2P(LANG_TAGCACHE_BUSY));
285 return false;
287 #endif
288 if (battery_level() > 10)
289 splash(0, str(LANG_SHUTTINGDOWN));
290 else
292 msg_id = LANG_WARNING_BATTERY_LOW;
293 splashf(0, "%s %s", str(LANG_WARNING_BATTERY_LOW),
294 str(LANG_SHUTTINGDOWN));
297 else
299 msg_id = LANG_WARNING_BATTERY_EMPTY;
300 splashf(0, "%s %s", str(LANG_WARNING_BATTERY_EMPTY),
301 str(LANG_SHUTTINGDOWN));
304 if (global_settings.fade_on_stop
305 && (audio_stat & AUDIO_STATUS_PLAY))
307 fade(false, false);
310 if (batt_safe) /* do not save on critical battery */
312 #if defined(HAVE_RECORDING) && CONFIG_CODEC == SWCODEC
313 if (audio_stat & AUDIO_STATUS_RECORD)
315 rec_command(RECORDING_CMD_STOP);
316 /* wait for stop to complete */
317 while (audio_status() & AUDIO_STATUS_RECORD)
318 sleep(1);
320 #endif
321 bookmark_autobookmark(false);
323 /* audio_stop_recording == audio_stop for HWCODEC */
324 audio_stop();
326 if (callback != NULL)
327 callback(parameter);
329 #if CONFIG_CODEC != SWCODEC
330 /* wait for audio_stop or audio_stop_recording to complete */
331 while (audio_status())
332 sleep(1);
333 #endif
335 #if defined(HAVE_RECORDING) && CONFIG_CODEC == SWCODEC
336 audio_close_recording();
337 #endif
339 if(global_settings.talk_menu)
341 bool enqueue = false;
342 if(msg_id != -1)
344 talk_id(msg_id, enqueue);
345 enqueue = true;
347 talk_id(LANG_SHUTTINGDOWN, enqueue);
348 #if CONFIG_CODEC == SWCODEC
349 voice_wait();
350 #endif
353 system_flush();
354 #ifdef HAVE_EEPROM_SETTINGS
355 if (firmware_settings.initialized)
357 firmware_settings.disk_clean = true;
358 firmware_settings.bl_version = 0;
359 eeprom_settings_store();
361 #endif
363 #ifdef HAVE_DIRCACHE
364 else
365 dircache_disable();
366 #endif
368 shutdown_hw();
370 #endif
371 return false;
374 bool list_stop_handler(void)
376 bool ret = false;
378 /* Stop the music if it is playing */
379 if(audio_status())
381 if (!global_settings.party_mode)
383 if (global_settings.fade_on_stop)
384 fade(false, false);
385 bookmark_autobookmark(true);
386 audio_stop();
387 ret = true; /* bookmarking can make a refresh necessary */
390 #if CONFIG_CHARGING
391 #if (CONFIG_KEYPAD == RECORDER_PAD) && !defined(HAVE_SW_POWEROFF)
392 else
394 if (charger_inserted())
395 charging_splash();
396 else
397 shutdown_screen(); /* won't return if shutdown actually happens */
399 ret = true; /* screen is dirty, caller needs to refresh */
401 #endif
402 #ifndef HAVE_POWEROFF_WHILE_CHARGING
404 static long last_off = 0;
406 if (TIME_BEFORE(current_tick, last_off + HZ/2))
408 if (charger_inserted())
410 charging_splash();
411 ret = true; /* screen is dirty, caller needs to refresh */
414 last_off = current_tick;
416 #endif
417 #endif /* CONFIG_CHARGING */
418 return ret;
421 #if CONFIG_CHARGING
422 static bool waiting_to_resume_play = false;
423 static long play_resume_tick;
425 static void car_adapter_mode_processing(bool inserted)
427 if (global_settings.car_adapter_mode)
429 if(inserted)
432 * Just got plugged in, delay & resume if we were playing
434 if (audio_status() & AUDIO_STATUS_PAUSE)
436 /* delay resume a bit while the engine is cranking */
437 play_resume_tick = current_tick + HZ*5;
438 waiting_to_resume_play = true;
441 else
444 * Just got unplugged, pause if playing
446 if ((audio_status() & AUDIO_STATUS_PLAY) &&
447 !(audio_status() & AUDIO_STATUS_PAUSE))
449 if (global_settings.fade_on_stop)
450 fade(false, false);
451 else
452 audio_pause();
454 waiting_to_resume_play = false;
459 static void car_adapter_tick(void)
461 if (waiting_to_resume_play)
463 if (TIME_AFTER(current_tick, play_resume_tick))
465 if (audio_status() & AUDIO_STATUS_PAUSE)
467 queue_broadcast(SYS_CAR_ADAPTER_RESUME, 0);
469 waiting_to_resume_play = false;
474 void car_adapter_mode_init(void)
476 tick_add_task(car_adapter_tick);
478 #endif
480 #ifdef HAVE_HEADPHONE_DETECTION
481 static void unplug_change(bool inserted)
483 static bool headphone_caused_pause = false;
485 if (global_settings.unplug_mode)
487 int audio_stat = audio_status();
488 if (inserted)
490 if ((audio_stat & AUDIO_STATUS_PLAY) &&
491 headphone_caused_pause &&
492 global_settings.unplug_mode > 1 )
493 audio_resume();
494 backlight_on();
495 headphone_caused_pause = false;
496 } else {
497 if ((audio_stat & AUDIO_STATUS_PLAY) &&
498 !(audio_stat & AUDIO_STATUS_PAUSE))
500 headphone_caused_pause = true;
501 audio_pause();
503 if (global_settings.unplug_rw)
505 if (audio_current_track()->elapsed >
506 (unsigned long)(global_settings.unplug_rw*1000))
507 audio_ff_rewind(audio_current_track()->elapsed -
508 (global_settings.unplug_rw*1000));
509 else
510 audio_ff_rewind(0);
516 #endif
518 long default_event_handler_ex(long event, void (*callback)(void *), void *parameter)
520 switch(event)
522 case SYS_BATTERY_UPDATE:
523 if(global_settings.talk_battery_level)
525 talk_ids(true, VOICE_PAUSE, VOICE_PAUSE,
526 LANG_BATTERY_TIME,
527 TALK_ID(battery_level(), UNIT_PERCENT),
528 VOICE_PAUSE);
529 talk_force_enqueue_next();
531 break;
532 case SYS_USB_CONNECTED:
533 if (callback != NULL)
534 callback(parameter);
535 #if (CONFIG_STORAGE & STORAGE_MMC)
536 if (!mmc_touched() ||
537 (mmc_remove_request() == SYS_HOTSWAP_EXTRACTED))
538 #endif
540 system_flush();
541 #ifdef BOOTFILE
542 #if !defined(USB_NONE) && !defined(USB_HANDLED_BY_OF)
543 check_bootfile(false); /* gets initial size */
544 #endif
545 #endif
546 gui_usb_screen_run();
547 #ifdef BOOTFILE
548 #if !defined(USB_NONE) && !defined(USB_HANDLED_BY_OF)
549 check_bootfile(true);
550 #endif
551 #endif
552 system_restore();
554 return SYS_USB_CONNECTED;
556 case SYS_POWEROFF:
557 if (!clean_shutdown(callback, parameter))
558 return SYS_POWEROFF;
559 break;
560 #if CONFIG_CHARGING
561 case SYS_CHARGER_CONNECTED:
562 car_adapter_mode_processing(true);
563 return SYS_CHARGER_CONNECTED;
565 case SYS_CHARGER_DISCONNECTED:
566 car_adapter_mode_processing(false);
567 /*reset rockbox battery runtime*/
568 global_status.runtime = 0;
569 return SYS_CHARGER_DISCONNECTED;
571 case SYS_CAR_ADAPTER_RESUME:
572 audio_resume();
573 return SYS_CAR_ADAPTER_RESUME;
574 #endif
575 #ifdef HAVE_HOTSWAP_STORAGE_AS_MAIN
576 case SYS_FS_CHANGED:
578 /* simple sanity: assume rockbox is on the first hotswappable
579 * driver, abort out if that one isn't inserted */
580 int i;
581 for (i = 0; i < NUM_DRIVES; i++)
583 if (storage_removable(i) && !storage_present(i))
584 return SYS_FS_CHANGED;
586 system_flush();
587 check_bootfile(true); /* state gotten in main.c:init() */
588 system_restore();
590 return SYS_FS_CHANGED;
591 #endif
592 #ifdef HAVE_HEADPHONE_DETECTION
593 case SYS_PHONE_PLUGGED:
594 unplug_change(true);
595 return SYS_PHONE_PLUGGED;
597 case SYS_PHONE_UNPLUGGED:
598 unplug_change(false);
599 return SYS_PHONE_UNPLUGGED;
600 #endif
601 #ifdef IPOD_ACCESSORY_PROTOCOL
602 case SYS_IAP_PERIODIC:
603 iap_periodic();
604 return SYS_IAP_PERIODIC;
605 case SYS_IAP_HANDLEPKT:
606 iap_handlepkt();
607 return SYS_IAP_HANDLEPKT;
608 #endif
610 return 0;
613 long default_event_handler(long event)
615 return default_event_handler_ex(event, NULL, NULL);
618 int show_logo( void )
620 #ifdef HAVE_LCD_BITMAP
621 char version[32];
622 int font_h, font_w;
624 snprintf(version, sizeof(version), "Ver. %s", rbversion);
626 lcd_clear_display();
627 #if defined(SANSA_CLIP) || defined(SANSA_CLIPV2) || defined(SANSA_CLIPPLUS)
628 /* display the logo in the blue area of the screen */
629 lcd_setfont(FONT_SYSFIXED);
630 lcd_getstringsize((unsigned char *)"A", &font_w, &font_h);
631 lcd_putsxy((LCD_WIDTH/2) - ((strlen(version)*font_w)/2),
632 0, (unsigned char *)version);
633 lcd_bitmap(rockboxlogo, 0, 16, BMPWIDTH_rockboxlogo, BMPHEIGHT_rockboxlogo);
634 #else
635 lcd_bitmap(rockboxlogo, 0, 10, BMPWIDTH_rockboxlogo, BMPHEIGHT_rockboxlogo);
636 lcd_setfont(FONT_SYSFIXED);
637 lcd_getstringsize((unsigned char *)"A", &font_w, &font_h);
638 lcd_putsxy((LCD_WIDTH/2) - ((strlen(version)*font_w)/2),
639 LCD_HEIGHT-font_h, (unsigned char *)version);
640 #endif
641 lcd_setfont(FONT_UI);
643 #else
644 char *rockbox = " ROCKbox!";
646 lcd_clear_display();
647 lcd_double_height(true);
648 lcd_puts(0, 0, rockbox);
649 lcd_puts_scroll(0, 1, rbversion);
650 #endif
651 lcd_update();
653 #ifdef HAVE_REMOTE_LCD
654 lcd_remote_clear_display();
655 lcd_remote_bitmap(remote_rockboxlogo, 0, 10, BMPWIDTH_remote_rockboxlogo,
656 BMPHEIGHT_remote_rockboxlogo);
657 lcd_remote_setfont(FONT_SYSFIXED);
658 lcd_remote_getstringsize((unsigned char *)"A", &font_w, &font_h);
659 lcd_remote_putsxy((LCD_REMOTE_WIDTH/2) - ((strlen(version)*font_w)/2),
660 LCD_REMOTE_HEIGHT-font_h, (unsigned char *)version);
661 lcd_remote_setfont(FONT_UI);
662 lcd_remote_update();
663 #endif
665 return 0;
668 #ifdef BOOTFILE
669 #if !defined(USB_NONE) && !defined(USB_HANDLED_BY_OF) || defined(HAVE_HOTSWAP_STORAGE_AS_MAIN)
671 memorize/compare details about the BOOTFILE
672 we don't use dircache because it may not be up to date after
673 USB disconnect (scanning in the background)
675 void check_bootfile(bool do_rolo)
677 static unsigned short wrtdate = 0;
678 static unsigned short wrttime = 0;
679 DIR* dir = NULL;
680 struct dirent* entry = NULL;
682 /* 1. open BOOTDIR and find the BOOTFILE dir entry */
683 dir = opendir(BOOTDIR);
685 if(!dir) return; /* do we want an error splash? */
687 /* loop all files in BOOTDIR */
688 while(0 != (entry = readdir(dir)))
690 if(!strcasecmp(entry->d_name, BOOTFILE))
692 /* found the bootfile */
693 if(wrtdate && do_rolo)
695 if((entry->wrtdate != wrtdate) ||
696 (entry->wrttime != wrttime))
698 static const char *lines[] = { ID2P(LANG_BOOT_CHANGED),
699 ID2P(LANG_REBOOT_NOW) };
700 static const struct text_message message={ lines, 2 };
701 button_clear_queue(); /* Empty the keyboard buffer */
702 if(gui_syncyesno_run(&message, NULL, NULL) == YESNO_YES)
703 rolo_load(BOOTDIR "/" BOOTFILE);
706 wrtdate = entry->wrtdate;
707 wrttime = entry->wrttime;
710 closedir(dir);
712 #endif
713 #endif
715 /* check range, set volume and save settings */
716 void setvol(void)
718 const int min_vol = sound_min(SOUND_VOLUME);
719 const int max_vol = sound_max(SOUND_VOLUME);
720 if (global_settings.volume < min_vol)
721 global_settings.volume = min_vol;
722 if (global_settings.volume > max_vol)
723 global_settings.volume = max_vol;
724 sound_set_volume(global_settings.volume);
725 global_status.last_volume_change = current_tick;
726 settings_save();
729 char* strrsplt(char* str, int c)
731 char* s = strrchr(str, c);
733 if (s != NULL)
735 *s++ = '\0';
737 else
739 s = str;
742 return s;
745 /* Test file existence, using dircache of possible */
746 bool file_exists(const char *file)
748 int fd;
750 if (!file || strlen(file) <= 0)
751 return false;
753 #ifdef HAVE_DIRCACHE
754 if (dircache_is_enabled())
755 return (dircache_get_entry_ptr(file) != NULL);
756 #endif
758 fd = open(file, O_RDONLY);
759 if (fd < 0)
760 return false;
761 close(fd);
762 return true;
765 bool dir_exists(const char *path)
767 DIR* d = opendir(path);
768 if (!d)
769 return false;
770 closedir(d);
771 return true;
775 * removes the extension of filename (if it doesn't start with a .)
776 * puts the result in buffer
778 char *strip_extension(char* buffer, int buffer_size, const char *filename)
780 char *dot = strrchr(filename, '.');
781 int len;
783 if (buffer_size <= 0)
785 return NULL;
788 buffer_size--; /* Make room for end nil */
790 if (dot != 0 && filename[0] != '.')
792 len = dot - filename;
793 len = MIN(len, buffer_size);
795 else
797 len = buffer_size;
800 strlcpy(buffer, filename, len + 1);
802 return buffer;
804 #endif /* !defined(__PCTOOL__) */
806 /* Read (up to) a line of text from fd into buffer and return number of bytes
807 * read (which may be larger than the number of bytes stored in buffer). If
808 * an error occurs, -1 is returned (and buffer contains whatever could be
809 * read). A line is terminated by a LF char. Neither LF nor CR chars are
810 * stored in buffer.
812 int read_line(int fd, char* buffer, int buffer_size)
814 int count = 0;
815 int num_read = 0;
817 errno = 0;
819 while (count < buffer_size)
821 unsigned char c;
823 if (1 != read(fd, &c, 1))
824 break;
826 num_read++;
828 if ( c == '\n' )
829 break;
831 if ( c == '\r' )
832 continue;
834 buffer[count++] = c;
837 buffer[MIN(count, buffer_size - 1)] = 0;
839 return errno ? -1 : num_read;
843 char* skip_whitespace(char* const str)
845 char *s = str;
847 while (isspace(*s))
848 s++;
850 return s;
853 /* Format time into buf.
855 * buf - buffer to format to.
856 * buf_size - size of buffer.
857 * t - time to format, in milliseconds.
859 void format_time(char* buf, int buf_size, long t)
861 if ( t < 3600000 )
863 snprintf(buf, buf_size, "%d:%02d",
864 (int) (t / 60000), (int) (t % 60000 / 1000));
866 else
868 snprintf(buf, buf_size, "%d:%02d:%02d",
869 (int) (t / 3600000), (int) (t % 3600000 / 60000),
870 (int) (t % 60000 / 1000));
875 /** Open a UTF-8 file and set file descriptor to first byte after BOM.
876 * If no BOM is present this behaves like open().
877 * If the file is opened for writing and O_TRUNC is set, write a BOM to
878 * the opened file and leave the file pointer set after the BOM.
880 #define BOM "\xef\xbb\xbf"
881 #define BOM_SIZE 3
883 int open_utf8(const char* pathname, int flags)
885 int fd;
886 unsigned char bom[BOM_SIZE];
888 fd = open(pathname, flags);
889 if(fd < 0)
890 return fd;
892 if(flags & (O_TRUNC | O_WRONLY))
894 write(fd, BOM, BOM_SIZE);
896 else
898 read(fd, bom, BOM_SIZE);
899 /* check for BOM */
900 if(memcmp(bom, BOM, BOM_SIZE))
901 lseek(fd, 0, SEEK_SET);
903 return fd;
907 #ifdef HAVE_LCD_COLOR
909 * Helper function to convert a string of 6 hex digits to a native colour
912 static int hex2dec(int c)
914 return (((c) >= '0' && ((c) <= '9')) ? (c) - '0' :
915 (toupper(c)) - 'A' + 10);
918 int hex_to_rgb(const char* hex, int* color)
920 int red, green, blue;
921 int i = 0;
923 while ((i < 6) && (isxdigit(hex[i])))
924 i++;
926 if (i < 6)
927 return -1;
929 red = (hex2dec(hex[0]) << 4) | hex2dec(hex[1]);
930 green = (hex2dec(hex[2]) << 4) | hex2dec(hex[3]);
931 blue = (hex2dec(hex[4]) << 4) | hex2dec(hex[5]);
933 *color = LCD_RGBPACK(red,green,blue);
935 return 0;
937 #endif /* HAVE_LCD_COLOR */
939 #ifdef HAVE_LCD_BITMAP
940 /* A simplified scanf - used (at time of writing) by wps parsing functions.
942 fmt - char array specifying the format of each list option. Valid values
943 are: d - int
944 s - string (sets pointer to string, without copying)
945 c - hex colour (RGB888 - e.g. ff00ff)
946 g - greyscale "colour" (0-3)
947 set_vals - if not NULL 1 is set in the bitplace if the item was read OK
948 0 if not read.
949 first item is LSB, (max 32 items! )
950 Stops parseing if an item is invalid unless the item == '-'
951 sep - list separator (e.g. ',' or '|')
952 str - string to parse, must be terminated by 0 or sep
953 ... - pointers to store the parsed values
955 return value - pointer to char after parsed data, 0 if there was an error.
959 /* '0'-'3' are ASCII 0x30 to 0x33 */
960 #define is0123(x) (((x) & 0xfc) == 0x30)
962 const char* parse_list(const char *fmt, uint32_t *set_vals,
963 const char sep, const char* str, ...)
965 va_list ap;
966 const char* p = str, *f = fmt;
967 const char** s;
968 int* d;
969 bool set, is_negative;
970 int i=0;
972 va_start(ap, str);
973 if (set_vals)
974 *set_vals = 0;
975 while (*fmt)
977 /* Check for separator, if we're not at the start */
978 if (f != fmt)
980 if (*p != sep)
981 goto err;
982 p++;
984 set = false;
985 switch (*fmt++)
987 case 's': /* string - return a pointer to it (not a copy) */
988 s = va_arg(ap, const char **);
990 *s = p;
991 while (*p && *p != sep && *p != ')')
992 p++;
993 set = (s[0][0]!='-') && (s[0][1]!=sep && s[0][1]!=')') ;
994 break;
996 case 'd': /* int */
997 is_negative = false;
998 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 p++;
1011 else
1013 *d = *p++ - '0';
1014 while (isdigit(*p))
1015 *d = (*d * 10) + (*p++ - '0');
1016 set = true;
1017 if (is_negative)
1018 *d *= -1;
1021 break;
1023 #ifdef HAVE_LCD_COLOR
1024 case 'c': /* colour (rrggbb - e.g. f3c1a8) */
1025 d = va_arg(ap, int*);
1027 if (hex_to_rgb(p, d) < 0)
1029 if (!set_vals || *p != '-')
1030 goto err;
1031 p++;
1033 else
1035 p += 6;
1036 set = true;
1039 break;
1040 #endif
1042 #if LCD_DEPTH == 2 || (defined(HAVE_REMOTE_LCD) && LCD_REMOTE_DEPTH == 2)
1043 case 'g': /* greyscale colour (0-3) */
1044 d = va_arg(ap, int*);
1046 if (!is0123(*p))
1048 if (!set_vals || *p != '-')
1049 goto err;
1050 p++;
1052 else
1054 *d = *p++ - '0';
1055 set = true;
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