Fix oops in r30242. I didn't want to change/reduce the buffer size.
[kugel-rb.git] / apps / tagtree.c
blob0b16695ad16d629c36d4a00eeaf1881062de117f
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 if (read_format)
1101 char formatchar = fmt->formatstr[i];
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[space_left + 1];
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, space_left))
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 snprintf(&buf[buf_pos], space_left, fmtbuf, result);
1149 break;
1151 case 'd':
1152 snprintf(&buf[buf_pos], space_left, fmtbuf,
1153 tagcache_get_numeric(tcs, fmt->tags[parpos]));
1156 buf_pos += strlen(&buf[buf_pos]);
1157 parpos++;
1160 else
1161 buf[buf_pos++] = fmt->formatstr[i];
1163 if (buf_pos - 1 >= buf_size)
1165 logf("buffer overflow");
1166 return -4;
1170 buf[buf_pos++] = '\0';
1172 return 0;
1175 static int retrieve_entries(struct tree_context *c, int offset, bool init)
1177 struct tagcache_search tcs;
1178 struct tagentry *dptr = c->cache.entries;
1179 struct display_format *fmt;
1180 int i;
1181 int namebufused = 0;
1182 int total_count = 0;
1183 int special_entry_count = 0;
1184 int level = c->currextra;
1185 int tag;
1186 bool sort = false;
1187 int sort_limit;
1188 int strip;
1190 /* Show search progress straight away if the disk needs to spin up,
1191 otherwise show it after the normal 1/2 second delay */
1192 show_search_progress(
1193 #ifdef HAVE_DISK_STORAGE
1194 storage_disk_is_active()
1195 #else
1196 true
1197 #endif
1198 , 0);
1200 if (c->currtable == ALLSUBENTRIES)
1202 tag = tag_title;
1203 level--;
1205 else
1206 tag = csi->tagorder[level];
1208 if (!tagcache_search(&tcs, tag))
1209 return -1;
1211 /* Prevent duplicate entries in the search list. */
1212 tagcache_search_set_uniqbuf(&tcs, uniqbuf, UNIQBUF_SIZE);
1214 if (level || csi->clause_count[0] || TAGCACHE_IS_NUMERIC(tag))
1215 sort = true;
1217 for (i = 0; i < level; i++)
1219 if (TAGCACHE_IS_NUMERIC(csi->tagorder[i]))
1221 static struct tagcache_search_clause cc;
1223 memset(&cc, 0, sizeof(struct tagcache_search_clause));
1224 cc.tag = csi->tagorder[i];
1225 cc.type = clause_is;
1226 cc.numeric = true;
1227 cc.numeric_data = csi->result_seek[i];
1228 tagcache_search_add_clause(&tcs, &cc);
1230 else
1232 tagcache_search_add_filter(&tcs, csi->tagorder[i],
1233 csi->result_seek[i]);
1237 for (i = 0; i <= level; i++)
1239 int j;
1241 for (j = 0; j < csi->clause_count[i]; j++)
1242 tagcache_search_add_clause(&tcs, csi->clause[i][j]);
1245 current_offset = offset;
1246 current_entry_count = 0;
1247 c->dirfull = false;
1249 fmt = NULL;
1250 for (i = 0; i < format_count; i++)
1252 if (formats[i]->group_id == csi->format_id[level])
1253 fmt = formats[i];
1256 if (fmt)
1258 sort_inverse = fmt->sort_inverse;
1259 sort_limit = fmt->limit;
1260 strip = fmt->strip;
1261 sort = true;
1263 else
1265 sort_inverse = false;
1266 sort_limit = 0;
1267 strip = 0;
1270 if (tag != tag_title && tag != tag_filename)
1272 if (offset == 0)
1274 dptr->newtable = ALLSUBENTRIES;
1275 dptr->name = str(LANG_TAGNAVI_ALL_TRACKS);
1276 dptr++;
1277 current_entry_count++;
1279 if (offset <= 1)
1281 dptr->newtable = NAVIBROWSE;
1282 dptr->name = str(LANG_TAGNAVI_RANDOM);
1283 dptr->extraseek = -1;
1284 dptr++;
1285 current_entry_count++;
1287 special_entry_count+=2;
1290 total_count += special_entry_count;
1292 while (tagcache_get_next(&tcs))
1294 if (total_count++ < offset)
1295 continue;
1297 dptr->newtable = NAVIBROWSE;
1298 if (tag == tag_title || tag == tag_filename)
1300 dptr->newtable = PLAYTRACK;
1301 dptr->extraseek = tcs.idx_id;
1303 else
1304 dptr->extraseek = tcs.result_seek;
1306 fmt = NULL;
1307 /* Check the format */
1308 for (i = 0; i < format_count; i++)
1310 if (formats[i]->group_id != csi->format_id[level])
1311 continue;
1313 if (tagcache_check_clauses(&tcs, formats[i]->clause,
1314 formats[i]->clause_count))
1316 fmt = formats[i];
1317 break;
1321 if (strcmp(tcs.result, UNTAGGED) == 0)
1323 tcs.result = str(LANG_TAGNAVI_UNTAGGED);
1324 tcs.result_len = strlen(tcs.result);
1325 tcs.ramresult = true;
1328 if (!tcs.ramresult || fmt)
1330 char buf[MAX_PATH];
1332 if (fmt)
1334 if (format_str(&tcs, fmt, buf, sizeof buf) < 0)
1336 logf("format_str() failed");
1337 tagcache_search_finish(&tcs);
1338 return 0;
1342 dptr->name = &c->cache.name_buffer[namebufused];
1343 if (fmt)
1344 namebufused += strlen(buf)+1;
1345 else
1346 namebufused += tcs.result_len;
1348 if (namebufused >= c->cache.name_buffer_size)
1350 logf("chunk mode #2: %d", current_entry_count);
1351 c->dirfull = true;
1352 sort = false;
1353 break ;
1355 if (fmt)
1356 strcpy(dptr->name, buf);
1357 else
1358 strcpy(dptr->name, tcs.result);
1360 else
1361 dptr->name = tcs.result;
1363 dptr++;
1364 current_entry_count++;
1366 if (current_entry_count >= c->cache.max_entries)
1368 logf("chunk mode #3: %d", current_entry_count);
1369 c->dirfull = true;
1370 sort = false;
1371 break ;
1374 if (init && !tcs.ramsearch)
1376 if (!show_search_progress(false, total_count))
1377 { /* user aborted */
1378 tagcache_search_finish(&tcs);
1379 return current_entry_count;
1384 if (sort)
1386 int entry_size = sizeof(struct tagentry);
1387 qsort(c->cache.entries + special_entry_count * entry_size,
1388 current_entry_count - special_entry_count,
1389 entry_size, compare);
1392 if (!init)
1394 tagcache_search_finish(&tcs);
1395 return current_entry_count;
1398 while (tagcache_get_next(&tcs))
1400 if (!tcs.ramsearch)
1402 if (!show_search_progress(false, total_count))
1403 break;
1405 total_count++;
1408 tagcache_search_finish(&tcs);
1410 if (!sort && (sort_inverse || sort_limit))
1412 splashf(HZ*4, ID2P(LANG_SHOWDIR_BUFFER_FULL), total_count);
1413 logf("Too small dir buffer");
1414 return 0;
1417 if (sort_limit)
1418 total_count = MIN(total_count, sort_limit);
1420 if (strip)
1422 dptr = c->cache.entries;
1423 for (i = 0; i < total_count; i++, dptr++)
1425 int len = strlen(dptr->name);
1427 if (len < strip)
1428 continue;
1430 dptr->name = &dptr->name[strip];
1434 return total_count;
1438 static int load_root(struct tree_context *c)
1440 struct tagentry *dptr = c->cache.entries;
1441 int i;
1443 tc = c;
1444 c->currtable = ROOT;
1445 if (c->dirlevel == 0)
1446 c->currextra = rootmenu;
1448 menu = menus[c->currextra];
1449 if (menu == NULL)
1450 return 0;
1452 for (i = 0; i < menu->itemcount; i++)
1454 dptr->name = menu->items[i]->name;
1455 switch (menu->items[i]->type)
1457 case menu_next:
1458 dptr->newtable = NAVIBROWSE;
1459 dptr->extraseek = i;
1460 break;
1462 case menu_load:
1463 dptr->newtable = ROOT;
1464 dptr->extraseek = menu->items[i]->link;
1465 break;
1468 dptr++;
1471 current_offset = 0;
1472 current_entry_count = i;
1474 return i;
1477 int tagtree_load(struct tree_context* c)
1479 int count;
1480 int table = c->currtable;
1482 c->dirsindir = 0;
1484 if (!table)
1486 c->dirfull = false;
1487 table = ROOT;
1488 c->currtable = table;
1489 c->currextra = rootmenu;
1492 switch (table)
1494 case ROOT:
1495 count = load_root(c);
1496 break;
1498 case ALLSUBENTRIES:
1499 case NAVIBROWSE:
1500 logf("navibrowse...");
1501 cpu_boost(true);
1502 count = retrieve_entries(c, 0, true);
1503 cpu_boost(false);
1504 break;
1506 default:
1507 logf("Unsupported table %d\n", table);
1508 return -1;
1511 if (count < 0)
1513 c->dirlevel = 0;
1514 count = load_root(c);
1515 splash(HZ, str(LANG_TAGCACHE_BUSY));
1518 /* The _total_ numer of entries available. */
1519 c->dirlength = c->filesindir = count;
1521 return count;
1524 int tagtree_enter(struct tree_context* c)
1526 int rc = 0;
1527 struct tagentry *dptr;
1528 struct mp3entry *id3;
1529 int newextra;
1530 int seek;
1531 int source;
1533 dptr = tagtree_get_entry(c, c->selected_item);
1535 c->dirfull = false;
1536 seek = dptr->extraseek;
1537 if (seek == -1)
1539 if(c->filesindir<=2)
1540 return 0;
1541 srand(current_tick);
1542 dptr = (tagtree_get_entry(c, 2+(rand() % (c->filesindir-2))));
1543 seek = dptr->extraseek;
1545 newextra = dptr->newtable;
1547 if (c->dirlevel >= MAX_DIR_LEVELS)
1548 return 0;
1550 c->selected_item_history[c->dirlevel]=c->selected_item;
1551 c->table_history[c->dirlevel] = c->currtable;
1552 c->extra_history[c->dirlevel] = c->currextra;
1553 c->pos_history[c->dirlevel] = c->firstpos;
1554 c->dirlevel++;
1556 switch (c->currtable) {
1557 case ROOT:
1558 c->currextra = newextra;
1560 if (newextra == ROOT)
1562 menu = menus[seek];
1563 c->currextra = seek;
1566 else if (newextra == NAVIBROWSE)
1568 int i, j;
1570 csi = &menu->items[seek]->si;
1571 c->currextra = 0;
1573 strlcpy(current_title[c->currextra], dptr->name,
1574 sizeof(current_title[0]));
1576 /* Read input as necessary. */
1577 for (i = 0; i < csi->tagorder_count; i++)
1579 for (j = 0; j < csi->clause_count[i]; j++)
1581 char* searchstring;
1583 if (csi->clause[i][j]->type == clause_logical_or)
1584 continue;
1586 source = csi->clause[i][j]->source;
1588 if (source == source_constant)
1589 continue;
1591 searchstring=csi->clause[i][j]->str;
1592 *searchstring = '\0';
1594 id3 = audio_current_track();
1596 if (source == source_current_path && id3)
1598 char *e;
1599 strlcpy(searchstring, id3->path, SEARCHSTR_SIZE);
1600 e = strrchr(searchstring, '/');
1601 if (e)
1602 *e = '\0';
1604 else if (source > source_runtime && id3)
1607 int k = source-source_runtime;
1608 int offset = id3_to_search_mapping[k].id3_offset;
1609 char **src = (char**)((char*)id3 + offset);
1610 if (*src)
1612 strlcpy(searchstring, *src, SEARCHSTR_SIZE);
1615 else
1617 rc = kbd_input(searchstring, SEARCHSTR_SIZE);
1618 if (rc < 0 || !searchstring[0])
1620 tagtree_exit(c);
1621 return 0;
1623 if (csi->clause[i][j]->numeric)
1624 csi->clause[i][j]->numeric_data = atoi(searchstring);
1631 c->currtable = newextra;
1633 break;
1635 case NAVIBROWSE:
1636 case ALLSUBENTRIES:
1637 if (newextra == PLAYTRACK)
1639 if (global_settings.party_mode && audio_status()) {
1640 splash(HZ, ID2P(LANG_PARTY_MODE));
1641 break;
1643 c->dirlevel--;
1644 /* about to create a new current playlist...
1645 allow user to cancel the operation */
1646 if (!warn_on_pl_erase())
1647 break;
1648 if (tagtree_play_folder(c) >= 0)
1649 rc = 2;
1650 break;
1653 c->currtable = newextra;
1654 csi->result_seek[c->currextra] = seek;
1655 if (c->currextra < csi->tagorder_count-1)
1656 c->currextra++;
1657 else
1658 c->dirlevel--;
1660 /* Update the statusbar title */
1661 strlcpy(current_title[c->currextra], dptr->name,
1662 sizeof(current_title[0]));
1663 break;
1665 default:
1666 c->dirlevel--;
1667 break;
1670 c->selected_item=0;
1671 gui_synclist_select_item(&tree_lists, c->selected_item);
1673 return rc;
1676 void tagtree_exit(struct tree_context* c)
1678 c->dirfull = false;
1679 if (c->dirlevel > 0)
1680 c->dirlevel--;
1681 c->selected_item=c->selected_item_history[c->dirlevel];
1682 gui_synclist_select_item(&tree_lists, c->selected_item);
1683 c->currtable = c->table_history[c->dirlevel];
1684 c->currextra = c->extra_history[c->dirlevel];
1685 c->firstpos = c->pos_history[c->dirlevel];
1688 int tagtree_get_filename(struct tree_context* c, char *buf, int buflen)
1690 struct tagcache_search tcs;
1691 struct tagentry *entry;
1693 entry = tagtree_get_entry(c, c->selected_item);
1695 if (!tagcache_search(&tcs, tag_filename))
1696 return -1;
1698 if (!tagcache_retrieve(&tcs, entry->extraseek, tcs.type, buf, buflen))
1700 tagcache_search_finish(&tcs);
1701 return -2;
1704 tagcache_search_finish(&tcs);
1706 return 0;
1709 static bool insert_all_playlist(struct tree_context *c, int position, bool queue)
1711 struct tagcache_search tcs;
1712 int i;
1713 char buf[MAX_PATH];
1714 int from, to, direction;
1715 int files_left = c->filesindir;
1717 cpu_boost(true);
1718 if (!tagcache_search(&tcs, tag_filename))
1720 splash(HZ, ID2P(LANG_TAGCACHE_BUSY));
1721 cpu_boost(false);
1722 return false;
1725 if (position == PLAYLIST_REPLACE)
1727 if (playlist_remove_all_tracks(NULL) == 0)
1728 position = PLAYLIST_INSERT_LAST;
1729 else
1731 cpu_boost(false);
1732 return false;
1736 if (position == PLAYLIST_INSERT_FIRST)
1738 from = c->filesindir - 1;
1739 to = -1;
1740 direction = -1;
1742 else
1744 from = 0;
1745 to = c->filesindir;
1746 direction = 1;
1749 for (i = from; i != to; i += direction)
1751 /* Count back to zero */
1752 if (!show_search_progress(false, files_left--))
1753 break;
1755 if (!tagcache_retrieve(&tcs, tagtree_get_entry(c, i)->extraseek,
1756 tcs.type, buf, sizeof buf))
1758 continue;
1761 if (playlist_insert_track(NULL, buf, position, queue, false) < 0)
1763 logf("playlist_insert_track failed");
1764 break;
1766 yield();
1768 playlist_sync(NULL);
1769 tagcache_search_finish(&tcs);
1770 cpu_boost(false);
1772 return true;
1775 bool tagtree_insert_selection_playlist(int position, bool queue)
1777 struct tagentry *dptr;
1778 char buf[MAX_PATH];
1779 int dirlevel = tc->dirlevel;
1781 show_search_progress(
1782 #ifdef HAVE_DISK_STORAGE
1783 storage_disk_is_active()
1784 #else
1785 true
1786 #endif
1787 , 0);
1790 /* We need to set the table to allsubentries. */
1791 dptr = tagtree_get_entry(tc, tc->selected_item);
1793 /* Insert a single track? */
1794 if (dptr->newtable == PLAYTRACK)
1796 if (tagtree_get_filename(tc, buf, sizeof buf) < 0)
1798 logf("tagtree_get_filename failed");
1799 return false;
1801 playlist_insert_track(NULL, buf, position, queue, true);
1803 return true;
1806 if (dptr->newtable == NAVIBROWSE)
1808 tagtree_enter(tc);
1809 tagtree_load(tc);
1810 dptr = tagtree_get_entry(tc, tc->selected_item);
1812 else if (dptr->newtable != ALLSUBENTRIES)
1814 logf("unsupported table: %d", dptr->newtable);
1815 return false;
1818 /* Now the current table should be allsubentries. */
1819 if (dptr->newtable != PLAYTRACK)
1821 tagtree_enter(tc);
1822 tagtree_load(tc);
1823 dptr = tagtree_get_entry(tc, tc->selected_item);
1825 /* And now the newtable should be playtrack. */
1826 if (dptr->newtable != PLAYTRACK)
1828 logf("newtable: %d !!", dptr->newtable);
1829 tc->dirlevel = dirlevel;
1830 return false;
1834 if (tc->filesindir <= 0)
1835 splash(HZ, ID2P(LANG_END_PLAYLIST));
1836 else
1838 logf("insert_all_playlist");
1839 if (!insert_all_playlist(tc, position, queue))
1840 splash(HZ*2, ID2P(LANG_FAILED));
1843 /* Finally return the dirlevel to its original value. */
1844 while (tc->dirlevel > dirlevel)
1845 tagtree_exit(tc);
1846 tagtree_load(tc);
1848 return true;
1851 static int tagtree_play_folder(struct tree_context* c)
1853 if (playlist_create(NULL, NULL) < 0)
1855 logf("Failed creating playlist\n");
1856 return -1;
1859 if (!insert_all_playlist(c, PLAYLIST_INSERT_LAST, false))
1860 return -2;
1862 if (global_settings.playlist_shuffle)
1863 c->selected_item = playlist_shuffle(current_tick, c->selected_item);
1864 if (!global_settings.play_selected)
1865 c->selected_item = 0;
1866 gui_synclist_select_item(&tree_lists, c->selected_item);
1868 playlist_start(c->selected_item,0);
1869 playlist_get_current()->num_inserted_tracks = 0; /* make warn on playlist erase work */
1870 return 0;
1873 struct tagentry* tagtree_get_entry(struct tree_context *c, int id)
1875 struct tagentry *entry = (struct tagentry *)c->cache.entries;
1876 int realid = id - current_offset;
1878 /* Load the next chunk if necessary. */
1879 if (realid >= current_entry_count || realid < 0)
1881 cpu_boost(true);
1882 if (retrieve_entries(c, MAX(0, id - (current_entry_count / 2)),
1883 false) < 0)
1885 logf("retrieve failed");
1886 cpu_boost(false);
1887 return NULL;
1889 realid = id - current_offset;
1890 cpu_boost(false);
1893 return &entry[realid];
1896 char *tagtree_get_title(struct tree_context* c)
1898 switch (c->currtable)
1900 case ROOT:
1901 return menu->title;
1903 case NAVIBROWSE:
1904 case ALLSUBENTRIES:
1905 return current_title[c->currextra];
1908 return "?";
1911 int tagtree_get_attr(struct tree_context* c)
1913 int attr = -1;
1914 switch (c->currtable)
1916 case NAVIBROWSE:
1917 if (csi->tagorder[c->currextra] == tag_title)
1918 attr = FILE_ATTR_AUDIO;
1919 else
1920 attr = ATTR_DIRECTORY;
1921 break;
1923 case ALLSUBENTRIES:
1924 attr = FILE_ATTR_AUDIO;
1925 break;
1927 default:
1928 attr = ATTR_DIRECTORY;
1929 break;
1932 return attr;
1935 int tagtree_get_icon(struct tree_context* c)
1937 int icon = Icon_Folder;
1939 if (tagtree_get_attr(c) == FILE_ATTR_AUDIO)
1940 icon = Icon_Audio;
1942 return icon;