tagnavi.config: Add a logical-OR operator ("|") for tagnavi conditionals.
[kugel-rb.git] / apps / tagtree.c
blobe7f703154c9e78f341beb6523e89e09206f897e9
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 search_instruction {
136 char name[64];
137 int tagorder[MAX_TAGS];
138 int tagorder_count;
139 struct tagcache_search_clause *clause[MAX_TAGS][TAGCACHE_MAX_CLAUSES];
140 int format_id[MAX_TAGS];
141 int clause_count[MAX_TAGS];
142 int result_seek[MAX_TAGS];
145 struct menu_entry {
146 char name[64];
147 int type;
148 struct search_instruction *si;
149 int link;
152 struct menu_root {
153 char title[64];
154 char id[MAX_MENU_ID_SIZE];
155 int itemcount;
156 struct menu_entry *items[TAGMENU_MAX_ITEMS];
159 /* Statusbar text of the current view. */
160 static char current_title[MAX_TAGS][128];
162 static struct menu_root *menus[TAGMENU_MAX_MENUS];
163 static struct menu_root *menu;
164 static struct search_instruction *csi;
165 static const char *strp;
166 static int menu_count;
167 static int rootmenu;
169 static int current_offset;
170 static int current_entry_count;
172 static struct tree_context *tc;
174 static int get_token_str(char *buf, int size)
176 /* Find the start. */
177 while (*strp != '"' && *strp != '\0')
178 strp++;
180 if (*strp == '\0' || *(++strp) == '\0')
181 return -1;
183 /* Read the data. */
184 while (*strp != '"' && *strp != '\0' && --size > 0)
185 *(buf++) = *(strp++);
187 *buf = '\0';
188 if (*strp != '"')
189 return -2;
191 strp++;
193 return 0;
196 #define MATCH(tag,str1,str2,settag) \
197 if (!strcasecmp(str1, str2)) { \
198 *tag = settag; \
199 return 1; \
202 static int get_tag(int *tag)
204 char buf[128];
205 int i;
207 /* Find the start. */
208 while ((*strp == ' ' || *strp == '>') && *strp != '\0')
209 strp++;
211 if (*strp == '\0' || *strp == '?')
212 return 0;
214 for (i = 0; i < (int)sizeof(buf)-1; i++)
216 if (*strp == '\0' || *strp == ' ')
217 break ;
218 buf[i] = *strp;
219 strp++;
221 buf[i] = '\0';
223 MATCH(tag, buf, "album", tag_album);
224 MATCH(tag, buf, "artist", tag_artist);
225 MATCH(tag, buf, "bitrate", tag_bitrate);
226 MATCH(tag, buf, "composer", tag_composer);
227 MATCH(tag, buf, "comment", tag_comment);
228 MATCH(tag, buf, "albumartist", tag_albumartist);
229 MATCH(tag, buf, "ensemble", tag_albumartist);
230 MATCH(tag, buf, "grouping", tag_grouping);
231 MATCH(tag, buf, "genre", tag_genre);
232 MATCH(tag, buf, "length", tag_length);
233 MATCH(tag, buf, "Lm", tag_virt_length_min);
234 MATCH(tag, buf, "Ls", tag_virt_length_sec);
235 MATCH(tag, buf, "Pm", tag_virt_playtime_min);
236 MATCH(tag, buf, "Ps", tag_virt_playtime_sec);
237 MATCH(tag, buf, "title", tag_title);
238 MATCH(tag, buf, "filename", tag_filename);
239 MATCH(tag, buf, "tracknum", tag_tracknumber);
240 MATCH(tag, buf, "discnum", tag_discnumber);
241 MATCH(tag, buf, "year", tag_year);
242 MATCH(tag, buf, "playcount", tag_playcount);
243 MATCH(tag, buf, "rating", tag_rating);
244 MATCH(tag, buf, "lastplayed", tag_lastplayed);
245 MATCH(tag, buf, "lastoffset", tag_lastoffset);
246 MATCH(tag, buf, "commitid", tag_commitid);
247 MATCH(tag, buf, "entryage", tag_virt_entryage);
248 MATCH(tag, buf, "autoscore", tag_virt_autoscore);
249 MATCH(tag, buf, "%sort", var_sorttype);
250 MATCH(tag, buf, "%limit", var_limit);
251 MATCH(tag, buf, "%strip", var_strip);
252 MATCH(tag, buf, "%menu_start", var_menu_start);
253 MATCH(tag, buf, "%include", var_include);
254 MATCH(tag, buf, "%root_menu", var_rootmenu);
255 MATCH(tag, buf, "%format", var_format);
256 MATCH(tag, buf, "->", menu_next);
257 MATCH(tag, buf, "==>", menu_load);
259 logf("NO MATCH: %s\n", buf);
260 if (buf[0] == '?')
261 return 0;
263 return -1;
266 static int get_clause(int *condition)
268 char buf[4];
269 int i;
271 /* Find the start. */
272 while (*strp == ' ' && *strp != '\0')
273 strp++;
275 if (*strp == '\0')
276 return 0;
278 for (i = 0; i < (int)sizeof(buf)-1; i++)
280 if (*strp == '\0' || *strp == ' ')
281 break ;
282 buf[i] = *strp;
283 strp++;
285 buf[i] = '\0';
287 MATCH(condition, buf, "=", clause_is);
288 MATCH(condition, buf, "==", clause_is);
289 MATCH(condition, buf, "!=", clause_is_not);
290 MATCH(condition, buf, ">", clause_gt);
291 MATCH(condition, buf, ">=", clause_gteq);
292 MATCH(condition, buf, "<", clause_lt);
293 MATCH(condition, buf, "<=", clause_lteq);
294 MATCH(condition, buf, "~", clause_contains);
295 MATCH(condition, buf, "!~", clause_not_contains);
296 MATCH(condition, buf, "^", clause_begins_with);
297 MATCH(condition, buf, "!^", clause_not_begins_with);
298 MATCH(condition, buf, "$", clause_ends_with);
299 MATCH(condition, buf, "!$", clause_not_ends_with);
300 MATCH(condition, buf, "@", clause_oneof);
302 return 0;
305 static bool read_clause(struct tagcache_search_clause *clause)
307 char buf[SEARCHSTR_SIZE];
308 unsigned int i;
310 if (get_tag(&clause->tag) <= 0)
311 return false;
313 if (get_clause(&clause->type) <= 0)
314 return false;
316 if (get_token_str(buf, sizeof buf) < 0)
317 return false;
319 for (i=0; i<ARRAYLEN(id3_to_search_mapping); i++)
321 if (!strcasecmp(buf, id3_to_search_mapping[i].string))
322 break;
325 if (i<ARRAYLEN(id3_to_search_mapping)) /* runtime search operand found */
327 clause->source = source_runtime+i;
328 clause->str = buffer_alloc(SEARCHSTR_SIZE);
330 else
332 clause->source = source_constant;
333 clause->str = buffer_alloc(strlen(buf)+1);
334 strcpy(clause->str, buf);
337 if (TAGCACHE_IS_NUMERIC(clause->tag))
339 clause->numeric = true;
340 clause->numeric_data = atoi(clause->str);
342 else
343 clause->numeric = false;
345 logf("got clause: %d/%d [%s]", clause->tag, clause->type, clause->str);
347 return true;
350 static bool read_variable(char *buf, int size)
352 int condition;
354 if (!get_clause(&condition))
355 return false;
357 if (condition != clause_is)
358 return false;
360 if (get_token_str(buf, size) < 0)
361 return false;
363 return true;
366 /* "%3d. %s" autoscore title %sort = "inverse" %limit = "100" */
367 static int get_format_str(struct display_format *fmt)
369 int ret;
370 char buf[128];
371 int i;
373 memset(fmt, 0, sizeof(struct display_format));
375 if (get_token_str(fmt->name, sizeof fmt->name) < 0)
376 return -10;
378 /* Determine the group id */
379 fmt->group_id = 0;
380 for (i = 0; i < format_count; i++)
382 if (!strcasecmp(formats[i]->name, fmt->name))
384 fmt->group_id = formats[i]->group_id;
385 break;
388 if (formats[i]->group_id > fmt->group_id)
389 fmt->group_id = formats[i]->group_id;
392 if (i == format_count)
393 fmt->group_id++;
395 logf("format: (%d) %s", fmt->group_id, fmt->name);
397 if (get_token_str(buf, sizeof buf) < 0)
398 return -10;
400 fmt->formatstr = buffer_alloc(strlen(buf) + 1);
401 strcpy(fmt->formatstr, buf);
403 while (fmt->tag_count < MAX_TAGS)
405 ret = get_tag(&fmt->tags[fmt->tag_count]);
406 if (ret < 0)
407 return -11;
409 if (ret == 0)
410 break;
412 switch (fmt->tags[fmt->tag_count]) {
413 case var_sorttype:
414 if (!read_variable(buf, sizeof buf))
415 return -12;
416 if (!strcasecmp("inverse", buf))
417 fmt->sort_inverse = true;
418 break;
420 case var_limit:
421 if (!read_variable(buf, sizeof buf))
422 return -13;
423 fmt->limit = atoi(buf);
424 break;
426 case var_strip:
427 if (!read_variable(buf, sizeof buf))
428 return -14;
429 fmt->strip = atoi(buf);
430 break;
432 default:
433 fmt->tag_count++;
437 return 1;
440 static int add_format(const char *buf)
442 strp = buf;
444 if (formats[format_count] == NULL)
445 formats[format_count] = buffer_alloc(sizeof(struct display_format));
447 memset(formats[format_count], 0, sizeof(struct display_format));
448 if (get_format_str(formats[format_count]) < 0)
450 logf("get_format_str() parser failed!");
451 return -4;
454 while (*strp != '\0' && *strp != '?')
455 strp++;
457 if (*strp == '?')
459 int clause_count = 0;
460 strp++;
462 while (1)
464 struct tagcache_search_clause *newclause;
466 if (clause_count >= TAGCACHE_MAX_CLAUSES)
468 logf("too many clauses");
469 break;
472 newclause = buffer_alloc(sizeof(struct tagcache_search_clause));
474 formats[format_count]->clause[clause_count] = newclause;
475 if (!read_clause(newclause))
476 break;
478 clause_count++;
481 formats[format_count]->clause_count = clause_count;
484 format_count++;
486 return 1;
489 static int get_condition(struct search_instruction *inst)
491 struct tagcache_search_clause *new_clause;
492 int clause_count;
493 char buf[128];
495 switch (*strp)
497 case '=':
499 int i;
501 if (get_token_str(buf, sizeof buf) < 0)
502 return -1;
504 for (i = 0; i < format_count; i++)
506 if (!strcasecmp(formats[i]->name, buf))
507 break;
510 if (i == format_count)
512 logf("format not found: %s", buf);
513 return -2;
516 inst->format_id[inst->tagorder_count] = formats[i]->group_id;
517 return 1;
519 case '?':
520 case ' ':
521 case '&':
522 strp++;
523 return 1;
524 case '-':
525 case '\0':
526 return 0;
529 clause_count = inst->clause_count[inst->tagorder_count];
530 if (clause_count >= TAGCACHE_MAX_CLAUSES)
532 logf("Too many clauses");
533 return false;
536 new_clause = buffer_alloc(sizeof(struct tagcache_search_clause));
537 inst->clause[inst->tagorder_count][clause_count] = new_clause;
539 if (*strp == '|')
541 strp++;
542 new_clause->type = clause_logical_or;
544 else if (!read_clause(new_clause))
545 return -1;
547 inst->clause_count[inst->tagorder_count]++;
549 return 1;
552 /* example search:
553 * "Best" artist ? year >= "2000" & title !^ "crap" & genre = "good genre" \
554 * : album ? year >= "2000" : songs
555 * ^ begins with
556 * * contains
557 * $ ends with
560 static bool parse_search(struct menu_entry *entry, const char *str)
562 int ret;
563 int type;
564 struct search_instruction *inst = entry->si;
565 char buf[MAX_PATH];
566 int i;
567 struct menu_root *new_menu;
569 strp = str;
571 /* Parse entry name */
572 if (get_token_str(entry->name, sizeof entry->name) < 0)
574 logf("No name found.");
575 return false;
578 /* Parse entry type */
579 if (get_tag(&entry->type) <= 0)
580 return false;
582 if (entry->type == menu_load)
584 if (get_token_str(buf, sizeof buf) < 0)
585 return false;
587 /* Find the matching root menu or "create" it */
588 for (i = 0; i < menu_count; i++)
590 if (!strcasecmp(menus[i]->id, buf))
592 entry->link = i;
593 return true;
597 if (menu_count >= TAGMENU_MAX_MENUS)
599 logf("max menucount reached");
600 return false;
603 /* Allocate a new menu unless link is found. */
604 menus[menu_count] = buffer_alloc(sizeof(struct menu_root));
605 new_menu = menus[menu_count];
606 memset(new_menu, 0, sizeof(struct menu_root));
607 strlcpy(new_menu->id, buf, MAX_MENU_ID_SIZE);
608 entry->link = menu_count;
609 ++menu_count;
611 return true;
614 if (entry->type != menu_next)
615 return false;
617 while (inst->tagorder_count < MAX_TAGS)
619 ret = get_tag(&inst->tagorder[inst->tagorder_count]);
620 if (ret < 0)
622 logf("Parse error #1");
623 logf("%s", strp);
624 return false;
627 if (ret == 0)
628 break ;
630 logf("tag: %d", inst->tagorder[inst->tagorder_count]);
632 while ( (ret = get_condition(inst)) > 0 ) ;
633 if (ret < 0)
634 return false;
636 inst->tagorder_count++;
638 if (get_tag(&type) <= 0 || type != menu_next)
639 break;
642 return true;
645 static int compare(const void *p1, const void *p2)
647 struct tagentry *e1 = (struct tagentry *)p1;
648 struct tagentry *e2 = (struct tagentry *)p2;
650 if (sort_inverse)
651 return strncasecmp(e2->name, e1->name, MAX_PATH);
653 return strncasecmp(e1->name, e2->name, MAX_PATH);
656 static void tagtree_buffer_event(void *data)
658 struct tagcache_search tcs;
659 struct mp3entry *id3 = (struct mp3entry*)data;
661 /* Do not gather data unless proper setting has been enabled. */
662 if (!global_settings.runtimedb && !global_settings.autoresume_enable)
663 return;
665 logf("be:%s", id3->path);
667 while (! tagcache_is_fully_initialized())
668 yield();
670 if (!tagcache_find_index(&tcs, id3->path))
672 logf("tc stat: not found: %s", id3->path);
673 return;
676 if (global_settings.runtimedb)
678 id3->playcount = tagcache_get_numeric(&tcs, tag_playcount);
679 if (!id3->rating)
680 id3->rating = tagcache_get_numeric(&tcs, tag_rating);
681 id3->lastplayed = tagcache_get_numeric(&tcs, tag_lastplayed);
682 id3->score = tagcache_get_numeric(&tcs, tag_virt_autoscore) / 10;
683 id3->playtime = tagcache_get_numeric(&tcs, tag_playtime);
685 logf("-> %ld/%ld", id3->playcount, id3->playtime);
688 #if CONFIG_CODEC == SWCODEC
689 if (global_settings.autoresume_enable)
691 /* Load current file resume offset if not already defined (by
692 another resume mechanism) */
693 if (id3->offset == 0)
695 id3->offset = tagcache_get_numeric(&tcs, tag_lastoffset);
697 logf("tagtree_buffer_event: Set offset for %s to %lX\n",
698 str_or_empty(id3->title), id3->offset);
701 #endif
703 /* Store our tagcache index pointer. */
704 id3->tagcache_idx = tcs.idx_id+1;
706 tagcache_search_finish(&tcs);
709 static void tagtree_track_finish_event(void *data)
711 long lastplayed;
712 long tagcache_idx;
713 struct mp3entry *id3 = (struct mp3entry*)data;
715 /* Do not gather data unless proper setting has been enabled. */
716 if (!global_settings.runtimedb && !global_settings.autoresume_enable)
718 logf("runtimedb gathering and autoresume not enabled");
719 return;
722 tagcache_idx=id3->tagcache_idx;
723 if (!tagcache_idx)
725 logf("No tagcache index pointer found");
726 return;
728 tagcache_idx--;
730 /* Don't process unplayed tracks, or tracks interrupted within the
731 first 15 seconds. */
732 if (id3->elapsed == 0
733 #if CONFIG_CODEC == SWCODEC /* HWCODEC doesn't have automatic_skip */
734 || (id3->elapsed < 15 * 1000 && !audio_automatic_skip())
735 #endif
738 logf("not logging unplayed or skipped track");
739 return;
742 lastplayed = tagcache_increase_serial();
743 if (lastplayed < 0)
745 logf("incorrect tc serial:%ld", lastplayed);
746 return;
749 if (global_settings.runtimedb)
751 long playcount;
752 long playtime;
754 playcount = id3->playcount + 1;
756 /* Ignore the last 15s (crossfade etc.) */
757 playtime = id3->playtime + MIN(id3->length, id3->elapsed + 15 * 1000);
759 logf("ube:%s", id3->path);
760 logf("-> %ld/%ld", playcount, playtime);
761 logf("-> %ld/%ld/%ld", id3->elapsed, id3->length,
762 MIN(id3->length, id3->elapsed + 15 * 1000));
764 /* Queue the updates to the tagcache system. */
765 tagcache_update_numeric(tagcache_idx, tag_playcount, playcount);
766 tagcache_update_numeric(tagcache_idx, tag_playtime, playtime);
767 tagcache_update_numeric(tagcache_idx, tag_lastplayed, lastplayed);
770 #if CONFIG_CODEC == SWCODEC
771 if (global_settings.autoresume_enable)
773 unsigned long offset
774 = audio_automatic_skip() ? 0 : id3->offset;
776 tagcache_update_numeric(tagcache_idx, tag_lastoffset, offset);
778 logf("tagtree_track_finish_event: Save offset for %s: %lX",
779 str_or_empty(id3->title), offset);
781 #endif
784 bool tagtree_export(void)
786 struct tagcache_search tcs;
788 splash(0, str(LANG_CREATING));
789 if (!tagcache_create_changelog(&tcs))
791 splash(HZ*2, ID2P(LANG_FAILED));
794 return false;
797 bool tagtree_import(void)
799 splash(0, ID2P(LANG_WAIT));
800 if (!tagcache_import_changelog())
802 splash(HZ*2, ID2P(LANG_FAILED));
805 return false;
808 static bool parse_menu(const char *filename);
810 static int parse_line(int n, const char *buf, void *parameters)
812 char data[256];
813 int variable;
814 static bool read_menu;
815 int i;
817 (void)parameters;
819 logf("parse:%d/%s", n, buf);
821 /* First line, do initialisation. */
822 if (n == 0)
824 if (strcasecmp(TAGNAVI_VERSION, buf))
826 logf("Version mismatch");
827 return -1;
830 read_menu = false;
833 if (buf[0] == '#')
834 return 0;
836 if (buf[0] == '\0')
838 if (read_menu)
840 /* End the menu */
841 read_menu = false;
843 return 0;
846 if (!read_menu)
848 strp = buf;
849 if (get_tag(&variable) <= 0)
850 return 0;
852 switch (variable)
854 case var_format:
855 if (add_format(strp) < 0)
857 logf("Format add fail: %s", data);
859 break;
861 case var_include:
862 if (get_token_str(data, sizeof(data)) < 0)
864 logf("%%include empty");
865 return 0;
868 if (!parse_menu(data))
870 logf("Load menu fail: %s", data);
872 break;
874 case var_menu_start:
875 if (menu_count >= TAGMENU_MAX_MENUS)
877 logf("max menucount reached");
878 return 0;
881 if (get_token_str(data, sizeof data) < 0)
883 logf("%%menu_start id empty");
884 return 0;
887 menu = NULL;
888 for (i = 0; i < menu_count; i++)
890 if (!strcasecmp(menus[i]->id, data))
892 menu = menus[i];
896 if (menu == NULL)
898 menus[menu_count] = buffer_alloc(sizeof(struct menu_root));
899 menu = menus[menu_count];
900 ++menu_count;
901 memset(menu, 0, sizeof(struct menu_root));
902 strlcpy(menu->id, data, MAX_MENU_ID_SIZE);
905 if (get_token_str(menu->title, sizeof(menu->title)) < 0)
907 logf("%%menu_start title empty");
908 return 0;
910 logf("menu: %s", menu->title);
911 read_menu = true;
912 break;
914 case var_rootmenu:
915 /* Only set root menu once. */
916 if (rootmenu >= 0)
917 break;
919 if (get_token_str(data, sizeof(data)) < 0)
921 logf("%%rootmenu empty");
922 return 0;
925 for (i = 0; i < menu_count; i++)
927 if (!strcasecmp(menus[i]->id, data))
929 rootmenu = i;
932 break;
935 return 0;
938 if (menu->itemcount >= TAGMENU_MAX_ITEMS)
940 logf("max itemcount reached");
941 return 0;
944 /* Allocate */
945 if (menu->items[menu->itemcount] == NULL)
947 menu->items[menu->itemcount] = buffer_alloc(sizeof(struct menu_entry));
948 memset(menu->items[menu->itemcount], 0, sizeof(struct menu_entry));
949 menu->items[menu->itemcount]->si = buffer_alloc(sizeof(struct search_instruction));
952 memset(menu->items[menu->itemcount]->si, 0, sizeof(struct search_instruction));
953 if (!parse_search(menu->items[menu->itemcount], buf))
954 return 0;
956 menu->itemcount++;
958 return 0;
961 static bool parse_menu(const char *filename)
963 int fd;
964 char buf[1024];
966 if (menu_count >= TAGMENU_MAX_MENUS)
968 logf("max menucount reached");
969 return false;
972 fd = open(filename, O_RDONLY);
973 if (fd < 0)
975 logf("Search instruction file not found.");
976 return false;
979 /* Now read file for real, parsing into si */
980 fast_readline(fd, buf, sizeof buf, NULL, parse_line);
981 close(fd);
983 return true;
986 void tagtree_init(void)
988 format_count = 0;
989 menu_count = 0;
990 menu = NULL;
991 rootmenu = -1;
992 parse_menu(FILE_SEARCH_INSTRUCTIONS);
994 /* If no root menu is set, assume it's the first single menu
995 * we have. That shouldn't normally happen. */
996 if (rootmenu < 0)
997 rootmenu = 0;
999 uniqbuf = buffer_alloc(UNIQBUF_SIZE);
1001 add_event(PLAYBACK_EVENT_TRACK_BUFFER, false, tagtree_buffer_event);
1002 add_event(PLAYBACK_EVENT_TRACK_FINISH, false, tagtree_track_finish_event);
1005 static bool show_search_progress(bool init, int count)
1007 static int last_tick = 0;
1009 /* Don't show splashes for 1/2 second after starting search */
1010 if (init)
1012 last_tick = current_tick + HZ/2;
1013 return true;
1016 /* Update progress every 1/10 of a second */
1017 if (TIME_AFTER(current_tick, last_tick + HZ/10))
1019 splashf(0, str(LANG_PLAYLIST_SEARCH_MSG), count, str(LANG_OFF_ABORT));
1020 if (action_userabort(TIMEOUT_NOBLOCK))
1021 return false;
1022 last_tick = current_tick;
1023 yield();
1026 return true;
1029 static int format_str(struct tagcache_search *tcs, struct display_format *fmt,
1030 char *buf, int buf_size)
1032 char fmtbuf[8];
1033 bool read_format = false;
1034 int fmtbuf_pos = 0;
1035 int parpos = 0;
1036 int buf_pos = 0;
1037 int i;
1039 memset(buf, 0, buf_size);
1040 for (i = 0; fmt->formatstr[i] != '\0'; i++)
1042 if (fmt->formatstr[i] == '%')
1044 read_format = true;
1045 fmtbuf_pos = 0;
1046 if (parpos >= fmt->tag_count)
1048 logf("too many format tags");
1049 return -1;
1053 if (read_format)
1055 fmtbuf[fmtbuf_pos++] = fmt->formatstr[i];
1056 if (fmtbuf_pos >= buf_size)
1058 logf("format parse error");
1059 return -2;
1062 if (fmt->formatstr[i] == 's')
1064 fmtbuf[fmtbuf_pos] = '\0';
1065 read_format = false;
1066 if (fmt->tags[parpos] == tcs->type)
1068 snprintf(&buf[buf_pos], buf_size - buf_pos, fmtbuf, tcs->result);
1070 else
1072 /* Need to fetch the tag data. */
1073 if (!tagcache_retrieve(tcs, tcs->idx_id, fmt->tags[parpos],
1074 &buf[buf_pos], buf_size - buf_pos))
1076 logf("retrieve failed");
1077 return -3;
1080 buf_pos += strlen(&buf[buf_pos]);
1081 parpos++;
1083 else if (fmt->formatstr[i] == 'd')
1085 fmtbuf[fmtbuf_pos] = '\0';
1086 read_format = false;
1087 snprintf(&buf[buf_pos], buf_size - buf_pos, fmtbuf,
1088 tagcache_get_numeric(tcs, fmt->tags[parpos]));
1089 buf_pos += strlen(&buf[buf_pos]);
1090 parpos++;
1092 continue;
1095 buf[buf_pos++] = fmt->formatstr[i];
1097 if (buf_pos - 1 >= buf_size)
1099 logf("buffer overflow");
1100 return -4;
1104 buf[buf_pos++] = '\0';
1106 return 0;
1109 static int retrieve_entries(struct tree_context *c, int offset, bool init)
1111 struct tagcache_search tcs;
1112 struct tagentry *dptr = (struct tagentry *)c->dircache;
1113 struct display_format *fmt;
1114 int i;
1115 int namebufused = 0;
1116 int total_count = 0;
1117 int special_entry_count = 0;
1118 int level = c->currextra;
1119 int tag;
1120 bool sort = false;
1121 int sort_limit;
1122 int strip;
1124 /* Show search progress straight away if the disk needs to spin up,
1125 otherwise show it after the normal 1/2 second delay */
1126 show_search_progress(
1127 #ifdef HAVE_DISK_STORAGE
1128 storage_disk_is_active()
1129 #else
1130 true
1131 #endif
1132 , 0);
1134 if (c->currtable == ALLSUBENTRIES)
1136 tag = tag_title;
1137 level--;
1139 else
1140 tag = csi->tagorder[level];
1142 if (!tagcache_search(&tcs, tag))
1143 return -1;
1145 /* Prevent duplicate entries in the search list. */
1146 tagcache_search_set_uniqbuf(&tcs, uniqbuf, UNIQBUF_SIZE);
1148 if (level || csi->clause_count[0] || TAGCACHE_IS_NUMERIC(tag))
1149 sort = true;
1151 for (i = 0; i < level; i++)
1153 if (TAGCACHE_IS_NUMERIC(csi->tagorder[i]))
1155 static struct tagcache_search_clause cc;
1157 memset(&cc, 0, sizeof(struct tagcache_search_clause));
1158 cc.tag = csi->tagorder[i];
1159 cc.type = clause_is;
1160 cc.numeric = true;
1161 cc.numeric_data = csi->result_seek[i];
1162 tagcache_search_add_clause(&tcs, &cc);
1164 else
1166 tagcache_search_add_filter(&tcs, csi->tagorder[i],
1167 csi->result_seek[i]);
1171 for (i = 0; i <= level; i++)
1173 int j;
1175 for (j = 0; j < csi->clause_count[i]; j++)
1176 tagcache_search_add_clause(&tcs, csi->clause[i][j]);
1179 current_offset = offset;
1180 current_entry_count = 0;
1181 c->dirfull = false;
1183 fmt = NULL;
1184 for (i = 0; i < format_count; i++)
1186 if (formats[i]->group_id == csi->format_id[level])
1187 fmt = formats[i];
1190 if (fmt)
1192 sort_inverse = fmt->sort_inverse;
1193 sort_limit = fmt->limit;
1194 strip = fmt->strip;
1195 sort = true;
1197 else
1199 sort_inverse = false;
1200 sort_limit = 0;
1201 strip = 0;
1204 if (tag != tag_title && tag != tag_filename)
1206 if (offset == 0)
1208 dptr->newtable = ALLSUBENTRIES;
1209 dptr->name = str(LANG_TAGNAVI_ALL_TRACKS);
1210 dptr++;
1211 current_entry_count++;
1213 if (offset <= 1)
1215 dptr->newtable = NAVIBROWSE;
1216 dptr->name = str(LANG_TAGNAVI_RANDOM);
1217 dptr->extraseek = -1;
1218 dptr++;
1219 current_entry_count++;
1221 special_entry_count+=2;
1224 total_count += special_entry_count;
1226 while (tagcache_get_next(&tcs))
1228 if (total_count++ < offset)
1229 continue;
1231 if ( strcmp(tcs.result , UNTAGGED ) == 0)
1233 tcs.result_len = strlcpy(tcs.result,
1234 str(LANG_TAGNAVI_UNTAGGED), TAG_MAXLEN )+1;
1237 dptr->newtable = NAVIBROWSE;
1238 if (tag == tag_title || tag == tag_filename)
1240 dptr->newtable = PLAYTRACK;
1241 dptr->extraseek = tcs.idx_id;
1243 else
1244 dptr->extraseek = tcs.result_seek;
1246 fmt = NULL;
1247 /* Check the format */
1248 for (i = 0; i < format_count; i++)
1250 if (formats[i]->group_id != csi->format_id[level])
1251 continue;
1253 if (tagcache_check_clauses(&tcs, formats[i]->clause,
1254 formats[i]->clause_count))
1256 fmt = formats[i];
1257 break;
1261 if (!tcs.ramresult || fmt)
1263 char buf[MAX_PATH];
1265 if (fmt)
1267 if (format_str(&tcs, fmt, buf, sizeof buf) < 0)
1269 logf("format_str() failed");
1270 tagcache_search_finish(&tcs);
1271 return 0;
1275 dptr->name = &c->name_buffer[namebufused];
1276 if (fmt)
1277 namebufused += strlen(buf)+1;
1278 else
1279 namebufused += tcs.result_len;
1281 if (namebufused >= c->name_buffer_size)
1283 logf("chunk mode #2: %d", current_entry_count);
1284 c->dirfull = true;
1285 sort = false;
1286 break ;
1288 if (fmt)
1289 strcpy(dptr->name, buf);
1290 else
1291 strcpy(dptr->name, tcs.result);
1293 else
1294 dptr->name = tcs.result;
1296 dptr++;
1297 current_entry_count++;
1299 if (current_entry_count >= c->dircache_count)
1301 logf("chunk mode #3: %d", current_entry_count);
1302 c->dirfull = true;
1303 sort = false;
1304 break ;
1307 if (init && !tcs.ramsearch)
1309 if (!show_search_progress(false, total_count))
1310 { /* user aborted */
1311 tagcache_search_finish(&tcs);
1312 return current_entry_count;
1317 if (sort)
1318 qsort(c->dircache + special_entry_count * c->dentry_size,
1319 current_entry_count - special_entry_count,
1320 c->dentry_size, compare);
1322 if (!init)
1324 tagcache_search_finish(&tcs);
1325 return current_entry_count;
1328 while (tagcache_get_next(&tcs))
1330 if (!tcs.ramsearch)
1332 if (!show_search_progress(false, total_count))
1333 break;
1335 total_count++;
1338 tagcache_search_finish(&tcs);
1340 if (!sort && (sort_inverse || sort_limit))
1342 splashf(HZ*4, ID2P(LANG_SHOWDIR_BUFFER_FULL), total_count);
1343 logf("Too small dir buffer");
1344 return 0;
1347 if (sort_limit)
1348 total_count = MIN(total_count, sort_limit);
1350 if (strip)
1352 dptr = c->dircache;
1353 for (i = 0; i < total_count; i++, dptr++)
1355 int len = strlen(dptr->name);
1357 if (len < strip)
1358 continue;
1360 dptr->name = &dptr->name[strip];
1364 return total_count;
1368 static int load_root(struct tree_context *c)
1370 struct tagentry *dptr = (struct tagentry *)c->dircache;
1371 int i;
1373 tc = c;
1374 c->currtable = ROOT;
1375 if (c->dirlevel == 0)
1376 c->currextra = rootmenu;
1378 menu = menus[c->currextra];
1379 if (menu == NULL)
1380 return 0;
1382 for (i = 0; i < menu->itemcount; i++)
1384 dptr->name = menu->items[i]->name;
1385 switch (menu->items[i]->type)
1387 case menu_next:
1388 dptr->newtable = NAVIBROWSE;
1389 dptr->extraseek = i;
1390 break;
1392 case menu_load:
1393 dptr->newtable = ROOT;
1394 dptr->extraseek = menu->items[i]->link;
1395 break;
1398 dptr++;
1401 current_offset = 0;
1402 current_entry_count = i;
1404 return i;
1407 int tagtree_load(struct tree_context* c)
1409 int count;
1410 int table = c->currtable;
1412 c->dentry_size = sizeof(struct tagentry);
1413 c->dirsindir = 0;
1415 if (!table)
1417 c->dirfull = false;
1418 table = ROOT;
1419 c->currtable = table;
1420 c->currextra = rootmenu;
1423 switch (table)
1425 case ROOT:
1426 count = load_root(c);
1427 break;
1429 case ALLSUBENTRIES:
1430 case NAVIBROWSE:
1431 logf("navibrowse...");
1432 cpu_boost(true);
1433 count = retrieve_entries(c, 0, true);
1434 cpu_boost(false);
1435 break;
1437 default:
1438 logf("Unsupported table %d\n", table);
1439 return -1;
1442 if (count < 0)
1444 c->dirlevel = 0;
1445 count = load_root(c);
1446 splash(HZ, str(LANG_TAGCACHE_BUSY));
1449 /* The _total_ numer of entries available. */
1450 c->dirlength = c->filesindir = count;
1452 return count;
1455 int tagtree_enter(struct tree_context* c)
1457 int rc = 0;
1458 struct tagentry *dptr;
1459 struct mp3entry *id3;
1460 int newextra;
1461 int seek;
1462 int source;
1464 dptr = tagtree_get_entry(c, c->selected_item);
1466 c->dirfull = false;
1467 seek = dptr->extraseek;
1468 if (seek == -1)
1470 if(c->filesindir<=2)
1471 return 0;
1472 srand(current_tick);
1473 dptr = (tagtree_get_entry(c, 2+(rand() % (c->filesindir-2))));
1474 seek = dptr->extraseek;
1476 newextra = dptr->newtable;
1478 if (c->dirlevel >= MAX_DIR_LEVELS)
1479 return 0;
1481 c->selected_item_history[c->dirlevel]=c->selected_item;
1482 c->table_history[c->dirlevel] = c->currtable;
1483 c->extra_history[c->dirlevel] = c->currextra;
1484 c->pos_history[c->dirlevel] = c->firstpos;
1485 c->dirlevel++;
1487 switch (c->currtable) {
1488 case ROOT:
1489 c->currextra = newextra;
1491 if (newextra == ROOT)
1493 menu = menus[seek];
1494 c->currextra = seek;
1497 else if (newextra == NAVIBROWSE)
1499 int i, j;
1501 csi = menu->items[seek]->si;
1502 c->currextra = 0;
1504 strlcpy(current_title[c->currextra], dptr->name,
1505 sizeof(current_title[0]));
1507 /* Read input as necessary. */
1508 for (i = 0; i < csi->tagorder_count; i++)
1510 for (j = 0; j < csi->clause_count[i]; j++)
1512 char* searchstring;
1514 if (csi->clause[i][j]->type == clause_logical_or)
1515 continue;
1517 source = csi->clause[i][j]->source;
1519 if (source == source_constant)
1520 continue;
1522 searchstring=csi->clause[i][j]->str;
1523 *searchstring = '\0';
1525 id3 = audio_current_track();
1527 if (source == source_current_path && id3)
1529 char *e;
1530 strlcpy(searchstring, id3->path, SEARCHSTR_SIZE);
1531 e = strrchr(searchstring, '/');
1532 if (e)
1533 *e = '\0';
1535 else if (source > source_runtime && id3)
1538 int k = source-source_runtime;
1539 int offset = id3_to_search_mapping[k].id3_offset;
1540 char **src = (char**)((char*)id3 + offset);
1541 if (*src)
1543 strlcpy(searchstring, *src, SEARCHSTR_SIZE);
1546 else
1548 rc = kbd_input(searchstring, SEARCHSTR_SIZE);
1549 if (rc < 0 || !searchstring[0])
1551 tagtree_exit(c);
1552 return 0;
1554 if (csi->clause[i][j]->numeric)
1555 csi->clause[i][j]->numeric_data = atoi(searchstring);
1562 c->currtable = newextra;
1564 break;
1566 case NAVIBROWSE:
1567 case ALLSUBENTRIES:
1568 if (newextra == PLAYTRACK)
1570 if (global_settings.party_mode && audio_status()) {
1571 splash(HZ, ID2P(LANG_PARTY_MODE));
1572 break;
1574 c->dirlevel--;
1575 /* about to create a new current playlist...
1576 allow user to cancel the operation */
1577 if (!warn_on_pl_erase())
1578 break;
1579 if (tagtree_play_folder(c) >= 0)
1580 rc = 2;
1581 break;
1584 c->currtable = newextra;
1585 csi->result_seek[c->currextra] = seek;
1586 if (c->currextra < csi->tagorder_count-1)
1587 c->currextra++;
1588 else
1589 c->dirlevel--;
1591 /* Update the statusbar title */
1592 strlcpy(current_title[c->currextra], dptr->name,
1593 sizeof(current_title[0]));
1594 break;
1596 default:
1597 c->dirlevel--;
1598 break;
1601 c->selected_item=0;
1602 gui_synclist_select_item(&tree_lists, c->selected_item);
1604 return rc;
1607 void tagtree_exit(struct tree_context* c)
1609 c->dirfull = false;
1610 if (c->dirlevel > 0)
1611 c->dirlevel--;
1612 c->selected_item=c->selected_item_history[c->dirlevel];
1613 gui_synclist_select_item(&tree_lists, c->selected_item);
1614 c->currtable = c->table_history[c->dirlevel];
1615 c->currextra = c->extra_history[c->dirlevel];
1616 c->firstpos = c->pos_history[c->dirlevel];
1619 int tagtree_get_filename(struct tree_context* c, char *buf, int buflen)
1621 struct tagcache_search tcs;
1622 struct tagentry *entry;
1624 entry = tagtree_get_entry(c, c->selected_item);
1626 if (!tagcache_search(&tcs, tag_filename))
1627 return -1;
1629 if (!tagcache_retrieve(&tcs, entry->extraseek, tcs.type, buf, buflen))
1631 tagcache_search_finish(&tcs);
1632 return -2;
1635 tagcache_search_finish(&tcs);
1637 return 0;
1640 static bool insert_all_playlist(struct tree_context *c, int position, bool queue)
1642 struct tagcache_search tcs;
1643 int i;
1644 char buf[MAX_PATH];
1645 int from, to, direction;
1646 int files_left = c->filesindir;
1648 cpu_boost(true);
1649 if (!tagcache_search(&tcs, tag_filename))
1651 splash(HZ, ID2P(LANG_TAGCACHE_BUSY));
1652 cpu_boost(false);
1653 return false;
1656 if (position == PLAYLIST_REPLACE)
1658 if (playlist_remove_all_tracks(NULL) == 0)
1659 position = PLAYLIST_INSERT_LAST;
1660 else
1662 cpu_boost(false);
1663 return false;
1667 if (position == PLAYLIST_INSERT_FIRST)
1669 from = c->filesindir - 1;
1670 to = -1;
1671 direction = -1;
1673 else
1675 from = 0;
1676 to = c->filesindir;
1677 direction = 1;
1680 for (i = from; i != to; i += direction)
1682 /* Count back to zero */
1683 if (!show_search_progress(false, files_left--))
1684 break;
1686 if (!tagcache_retrieve(&tcs, tagtree_get_entry(c, i)->extraseek,
1687 tcs.type, buf, sizeof buf))
1689 continue;
1692 if (playlist_insert_track(NULL, buf, position, queue, false) < 0)
1694 logf("playlist_insert_track failed");
1695 break;
1697 yield();
1699 playlist_sync(NULL);
1700 tagcache_search_finish(&tcs);
1701 cpu_boost(false);
1703 return true;
1706 bool tagtree_insert_selection_playlist(int position, bool queue)
1708 struct tagentry *dptr;
1709 char buf[MAX_PATH];
1710 int dirlevel = tc->dirlevel;
1712 show_search_progress(
1713 #ifdef HAVE_DISK_STORAGE
1714 storage_disk_is_active()
1715 #else
1716 true
1717 #endif
1718 , 0);
1721 /* We need to set the table to allsubentries. */
1722 dptr = tagtree_get_entry(tc, tc->selected_item);
1724 /* Insert a single track? */
1725 if (dptr->newtable == PLAYTRACK)
1727 if (tagtree_get_filename(tc, buf, sizeof buf) < 0)
1729 logf("tagtree_get_filename failed");
1730 return false;
1732 playlist_insert_track(NULL, buf, position, queue, true);
1734 return true;
1737 if (dptr->newtable == NAVIBROWSE)
1739 tagtree_enter(tc);
1740 tagtree_load(tc);
1741 dptr = tagtree_get_entry(tc, tc->selected_item);
1743 else if (dptr->newtable != ALLSUBENTRIES)
1745 logf("unsupported table: %d", dptr->newtable);
1746 return false;
1749 /* Now the current table should be allsubentries. */
1750 if (dptr->newtable != PLAYTRACK)
1752 tagtree_enter(tc);
1753 tagtree_load(tc);
1754 dptr = tagtree_get_entry(tc, tc->selected_item);
1756 /* And now the newtable should be playtrack. */
1757 if (dptr->newtable != PLAYTRACK)
1759 logf("newtable: %d !!", dptr->newtable);
1760 tc->dirlevel = dirlevel;
1761 return false;
1765 if (tc->filesindir <= 0)
1766 splash(HZ, ID2P(LANG_END_PLAYLIST));
1767 else
1769 logf("insert_all_playlist");
1770 if (!insert_all_playlist(tc, position, queue))
1771 splash(HZ*2, ID2P(LANG_FAILED));
1774 /* Finally return the dirlevel to its original value. */
1775 while (tc->dirlevel > dirlevel)
1776 tagtree_exit(tc);
1777 tagtree_load(tc);
1779 return true;
1782 static int tagtree_play_folder(struct tree_context* c)
1784 if (playlist_create(NULL, NULL) < 0)
1786 logf("Failed creating playlist\n");
1787 return -1;
1790 if (!insert_all_playlist(c, PLAYLIST_INSERT_LAST, false))
1791 return -2;
1793 if (global_settings.playlist_shuffle)
1794 c->selected_item = playlist_shuffle(current_tick, c->selected_item);
1795 if (!global_settings.play_selected)
1796 c->selected_item = 0;
1797 gui_synclist_select_item(&tree_lists, c->selected_item);
1799 playlist_start(c->selected_item,0);
1800 playlist_get_current()->num_inserted_tracks = 0; /* make warn on playlist erase work */
1801 return 0;
1804 struct tagentry* tagtree_get_entry(struct tree_context *c, int id)
1806 struct tagentry *entry = (struct tagentry *)c->dircache;
1807 int realid = id - current_offset;
1809 /* Load the next chunk if necessary. */
1810 if (realid >= current_entry_count || realid < 0)
1812 cpu_boost(true);
1813 if (retrieve_entries(c, MAX(0, id - (current_entry_count / 2)),
1814 false) < 0)
1816 logf("retrieve failed");
1817 cpu_boost(false);
1818 return NULL;
1820 realid = id - current_offset;
1821 cpu_boost(false);
1824 return &entry[realid];
1827 char *tagtree_get_title(struct tree_context* c)
1829 switch (c->currtable)
1831 case ROOT:
1832 return menu->title;
1834 case NAVIBROWSE:
1835 case ALLSUBENTRIES:
1836 return current_title[c->currextra];
1839 return "?";
1842 int tagtree_get_attr(struct tree_context* c)
1844 int attr = -1;
1845 switch (c->currtable)
1847 case NAVIBROWSE:
1848 if (csi->tagorder[c->currextra] == tag_title)
1849 attr = FILE_ATTR_AUDIO;
1850 else
1851 attr = ATTR_DIRECTORY;
1852 break;
1854 case ALLSUBENTRIES:
1855 attr = FILE_ATTR_AUDIO;
1856 break;
1858 default:
1859 attr = ATTR_DIRECTORY;
1860 break;
1863 return attr;
1866 int tagtree_get_icon(struct tree_context* c)
1868 int icon = Icon_Folder;
1870 if (tagtree_get_attr(c) == FILE_ATTR_AUDIO)
1871 icon = Icon_Audio;
1873 return icon;