493ce0fe517f419c8788d7890fb978e952876292
[hackover2013-badge-firmware.git] / badge / ui / browser.c
1 #include "browser.h"
2 #include "menu.h"
3
4 #include <drivers/fatfs/ff.h>
5 #include <string.h>
6
7 enum {
8 LINE_LENGTH = 16,
9 FNAME_MAX = 12,
10 BUFLEN = LINE_LENGTH + 1 + FNAME_MAX + 1
11 };
12
13 static void badge_browse_textfile_fd(FIL *fd) {
14 unsigned linecount = 0;
15
16 {
17 char buf[LINE_LENGTH];
18 while(f_gets(buf, LINE_LENGTH, fd)) {
19 ++linecount;
20 }
21 }
22
23 if(FR_OK != f_lseek(fd, 0)) {
24 return;
25 }
26
27 char lines_buf[linecount][LINE_LENGTH];
28 char const *lines[linecount];
29 unsigned i;
30
31 for(i = 0; i < linecount && f_gets(lines_buf[i], LINE_LENGTH, fd); ++i) {
32 lines[i] = lines_buf[i];
33 }
34
35 badge_scroll_text(lines, i);
36 }
37
38 static size_t badge_count_lines_in_file(FIL *fd) {
39 size_t count = 0;
40
41 if(FR_OK == f_lseek(fd, 0)) {
42 char buf[BUFLEN];
43 while(f_gets(buf, BUFLEN, fd)) {
44 ++count;
45 }
46 }
47
48 return count;
49 }
50
51 static uint8_t badge_browse_pick_filename_from_fd(char *buf, size_t *first_visible, size_t *selected, FIL *fd) {
52 unsigned linecount = badge_count_lines_in_file(fd);
53
54 if(FR_OK != f_lseek(fd, 0)) {
55 return 1;
56 }
57
58 char menu_buf [linecount + 1][BUFLEN];
59 char const *menu_index[linecount + 1];
60 char *fnames [linecount + 1];
61 unsigned i;
62
63 for(i = 0; i < linecount && f_gets(menu_buf[i], BUFLEN, fd); ++i) {
64 menu_index[i] = menu_buf[i];
65 char *p;
66 for(p = menu_buf[i]; *p && *p != '|'; ++p)
67 ;
68 if(*p) {
69 *p++ = '\0';
70 }
71 fnames[i] = p;
72 }
73
74 strcpy(menu_buf[i], "Zurück");
75 menu_index[i] = menu_buf[i];
76 size_t choice = badge_menu(menu_index, i + 1, first_visible, *selected);
77
78 if(choice == linecount) {
79 return 1; // exit
80 }
81
82 *selected = choice;
83 strncpy(buf, fnames[*selected], FNAME_MAX);
84 buf[FNAME_MAX] = '\0';
85
86 return 0;
87 }
88
89 static uint8_t badge_pick_filename(char *buf, char const *menufile, size_t *first_visible, size_t *selected) {
90 FIL fd;
91 uint8_t err = 1;
92
93 if(FR_OK == f_open(&fd, menufile, FA_OPEN_EXISTING | FA_READ)) {
94 err = badge_browse_pick_filename_from_fd(buf, first_visible, selected, &fd);
95 f_close(&fd);
96 }
97
98 return err;
99 }
100
101 void badge_browse_textfile(char const *fname) {
102 FIL fd;
103
104 if(FR_OK == f_open(&fd, fname, FA_OPEN_EXISTING | FA_READ)) {
105 badge_browse_textfile_fd(&fd);
106 f_close(&fd);
107 }
108 }
109
110 void badge_browse_textfiles(char const *menufile, size_t *selected) {
111 char buf[FNAME_MAX + 1];
112 size_t first_visible = 0;
113
114 while(0 == badge_pick_filename(buf, menufile, &first_visible, selected)) {
115 badge_browse_textfile(buf);
116 }
117 }
This page took 0.057641 seconds and 3 git commands to generate.