Merely correct a comment.
[kugel-rb.git] / apps / misc.c
blob22f21d2106091975bd3fdefa2b16a0ca28878de0
1 /***************************************************************************
2 * __________ __ ___.
3 * Open \______ \ ____ ____ | | _\_ |__ _______ ___
4 * Source | _// _ \_/ ___\| |/ /| __ \ / _ \ \/ /
5 * Jukebox | | ( <_> ) \___| < | \_\ ( <_> > < <
6 * Firmware |____|_ /\____/ \___ >__|_ \|___ /\____/__/\_ \
7 * \/ \/ \/ \/ \/
8 * $Id$
10 * Copyright (C) 2002 by Daniel Stenberg
12 * This program is free software; you can redistribute it and/or
13 * modify it under the terms of the GNU General Public License
14 * as published by the Free Software Foundation; either version 2
15 * of the License, or (at your option) any later version.
17 * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
18 * KIND, either express or implied.
20 ****************************************************************************/
21 #include <stdlib.h>
22 #include <ctype.h>
23 #include <string.h>
24 #include <errno.h>
25 #include "config.h"
26 #include "misc.h"
27 #include "lcd.h"
28 #include "file.h"
29 #ifdef __PCTOOL__
30 #include <stdarg.h>
31 #include <stdio.h>
32 #else
33 #include "sprintf.h"
34 #include "lang.h"
35 #include "dir.h"
36 #include "lcd-remote.h"
37 #include "system.h"
38 #include "timefuncs.h"
39 #include "screens.h"
40 #include "usb_screen.h"
41 #include "talk.h"
42 #include "audio.h"
43 #include "mp3_playback.h"
44 #include "settings.h"
45 #include "storage.h"
46 #include "ata_idle_notify.h"
47 #include "kernel.h"
48 #include "power.h"
49 #include "powermgmt.h"
50 #include "backlight.h"
51 #include "version.h"
52 #include "font.h"
53 #include "splash.h"
54 #include "tagcache.h"
55 #include "scrobbler.h"
56 #include "sound.h"
57 #include "playlist.h"
58 #include "yesno.h"
59 #include "viewport.h"
61 #ifdef IPOD_ACCESSORY_PROTOCOL
62 #include "iap.h"
63 #endif
65 #if (CONFIG_STORAGE & STORAGE_MMC)
66 #include "ata_mmc.h"
67 #endif
68 #include "tree.h"
69 #include "eeprom_settings.h"
70 #if defined(HAVE_RECORDING) && !defined(__PCTOOL__)
71 #include "recording.h"
72 #endif
73 #if defined(HAVE_LCD_BITMAP) && !defined(__PCTOOL__)
74 #include "bmp.h"
75 #include "icons.h"
76 #endif /* End HAVE_LCD_BITMAP */
77 #include "bookmark.h"
78 #include "wps.h"
79 #include "playback.h"
81 #ifdef BOOTFILE
82 #if !defined(USB_NONE) && !defined(USB_HANDLED_BY_OF) \
83 || defined(HAVE_HOTSWAP_STORAGE_AS_MAIN)
84 #include "rolo.h"
85 #endif
86 #endif
88 /* units used with output_dyn_value */
89 const unsigned char * const byte_units[] =
91 ID2P(LANG_BYTE),
92 ID2P(LANG_KILOBYTE),
93 ID2P(LANG_MEGABYTE),
94 ID2P(LANG_GIGABYTE)
97 const unsigned char * const * const kbyte_units = &byte_units[1];
99 /* Format a large-range value for output, using the appropriate unit so that
100 * the displayed value is in the range 1 <= display < 1000 (1024 for "binary"
101 * units) if possible, and 3 significant digits are shown. If a buffer is
102 * given, the result is snprintf()'d into that buffer, otherwise the result is
103 * voiced.*/
104 char *output_dyn_value(char *buf, int buf_size, int value,
105 const unsigned char * const *units, bool bin_scale)
107 int scale = bin_scale ? 1024 : 1000;
108 int fraction = 0;
109 int unit_no = 0;
110 char tbuf[5];
112 while (value >= scale)
114 fraction = value % scale;
115 value /= scale;
116 unit_no++;
118 if (bin_scale)
119 fraction = fraction * 1000 / 1024;
121 if (value >= 100 || !unit_no)
122 tbuf[0] = '\0';
123 else if (value >= 10)
124 snprintf(tbuf, sizeof(tbuf), "%01d", fraction / 100);
125 else
126 snprintf(tbuf, sizeof(tbuf), "%02d", fraction / 10);
128 if (buf)
130 if (strlen(tbuf))
131 snprintf(buf, buf_size, "%d%s%s%s", value, str(LANG_POINT),
132 tbuf, P2STR(units[unit_no]));
133 else
134 snprintf(buf, buf_size, "%d%s", value, P2STR(units[unit_no]));
136 else
138 talk_fractional(tbuf, value, P2ID(units[unit_no]));
140 return buf;
143 /* Ask the user if they really want to erase the current dynamic playlist
144 * returns true if the playlist should be replaced */
145 bool warn_on_pl_erase(void)
147 if (global_settings.warnon_erase_dynplaylist &&
148 !global_settings.party_mode &&
149 playlist_modified(NULL))
151 static const char *lines[] =
152 {ID2P(LANG_WARN_ERASEDYNPLAYLIST_PROMPT)};
153 static const struct text_message message={lines, 1};
155 return (gui_syncyesno_run(&message, NULL, NULL) == YESNO_YES);
157 else
158 return true;
162 /* Performance optimized version of the read_line() (see below) function. */
163 int fast_readline(int fd, char *buf, int buf_size, void *parameters,
164 int (*callback)(int n, const char *buf, void *parameters))
166 char *p, *next;
167 int rc, pos = 0;
168 int count = 0;
170 while ( 1 )
172 next = NULL;
174 rc = read(fd, &buf[pos], buf_size - pos - 1);
175 if (rc >= 0)
176 buf[pos+rc] = '\0';
178 if ( (p = strchr(buf, '\r')) != NULL)
180 *p = '\0';
181 next = ++p;
183 else
184 p = buf;
186 if ( (p = strchr(p, '\n')) != NULL)
188 *p = '\0';
189 next = ++p;
192 rc = callback(count, buf, parameters);
193 if (rc < 0)
194 return rc;
196 count++;
197 if (next)
199 pos = buf_size - ((long)next - (long)buf) - 1;
200 memmove(buf, next, pos);
202 else
203 break ;
206 return 0;
209 /* parse a line from a configuration file. the line format is:
211 name: value
213 Any whitespace before setting name or value (after ':') is ignored.
214 A # as first non-whitespace character discards the whole line.
215 Function sets pointers to null-terminated setting name and value.
216 Returns false if no valid config entry was found.
219 bool settings_parseline(char* line, char** name, char** value)
221 char* ptr;
223 line = skip_whitespace(line);
225 if ( *line == '#' )
226 return false;
228 ptr = strchr(line, ':');
229 if ( !ptr )
230 return false;
232 *name = line;
233 *ptr = 0;
234 ptr++;
235 ptr = skip_whitespace(ptr);
236 *value = ptr;
237 return true;
240 static void system_flush(void)
242 scrobbler_shutdown();
243 playlist_shutdown();
244 tree_flush();
245 call_storage_idle_notifys(true); /*doesnt work on usb and shutdown from ata thread */
248 static void system_restore(void)
250 tree_restore();
251 scrobbler_init();
254 static bool clean_shutdown(void (*callback)(void *), void *parameter)
256 #ifdef SIMULATOR
257 (void)callback;
258 (void)parameter;
259 bookmark_autobookmark(false);
260 call_storage_idle_notifys(true);
261 exit(0);
262 #else
263 long msg_id = -1;
264 int i;
266 scrobbler_poweroff();
268 #if CONFIG_CHARGING && !defined(HAVE_POWEROFF_WHILE_CHARGING)
269 if(!charger_inserted())
270 #endif
272 bool batt_safe = battery_level_safe();
273 int audio_stat = audio_status();
275 FOR_NB_SCREENS(i)
277 screens[i].clear_display();
278 screens[i].update();
281 if (batt_safe)
283 #ifdef HAVE_TAGCACHE
284 if (!tagcache_prepare_shutdown())
286 cancel_shutdown();
287 splash(HZ, ID2P(LANG_TAGCACHE_BUSY));
288 return false;
290 #endif
291 if (battery_level() > 10)
292 splash(0, str(LANG_SHUTTINGDOWN));
293 else
295 msg_id = LANG_WARNING_BATTERY_LOW;
296 splashf(0, "%s %s", str(LANG_WARNING_BATTERY_LOW),
297 str(LANG_SHUTTINGDOWN));
300 else
302 msg_id = LANG_WARNING_BATTERY_EMPTY;
303 splashf(0, "%s %s", str(LANG_WARNING_BATTERY_EMPTY),
304 str(LANG_SHUTTINGDOWN));
307 if (global_settings.fade_on_stop
308 && (audio_stat & AUDIO_STATUS_PLAY))
310 fade(false, false);
313 if (batt_safe) /* do not save on critical battery */
315 #if defined(HAVE_RECORDING) && CONFIG_CODEC == SWCODEC
316 if (audio_stat & AUDIO_STATUS_RECORD)
318 rec_command(RECORDING_CMD_STOP);
319 /* wait for stop to complete */
320 while (audio_status() & AUDIO_STATUS_RECORD)
321 sleep(1);
323 #endif
324 bookmark_autobookmark(false);
326 /* audio_stop_recording == audio_stop for HWCODEC */
327 audio_stop();
329 if (callback != NULL)
330 callback(parameter);
332 #if CONFIG_CODEC != SWCODEC
333 /* wait for audio_stop or audio_stop_recording to complete */
334 while (audio_status())
335 sleep(1);
336 #endif
338 #if defined(HAVE_RECORDING) && CONFIG_CODEC == SWCODEC
339 audio_close_recording();
340 #endif
342 if(global_settings.talk_menu)
344 bool enqueue = false;
345 if(msg_id != -1)
347 talk_id(msg_id, enqueue);
348 enqueue = true;
350 talk_id(LANG_SHUTTINGDOWN, enqueue);
351 #if CONFIG_CODEC == SWCODEC
352 voice_wait();
353 #endif
356 system_flush();
357 #ifdef HAVE_EEPROM_SETTINGS
358 if (firmware_settings.initialized)
360 firmware_settings.disk_clean = true;
361 firmware_settings.bl_version = 0;
362 eeprom_settings_store();
364 #endif
366 #ifdef HAVE_DIRCACHE
367 else
368 dircache_disable();
369 #endif
371 shutdown_hw();
373 #endif
374 return false;
377 bool list_stop_handler(void)
379 bool ret = false;
381 /* Stop the music if it is playing */
382 if(audio_status())
384 if (!global_settings.party_mode)
386 if (global_settings.fade_on_stop)
387 fade(false, false);
388 bookmark_autobookmark(true);
389 audio_stop();
390 ret = true; /* bookmarking can make a refresh necessary */
393 #if CONFIG_CHARGING
394 #if (CONFIG_KEYPAD == RECORDER_PAD) && !defined(HAVE_SW_POWEROFF)
395 else
397 if (charger_inserted())
398 charging_splash();
399 else
400 shutdown_screen(); /* won't return if shutdown actually happens */
402 ret = true; /* screen is dirty, caller needs to refresh */
404 #endif
405 #ifndef HAVE_POWEROFF_WHILE_CHARGING
407 static long last_off = 0;
409 if (TIME_BEFORE(current_tick, last_off + HZ/2))
411 if (charger_inserted())
413 charging_splash();
414 ret = true; /* screen is dirty, caller needs to refresh */
417 last_off = current_tick;
419 #endif
420 #endif /* CONFIG_CHARGING */
421 return ret;
424 #if CONFIG_CHARGING
425 static bool waiting_to_resume_play = false;
426 static long play_resume_tick;
428 static void car_adapter_mode_processing(bool inserted)
430 if (global_settings.car_adapter_mode)
432 if(inserted)
435 * Just got plugged in, delay & resume if we were playing
437 if (audio_status() & AUDIO_STATUS_PAUSE)
439 /* delay resume a bit while the engine is cranking */
440 play_resume_tick = current_tick + HZ*5;
441 waiting_to_resume_play = true;
444 else
447 * Just got unplugged, pause if playing
449 if ((audio_status() & AUDIO_STATUS_PLAY) &&
450 !(audio_status() & AUDIO_STATUS_PAUSE))
452 if (global_settings.fade_on_stop)
453 fade(false, false);
454 else
455 audio_pause();
457 waiting_to_resume_play = false;
462 static void car_adapter_tick(void)
464 if (waiting_to_resume_play)
466 if (TIME_AFTER(current_tick, play_resume_tick))
468 if (audio_status() & AUDIO_STATUS_PAUSE)
470 queue_broadcast(SYS_CAR_ADAPTER_RESUME, 0);
472 waiting_to_resume_play = false;
477 void car_adapter_mode_init(void)
479 tick_add_task(car_adapter_tick);
481 #endif
483 #ifdef HAVE_HEADPHONE_DETECTION
484 static void unplug_change(bool inserted)
486 static bool headphone_caused_pause = false;
488 if (global_settings.unplug_mode)
490 int audio_stat = audio_status();
491 if (inserted)
493 if ((audio_stat & AUDIO_STATUS_PLAY) &&
494 headphone_caused_pause &&
495 global_settings.unplug_mode > 1 )
496 audio_resume();
497 backlight_on();
498 headphone_caused_pause = false;
499 } else {
500 if ((audio_stat & AUDIO_STATUS_PLAY) &&
501 !(audio_stat & AUDIO_STATUS_PAUSE))
503 headphone_caused_pause = true;
504 audio_pause();
506 if (global_settings.unplug_rw)
508 if (audio_current_track()->elapsed >
509 (unsigned long)(global_settings.unplug_rw*1000))
510 audio_ff_rewind(audio_current_track()->elapsed -
511 (global_settings.unplug_rw*1000));
512 else
513 audio_ff_rewind(0);
519 #endif
521 long default_event_handler_ex(long event, void (*callback)(void *), void *parameter)
523 switch(event)
525 case SYS_BATTERY_UPDATE:
526 if(global_settings.talk_battery_level)
528 talk_ids(true, VOICE_PAUSE, VOICE_PAUSE,
529 LANG_BATTERY_TIME,
530 TALK_ID(battery_level(), UNIT_PERCENT),
531 VOICE_PAUSE);
532 talk_force_enqueue_next();
534 break;
535 case SYS_USB_CONNECTED:
536 if (callback != NULL)
537 callback(parameter);
538 #if (CONFIG_STORAGE & STORAGE_MMC)
539 if (!mmc_touched() ||
540 (mmc_remove_request() == SYS_HOTSWAP_EXTRACTED))
541 #endif
543 system_flush();
544 #ifdef BOOTFILE
545 #if !defined(USB_NONE) && !defined(USB_HANDLED_BY_OF)
546 check_bootfile(false); /* gets initial size */
547 #endif
548 #endif
549 gui_usb_screen_run();
550 #ifdef BOOTFILE
551 #if !defined(USB_NONE) && !defined(USB_HANDLED_BY_OF)
552 check_bootfile(true);
553 #endif
554 #endif
555 system_restore();
557 return SYS_USB_CONNECTED;
559 case SYS_POWEROFF:
560 if (!clean_shutdown(callback, parameter))
561 return SYS_POWEROFF;
562 break;
563 #if CONFIG_CHARGING
564 case SYS_CHARGER_CONNECTED:
565 car_adapter_mode_processing(true);
566 return SYS_CHARGER_CONNECTED;
568 case SYS_CHARGER_DISCONNECTED:
569 car_adapter_mode_processing(false);
570 /*reset rockbox battery runtime*/
571 global_status.runtime = 0;
572 return SYS_CHARGER_DISCONNECTED;
574 case SYS_CAR_ADAPTER_RESUME:
575 audio_resume();
576 return SYS_CAR_ADAPTER_RESUME;
577 #endif
578 #ifdef HAVE_HOTSWAP_STORAGE_AS_MAIN
579 case SYS_FS_CHANGED:
581 /* simple sanity: assume rockbox is on the first hotswappable
582 * driver, abort out if that one isn't inserted */
583 int i;
584 for (i = 0; i < NUM_DRIVES; i++)
586 if (storage_removable(i) && !storage_present(i))
587 return SYS_FS_CHANGED;
589 system_flush();
590 check_bootfile(true); /* state gotten in main.c:init() */
591 system_restore();
593 return SYS_FS_CHANGED;
594 #endif
595 #ifdef HAVE_HEADPHONE_DETECTION
596 case SYS_PHONE_PLUGGED:
597 unplug_change(true);
598 return SYS_PHONE_PLUGGED;
600 case SYS_PHONE_UNPLUGGED:
601 unplug_change(false);
602 return SYS_PHONE_UNPLUGGED;
603 #endif
604 #ifdef IPOD_ACCESSORY_PROTOCOL
605 case SYS_IAP_PERIODIC:
606 iap_periodic();
607 return SYS_IAP_PERIODIC;
608 case SYS_IAP_HANDLEPKT:
609 iap_handlepkt();
610 return SYS_IAP_HANDLEPKT;
611 #endif
613 return 0;
616 long default_event_handler(long event)
618 return default_event_handler_ex(event, NULL, NULL);
621 int show_logo( void )
623 #ifdef HAVE_LCD_BITMAP
624 char version[32];
625 int font_h, font_w;
627 snprintf(version, sizeof(version), "Ver. %s", appsversion);
629 lcd_clear_display();
630 #if defined(SANSA_CLIP) || defined(SANSA_CLIPV2) || defined(SANSA_CLIPPLUS)
631 /* display the logo in the blue area of the screen */
632 lcd_setfont(FONT_SYSFIXED);
633 lcd_getstringsize((unsigned char *)"A", &font_w, &font_h);
634 lcd_putsxy((LCD_WIDTH/2) - ((strlen(version)*font_w)/2),
635 0, (unsigned char *)version);
636 lcd_bitmap(rockboxlogo, 0, 16, BMPWIDTH_rockboxlogo, BMPHEIGHT_rockboxlogo);
637 #else
638 lcd_bitmap(rockboxlogo, 0, 10, BMPWIDTH_rockboxlogo, BMPHEIGHT_rockboxlogo);
639 lcd_setfont(FONT_SYSFIXED);
640 lcd_getstringsize((unsigned char *)"A", &font_w, &font_h);
641 lcd_putsxy((LCD_WIDTH/2) - ((strlen(version)*font_w)/2),
642 LCD_HEIGHT-font_h, (unsigned char *)version);
643 #endif
644 lcd_setfont(FONT_UI);
646 #else
647 char *rockbox = " ROCKbox!";
649 lcd_clear_display();
650 lcd_double_height(true);
651 lcd_puts(0, 0, rockbox);
652 lcd_puts_scroll(0, 1, appsversion);
653 #endif
654 lcd_update();
656 #ifdef HAVE_REMOTE_LCD
657 lcd_remote_clear_display();
658 lcd_remote_bitmap(remote_rockboxlogo, 0, 10, BMPWIDTH_remote_rockboxlogo,
659 BMPHEIGHT_remote_rockboxlogo);
660 lcd_remote_setfont(FONT_SYSFIXED);
661 lcd_remote_getstringsize((unsigned char *)"A", &font_w, &font_h);
662 lcd_remote_putsxy((LCD_REMOTE_WIDTH/2) - ((strlen(version)*font_w)/2),
663 LCD_REMOTE_HEIGHT-font_h, (unsigned char *)version);
664 lcd_remote_setfont(FONT_UI);
665 lcd_remote_update();
666 #endif
668 return 0;
671 #ifdef BOOTFILE
672 #if !defined(USB_NONE) && !defined(USB_HANDLED_BY_OF) || defined(HAVE_HOTSWAP_STORAGE_AS_MAIN)
674 memorize/compare details about the BOOTFILE
675 we don't use dircache because it may not be up to date after
676 USB disconnect (scanning in the background)
678 void check_bootfile(bool do_rolo)
680 static unsigned short wrtdate = 0;
681 static unsigned short wrttime = 0;
682 DIR* dir = NULL;
683 struct dirent* entry = NULL;
685 /* 1. open BOOTDIR and find the BOOTFILE dir entry */
686 dir = opendir(BOOTDIR);
688 if(!dir) return; /* do we want an error splash? */
690 /* loop all files in BOOTDIR */
691 while(0 != (entry = readdir(dir)))
693 if(!strcasecmp(entry->d_name, BOOTFILE))
695 /* found the bootfile */
696 if(wrtdate && do_rolo)
698 if((entry->wrtdate != wrtdate) ||
699 (entry->wrttime != wrttime))
701 static const char *lines[] = { ID2P(LANG_BOOT_CHANGED),
702 ID2P(LANG_REBOOT_NOW) };
703 static const struct text_message message={ lines, 2 };
704 button_clear_queue(); /* Empty the keyboard buffer */
705 if(gui_syncyesno_run(&message, NULL, NULL) == YESNO_YES)
706 rolo_load(BOOTDIR "/" BOOTFILE);
709 wrtdate = entry->wrtdate;
710 wrttime = entry->wrttime;
713 closedir(dir);
715 #endif
716 #endif
718 /* check range, set volume and save settings */
719 void setvol(void)
721 const int min_vol = sound_min(SOUND_VOLUME);
722 const int max_vol = sound_max(SOUND_VOLUME);
723 if (global_settings.volume < min_vol)
724 global_settings.volume = min_vol;
725 if (global_settings.volume > max_vol)
726 global_settings.volume = max_vol;
727 sound_set_volume(global_settings.volume);
728 global_status.last_volume_change = current_tick;
729 settings_save();
732 char* strrsplt(char* str, int c)
734 char* s = strrchr(str, c);
736 if (s != NULL)
738 *s++ = '\0';
740 else
742 s = str;
745 return s;
748 /* Test file existence, using dircache of possible */
749 bool file_exists(const char *file)
751 int fd;
753 if (!file || strlen(file) <= 0)
754 return false;
756 #ifdef HAVE_DIRCACHE
757 if (dircache_is_enabled())
758 return (dircache_get_entry_ptr(file) != NULL);
759 #endif
761 fd = open(file, O_RDONLY);
762 if (fd < 0)
763 return false;
764 close(fd);
765 return true;
768 bool dir_exists(const char *path)
770 DIR* d = opendir(path);
771 if (!d)
772 return false;
773 closedir(d);
774 return true;
778 * removes the extension of filename (if it doesn't start with a .)
779 * puts the result in buffer
781 char *strip_extension(char* buffer, int buffer_size, const char *filename)
783 char *dot = strrchr(filename, '.');
784 int len;
786 if (buffer_size <= 0)
788 return NULL;
791 buffer_size--; /* Make room for end nil */
793 if (dot != 0 && filename[0] != '.')
795 len = dot - filename;
796 len = MIN(len, buffer_size);
798 else
800 len = buffer_size;
803 strlcpy(buffer, filename, len + 1);
805 return buffer;
807 #endif /* !defined(__PCTOOL__) */
809 /* Read (up to) a line of text from fd into buffer and return number of bytes
810 * read (which may be larger than the number of bytes stored in buffer). If
811 * an error occurs, -1 is returned (and buffer contains whatever could be
812 * read). A line is terminated by a LF char. Neither LF nor CR chars are
813 * stored in buffer.
815 int read_line(int fd, char* buffer, int buffer_size)
817 int count = 0;
818 int num_read = 0;
820 errno = 0;
822 while (count < buffer_size)
824 unsigned char c;
826 if (1 != read(fd, &c, 1))
827 break;
829 num_read++;
831 if ( c == '\n' )
832 break;
834 if ( c == '\r' )
835 continue;
837 buffer[count++] = c;
840 buffer[MIN(count, buffer_size - 1)] = 0;
842 return errno ? -1 : num_read;
846 char* skip_whitespace(char* const str)
848 char *s = str;
850 while (isspace(*s))
851 s++;
853 return s;
856 /* Format time into buf.
858 * buf - buffer to format to.
859 * buf_size - size of buffer.
860 * t - time to format, in milliseconds.
862 void format_time(char* buf, int buf_size, long t)
864 if ( t < 3600000 )
866 snprintf(buf, buf_size, "%d:%02d",
867 (int) (t / 60000), (int) (t % 60000 / 1000));
869 else
871 snprintf(buf, buf_size, "%d:%02d:%02d",
872 (int) (t / 3600000), (int) (t % 3600000 / 60000),
873 (int) (t % 60000 / 1000));
878 /** Open a UTF-8 file and set file descriptor to first byte after BOM.
879 * If no BOM is present this behaves like open().
880 * If the file is opened for writing and O_TRUNC is set, write a BOM to
881 * the opened file and leave the file pointer set after the BOM.
883 #define BOM "\xef\xbb\xbf"
884 #define BOM_SIZE 3
886 int open_utf8(const char* pathname, int flags)
888 int fd;
889 unsigned char bom[BOM_SIZE];
891 fd = open(pathname, flags);
892 if(fd < 0)
893 return fd;
895 if(flags & (O_TRUNC | O_WRONLY))
897 write(fd, BOM, BOM_SIZE);
899 else
901 read(fd, bom, BOM_SIZE);
902 /* check for BOM */
903 if(memcmp(bom, BOM, BOM_SIZE))
904 lseek(fd, 0, SEEK_SET);
906 return fd;
910 #ifdef HAVE_LCD_COLOR
912 * Helper function to convert a string of 6 hex digits to a native colour
915 static int hex2dec(int c)
917 return (((c) >= '0' && ((c) <= '9')) ? (c) - '0' :
918 (toupper(c)) - 'A' + 10);
921 int hex_to_rgb(const char* hex, int* color)
923 int red, green, blue;
924 int i = 0;
926 while ((i < 6) && (isxdigit(hex[i])))
927 i++;
929 if (i < 6)
930 return -1;
932 red = (hex2dec(hex[0]) << 4) | hex2dec(hex[1]);
933 green = (hex2dec(hex[2]) << 4) | hex2dec(hex[3]);
934 blue = (hex2dec(hex[4]) << 4) | hex2dec(hex[5]);
936 *color = LCD_RGBPACK(red,green,blue);
938 return 0;
940 #endif /* HAVE_LCD_COLOR */
942 #ifdef HAVE_LCD_BITMAP
943 /* A simplified scanf - used (at time of writing) by wps parsing functions.
945 fmt - char array specifying the format of each list option. Valid values
946 are: d - int
947 s - string (sets pointer to string, without copying)
948 c - hex colour (RGB888 - e.g. ff00ff)
949 g - greyscale "colour" (0-3)
950 set_vals - if not NULL 1 is set in the bitplace if the item was read OK
951 0 if not read.
952 first item is LSB, (max 32 items! )
953 Stops parseing if an item is invalid unless the item == '-'
954 sep - list separator (e.g. ',' or '|')
955 str - string to parse, must be terminated by 0 or sep
956 ... - pointers to store the parsed values
958 return value - pointer to char after parsed data, 0 if there was an error.
962 /* '0'-'3' are ASCII 0x30 to 0x33 */
963 #define is0123(x) (((x) & 0xfc) == 0x30)
965 const char* parse_list(const char *fmt, uint32_t *set_vals,
966 const char sep, const char* str, ...)
968 va_list ap;
969 const char* p = str, *f = fmt;
970 const char** s;
971 int* d;
972 bool set, is_negative;
973 int i=0;
975 va_start(ap, str);
976 if (set_vals)
977 *set_vals = 0;
978 while (*fmt)
980 /* Check for separator, if we're not at the start */
981 if (f != fmt)
983 if (*p != sep)
984 goto err;
985 p++;
987 set = false;
988 switch (*fmt++)
990 case 's': /* string - return a pointer to it (not a copy) */
991 s = va_arg(ap, const char **);
993 *s = p;
994 while (*p && *p != sep)
995 p++;
996 set = (s[0][0]!='-') && (s[0][1]!=sep) ;
997 break;
999 case 'd': /* int */
1000 is_negative = false;
1001 d = va_arg(ap, int*);
1002 if (*p == '-' && isdigit(*(p+1)))
1004 is_negative = true;
1005 p++;
1007 if (!isdigit(*p))
1009 if (!set_vals || *p != '-')
1010 goto err;
1011 while (*p && *p != sep)
1012 p++;
1014 else
1016 *d = *p++ - '0';
1017 while (isdigit(*p))
1018 *d = (*d * 10) + (*p++ - '0');
1019 set = true;
1020 if (is_negative)
1021 *d *= -1;
1024 break;
1026 #ifdef HAVE_LCD_COLOR
1027 case 'c': /* colour (rrggbb - e.g. f3c1a8) */
1028 d = va_arg(ap, int*);
1030 if (hex_to_rgb(p, d) < 0)
1032 if (!set_vals || *p != '-')
1033 goto err;
1034 while (*p && *p != sep)
1035 p++;
1037 else
1039 p += 6;
1040 set = true;
1043 break;
1044 #endif
1046 #if LCD_DEPTH == 2 || (defined(HAVE_REMOTE_LCD) && LCD_REMOTE_DEPTH == 2)
1047 case 'g': /* greyscale colour (0-3) */
1048 d = va_arg(ap, int*);
1050 if (is0123(*p))
1052 *d = *p++ - '0';
1053 set = true;
1055 else if (!set_vals || *p != '-')
1056 goto err;
1057 else
1059 while (*p && *p != sep)
1060 p++;
1063 break;
1064 #endif
1066 default: /* Unknown format type */
1067 goto err;
1068 break;
1070 if (set_vals && set)
1071 *set_vals |= BIT_N(i);
1072 i++;
1075 va_end(ap);
1076 return p;
1078 err:
1079 va_end(ap);
1080 return NULL;
1083 /* only used in USB HID and set_time screen */
1084 #if defined(USB_ENABLE_HID) || (CONFIG_RTC != 0)
1085 int clamp_value_wrap(int value, int max, int min)
1087 if (value > max)
1088 return min;
1089 if (value < min)
1090 return max;
1091 return value;
1093 #endif
1094 #endif