unplug_change: Precede call to audio_ff_rewind with
[kugel-rb.git] / apps / misc.c
blob12d0c8d95a0cc807527bcc082ea7f3add4902021
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 "system.h"
30 #include "lcd.h"
31 #include "file.h"
32 #include "filefuncs.h"
33 #ifndef __PCTOOL__
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 #include "debug.h"
63 #if CONFIG_TUNER
64 #include "radio.h"
65 #endif
67 #ifdef IPOD_ACCESSORY_PROTOCOL
68 #include "iap.h"
69 #endif
71 #if (CONFIG_STORAGE & STORAGE_MMC)
72 #include "ata_mmc.h"
73 #endif
74 #include "tree.h"
75 #include "eeprom_settings.h"
76 #if defined(HAVE_RECORDING) && !defined(__PCTOOL__)
77 #include "recording.h"
78 #endif
79 #if defined(HAVE_LCD_BITMAP) && !defined(__PCTOOL__)
80 #include "bmp.h"
81 #include "icons.h"
82 #endif /* End HAVE_LCD_BITMAP */
83 #include "bookmark.h"
84 #include "wps.h"
85 #include "playback.h"
86 #if CONFIG_CODEC == SWCODEC
87 #include "voice_thread.h"
88 #endif
90 #ifdef BOOTFILE
91 #if !defined(USB_NONE) && !defined(USB_HANDLED_BY_OF) \
92 || defined(HAVE_HOTSWAP_STORAGE_AS_MAIN)
93 #include "rolo.h"
94 #endif
95 #endif
97 /* units used with output_dyn_value */
98 const unsigned char * const byte_units[] =
100 ID2P(LANG_BYTE),
101 ID2P(LANG_KILOBYTE),
102 ID2P(LANG_MEGABYTE),
103 ID2P(LANG_GIGABYTE)
106 const unsigned char * const * const kbyte_units = &byte_units[1];
108 /* Format a large-range value for output, using the appropriate unit so that
109 * the displayed value is in the range 1 <= display < 1000 (1024 for "binary"
110 * units) if possible, and 3 significant digits are shown. If a buffer is
111 * given, the result is snprintf()'d into that buffer, otherwise the result is
112 * voiced.*/
113 char *output_dyn_value(char *buf, int buf_size, int value,
114 const unsigned char * const *units, bool bin_scale)
116 int scale = bin_scale ? 1024 : 1000;
117 int fraction = 0;
118 int unit_no = 0;
119 char tbuf[5];
121 while (value >= scale)
123 fraction = value % scale;
124 value /= scale;
125 unit_no++;
127 if (bin_scale)
128 fraction = fraction * 1000 / 1024;
130 if (value >= 100 || !unit_no)
131 tbuf[0] = '\0';
132 else if (value >= 10)
133 snprintf(tbuf, sizeof(tbuf), "%01d", fraction / 100);
134 else
135 snprintf(tbuf, sizeof(tbuf), "%02d", fraction / 10);
137 if (buf)
139 if (*tbuf)
140 snprintf(buf, buf_size, "%d%s%s%s", value, str(LANG_POINT),
141 tbuf, P2STR(units[unit_no]));
142 else
143 snprintf(buf, buf_size, "%d%s", value, P2STR(units[unit_no]));
145 else
147 talk_fractional(tbuf, value, P2ID(units[unit_no]));
149 return buf;
152 /* Ask the user if they really want to erase the current dynamic playlist
153 * returns true if the playlist should be replaced */
154 bool warn_on_pl_erase(void)
156 if (global_settings.warnon_erase_dynplaylist &&
157 !global_settings.party_mode &&
158 playlist_modified(NULL))
160 static const char *lines[] =
161 {ID2P(LANG_WARN_ERASEDYNPLAYLIST_PROMPT)};
162 static const struct text_message message={lines, 1};
164 return (gui_syncyesno_run(&message, NULL, NULL) == YESNO_YES);
166 else
167 return true;
171 /* Performance optimized version of the read_line() (see below) function. */
172 int fast_readline(int fd, char *buf, int buf_size, void *parameters,
173 int (*callback)(int n, const char *buf, void *parameters))
175 char *p, *next;
176 int rc, pos = 0;
177 int count = 0;
179 while ( 1 )
181 next = NULL;
183 rc = read(fd, &buf[pos], buf_size - pos - 1);
184 if (rc >= 0)
185 buf[pos+rc] = '\0';
187 if ( (p = strchr(buf, '\r')) != NULL)
189 *p = '\0';
190 next = ++p;
192 else
193 p = buf;
195 if ( (p = strchr(p, '\n')) != NULL)
197 *p = '\0';
198 next = ++p;
201 rc = callback(count, buf, parameters);
202 if (rc < 0)
203 return rc;
205 count++;
206 if (next)
208 pos = buf_size - ((long)next - (long)buf) - 1;
209 memmove(buf, next, pos);
211 else
212 break ;
215 return 0;
218 /* parse a line from a configuration file. the line format is:
220 name: value
222 Any whitespace before setting name or value (after ':') is ignored.
223 A # as first non-whitespace character discards the whole line.
224 Function sets pointers to null-terminated setting name and value.
225 Returns false if no valid config entry was found.
228 bool settings_parseline(char* line, char** name, char** value)
230 char* ptr;
232 line = skip_whitespace(line);
234 if ( *line == '#' )
235 return false;
237 ptr = strchr(line, ':');
238 if ( !ptr )
239 return false;
241 *name = line;
242 *ptr = 0;
243 ptr++;
244 ptr = skip_whitespace(ptr);
245 *value = ptr;
246 return true;
249 static void system_flush(void)
251 scrobbler_shutdown();
252 playlist_shutdown();
253 tree_flush();
254 call_storage_idle_notifys(true); /*doesnt work on usb and shutdown from ata thread */
257 static void system_restore(void)
259 tree_restore();
260 scrobbler_init();
263 static bool clean_shutdown(void (*callback)(void *), void *parameter)
265 long msg_id = -1;
266 int i;
268 scrobbler_poweroff();
270 #if CONFIG_CHARGING && !defined(HAVE_POWEROFF_WHILE_CHARGING)
271 if(!charger_inserted())
272 #endif
274 bool batt_safe = battery_level_safe();
275 int audio_stat = audio_status();
277 FOR_NB_SCREENS(i)
279 screens[i].clear_display();
280 screens[i].update();
283 if (batt_safe)
285 #ifdef HAVE_TAGCACHE
286 if (!tagcache_prepare_shutdown())
288 cancel_shutdown();
289 splash(HZ, ID2P(LANG_TAGCACHE_BUSY));
290 return false;
292 #endif
293 if (battery_level() > 10)
294 splash(0, str(LANG_SHUTTINGDOWN));
295 else
297 msg_id = LANG_WARNING_BATTERY_LOW;
298 splashf(0, "%s %s", str(LANG_WARNING_BATTERY_LOW),
299 str(LANG_SHUTTINGDOWN));
302 else
304 msg_id = LANG_WARNING_BATTERY_EMPTY;
305 splashf(0, "%s %s", str(LANG_WARNING_BATTERY_EMPTY),
306 str(LANG_SHUTTINGDOWN));
309 if (global_settings.fade_on_stop
310 && (audio_stat & AUDIO_STATUS_PLAY))
312 fade(false, false);
315 if (batt_safe) /* do not save on critical battery */
317 #if defined(HAVE_RECORDING) && CONFIG_CODEC == SWCODEC
318 if (audio_stat & AUDIO_STATUS_RECORD)
320 rec_command(RECORDING_CMD_STOP);
321 /* wait for stop to complete */
322 while (audio_status() & AUDIO_STATUS_RECORD)
323 sleep(1);
325 #endif
326 bookmark_autobookmark(false);
328 /* audio_stop_recording == audio_stop for HWCODEC */
329 audio_stop();
331 if (callback != NULL)
332 callback(parameter);
334 #if CONFIG_CODEC != SWCODEC
335 /* wait for audio_stop or audio_stop_recording to complete */
336 while (audio_status())
337 sleep(1);
338 #endif
340 #if defined(HAVE_RECORDING) && CONFIG_CODEC == SWCODEC
341 audio_close_recording();
342 #endif
344 if(global_settings.talk_menu)
346 bool enqueue = false;
347 if(msg_id != -1)
349 talk_id(msg_id, enqueue);
350 enqueue = true;
352 talk_id(LANG_SHUTTINGDOWN, enqueue);
353 #if CONFIG_CODEC == SWCODEC
354 voice_wait();
355 #endif
358 system_flush();
359 #ifdef HAVE_EEPROM_SETTINGS
360 if (firmware_settings.initialized)
362 firmware_settings.disk_clean = true;
363 firmware_settings.bl_version = 0;
364 eeprom_settings_store();
366 #endif
368 #ifdef HAVE_DIRCACHE
369 else
370 dircache_disable();
371 #endif
373 shutdown_hw();
375 return false;
378 bool list_stop_handler(void)
380 bool ret = false;
382 #if CONFIG_TUNER
383 radio_stop();
384 #endif
386 /* Stop the music if it is playing */
387 if(audio_status())
389 if (!global_settings.party_mode)
391 if (global_settings.fade_on_stop)
392 fade(false, false);
393 bookmark_autobookmark(true);
394 audio_stop();
395 ret = true; /* bookmarking can make a refresh necessary */
398 #if CONFIG_CHARGING
399 #if (CONFIG_KEYPAD == RECORDER_PAD) && !defined(HAVE_SW_POWEROFF)
400 else
402 if (charger_inserted())
403 charging_splash();
404 else
405 shutdown_screen(); /* won't return if shutdown actually happens */
407 ret = true; /* screen is dirty, caller needs to refresh */
409 #endif
410 #ifndef HAVE_POWEROFF_WHILE_CHARGING
412 static long last_off = 0;
414 if (TIME_BEFORE(current_tick, last_off + HZ/2))
416 if (charger_inserted())
418 charging_splash();
419 ret = true; /* screen is dirty, caller needs to refresh */
422 last_off = current_tick;
424 #endif
425 #endif /* CONFIG_CHARGING */
426 return ret;
429 #if CONFIG_CHARGING
430 static bool waiting_to_resume_play = false;
431 static long play_resume_tick;
433 static void car_adapter_mode_processing(bool inserted)
435 if (global_settings.car_adapter_mode)
437 if(inserted)
440 * Just got plugged in, delay & resume if we were playing
442 if (audio_status() & AUDIO_STATUS_PAUSE)
444 /* delay resume a bit while the engine is cranking */
445 play_resume_tick = current_tick + HZ*5;
446 waiting_to_resume_play = true;
449 else
452 * Just got unplugged, pause if playing
454 if ((audio_status() & AUDIO_STATUS_PLAY) &&
455 !(audio_status() & AUDIO_STATUS_PAUSE))
457 if (global_settings.fade_on_stop)
458 fade(false, false);
459 else
460 audio_pause();
462 waiting_to_resume_play = false;
467 static void car_adapter_tick(void)
469 if (waiting_to_resume_play)
471 if (TIME_AFTER(current_tick, play_resume_tick))
473 if (audio_status() & AUDIO_STATUS_PAUSE)
475 queue_broadcast(SYS_CAR_ADAPTER_RESUME, 0);
477 waiting_to_resume_play = false;
482 void car_adapter_mode_init(void)
484 tick_add_task(car_adapter_tick);
486 #endif
488 #ifdef HAVE_HEADPHONE_DETECTION
489 static void unplug_change(bool inserted)
491 static bool headphone_caused_pause = false;
493 if (global_settings.unplug_mode)
495 int audio_stat = audio_status();
496 if (inserted)
498 if ((audio_stat & AUDIO_STATUS_PLAY) &&
499 headphone_caused_pause &&
500 global_settings.unplug_mode > 1 )
501 audio_resume();
502 backlight_on();
503 headphone_caused_pause = false;
504 } else {
505 if ((audio_stat & AUDIO_STATUS_PLAY) &&
506 !(audio_stat & AUDIO_STATUS_PAUSE))
508 headphone_caused_pause = true;
509 audio_pause();
511 if (global_settings.unplug_rw)
513 #if (CONFIG_CODEC == SWCODEC)
514 audio_pre_ff_rewind();
515 #endif
516 if (audio_current_track()->elapsed >
517 (unsigned long)(global_settings.unplug_rw*1000))
518 audio_ff_rewind(audio_current_track()->elapsed -
519 (global_settings.unplug_rw*1000));
520 else
521 audio_ff_rewind(0);
527 #endif
529 long default_event_handler_ex(long event, void (*callback)(void *), void *parameter)
531 #if CONFIG_PLATFORM & (PLATFORM_ANDROID|PLATFORM_MAEMO)
532 static bool resume = false;
533 #endif
535 switch(event)
537 case SYS_BATTERY_UPDATE:
538 if(global_settings.talk_battery_level)
540 talk_ids(true, VOICE_PAUSE, VOICE_PAUSE,
541 LANG_BATTERY_TIME,
542 TALK_ID(battery_level(), UNIT_PERCENT),
543 VOICE_PAUSE);
544 talk_force_enqueue_next();
546 break;
547 case SYS_USB_CONNECTED:
548 if (callback != NULL)
549 callback(parameter);
550 #if (CONFIG_STORAGE & STORAGE_MMC)
551 if (!mmc_touched() ||
552 (mmc_remove_request() == SYS_HOTSWAP_EXTRACTED))
553 #endif
555 system_flush();
556 #ifdef BOOTFILE
557 #if !defined(USB_NONE) && !defined(USB_HANDLED_BY_OF)
558 check_bootfile(false); /* gets initial size */
559 #endif
560 #endif
561 gui_usb_screen_run(false);
562 #ifdef BOOTFILE
563 #if !defined(USB_NONE) && !defined(USB_HANDLED_BY_OF)
564 check_bootfile(true);
565 #endif
566 #endif
567 system_restore();
569 return SYS_USB_CONNECTED;
571 case SYS_POWEROFF:
572 if (!clean_shutdown(callback, parameter))
573 return SYS_POWEROFF;
574 break;
575 #if CONFIG_CHARGING
576 case SYS_CHARGER_CONNECTED:
577 car_adapter_mode_processing(true);
578 return SYS_CHARGER_CONNECTED;
580 case SYS_CHARGER_DISCONNECTED:
581 car_adapter_mode_processing(false);
582 /*reset rockbox battery runtime*/
583 global_status.runtime = 0;
584 return SYS_CHARGER_DISCONNECTED;
586 case SYS_CAR_ADAPTER_RESUME:
587 audio_resume();
588 return SYS_CAR_ADAPTER_RESUME;
589 #endif
590 #ifdef HAVE_HOTSWAP_STORAGE_AS_MAIN
591 case SYS_FS_CHANGED:
593 /* simple sanity: assume rockbox is on the first hotswappable
594 * driver, abort out if that one isn't inserted */
595 int i;
596 for (i = 0; i < NUM_DRIVES; i++)
598 if (storage_removable(i) && !storage_present(i))
599 return SYS_FS_CHANGED;
601 system_flush();
602 check_bootfile(true); /* state gotten in main.c:init() */
603 system_restore();
605 return SYS_FS_CHANGED;
606 #endif
607 #ifdef HAVE_HEADPHONE_DETECTION
608 case SYS_PHONE_PLUGGED:
609 unplug_change(true);
610 return SYS_PHONE_PLUGGED;
612 case SYS_PHONE_UNPLUGGED:
613 unplug_change(false);
614 return SYS_PHONE_UNPLUGGED;
615 #endif
616 #ifdef IPOD_ACCESSORY_PROTOCOL
617 case SYS_IAP_PERIODIC:
618 iap_periodic();
619 return SYS_IAP_PERIODIC;
620 case SYS_IAP_HANDLEPKT:
621 iap_handlepkt();
622 return SYS_IAP_HANDLEPKT;
623 #endif
624 #if CONFIG_PLATFORM & (PLATFORM_ANDROID|PLATFORM_MAEMO)
625 /* stop playback if we receive a call */
626 case SYS_CALL_INCOMING:
627 resume = audio_status() == AUDIO_STATUS_PLAY;
628 list_stop_handler();
629 return SYS_CALL_INCOMING;
630 /* resume playback if needed */
631 case SYS_CALL_HUNG_UP:
632 if (resume && playlist_resume() != -1)
634 playlist_start(global_status.resume_index,
635 global_status.resume_offset);
637 resume = false;
638 return SYS_CALL_HUNG_UP;
639 #endif
640 #if (CONFIG_PLATFORM & PLATFORM_HOSTED) && defined(PLATFORM_HAS_VOLUME_CHANGE)
641 case SYS_VOLUME_CHANGED:
643 static bool firstvolume = true;
644 int volume = hosted_get_volume();
645 DEBUGF("SYS_VOLUME_CHANGED: %d\n", volume);
646 if (global_settings.volume != volume) {
647 global_settings.volume = volume;
648 if (firstvolume) {
649 setvol();
650 firstvolume = false;
653 return 0;
655 #endif
656 #ifdef HAVE_MULTIMEDIA_KEYS
657 /* multimedia keys on keyboards, headsets */
658 case BUTTON_MULTIMEDIA_PLAYPAUSE:
660 int status = audio_status();
661 if (status & AUDIO_STATUS_PLAY)
663 if (status & AUDIO_STATUS_PAUSE)
664 audio_resume();
665 else
666 audio_pause();
668 else
669 if (playlist_resume() != -1)
671 playlist_start(global_status.resume_index,
672 global_status.resume_offset);
674 return event;
676 case BUTTON_MULTIMEDIA_NEXT:
677 audio_next();
678 return event;
679 case BUTTON_MULTIMEDIA_PREV:
680 audio_prev();
681 return event;
682 case BUTTON_MULTIMEDIA_STOP:
683 list_stop_handler();
684 return event;
685 case BUTTON_MULTIMEDIA_REW:
686 case BUTTON_MULTIMEDIA_FFWD:
687 /* not supported yet, needs to be done in the WPS */
688 return 0;
689 #endif
691 return 0;
694 long default_event_handler(long event)
696 return default_event_handler_ex(event, NULL, NULL);
699 int show_logo( void )
701 #ifdef HAVE_LCD_BITMAP
702 char version[32];
703 int font_h, font_w;
705 snprintf(version, sizeof(version), "Ver. %s", rbversion);
707 lcd_clear_display();
708 #if defined(SANSA_CLIP) || defined(SANSA_CLIPV2) || defined(SANSA_CLIPPLUS)
709 /* display the logo in the blue area of the screen */
710 lcd_setfont(FONT_SYSFIXED);
711 lcd_getstringsize((unsigned char *)"A", &font_w, &font_h);
712 lcd_putsxy((LCD_WIDTH/2) - ((strlen(version)*font_w)/2),
713 0, (unsigned char *)version);
714 lcd_bitmap(rockboxlogo, 0, 16, BMPWIDTH_rockboxlogo, BMPHEIGHT_rockboxlogo);
715 #else
716 lcd_bitmap(rockboxlogo, 0, 10, BMPWIDTH_rockboxlogo, BMPHEIGHT_rockboxlogo);
717 lcd_setfont(FONT_SYSFIXED);
718 lcd_getstringsize((unsigned char *)"A", &font_w, &font_h);
719 lcd_putsxy((LCD_WIDTH/2) - ((strlen(version)*font_w)/2),
720 LCD_HEIGHT-font_h, (unsigned char *)version);
721 #endif
722 lcd_setfont(FONT_UI);
724 #else
725 char *rockbox = " ROCKbox!";
727 lcd_clear_display();
728 lcd_double_height(true);
729 lcd_puts(0, 0, rockbox);
730 lcd_puts_scroll(0, 1, rbversion);
731 #endif
732 lcd_update();
734 #ifdef HAVE_REMOTE_LCD
735 lcd_remote_clear_display();
736 lcd_remote_bitmap(remote_rockboxlogo, 0, 10, BMPWIDTH_remote_rockboxlogo,
737 BMPHEIGHT_remote_rockboxlogo);
738 lcd_remote_setfont(FONT_SYSFIXED);
739 lcd_remote_getstringsize((unsigned char *)"A", &font_w, &font_h);
740 lcd_remote_putsxy((LCD_REMOTE_WIDTH/2) - ((strlen(version)*font_w)/2),
741 LCD_REMOTE_HEIGHT-font_h, (unsigned char *)version);
742 lcd_remote_setfont(FONT_UI);
743 lcd_remote_update();
744 #endif
746 return 0;
749 #ifdef BOOTFILE
750 #if !defined(USB_NONE) && !defined(USB_HANDLED_BY_OF) || defined(HAVE_HOTSWAP_STORAGE_AS_MAIN)
752 memorize/compare details about the BOOTFILE
753 we don't use dircache because it may not be up to date after
754 USB disconnect (scanning in the background)
756 void check_bootfile(bool do_rolo)
758 static unsigned short wrtdate = 0;
759 static unsigned short wrttime = 0;
760 DIR* dir = NULL;
761 struct dirent* entry = NULL;
763 /* 1. open BOOTDIR and find the BOOTFILE dir entry */
764 dir = opendir(BOOTDIR);
766 if(!dir) return; /* do we want an error splash? */
768 /* loop all files in BOOTDIR */
769 while(0 != (entry = readdir(dir)))
771 if(!strcasecmp(entry->d_name, BOOTFILE))
773 struct dirinfo info = dir_get_info(dir, entry);
774 /* found the bootfile */
775 if(wrtdate && do_rolo)
777 if((info.wrtdate != wrtdate) ||
778 (info.wrttime != wrttime))
780 static const char *lines[] = { ID2P(LANG_BOOT_CHANGED),
781 ID2P(LANG_REBOOT_NOW) };
782 static const struct text_message message={ lines, 2 };
783 button_clear_queue(); /* Empty the keyboard buffer */
784 if(gui_syncyesno_run(&message, NULL, NULL) == YESNO_YES)
785 rolo_load(BOOTDIR "/" BOOTFILE);
788 wrtdate = info.wrtdate;
789 wrttime = info.wrttime;
792 closedir(dir);
794 #endif
795 #endif
797 /* check range, set volume and save settings */
798 void setvol(void)
800 const int min_vol = sound_min(SOUND_VOLUME);
801 const int max_vol = sound_max(SOUND_VOLUME);
802 if (global_settings.volume < min_vol)
803 global_settings.volume = min_vol;
804 if (global_settings.volume > max_vol)
805 global_settings.volume = max_vol;
806 sound_set_volume(global_settings.volume);
807 global_status.last_volume_change = current_tick;
808 settings_save();
811 char* strrsplt(char* str, int c)
813 char* s = strrchr(str, c);
815 if (s != NULL)
817 *s++ = '\0';
819 else
821 s = str;
824 return s;
828 * removes the extension of filename (if it doesn't start with a .)
829 * puts the result in buffer
831 char *strip_extension(char* buffer, int buffer_size, const char *filename)
833 char *dot = strrchr(filename, '.');
834 int len;
836 if (buffer_size <= 0)
838 return NULL;
841 buffer_size--; /* Make room for end nil */
843 if (dot != 0 && filename[0] != '.')
845 len = dot - filename;
846 len = MIN(len, buffer_size);
848 else
850 len = buffer_size;
853 strlcpy(buffer, filename, len + 1);
855 return buffer;
857 #endif /* !defined(__PCTOOL__) */
859 /* Read (up to) a line of text from fd into buffer and return number of bytes
860 * read (which may be larger than the number of bytes stored in buffer). If
861 * an error occurs, -1 is returned (and buffer contains whatever could be
862 * read). A line is terminated by a LF char. Neither LF nor CR chars are
863 * stored in buffer.
865 int read_line(int fd, char* buffer, int buffer_size)
867 int count = 0;
868 int num_read = 0;
870 errno = 0;
872 while (count < buffer_size)
874 unsigned char c;
876 if (1 != read(fd, &c, 1))
877 break;
879 num_read++;
881 if ( c == '\n' )
882 break;
884 if ( c == '\r' )
885 continue;
887 buffer[count++] = c;
890 buffer[MIN(count, buffer_size - 1)] = 0;
892 return errno ? -1 : num_read;
896 char* skip_whitespace(char* const str)
898 char *s = str;
900 while (isspace(*s))
901 s++;
903 return s;
906 /* Format time into buf.
908 * buf - buffer to format to.
909 * buf_size - size of buffer.
910 * t - time to format, in milliseconds.
912 void format_time(char* buf, int buf_size, long t)
914 int const time = abs(t / 1000);
915 int const hours = time / 3600;
916 int const minutes = time / 60 - hours * 60;
917 int const seconds = time % 60;
918 const char * const sign = &"-"[t < 0 ? 0 : 1];
920 if ( hours == 0 )
922 snprintf(buf, buf_size, "%s%d:%02d", sign, minutes, seconds);
924 else
926 snprintf(buf, buf_size, "%s%d:%02d:%02d", sign, hours, minutes,
927 seconds);
932 /** Open a UTF-8 file and set file descriptor to first byte after BOM.
933 * If no BOM is present this behaves like open().
934 * If the file is opened for writing and O_TRUNC is set, write a BOM to
935 * the opened file and leave the file pointer set after the BOM.
937 #define BOM "\xef\xbb\xbf"
938 #define BOM_SIZE 3
940 int open_utf8(const char* pathname, int flags)
942 int fd;
943 unsigned char bom[BOM_SIZE];
945 fd = open(pathname, flags, 0666);
946 if(fd < 0)
947 return fd;
949 if(flags & (O_TRUNC | O_WRONLY))
951 write(fd, BOM, BOM_SIZE);
953 else
955 read(fd, bom, BOM_SIZE);
956 /* check for BOM */
957 if(memcmp(bom, BOM, BOM_SIZE))
958 lseek(fd, 0, SEEK_SET);
960 return fd;
964 #ifdef HAVE_LCD_COLOR
966 * Helper function to convert a string of 6 hex digits to a native colour
969 static int hex2dec(int c)
971 return (((c) >= '0' && ((c) <= '9')) ? (c) - '0' :
972 (toupper(c)) - 'A' + 10);
975 int hex_to_rgb(const char* hex, int* color)
977 int red, green, blue;
978 int i = 0;
980 while ((i < 6) && (isxdigit(hex[i])))
981 i++;
983 if (i < 6)
984 return -1;
986 red = (hex2dec(hex[0]) << 4) | hex2dec(hex[1]);
987 green = (hex2dec(hex[2]) << 4) | hex2dec(hex[3]);
988 blue = (hex2dec(hex[4]) << 4) | hex2dec(hex[5]);
990 *color = LCD_RGBPACK(red,green,blue);
992 return 0;
994 #endif /* HAVE_LCD_COLOR */
996 #ifdef HAVE_LCD_BITMAP
997 /* '0'-'3' are ASCII 0x30 to 0x33 */
998 #define is0123(x) (((x) & 0xfc) == 0x30)
999 #if !defined(__PCTOOL__) || defined(CHECKWPS)
1000 bool parse_color(enum screen_type screen, char *text, int *value)
1002 (void)text; (void)value; /* silence warnings on mono bitmap */
1003 (void)screen;
1005 #ifdef HAVE_LCD_COLOR
1006 if (screens[screen].depth > 2)
1008 if (hex_to_rgb(text, value) < 0)
1009 return false;
1010 else
1011 return true;
1013 #endif
1015 #if LCD_DEPTH == 2 || (defined(HAVE_REMOTE_LCD) && LCD_REMOTE_DEPTH == 2)
1016 if (screens[screen].depth == 2)
1018 if (text[1] != '\0' || !is0123(*text))
1019 return false;
1020 *value = *text - '0';
1021 return true;
1023 #endif
1024 return false;
1026 #endif /* !defined(__PCTOOL__) || defined(CHECKWPS) */
1028 /* only used in USB HID and set_time screen */
1029 #if defined(USB_ENABLE_HID) || (CONFIG_RTC != 0)
1030 int clamp_value_wrap(int value, int max, int min)
1032 if (value > max)
1033 return min;
1034 if (value < min)
1035 return max;
1036 return value;
1038 #endif
1039 #endif