Fix some greedy sed changes in imported code. Also provide a sys/types.h for compatib...
[kugel-rb.git] / apps / misc.c
blob0cdd71dda240a0a246bce22dd95127559cf4cb5a
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-extra.h"
24 #include <stdio.h>
25 #include <stdarg.h>
26 #include "config.h"
27 #include "misc.h"
28 #include "lcd.h"
29 #include "file.h"
30 #ifdef __PCTOOL__
31 #include <stdarg.h>
32 #include <stdio.h>
33 #else
34 #include "lang.h"
35 #include "dir.h"
36 #include "lcd-remote.h"
37 #include "errno.h"
38 #include "system.h"
39 #include "timefuncs.h"
40 #include "screens.h"
41 #include "usb_screen.h"
42 #include "talk.h"
43 #include "audio.h"
44 #include "mp3_playback.h"
45 #include "settings.h"
46 #include "storage.h"
47 #include "ata_idle_notify.h"
48 #include "kernel.h"
49 #include "power.h"
50 #include "powermgmt.h"
51 #include "backlight.h"
52 #include "version.h"
53 #include "font.h"
54 #include "splash.h"
55 #include "tagcache.h"
56 #include "scrobbler.h"
57 #include "sound.h"
58 #include "playlist.h"
59 #include "yesno.h"
60 #include "viewport.h"
62 #ifdef IPOD_ACCESSORY_PROTOCOL
63 #include "iap.h"
64 #endif
66 #if (CONFIG_STORAGE & STORAGE_MMC)
67 #include "ata_mmc.h"
68 #endif
69 #include "tree.h"
70 #include "eeprom_settings.h"
71 #if defined(HAVE_RECORDING) && !defined(__PCTOOL__)
72 #include "recording.h"
73 #endif
74 #if defined(HAVE_LCD_BITMAP) && !defined(__PCTOOL__)
75 #include "bmp.h"
76 #include "icons.h"
77 #endif /* End HAVE_LCD_BITMAP */
78 #include "bookmark.h"
79 #include "wps.h"
80 #include "playback.h"
82 #ifdef BOOTFILE
83 #if !defined(USB_NONE) && !defined(USB_HANDLED_BY_OF) \
84 || defined(HAVE_HOTSWAP_STORAGE_AS_MAIN)
85 #include "rolo.h"
86 #endif
87 #endif
89 /* units used with output_dyn_value */
90 const unsigned char * const byte_units[] =
92 ID2P(LANG_BYTE),
93 ID2P(LANG_KILOBYTE),
94 ID2P(LANG_MEGABYTE),
95 ID2P(LANG_GIGABYTE)
98 const unsigned char * const * const kbyte_units = &byte_units[1];
100 /* Format a large-range value for output, using the appropriate unit so that
101 * the displayed value is in the range 1 <= display < 1000 (1024 for "binary"
102 * units) if possible, and 3 significant digits are shown. If a buffer is
103 * given, the result is snprintf()'d into that buffer, otherwise the result is
104 * voiced.*/
105 char *output_dyn_value(char *buf, int buf_size, int value,
106 const unsigned char * const *units, bool bin_scale)
108 int scale = bin_scale ? 1024 : 1000;
109 int fraction = 0;
110 int unit_no = 0;
111 char tbuf[5];
113 while (value >= scale)
115 fraction = value % scale;
116 value /= scale;
117 unit_no++;
119 if (bin_scale)
120 fraction = fraction * 1000 / 1024;
122 if (value >= 100 || !unit_no)
123 tbuf[0] = '\0';
124 else if (value >= 10)
125 snprintf(tbuf, sizeof(tbuf), "%01d", fraction / 100);
126 else
127 snprintf(tbuf, sizeof(tbuf), "%02d", fraction / 10);
129 if (buf)
131 if (strlen(tbuf))
132 snprintf(buf, buf_size, "%d%s%s%s", value, str(LANG_POINT),
133 tbuf, P2STR(units[unit_no]));
134 else
135 snprintf(buf, buf_size, "%d%s", value, P2STR(units[unit_no]));
137 else
139 talk_fractional(tbuf, value, P2ID(units[unit_no]));
141 return buf;
144 /* Ask the user if they really want to erase the current dynamic playlist
145 * returns true if the playlist should be replaced */
146 bool warn_on_pl_erase(void)
148 if (global_settings.warnon_erase_dynplaylist &&
149 !global_settings.party_mode &&
150 playlist_modified(NULL))
152 static const char *lines[] =
153 {ID2P(LANG_WARN_ERASEDYNPLAYLIST_PROMPT)};
154 static const struct text_message message={lines, 1};
156 return (gui_syncyesno_run(&message, NULL, NULL) == YESNO_YES);
158 else
159 return true;
162 /* Read (up to) a line of text from fd into buffer and return number of bytes
163 * read (which may be larger than the number of bytes stored in buffer). If
164 * an error occurs, -1 is returned (and buffer contains whatever could be
165 * read). A line is terminated by a LF char. Neither LF nor CR chars are
166 * stored in buffer.
168 int read_line(int fd, char* buffer, int buffer_size)
170 int count = 0;
171 int num_read = 0;
173 errno = 0;
175 while (count < buffer_size)
177 unsigned char c;
179 if (1 != read(fd, &c, 1))
180 break;
182 num_read++;
184 if ( c == '\n' )
185 break;
187 if ( c == '\r' )
188 continue;
190 buffer[count++] = c;
193 buffer[MIN(count, buffer_size - 1)] = 0;
195 return errno ? -1 : num_read;
198 /* Performance optimized version of the previous function. */
199 int fast_readline(int fd, char *buf, int buf_size, void *parameters,
200 int (*callback)(int n, const char *buf, void *parameters))
202 char *p, *next;
203 int rc, pos = 0;
204 int count = 0;
206 while ( 1 )
208 next = NULL;
210 rc = read(fd, &buf[pos], buf_size - pos - 1);
211 if (rc >= 0)
212 buf[pos+rc] = '\0';
214 if ( (p = strchr(buf, '\r')) != NULL)
216 *p = '\0';
217 next = ++p;
219 else
220 p = buf;
222 if ( (p = strchr(p, '\n')) != NULL)
224 *p = '\0';
225 next = ++p;
228 rc = callback(count, buf, parameters);
229 if (rc < 0)
230 return rc;
232 count++;
233 if (next)
235 pos = buf_size - ((long)next - (long)buf) - 1;
236 memmove(buf, next, pos);
238 else
239 break ;
242 return 0;
245 /* parse a line from a configuration file. the line format is:
247 name: value
249 Any whitespace before setting name or value (after ':') is ignored.
250 A # as first non-whitespace character discards the whole line.
251 Function sets pointers to null-terminated setting name and value.
252 Returns false if no valid config entry was found.
255 bool settings_parseline(char* line, char** name, char** value)
257 char* ptr;
259 line = skip_whitespace(line);
261 if ( *line == '#' )
262 return false;
264 ptr = strchr(line, ':');
265 if ( !ptr )
266 return false;
268 *name = line;
269 *ptr = 0;
270 ptr++;
271 ptr = skip_whitespace(ptr);
272 *value = ptr;
273 return true;
276 static void system_flush(void)
278 scrobbler_shutdown();
279 playlist_shutdown();
280 tree_flush();
281 call_storage_idle_notifys(true); /*doesnt work on usb and shutdown from ata thread */
284 static void system_restore(void)
286 tree_restore();
287 scrobbler_init();
290 static bool clean_shutdown(void (*callback)(void *), void *parameter)
292 #ifdef SIMULATOR
293 (void)callback;
294 (void)parameter;
295 bookmark_autobookmark(false);
296 call_storage_idle_notifys(true);
297 exit(0);
298 #else
299 long msg_id = -1;
300 int i;
302 scrobbler_poweroff();
304 #if CONFIG_CHARGING && !defined(HAVE_POWEROFF_WHILE_CHARGING)
305 if(!charger_inserted())
306 #endif
308 bool batt_safe = battery_level_safe();
309 int audio_stat = audio_status();
311 FOR_NB_SCREENS(i)
313 screens[i].clear_display();
314 screens[i].update();
317 if (batt_safe)
319 #ifdef HAVE_TAGCACHE
320 if (!tagcache_prepare_shutdown())
322 cancel_shutdown();
323 splash(HZ, ID2P(LANG_TAGCACHE_BUSY));
324 return false;
326 #endif
327 if (battery_level() > 10)
328 splash(0, str(LANG_SHUTTINGDOWN));
329 else
331 msg_id = LANG_WARNING_BATTERY_LOW;
332 splashf(0, "%s %s", str(LANG_WARNING_BATTERY_LOW),
333 str(LANG_SHUTTINGDOWN));
336 else
338 msg_id = LANG_WARNING_BATTERY_EMPTY;
339 splashf(0, "%s %s", str(LANG_WARNING_BATTERY_EMPTY),
340 str(LANG_SHUTTINGDOWN));
343 if (global_settings.fade_on_stop
344 && (audio_stat & AUDIO_STATUS_PLAY))
346 fade(false, false);
349 if (batt_safe) /* do not save on critical battery */
351 #if defined(HAVE_RECORDING) && CONFIG_CODEC == SWCODEC
352 if (audio_stat & AUDIO_STATUS_RECORD)
354 rec_command(RECORDING_CMD_STOP);
355 /* wait for stop to complete */
356 while (audio_status() & AUDIO_STATUS_RECORD)
357 sleep(1);
359 #endif
360 bookmark_autobookmark(false);
362 /* audio_stop_recording == audio_stop for HWCODEC */
363 audio_stop();
365 if (callback != NULL)
366 callback(parameter);
368 #if CONFIG_CODEC != SWCODEC
369 /* wait for audio_stop or audio_stop_recording to complete */
370 while (audio_status())
371 sleep(1);
372 #endif
374 #if defined(HAVE_RECORDING) && CONFIG_CODEC == SWCODEC
375 audio_close_recording();
376 #endif
378 if(global_settings.talk_menu)
380 bool enqueue = false;
381 if(msg_id != -1)
383 talk_id(msg_id, enqueue);
384 enqueue = true;
386 talk_id(LANG_SHUTTINGDOWN, enqueue);
387 #if CONFIG_CODEC == SWCODEC
388 voice_wait();
389 #endif
392 system_flush();
393 #ifdef HAVE_EEPROM_SETTINGS
394 if (firmware_settings.initialized)
396 firmware_settings.disk_clean = true;
397 firmware_settings.bl_version = 0;
398 eeprom_settings_store();
400 #endif
402 #ifdef HAVE_DIRCACHE
403 else
404 dircache_disable();
405 #endif
407 shutdown_hw();
409 #endif
410 return false;
413 bool list_stop_handler(void)
415 bool ret = false;
417 /* Stop the music if it is playing */
418 if(audio_status())
420 if (!global_settings.party_mode)
422 if (global_settings.fade_on_stop)
423 fade(false, false);
424 bookmark_autobookmark(true);
425 audio_stop();
426 ret = true; /* bookmarking can make a refresh necessary */
429 #if CONFIG_CHARGING
430 #if (CONFIG_KEYPAD == RECORDER_PAD) && !defined(HAVE_SW_POWEROFF)
431 else
433 if (charger_inserted())
434 charging_splash();
435 else
436 shutdown_screen(); /* won't return if shutdown actually happens */
438 ret = true; /* screen is dirty, caller needs to refresh */
440 #endif
441 #ifndef HAVE_POWEROFF_WHILE_CHARGING
443 static long last_off = 0;
445 if (TIME_BEFORE(current_tick, last_off + HZ/2))
447 if (charger_inserted())
449 charging_splash();
450 ret = true; /* screen is dirty, caller needs to refresh */
453 last_off = current_tick;
455 #endif
456 #endif /* CONFIG_CHARGING */
457 return ret;
460 #if CONFIG_CHARGING
461 static bool waiting_to_resume_play = false;
462 static long play_resume_tick;
464 static void car_adapter_mode_processing(bool inserted)
466 if (global_settings.car_adapter_mode)
468 if(inserted)
471 * Just got plugged in, delay & resume if we were playing
473 if (audio_status() & AUDIO_STATUS_PAUSE)
475 /* delay resume a bit while the engine is cranking */
476 play_resume_tick = current_tick + HZ*5;
477 waiting_to_resume_play = true;
480 else
483 * Just got unplugged, pause if playing
485 if ((audio_status() & AUDIO_STATUS_PLAY) &&
486 !(audio_status() & AUDIO_STATUS_PAUSE))
488 if (global_settings.fade_on_stop)
489 fade(false, false);
490 else
491 audio_pause();
493 waiting_to_resume_play = false;
498 static void car_adapter_tick(void)
500 if (waiting_to_resume_play)
502 if (TIME_AFTER(current_tick, play_resume_tick))
504 if (audio_status() & AUDIO_STATUS_PAUSE)
506 queue_broadcast(SYS_CAR_ADAPTER_RESUME, 0);
508 waiting_to_resume_play = false;
513 void car_adapter_mode_init(void)
515 tick_add_task(car_adapter_tick);
517 #endif
519 #ifdef HAVE_HEADPHONE_DETECTION
520 static void unplug_change(bool inserted)
522 static bool headphone_caused_pause = false;
524 if (global_settings.unplug_mode)
526 int audio_stat = audio_status();
527 if (inserted)
529 if ((audio_stat & AUDIO_STATUS_PLAY) &&
530 headphone_caused_pause &&
531 global_settings.unplug_mode > 1 )
532 audio_resume();
533 backlight_on();
534 headphone_caused_pause = false;
535 } else {
536 if ((audio_stat & AUDIO_STATUS_PLAY) &&
537 !(audio_stat & AUDIO_STATUS_PAUSE))
539 headphone_caused_pause = true;
540 audio_pause();
542 if (global_settings.unplug_rw)
544 if (audio_current_track()->elapsed >
545 (unsigned long)(global_settings.unplug_rw*1000))
546 audio_ff_rewind(audio_current_track()->elapsed -
547 (global_settings.unplug_rw*1000));
548 else
549 audio_ff_rewind(0);
555 #endif
557 long default_event_handler_ex(long event, void (*callback)(void *), void *parameter)
559 switch(event)
561 case SYS_BATTERY_UPDATE:
562 if(global_settings.talk_battery_level)
564 talk_ids(true, VOICE_PAUSE, VOICE_PAUSE,
565 LANG_BATTERY_TIME,
566 TALK_ID(battery_level(), UNIT_PERCENT),
567 VOICE_PAUSE);
568 talk_force_enqueue_next();
570 break;
571 case SYS_USB_CONNECTED:
572 if (callback != NULL)
573 callback(parameter);
574 #if (CONFIG_STORAGE & STORAGE_MMC)
575 if (!mmc_touched() ||
576 (mmc_remove_request() == SYS_HOTSWAP_EXTRACTED))
577 #endif
579 system_flush();
580 #ifdef BOOTFILE
581 #if !defined(USB_NONE) && !defined(USB_HANDLED_BY_OF)
582 check_bootfile(false); /* gets initial size */
583 #endif
584 #endif
585 gui_usb_screen_run();
586 #ifdef BOOTFILE
587 #if !defined(USB_NONE) && !defined(USB_HANDLED_BY_OF)
588 check_bootfile(true);
589 #endif
590 #endif
591 system_restore();
593 return SYS_USB_CONNECTED;
595 case SYS_POWEROFF:
596 if (!clean_shutdown(callback, parameter))
597 return SYS_POWEROFF;
598 break;
599 #if CONFIG_CHARGING
600 case SYS_CHARGER_CONNECTED:
601 car_adapter_mode_processing(true);
602 return SYS_CHARGER_CONNECTED;
604 case SYS_CHARGER_DISCONNECTED:
605 car_adapter_mode_processing(false);
606 /*reset rockbox battery runtime*/
607 global_status.runtime = 0;
608 return SYS_CHARGER_DISCONNECTED;
610 case SYS_CAR_ADAPTER_RESUME:
611 audio_resume();
612 return SYS_CAR_ADAPTER_RESUME;
613 #endif
614 #ifdef HAVE_HOTSWAP_STORAGE_AS_MAIN
615 case SYS_FS_CHANGED:
617 /* simple sanity: assume rockbox is on the first hotswappable
618 * driver, abort out if that one isn't inserted */
619 int i;
620 for (i = 0; i < NUM_DRIVES; i++)
622 if (storage_removable(i) && !storage_present(i))
623 return SYS_FS_CHANGED;
625 system_flush();
626 check_bootfile(true); /* state gotten in main.c:init() */
627 system_restore();
629 return SYS_FS_CHANGED;
630 #endif
631 #ifdef HAVE_HEADPHONE_DETECTION
632 case SYS_PHONE_PLUGGED:
633 unplug_change(true);
634 return SYS_PHONE_PLUGGED;
636 case SYS_PHONE_UNPLUGGED:
637 unplug_change(false);
638 return SYS_PHONE_UNPLUGGED;
639 #endif
640 #ifdef IPOD_ACCESSORY_PROTOCOL
641 case SYS_IAP_PERIODIC:
642 iap_periodic();
643 return SYS_IAP_PERIODIC;
644 case SYS_IAP_HANDLEPKT:
645 iap_handlepkt();
646 return SYS_IAP_HANDLEPKT;
647 #endif
649 return 0;
652 long default_event_handler(long event)
654 return default_event_handler_ex(event, NULL, NULL);
657 int show_logo( void )
659 #ifdef HAVE_LCD_BITMAP
660 char version[32];
661 int font_h, font_w;
663 snprintf(version, sizeof(version), "Ver. %s", appsversion);
665 lcd_clear_display();
666 #if defined(SANSA_CLIP) || defined(SANSA_CLIPV2) || defined(SANSA_CLIPPLUS)
667 /* display the logo in the blue area of the screen */
668 lcd_setfont(FONT_SYSFIXED);
669 lcd_getstringsize((unsigned char *)"A", &font_w, &font_h);
670 lcd_putsxy((LCD_WIDTH/2) - ((strlen(version)*font_w)/2),
671 0, (unsigned char *)version);
672 lcd_bitmap(rockboxlogo, 0, 16, BMPWIDTH_rockboxlogo, BMPHEIGHT_rockboxlogo);
673 #else
674 lcd_bitmap(rockboxlogo, 0, 10, BMPWIDTH_rockboxlogo, BMPHEIGHT_rockboxlogo);
675 lcd_setfont(FONT_SYSFIXED);
676 lcd_getstringsize((unsigned char *)"A", &font_w, &font_h);
677 lcd_putsxy((LCD_WIDTH/2) - ((strlen(version)*font_w)/2),
678 LCD_HEIGHT-font_h, (unsigned char *)version);
679 #endif
680 lcd_setfont(FONT_UI);
682 #else
683 char *rockbox = " ROCKbox!";
685 lcd_clear_display();
686 lcd_double_height(true);
687 lcd_puts(0, 0, rockbox);
688 lcd_puts_scroll(0, 1, appsversion);
689 #endif
690 lcd_update();
692 #ifdef HAVE_REMOTE_LCD
693 lcd_remote_clear_display();
694 lcd_remote_bitmap(remote_rockboxlogo, 0, 10, BMPWIDTH_remote_rockboxlogo,
695 BMPHEIGHT_remote_rockboxlogo);
696 lcd_remote_setfont(FONT_SYSFIXED);
697 lcd_remote_getstringsize((unsigned char *)"A", &font_w, &font_h);
698 lcd_remote_putsxy((LCD_REMOTE_WIDTH/2) - ((strlen(version)*font_w)/2),
699 LCD_REMOTE_HEIGHT-font_h, (unsigned char *)version);
700 lcd_remote_setfont(FONT_UI);
701 lcd_remote_update();
702 #endif
704 return 0;
707 #ifdef BOOTFILE
708 #if !defined(USB_NONE) && !defined(USB_HANDLED_BY_OF) || defined(HAVE_HOTSWAP_STORAGE_AS_MAIN)
710 memorize/compare details about the BOOTFILE
711 we don't use dircache because it may not be up to date after
712 USB disconnect (scanning in the background)
714 void check_bootfile(bool do_rolo)
716 static unsigned short wrtdate = 0;
717 static unsigned short wrttime = 0;
718 DIR* dir = NULL;
719 struct dirent* entry = NULL;
721 /* 1. open BOOTDIR and find the BOOTFILE dir entry */
722 dir = opendir(BOOTDIR);
724 if(!dir) return; /* do we want an error splash? */
726 /* loop all files in BOOTDIR */
727 while(0 != (entry = readdir(dir)))
729 if(!strcasecmp(entry->d_name, BOOTFILE))
731 /* found the bootfile */
732 if(wrtdate && do_rolo)
734 if((entry->wrtdate != wrtdate) ||
735 (entry->wrttime != wrttime))
737 static const char *lines[] = { ID2P(LANG_BOOT_CHANGED),
738 ID2P(LANG_REBOOT_NOW) };
739 static const struct text_message message={ lines, 2 };
740 button_clear_queue(); /* Empty the keyboard buffer */
741 if(gui_syncyesno_run(&message, NULL, NULL) == YESNO_YES)
742 rolo_load(BOOTDIR "/" BOOTFILE);
745 wrtdate = entry->wrtdate;
746 wrttime = entry->wrttime;
749 closedir(dir);
751 #endif
752 #endif
754 /* check range, set volume and save settings */
755 void setvol(void)
757 const int min_vol = sound_min(SOUND_VOLUME);
758 const int max_vol = sound_max(SOUND_VOLUME);
759 if (global_settings.volume < min_vol)
760 global_settings.volume = min_vol;
761 if (global_settings.volume > max_vol)
762 global_settings.volume = max_vol;
763 sound_set_volume(global_settings.volume);
764 global_status.last_volume_change = current_tick;
765 settings_save();
768 char* strrsplt(char* str, int c)
770 char* s = strrchr(str, c);
772 if (s != NULL)
774 *s++ = '\0';
776 else
778 s = str;
781 return s;
784 /* Test file existence, using dircache of possible */
785 bool file_exists(const char *file)
787 int fd;
789 if (!file || strlen(file) <= 0)
790 return false;
792 #ifdef HAVE_DIRCACHE
793 if (dircache_is_enabled())
794 return (dircache_get_entry_ptr(file) != NULL);
795 #endif
797 fd = open(file, O_RDONLY);
798 if (fd < 0)
799 return false;
800 close(fd);
801 return true;
804 bool dir_exists(const char *path)
806 DIR* d = opendir(path);
807 if (!d)
808 return false;
809 closedir(d);
810 return true;
814 * removes the extension of filename (if it doesn't start with a .)
815 * puts the result in buffer
817 char *strip_extension(char* buffer, int buffer_size, const char *filename)
819 char *dot = strrchr(filename, '.');
820 int len;
822 if (buffer_size <= 0)
824 return NULL;
827 buffer_size--; /* Make room for end nil */
829 if (dot != 0 && filename[0] != '.')
831 len = dot - filename;
832 len = MIN(len, buffer_size);
834 else
836 len = buffer_size;
839 strlcpy(buffer, filename, len + 1);
841 return buffer;
843 #endif /* !defined(__PCTOOL__) */
845 char* skip_whitespace(char* const str)
847 char *s = str;
849 while (isspace(*s))
850 s++;
852 return s;
855 /* Format time into buf.
857 * buf - buffer to format to.
858 * buf_size - size of buffer.
859 * t - time to format, in milliseconds.
861 void format_time(char* buf, int buf_size, long t)
863 if ( t < 3600000 )
865 snprintf(buf, buf_size, "%d:%02d",
866 (int) (t / 60000), (int) (t % 60000 / 1000));
868 else
870 snprintf(buf, buf_size, "%d:%02d:%02d",
871 (int) (t / 3600000), (int) (t % 3600000 / 60000),
872 (int) (t % 60000 / 1000));
877 /** Open a UTF-8 file and set file descriptor to first byte after BOM.
878 * If no BOM is present this behaves like open().
879 * If the file is opened for writing and O_TRUNC is set, write a BOM to
880 * the opened file and leave the file pointer set after the BOM.
882 #define BOM "\xef\xbb\xbf"
883 #define BOM_SIZE 3
885 int open_utf8(const char* pathname, int flags)
887 int fd;
888 unsigned char bom[BOM_SIZE];
890 fd = open(pathname, flags);
891 if(fd < 0)
892 return fd;
894 if(flags & (O_TRUNC | O_WRONLY))
896 write(fd, BOM, BOM_SIZE);
898 else
900 read(fd, bom, BOM_SIZE);
901 /* check for BOM */
902 if(memcmp(bom, BOM, BOM_SIZE))
903 lseek(fd, 0, SEEK_SET);
905 return fd;
909 #ifdef HAVE_LCD_COLOR
911 * Helper function to convert a string of 6 hex digits to a native colour
914 static int hex2dec(int c)
916 return (((c) >= '0' && ((c) <= '9')) ? (c) - '0' :
917 (toupper(c)) - 'A' + 10);
920 int hex_to_rgb(const char* hex, int* color)
922 int red, green, blue;
923 int i = 0;
925 while ((i < 6) && (isxdigit(hex[i])))
926 i++;
928 if (i < 6)
929 return -1;
931 red = (hex2dec(hex[0]) << 4) | hex2dec(hex[1]);
932 green = (hex2dec(hex[2]) << 4) | hex2dec(hex[3]);
933 blue = (hex2dec(hex[4]) << 4) | hex2dec(hex[5]);
935 *color = LCD_RGBPACK(red,green,blue);
937 return 0;
939 #endif /* HAVE_LCD_COLOR */
941 #ifdef HAVE_LCD_BITMAP
942 /* A simplified scanf - used (at time of writing) by wps parsing functions.
944 fmt - char array specifying the format of each list option. Valid values
945 are: d - int
946 s - string (sets pointer to string, without copying)
947 c - hex colour (RGB888 - e.g. ff00ff)
948 g - greyscale "colour" (0-3)
949 set_vals - if not NULL 1 is set in the bitplace if the item was read OK
950 0 if not read.
951 first item is LSB, (max 32 items! )
952 Stops parseing if an item is invalid unless the item == '-'
953 sep - list separator (e.g. ',' or '|')
954 str - string to parse, must be terminated by 0 or sep
955 ... - pointers to store the parsed values
957 return value - pointer to char after parsed data, 0 if there was an error.
961 /* '0'-'3' are ASCII 0x30 to 0x33 */
962 #define is0123(x) (((x) & 0xfc) == 0x30)
964 const char* parse_list(const char *fmt, uint32_t *set_vals,
965 const char sep, const char* str, ...)
967 va_list ap;
968 const char* p = str, *f = fmt;
969 const char** s;
970 int* d;
971 bool set, is_negative;
972 int i=0;
974 va_start(ap, str);
975 if (set_vals)
976 *set_vals = 0;
977 while (*fmt)
979 /* Check for separator, if we're not at the start */
980 if (f != fmt)
982 if (*p != sep)
983 goto err;
984 p++;
986 set = false;
987 switch (*fmt++)
989 case 's': /* string - return a pointer to it (not a copy) */
990 s = va_arg(ap, const char **);
992 *s = p;
993 while (*p && *p != sep)
994 p++;
995 set = (s[0][0]!='-') && (s[0][1]!=sep) ;
996 break;
998 case 'd': /* int */
999 is_negative = false;
1000 d = va_arg(ap, int*);
1001 if (*p == '-' && isdigit(*(p+1)))
1003 is_negative = true;
1004 p++;
1006 if (!isdigit(*p))
1008 if (!set_vals || *p != '-')
1009 goto err;
1010 while (*p && *p != sep)
1011 p++;
1013 else
1015 *d = *p++ - '0';
1016 while (isdigit(*p))
1017 *d = (*d * 10) + (*p++ - '0');
1018 set = true;
1019 if (is_negative)
1020 *d *= -1;
1023 break;
1025 #ifdef HAVE_LCD_COLOR
1026 case 'c': /* colour (rrggbb - e.g. f3c1a8) */
1027 d = va_arg(ap, int*);
1029 if (hex_to_rgb(p, d) < 0)
1031 if (!set_vals || *p != '-')
1032 goto err;
1033 while (*p && *p != sep)
1034 p++;
1036 else
1038 p += 6;
1039 set = true;
1042 break;
1043 #endif
1045 #if LCD_DEPTH == 2 || (defined(HAVE_REMOTE_LCD) && LCD_REMOTE_DEPTH == 2)
1046 case 'g': /* greyscale colour (0-3) */
1047 d = va_arg(ap, int*);
1049 if (is0123(*p))
1051 *d = *p++ - '0';
1052 set = true;
1054 else if (!set_vals || *p != '-')
1055 goto err;
1056 else
1058 while (*p && *p != sep)
1059 p++;
1062 break;
1063 #endif
1065 default: /* Unknown format type */
1066 goto err;
1067 break;
1069 if (set_vals && set)
1070 *set_vals |= BIT_N(i);
1071 i++;
1074 va_end(ap);
1075 return p;
1077 err:
1078 va_end(ap);
1079 return NULL;
1082 /* only used in USB HID and set_time screen */
1083 #if defined(USB_ENABLE_HID) || (CONFIG_RTC != 0)
1084 int clamp_value_wrap(int value, int max, int min)
1086 if (value > max)
1087 return min;
1088 if (value < min)
1089 return max;
1090 return value;
1092 #endif
1093 #endif