Correct spelling of catalogue.
[kugel-rb.git] / apps / tagtree.c
blob3df8d9db2bb30a3b1eb1d283ad75dfbb8d7ac7ad
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 {"tracknum", tag_tracknumber},
242 {"discnum", tag_discnumber},
243 {"year", tag_year},
244 {"playcount", tag_playcount},
245 {"rating", tag_rating},
246 {"lastplayed", tag_lastplayed},
247 {"lastoffset", tag_lastoffset},
248 {"commitid", tag_commitid},
249 {"entryage", tag_virt_entryage},
250 {"autoscore", tag_virt_autoscore},
251 {"%sort", var_sorttype},
252 {"%limit", var_limit},
253 {"%strip", var_strip},
254 {"%menu_start", var_menu_start},
255 {"%include", var_include},
256 {"%root_menu", var_rootmenu},
257 {"%format", var_format},
258 {"->", menu_next},
259 {"==>", menu_load}
261 char buf[128];
262 unsigned int i;
264 /* Find the start. */
265 while ((*strp == ' ' || *strp == '>') && *strp != '\0')
266 strp++;
268 if (*strp == '\0' || *strp == '?')
269 return 0;
271 for (i = 0; i < sizeof(buf)-1; i++)
273 if (*strp == '\0' || *strp == ' ')
274 break ;
275 buf[i] = *strp;
276 strp++;
278 buf[i] = '\0';
280 for (i = 0; i < ARRAYLEN(get_tag_match); i++)
282 if (!strcasecmp(buf, get_tag_match[i].str))
284 *tag = get_tag_match[i].symbol;
285 return 1;
289 logf("NO MATCH: %s\n", buf);
290 if (buf[0] == '?')
291 return 0;
293 return -1;
296 static int get_clause(int *condition)
298 static const struct match get_clause_match[] =
300 {"=", clause_is},
301 {"==", clause_is},
302 {"!=", clause_is_not},
303 {">", clause_gt},
304 {">=", clause_gteq},
305 {"<", clause_lt},
306 {"<=", clause_lteq},
307 {"~", clause_contains},
308 {"!~", clause_not_contains},
309 {"^", clause_begins_with},
310 {"!^", clause_not_begins_with},
311 {"$", clause_ends_with},
312 {"!$", clause_not_ends_with},
313 {"@", clause_oneof}
316 char buf[4];
317 unsigned int i;
319 /* Find the start. */
320 while (*strp == ' ' && *strp != '\0')
321 strp++;
323 if (*strp == '\0')
324 return 0;
326 for (i = 0; i < sizeof(buf)-1; i++)
328 if (*strp == '\0' || *strp == ' ')
329 break ;
330 buf[i] = *strp;
331 strp++;
333 buf[i] = '\0';
335 for (i = 0; i < ARRAYLEN(get_clause_match); i++)
337 if (!strcasecmp(buf, get_clause_match[i].str))
339 *condition = get_clause_match[i].symbol;
340 return 1;
344 return 0;
347 static bool read_clause(struct tagcache_search_clause *clause)
349 char buf[SEARCHSTR_SIZE];
350 unsigned int i;
352 if (get_tag(&clause->tag) <= 0)
353 return false;
355 if (get_clause(&clause->type) <= 0)
356 return false;
358 if (get_token_str(buf, sizeof buf) < 0)
359 return false;
361 for (i=0; i<ARRAYLEN(id3_to_search_mapping); i++)
363 if (!strcasecmp(buf, id3_to_search_mapping[i].string))
364 break;
367 if (i<ARRAYLEN(id3_to_search_mapping)) /* runtime search operand found */
369 clause->source = source_runtime+i;
370 clause->str = tagtree_alloc(SEARCHSTR_SIZE);
372 else
374 clause->source = source_constant;
375 clause->str = tagtree_strdup(buf);
378 if (TAGCACHE_IS_NUMERIC(clause->tag))
380 clause->numeric = true;
381 clause->numeric_data = atoi(clause->str);
383 else
384 clause->numeric = false;
386 logf("got clause: %d/%d [%s]", clause->tag, clause->type, clause->str);
388 return true;
391 static bool read_variable(char *buf, int size)
393 int condition;
395 if (!get_clause(&condition))
396 return false;
398 if (condition != clause_is)
399 return false;
401 if (get_token_str(buf, size) < 0)
402 return false;
404 return true;
407 /* "%3d. %s" autoscore title %sort = "inverse" %limit = "100" */
408 static int get_format_str(struct display_format *fmt)
410 int ret;
411 char buf[128];
412 int i;
414 memset(fmt, 0, sizeof(struct display_format));
416 if (get_token_str(fmt->name, sizeof fmt->name) < 0)
417 return -10;
419 /* Determine the group id */
420 fmt->group_id = 0;
421 for (i = 0; i < format_count; i++)
423 if (!strcasecmp(formats[i]->name, fmt->name))
425 fmt->group_id = formats[i]->group_id;
426 break;
429 if (formats[i]->group_id > fmt->group_id)
430 fmt->group_id = formats[i]->group_id;
433 if (i == format_count)
434 fmt->group_id++;
436 logf("format: (%d) %s", fmt->group_id, fmt->name);
438 if (get_token_str(buf, sizeof buf) < 0)
439 return -10;
441 fmt->formatstr = tagtree_strdup(buf);
443 while (fmt->tag_count < MAX_TAGS)
445 ret = get_tag(&fmt->tags[fmt->tag_count]);
446 if (ret < 0)
447 return -11;
449 if (ret == 0)
450 break;
452 switch (fmt->tags[fmt->tag_count]) {
453 case var_sorttype:
454 if (!read_variable(buf, sizeof buf))
455 return -12;
456 if (!strcasecmp("inverse", buf))
457 fmt->sort_inverse = true;
458 break;
460 case var_limit:
461 if (!read_variable(buf, sizeof buf))
462 return -13;
463 fmt->limit = atoi(buf);
464 break;
466 case var_strip:
467 if (!read_variable(buf, sizeof buf))
468 return -14;
469 fmt->strip = atoi(buf);
470 break;
472 default:
473 fmt->tag_count++;
477 return 1;
480 static int add_format(const char *buf)
482 if (format_count >= TAGMENU_MAX_FMTS)
484 logf("too many formats");
485 return -1;
488 strp = buf;
490 if (formats[format_count] == NULL)
491 formats[format_count] = tagtree_alloc0(sizeof(struct display_format));
493 if (get_format_str(formats[format_count]) < 0)
495 logf("get_format_str() parser failed!");
496 memset(formats[format_count], 0, sizeof(struct display_format));
497 return -4;
500 while (*strp != '\0' && *strp != '?')
501 strp++;
503 if (*strp == '?')
505 int clause_count = 0;
506 strp++;
508 while (1)
510 struct tagcache_search_clause *newclause;
512 if (clause_count >= TAGCACHE_MAX_CLAUSES)
514 logf("too many clauses");
515 break;
518 newclause = tagtree_alloc(sizeof(struct tagcache_search_clause));
520 formats[format_count]->clause[clause_count] = newclause;
521 if (!read_clause(newclause))
522 break;
524 clause_count++;
527 formats[format_count]->clause_count = clause_count;
530 format_count++;
532 return 1;
535 static int get_condition(struct search_instruction *inst)
537 struct tagcache_search_clause *new_clause;
538 int clause_count;
539 char buf[128];
541 switch (*strp)
543 case '=':
545 int i;
547 if (get_token_str(buf, sizeof buf) < 0)
548 return -1;
550 for (i = 0; i < format_count; i++)
552 if (!strcasecmp(formats[i]->name, buf))
553 break;
556 if (i == format_count)
558 logf("format not found: %s", buf);
559 return -2;
562 inst->format_id[inst->tagorder_count] = formats[i]->group_id;
563 return 1;
565 case '?':
566 case ' ':
567 case '&':
568 strp++;
569 return 1;
570 case '-':
571 case '\0':
572 return 0;
575 clause_count = inst->clause_count[inst->tagorder_count];
576 if (clause_count >= TAGCACHE_MAX_CLAUSES)
578 logf("Too many clauses");
579 return false;
582 new_clause = tagtree_alloc(sizeof(struct tagcache_search_clause));
583 inst->clause[inst->tagorder_count][clause_count] = new_clause;
585 if (*strp == '|')
587 strp++;
588 new_clause->type = clause_logical_or;
590 else if (!read_clause(new_clause))
591 return -1;
593 inst->clause_count[inst->tagorder_count]++;
595 return 1;
598 /* example search:
599 * "Best" artist ? year >= "2000" & title !^ "crap" & genre = "good genre" \
600 * : album ? year >= "2000" : songs
601 * ^ begins with
602 * * contains
603 * $ ends with
606 static bool parse_search(struct menu_entry *entry, const char *str)
608 int ret;
609 int type;
610 struct search_instruction *inst = &entry->si;
611 char buf[MAX_PATH];
612 int i;
613 struct menu_root *new_menu;
615 strp = str;
617 /* Parse entry name */
618 if (get_token_str(entry->name, sizeof entry->name) < 0)
620 logf("No name found.");
621 return false;
624 /* Parse entry type */
625 if (get_tag(&entry->type) <= 0)
626 return false;
628 if (entry->type == menu_load)
630 if (get_token_str(buf, sizeof buf) < 0)
631 return false;
633 /* Find the matching root menu or "create" it */
634 for (i = 0; i < menu_count; i++)
636 if (!strcasecmp(menus[i]->id, buf))
638 entry->link = i;
639 return true;
643 if (menu_count >= TAGMENU_MAX_MENUS)
645 logf("max menucount reached");
646 return false;
649 /* Allocate a new menu unless link is found. */
650 menus[menu_count] = tagtree_alloc0(sizeof(struct menu_root));
651 new_menu = menus[menu_count];
652 strlcpy(new_menu->id, buf, MAX_MENU_ID_SIZE);
653 entry->link = menu_count;
654 ++menu_count;
656 return true;
659 if (entry->type != menu_next)
660 return false;
662 while (inst->tagorder_count < MAX_TAGS)
664 ret = get_tag(&inst->tagorder[inst->tagorder_count]);
665 if (ret < 0)
667 logf("Parse error #1");
668 logf("%s", strp);
669 return false;
672 if (ret == 0)
673 break ;
675 logf("tag: %d", inst->tagorder[inst->tagorder_count]);
677 while ( (ret = get_condition(inst)) > 0 ) ;
678 if (ret < 0)
679 return false;
681 inst->tagorder_count++;
683 if (get_tag(&type) <= 0 || type != menu_next)
684 break;
687 return true;
690 static int compare(const void *p1, const void *p2)
692 struct tagentry *e1 = (struct tagentry *)p1;
693 struct tagentry *e2 = (struct tagentry *)p2;
695 if (sort_inverse)
696 return strncasecmp(e2->name, e1->name, MAX_PATH);
698 return strncasecmp(e1->name, e2->name, MAX_PATH);
701 static void tagtree_buffer_event(void *data)
703 struct tagcache_search tcs;
704 struct mp3entry *id3 = (struct mp3entry*)data;
706 /* Do not gather data unless proper setting has been enabled. */
707 if (!global_settings.runtimedb && !global_settings.autoresume_enable)
708 return;
710 logf("be:%s", id3->path);
712 while (! tagcache_is_fully_initialized())
713 yield();
715 if (!tagcache_find_index(&tcs, id3->path))
717 logf("tc stat: not found: %s", id3->path);
718 return;
721 if (global_settings.runtimedb)
723 id3->playcount = tagcache_get_numeric(&tcs, tag_playcount);
724 if (!id3->rating)
725 id3->rating = tagcache_get_numeric(&tcs, tag_rating);
726 id3->lastplayed = tagcache_get_numeric(&tcs, tag_lastplayed);
727 id3->score = tagcache_get_numeric(&tcs, tag_virt_autoscore) / 10;
728 id3->playtime = tagcache_get_numeric(&tcs, tag_playtime);
730 logf("-> %ld/%ld", id3->playcount, id3->playtime);
733 #if CONFIG_CODEC == SWCODEC
734 if (global_settings.autoresume_enable)
736 /* Load current file resume offset if not already defined (by
737 another resume mechanism) */
738 if (id3->offset == 0)
740 id3->offset = tagcache_get_numeric(&tcs, tag_lastoffset);
742 logf("tagtree_buffer_event: Set offset for %s to %lX\n",
743 str_or_empty(id3->title), id3->offset);
746 #endif
748 /* Store our tagcache index pointer. */
749 id3->tagcache_idx = tcs.idx_id+1;
751 tagcache_search_finish(&tcs);
754 static void tagtree_track_finish_event(void *data)
756 long lastplayed;
757 long tagcache_idx;
758 struct mp3entry *id3 = (struct mp3entry*)data;
760 /* Do not gather data unless proper setting has been enabled. */
761 if (!global_settings.runtimedb && !global_settings.autoresume_enable)
763 logf("runtimedb gathering and autoresume not enabled");
764 return;
767 tagcache_idx=id3->tagcache_idx;
768 if (!tagcache_idx)
770 logf("No tagcache index pointer found");
771 return;
773 tagcache_idx--;
775 /* Don't process unplayed tracks, or tracks interrupted within the
776 first 15 seconds. */
777 if (id3->elapsed == 0
778 #if CONFIG_CODEC == SWCODEC /* HWCODEC doesn't have automatic_skip */
779 || (id3->elapsed < 15 * 1000 && !audio_automatic_skip())
780 #endif
783 logf("not logging unplayed or skipped track");
784 return;
787 lastplayed = tagcache_increase_serial();
788 if (lastplayed < 0)
790 logf("incorrect tc serial:%ld", lastplayed);
791 return;
794 if (global_settings.runtimedb)
796 long playcount;
797 long playtime;
799 playcount = id3->playcount + 1;
801 /* Ignore the last 15s (crossfade etc.) */
802 playtime = id3->playtime + MIN(id3->length, id3->elapsed + 15 * 1000);
804 logf("ube:%s", id3->path);
805 logf("-> %ld/%ld", playcount, playtime);
806 logf("-> %ld/%ld/%ld", id3->elapsed, id3->length,
807 MIN(id3->length, id3->elapsed + 15 * 1000));
809 /* Queue the updates to the tagcache system. */
810 tagcache_update_numeric(tagcache_idx, tag_playcount, playcount);
811 tagcache_update_numeric(tagcache_idx, tag_playtime, playtime);
812 tagcache_update_numeric(tagcache_idx, tag_lastplayed, lastplayed);
815 #if CONFIG_CODEC == SWCODEC
816 if (global_settings.autoresume_enable)
818 unsigned long offset
819 = audio_automatic_skip() ? 0 : id3->offset;
821 tagcache_update_numeric(tagcache_idx, tag_lastoffset, offset);
823 logf("tagtree_track_finish_event: Save offset for %s: %lX",
824 str_or_empty(id3->title), offset);
826 #endif
829 bool tagtree_export(void)
831 struct tagcache_search tcs;
833 splash(0, str(LANG_CREATING));
834 if (!tagcache_create_changelog(&tcs))
836 splash(HZ*2, ID2P(LANG_FAILED));
839 return false;
842 bool tagtree_import(void)
844 splash(0, ID2P(LANG_WAIT));
845 if (!tagcache_import_changelog())
847 splash(HZ*2, ID2P(LANG_FAILED));
850 return false;
853 static bool parse_menu(const char *filename);
855 static int parse_line(int n, char *buf, void *parameters)
857 char data[256];
858 int variable;
859 static bool read_menu;
860 int i;
861 char *p;
863 (void)parameters;
865 /* Strip possible <CR> at end of line. */
866 p = strchr(buf, '\r');
867 if (p != NULL)
868 *p = '\0';
870 logf("parse:%d/%s", n, buf);
872 /* First line, do initialisation. */
873 if (n == 0)
875 if (strcasecmp(TAGNAVI_VERSION, buf))
877 logf("Version mismatch");
878 return -1;
881 read_menu = false;
884 if (buf[0] == '#')
885 return 0;
887 if (buf[0] == '\0')
889 if (read_menu)
891 /* End the menu */
892 read_menu = false;
894 return 0;
897 if (!read_menu)
899 strp = buf;
900 if (get_tag(&variable) <= 0)
901 return 0;
903 switch (variable)
905 case var_format:
906 if (add_format(strp) < 0)
908 logf("Format add fail: %s", data);
910 break;
912 case var_include:
913 if (get_token_str(data, sizeof(data)) < 0)
915 logf("%%include empty");
916 return 0;
919 if (!parse_menu(data))
921 logf("Load menu fail: %s", data);
923 break;
925 case var_menu_start:
926 if (menu_count >= TAGMENU_MAX_MENUS)
928 logf("max menucount reached");
929 return 0;
932 if (get_token_str(data, sizeof data) < 0)
934 logf("%%menu_start id empty");
935 return 0;
938 menu = NULL;
939 for (i = 0; i < menu_count; i++)
941 if (!strcasecmp(menus[i]->id, data))
943 menu = menus[i];
947 if (menu == NULL)
949 menus[menu_count] = tagtree_alloc0(sizeof(struct menu_root));
950 menu = menus[menu_count];
951 ++menu_count;
952 strlcpy(menu->id, data, MAX_MENU_ID_SIZE);
955 if (get_token_str(menu->title, sizeof(menu->title)) < 0)
957 logf("%%menu_start title empty");
958 return 0;
960 logf("menu: %s", menu->title);
961 read_menu = true;
962 break;
964 case var_rootmenu:
965 /* Only set root menu once. */
966 if (rootmenu >= 0)
967 break;
969 if (get_token_str(data, sizeof(data)) < 0)
971 logf("%%rootmenu empty");
972 return 0;
975 for (i = 0; i < menu_count; i++)
977 if (!strcasecmp(menus[i]->id, data))
979 rootmenu = i;
982 break;
985 return 0;
988 if (menu->itemcount >= TAGMENU_MAX_ITEMS)
990 logf("max itemcount reached");
991 return 0;
994 /* Allocate */
995 if (menu->items[menu->itemcount] == NULL)
996 menu->items[menu->itemcount] = tagtree_alloc0(sizeof(struct menu_entry));
998 if (!parse_search(menu->items[menu->itemcount], buf))
999 return 0;
1001 menu->itemcount++;
1003 return 0;
1006 static bool parse_menu(const char *filename)
1008 int fd;
1009 char buf[1024];
1011 if (menu_count >= TAGMENU_MAX_MENUS)
1013 logf("max menucount reached");
1014 return false;
1017 fd = open(filename, O_RDONLY);
1018 if (fd < 0)
1020 logf("Search instruction file not found.");
1021 return false;
1024 /* Now read file for real, parsing into si */
1025 fast_readline(fd, buf, sizeof buf, NULL, parse_line);
1026 close(fd);
1028 return true;
1031 void tagtree_init(void)
1033 format_count = 0;
1034 menu_count = 0;
1035 menu = NULL;
1036 rootmenu = -1;
1037 parse_menu(FILE_SEARCH_INSTRUCTIONS);
1039 /* If no root menu is set, assume it's the first single menu
1040 * we have. That shouldn't normally happen. */
1041 if (rootmenu < 0)
1042 rootmenu = 0;
1044 uniqbuf = tagtree_alloc(UNIQBUF_SIZE);
1046 add_event(PLAYBACK_EVENT_TRACK_BUFFER, false, tagtree_buffer_event);
1047 add_event(PLAYBACK_EVENT_TRACK_FINISH, false, tagtree_track_finish_event);
1050 static bool show_search_progress(bool init, int count)
1052 static int last_tick = 0;
1054 /* Don't show splashes for 1/2 second after starting search */
1055 if (init)
1057 last_tick = current_tick + HZ/2;
1058 return true;
1061 /* Update progress every 1/10 of a second */
1062 if (TIME_AFTER(current_tick, last_tick + HZ/10))
1064 splashf(0, str(LANG_PLAYLIST_SEARCH_MSG), count, str(LANG_OFF_ABORT));
1065 if (action_userabort(TIMEOUT_NOBLOCK))
1066 return false;
1067 last_tick = current_tick;
1068 yield();
1071 return true;
1074 static int format_str(struct tagcache_search *tcs, struct display_format *fmt,
1075 char *buf, int buf_size)
1077 char fmtbuf[8];
1078 bool read_format = false;
1079 int fmtbuf_pos = 0;
1080 int parpos = 0;
1081 int buf_pos = 0;
1082 int i;
1084 memset(buf, 0, buf_size);
1085 for (i = 0; fmt->formatstr[i] != '\0'; i++)
1087 if (fmt->formatstr[i] == '%')
1089 read_format = true;
1090 fmtbuf_pos = 0;
1091 if (parpos >= fmt->tag_count)
1093 logf("too many format tags");
1094 return -1;
1098 if (read_format)
1100 fmtbuf[fmtbuf_pos++] = fmt->formatstr[i];
1101 if (fmtbuf_pos >= buf_size)
1103 logf("format parse error");
1104 return -2;
1107 if (fmt->formatstr[i] == 's')
1109 fmtbuf[fmtbuf_pos] = '\0';
1110 read_format = false;
1111 if (fmt->tags[parpos] == tcs->type)
1113 snprintf(&buf[buf_pos], buf_size - buf_pos, fmtbuf, tcs->result);
1115 else
1117 /* Need to fetch the tag data. */
1118 if (!tagcache_retrieve(tcs, tcs->idx_id, fmt->tags[parpos],
1119 &buf[buf_pos], buf_size - buf_pos))
1121 logf("retrieve failed");
1122 return -3;
1125 buf_pos += strlen(&buf[buf_pos]);
1126 parpos++;
1128 else if (fmt->formatstr[i] == 'd')
1130 fmtbuf[fmtbuf_pos] = '\0';
1131 read_format = false;
1132 snprintf(&buf[buf_pos], buf_size - buf_pos, fmtbuf,
1133 tagcache_get_numeric(tcs, fmt->tags[parpos]));
1134 buf_pos += strlen(&buf[buf_pos]);
1135 parpos++;
1137 continue;
1140 buf[buf_pos++] = fmt->formatstr[i];
1142 if (buf_pos - 1 >= buf_size)
1144 logf("buffer overflow");
1145 return -4;
1149 buf[buf_pos++] = '\0';
1151 return 0;
1154 static int retrieve_entries(struct tree_context *c, int offset, bool init)
1156 struct tagcache_search tcs;
1157 struct tagentry *dptr = (struct tagentry *)c->dircache;
1158 struct display_format *fmt;
1159 int i;
1160 int namebufused = 0;
1161 int total_count = 0;
1162 int special_entry_count = 0;
1163 int level = c->currextra;
1164 int tag;
1165 bool sort = false;
1166 int sort_limit;
1167 int strip;
1169 /* Show search progress straight away if the disk needs to spin up,
1170 otherwise show it after the normal 1/2 second delay */
1171 show_search_progress(
1172 #ifdef HAVE_DISK_STORAGE
1173 storage_disk_is_active()
1174 #else
1175 true
1176 #endif
1177 , 0);
1179 if (c->currtable == ALLSUBENTRIES)
1181 tag = tag_title;
1182 level--;
1184 else
1185 tag = csi->tagorder[level];
1187 if (!tagcache_search(&tcs, tag))
1188 return -1;
1190 /* Prevent duplicate entries in the search list. */
1191 tagcache_search_set_uniqbuf(&tcs, uniqbuf, UNIQBUF_SIZE);
1193 if (level || csi->clause_count[0] || TAGCACHE_IS_NUMERIC(tag))
1194 sort = true;
1196 for (i = 0; i < level; i++)
1198 if (TAGCACHE_IS_NUMERIC(csi->tagorder[i]))
1200 static struct tagcache_search_clause cc;
1202 memset(&cc, 0, sizeof(struct tagcache_search_clause));
1203 cc.tag = csi->tagorder[i];
1204 cc.type = clause_is;
1205 cc.numeric = true;
1206 cc.numeric_data = csi->result_seek[i];
1207 tagcache_search_add_clause(&tcs, &cc);
1209 else
1211 tagcache_search_add_filter(&tcs, csi->tagorder[i],
1212 csi->result_seek[i]);
1216 for (i = 0; i <= level; i++)
1218 int j;
1220 for (j = 0; j < csi->clause_count[i]; j++)
1221 tagcache_search_add_clause(&tcs, csi->clause[i][j]);
1224 current_offset = offset;
1225 current_entry_count = 0;
1226 c->dirfull = false;
1228 fmt = NULL;
1229 for (i = 0; i < format_count; i++)
1231 if (formats[i]->group_id == csi->format_id[level])
1232 fmt = formats[i];
1235 if (fmt)
1237 sort_inverse = fmt->sort_inverse;
1238 sort_limit = fmt->limit;
1239 strip = fmt->strip;
1240 sort = true;
1242 else
1244 sort_inverse = false;
1245 sort_limit = 0;
1246 strip = 0;
1249 if (tag != tag_title && tag != tag_filename)
1251 if (offset == 0)
1253 dptr->newtable = ALLSUBENTRIES;
1254 dptr->name = str(LANG_TAGNAVI_ALL_TRACKS);
1255 dptr++;
1256 current_entry_count++;
1258 if (offset <= 1)
1260 dptr->newtable = NAVIBROWSE;
1261 dptr->name = str(LANG_TAGNAVI_RANDOM);
1262 dptr->extraseek = -1;
1263 dptr++;
1264 current_entry_count++;
1266 special_entry_count+=2;
1269 total_count += special_entry_count;
1271 while (tagcache_get_next(&tcs))
1273 if (total_count++ < offset)
1274 continue;
1276 dptr->newtable = NAVIBROWSE;
1277 if (tag == tag_title || tag == tag_filename)
1279 dptr->newtable = PLAYTRACK;
1280 dptr->extraseek = tcs.idx_id;
1282 else
1283 dptr->extraseek = tcs.result_seek;
1285 fmt = NULL;
1286 /* Check the format */
1287 for (i = 0; i < format_count; i++)
1289 if (formats[i]->group_id != csi->format_id[level])
1290 continue;
1292 if (tagcache_check_clauses(&tcs, formats[i]->clause,
1293 formats[i]->clause_count))
1295 fmt = formats[i];
1296 break;
1300 if (strcmp(tcs.result, UNTAGGED) == 0)
1302 tcs.result = str(LANG_TAGNAVI_UNTAGGED);
1303 tcs.result_len = strlen(tcs.result);
1304 tcs.ramresult = true;
1307 if (!tcs.ramresult || fmt)
1309 char buf[MAX_PATH];
1311 if (fmt)
1313 if (format_str(&tcs, fmt, buf, sizeof buf) < 0)
1315 logf("format_str() failed");
1316 tagcache_search_finish(&tcs);
1317 return 0;
1321 dptr->name = &c->name_buffer[namebufused];
1322 if (fmt)
1323 namebufused += strlen(buf)+1;
1324 else
1325 namebufused += tcs.result_len;
1327 if (namebufused >= c->name_buffer_size)
1329 logf("chunk mode #2: %d", current_entry_count);
1330 c->dirfull = true;
1331 sort = false;
1332 break ;
1334 if (fmt)
1335 strcpy(dptr->name, buf);
1336 else
1337 strcpy(dptr->name, tcs.result);
1339 else
1340 dptr->name = tcs.result;
1342 dptr++;
1343 current_entry_count++;
1345 if (current_entry_count >= c->dircache_count)
1347 logf("chunk mode #3: %d", current_entry_count);
1348 c->dirfull = true;
1349 sort = false;
1350 break ;
1353 if (init && !tcs.ramsearch)
1355 if (!show_search_progress(false, total_count))
1356 { /* user aborted */
1357 tagcache_search_finish(&tcs);
1358 return current_entry_count;
1363 if (sort)
1364 qsort(c->dircache + special_entry_count * c->dentry_size,
1365 current_entry_count - special_entry_count,
1366 c->dentry_size, compare);
1368 if (!init)
1370 tagcache_search_finish(&tcs);
1371 return current_entry_count;
1374 while (tagcache_get_next(&tcs))
1376 if (!tcs.ramsearch)
1378 if (!show_search_progress(false, total_count))
1379 break;
1381 total_count++;
1384 tagcache_search_finish(&tcs);
1386 if (!sort && (sort_inverse || sort_limit))
1388 splashf(HZ*4, ID2P(LANG_SHOWDIR_BUFFER_FULL), total_count);
1389 logf("Too small dir buffer");
1390 return 0;
1393 if (sort_limit)
1394 total_count = MIN(total_count, sort_limit);
1396 if (strip)
1398 dptr = c->dircache;
1399 for (i = 0; i < total_count; i++, dptr++)
1401 int len = strlen(dptr->name);
1403 if (len < strip)
1404 continue;
1406 dptr->name = &dptr->name[strip];
1410 return total_count;
1414 static int load_root(struct tree_context *c)
1416 struct tagentry *dptr = (struct tagentry *)c->dircache;
1417 int i;
1419 tc = c;
1420 c->currtable = ROOT;
1421 if (c->dirlevel == 0)
1422 c->currextra = rootmenu;
1424 menu = menus[c->currextra];
1425 if (menu == NULL)
1426 return 0;
1428 for (i = 0; i < menu->itemcount; i++)
1430 dptr->name = menu->items[i]->name;
1431 switch (menu->items[i]->type)
1433 case menu_next:
1434 dptr->newtable = NAVIBROWSE;
1435 dptr->extraseek = i;
1436 break;
1438 case menu_load:
1439 dptr->newtable = ROOT;
1440 dptr->extraseek = menu->items[i]->link;
1441 break;
1444 dptr++;
1447 current_offset = 0;
1448 current_entry_count = i;
1450 return i;
1453 int tagtree_load(struct tree_context* c)
1455 int count;
1456 int table = c->currtable;
1458 c->dentry_size = sizeof(struct tagentry);
1459 c->dirsindir = 0;
1461 if (!table)
1463 c->dirfull = false;
1464 table = ROOT;
1465 c->currtable = table;
1466 c->currextra = rootmenu;
1469 switch (table)
1471 case ROOT:
1472 count = load_root(c);
1473 break;
1475 case ALLSUBENTRIES:
1476 case NAVIBROWSE:
1477 logf("navibrowse...");
1478 cpu_boost(true);
1479 count = retrieve_entries(c, 0, true);
1480 cpu_boost(false);
1481 break;
1483 default:
1484 logf("Unsupported table %d\n", table);
1485 return -1;
1488 if (count < 0)
1490 c->dirlevel = 0;
1491 count = load_root(c);
1492 splash(HZ, str(LANG_TAGCACHE_BUSY));
1495 /* The _total_ numer of entries available. */
1496 c->dirlength = c->filesindir = count;
1498 return count;
1501 int tagtree_enter(struct tree_context* c)
1503 int rc = 0;
1504 struct tagentry *dptr;
1505 struct mp3entry *id3;
1506 int newextra;
1507 int seek;
1508 int source;
1510 dptr = tagtree_get_entry(c, c->selected_item);
1512 c->dirfull = false;
1513 seek = dptr->extraseek;
1514 if (seek == -1)
1516 if(c->filesindir<=2)
1517 return 0;
1518 srand(current_tick);
1519 dptr = (tagtree_get_entry(c, 2+(rand() % (c->filesindir-2))));
1520 seek = dptr->extraseek;
1522 newextra = dptr->newtable;
1524 if (c->dirlevel >= MAX_DIR_LEVELS)
1525 return 0;
1527 c->selected_item_history[c->dirlevel]=c->selected_item;
1528 c->table_history[c->dirlevel] = c->currtable;
1529 c->extra_history[c->dirlevel] = c->currextra;
1530 c->pos_history[c->dirlevel] = c->firstpos;
1531 c->dirlevel++;
1533 switch (c->currtable) {
1534 case ROOT:
1535 c->currextra = newextra;
1537 if (newextra == ROOT)
1539 menu = menus[seek];
1540 c->currextra = seek;
1543 else if (newextra == NAVIBROWSE)
1545 int i, j;
1547 csi = &menu->items[seek]->si;
1548 c->currextra = 0;
1550 strlcpy(current_title[c->currextra], dptr->name,
1551 sizeof(current_title[0]));
1553 /* Read input as necessary. */
1554 for (i = 0; i < csi->tagorder_count; i++)
1556 for (j = 0; j < csi->clause_count[i]; j++)
1558 char* searchstring;
1560 if (csi->clause[i][j]->type == clause_logical_or)
1561 continue;
1563 source = csi->clause[i][j]->source;
1565 if (source == source_constant)
1566 continue;
1568 searchstring=csi->clause[i][j]->str;
1569 *searchstring = '\0';
1571 id3 = audio_current_track();
1573 if (source == source_current_path && id3)
1575 char *e;
1576 strlcpy(searchstring, id3->path, SEARCHSTR_SIZE);
1577 e = strrchr(searchstring, '/');
1578 if (e)
1579 *e = '\0';
1581 else if (source > source_runtime && id3)
1584 int k = source-source_runtime;
1585 int offset = id3_to_search_mapping[k].id3_offset;
1586 char **src = (char**)((char*)id3 + offset);
1587 if (*src)
1589 strlcpy(searchstring, *src, SEARCHSTR_SIZE);
1592 else
1594 rc = kbd_input(searchstring, SEARCHSTR_SIZE);
1595 if (rc < 0 || !searchstring[0])
1597 tagtree_exit(c);
1598 return 0;
1600 if (csi->clause[i][j]->numeric)
1601 csi->clause[i][j]->numeric_data = atoi(searchstring);
1608 c->currtable = newextra;
1610 break;
1612 case NAVIBROWSE:
1613 case ALLSUBENTRIES:
1614 if (newextra == PLAYTRACK)
1616 if (global_settings.party_mode && audio_status()) {
1617 splash(HZ, ID2P(LANG_PARTY_MODE));
1618 break;
1620 c->dirlevel--;
1621 /* about to create a new current playlist...
1622 allow user to cancel the operation */
1623 if (!warn_on_pl_erase())
1624 break;
1625 if (tagtree_play_folder(c) >= 0)
1626 rc = 2;
1627 break;
1630 c->currtable = newextra;
1631 csi->result_seek[c->currextra] = seek;
1632 if (c->currextra < csi->tagorder_count-1)
1633 c->currextra++;
1634 else
1635 c->dirlevel--;
1637 /* Update the statusbar title */
1638 strlcpy(current_title[c->currextra], dptr->name,
1639 sizeof(current_title[0]));
1640 break;
1642 default:
1643 c->dirlevel--;
1644 break;
1647 c->selected_item=0;
1648 gui_synclist_select_item(&tree_lists, c->selected_item);
1650 return rc;
1653 void tagtree_exit(struct tree_context* c)
1655 c->dirfull = false;
1656 if (c->dirlevel > 0)
1657 c->dirlevel--;
1658 c->selected_item=c->selected_item_history[c->dirlevel];
1659 gui_synclist_select_item(&tree_lists, c->selected_item);
1660 c->currtable = c->table_history[c->dirlevel];
1661 c->currextra = c->extra_history[c->dirlevel];
1662 c->firstpos = c->pos_history[c->dirlevel];
1665 int tagtree_get_filename(struct tree_context* c, char *buf, int buflen)
1667 struct tagcache_search tcs;
1668 struct tagentry *entry;
1670 entry = tagtree_get_entry(c, c->selected_item);
1672 if (!tagcache_search(&tcs, tag_filename))
1673 return -1;
1675 if (!tagcache_retrieve(&tcs, entry->extraseek, tcs.type, buf, buflen))
1677 tagcache_search_finish(&tcs);
1678 return -2;
1681 tagcache_search_finish(&tcs);
1683 return 0;
1686 static bool insert_all_playlist(struct tree_context *c, int position, bool queue)
1688 struct tagcache_search tcs;
1689 int i;
1690 char buf[MAX_PATH];
1691 int from, to, direction;
1692 int files_left = c->filesindir;
1694 cpu_boost(true);
1695 if (!tagcache_search(&tcs, tag_filename))
1697 splash(HZ, ID2P(LANG_TAGCACHE_BUSY));
1698 cpu_boost(false);
1699 return false;
1702 if (position == PLAYLIST_REPLACE)
1704 if (playlist_remove_all_tracks(NULL) == 0)
1705 position = PLAYLIST_INSERT_LAST;
1706 else
1708 cpu_boost(false);
1709 return false;
1713 if (position == PLAYLIST_INSERT_FIRST)
1715 from = c->filesindir - 1;
1716 to = -1;
1717 direction = -1;
1719 else
1721 from = 0;
1722 to = c->filesindir;
1723 direction = 1;
1726 for (i = from; i != to; i += direction)
1728 /* Count back to zero */
1729 if (!show_search_progress(false, files_left--))
1730 break;
1732 if (!tagcache_retrieve(&tcs, tagtree_get_entry(c, i)->extraseek,
1733 tcs.type, buf, sizeof buf))
1735 continue;
1738 if (playlist_insert_track(NULL, buf, position, queue, false) < 0)
1740 logf("playlist_insert_track failed");
1741 break;
1743 yield();
1745 playlist_sync(NULL);
1746 tagcache_search_finish(&tcs);
1747 cpu_boost(false);
1749 return true;
1752 bool tagtree_insert_selection_playlist(int position, bool queue)
1754 struct tagentry *dptr;
1755 char buf[MAX_PATH];
1756 int dirlevel = tc->dirlevel;
1758 show_search_progress(
1759 #ifdef HAVE_DISK_STORAGE
1760 storage_disk_is_active()
1761 #else
1762 true
1763 #endif
1764 , 0);
1767 /* We need to set the table to allsubentries. */
1768 dptr = tagtree_get_entry(tc, tc->selected_item);
1770 /* Insert a single track? */
1771 if (dptr->newtable == PLAYTRACK)
1773 if (tagtree_get_filename(tc, buf, sizeof buf) < 0)
1775 logf("tagtree_get_filename failed");
1776 return false;
1778 playlist_insert_track(NULL, buf, position, queue, true);
1780 return true;
1783 if (dptr->newtable == NAVIBROWSE)
1785 tagtree_enter(tc);
1786 tagtree_load(tc);
1787 dptr = tagtree_get_entry(tc, tc->selected_item);
1789 else if (dptr->newtable != ALLSUBENTRIES)
1791 logf("unsupported table: %d", dptr->newtable);
1792 return false;
1795 /* Now the current table should be allsubentries. */
1796 if (dptr->newtable != PLAYTRACK)
1798 tagtree_enter(tc);
1799 tagtree_load(tc);
1800 dptr = tagtree_get_entry(tc, tc->selected_item);
1802 /* And now the newtable should be playtrack. */
1803 if (dptr->newtable != PLAYTRACK)
1805 logf("newtable: %d !!", dptr->newtable);
1806 tc->dirlevel = dirlevel;
1807 return false;
1811 if (tc->filesindir <= 0)
1812 splash(HZ, ID2P(LANG_END_PLAYLIST));
1813 else
1815 logf("insert_all_playlist");
1816 if (!insert_all_playlist(tc, position, queue))
1817 splash(HZ*2, ID2P(LANG_FAILED));
1820 /* Finally return the dirlevel to its original value. */
1821 while (tc->dirlevel > dirlevel)
1822 tagtree_exit(tc);
1823 tagtree_load(tc);
1825 return true;
1828 static int tagtree_play_folder(struct tree_context* c)
1830 if (playlist_create(NULL, NULL) < 0)
1832 logf("Failed creating playlist\n");
1833 return -1;
1836 if (!insert_all_playlist(c, PLAYLIST_INSERT_LAST, false))
1837 return -2;
1839 if (global_settings.playlist_shuffle)
1840 c->selected_item = playlist_shuffle(current_tick, c->selected_item);
1841 if (!global_settings.play_selected)
1842 c->selected_item = 0;
1843 gui_synclist_select_item(&tree_lists, c->selected_item);
1845 playlist_start(c->selected_item,0);
1846 playlist_get_current()->num_inserted_tracks = 0; /* make warn on playlist erase work */
1847 return 0;
1850 struct tagentry* tagtree_get_entry(struct tree_context *c, int id)
1852 struct tagentry *entry = (struct tagentry *)c->dircache;
1853 int realid = id - current_offset;
1855 /* Load the next chunk if necessary. */
1856 if (realid >= current_entry_count || realid < 0)
1858 cpu_boost(true);
1859 if (retrieve_entries(c, MAX(0, id - (current_entry_count / 2)),
1860 false) < 0)
1862 logf("retrieve failed");
1863 cpu_boost(false);
1864 return NULL;
1866 realid = id - current_offset;
1867 cpu_boost(false);
1870 return &entry[realid];
1873 char *tagtree_get_title(struct tree_context* c)
1875 switch (c->currtable)
1877 case ROOT:
1878 return menu->title;
1880 case NAVIBROWSE:
1881 case ALLSUBENTRIES:
1882 return current_title[c->currextra];
1885 return "?";
1888 int tagtree_get_attr(struct tree_context* c)
1890 int attr = -1;
1891 switch (c->currtable)
1893 case NAVIBROWSE:
1894 if (csi->tagorder[c->currextra] == tag_title)
1895 attr = FILE_ATTR_AUDIO;
1896 else
1897 attr = ATTR_DIRECTORY;
1898 break;
1900 case ALLSUBENTRIES:
1901 attr = FILE_ATTR_AUDIO;
1902 break;
1904 default:
1905 attr = ATTR_DIRECTORY;
1906 break;
1909 return attr;
1912 int tagtree_get_icon(struct tree_context* c)
1914 int icon = Icon_Folder;
1916 if (tagtree_get_attr(c) == FILE_ATTR_AUDIO)
1917 icon = Icon_Audio;
1919 return icon;