Add a "early_usb" argument to gui_usb_screen_run(), and don't do skin unloading/reloa...
[kugel-rb.git] / apps / misc.c
blob5f6df46485c119c60659cd5a366331e8e555e2b0
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 #include "filefuncs.h"
32 #ifndef __PCTOOL__
33 #include "lang.h"
34 #include "dir.h"
35 #include "lcd-remote.h"
36 #include "system.h"
37 #include "timefuncs.h"
38 #include "screens.h"
39 #include "usb_screen.h"
40 #include "talk.h"
41 #include "audio.h"
42 #include "mp3_playback.h"
43 #include "settings.h"
44 #include "storage.h"
45 #include "ata_idle_notify.h"
46 #include "kernel.h"
47 #include "power.h"
48 #include "powermgmt.h"
49 #include "backlight.h"
50 #include "version.h"
51 #include "font.h"
52 #include "splash.h"
53 #include "tagcache.h"
54 #include "scrobbler.h"
55 #include "sound.h"
56 #include "playlist.h"
57 #include "yesno.h"
58 #include "viewport.h"
60 #ifdef IPOD_ACCESSORY_PROTOCOL
61 #include "iap.h"
62 #endif
64 #if (CONFIG_STORAGE & STORAGE_MMC)
65 #include "ata_mmc.h"
66 #endif
67 #include "tree.h"
68 #include "eeprom_settings.h"
69 #if defined(HAVE_RECORDING) && !defined(__PCTOOL__)
70 #include "recording.h"
71 #endif
72 #if defined(HAVE_LCD_BITMAP) && !defined(__PCTOOL__)
73 #include "bmp.h"
74 #include "icons.h"
75 #endif /* End HAVE_LCD_BITMAP */
76 #include "bookmark.h"
77 #include "wps.h"
78 #include "playback.h"
80 #ifdef BOOTFILE
81 #if !defined(USB_NONE) && !defined(USB_HANDLED_BY_OF) \
82 || defined(HAVE_HOTSWAP_STORAGE_AS_MAIN)
83 #include "rolo.h"
84 #endif
85 #endif
87 /* units used with output_dyn_value */
88 const unsigned char * const byte_units[] =
90 ID2P(LANG_BYTE),
91 ID2P(LANG_KILOBYTE),
92 ID2P(LANG_MEGABYTE),
93 ID2P(LANG_GIGABYTE)
96 const unsigned char * const * const kbyte_units = &byte_units[1];
98 /* Format a large-range value for output, using the appropriate unit so that
99 * the displayed value is in the range 1 <= display < 1000 (1024 for "binary"
100 * units) if possible, and 3 significant digits are shown. If a buffer is
101 * given, the result is snprintf()'d into that buffer, otherwise the result is
102 * voiced.*/
103 char *output_dyn_value(char *buf, int buf_size, int value,
104 const unsigned char * const *units, bool bin_scale)
106 int scale = bin_scale ? 1024 : 1000;
107 int fraction = 0;
108 int unit_no = 0;
109 char tbuf[5];
111 while (value >= scale)
113 fraction = value % scale;
114 value /= scale;
115 unit_no++;
117 if (bin_scale)
118 fraction = fraction * 1000 / 1024;
120 if (value >= 100 || !unit_no)
121 tbuf[0] = '\0';
122 else if (value >= 10)
123 snprintf(tbuf, sizeof(tbuf), "%01d", fraction / 100);
124 else
125 snprintf(tbuf, sizeof(tbuf), "%02d", fraction / 10);
127 if (buf)
129 if (*tbuf)
130 snprintf(buf, buf_size, "%d%s%s%s", value, str(LANG_POINT),
131 tbuf, P2STR(units[unit_no]));
132 else
133 snprintf(buf, buf_size, "%d%s", value, P2STR(units[unit_no]));
135 else
137 talk_fractional(tbuf, value, P2ID(units[unit_no]));
139 return buf;
142 /* Ask the user if they really want to erase the current dynamic playlist
143 * returns true if the playlist should be replaced */
144 bool warn_on_pl_erase(void)
146 if (global_settings.warnon_erase_dynplaylist &&
147 !global_settings.party_mode &&
148 playlist_modified(NULL))
150 static const char *lines[] =
151 {ID2P(LANG_WARN_ERASEDYNPLAYLIST_PROMPT)};
152 static const struct text_message message={lines, 1};
154 return (gui_syncyesno_run(&message, NULL, NULL) == YESNO_YES);
156 else
157 return true;
161 /* Performance optimized version of the read_line() (see below) function. */
162 int fast_readline(int fd, char *buf, int buf_size, void *parameters,
163 int (*callback)(int n, const char *buf, void *parameters))
165 char *p, *next;
166 int rc, pos = 0;
167 int count = 0;
169 while ( 1 )
171 next = NULL;
173 rc = read(fd, &buf[pos], buf_size - pos - 1);
174 if (rc >= 0)
175 buf[pos+rc] = '\0';
177 if ( (p = strchr(buf, '\r')) != NULL)
179 *p = '\0';
180 next = ++p;
182 else
183 p = buf;
185 if ( (p = strchr(p, '\n')) != NULL)
187 *p = '\0';
188 next = ++p;
191 rc = callback(count, buf, parameters);
192 if (rc < 0)
193 return rc;
195 count++;
196 if (next)
198 pos = buf_size - ((long)next - (long)buf) - 1;
199 memmove(buf, next, pos);
201 else
202 break ;
205 return 0;
208 /* parse a line from a configuration file. the line format is:
210 name: value
212 Any whitespace before setting name or value (after ':') is ignored.
213 A # as first non-whitespace character discards the whole line.
214 Function sets pointers to null-terminated setting name and value.
215 Returns false if no valid config entry was found.
218 bool settings_parseline(char* line, char** name, char** value)
220 char* ptr;
222 line = skip_whitespace(line);
224 if ( *line == '#' )
225 return false;
227 ptr = strchr(line, ':');
228 if ( !ptr )
229 return false;
231 *name = line;
232 *ptr = 0;
233 ptr++;
234 ptr = skip_whitespace(ptr);
235 *value = ptr;
236 return true;
239 static void system_flush(void)
241 scrobbler_shutdown();
242 playlist_shutdown();
243 tree_flush();
244 call_storage_idle_notifys(true); /*doesnt work on usb and shutdown from ata thread */
247 static void system_restore(void)
249 tree_restore();
250 scrobbler_init();
253 static bool clean_shutdown(void (*callback)(void *), void *parameter)
255 #if (CONFIG_PLATFORM & PLATFORM_HOSTED)
256 (void)callback;
257 (void)parameter;
258 bookmark_autobookmark(false);
259 call_storage_idle_notifys(true);
260 #else
261 long msg_id = -1;
262 int i;
264 scrobbler_poweroff();
266 #if CONFIG_CHARGING && !defined(HAVE_POWEROFF_WHILE_CHARGING)
267 if(!charger_inserted())
268 #endif
270 bool batt_safe = battery_level_safe();
271 int audio_stat = audio_status();
273 FOR_NB_SCREENS(i)
275 screens[i].clear_display();
276 screens[i].update();
279 if (batt_safe)
281 #ifdef HAVE_TAGCACHE
282 if (!tagcache_prepare_shutdown())
284 cancel_shutdown();
285 splash(HZ, ID2P(LANG_TAGCACHE_BUSY));
286 return false;
288 #endif
289 if (battery_level() > 10)
290 splash(0, str(LANG_SHUTTINGDOWN));
291 else
293 msg_id = LANG_WARNING_BATTERY_LOW;
294 splashf(0, "%s %s", str(LANG_WARNING_BATTERY_LOW),
295 str(LANG_SHUTTINGDOWN));
298 else
300 msg_id = LANG_WARNING_BATTERY_EMPTY;
301 splashf(0, "%s %s", str(LANG_WARNING_BATTERY_EMPTY),
302 str(LANG_SHUTTINGDOWN));
305 if (global_settings.fade_on_stop
306 && (audio_stat & AUDIO_STATUS_PLAY))
308 fade(false, false);
311 if (batt_safe) /* do not save on critical battery */
313 #if defined(HAVE_RECORDING) && CONFIG_CODEC == SWCODEC
314 if (audio_stat & AUDIO_STATUS_RECORD)
316 rec_command(RECORDING_CMD_STOP);
317 /* wait for stop to complete */
318 while (audio_status() & AUDIO_STATUS_RECORD)
319 sleep(1);
321 #endif
322 bookmark_autobookmark(false);
324 /* audio_stop_recording == audio_stop for HWCODEC */
325 audio_stop();
327 if (callback != NULL)
328 callback(parameter);
330 #if CONFIG_CODEC != SWCODEC
331 /* wait for audio_stop or audio_stop_recording to complete */
332 while (audio_status())
333 sleep(1);
334 #endif
336 #if defined(HAVE_RECORDING) && CONFIG_CODEC == SWCODEC
337 audio_close_recording();
338 #endif
340 if(global_settings.talk_menu)
342 bool enqueue = false;
343 if(msg_id != -1)
345 talk_id(msg_id, enqueue);
346 enqueue = true;
348 talk_id(LANG_SHUTTINGDOWN, enqueue);
349 #if CONFIG_CODEC == SWCODEC
350 voice_wait();
351 #endif
354 system_flush();
355 #ifdef HAVE_EEPROM_SETTINGS
356 if (firmware_settings.initialized)
358 firmware_settings.disk_clean = true;
359 firmware_settings.bl_version = 0;
360 eeprom_settings_store();
362 #endif
364 #ifdef HAVE_DIRCACHE
365 else
366 dircache_disable();
367 #endif
369 shutdown_hw();
371 #endif
372 return false;
375 bool list_stop_handler(void)
377 bool ret = false;
379 /* Stop the music if it is playing */
380 if(audio_status())
382 if (!global_settings.party_mode)
384 if (global_settings.fade_on_stop)
385 fade(false, false);
386 bookmark_autobookmark(true);
387 audio_stop();
388 ret = true; /* bookmarking can make a refresh necessary */
391 #if CONFIG_CHARGING
392 #if (CONFIG_KEYPAD == RECORDER_PAD) && !defined(HAVE_SW_POWEROFF)
393 else
395 if (charger_inserted())
396 charging_splash();
397 else
398 shutdown_screen(); /* won't return if shutdown actually happens */
400 ret = true; /* screen is dirty, caller needs to refresh */
402 #endif
403 #ifndef HAVE_POWEROFF_WHILE_CHARGING
405 static long last_off = 0;
407 if (TIME_BEFORE(current_tick, last_off + HZ/2))
409 if (charger_inserted())
411 charging_splash();
412 ret = true; /* screen is dirty, caller needs to refresh */
415 last_off = current_tick;
417 #endif
418 #endif /* CONFIG_CHARGING */
419 return ret;
422 #if CONFIG_CHARGING
423 static bool waiting_to_resume_play = false;
424 static long play_resume_tick;
426 static void car_adapter_mode_processing(bool inserted)
428 if (global_settings.car_adapter_mode)
430 if(inserted)
433 * Just got plugged in, delay & resume if we were playing
435 if (audio_status() & AUDIO_STATUS_PAUSE)
437 /* delay resume a bit while the engine is cranking */
438 play_resume_tick = current_tick + HZ*5;
439 waiting_to_resume_play = true;
442 else
445 * Just got unplugged, pause if playing
447 if ((audio_status() & AUDIO_STATUS_PLAY) &&
448 !(audio_status() & AUDIO_STATUS_PAUSE))
450 if (global_settings.fade_on_stop)
451 fade(false, false);
452 else
453 audio_pause();
455 waiting_to_resume_play = false;
460 static void car_adapter_tick(void)
462 if (waiting_to_resume_play)
464 if (TIME_AFTER(current_tick, play_resume_tick))
466 if (audio_status() & AUDIO_STATUS_PAUSE)
468 queue_broadcast(SYS_CAR_ADAPTER_RESUME, 0);
470 waiting_to_resume_play = false;
475 void car_adapter_mode_init(void)
477 tick_add_task(car_adapter_tick);
479 #endif
481 #ifdef HAVE_HEADPHONE_DETECTION
482 static void unplug_change(bool inserted)
484 static bool headphone_caused_pause = false;
486 if (global_settings.unplug_mode)
488 int audio_stat = audio_status();
489 if (inserted)
491 if ((audio_stat & AUDIO_STATUS_PLAY) &&
492 headphone_caused_pause &&
493 global_settings.unplug_mode > 1 )
494 audio_resume();
495 backlight_on();
496 headphone_caused_pause = false;
497 } else {
498 if ((audio_stat & AUDIO_STATUS_PLAY) &&
499 !(audio_stat & AUDIO_STATUS_PAUSE))
501 headphone_caused_pause = true;
502 audio_pause();
504 if (global_settings.unplug_rw)
506 if (audio_current_track()->elapsed >
507 (unsigned long)(global_settings.unplug_rw*1000))
508 audio_ff_rewind(audio_current_track()->elapsed -
509 (global_settings.unplug_rw*1000));
510 else
511 audio_ff_rewind(0);
517 #endif
519 long default_event_handler_ex(long event, void (*callback)(void *), void *parameter)
521 #if CONFIG_PLATFORM & PLATFORM_ANDROID
522 static bool resume = false;
523 #endif
524 switch(event)
526 case SYS_BATTERY_UPDATE:
527 if(global_settings.talk_battery_level)
529 talk_ids(true, VOICE_PAUSE, VOICE_PAUSE,
530 LANG_BATTERY_TIME,
531 TALK_ID(battery_level(), UNIT_PERCENT),
532 VOICE_PAUSE);
533 talk_force_enqueue_next();
535 break;
536 case SYS_USB_CONNECTED:
537 if (callback != NULL)
538 callback(parameter);
539 #if (CONFIG_STORAGE & STORAGE_MMC)
540 if (!mmc_touched() ||
541 (mmc_remove_request() == SYS_HOTSWAP_EXTRACTED))
542 #endif
544 system_flush();
545 #ifdef BOOTFILE
546 #if !defined(USB_NONE) && !defined(USB_HANDLED_BY_OF)
547 check_bootfile(false); /* gets initial size */
548 #endif
549 #endif
550 gui_usb_screen_run(false);
551 #ifdef BOOTFILE
552 #if !defined(USB_NONE) && !defined(USB_HANDLED_BY_OF)
553 check_bootfile(true);
554 #endif
555 #endif
556 system_restore();
558 return SYS_USB_CONNECTED;
560 case SYS_POWEROFF:
561 if (!clean_shutdown(callback, parameter))
562 return SYS_POWEROFF;
563 break;
564 #if CONFIG_CHARGING
565 case SYS_CHARGER_CONNECTED:
566 car_adapter_mode_processing(true);
567 return SYS_CHARGER_CONNECTED;
569 case SYS_CHARGER_DISCONNECTED:
570 car_adapter_mode_processing(false);
571 /*reset rockbox battery runtime*/
572 global_status.runtime = 0;
573 return SYS_CHARGER_DISCONNECTED;
575 case SYS_CAR_ADAPTER_RESUME:
576 audio_resume();
577 return SYS_CAR_ADAPTER_RESUME;
578 #endif
579 #ifdef HAVE_HOTSWAP_STORAGE_AS_MAIN
580 case SYS_FS_CHANGED:
582 /* simple sanity: assume rockbox is on the first hotswappable
583 * driver, abort out if that one isn't inserted */
584 int i;
585 for (i = 0; i < NUM_DRIVES; i++)
587 if (storage_removable(i) && !storage_present(i))
588 return SYS_FS_CHANGED;
590 system_flush();
591 check_bootfile(true); /* state gotten in main.c:init() */
592 system_restore();
594 return SYS_FS_CHANGED;
595 #endif
596 #ifdef HAVE_HEADPHONE_DETECTION
597 case SYS_PHONE_PLUGGED:
598 unplug_change(true);
599 return SYS_PHONE_PLUGGED;
601 case SYS_PHONE_UNPLUGGED:
602 unplug_change(false);
603 return SYS_PHONE_UNPLUGGED;
604 #endif
605 #ifdef IPOD_ACCESSORY_PROTOCOL
606 case SYS_IAP_PERIODIC:
607 iap_periodic();
608 return SYS_IAP_PERIODIC;
609 case SYS_IAP_HANDLEPKT:
610 iap_handlepkt();
611 return SYS_IAP_HANDLEPKT;
612 #endif
613 #if CONFIG_PLATFORM & PLATFORM_ANDROID
614 /* stop playback if we receive a call */
615 case SYS_CALL_INCOMING:
616 resume = (audio_status() & AUDIO_STATUS_PLAY) != 0;
617 list_stop_handler();
618 return SYS_CALL_INCOMING;
619 /* resume playback if needed */
620 case SYS_CALL_HUNG_UP:
621 if (resume && playlist_resume() != -1)
623 playlist_start(global_status.resume_index,
624 global_status.resume_offset);
626 resume = false;
627 return SYS_CALL_HUNG_UP;
628 #endif
630 return 0;
633 long default_event_handler(long event)
635 return default_event_handler_ex(event, NULL, NULL);
638 int show_logo( void )
640 #ifdef HAVE_LCD_BITMAP
641 char version[32];
642 int font_h, font_w;
644 snprintf(version, sizeof(version), "Ver. %s", rbversion);
646 lcd_clear_display();
647 #if defined(SANSA_CLIP) || defined(SANSA_CLIPV2) || defined(SANSA_CLIPPLUS)
648 /* display the logo in the blue area of the screen */
649 lcd_setfont(FONT_SYSFIXED);
650 lcd_getstringsize((unsigned char *)"A", &font_w, &font_h);
651 lcd_putsxy((LCD_WIDTH/2) - ((strlen(version)*font_w)/2),
652 0, (unsigned char *)version);
653 lcd_bitmap(rockboxlogo, 0, 16, BMPWIDTH_rockboxlogo, BMPHEIGHT_rockboxlogo);
654 #else
655 lcd_bitmap(rockboxlogo, 0, 10, BMPWIDTH_rockboxlogo, BMPHEIGHT_rockboxlogo);
656 lcd_setfont(FONT_SYSFIXED);
657 lcd_getstringsize((unsigned char *)"A", &font_w, &font_h);
658 lcd_putsxy((LCD_WIDTH/2) - ((strlen(version)*font_w)/2),
659 LCD_HEIGHT-font_h, (unsigned char *)version);
660 #endif
661 lcd_setfont(FONT_UI);
663 #else
664 char *rockbox = " ROCKbox!";
666 lcd_clear_display();
667 lcd_double_height(true);
668 lcd_puts(0, 0, rockbox);
669 lcd_puts_scroll(0, 1, rbversion);
670 #endif
671 lcd_update();
673 #ifdef HAVE_REMOTE_LCD
674 lcd_remote_clear_display();
675 lcd_remote_bitmap(remote_rockboxlogo, 0, 10, BMPWIDTH_remote_rockboxlogo,
676 BMPHEIGHT_remote_rockboxlogo);
677 lcd_remote_setfont(FONT_SYSFIXED);
678 lcd_remote_getstringsize((unsigned char *)"A", &font_w, &font_h);
679 lcd_remote_putsxy((LCD_REMOTE_WIDTH/2) - ((strlen(version)*font_w)/2),
680 LCD_REMOTE_HEIGHT-font_h, (unsigned char *)version);
681 lcd_remote_setfont(FONT_UI);
682 lcd_remote_update();
683 #endif
685 return 0;
688 #ifdef BOOTFILE
689 #if !defined(USB_NONE) && !defined(USB_HANDLED_BY_OF) || defined(HAVE_HOTSWAP_STORAGE_AS_MAIN)
691 memorize/compare details about the BOOTFILE
692 we don't use dircache because it may not be up to date after
693 USB disconnect (scanning in the background)
695 void check_bootfile(bool do_rolo)
697 static unsigned short wrtdate = 0;
698 static unsigned short wrttime = 0;
699 DIR* dir = NULL;
700 struct dirent* entry = NULL;
702 /* 1. open BOOTDIR and find the BOOTFILE dir entry */
703 dir = opendir(BOOTDIR);
705 if(!dir) return; /* do we want an error splash? */
707 /* loop all files in BOOTDIR */
708 while(0 != (entry = readdir(dir)))
710 if(!strcasecmp(entry->d_name, BOOTFILE))
712 struct dirinfo info = dir_get_info(dir, entry);
713 /* found the bootfile */
714 if(wrtdate && do_rolo)
716 if((info.wrtdate != wrtdate) ||
717 (info.wrttime != wrttime))
719 static const char *lines[] = { ID2P(LANG_BOOT_CHANGED),
720 ID2P(LANG_REBOOT_NOW) };
721 static const struct text_message message={ lines, 2 };
722 button_clear_queue(); /* Empty the keyboard buffer */
723 if(gui_syncyesno_run(&message, NULL, NULL) == YESNO_YES)
724 rolo_load(BOOTDIR "/" BOOTFILE);
727 wrtdate = info.wrtdate;
728 wrttime = info.wrttime;
731 closedir(dir);
733 #endif
734 #endif
736 /* check range, set volume and save settings */
737 void setvol(void)
739 const int min_vol = sound_min(SOUND_VOLUME);
740 const int max_vol = sound_max(SOUND_VOLUME);
741 if (global_settings.volume < min_vol)
742 global_settings.volume = min_vol;
743 if (global_settings.volume > max_vol)
744 global_settings.volume = max_vol;
745 sound_set_volume(global_settings.volume);
746 global_status.last_volume_change = current_tick;
747 settings_save();
750 char* strrsplt(char* str, int c)
752 char* s = strrchr(str, c);
754 if (s != NULL)
756 *s++ = '\0';
758 else
760 s = str;
763 return s;
767 * removes the extension of filename (if it doesn't start with a .)
768 * puts the result in buffer
770 char *strip_extension(char* buffer, int buffer_size, const char *filename)
772 char *dot = strrchr(filename, '.');
773 int len;
775 if (buffer_size <= 0)
777 return NULL;
780 buffer_size--; /* Make room for end nil */
782 if (dot != 0 && filename[0] != '.')
784 len = dot - filename;
785 len = MIN(len, buffer_size);
787 else
789 len = buffer_size;
792 strlcpy(buffer, filename, len + 1);
794 return buffer;
796 #endif /* !defined(__PCTOOL__) */
798 /* Read (up to) a line of text from fd into buffer and return number of bytes
799 * read (which may be larger than the number of bytes stored in buffer). If
800 * an error occurs, -1 is returned (and buffer contains whatever could be
801 * read). A line is terminated by a LF char. Neither LF nor CR chars are
802 * stored in buffer.
804 int read_line(int fd, char* buffer, int buffer_size)
806 int count = 0;
807 int num_read = 0;
809 errno = 0;
811 while (count < buffer_size)
813 unsigned char c;
815 if (1 != read(fd, &c, 1))
816 break;
818 num_read++;
820 if ( c == '\n' )
821 break;
823 if ( c == '\r' )
824 continue;
826 buffer[count++] = c;
829 buffer[MIN(count, buffer_size - 1)] = 0;
831 return errno ? -1 : num_read;
835 char* skip_whitespace(char* const str)
837 char *s = str;
839 while (isspace(*s))
840 s++;
842 return s;
845 /* Format time into buf.
847 * buf - buffer to format to.
848 * buf_size - size of buffer.
849 * t - time to format, in milliseconds.
851 void format_time(char* buf, int buf_size, long t)
853 if ( t < 3600000 )
855 snprintf(buf, buf_size, "%d:%02d",
856 (int) (t / 60000), (int) (t % 60000 / 1000));
858 else
860 snprintf(buf, buf_size, "%d:%02d:%02d",
861 (int) (t / 3600000), (int) (t % 3600000 / 60000),
862 (int) (t % 60000 / 1000));
867 /** Open a UTF-8 file and set file descriptor to first byte after BOM.
868 * If no BOM is present this behaves like open().
869 * If the file is opened for writing and O_TRUNC is set, write a BOM to
870 * the opened file and leave the file pointer set after the BOM.
872 #define BOM "\xef\xbb\xbf"
873 #define BOM_SIZE 3
875 int open_utf8(const char* pathname, int flags)
877 int fd;
878 unsigned char bom[BOM_SIZE];
880 fd = open(pathname, flags);
881 if(fd < 0)
882 return fd;
884 if(flags & (O_TRUNC | O_WRONLY))
886 write(fd, BOM, BOM_SIZE);
888 else
890 read(fd, bom, BOM_SIZE);
891 /* check for BOM */
892 if(memcmp(bom, BOM, BOM_SIZE))
893 lseek(fd, 0, SEEK_SET);
895 return fd;
899 #ifdef HAVE_LCD_COLOR
901 * Helper function to convert a string of 6 hex digits to a native colour
904 static int hex2dec(int c)
906 return (((c) >= '0' && ((c) <= '9')) ? (c) - '0' :
907 (toupper(c)) - 'A' + 10);
910 int hex_to_rgb(const char* hex, int* color)
912 int red, green, blue;
913 int i = 0;
915 while ((i < 6) && (isxdigit(hex[i])))
916 i++;
918 if (i < 6)
919 return -1;
921 red = (hex2dec(hex[0]) << 4) | hex2dec(hex[1]);
922 green = (hex2dec(hex[2]) << 4) | hex2dec(hex[3]);
923 blue = (hex2dec(hex[4]) << 4) | hex2dec(hex[5]);
925 *color = LCD_RGBPACK(red,green,blue);
927 return 0;
929 #endif /* HAVE_LCD_COLOR */
931 #ifdef HAVE_LCD_BITMAP
932 /* '0'-'3' are ASCII 0x30 to 0x33 */
933 #define is0123(x) (((x) & 0xfc) == 0x30)
934 #if !defined(__PCTOOL__) || defined(CHECKWPS)
935 bool parse_color(enum screen_type screen, char *text, int *value)
937 (void)text; (void)value; /* silence warnings on mono bitmap */
938 (void)screen;
940 #ifdef HAVE_LCD_COLOR
941 if (screens[screen].depth > 2)
943 if (hex_to_rgb(text, value) < 0)
944 return false;
945 else
946 return true;
948 #endif
950 #if LCD_DEPTH == 2 || (defined(HAVE_REMOTE_LCD) && LCD_REMOTE_DEPTH == 2)
951 if (screens[screen].depth == 2)
953 if (text[1] != '\0' || !is0123(*text))
954 return false;
955 *value = *text - '0';
956 return true;
958 #endif
959 return false;
961 #endif /* !defined(__PCTOOL__) || defined(CHECKWPS) */
963 /* only used in USB HID and set_time screen */
964 #if defined(USB_ENABLE_HID) || (CONFIG_RTC != 0)
965 int clamp_value_wrap(int value, int max, int min)
967 if (value > max)
968 return min;
969 if (value < min)
970 return max;
971 return value;
973 #endif
974 #endif