Fix errors and warnings.
[kugel-rb.git] / apps / tagtree.c
blob5012c084d059a34e203dbe10e731c6085b7bad83
1 /***************************************************************************
2 * __________ __ ___.
3 * Open \______ \ ____ ____ | | _\_ |__ _______ ___
4 * Source | _// _ \_/ ___\| |/ /| __ \ / _ \ \/ /
5 * Jukebox | | ( <_> ) \___| < | \_\ ( <_> > < <
6 * Firmware |____|_ /\____/ \___ >__|_ \|___ /\____/__/\_ \
7 * \/ \/ \/ \/ \/
8 * $Id$
10 * Copyright (C) 2005 by Miika Pekkarinen
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 ****************************************************************************/
22 /**
23 * Basic structure on this file was copied from dbtree.c and modified to
24 * support the tag cache interface.
27 /*#define LOGF_ENABLE*/
29 #include <stdio.h>
30 #include <stdlib.h>
31 #include "string-extra.h"
32 #include "config.h"
33 #include "system.h"
34 #include "kernel.h"
35 #include "splash.h"
36 #include "icons.h"
37 #include "tree.h"
38 #include "action.h"
39 #include "settings.h"
40 #include "tagcache.h"
41 #include "tagtree.h"
42 #include "lang.h"
43 #include "logf.h"
44 #include "playlist.h"
45 #include "keyboard.h"
46 #include "gui/list.h"
47 #include "buffer.h"
48 #include "yesno.h"
49 #include "misc.h"
50 #include "filetypes.h"
51 #include "audio.h"
52 #include "appevents.h"
53 #include "storage.h"
54 #include "dir.h"
55 #include "playback.h"
57 #define str_or_empty(x) (x ? x : "(NULL)")
59 #define FILE_SEARCH_INSTRUCTIONS ROCKBOX_DIR "/tagnavi.config"
61 static int tagtree_play_folder(struct tree_context* c);
63 #define SEARCHSTR_SIZE 256
65 enum table {
66 ROOT = 1,
67 NAVIBROWSE,
68 ALLSUBENTRIES,
69 PLAYTRACK,
72 static const struct id3_to_search_mapping {
73 char *string;
74 size_t id3_offset;
75 } id3_to_search_mapping[] = {
76 { "", 0 }, /* offset n/a */
77 { "#directory#", 0 }, /* offset n/a */
78 { "#title#", offsetof(struct mp3entry, title) },
79 { "#artist#", offsetof(struct mp3entry, artist) },
80 { "#album#", offsetof(struct mp3entry, album) },
81 { "#genre#", offsetof(struct mp3entry, genre_string) },
82 { "#composer#", offsetof(struct mp3entry, composer) },
83 { "#albumartist#", offsetof(struct mp3entry, albumartist) },
85 enum variables {
86 var_sorttype = 100,
87 var_limit,
88 var_strip,
89 var_menu_start,
90 var_include,
91 var_rootmenu,
92 var_format,
93 menu_next,
94 menu_load,
97 /* Capacity 10 000 entries (for example 10k different artists) */
98 #define UNIQBUF_SIZE (64*1024)
99 static long *uniqbuf;
101 #define MAX_TAGS 5
102 #define MAX_MENU_ID_SIZE 32
104 static bool sort_inverse;
107 * "%3d. %s" autoscore title %sort = "inverse" %limit = "100"
109 * valid = true
110 * formatstr = "%-3d. %s"
111 * tags[0] = tag_autoscore
112 * tags[1] = tag_title
113 * tag_count = 2
115 * limit = 100
116 * sort_inverse = true
118 struct display_format {
119 char name[32];
120 struct tagcache_search_clause *clause[TAGCACHE_MAX_CLAUSES];
121 int clause_count;
122 char *formatstr;
123 int group_id;
124 int tags[MAX_TAGS];
125 int tag_count;
127 int limit;
128 int strip;
129 bool sort_inverse;
132 static struct display_format *formats[TAGMENU_MAX_FMTS];
133 static int format_count;
135 struct menu_entry {
136 char name[64];
137 int type;
138 struct search_instruction {
139 char name[64];
140 int tagorder[MAX_TAGS];
141 int tagorder_count;
142 struct tagcache_search_clause *clause[MAX_TAGS][TAGCACHE_MAX_CLAUSES];
143 int format_id[MAX_TAGS];
144 int clause_count[MAX_TAGS];
145 int result_seek[MAX_TAGS];
146 } si;
147 int link;
150 struct menu_root {
151 char title[64];
152 char id[MAX_MENU_ID_SIZE];
153 int itemcount;
154 struct menu_entry *items[TAGMENU_MAX_ITEMS];
157 struct match
159 const char* str;
160 int symbol;
163 /* Statusbar text of the current view. */
164 static char current_title[MAX_TAGS][128];
166 static struct menu_root *menus[TAGMENU_MAX_MENUS];
167 static struct menu_root *menu;
168 static struct search_instruction *csi;
169 static const char *strp;
170 static int menu_count;
171 static int rootmenu;
173 static int current_offset;
174 static int current_entry_count;
176 static struct tree_context *tc;
178 /* a few memory alloc helper */
179 static void* tagtree_alloc(size_t size)
181 return buffer_alloc(size);
184 static void* tagtree_alloc0(size_t size)
186 void* ret = tagtree_alloc(size);
187 memset(ret, 0, size);
188 return ret;
191 static char* tagtree_strdup(const char* buf)
193 size_t len = strlen(buf) + 1;
194 char* dest = tagtree_alloc(len);
195 strcpy(dest, buf);
196 return dest;
199 static int get_token_str(char *buf, int size)
201 /* Find the start. */
202 while (*strp != '"' && *strp != '\0')
203 strp++;
205 if (*strp == '\0' || *(++strp) == '\0')
206 return -1;
208 /* Read the data. */
209 while (*strp != '"' && *strp != '\0' && --size > 0)
210 *(buf++) = *(strp++);
212 *buf = '\0';
213 if (*strp != '"')
214 return -2;
216 strp++;
218 return 0;
221 static int get_tag(int *tag)
223 static const struct match get_tag_match[] =
225 {"album", tag_album},
226 {"artist", tag_artist},
227 {"bitrate", tag_bitrate},
228 {"composer", tag_composer},
229 {"comment", tag_comment},
230 {"albumartist", tag_albumartist},
231 {"ensemble", tag_albumartist},
232 {"grouping", tag_grouping},
233 {"genre", tag_genre},
234 {"length", tag_length},
235 {"Lm", tag_virt_length_min},
236 {"Ls", tag_virt_length_sec},
237 {"Pm", tag_virt_playtime_min},
238 {"Ps", tag_virt_playtime_sec},
239 {"title", tag_title},
240 {"filename", tag_filename},
241 {"basename", tag_virt_basename},
242 {"tracknum", tag_tracknumber},
243 {"discnum", tag_discnumber},
244 {"year", tag_year},
245 {"playcount", tag_playcount},
246 {"rating", tag_rating},
247 {"lastplayed", tag_lastplayed},
248 {"lastoffset", tag_lastoffset},
249 {"commitid", tag_commitid},
250 {"entryage", tag_virt_entryage},
251 {"autoscore", tag_virt_autoscore},
252 {"%sort", var_sorttype},
253 {"%limit", var_limit},
254 {"%strip", var_strip},
255 {"%menu_start", var_menu_start},
256 {"%include", var_include},
257 {"%root_menu", var_rootmenu},
258 {"%format", var_format},
259 {"->", menu_next},
260 {"==>", menu_load}
262 char buf[128];
263 unsigned int i;
265 /* Find the start. */
266 while ((*strp == ' ' || *strp == '>') && *strp != '\0')
267 strp++;
269 if (*strp == '\0' || *strp == '?')
270 return 0;
272 for (i = 0; i < sizeof(buf)-1; i++)
274 if (*strp == '\0' || *strp == ' ')
275 break ;
276 buf[i] = *strp;
277 strp++;
279 buf[i] = '\0';
281 for (i = 0; i < ARRAYLEN(get_tag_match); i++)
283 if (!strcasecmp(buf, get_tag_match[i].str))
285 *tag = get_tag_match[i].symbol;
286 return 1;
290 logf("NO MATCH: %s\n", buf);
291 if (buf[0] == '?')
292 return 0;
294 return -1;
297 static int get_clause(int *condition)
299 static const struct match get_clause_match[] =
301 {"=", clause_is},
302 {"==", clause_is},
303 {"!=", clause_is_not},
304 {">", clause_gt},
305 {">=", clause_gteq},
306 {"<", clause_lt},
307 {"<=", clause_lteq},
308 {"~", clause_contains},
309 {"!~", clause_not_contains},
310 {"^", clause_begins_with},
311 {"!^", clause_not_begins_with},
312 {"$", clause_ends_with},
313 {"!$", clause_not_ends_with},
314 {"@", clause_oneof}
317 char buf[4];
318 unsigned int i;
320 /* Find the start. */
321 while (*strp == ' ' && *strp != '\0')
322 strp++;
324 if (*strp == '\0')
325 return 0;
327 for (i = 0; i < sizeof(buf)-1; i++)
329 if (*strp == '\0' || *strp == ' ')
330 break ;
331 buf[i] = *strp;
332 strp++;
334 buf[i] = '\0';
336 for (i = 0; i < ARRAYLEN(get_clause_match); i++)
338 if (!strcasecmp(buf, get_clause_match[i].str))
340 *condition = get_clause_match[i].symbol;
341 return 1;
345 return 0;
348 static bool read_clause(struct tagcache_search_clause *clause)
350 char buf[SEARCHSTR_SIZE];
351 unsigned int i;
353 if (get_tag(&clause->tag) <= 0)
354 return false;
356 if (get_clause(&clause->type) <= 0)
357 return false;
359 if (get_token_str(buf, sizeof buf) < 0)
360 return false;
362 for (i=0; i<ARRAYLEN(id3_to_search_mapping); i++)
364 if (!strcasecmp(buf, id3_to_search_mapping[i].string))
365 break;
368 if (i<ARRAYLEN(id3_to_search_mapping)) /* runtime search operand found */
370 clause->source = source_runtime+i;
371 clause->str = tagtree_alloc(SEARCHSTR_SIZE);
373 else
375 clause->source = source_constant;
376 clause->str = tagtree_strdup(buf);
379 if (TAGCACHE_IS_NUMERIC(clause->tag))
381 clause->numeric = true;
382 clause->numeric_data = atoi(clause->str);
384 else
385 clause->numeric = false;
387 logf("got clause: %d/%d [%s]", clause->tag, clause->type, clause->str);
389 return true;
392 static bool read_variable(char *buf, int size)
394 int condition;
396 if (!get_clause(&condition))
397 return false;
399 if (condition != clause_is)
400 return false;
402 if (get_token_str(buf, size) < 0)
403 return false;
405 return true;
408 /* "%3d. %s" autoscore title %sort = "inverse" %limit = "100" */
409 static int get_format_str(struct display_format *fmt)
411 int ret;
412 char buf[128];
413 int i;
415 memset(fmt, 0, sizeof(struct display_format));
417 if (get_token_str(fmt->name, sizeof fmt->name) < 0)
418 return -10;
420 /* Determine the group id */
421 fmt->group_id = 0;
422 for (i = 0; i < format_count; i++)
424 if (!strcasecmp(formats[i]->name, fmt->name))
426 fmt->group_id = formats[i]->group_id;
427 break;
430 if (formats[i]->group_id > fmt->group_id)
431 fmt->group_id = formats[i]->group_id;
434 if (i == format_count)
435 fmt->group_id++;
437 logf("format: (%d) %s", fmt->group_id, fmt->name);
439 if (get_token_str(buf, sizeof buf) < 0)
440 return -10;
442 fmt->formatstr = tagtree_strdup(buf);
444 while (fmt->tag_count < MAX_TAGS)
446 ret = get_tag(&fmt->tags[fmt->tag_count]);
447 if (ret < 0)
448 return -11;
450 if (ret == 0)
451 break;
453 switch (fmt->tags[fmt->tag_count]) {
454 case var_sorttype:
455 if (!read_variable(buf, sizeof buf))
456 return -12;
457 if (!strcasecmp("inverse", buf))
458 fmt->sort_inverse = true;
459 break;
461 case var_limit:
462 if (!read_variable(buf, sizeof buf))
463 return -13;
464 fmt->limit = atoi(buf);
465 break;
467 case var_strip:
468 if (!read_variable(buf, sizeof buf))
469 return -14;
470 fmt->strip = atoi(buf);
471 break;
473 default:
474 fmt->tag_count++;
478 return 1;
481 static int add_format(const char *buf)
483 if (format_count >= TAGMENU_MAX_FMTS)
485 logf("too many formats");
486 return -1;
489 strp = buf;
491 if (formats[format_count] == NULL)
492 formats[format_count] = tagtree_alloc0(sizeof(struct display_format));
494 if (get_format_str(formats[format_count]) < 0)
496 logf("get_format_str() parser failed!");
497 memset(formats[format_count], 0, sizeof(struct display_format));
498 return -4;
501 while (*strp != '\0' && *strp != '?')
502 strp++;
504 if (*strp == '?')
506 int clause_count = 0;
507 strp++;
509 while (1)
511 struct tagcache_search_clause *newclause;
513 if (clause_count >= TAGCACHE_MAX_CLAUSES)
515 logf("too many clauses");
516 break;
519 newclause = tagtree_alloc(sizeof(struct tagcache_search_clause));
521 formats[format_count]->clause[clause_count] = newclause;
522 if (!read_clause(newclause))
523 break;
525 clause_count++;
528 formats[format_count]->clause_count = clause_count;
531 format_count++;
533 return 1;
536 static int get_condition(struct search_instruction *inst)
538 struct tagcache_search_clause *new_clause;
539 int clause_count;
540 char buf[128];
542 switch (*strp)
544 case '=':
546 int i;
548 if (get_token_str(buf, sizeof buf) < 0)
549 return -1;
551 for (i = 0; i < format_count; i++)
553 if (!strcasecmp(formats[i]->name, buf))
554 break;
557 if (i == format_count)
559 logf("format not found: %s", buf);
560 return -2;
563 inst->format_id[inst->tagorder_count] = formats[i]->group_id;
564 return 1;
566 case '?':
567 case ' ':
568 case '&':
569 strp++;
570 return 1;
571 case '-':
572 case '\0':
573 return 0;
576 clause_count = inst->clause_count[inst->tagorder_count];
577 if (clause_count >= TAGCACHE_MAX_CLAUSES)
579 logf("Too many clauses");
580 return false;
583 new_clause = tagtree_alloc(sizeof(struct tagcache_search_clause));
584 inst->clause[inst->tagorder_count][clause_count] = new_clause;
586 if (*strp == '|')
588 strp++;
589 new_clause->type = clause_logical_or;
591 else if (!read_clause(new_clause))
592 return -1;
594 inst->clause_count[inst->tagorder_count]++;
596 return 1;
599 /* example search:
600 * "Best" artist ? year >= "2000" & title !^ "crap" & genre = "good genre" \
601 * : album ? year >= "2000" : songs
602 * ^ begins with
603 * * contains
604 * $ ends with
607 static bool parse_search(struct menu_entry *entry, const char *str)
609 int ret;
610 int type;
611 struct search_instruction *inst = &entry->si;
612 char buf[MAX_PATH];
613 int i;
614 struct menu_root *new_menu;
616 strp = str;
618 /* Parse entry name */
619 if (get_token_str(entry->name, sizeof entry->name) < 0)
621 logf("No name found.");
622 return false;
625 /* Parse entry type */
626 if (get_tag(&entry->type) <= 0)
627 return false;
629 if (entry->type == menu_load)
631 if (get_token_str(buf, sizeof buf) < 0)
632 return false;
634 /* Find the matching root menu or "create" it */
635 for (i = 0; i < menu_count; i++)
637 if (!strcasecmp(menus[i]->id, buf))
639 entry->link = i;
640 return true;
644 if (menu_count >= TAGMENU_MAX_MENUS)
646 logf("max menucount reached");
647 return false;
650 /* Allocate a new menu unless link is found. */
651 menus[menu_count] = tagtree_alloc0(sizeof(struct menu_root));
652 new_menu = menus[menu_count];
653 strlcpy(new_menu->id, buf, MAX_MENU_ID_SIZE);
654 entry->link = menu_count;
655 ++menu_count;
657 return true;
660 if (entry->type != menu_next)
661 return false;
663 while (inst->tagorder_count < MAX_TAGS)
665 ret = get_tag(&inst->tagorder[inst->tagorder_count]);
666 if (ret < 0)
668 logf("Parse error #1");
669 logf("%s", strp);
670 return false;
673 if (ret == 0)
674 break ;
676 logf("tag: %d", inst->tagorder[inst->tagorder_count]);
678 while ( (ret = get_condition(inst)) > 0 ) ;
679 if (ret < 0)
680 return false;
682 inst->tagorder_count++;
684 if (get_tag(&type) <= 0 || type != menu_next)
685 break;
688 return true;
691 static int compare(const void *p1, const void *p2)
693 struct tagentry *e1 = (struct tagentry *)p1;
694 struct tagentry *e2 = (struct tagentry *)p2;
696 if (sort_inverse)
697 return strncasecmp(e2->name, e1->name, MAX_PATH);
699 return strncasecmp(e1->name, e2->name, MAX_PATH);
702 static void tagtree_buffer_event(void *data)
704 struct tagcache_search tcs;
705 struct mp3entry *id3 = (struct mp3entry*)data;
707 /* Do not gather data unless proper setting has been enabled. */
708 if (!global_settings.runtimedb && !global_settings.autoresume_enable)
709 return;
711 logf("be:%s", id3->path);
713 while (! tagcache_is_fully_initialized())
714 yield();
716 if (!tagcache_find_index(&tcs, id3->path))
718 logf("tc stat: not found: %s", id3->path);
719 return;
722 if (global_settings.runtimedb)
724 id3->playcount = tagcache_get_numeric(&tcs, tag_playcount);
725 if (!id3->rating)
726 id3->rating = tagcache_get_numeric(&tcs, tag_rating);
727 id3->lastplayed = tagcache_get_numeric(&tcs, tag_lastplayed);
728 id3->score = tagcache_get_numeric(&tcs, tag_virt_autoscore) / 10;
729 id3->playtime = tagcache_get_numeric(&tcs, tag_playtime);
731 logf("-> %ld/%ld", id3->playcount, id3->playtime);
734 #if CONFIG_CODEC == SWCODEC
735 if (global_settings.autoresume_enable)
737 /* Load current file resume offset if not already defined (by
738 another resume mechanism) */
739 if (id3->offset == 0)
741 id3->offset = tagcache_get_numeric(&tcs, tag_lastoffset);
743 logf("tagtree_buffer_event: Set offset for %s to %lX\n",
744 str_or_empty(id3->title), id3->offset);
747 #endif
749 /* Store our tagcache index pointer. */
750 id3->tagcache_idx = tcs.idx_id+1;
752 tagcache_search_finish(&tcs);
755 static void tagtree_track_finish_event(void *data)
757 long lastplayed;
758 long tagcache_idx;
759 struct mp3entry *id3 = (struct mp3entry*)data;
761 /* Do not gather data unless proper setting has been enabled. */
762 if (!global_settings.runtimedb && !global_settings.autoresume_enable)
764 logf("runtimedb gathering and autoresume not enabled");
765 return;
768 tagcache_idx=id3->tagcache_idx;
769 if (!tagcache_idx)
771 logf("No tagcache index pointer found");
772 return;
774 tagcache_idx--;
776 /* Don't process unplayed tracks, or tracks interrupted within the
777 first 15 seconds. */
778 if (id3->elapsed == 0
779 #if CONFIG_CODEC == SWCODEC /* HWCODEC doesn't have automatic_skip */
780 || (id3->elapsed < 15 * 1000 && !audio_automatic_skip())
781 #endif
784 logf("not logging unplayed or skipped track");
785 return;
788 lastplayed = tagcache_increase_serial();
789 if (lastplayed < 0)
791 logf("incorrect tc serial:%ld", lastplayed);
792 return;
795 if (global_settings.runtimedb)
797 long playcount;
798 long playtime;
800 playcount = id3->playcount + 1;
802 /* Ignore the last 15s (crossfade etc.) */
803 playtime = id3->playtime + MIN(id3->length, id3->elapsed + 15 * 1000);
805 logf("ube:%s", id3->path);
806 logf("-> %ld/%ld", playcount, playtime);
807 logf("-> %ld/%ld/%ld", id3->elapsed, id3->length,
808 MIN(id3->length, id3->elapsed + 15 * 1000));
810 /* Queue the updates to the tagcache system. */
811 tagcache_update_numeric(tagcache_idx, tag_playcount, playcount);
812 tagcache_update_numeric(tagcache_idx, tag_playtime, playtime);
813 tagcache_update_numeric(tagcache_idx, tag_lastplayed, lastplayed);
816 #if CONFIG_CODEC == SWCODEC
817 if (global_settings.autoresume_enable)
819 unsigned long offset
820 = audio_automatic_skip() ? 0 : id3->offset;
822 tagcache_update_numeric(tagcache_idx, tag_lastoffset, offset);
824 logf("tagtree_track_finish_event: Save offset for %s: %lX",
825 str_or_empty(id3->title), offset);
827 #endif
830 bool tagtree_export(void)
832 struct tagcache_search tcs;
834 splash(0, str(LANG_CREATING));
835 if (!tagcache_create_changelog(&tcs))
837 splash(HZ*2, ID2P(LANG_FAILED));
840 return false;
843 bool tagtree_import(void)
845 splash(0, ID2P(LANG_WAIT));
846 if (!tagcache_import_changelog())
848 splash(HZ*2, ID2P(LANG_FAILED));
851 return false;
854 static bool parse_menu(const char *filename);
856 static int parse_line(int n, char *buf, void *parameters)
858 char data[256];
859 int variable;
860 static bool read_menu;
861 int i;
862 char *p;
864 (void)parameters;
866 /* Strip possible <CR> at end of line. */
867 p = strchr(buf, '\r');
868 if (p != NULL)
869 *p = '\0';
871 logf("parse:%d/%s", n, buf);
873 /* First line, do initialisation. */
874 if (n == 0)
876 if (strcasecmp(TAGNAVI_VERSION, buf))
878 logf("Version mismatch");
879 return -1;
882 read_menu = false;
885 if (buf[0] == '#')
886 return 0;
888 if (buf[0] == '\0')
890 if (read_menu)
892 /* End the menu */
893 read_menu = false;
895 return 0;
898 if (!read_menu)
900 strp = buf;
901 if (get_tag(&variable) <= 0)
902 return 0;
904 switch (variable)
906 case var_format:
907 if (add_format(strp) < 0)
909 logf("Format add fail: %s", data);
911 break;
913 case var_include:
914 if (get_token_str(data, sizeof(data)) < 0)
916 logf("%%include empty");
917 return 0;
920 if (!parse_menu(data))
922 logf("Load menu fail: %s", data);
924 break;
926 case var_menu_start:
927 if (menu_count >= TAGMENU_MAX_MENUS)
929 logf("max menucount reached");
930 return 0;
933 if (get_token_str(data, sizeof data) < 0)
935 logf("%%menu_start id empty");
936 return 0;
939 menu = NULL;
940 for (i = 0; i < menu_count; i++)
942 if (!strcasecmp(menus[i]->id, data))
944 menu = menus[i];
948 if (menu == NULL)
950 menus[menu_count] = tagtree_alloc0(sizeof(struct menu_root));
951 menu = menus[menu_count];
952 ++menu_count;
953 strlcpy(menu->id, data, MAX_MENU_ID_SIZE);
956 if (get_token_str(menu->title, sizeof(menu->title)) < 0)
958 logf("%%menu_start title empty");
959 return 0;
961 logf("menu: %s", menu->title);
962 read_menu = true;
963 break;
965 case var_rootmenu:
966 /* Only set root menu once. */
967 if (rootmenu >= 0)
968 break;
970 if (get_token_str(data, sizeof(data)) < 0)
972 logf("%%rootmenu empty");
973 return 0;
976 for (i = 0; i < menu_count; i++)
978 if (!strcasecmp(menus[i]->id, data))
980 rootmenu = i;
983 break;
986 return 0;
989 if (menu->itemcount >= TAGMENU_MAX_ITEMS)
991 logf("max itemcount reached");
992 return 0;
995 /* Allocate */
996 if (menu->items[menu->itemcount] == NULL)
997 menu->items[menu->itemcount] = tagtree_alloc0(sizeof(struct menu_entry));
999 if (!parse_search(menu->items[menu->itemcount], buf))
1000 return 0;
1002 menu->itemcount++;
1004 return 0;
1007 static bool parse_menu(const char *filename)
1009 int fd;
1010 char buf[1024];
1012 if (menu_count >= TAGMENU_MAX_MENUS)
1014 logf("max menucount reached");
1015 return false;
1018 fd = open(filename, O_RDONLY);
1019 if (fd < 0)
1021 logf("Search instruction file not found.");
1022 return false;
1025 /* Now read file for real, parsing into si */
1026 fast_readline(fd, buf, sizeof buf, NULL, parse_line);
1027 close(fd);
1029 return true;
1032 void tagtree_init(void)
1034 format_count = 0;
1035 menu_count = 0;
1036 menu = NULL;
1037 rootmenu = -1;
1038 parse_menu(FILE_SEARCH_INSTRUCTIONS);
1040 /* If no root menu is set, assume it's the first single menu
1041 * we have. That shouldn't normally happen. */
1042 if (rootmenu < 0)
1043 rootmenu = 0;
1045 uniqbuf = tagtree_alloc(UNIQBUF_SIZE);
1047 add_event(PLAYBACK_EVENT_TRACK_BUFFER, false, tagtree_buffer_event);
1048 add_event(PLAYBACK_EVENT_TRACK_FINISH, false, tagtree_track_finish_event);
1051 static bool show_search_progress(bool init, int count)
1053 static int last_tick = 0;
1055 /* Don't show splashes for 1/2 second after starting search */
1056 if (init)
1058 last_tick = current_tick + HZ/2;
1059 return true;
1062 /* Update progress every 1/10 of a second */
1063 if (TIME_AFTER(current_tick, last_tick + HZ/10))
1065 splashf(0, str(LANG_PLAYLIST_SEARCH_MSG), count, str(LANG_OFF_ABORT));
1066 if (action_userabort(TIMEOUT_NOBLOCK))
1067 return false;
1068 last_tick = current_tick;
1069 yield();
1072 return true;
1075 static int format_str(struct tagcache_search *tcs, struct display_format *fmt,
1076 char *buf, int buf_size)
1078 char fmtbuf[20];
1079 bool read_format = false;
1080 unsigned fmtbuf_pos = 0;
1081 int parpos = 0;
1082 int buf_pos = 0;
1083 int i;
1085 memset(buf, 0, buf_size);
1086 for (i = 0; fmt->formatstr[i] != '\0'; i++)
1088 if (fmt->formatstr[i] == '%')
1090 read_format = true;
1091 fmtbuf_pos = 0;
1092 if (parpos >= fmt->tag_count)
1094 logf("too many format tags");
1095 return -1;
1099 char formatchar = fmt->formatstr[i];
1101 if (read_format)
1103 fmtbuf[fmtbuf_pos++] = formatchar;
1104 if (fmtbuf_pos >= sizeof fmtbuf)
1106 logf("format parse error");
1107 return -2;
1110 if (formatchar == 's' || formatchar == 'd')
1112 unsigned space_left = buf_size - buf_pos;
1113 char tmpbuf[MAX_PATH];
1114 char *result;
1116 fmtbuf[fmtbuf_pos] = '\0';
1117 read_format = false;
1119 switch (formatchar)
1121 case 's':
1122 if (fmt->tags[parpos] == tcs->type)
1124 result = tcs->result;
1126 else
1128 /* Need to fetch the tag data. */
1129 int tag = fmt->tags[parpos];
1131 if (!tagcache_retrieve(tcs, tcs->idx_id,
1132 (tag == tag_virt_basename ?
1133 tag_filename : tag),
1134 tmpbuf, sizeof tmpbuf))
1136 logf("retrieve failed");
1137 return -3;
1140 if (tag == tag_virt_basename
1141 && (result = strrchr(tmpbuf, '/')) != NULL)
1143 result++;
1145 else
1146 result = tmpbuf;
1148 buf_pos +=
1149 snprintf(&buf[buf_pos], space_left, fmtbuf, result);
1150 break;
1152 case 'd':
1153 buf_pos +=
1154 snprintf(&buf[buf_pos], space_left, fmtbuf,
1155 tagcache_get_numeric(tcs, fmt->tags[parpos]));
1158 parpos++;
1161 else
1162 buf[buf_pos++] = formatchar;
1164 if (buf_pos >= buf_size - 1) /* need at least one more byte for \0 */
1166 logf("buffer overflow");
1167 return -4;
1171 buf[buf_pos++] = '\0';
1173 return 0;
1176 static int retrieve_entries(struct tree_context *c, int offset, bool init)
1178 struct tagcache_search tcs;
1179 struct tagentry *dptr = c->cache.entries;
1180 struct display_format *fmt;
1181 int i;
1182 int namebufused = 0;
1183 int total_count = 0;
1184 int special_entry_count = 0;
1185 int level = c->currextra;
1186 int tag;
1187 bool sort = false;
1188 int sort_limit;
1189 int strip;
1191 /* Show search progress straight away if the disk needs to spin up,
1192 otherwise show it after the normal 1/2 second delay */
1193 show_search_progress(
1194 #ifdef HAVE_DISK_STORAGE
1195 storage_disk_is_active()
1196 #else
1197 true
1198 #endif
1199 , 0);
1201 if (c->currtable == ALLSUBENTRIES)
1203 tag = tag_title;
1204 level--;
1206 else
1207 tag = csi->tagorder[level];
1209 if (!tagcache_search(&tcs, tag))
1210 return -1;
1212 /* Prevent duplicate entries in the search list. */
1213 tagcache_search_set_uniqbuf(&tcs, uniqbuf, UNIQBUF_SIZE);
1215 if (level || csi->clause_count[0] || TAGCACHE_IS_NUMERIC(tag))
1216 sort = true;
1218 for (i = 0; i < level; i++)
1220 if (TAGCACHE_IS_NUMERIC(csi->tagorder[i]))
1222 static struct tagcache_search_clause cc;
1224 memset(&cc, 0, sizeof(struct tagcache_search_clause));
1225 cc.tag = csi->tagorder[i];
1226 cc.type = clause_is;
1227 cc.numeric = true;
1228 cc.numeric_data = csi->result_seek[i];
1229 tagcache_search_add_clause(&tcs, &cc);
1231 else
1233 tagcache_search_add_filter(&tcs, csi->tagorder[i],
1234 csi->result_seek[i]);
1238 for (i = 0; i <= level; i++)
1240 int j;
1242 for (j = 0; j < csi->clause_count[i]; j++)
1243 tagcache_search_add_clause(&tcs, csi->clause[i][j]);
1246 current_offset = offset;
1247 current_entry_count = 0;
1248 c->dirfull = false;
1250 fmt = NULL;
1251 for (i = 0; i < format_count; i++)
1253 if (formats[i]->group_id == csi->format_id[level])
1254 fmt = formats[i];
1257 if (fmt)
1259 sort_inverse = fmt->sort_inverse;
1260 sort_limit = fmt->limit;
1261 strip = fmt->strip;
1262 sort = true;
1264 else
1266 sort_inverse = false;
1267 sort_limit = 0;
1268 strip = 0;
1271 if (tag != tag_title && tag != tag_filename)
1273 if (offset == 0)
1275 dptr->newtable = ALLSUBENTRIES;
1276 dptr->name = str(LANG_TAGNAVI_ALL_TRACKS);
1277 dptr++;
1278 current_entry_count++;
1279 special_entry_count++;
1281 if (offset <= 1)
1283 dptr->newtable = NAVIBROWSE;
1284 dptr->name = str(LANG_TAGNAVI_RANDOM);
1285 dptr->extraseek = -1;
1286 dptr++;
1287 current_entry_count++;
1288 special_entry_count++;
1291 total_count += 2;
1294 while (tagcache_get_next(&tcs))
1296 if (total_count++ < offset)
1297 continue;
1299 dptr->newtable = NAVIBROWSE;
1300 if (tag == tag_title || tag == tag_filename)
1302 dptr->newtable = PLAYTRACK;
1303 dptr->extraseek = tcs.idx_id;
1305 else
1306 dptr->extraseek = tcs.result_seek;
1308 fmt = NULL;
1309 /* Check the format */
1310 for (i = 0; i < format_count; i++)
1312 if (formats[i]->group_id != csi->format_id[level])
1313 continue;
1315 if (tagcache_check_clauses(&tcs, formats[i]->clause,
1316 formats[i]->clause_count))
1318 fmt = formats[i];
1319 break;
1323 if (strcmp(tcs.result, UNTAGGED) == 0)
1325 tcs.result = str(LANG_TAGNAVI_UNTAGGED);
1326 tcs.result_len = strlen(tcs.result);
1327 tcs.ramresult = true;
1330 if (!tcs.ramresult || fmt)
1332 dptr->name = &c->cache.name_buffer[namebufused];
1334 if (fmt)
1336 int ret = format_str(&tcs, fmt, dptr->name,
1337 c->cache.name_buffer_size - namebufused);
1338 if (ret == -4) /* buffer full */
1340 logf("chunk mode #2: %d", current_entry_count);
1341 c->dirfull = true;
1342 sort = false;
1343 break ;
1345 else if (ret < 0)
1347 logf("format_str() failed");
1348 tagcache_search_finish(&tcs);
1349 return 0;
1351 else
1352 namebufused += strlen(dptr->name)+1;
1354 else
1356 namebufused += tcs.result_len;
1357 if (namebufused < c->cache.name_buffer_size)
1358 strcpy(dptr->name, tcs.result);
1359 else
1361 logf("chunk mode #2a: %d", current_entry_count);
1362 c->dirfull = true;
1363 sort = false;
1364 break ;
1368 else
1369 dptr->name = tcs.result;
1371 dptr++;
1372 current_entry_count++;
1374 if (current_entry_count >= c->cache.max_entries)
1376 logf("chunk mode #3: %d", current_entry_count);
1377 c->dirfull = true;
1378 sort = false;
1379 break ;
1382 if (init && !tcs.ramsearch)
1384 if (!show_search_progress(false, total_count))
1385 { /* user aborted */
1386 tagcache_search_finish(&tcs);
1387 return current_entry_count;
1392 if (sort)
1394 int entry_size = sizeof(struct tagentry);
1395 qsort(c->cache.entries + special_entry_count * entry_size,
1396 current_entry_count - special_entry_count,
1397 entry_size, compare);
1400 if (!init)
1402 tagcache_search_finish(&tcs);
1403 return current_entry_count;
1406 while (tagcache_get_next(&tcs))
1408 if (!tcs.ramsearch)
1410 if (!show_search_progress(false, total_count))
1411 break;
1413 total_count++;
1416 tagcache_search_finish(&tcs);
1418 if (!sort && (sort_inverse || sort_limit))
1420 splashf(HZ*4, ID2P(LANG_SHOWDIR_BUFFER_FULL), total_count);
1421 logf("Too small dir buffer");
1422 return 0;
1425 if (sort_limit)
1426 total_count = MIN(total_count, sort_limit);
1428 if (strip)
1430 dptr = c->cache.entries;
1431 for (i = special_entry_count; i < current_entry_count; i++, dptr++)
1433 int len = strlen(dptr->name);
1435 if (len < strip)
1436 continue;
1438 dptr->name = &dptr->name[strip];
1442 return total_count;
1446 static int load_root(struct tree_context *c)
1448 struct tagentry *dptr = c->cache.entries;
1449 int i;
1451 tc = c;
1452 c->currtable = ROOT;
1453 if (c->dirlevel == 0)
1454 c->currextra = rootmenu;
1456 menu = menus[c->currextra];
1457 if (menu == NULL)
1458 return 0;
1460 for (i = 0; i < menu->itemcount; i++)
1462 dptr->name = menu->items[i]->name;
1463 switch (menu->items[i]->type)
1465 case menu_next:
1466 dptr->newtable = NAVIBROWSE;
1467 dptr->extraseek = i;
1468 break;
1470 case menu_load:
1471 dptr->newtable = ROOT;
1472 dptr->extraseek = menu->items[i]->link;
1473 break;
1476 dptr++;
1479 current_offset = 0;
1480 current_entry_count = i;
1482 return i;
1485 int tagtree_load(struct tree_context* c)
1487 int count;
1488 int table = c->currtable;
1490 c->dirsindir = 0;
1492 if (!table)
1494 c->dirfull = false;
1495 table = ROOT;
1496 c->currtable = table;
1497 c->currextra = rootmenu;
1500 switch (table)
1502 case ROOT:
1503 count = load_root(c);
1504 break;
1506 case ALLSUBENTRIES:
1507 case NAVIBROWSE:
1508 logf("navibrowse...");
1509 cpu_boost(true);
1510 count = retrieve_entries(c, 0, true);
1511 cpu_boost(false);
1512 break;
1514 default:
1515 logf("Unsupported table %d\n", table);
1516 return -1;
1519 if (count < 0)
1521 c->dirlevel = 0;
1522 count = load_root(c);
1523 splash(HZ, str(LANG_TAGCACHE_BUSY));
1526 /* The _total_ numer of entries available. */
1527 c->dirlength = c->filesindir = count;
1529 return count;
1532 int tagtree_enter(struct tree_context* c)
1534 int rc = 0;
1535 struct tagentry *dptr;
1536 struct mp3entry *id3;
1537 int newextra;
1538 int seek;
1539 int source;
1541 dptr = tagtree_get_entry(c, c->selected_item);
1543 c->dirfull = false;
1544 seek = dptr->extraseek;
1545 if (seek == -1)
1547 if(c->filesindir<=2)
1548 return 0;
1549 srand(current_tick);
1550 dptr = (tagtree_get_entry(c, 2+(rand() % (c->filesindir-2))));
1551 seek = dptr->extraseek;
1553 newextra = dptr->newtable;
1555 if (c->dirlevel >= MAX_DIR_LEVELS)
1556 return 0;
1558 c->selected_item_history[c->dirlevel]=c->selected_item;
1559 c->table_history[c->dirlevel] = c->currtable;
1560 c->extra_history[c->dirlevel] = c->currextra;
1561 c->pos_history[c->dirlevel] = c->firstpos;
1562 c->dirlevel++;
1564 switch (c->currtable) {
1565 case ROOT:
1566 c->currextra = newextra;
1568 if (newextra == ROOT)
1570 menu = menus[seek];
1571 c->currextra = seek;
1574 else if (newextra == NAVIBROWSE)
1576 int i, j;
1578 csi = &menu->items[seek]->si;
1579 c->currextra = 0;
1581 strlcpy(current_title[c->currextra], dptr->name,
1582 sizeof(current_title[0]));
1584 /* Read input as necessary. */
1585 for (i = 0; i < csi->tagorder_count; i++)
1587 for (j = 0; j < csi->clause_count[i]; j++)
1589 char* searchstring;
1591 if (csi->clause[i][j]->type == clause_logical_or)
1592 continue;
1594 source = csi->clause[i][j]->source;
1596 if (source == source_constant)
1597 continue;
1599 searchstring=csi->clause[i][j]->str;
1600 *searchstring = '\0';
1602 id3 = audio_current_track();
1604 if (source == source_current_path && id3)
1606 char *e;
1607 strlcpy(searchstring, id3->path, SEARCHSTR_SIZE);
1608 e = strrchr(searchstring, '/');
1609 if (e)
1610 *e = '\0';
1612 else if (source > source_runtime && id3)
1615 int k = source-source_runtime;
1616 int offset = id3_to_search_mapping[k].id3_offset;
1617 char **src = (char**)((char*)id3 + offset);
1618 if (*src)
1620 strlcpy(searchstring, *src, SEARCHSTR_SIZE);
1623 else
1625 rc = kbd_input(searchstring, SEARCHSTR_SIZE);
1626 if (rc < 0 || !searchstring[0])
1628 tagtree_exit(c);
1629 return 0;
1631 if (csi->clause[i][j]->numeric)
1632 csi->clause[i][j]->numeric_data = atoi(searchstring);
1639 c->currtable = newextra;
1641 break;
1643 case NAVIBROWSE:
1644 case ALLSUBENTRIES:
1645 if (newextra == PLAYTRACK)
1647 if (global_settings.party_mode && audio_status()) {
1648 splash(HZ, ID2P(LANG_PARTY_MODE));
1649 break;
1651 c->dirlevel--;
1652 /* about to create a new current playlist...
1653 allow user to cancel the operation */
1654 if (!warn_on_pl_erase())
1655 break;
1656 if (tagtree_play_folder(c) >= 0)
1657 rc = 2;
1658 break;
1661 c->currtable = newextra;
1662 csi->result_seek[c->currextra] = seek;
1663 if (c->currextra < csi->tagorder_count-1)
1664 c->currextra++;
1665 else
1666 c->dirlevel--;
1668 /* Update the statusbar title */
1669 strlcpy(current_title[c->currextra], dptr->name,
1670 sizeof(current_title[0]));
1671 break;
1673 default:
1674 c->dirlevel--;
1675 break;
1678 c->selected_item=0;
1679 gui_synclist_select_item(&tree_lists, c->selected_item);
1681 return rc;
1684 void tagtree_exit(struct tree_context* c)
1686 c->dirfull = false;
1687 if (c->dirlevel > 0)
1688 c->dirlevel--;
1689 c->selected_item=c->selected_item_history[c->dirlevel];
1690 gui_synclist_select_item(&tree_lists, c->selected_item);
1691 c->currtable = c->table_history[c->dirlevel];
1692 c->currextra = c->extra_history[c->dirlevel];
1693 c->firstpos = c->pos_history[c->dirlevel];
1696 int tagtree_get_filename(struct tree_context* c, char *buf, int buflen)
1698 struct tagcache_search tcs;
1699 struct tagentry *entry;
1701 entry = tagtree_get_entry(c, c->selected_item);
1703 if (!tagcache_search(&tcs, tag_filename))
1704 return -1;
1706 if (!tagcache_retrieve(&tcs, entry->extraseek, tcs.type, buf, buflen))
1708 tagcache_search_finish(&tcs);
1709 return -2;
1712 tagcache_search_finish(&tcs);
1714 return 0;
1717 static bool insert_all_playlist(struct tree_context *c, int position, bool queue)
1719 struct tagcache_search tcs;
1720 int i;
1721 char buf[MAX_PATH];
1722 int from, to, direction;
1723 int files_left = c->filesindir;
1725 cpu_boost(true);
1726 if (!tagcache_search(&tcs, tag_filename))
1728 splash(HZ, ID2P(LANG_TAGCACHE_BUSY));
1729 cpu_boost(false);
1730 return false;
1733 if (position == PLAYLIST_REPLACE)
1735 if (playlist_remove_all_tracks(NULL) == 0)
1736 position = PLAYLIST_INSERT_LAST;
1737 else
1739 cpu_boost(false);
1740 return false;
1744 if (position == PLAYLIST_INSERT_FIRST)
1746 from = c->filesindir - 1;
1747 to = -1;
1748 direction = -1;
1750 else
1752 from = 0;
1753 to = c->filesindir;
1754 direction = 1;
1757 for (i = from; i != to; i += direction)
1759 /* Count back to zero */
1760 if (!show_search_progress(false, files_left--))
1761 break;
1763 if (!tagcache_retrieve(&tcs, tagtree_get_entry(c, i)->extraseek,
1764 tcs.type, buf, sizeof buf))
1766 continue;
1769 if (playlist_insert_track(NULL, buf, position, queue, false) < 0)
1771 logf("playlist_insert_track failed");
1772 break;
1774 yield();
1776 playlist_sync(NULL);
1777 tagcache_search_finish(&tcs);
1778 cpu_boost(false);
1780 return true;
1783 bool tagtree_insert_selection_playlist(int position, bool queue)
1785 struct tagentry *dptr;
1786 char buf[MAX_PATH];
1787 int dirlevel = tc->dirlevel;
1789 show_search_progress(
1790 #ifdef HAVE_DISK_STORAGE
1791 storage_disk_is_active()
1792 #else
1793 true
1794 #endif
1795 , 0);
1798 /* We need to set the table to allsubentries. */
1799 dptr = tagtree_get_entry(tc, tc->selected_item);
1801 /* Insert a single track? */
1802 if (dptr->newtable == PLAYTRACK)
1804 if (tagtree_get_filename(tc, buf, sizeof buf) < 0)
1806 logf("tagtree_get_filename failed");
1807 return false;
1809 playlist_insert_track(NULL, buf, position, queue, true);
1811 return true;
1814 if (dptr->newtable == NAVIBROWSE)
1816 tagtree_enter(tc);
1817 tagtree_load(tc);
1818 dptr = tagtree_get_entry(tc, tc->selected_item);
1820 else if (dptr->newtable != ALLSUBENTRIES)
1822 logf("unsupported table: %d", dptr->newtable);
1823 return false;
1826 /* Now the current table should be allsubentries. */
1827 if (dptr->newtable != PLAYTRACK)
1829 tagtree_enter(tc);
1830 tagtree_load(tc);
1831 dptr = tagtree_get_entry(tc, tc->selected_item);
1833 /* And now the newtable should be playtrack. */
1834 if (dptr->newtable != PLAYTRACK)
1836 logf("newtable: %d !!", dptr->newtable);
1837 tc->dirlevel = dirlevel;
1838 return false;
1842 if (tc->filesindir <= 0)
1843 splash(HZ, ID2P(LANG_END_PLAYLIST));
1844 else
1846 logf("insert_all_playlist");
1847 if (!insert_all_playlist(tc, position, queue))
1848 splash(HZ*2, ID2P(LANG_FAILED));
1851 /* Finally return the dirlevel to its original value. */
1852 while (tc->dirlevel > dirlevel)
1853 tagtree_exit(tc);
1854 tagtree_load(tc);
1856 return true;
1859 static int tagtree_play_folder(struct tree_context* c)
1861 if (playlist_create(NULL, NULL) < 0)
1863 logf("Failed creating playlist\n");
1864 return -1;
1867 if (!insert_all_playlist(c, PLAYLIST_INSERT_LAST, false))
1868 return -2;
1870 if (global_settings.playlist_shuffle)
1871 c->selected_item = playlist_shuffle(current_tick, c->selected_item);
1872 if (!global_settings.play_selected)
1873 c->selected_item = 0;
1874 gui_synclist_select_item(&tree_lists, c->selected_item);
1876 playlist_start(c->selected_item,0);
1877 playlist_get_current()->num_inserted_tracks = 0; /* make warn on playlist erase work */
1878 return 0;
1881 struct tagentry* tagtree_get_entry(struct tree_context *c, int id)
1883 struct tagentry *entry = (struct tagentry *)c->cache.entries;
1884 int realid = id - current_offset;
1886 /* Load the next chunk if necessary. */
1887 if (realid >= current_entry_count || realid < 0)
1889 cpu_boost(true);
1890 if (retrieve_entries(c, MAX(0, id - (current_entry_count / 2)),
1891 false) < 0)
1893 logf("retrieve failed");
1894 cpu_boost(false);
1895 return NULL;
1897 realid = id - current_offset;
1898 cpu_boost(false);
1901 return &entry[realid];
1904 char *tagtree_get_title(struct tree_context* c)
1906 switch (c->currtable)
1908 case ROOT:
1909 return menu->title;
1911 case NAVIBROWSE:
1912 case ALLSUBENTRIES:
1913 return current_title[c->currextra];
1916 return "?";
1919 int tagtree_get_attr(struct tree_context* c)
1921 int attr = -1;
1922 switch (c->currtable)
1924 case NAVIBROWSE:
1925 if (csi->tagorder[c->currextra] == tag_title)
1926 attr = FILE_ATTR_AUDIO;
1927 else
1928 attr = ATTR_DIRECTORY;
1929 break;
1931 case ALLSUBENTRIES:
1932 attr = FILE_ATTR_AUDIO;
1933 break;
1935 default:
1936 attr = ATTR_DIRECTORY;
1937 break;
1940 return attr;
1943 int tagtree_get_icon(struct tree_context* c)
1945 int icon = Icon_Folder;
1947 if (tagtree_get_attr(c) == FILE_ATTR_AUDIO)
1948 icon = Icon_Audio;
1950 return icon;