Current state of inserting buflib.
[kugel-rb.git] / apps / tagtree.c
blob495fa391c47c326040adac1182babd92d677b78d
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 "core_alloc.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 int tagtree_handle;
180 static size_t tagtree_bufsize, tagtree_buf_used;
181 static void* tagtree_alloc(size_t size)
183 char* buf = core_get_data(tagtree_handle) + tagtree_buf_used;
184 size = (size+sizeof(char*)-1) & ~sizeof(char*);
185 tagtree_buf_used += size;
186 return buf;
189 static void* tagtree_alloc0(size_t size)
191 void* ret = tagtree_alloc(size);
192 memset(ret, 0, size);
193 return ret;
196 static char* tagtree_strdup(const char* buf)
198 size_t len = strlen(buf) + 1;
199 char* dest = tagtree_alloc(len);
200 strcpy(dest, buf);
201 return dest;
204 static int get_token_str(char *buf, int size)
206 /* Find the start. */
207 while (*strp != '"' && *strp != '\0')
208 strp++;
210 if (*strp == '\0' || *(++strp) == '\0')
211 return -1;
213 /* Read the data. */
214 while (*strp != '"' && *strp != '\0' && --size > 0)
215 *(buf++) = *(strp++);
217 *buf = '\0';
218 if (*strp != '"')
219 return -2;
221 strp++;
223 return 0;
226 static int get_tag(int *tag)
228 static const struct match get_tag_match[] =
230 {"album", tag_album},
231 {"artist", tag_artist},
232 {"bitrate", tag_bitrate},
233 {"composer", tag_composer},
234 {"comment", tag_comment},
235 {"albumartist", tag_albumartist},
236 {"ensemble", tag_albumartist},
237 {"grouping", tag_grouping},
238 {"genre", tag_genre},
239 {"length", tag_length},
240 {"Lm", tag_virt_length_min},
241 {"Ls", tag_virt_length_sec},
242 {"Pm", tag_virt_playtime_min},
243 {"Ps", tag_virt_playtime_sec},
244 {"title", tag_title},
245 {"filename", tag_filename},
246 {"basename", tag_virt_basename},
247 {"tracknum", tag_tracknumber},
248 {"discnum", tag_discnumber},
249 {"year", tag_year},
250 {"playcount", tag_playcount},
251 {"rating", tag_rating},
252 {"lastplayed", tag_lastplayed},
253 {"lastoffset", tag_lastoffset},
254 {"commitid", tag_commitid},
255 {"entryage", tag_virt_entryage},
256 {"autoscore", tag_virt_autoscore},
257 {"%sort", var_sorttype},
258 {"%limit", var_limit},
259 {"%strip", var_strip},
260 {"%menu_start", var_menu_start},
261 {"%include", var_include},
262 {"%root_menu", var_rootmenu},
263 {"%format", var_format},
264 {"->", menu_next},
265 {"==>", menu_load}
267 char buf[128];
268 unsigned int i;
270 /* Find the start. */
271 while ((*strp == ' ' || *strp == '>') && *strp != '\0')
272 strp++;
274 if (*strp == '\0' || *strp == '?')
275 return 0;
277 for (i = 0; i < sizeof(buf)-1; i++)
279 if (*strp == '\0' || *strp == ' ')
280 break ;
281 buf[i] = *strp;
282 strp++;
284 buf[i] = '\0';
286 for (i = 0; i < ARRAYLEN(get_tag_match); i++)
288 if (!strcasecmp(buf, get_tag_match[i].str))
290 *tag = get_tag_match[i].symbol;
291 return 1;
295 logf("NO MATCH: %s\n", buf);
296 if (buf[0] == '?')
297 return 0;
299 return -1;
302 static int get_clause(int *condition)
304 static const struct match get_clause_match[] =
306 {"=", clause_is},
307 {"==", clause_is},
308 {"!=", clause_is_not},
309 {">", clause_gt},
310 {">=", clause_gteq},
311 {"<", clause_lt},
312 {"<=", clause_lteq},
313 {"~", clause_contains},
314 {"!~", clause_not_contains},
315 {"^", clause_begins_with},
316 {"!^", clause_not_begins_with},
317 {"$", clause_ends_with},
318 {"!$", clause_not_ends_with},
319 {"@", clause_oneof}
322 char buf[4];
323 unsigned int i;
325 /* Find the start. */
326 while (*strp == ' ' && *strp != '\0')
327 strp++;
329 if (*strp == '\0')
330 return 0;
332 for (i = 0; i < sizeof(buf)-1; i++)
334 if (*strp == '\0' || *strp == ' ')
335 break ;
336 buf[i] = *strp;
337 strp++;
339 buf[i] = '\0';
341 for (i = 0; i < ARRAYLEN(get_clause_match); i++)
343 if (!strcasecmp(buf, get_clause_match[i].str))
345 *condition = get_clause_match[i].symbol;
346 return 1;
350 return 0;
353 static bool read_clause(struct tagcache_search_clause *clause)
355 char buf[SEARCHSTR_SIZE];
356 unsigned int i;
358 if (get_tag(&clause->tag) <= 0)
359 return false;
361 if (get_clause(&clause->type) <= 0)
362 return false;
364 if (get_token_str(buf, sizeof buf) < 0)
365 return false;
367 for (i=0; i<ARRAYLEN(id3_to_search_mapping); i++)
369 if (!strcasecmp(buf, id3_to_search_mapping[i].string))
370 break;
373 if (i<ARRAYLEN(id3_to_search_mapping)) /* runtime search operand found */
375 clause->source = source_runtime+i;
376 clause->str = tagtree_alloc(SEARCHSTR_SIZE);
378 else
380 clause->source = source_constant;
381 clause->str = tagtree_strdup(buf);
384 if (TAGCACHE_IS_NUMERIC(clause->tag))
386 clause->numeric = true;
387 clause->numeric_data = atoi(clause->str);
389 else
390 clause->numeric = false;
392 logf("got clause: %d/%d [%s]", clause->tag, clause->type, clause->str);
394 return true;
397 static bool read_variable(char *buf, int size)
399 int condition;
401 if (!get_clause(&condition))
402 return false;
404 if (condition != clause_is)
405 return false;
407 if (get_token_str(buf, size) < 0)
408 return false;
410 return true;
413 /* "%3d. %s" autoscore title %sort = "inverse" %limit = "100" */
414 static int get_format_str(struct display_format *fmt)
416 int ret;
417 char buf[128];
418 int i;
420 memset(fmt, 0, sizeof(struct display_format));
422 if (get_token_str(fmt->name, sizeof fmt->name) < 0)
423 return -10;
425 /* Determine the group id */
426 fmt->group_id = 0;
427 for (i = 0; i < format_count; i++)
429 if (!strcasecmp(formats[i]->name, fmt->name))
431 fmt->group_id = formats[i]->group_id;
432 break;
435 if (formats[i]->group_id > fmt->group_id)
436 fmt->group_id = formats[i]->group_id;
439 if (i == format_count)
440 fmt->group_id++;
442 logf("format: (%d) %s", fmt->group_id, fmt->name);
444 if (get_token_str(buf, sizeof buf) < 0)
445 return -10;
447 fmt->formatstr = tagtree_strdup(buf);
449 while (fmt->tag_count < MAX_TAGS)
451 ret = get_tag(&fmt->tags[fmt->tag_count]);
452 if (ret < 0)
453 return -11;
455 if (ret == 0)
456 break;
458 switch (fmt->tags[fmt->tag_count]) {
459 case var_sorttype:
460 if (!read_variable(buf, sizeof buf))
461 return -12;
462 if (!strcasecmp("inverse", buf))
463 fmt->sort_inverse = true;
464 break;
466 case var_limit:
467 if (!read_variable(buf, sizeof buf))
468 return -13;
469 fmt->limit = atoi(buf);
470 break;
472 case var_strip:
473 if (!read_variable(buf, sizeof buf))
474 return -14;
475 fmt->strip = atoi(buf);
476 break;
478 default:
479 fmt->tag_count++;
483 return 1;
486 static int add_format(const char *buf)
488 if (format_count >= TAGMENU_MAX_FMTS)
490 logf("too many formats");
491 return -1;
494 strp = buf;
496 if (formats[format_count] == NULL)
497 formats[format_count] = tagtree_alloc0(sizeof(struct display_format));
499 if (get_format_str(formats[format_count]) < 0)
501 logf("get_format_str() parser failed!");
502 memset(formats[format_count], 0, sizeof(struct display_format));
503 return -4;
506 while (*strp != '\0' && *strp != '?')
507 strp++;
509 if (*strp == '?')
511 int clause_count = 0;
512 strp++;
514 while (1)
516 struct tagcache_search_clause *newclause;
518 if (clause_count >= TAGCACHE_MAX_CLAUSES)
520 logf("too many clauses");
521 break;
524 newclause = tagtree_alloc(sizeof(struct tagcache_search_clause));
526 formats[format_count]->clause[clause_count] = newclause;
527 if (!read_clause(newclause))
528 break;
530 clause_count++;
533 formats[format_count]->clause_count = clause_count;
536 format_count++;
538 return 1;
541 static int get_condition(struct search_instruction *inst)
543 struct tagcache_search_clause *new_clause;
544 int clause_count;
545 char buf[128];
547 switch (*strp)
549 case '=':
551 int i;
553 if (get_token_str(buf, sizeof buf) < 0)
554 return -1;
556 for (i = 0; i < format_count; i++)
558 if (!strcasecmp(formats[i]->name, buf))
559 break;
562 if (i == format_count)
564 logf("format not found: %s", buf);
565 return -2;
568 inst->format_id[inst->tagorder_count] = formats[i]->group_id;
569 return 1;
571 case '?':
572 case ' ':
573 case '&':
574 strp++;
575 return 1;
576 case '-':
577 case '\0':
578 return 0;
581 clause_count = inst->clause_count[inst->tagorder_count];
582 if (clause_count >= TAGCACHE_MAX_CLAUSES)
584 logf("Too many clauses");
585 return false;
588 new_clause = tagtree_alloc(sizeof(struct tagcache_search_clause));
589 inst->clause[inst->tagorder_count][clause_count] = new_clause;
591 if (*strp == '|')
593 strp++;
594 new_clause->type = clause_logical_or;
596 else if (!read_clause(new_clause))
597 return -1;
599 inst->clause_count[inst->tagorder_count]++;
601 return 1;
604 /* example search:
605 * "Best" artist ? year >= "2000" & title !^ "crap" & genre = "good genre" \
606 * : album ? year >= "2000" : songs
607 * ^ begins with
608 * * contains
609 * $ ends with
612 static bool parse_search(struct menu_entry *entry, const char *str)
614 int ret;
615 int type;
616 struct search_instruction *inst = &entry->si;
617 char buf[MAX_PATH];
618 int i;
619 struct menu_root *new_menu;
621 strp = str;
623 /* Parse entry name */
624 if (get_token_str(entry->name, sizeof entry->name) < 0)
626 logf("No name found.");
627 return false;
630 /* Parse entry type */
631 if (get_tag(&entry->type) <= 0)
632 return false;
634 if (entry->type == menu_load)
636 if (get_token_str(buf, sizeof buf) < 0)
637 return false;
639 /* Find the matching root menu or "create" it */
640 for (i = 0; i < menu_count; i++)
642 if (!strcasecmp(menus[i]->id, buf))
644 entry->link = i;
645 return true;
649 if (menu_count >= TAGMENU_MAX_MENUS)
651 logf("max menucount reached");
652 return false;
655 /* Allocate a new menu unless link is found. */
656 menus[menu_count] = tagtree_alloc0(sizeof(struct menu_root));
657 new_menu = menus[menu_count];
658 strlcpy(new_menu->id, buf, MAX_MENU_ID_SIZE);
659 entry->link = menu_count;
660 ++menu_count;
662 return true;
665 if (entry->type != menu_next)
666 return false;
668 while (inst->tagorder_count < MAX_TAGS)
670 ret = get_tag(&inst->tagorder[inst->tagorder_count]);
671 if (ret < 0)
673 logf("Parse error #1");
674 logf("%s", strp);
675 return false;
678 if (ret == 0)
679 break ;
681 logf("tag: %d", inst->tagorder[inst->tagorder_count]);
683 while ( (ret = get_condition(inst)) > 0 ) ;
684 if (ret < 0)
685 return false;
687 inst->tagorder_count++;
689 if (get_tag(&type) <= 0 || type != menu_next)
690 break;
693 return true;
696 static int compare(const void *p1, const void *p2)
698 struct tagentry *e1 = (struct tagentry *)p1;
699 struct tagentry *e2 = (struct tagentry *)p2;
701 if (sort_inverse)
702 return strncasecmp(e2->name, e1->name, MAX_PATH);
704 return strncasecmp(e1->name, e2->name, MAX_PATH);
707 static void tagtree_buffer_event(void *data)
709 struct tagcache_search tcs;
710 struct mp3entry *id3 = (struct mp3entry*)data;
712 /* Do not gather data unless proper setting has been enabled. */
713 if (!global_settings.runtimedb && !global_settings.autoresume_enable)
714 return;
716 logf("be:%s", id3->path);
718 while (! tagcache_is_fully_initialized())
719 yield();
721 if (!tagcache_find_index(&tcs, id3->path))
723 logf("tc stat: not found: %s", id3->path);
724 return;
727 if (global_settings.runtimedb)
729 id3->playcount = tagcache_get_numeric(&tcs, tag_playcount);
730 if (!id3->rating)
731 id3->rating = tagcache_get_numeric(&tcs, tag_rating);
732 id3->lastplayed = tagcache_get_numeric(&tcs, tag_lastplayed);
733 id3->score = tagcache_get_numeric(&tcs, tag_virt_autoscore) / 10;
734 id3->playtime = tagcache_get_numeric(&tcs, tag_playtime);
736 logf("-> %ld/%ld", id3->playcount, id3->playtime);
739 #if CONFIG_CODEC == SWCODEC
740 if (global_settings.autoresume_enable)
742 /* Load current file resume offset if not already defined (by
743 another resume mechanism) */
744 if (id3->offset == 0)
746 id3->offset = tagcache_get_numeric(&tcs, tag_lastoffset);
748 logf("tagtree_buffer_event: Set offset for %s to %lX\n",
749 str_or_empty(id3->title), id3->offset);
752 #endif
754 /* Store our tagcache index pointer. */
755 id3->tagcache_idx = tcs.idx_id+1;
757 tagcache_search_finish(&tcs);
760 static void tagtree_track_finish_event(void *data)
762 long lastplayed;
763 long tagcache_idx;
764 struct mp3entry *id3 = (struct mp3entry*)data;
766 /* Do not gather data unless proper setting has been enabled. */
767 if (!global_settings.runtimedb && !global_settings.autoresume_enable)
769 logf("runtimedb gathering and autoresume not enabled");
770 return;
773 tagcache_idx=id3->tagcache_idx;
774 if (!tagcache_idx)
776 logf("No tagcache index pointer found");
777 return;
779 tagcache_idx--;
781 /* Don't process unplayed tracks, or tracks interrupted within the
782 first 15 seconds. */
783 if (id3->elapsed == 0
784 #if CONFIG_CODEC == SWCODEC /* HWCODEC doesn't have automatic_skip */
785 || (id3->elapsed < 15 * 1000 && !audio_automatic_skip())
786 #endif
789 logf("not logging unplayed or skipped track");
790 return;
793 lastplayed = tagcache_increase_serial();
794 if (lastplayed < 0)
796 logf("incorrect tc serial:%ld", lastplayed);
797 return;
800 if (global_settings.runtimedb)
802 long playcount;
803 long playtime;
805 playcount = id3->playcount + 1;
807 /* Ignore the last 15s (crossfade etc.) */
808 playtime = id3->playtime + MIN(id3->length, id3->elapsed + 15 * 1000);
810 logf("ube:%s", id3->path);
811 logf("-> %ld/%ld", playcount, playtime);
812 logf("-> %ld/%ld/%ld", id3->elapsed, id3->length,
813 MIN(id3->length, id3->elapsed + 15 * 1000));
815 /* Queue the updates to the tagcache system. */
816 tagcache_update_numeric(tagcache_idx, tag_playcount, playcount);
817 tagcache_update_numeric(tagcache_idx, tag_playtime, playtime);
818 tagcache_update_numeric(tagcache_idx, tag_lastplayed, lastplayed);
821 #if CONFIG_CODEC == SWCODEC
822 if (global_settings.autoresume_enable)
824 unsigned long offset
825 = audio_automatic_skip() ? 0 : id3->offset;
827 tagcache_update_numeric(tagcache_idx, tag_lastoffset, offset);
829 logf("tagtree_track_finish_event: Save offset for %s: %lX",
830 str_or_empty(id3->title), offset);
832 #endif
835 bool tagtree_export(void)
837 struct tagcache_search tcs;
839 splash(0, str(LANG_CREATING));
840 if (!tagcache_create_changelog(&tcs))
842 splash(HZ*2, ID2P(LANG_FAILED));
845 return false;
848 bool tagtree_import(void)
850 splash(0, ID2P(LANG_WAIT));
851 if (!tagcache_import_changelog())
853 splash(HZ*2, ID2P(LANG_FAILED));
856 return false;
859 static bool parse_menu(const char *filename);
861 static int parse_line(int n, char *buf, void *parameters)
863 char data[256];
864 int variable;
865 static bool read_menu;
866 int i;
867 char *p;
869 (void)parameters;
871 /* Strip possible <CR> at end of line. */
872 p = strchr(buf, '\r');
873 if (p != NULL)
874 *p = '\0';
876 logf("parse:%d/%s", n, buf);
878 /* First line, do initialisation. */
879 if (n == 0)
881 if (strcasecmp(TAGNAVI_VERSION, buf))
883 logf("Version mismatch");
884 return -1;
887 read_menu = false;
890 if (buf[0] == '#')
891 return 0;
893 if (buf[0] == '\0')
895 if (read_menu)
897 /* End the menu */
898 read_menu = false;
900 return 0;
903 if (!read_menu)
905 strp = buf;
906 if (get_tag(&variable) <= 0)
907 return 0;
909 switch (variable)
911 case var_format:
912 if (add_format(strp) < 0)
914 logf("Format add fail: %s", data);
916 break;
918 case var_include:
919 if (get_token_str(data, sizeof(data)) < 0)
921 logf("%%include empty");
922 return 0;
925 if (!parse_menu(data))
927 logf("Load menu fail: %s", data);
929 break;
931 case var_menu_start:
932 if (menu_count >= TAGMENU_MAX_MENUS)
934 logf("max menucount reached");
935 return 0;
938 if (get_token_str(data, sizeof data) < 0)
940 logf("%%menu_start id empty");
941 return 0;
944 menu = NULL;
945 for (i = 0; i < menu_count; i++)
947 if (!strcasecmp(menus[i]->id, data))
949 menu = menus[i];
953 if (menu == NULL)
955 menus[menu_count] = tagtree_alloc0(sizeof(struct menu_root));
956 menu = menus[menu_count];
957 ++menu_count;
958 strlcpy(menu->id, data, MAX_MENU_ID_SIZE);
961 if (get_token_str(menu->title, sizeof(menu->title)) < 0)
963 logf("%%menu_start title empty");
964 return 0;
966 logf("menu: %s", menu->title);
967 read_menu = true;
968 break;
970 case var_rootmenu:
971 /* Only set root menu once. */
972 if (rootmenu >= 0)
973 break;
975 if (get_token_str(data, sizeof(data)) < 0)
977 logf("%%rootmenu empty");
978 return 0;
981 for (i = 0; i < menu_count; i++)
983 if (!strcasecmp(menus[i]->id, data))
985 rootmenu = i;
988 break;
991 return 0;
994 if (menu->itemcount >= TAGMENU_MAX_ITEMS)
996 logf("max itemcount reached");
997 return 0;
1000 /* Allocate */
1001 if (menu->items[menu->itemcount] == NULL)
1002 menu->items[menu->itemcount] = tagtree_alloc0(sizeof(struct menu_entry));
1004 if (!parse_search(menu->items[menu->itemcount], buf))
1005 return 0;
1007 menu->itemcount++;
1009 return 0;
1012 static bool parse_menu(const char *filename)
1014 int fd;
1015 char buf[1024];
1017 if (menu_count >= TAGMENU_MAX_MENUS)
1019 logf("max menucount reached");
1020 return false;
1023 fd = open(filename, O_RDONLY);
1024 if (fd < 0)
1026 logf("Search instruction file not found.");
1027 return false;
1030 /* Now read file for real, parsing into si */
1031 fast_readline(fd, buf, sizeof buf, NULL, parse_line);
1032 close(fd);
1034 return true;
1037 void tagtree_init(void)
1039 format_count = 0;
1040 menu_count = 0;
1041 menu = NULL;
1042 rootmenu = -1;
1043 tagtree_handle = core_alloc_maximum("tagtree", &tagtree_bufsize, NULL);
1044 parse_menu(FILE_SEARCH_INSTRUCTIONS);
1046 /* If no root menu is set, assume it's the first single menu
1047 * we have. That shouldn't normally happen. */
1048 if (rootmenu < 0)
1049 rootmenu = 0;
1051 uniqbuf = tagtree_alloc(UNIQBUF_SIZE);
1053 add_event(PLAYBACK_EVENT_TRACK_BUFFER, false, tagtree_buffer_event);
1054 add_event(PLAYBACK_EVENT_TRACK_FINISH, false, tagtree_track_finish_event);
1056 core_shrink(tagtree_handle, core_get_data(tagtree_handle), tagtree_buf_used);
1059 static bool show_search_progress(bool init, int count)
1061 static int last_tick = 0;
1063 /* Don't show splashes for 1/2 second after starting search */
1064 if (init)
1066 last_tick = current_tick + HZ/2;
1067 return true;
1070 /* Update progress every 1/10 of a second */
1071 if (TIME_AFTER(current_tick, last_tick + HZ/10))
1073 splashf(0, str(LANG_PLAYLIST_SEARCH_MSG), count, str(LANG_OFF_ABORT));
1074 if (action_userabort(TIMEOUT_NOBLOCK))
1075 return false;
1076 last_tick = current_tick;
1077 yield();
1080 return true;
1083 static int format_str(struct tagcache_search *tcs, struct display_format *fmt,
1084 char *buf, int buf_size)
1086 char fmtbuf[20];
1087 bool read_format = false;
1088 unsigned fmtbuf_pos = 0;
1089 int parpos = 0;
1090 int buf_pos = 0;
1091 int i;
1093 memset(buf, 0, buf_size);
1094 for (i = 0; fmt->formatstr[i] != '\0'; i++)
1096 if (fmt->formatstr[i] == '%')
1098 read_format = true;
1099 fmtbuf_pos = 0;
1100 if (parpos >= fmt->tag_count)
1102 logf("too many format tags");
1103 return -1;
1107 char formatchar = fmt->formatstr[i];
1109 if (read_format)
1111 fmtbuf[fmtbuf_pos++] = formatchar;
1112 if (fmtbuf_pos >= sizeof fmtbuf)
1114 logf("format parse error");
1115 return -2;
1118 if (formatchar == 's' || formatchar == 'd')
1120 unsigned space_left = buf_size - buf_pos;
1121 char tmpbuf[MAX_PATH];
1122 char *result;
1124 fmtbuf[fmtbuf_pos] = '\0';
1125 read_format = false;
1127 switch (formatchar)
1129 case 's':
1130 if (fmt->tags[parpos] == tcs->type)
1132 result = tcs->result;
1134 else
1136 /* Need to fetch the tag data. */
1137 int tag = fmt->tags[parpos];
1139 if (!tagcache_retrieve(tcs, tcs->idx_id,
1140 (tag == tag_virt_basename ?
1141 tag_filename : tag),
1142 tmpbuf, sizeof tmpbuf))
1144 logf("retrieve failed");
1145 return -3;
1148 if (tag == tag_virt_basename
1149 && (result = strrchr(tmpbuf, '/')) != NULL)
1151 result++;
1153 else
1154 result = tmpbuf;
1156 buf_pos +=
1157 snprintf(&buf[buf_pos], space_left, fmtbuf, result);
1158 break;
1160 case 'd':
1161 buf_pos +=
1162 snprintf(&buf[buf_pos], space_left, fmtbuf,
1163 tagcache_get_numeric(tcs, fmt->tags[parpos]));
1166 parpos++;
1169 else
1170 buf[buf_pos++] = formatchar;
1172 if (buf_pos >= buf_size - 1) /* need at least one more byte for \0 */
1174 logf("buffer overflow");
1175 return -4;
1179 buf[buf_pos++] = '\0';
1181 return 0;
1184 static int retrieve_entries(struct tree_context *c, int offset, bool init)
1186 struct tagcache_search tcs;
1187 struct tagentry *dptr = c->cache.entries;
1188 struct display_format *fmt;
1189 int i;
1190 int namebufused = 0;
1191 int total_count = 0;
1192 int special_entry_count = 0;
1193 int level = c->currextra;
1194 int tag;
1195 bool sort = false;
1196 int sort_limit;
1197 int strip;
1199 /* Show search progress straight away if the disk needs to spin up,
1200 otherwise show it after the normal 1/2 second delay */
1201 show_search_progress(
1202 #ifdef HAVE_DISK_STORAGE
1203 storage_disk_is_active()
1204 #else
1205 true
1206 #endif
1207 , 0);
1209 if (c->currtable == ALLSUBENTRIES)
1211 tag = tag_title;
1212 level--;
1214 else
1215 tag = csi->tagorder[level];
1217 if (!tagcache_search(&tcs, tag))
1218 return -1;
1220 /* Prevent duplicate entries in the search list. */
1221 tagcache_search_set_uniqbuf(&tcs, uniqbuf, UNIQBUF_SIZE);
1223 if (level || csi->clause_count[0] || TAGCACHE_IS_NUMERIC(tag))
1224 sort = true;
1226 for (i = 0; i < level; i++)
1228 if (TAGCACHE_IS_NUMERIC(csi->tagorder[i]))
1230 static struct tagcache_search_clause cc;
1232 memset(&cc, 0, sizeof(struct tagcache_search_clause));
1233 cc.tag = csi->tagorder[i];
1234 cc.type = clause_is;
1235 cc.numeric = true;
1236 cc.numeric_data = csi->result_seek[i];
1237 tagcache_search_add_clause(&tcs, &cc);
1239 else
1241 tagcache_search_add_filter(&tcs, csi->tagorder[i],
1242 csi->result_seek[i]);
1246 for (i = 0; i <= level; i++)
1248 int j;
1250 for (j = 0; j < csi->clause_count[i]; j++)
1251 tagcache_search_add_clause(&tcs, csi->clause[i][j]);
1254 current_offset = offset;
1255 current_entry_count = 0;
1256 c->dirfull = false;
1258 fmt = NULL;
1259 for (i = 0; i < format_count; i++)
1261 if (formats[i]->group_id == csi->format_id[level])
1262 fmt = formats[i];
1265 if (fmt)
1267 sort_inverse = fmt->sort_inverse;
1268 sort_limit = fmt->limit;
1269 strip = fmt->strip;
1270 sort = true;
1272 else
1274 sort_inverse = false;
1275 sort_limit = 0;
1276 strip = 0;
1279 if (tag != tag_title && tag != tag_filename)
1281 if (offset == 0)
1283 dptr->newtable = ALLSUBENTRIES;
1284 dptr->name = str(LANG_TAGNAVI_ALL_TRACKS);
1285 dptr++;
1286 current_entry_count++;
1287 special_entry_count++;
1289 if (offset <= 1)
1291 dptr->newtable = NAVIBROWSE;
1292 dptr->name = str(LANG_TAGNAVI_RANDOM);
1293 dptr->extraseek = -1;
1294 dptr++;
1295 current_entry_count++;
1296 special_entry_count++;
1299 total_count += 2;
1302 while (tagcache_get_next(&tcs))
1304 if (total_count++ < offset)
1305 continue;
1307 dptr->newtable = NAVIBROWSE;
1308 if (tag == tag_title || tag == tag_filename)
1310 dptr->newtable = PLAYTRACK;
1311 dptr->extraseek = tcs.idx_id;
1313 else
1314 dptr->extraseek = tcs.result_seek;
1316 fmt = NULL;
1317 /* Check the format */
1318 for (i = 0; i < format_count; i++)
1320 if (formats[i]->group_id != csi->format_id[level])
1321 continue;
1323 if (tagcache_check_clauses(&tcs, formats[i]->clause,
1324 formats[i]->clause_count))
1326 fmt = formats[i];
1327 break;
1331 if (strcmp(tcs.result, UNTAGGED) == 0)
1333 tcs.result = str(LANG_TAGNAVI_UNTAGGED);
1334 tcs.result_len = strlen(tcs.result);
1335 tcs.ramresult = true;
1338 if (!tcs.ramresult || fmt)
1340 dptr->name = &c->cache.name_buffer[namebufused];
1342 if (fmt)
1344 int ret = format_str(&tcs, fmt, dptr->name,
1345 c->cache.name_buffer_size - namebufused);
1346 if (ret == -4) /* buffer full */
1348 logf("chunk mode #2: %d", current_entry_count);
1349 c->dirfull = true;
1350 sort = false;
1351 break ;
1353 else if (ret < 0)
1355 logf("format_str() failed");
1356 tagcache_search_finish(&tcs);
1357 return 0;
1359 else
1360 namebufused += strlen(dptr->name)+1;
1362 else
1364 namebufused += tcs.result_len;
1365 if (namebufused < c->cache.name_buffer_size)
1366 strcpy(dptr->name, tcs.result);
1367 else
1369 logf("chunk mode #2a: %d", current_entry_count);
1370 c->dirfull = true;
1371 sort = false;
1372 break ;
1376 else
1377 dptr->name = tcs.result;
1379 dptr++;
1380 current_entry_count++;
1382 if (current_entry_count >= c->cache.max_entries)
1384 logf("chunk mode #3: %d", current_entry_count);
1385 c->dirfull = true;
1386 sort = false;
1387 break ;
1390 if (init && !tcs.ramsearch)
1392 if (!show_search_progress(false, total_count))
1393 { /* user aborted */
1394 tagcache_search_finish(&tcs);
1395 return current_entry_count;
1400 if (sort)
1402 int entry_size = sizeof(struct tagentry);
1403 qsort(c->cache.entries + special_entry_count * entry_size,
1404 current_entry_count - special_entry_count,
1405 entry_size, compare);
1408 if (!init)
1410 tagcache_search_finish(&tcs);
1411 return current_entry_count;
1414 while (tagcache_get_next(&tcs))
1416 if (!tcs.ramsearch)
1418 if (!show_search_progress(false, total_count))
1419 break;
1421 total_count++;
1424 tagcache_search_finish(&tcs);
1426 if (!sort && (sort_inverse || sort_limit))
1428 splashf(HZ*4, ID2P(LANG_SHOWDIR_BUFFER_FULL), total_count);
1429 logf("Too small dir buffer");
1430 return 0;
1433 if (sort_limit)
1434 total_count = MIN(total_count, sort_limit);
1436 if (strip)
1438 dptr = c->cache.entries;
1439 for (i = special_entry_count; i < current_entry_count; i++, dptr++)
1441 int len = strlen(dptr->name);
1443 if (len < strip)
1444 continue;
1446 dptr->name = &dptr->name[strip];
1450 return total_count;
1454 static int load_root(struct tree_context *c)
1456 struct tagentry *dptr = c->cache.entries;
1457 int i;
1459 tc = c;
1460 c->currtable = ROOT;
1461 if (c->dirlevel == 0)
1462 c->currextra = rootmenu;
1464 menu = menus[c->currextra];
1465 if (menu == NULL)
1466 return 0;
1468 for (i = 0; i < menu->itemcount; i++)
1470 dptr->name = menu->items[i]->name;
1471 switch (menu->items[i]->type)
1473 case menu_next:
1474 dptr->newtable = NAVIBROWSE;
1475 dptr->extraseek = i;
1476 break;
1478 case menu_load:
1479 dptr->newtable = ROOT;
1480 dptr->extraseek = menu->items[i]->link;
1481 break;
1484 dptr++;
1487 current_offset = 0;
1488 current_entry_count = i;
1490 return i;
1493 int tagtree_load(struct tree_context* c)
1495 int count;
1496 int table = c->currtable;
1498 c->dirsindir = 0;
1500 if (!table)
1502 c->dirfull = false;
1503 table = ROOT;
1504 c->currtable = table;
1505 c->currextra = rootmenu;
1508 switch (table)
1510 case ROOT:
1511 count = load_root(c);
1512 break;
1514 case ALLSUBENTRIES:
1515 case NAVIBROWSE:
1516 logf("navibrowse...");
1517 cpu_boost(true);
1518 count = retrieve_entries(c, 0, true);
1519 cpu_boost(false);
1520 break;
1522 default:
1523 logf("Unsupported table %d\n", table);
1524 return -1;
1527 if (count < 0)
1529 c->dirlevel = 0;
1530 count = load_root(c);
1531 splash(HZ, str(LANG_TAGCACHE_BUSY));
1534 /* The _total_ numer of entries available. */
1535 c->dirlength = c->filesindir = count;
1537 return count;
1540 int tagtree_enter(struct tree_context* c)
1542 int rc = 0;
1543 struct tagentry *dptr;
1544 struct mp3entry *id3;
1545 int newextra;
1546 int seek;
1547 int source;
1549 dptr = tagtree_get_entry(c, c->selected_item);
1551 c->dirfull = false;
1552 seek = dptr->extraseek;
1553 if (seek == -1)
1555 if(c->filesindir<=2)
1556 return 0;
1557 srand(current_tick);
1558 dptr = (tagtree_get_entry(c, 2+(rand() % (c->filesindir-2))));
1559 seek = dptr->extraseek;
1561 newextra = dptr->newtable;
1563 if (c->dirlevel >= MAX_DIR_LEVELS)
1564 return 0;
1566 c->selected_item_history[c->dirlevel]=c->selected_item;
1567 c->table_history[c->dirlevel] = c->currtable;
1568 c->extra_history[c->dirlevel] = c->currextra;
1569 c->pos_history[c->dirlevel] = c->firstpos;
1570 c->dirlevel++;
1572 switch (c->currtable) {
1573 case ROOT:
1574 c->currextra = newextra;
1576 if (newextra == ROOT)
1578 menu = menus[seek];
1579 c->currextra = seek;
1582 else if (newextra == NAVIBROWSE)
1584 int i, j;
1586 csi = &menu->items[seek]->si;
1587 c->currextra = 0;
1589 strlcpy(current_title[c->currextra], dptr->name,
1590 sizeof(current_title[0]));
1592 /* Read input as necessary. */
1593 for (i = 0; i < csi->tagorder_count; i++)
1595 for (j = 0; j < csi->clause_count[i]; j++)
1597 char* searchstring;
1599 if (csi->clause[i][j]->type == clause_logical_or)
1600 continue;
1602 source = csi->clause[i][j]->source;
1604 if (source == source_constant)
1605 continue;
1607 searchstring=csi->clause[i][j]->str;
1608 *searchstring = '\0';
1610 id3 = audio_current_track();
1612 if (source == source_current_path && id3)
1614 char *e;
1615 strlcpy(searchstring, id3->path, SEARCHSTR_SIZE);
1616 e = strrchr(searchstring, '/');
1617 if (e)
1618 *e = '\0';
1620 else if (source > source_runtime && id3)
1623 int k = source-source_runtime;
1624 int offset = id3_to_search_mapping[k].id3_offset;
1625 char **src = (char**)((char*)id3 + offset);
1626 if (*src)
1628 strlcpy(searchstring, *src, SEARCHSTR_SIZE);
1631 else
1633 rc = kbd_input(searchstring, SEARCHSTR_SIZE);
1634 if (rc < 0 || !searchstring[0])
1636 tagtree_exit(c);
1637 return 0;
1639 if (csi->clause[i][j]->numeric)
1640 csi->clause[i][j]->numeric_data = atoi(searchstring);
1647 c->currtable = newextra;
1649 break;
1651 case NAVIBROWSE:
1652 case ALLSUBENTRIES:
1653 if (newextra == PLAYTRACK)
1655 if (global_settings.party_mode && audio_status()) {
1656 splash(HZ, ID2P(LANG_PARTY_MODE));
1657 break;
1659 c->dirlevel--;
1660 /* about to create a new current playlist...
1661 allow user to cancel the operation */
1662 if (!warn_on_pl_erase())
1663 break;
1664 if (tagtree_play_folder(c) >= 0)
1665 rc = 2;
1666 break;
1669 c->currtable = newextra;
1670 csi->result_seek[c->currextra] = seek;
1671 if (c->currextra < csi->tagorder_count-1)
1672 c->currextra++;
1673 else
1674 c->dirlevel--;
1676 /* Update the statusbar title */
1677 strlcpy(current_title[c->currextra], dptr->name,
1678 sizeof(current_title[0]));
1679 break;
1681 default:
1682 c->dirlevel--;
1683 break;
1686 c->selected_item=0;
1687 gui_synclist_select_item(&tree_lists, c->selected_item);
1689 return rc;
1692 void tagtree_exit(struct tree_context* c)
1694 c->dirfull = false;
1695 if (c->dirlevel > 0)
1696 c->dirlevel--;
1697 c->selected_item=c->selected_item_history[c->dirlevel];
1698 gui_synclist_select_item(&tree_lists, c->selected_item);
1699 c->currtable = c->table_history[c->dirlevel];
1700 c->currextra = c->extra_history[c->dirlevel];
1701 c->firstpos = c->pos_history[c->dirlevel];
1704 int tagtree_get_filename(struct tree_context* c, char *buf, int buflen)
1706 struct tagcache_search tcs;
1707 struct tagentry *entry;
1709 entry = tagtree_get_entry(c, c->selected_item);
1711 if (!tagcache_search(&tcs, tag_filename))
1712 return -1;
1714 if (!tagcache_retrieve(&tcs, entry->extraseek, tcs.type, buf, buflen))
1716 tagcache_search_finish(&tcs);
1717 return -2;
1720 tagcache_search_finish(&tcs);
1722 return 0;
1725 static bool insert_all_playlist(struct tree_context *c, int position, bool queue)
1727 struct tagcache_search tcs;
1728 int i;
1729 char buf[MAX_PATH];
1730 int from, to, direction;
1731 int files_left = c->filesindir;
1733 cpu_boost(true);
1734 if (!tagcache_search(&tcs, tag_filename))
1736 splash(HZ, ID2P(LANG_TAGCACHE_BUSY));
1737 cpu_boost(false);
1738 return false;
1741 if (position == PLAYLIST_REPLACE)
1743 if (playlist_remove_all_tracks(NULL) == 0)
1744 position = PLAYLIST_INSERT_LAST;
1745 else
1747 cpu_boost(false);
1748 return false;
1752 if (position == PLAYLIST_INSERT_FIRST)
1754 from = c->filesindir - 1;
1755 to = -1;
1756 direction = -1;
1758 else
1760 from = 0;
1761 to = c->filesindir;
1762 direction = 1;
1765 for (i = from; i != to; i += direction)
1767 /* Count back to zero */
1768 if (!show_search_progress(false, files_left--))
1769 break;
1771 if (!tagcache_retrieve(&tcs, tagtree_get_entry(c, i)->extraseek,
1772 tcs.type, buf, sizeof buf))
1774 continue;
1777 if (playlist_insert_track(NULL, buf, position, queue, false) < 0)
1779 logf("playlist_insert_track failed");
1780 break;
1782 yield();
1784 playlist_sync(NULL);
1785 tagcache_search_finish(&tcs);
1786 cpu_boost(false);
1788 return true;
1791 bool tagtree_insert_selection_playlist(int position, bool queue)
1793 struct tagentry *dptr;
1794 char buf[MAX_PATH];
1795 int dirlevel = tc->dirlevel;
1797 show_search_progress(
1798 #ifdef HAVE_DISK_STORAGE
1799 storage_disk_is_active()
1800 #else
1801 true
1802 #endif
1803 , 0);
1806 /* We need to set the table to allsubentries. */
1807 dptr = tagtree_get_entry(tc, tc->selected_item);
1809 /* Insert a single track? */
1810 if (dptr->newtable == PLAYTRACK)
1812 if (tagtree_get_filename(tc, buf, sizeof buf) < 0)
1814 logf("tagtree_get_filename failed");
1815 return false;
1817 playlist_insert_track(NULL, buf, position, queue, true);
1819 return true;
1822 if (dptr->newtable == NAVIBROWSE)
1824 tagtree_enter(tc);
1825 tagtree_load(tc);
1826 dptr = tagtree_get_entry(tc, tc->selected_item);
1828 else if (dptr->newtable != ALLSUBENTRIES)
1830 logf("unsupported table: %d", dptr->newtable);
1831 return false;
1834 /* Now the current table should be allsubentries. */
1835 if (dptr->newtable != PLAYTRACK)
1837 tagtree_enter(tc);
1838 tagtree_load(tc);
1839 dptr = tagtree_get_entry(tc, tc->selected_item);
1841 /* And now the newtable should be playtrack. */
1842 if (dptr->newtable != PLAYTRACK)
1844 logf("newtable: %d !!", dptr->newtable);
1845 tc->dirlevel = dirlevel;
1846 return false;
1850 if (tc->filesindir <= 0)
1851 splash(HZ, ID2P(LANG_END_PLAYLIST));
1852 else
1854 logf("insert_all_playlist");
1855 if (!insert_all_playlist(tc, position, queue))
1856 splash(HZ*2, ID2P(LANG_FAILED));
1859 /* Finally return the dirlevel to its original value. */
1860 while (tc->dirlevel > dirlevel)
1861 tagtree_exit(tc);
1862 tagtree_load(tc);
1864 return true;
1867 static int tagtree_play_folder(struct tree_context* c)
1869 if (playlist_create(NULL, NULL) < 0)
1871 logf("Failed creating playlist\n");
1872 return -1;
1875 if (!insert_all_playlist(c, PLAYLIST_INSERT_LAST, false))
1876 return -2;
1878 if (global_settings.playlist_shuffle)
1879 c->selected_item = playlist_shuffle(current_tick, c->selected_item);
1880 if (!global_settings.play_selected)
1881 c->selected_item = 0;
1882 gui_synclist_select_item(&tree_lists, c->selected_item);
1884 playlist_start(c->selected_item,0);
1885 playlist_get_current()->num_inserted_tracks = 0; /* make warn on playlist erase work */
1886 return 0;
1889 struct tagentry* tagtree_get_entry(struct tree_context *c, int id)
1891 struct tagentry *entry = (struct tagentry *)c->cache.entries;
1892 int realid = id - current_offset;
1894 /* Load the next chunk if necessary. */
1895 if (realid >= current_entry_count || realid < 0)
1897 cpu_boost(true);
1898 if (retrieve_entries(c, MAX(0, id - (current_entry_count / 2)),
1899 false) < 0)
1901 logf("retrieve failed");
1902 cpu_boost(false);
1903 return NULL;
1905 realid = id - current_offset;
1906 cpu_boost(false);
1909 return &entry[realid];
1912 char *tagtree_get_title(struct tree_context* c)
1914 switch (c->currtable)
1916 case ROOT:
1917 return menu->title;
1919 case NAVIBROWSE:
1920 case ALLSUBENTRIES:
1921 return current_title[c->currextra];
1924 return "?";
1927 int tagtree_get_attr(struct tree_context* c)
1929 int attr = -1;
1930 switch (c->currtable)
1932 case NAVIBROWSE:
1933 if (csi->tagorder[c->currextra] == tag_title)
1934 attr = FILE_ATTR_AUDIO;
1935 else
1936 attr = ATTR_DIRECTORY;
1937 break;
1939 case ALLSUBENTRIES:
1940 attr = FILE_ATTR_AUDIO;
1941 break;
1943 default:
1944 attr = ATTR_DIRECTORY;
1945 break;
1948 return attr;
1951 int tagtree_get_icon(struct tree_context* c)
1953 int icon = Icon_Folder;
1955 if (tagtree_get_attr(c) == FILE_ATTR_AUDIO)
1956 icon = Icon_Audio;
1958 return icon;