Move android notification display format logic to java code (no functional change...
[kugel-rb.git] / apps / tagtree.c
blobfa88a5941b7f0b44b87cd11ac91d2cbe49065b91
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"
56 #define str_or_empty(x) (x ? x : "(NULL)")
58 #define FILE_SEARCH_INSTRUCTIONS ROCKBOX_DIR "/tagnavi.config"
60 static int tagtree_play_folder(struct tree_context* c);
62 #define SEARCHSTR_SIZE 256
64 enum table {
65 ROOT = 1,
66 NAVIBROWSE,
67 ALLSUBENTRIES,
68 PLAYTRACK,
71 static const struct id3_to_search_mapping {
72 char *string;
73 size_t id3_offset;
74 } id3_to_search_mapping[] = {
75 { "", 0 }, /* offset n/a */
76 { "#directory#", 0 }, /* offset n/a */
77 { "#title#", offsetof(struct mp3entry, title) },
78 { "#artist#", offsetof(struct mp3entry, artist) },
79 { "#album#", offsetof(struct mp3entry, album) },
80 { "#genre#", offsetof(struct mp3entry, genre_string) },
81 { "#composer#", offsetof(struct mp3entry, composer) },
82 { "#albumartist#", offsetof(struct mp3entry, albumartist) },
84 enum variables {
85 var_sorttype = 100,
86 var_limit,
87 var_strip,
88 var_menu_start,
89 var_include,
90 var_rootmenu,
91 var_format,
92 menu_next,
93 menu_load,
96 /* Capacity 10 000 entries (for example 10k different artists) */
97 #define UNIQBUF_SIZE (64*1024)
98 static long *uniqbuf;
100 #define MAX_TAGS 5
101 #define MAX_MENU_ID_SIZE 32
103 static bool sort_inverse;
106 * "%3d. %s" autoscore title %sort = "inverse" %limit = "100"
108 * valid = true
109 * formatstr = "%-3d. %s"
110 * tags[0] = tag_autoscore
111 * tags[1] = tag_title
112 * tag_count = 2
114 * limit = 100
115 * sort_inverse = true
117 struct display_format {
118 char name[32];
119 struct tagcache_search_clause *clause[TAGCACHE_MAX_CLAUSES];
120 int clause_count;
121 char *formatstr;
122 int group_id;
123 int tags[MAX_TAGS];
124 int tag_count;
126 int limit;
127 int strip;
128 bool sort_inverse;
131 static struct display_format *formats[TAGMENU_MAX_FMTS];
132 static int format_count;
134 struct search_instruction {
135 char name[64];
136 int tagorder[MAX_TAGS];
137 int tagorder_count;
138 struct tagcache_search_clause *clause[MAX_TAGS][TAGCACHE_MAX_CLAUSES];
139 int format_id[MAX_TAGS];
140 int clause_count[MAX_TAGS];
141 int result_seek[MAX_TAGS];
144 struct menu_entry {
145 char name[64];
146 int type;
147 struct search_instruction *si;
148 int link;
151 struct menu_root {
152 char title[64];
153 char id[MAX_MENU_ID_SIZE];
154 int itemcount;
155 struct menu_entry *items[TAGMENU_MAX_ITEMS];
158 /* Statusbar text of the current view. */
159 static char current_title[MAX_TAGS][128];
161 static struct menu_root *menus[TAGMENU_MAX_MENUS];
162 static struct menu_root *menu;
163 static struct search_instruction *csi;
164 static const char *strp;
165 static int menu_count;
166 static int rootmenu;
168 static int current_offset;
169 static int current_entry_count;
171 static struct tree_context *tc;
173 #if CONFIG_CODEC == SWCODEC
174 extern bool automatic_skip; /* Who initiated in-progress skip? (C/A-) */
175 #endif
177 static int get_token_str(char *buf, int size)
179 /* Find the start. */
180 while (*strp != '"' && *strp != '\0')
181 strp++;
183 if (*strp == '\0' || *(++strp) == '\0')
184 return -1;
186 /* Read the data. */
187 while (*strp != '"' && *strp != '\0' && --size > 0)
188 *(buf++) = *(strp++);
190 *buf = '\0';
191 if (*strp != '"')
192 return -2;
194 strp++;
196 return 0;
199 #define MATCH(tag,str1,str2,settag) \
200 if (!strcasecmp(str1, str2)) { \
201 *tag = settag; \
202 return 1; \
205 static int get_tag(int *tag)
207 char buf[128];
208 int i;
210 /* Find the start. */
211 while ((*strp == ' ' || *strp == '>') && *strp != '\0')
212 strp++;
214 if (*strp == '\0' || *strp == '?')
215 return 0;
217 for (i = 0; i < (int)sizeof(buf)-1; i++)
219 if (*strp == '\0' || *strp == ' ')
220 break ;
221 buf[i] = *strp;
222 strp++;
224 buf[i] = '\0';
226 MATCH(tag, buf, "album", tag_album);
227 MATCH(tag, buf, "artist", tag_artist);
228 MATCH(tag, buf, "bitrate", tag_bitrate);
229 MATCH(tag, buf, "composer", tag_composer);
230 MATCH(tag, buf, "comment", tag_comment);
231 MATCH(tag, buf, "albumartist", tag_albumartist);
232 MATCH(tag, buf, "ensemble", tag_albumartist);
233 MATCH(tag, buf, "grouping", tag_grouping);
234 MATCH(tag, buf, "genre", tag_genre);
235 MATCH(tag, buf, "length", tag_length);
236 MATCH(tag, buf, "Lm", tag_virt_length_min);
237 MATCH(tag, buf, "Ls", tag_virt_length_sec);
238 MATCH(tag, buf, "Pm", tag_virt_playtime_min);
239 MATCH(tag, buf, "Ps", tag_virt_playtime_sec);
240 MATCH(tag, buf, "title", tag_title);
241 MATCH(tag, buf, "filename", tag_filename);
242 MATCH(tag, buf, "tracknum", tag_tracknumber);
243 MATCH(tag, buf, "discnum", tag_discnumber);
244 MATCH(tag, buf, "year", tag_year);
245 MATCH(tag, buf, "playcount", tag_playcount);
246 MATCH(tag, buf, "rating", tag_rating);
247 MATCH(tag, buf, "lastplayed", tag_lastplayed);
248 MATCH(tag, buf, "lastoffset", tag_lastoffset);
249 MATCH(tag, buf, "commitid", tag_commitid);
250 MATCH(tag, buf, "entryage", tag_virt_entryage);
251 MATCH(tag, buf, "autoscore", tag_virt_autoscore);
252 MATCH(tag, buf, "%sort", var_sorttype);
253 MATCH(tag, buf, "%limit", var_limit);
254 MATCH(tag, buf, "%strip", var_strip);
255 MATCH(tag, buf, "%menu_start", var_menu_start);
256 MATCH(tag, buf, "%include", var_include);
257 MATCH(tag, buf, "%root_menu", var_rootmenu);
258 MATCH(tag, buf, "%format", var_format);
259 MATCH(tag, buf, "->", menu_next);
260 MATCH(tag, buf, "==>", menu_load);
262 logf("NO MATCH: %s\n", buf);
263 if (buf[0] == '?')
264 return 0;
266 return -1;
269 static int get_clause(int *condition)
271 char buf[4];
272 int i;
274 /* Find the start. */
275 while (*strp == ' ' && *strp != '\0')
276 strp++;
278 if (*strp == '\0')
279 return 0;
281 for (i = 0; i < (int)sizeof(buf)-1; i++)
283 if (*strp == '\0' || *strp == ' ')
284 break ;
285 buf[i] = *strp;
286 strp++;
288 buf[i] = '\0';
290 MATCH(condition, buf, "=", clause_is);
291 MATCH(condition, buf, "==", clause_is);
292 MATCH(condition, buf, "!=", clause_is_not);
293 MATCH(condition, buf, ">", clause_gt);
294 MATCH(condition, buf, ">=", clause_gteq);
295 MATCH(condition, buf, "<", clause_lt);
296 MATCH(condition, buf, "<=", clause_lteq);
297 MATCH(condition, buf, "~", clause_contains);
298 MATCH(condition, buf, "!~", clause_not_contains);
299 MATCH(condition, buf, "^", clause_begins_with);
300 MATCH(condition, buf, "!^", clause_not_begins_with);
301 MATCH(condition, buf, "$", clause_ends_with);
302 MATCH(condition, buf, "!$", clause_not_ends_with);
303 MATCH(condition, buf, "@", clause_oneof);
305 return 0;
308 static bool read_clause(struct tagcache_search_clause *clause)
310 char buf[SEARCHSTR_SIZE];
311 unsigned int i;
313 if (get_tag(&clause->tag) <= 0)
314 return false;
316 if (get_clause(&clause->type) <= 0)
317 return false;
319 if (get_token_str(buf, sizeof buf) < 0)
320 return false;
322 for (i=0; i<ARRAYLEN(id3_to_search_mapping); i++)
324 if (!strcasecmp(buf, id3_to_search_mapping[i].string))
325 break;
328 if (i<ARRAYLEN(id3_to_search_mapping)) /* runtime search operand found */
330 clause->source = source_runtime+i;
331 clause->str = buffer_alloc(SEARCHSTR_SIZE);
333 else
335 clause->source = source_constant;
336 clause->str = buffer_alloc(strlen(buf)+1);
337 strcpy(clause->str, buf);
340 if (TAGCACHE_IS_NUMERIC(clause->tag))
342 clause->numeric = true;
343 clause->numeric_data = atoi(clause->str);
345 else
346 clause->numeric = false;
348 logf("got clause: %d/%d [%s]", clause->tag, clause->type, clause->str);
350 return true;
353 static bool read_variable(char *buf, int size)
355 int condition;
357 if (!get_clause(&condition))
358 return false;
360 if (condition != clause_is)
361 return false;
363 if (get_token_str(buf, size) < 0)
364 return false;
366 return true;
369 /* "%3d. %s" autoscore title %sort = "inverse" %limit = "100" */
370 static int get_format_str(struct display_format *fmt)
372 int ret;
373 char buf[128];
374 int i;
376 memset(fmt, 0, sizeof(struct display_format));
378 if (get_token_str(fmt->name, sizeof fmt->name) < 0)
379 return -10;
381 /* Determine the group id */
382 fmt->group_id = 0;
383 for (i = 0; i < format_count; i++)
385 if (!strcasecmp(formats[i]->name, fmt->name))
387 fmt->group_id = formats[i]->group_id;
388 break;
391 if (formats[i]->group_id > fmt->group_id)
392 fmt->group_id = formats[i]->group_id;
395 if (i == format_count)
396 fmt->group_id++;
398 logf("format: (%d) %s", fmt->group_id, fmt->name);
400 if (get_token_str(buf, sizeof buf) < 0)
401 return -10;
403 fmt->formatstr = buffer_alloc(strlen(buf) + 1);
404 strcpy(fmt->formatstr, buf);
406 while (fmt->tag_count < MAX_TAGS)
408 ret = get_tag(&fmt->tags[fmt->tag_count]);
409 if (ret < 0)
410 return -11;
412 if (ret == 0)
413 break;
415 switch (fmt->tags[fmt->tag_count]) {
416 case var_sorttype:
417 if (!read_variable(buf, sizeof buf))
418 return -12;
419 if (!strcasecmp("inverse", buf))
420 fmt->sort_inverse = true;
421 break;
423 case var_limit:
424 if (!read_variable(buf, sizeof buf))
425 return -13;
426 fmt->limit = atoi(buf);
427 break;
429 case var_strip:
430 if (!read_variable(buf, sizeof buf))
431 return -14;
432 fmt->strip = atoi(buf);
433 break;
435 default:
436 fmt->tag_count++;
440 return 1;
443 static int add_format(const char *buf)
445 strp = buf;
447 if (formats[format_count] == NULL)
448 formats[format_count] = buffer_alloc(sizeof(struct display_format));
450 memset(formats[format_count], 0, sizeof(struct display_format));
451 if (get_format_str(formats[format_count]) < 0)
453 logf("get_format_str() parser failed!");
454 return -4;
457 while (*strp != '\0' && *strp != '?')
458 strp++;
460 if (*strp == '?')
462 int clause_count = 0;
463 strp++;
465 while (1)
467 if (clause_count >= TAGCACHE_MAX_CLAUSES)
469 logf("too many clauses");
470 break;
473 formats[format_count]->clause[clause_count] =
474 buffer_alloc(sizeof(struct tagcache_search_clause));
476 if (!read_clause(formats[format_count]->clause[clause_count]))
477 break;
479 clause_count++;
482 formats[format_count]->clause_count = clause_count;
485 format_count++;
487 return 1;
490 static int get_condition(struct search_instruction *inst)
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 inst->clause[inst->tagorder_count][clause_count] =
537 buffer_alloc(sizeof(struct tagcache_search_clause));
539 if (!read_clause(inst->clause[inst->tagorder_count][clause_count]))
540 return -1;
542 inst->clause_count[inst->tagorder_count]++;
544 return 1;
547 /* example search:
548 * "Best" artist ? year >= "2000" & title !^ "crap" & genre = "good genre" \
549 * : album ? year >= "2000" : songs
550 * ^ begins with
551 * * contains
552 * $ ends with
555 static bool parse_search(struct menu_entry *entry, const char *str)
557 int ret;
558 int type;
559 struct search_instruction *inst = entry->si;
560 char buf[MAX_PATH];
561 int i;
562 struct menu_root *new_menu;
564 strp = str;
566 /* Parse entry name */
567 if (get_token_str(entry->name, sizeof entry->name) < 0)
569 logf("No name found.");
570 return false;
573 /* Parse entry type */
574 if (get_tag(&entry->type) <= 0)
575 return false;
577 if (entry->type == menu_load)
579 if (get_token_str(buf, sizeof buf) < 0)
580 return false;
582 /* Find the matching root menu or "create" it */
583 for (i = 0; i < menu_count; i++)
585 if (!strcasecmp(menus[i]->id, buf))
587 entry->link = i;
588 return true;
592 if (menu_count >= TAGMENU_MAX_MENUS)
594 logf("max menucount reached");
595 return false;
598 /* Allocate a new menu unless link is found. */
599 menus[menu_count] = buffer_alloc(sizeof(struct menu_root));
600 new_menu = menus[menu_count];
601 memset(new_menu, 0, sizeof(struct menu_root));
602 strlcpy(new_menu->id, buf, MAX_MENU_ID_SIZE);
603 entry->link = menu_count;
604 ++menu_count;
606 return true;
609 if (entry->type != menu_next)
610 return false;
612 while (inst->tagorder_count < MAX_TAGS)
614 ret = get_tag(&inst->tagorder[inst->tagorder_count]);
615 if (ret < 0)
617 logf("Parse error #1");
618 logf("%s", strp);
619 return false;
622 if (ret == 0)
623 break ;
625 logf("tag: %d", inst->tagorder[inst->tagorder_count]);
627 while ( (ret = get_condition(inst)) > 0 ) ;
628 if (ret < 0)
629 return false;
631 inst->tagorder_count++;
633 if (get_tag(&type) <= 0 || type != menu_next)
634 break;
637 return true;
640 static int compare(const void *p1, const void *p2)
642 struct tagentry *e1 = (struct tagentry *)p1;
643 struct tagentry *e2 = (struct tagentry *)p2;
645 if (sort_inverse)
646 return strncasecmp(e2->name, e1->name, MAX_PATH);
648 return strncasecmp(e1->name, e2->name, MAX_PATH);
651 static void tagtree_buffer_event(void *data)
653 struct tagcache_search tcs;
654 struct mp3entry *id3 = (struct mp3entry*)data;
656 /* Do not gather data unless proper setting has been enabled. */
657 if (!global_settings.runtimedb && !global_settings.autoresume_enable)
658 return;
660 logf("be:%s", id3->path);
662 while (! tagcache_is_fully_initialized())
663 yield();
665 if (!tagcache_find_index(&tcs, id3->path))
667 logf("tc stat: not found: %s", id3->path);
668 return;
671 if (global_settings.runtimedb)
673 id3->playcount = tagcache_get_numeric(&tcs, tag_playcount);
674 if (!id3->rating)
675 id3->rating = tagcache_get_numeric(&tcs, tag_rating);
676 id3->lastplayed = tagcache_get_numeric(&tcs, tag_lastplayed);
677 id3->score = tagcache_get_numeric(&tcs, tag_virt_autoscore) / 10;
678 id3->playtime = tagcache_get_numeric(&tcs, tag_playtime);
680 logf("-> %ld/%ld", id3->playcount, id3->playtime);
683 #if CONFIG_CODEC == SWCODEC
684 if (global_settings.autoresume_enable)
686 /* Load current file resume offset if not already defined (by
687 another resume mechanism) */
688 if (id3->offset == 0)
690 id3->offset = tagcache_get_numeric(&tcs, tag_lastoffset);
692 logf("tagtree_buffer_event: Set offset for %s to %lX\n",
693 str_or_empty(id3->title), id3->offset);
696 #endif
698 /* Store our tagcache index pointer. */
699 id3->tagcache_idx = tcs.idx_id+1;
701 tagcache_search_finish(&tcs);
704 static void tagtree_track_finish_event(void *data)
706 long lastplayed;
707 long tagcache_idx;
708 struct mp3entry *id3 = (struct mp3entry*)data;
710 /* Do not gather data unless proper setting has been enabled. */
711 if (!global_settings.runtimedb && !global_settings.autoresume_enable)
713 logf("runtimedb gathering and autoresume not enabled");
714 return;
717 tagcache_idx=id3->tagcache_idx;
718 if (!tagcache_idx)
720 logf("No tagcache index pointer found");
721 return;
723 tagcache_idx--;
725 /* Don't process unplayed tracks. */
726 if (id3->elapsed == 0)
728 logf("not logging unplayed track");
729 return;
732 lastplayed = tagcache_increase_serial();
733 if (lastplayed < 0)
735 logf("incorrect tc serial:%ld", lastplayed);
736 return;
739 if (global_settings.runtimedb)
741 long playcount;
742 long playtime;
744 playcount = id3->playcount + 1;
746 /* Ignore the last 15s (crossfade etc.) */
747 playtime = id3->playtime + MIN(id3->length, id3->elapsed + 15 * 1000);
749 logf("ube:%s", id3->path);
750 logf("-> %ld/%ld", playcount, playtime);
751 logf("-> %ld/%ld/%ld", id3->elapsed, id3->length,
752 MIN(id3->length, id3->elapsed + 15 * 1000));
754 /* Queue the updates to the tagcache system. */
755 tagcache_update_numeric(tagcache_idx, tag_playcount, playcount);
756 tagcache_update_numeric(tagcache_idx, tag_playtime, playtime);
757 tagcache_update_numeric(tagcache_idx, tag_lastplayed, lastplayed);
760 #if CONFIG_CODEC == SWCODEC
761 if (global_settings.autoresume_enable)
763 unsigned long offset
764 = automatic_skip ? 0 : id3->offset;
766 tagcache_update_numeric(tagcache_idx, tag_lastoffset, offset);
768 logf("tagtree_track_finish_event: Save offset for %s: %lX",
769 str_or_empty(id3->title), offset);
771 #endif
774 bool tagtree_export(void)
776 struct tagcache_search tcs;
778 splash(0, str(LANG_CREATING));
779 if (!tagcache_create_changelog(&tcs))
781 splash(HZ*2, ID2P(LANG_FAILED));
784 return false;
787 bool tagtree_import(void)
789 splash(0, ID2P(LANG_WAIT));
790 if (!tagcache_import_changelog())
792 splash(HZ*2, ID2P(LANG_FAILED));
795 return false;
798 static bool parse_menu(const char *filename);
800 static int parse_line(int n, const char *buf, void *parameters)
802 char data[256];
803 int variable;
804 static bool read_menu;
805 int i;
807 (void)parameters;
809 logf("parse:%d/%s", n, buf);
811 /* First line, do initialisation. */
812 if (n == 0)
814 if (strcasecmp(TAGNAVI_VERSION, buf))
816 logf("Version mismatch");
817 return -1;
820 read_menu = false;
823 if (buf[0] == '#')
824 return 0;
826 if (buf[0] == '\0')
828 if (read_menu)
830 /* End the menu */
831 read_menu = false;
833 return 0;
836 if (!read_menu)
838 strp = buf;
839 if (get_tag(&variable) <= 0)
840 return 0;
842 switch (variable)
844 case var_format:
845 if (add_format(strp) < 0)
847 logf("Format add fail: %s", data);
849 break;
851 case var_include:
852 if (get_token_str(data, sizeof(data)) < 0)
854 logf("%%include empty");
855 return 0;
858 if (!parse_menu(data))
860 logf("Load menu fail: %s", data);
862 break;
864 case var_menu_start:
865 if (menu_count >= TAGMENU_MAX_MENUS)
867 logf("max menucount reached");
868 return 0;
871 if (get_token_str(data, sizeof data) < 0)
873 logf("%%menu_start id empty");
874 return 0;
877 menu = NULL;
878 for (i = 0; i < menu_count; i++)
880 if (!strcasecmp(menus[i]->id, data))
882 menu = menus[i];
886 if (menu == NULL)
888 menus[menu_count] = buffer_alloc(sizeof(struct menu_root));
889 menu = menus[menu_count];
890 ++menu_count;
891 memset(menu, 0, sizeof(struct menu_root));
892 strlcpy(menu->id, data, MAX_MENU_ID_SIZE);
895 if (get_token_str(menu->title, sizeof(menu->title)) < 0)
897 logf("%%menu_start title empty");
898 return 0;
900 logf("menu: %s", menu->title);
901 read_menu = true;
902 break;
904 case var_rootmenu:
905 /* Only set root menu once. */
906 if (rootmenu >= 0)
907 break;
909 if (get_token_str(data, sizeof(data)) < 0)
911 logf("%%rootmenu empty");
912 return 0;
915 for (i = 0; i < menu_count; i++)
917 if (!strcasecmp(menus[i]->id, data))
919 rootmenu = i;
922 break;
925 return 0;
928 if (menu->itemcount >= TAGMENU_MAX_ITEMS)
930 logf("max itemcount reached");
931 return 0;
934 /* Allocate */
935 if (menu->items[menu->itemcount] == NULL)
937 menu->items[menu->itemcount] = buffer_alloc(sizeof(struct menu_entry));
938 memset(menu->items[menu->itemcount], 0, sizeof(struct menu_entry));
939 menu->items[menu->itemcount]->si = buffer_alloc(sizeof(struct search_instruction));
942 memset(menu->items[menu->itemcount]->si, 0, sizeof(struct search_instruction));
943 if (!parse_search(menu->items[menu->itemcount], buf))
944 return 0;
946 menu->itemcount++;
948 return 0;
951 static bool parse_menu(const char *filename)
953 int fd;
954 char buf[1024];
956 if (menu_count >= TAGMENU_MAX_MENUS)
958 logf("max menucount reached");
959 return false;
962 fd = open(filename, O_RDONLY);
963 if (fd < 0)
965 logf("Search instruction file not found.");
966 return false;
969 /* Now read file for real, parsing into si */
970 fast_readline(fd, buf, sizeof buf, NULL, parse_line);
971 close(fd);
973 return true;
976 void tagtree_init(void)
978 format_count = 0;
979 menu_count = 0;
980 menu = NULL;
981 rootmenu = -1;
982 parse_menu(FILE_SEARCH_INSTRUCTIONS);
984 /* If no root menu is set, assume it's the first single menu
985 * we have. That shouldn't normally happen. */
986 if (rootmenu < 0)
987 rootmenu = 0;
989 uniqbuf = buffer_alloc(UNIQBUF_SIZE);
991 add_event(PLAYBACK_EVENT_TRACK_BUFFER, false, tagtree_buffer_event);
992 add_event(PLAYBACK_EVENT_TRACK_FINISH, false, tagtree_track_finish_event);
995 static bool show_search_progress(bool init, int count)
997 static int last_tick = 0;
999 /* Don't show splashes for 1/2 second after starting search */
1000 if (init)
1002 last_tick = current_tick + HZ/2;
1003 return true;
1006 /* Update progress every 1/10 of a second */
1007 if (TIME_AFTER(current_tick, last_tick + HZ/10))
1009 splashf(0, str(LANG_PLAYLIST_SEARCH_MSG), count, str(LANG_OFF_ABORT));
1010 if (action_userabort(TIMEOUT_NOBLOCK))
1011 return false;
1012 last_tick = current_tick;
1013 yield();
1016 return true;
1019 static int format_str(struct tagcache_search *tcs, struct display_format *fmt,
1020 char *buf, int buf_size)
1022 char fmtbuf[8];
1023 bool read_format = false;
1024 int fmtbuf_pos = 0;
1025 int parpos = 0;
1026 int buf_pos = 0;
1027 int i;
1029 memset(buf, 0, buf_size);
1030 for (i = 0; fmt->formatstr[i] != '\0'; i++)
1032 if (fmt->formatstr[i] == '%')
1034 read_format = true;
1035 fmtbuf_pos = 0;
1036 if (parpos >= fmt->tag_count)
1038 logf("too many format tags");
1039 return -1;
1043 if (read_format)
1045 fmtbuf[fmtbuf_pos++] = fmt->formatstr[i];
1046 if (fmtbuf_pos >= buf_size)
1048 logf("format parse error");
1049 return -2;
1052 if (fmt->formatstr[i] == 's')
1054 fmtbuf[fmtbuf_pos] = '\0';
1055 read_format = false;
1056 if (fmt->tags[parpos] == tcs->type)
1058 snprintf(&buf[buf_pos], buf_size - buf_pos, fmtbuf, tcs->result);
1060 else
1062 /* Need to fetch the tag data. */
1063 if (!tagcache_retrieve(tcs, tcs->idx_id, fmt->tags[parpos],
1064 &buf[buf_pos], buf_size - buf_pos))
1066 logf("retrieve failed");
1067 return -3;
1070 buf_pos += strlen(&buf[buf_pos]);
1071 parpos++;
1073 else if (fmt->formatstr[i] == 'd')
1075 fmtbuf[fmtbuf_pos] = '\0';
1076 read_format = false;
1077 snprintf(&buf[buf_pos], buf_size - buf_pos, fmtbuf,
1078 tagcache_get_numeric(tcs, fmt->tags[parpos]));
1079 buf_pos += strlen(&buf[buf_pos]);
1080 parpos++;
1082 continue;
1085 buf[buf_pos++] = fmt->formatstr[i];
1087 if (buf_pos - 1 >= buf_size)
1089 logf("buffer overflow");
1090 return -4;
1094 buf[buf_pos++] = '\0';
1096 return 0;
1099 static int retrieve_entries(struct tree_context *c, int offset, bool init)
1101 struct tagcache_search tcs;
1102 struct tagentry *dptr = (struct tagentry *)c->dircache;
1103 struct display_format *fmt;
1104 int i;
1105 int namebufused = 0;
1106 int total_count = 0;
1107 int special_entry_count = 0;
1108 int level = c->currextra;
1109 int tag;
1110 bool sort = false;
1111 int sort_limit;
1112 int strip;
1114 /* Show search progress straight away if the disk needs to spin up,
1115 otherwise show it after the normal 1/2 second delay */
1116 show_search_progress(
1117 #ifdef HAVE_DISK_STORAGE
1118 storage_disk_is_active()
1119 #else
1120 true
1121 #endif
1122 , 0);
1124 if (c->currtable == ALLSUBENTRIES)
1126 tag = tag_title;
1127 level--;
1129 else
1130 tag = csi->tagorder[level];
1132 if (!tagcache_search(&tcs, tag))
1133 return -1;
1135 /* Prevent duplicate entries in the search list. */
1136 tagcache_search_set_uniqbuf(&tcs, uniqbuf, UNIQBUF_SIZE);
1138 if (level || csi->clause_count[0] || TAGCACHE_IS_NUMERIC(tag))
1139 sort = true;
1141 for (i = 0; i < level; i++)
1143 if (TAGCACHE_IS_NUMERIC(csi->tagorder[i]))
1145 static struct tagcache_search_clause cc;
1147 memset(&cc, 0, sizeof(struct tagcache_search_clause));
1148 cc.tag = csi->tagorder[i];
1149 cc.type = clause_is;
1150 cc.numeric = true;
1151 cc.numeric_data = csi->result_seek[i];
1152 tagcache_search_add_clause(&tcs, &cc);
1154 else
1156 tagcache_search_add_filter(&tcs, csi->tagorder[i],
1157 csi->result_seek[i]);
1161 for (i = 0; i <= level; i++)
1163 int j;
1165 for (j = 0; j < csi->clause_count[i]; j++)
1166 tagcache_search_add_clause(&tcs, csi->clause[i][j]);
1169 current_offset = offset;
1170 current_entry_count = 0;
1171 c->dirfull = false;
1173 fmt = NULL;
1174 for (i = 0; i < format_count; i++)
1176 if (formats[i]->group_id == csi->format_id[level])
1177 fmt = formats[i];
1180 if (fmt)
1182 sort_inverse = fmt->sort_inverse;
1183 sort_limit = fmt->limit;
1184 strip = fmt->strip;
1185 sort = true;
1187 else
1189 sort_inverse = false;
1190 sort_limit = 0;
1191 strip = 0;
1194 if (tag != tag_title && tag != tag_filename)
1196 if (offset == 0)
1198 dptr->newtable = ALLSUBENTRIES;
1199 dptr->name = str(LANG_TAGNAVI_ALL_TRACKS);
1200 dptr++;
1201 current_entry_count++;
1203 if (offset <= 1)
1205 dptr->newtable = NAVIBROWSE;
1206 dptr->name = str(LANG_TAGNAVI_RANDOM);
1207 dptr->extraseek = -1;
1208 dptr++;
1209 current_entry_count++;
1211 special_entry_count+=2;
1214 total_count += special_entry_count;
1216 while (tagcache_get_next(&tcs))
1218 if (total_count++ < offset)
1219 continue;
1221 if ( strcmp(tcs.result , UNTAGGED ) == 0)
1223 tcs.result_len = strlcpy(tcs.result,
1224 str(LANG_TAGNAVI_UNTAGGED), TAG_MAXLEN )+1;
1227 dptr->newtable = NAVIBROWSE;
1228 if (tag == tag_title || tag == tag_filename)
1230 dptr->newtable = PLAYTRACK;
1231 dptr->extraseek = tcs.idx_id;
1233 else
1234 dptr->extraseek = tcs.result_seek;
1236 fmt = NULL;
1237 /* Check the format */
1238 for (i = 0; i < format_count; i++)
1240 if (formats[i]->group_id != csi->format_id[level])
1241 continue;
1243 if (tagcache_check_clauses(&tcs, formats[i]->clause,
1244 formats[i]->clause_count))
1246 fmt = formats[i];
1247 break;
1251 if (!tcs.ramresult || fmt)
1253 char buf[MAX_PATH];
1255 if (fmt)
1257 if (format_str(&tcs, fmt, buf, sizeof buf) < 0)
1259 logf("format_str() failed");
1260 tagcache_search_finish(&tcs);
1261 return 0;
1265 dptr->name = &c->name_buffer[namebufused];
1266 if (fmt)
1267 namebufused += strlen(buf)+1;
1268 else
1269 namebufused += tcs.result_len;
1271 if (namebufused >= c->name_buffer_size)
1273 logf("chunk mode #2: %d", current_entry_count);
1274 c->dirfull = true;
1275 sort = false;
1276 break ;
1278 if (fmt)
1279 strcpy(dptr->name, buf);
1280 else
1281 strcpy(dptr->name, tcs.result);
1283 else
1284 dptr->name = tcs.result;
1286 dptr++;
1287 current_entry_count++;
1289 if (current_entry_count >= global_settings.max_files_in_dir)
1291 logf("chunk mode #3: %d", current_entry_count);
1292 c->dirfull = true;
1293 sort = false;
1294 break ;
1297 if (init && !tcs.ramsearch)
1299 if (!show_search_progress(false, total_count))
1300 { /* user aborted */
1301 tagcache_search_finish(&tcs);
1302 return current_entry_count;
1307 if (sort)
1308 qsort(c->dircache + special_entry_count * c->dentry_size,
1309 current_entry_count - special_entry_count,
1310 c->dentry_size, compare);
1312 if (!init)
1314 tagcache_search_finish(&tcs);
1315 return current_entry_count;
1318 while (tagcache_get_next(&tcs))
1320 if (!tcs.ramsearch)
1322 if (!show_search_progress(false, total_count))
1323 break;
1325 total_count++;
1328 tagcache_search_finish(&tcs);
1330 if (!sort && (sort_inverse || sort_limit))
1332 splashf(HZ*4, ID2P(LANG_SHOWDIR_BUFFER_FULL), total_count);
1333 logf("Too small dir buffer");
1334 return 0;
1337 if (sort_limit)
1338 total_count = MIN(total_count, sort_limit);
1340 if (strip)
1342 dptr = c->dircache;
1343 for (i = 0; i < total_count; i++, dptr++)
1345 int len = strlen(dptr->name);
1347 if (len < strip)
1348 continue;
1350 dptr->name = &dptr->name[strip];
1354 return total_count;
1358 static int load_root(struct tree_context *c)
1360 struct tagentry *dptr = (struct tagentry *)c->dircache;
1361 int i;
1363 tc = c;
1364 c->currtable = ROOT;
1365 if (c->dirlevel == 0)
1366 c->currextra = rootmenu;
1368 menu = menus[c->currextra];
1369 if (menu == NULL)
1370 return 0;
1372 for (i = 0; i < menu->itemcount; i++)
1374 dptr->name = menu->items[i]->name;
1375 switch (menu->items[i]->type)
1377 case menu_next:
1378 dptr->newtable = NAVIBROWSE;
1379 dptr->extraseek = i;
1380 break;
1382 case menu_load:
1383 dptr->newtable = ROOT;
1384 dptr->extraseek = menu->items[i]->link;
1385 break;
1388 dptr++;
1391 current_offset = 0;
1392 current_entry_count = i;
1394 return i;
1397 int tagtree_load(struct tree_context* c)
1399 int count;
1400 int table = c->currtable;
1402 c->dentry_size = sizeof(struct tagentry);
1403 c->dirsindir = 0;
1405 if (!table)
1407 c->dirfull = false;
1408 table = ROOT;
1409 c->currtable = table;
1410 c->currextra = rootmenu;
1413 switch (table)
1415 case ROOT:
1416 count = load_root(c);
1417 break;
1419 case ALLSUBENTRIES:
1420 case NAVIBROWSE:
1421 logf("navibrowse...");
1422 cpu_boost(true);
1423 count = retrieve_entries(c, 0, true);
1424 cpu_boost(false);
1425 break;
1427 default:
1428 logf("Unsupported table %d\n", table);
1429 return -1;
1432 if (count < 0)
1434 c->dirlevel = 0;
1435 count = load_root(c);
1436 splash(HZ, str(LANG_TAGCACHE_BUSY));
1439 /* The _total_ numer of entries available. */
1440 c->dirlength = c->filesindir = count;
1442 return count;
1445 int tagtree_enter(struct tree_context* c)
1447 int rc = 0;
1448 struct tagentry *dptr;
1449 struct mp3entry *id3;
1450 int newextra;
1451 int seek;
1452 int source;
1454 dptr = tagtree_get_entry(c, c->selected_item);
1456 c->dirfull = false;
1457 seek = dptr->extraseek;
1458 if (seek == -1)
1460 if(c->filesindir<=2)
1461 return 0;
1462 srand(current_tick);
1463 dptr = (tagtree_get_entry(c, 2+(rand() % (c->filesindir-2))));
1464 seek = dptr->extraseek;
1466 newextra = dptr->newtable;
1468 if (c->dirlevel >= MAX_DIR_LEVELS)
1469 return 0;
1471 c->selected_item_history[c->dirlevel]=c->selected_item;
1472 c->table_history[c->dirlevel] = c->currtable;
1473 c->extra_history[c->dirlevel] = c->currextra;
1474 c->pos_history[c->dirlevel] = c->firstpos;
1475 c->dirlevel++;
1477 switch (c->currtable) {
1478 case ROOT:
1479 c->currextra = newextra;
1481 if (newextra == ROOT)
1483 menu = menus[seek];
1484 c->currextra = seek;
1487 else if (newextra == NAVIBROWSE)
1489 int i, j;
1491 csi = menu->items[seek]->si;
1492 c->currextra = 0;
1494 strlcpy(current_title[c->currextra], dptr->name,
1495 sizeof(current_title[0]));
1497 /* Read input as necessary. */
1498 for (i = 0; i < csi->tagorder_count; i++)
1500 for (j = 0; j < csi->clause_count[i]; j++)
1502 char* searchstring;
1503 source = csi->clause[i][j]->source;
1505 if (source == source_constant)
1506 continue;
1508 searchstring=csi->clause[i][j]->str;
1509 *searchstring = '\0';
1511 id3 = audio_current_track();
1513 if (source == source_current_path && id3)
1515 char *e;
1516 strlcpy(searchstring, id3->path, SEARCHSTR_SIZE);
1517 e = strrchr(searchstring, '/');
1518 if (e)
1519 *e = '\0';
1521 else if (source > source_runtime && id3)
1524 int k = source-source_runtime;
1525 int offset = id3_to_search_mapping[k].id3_offset;
1526 char **src = (char**)((char*)id3 + offset);
1527 if (*src)
1529 strlcpy(searchstring, *src, SEARCHSTR_SIZE);
1532 else
1534 rc = kbd_input(searchstring, SEARCHSTR_SIZE);
1535 if (rc < 0 || !searchstring[0])
1537 tagtree_exit(c);
1538 return 0;
1540 if (csi->clause[i][j]->numeric)
1541 csi->clause[i][j]->numeric_data = atoi(searchstring);
1548 c->currtable = newextra;
1550 break;
1552 case NAVIBROWSE:
1553 case ALLSUBENTRIES:
1554 if (newextra == PLAYTRACK)
1556 if (global_settings.party_mode && audio_status()) {
1557 splash(HZ, ID2P(LANG_PARTY_MODE));
1558 break;
1560 c->dirlevel--;
1561 /* about to create a new current playlist...
1562 allow user to cancel the operation */
1563 if (!warn_on_pl_erase())
1564 break;
1565 if (tagtree_play_folder(c) >= 0)
1566 rc = 2;
1567 break;
1570 c->currtable = newextra;
1571 csi->result_seek[c->currextra] = seek;
1572 if (c->currextra < csi->tagorder_count-1)
1573 c->currextra++;
1574 else
1575 c->dirlevel--;
1577 /* Update the statusbar title */
1578 strlcpy(current_title[c->currextra], dptr->name,
1579 sizeof(current_title[0]));
1580 break;
1582 default:
1583 c->dirlevel--;
1584 break;
1587 c->selected_item=0;
1588 gui_synclist_select_item(&tree_lists, c->selected_item);
1590 return rc;
1593 void tagtree_exit(struct tree_context* c)
1595 c->dirfull = false;
1596 if (c->dirlevel > 0)
1597 c->dirlevel--;
1598 c->selected_item=c->selected_item_history[c->dirlevel];
1599 gui_synclist_select_item(&tree_lists, c->selected_item);
1600 c->currtable = c->table_history[c->dirlevel];
1601 c->currextra = c->extra_history[c->dirlevel];
1602 c->firstpos = c->pos_history[c->dirlevel];
1605 int tagtree_get_filename(struct tree_context* c, char *buf, int buflen)
1607 struct tagcache_search tcs;
1608 struct tagentry *entry;
1610 entry = tagtree_get_entry(c, c->selected_item);
1612 if (!tagcache_search(&tcs, tag_filename))
1613 return -1;
1615 if (!tagcache_retrieve(&tcs, entry->extraseek, tcs.type, buf, buflen))
1617 tagcache_search_finish(&tcs);
1618 return -2;
1621 tagcache_search_finish(&tcs);
1623 return 0;
1626 static bool insert_all_playlist(struct tree_context *c, int position, bool queue)
1628 struct tagcache_search tcs;
1629 int i;
1630 char buf[MAX_PATH];
1631 int from, to, direction;
1632 int files_left = c->filesindir;
1634 cpu_boost(true);
1635 if (!tagcache_search(&tcs, tag_filename))
1637 splash(HZ, ID2P(LANG_TAGCACHE_BUSY));
1638 cpu_boost(false);
1639 return false;
1642 if (position == PLAYLIST_REPLACE)
1644 if (playlist_remove_all_tracks(NULL) == 0)
1645 position = PLAYLIST_INSERT_LAST;
1646 else
1648 cpu_boost(false);
1649 return false;
1653 if (position == PLAYLIST_INSERT_FIRST)
1655 from = c->filesindir - 1;
1656 to = -1;
1657 direction = -1;
1659 else
1661 from = 0;
1662 to = c->filesindir;
1663 direction = 1;
1666 for (i = from; i != to; i += direction)
1668 /* Count back to zero */
1669 if (!show_search_progress(false, files_left--))
1670 break;
1672 if (!tagcache_retrieve(&tcs, tagtree_get_entry(c, i)->extraseek,
1673 tcs.type, buf, sizeof buf))
1675 continue;
1678 if (playlist_insert_track(NULL, buf, position, queue, false) < 0)
1680 logf("playlist_insert_track failed");
1681 break;
1683 yield();
1685 playlist_sync(NULL);
1686 tagcache_search_finish(&tcs);
1687 cpu_boost(false);
1689 return true;
1692 bool tagtree_insert_selection_playlist(int position, bool queue)
1694 struct tagentry *dptr;
1695 char buf[MAX_PATH];
1696 int dirlevel = tc->dirlevel;
1698 show_search_progress(
1699 #ifdef HAVE_DISK_STORAGE
1700 storage_disk_is_active()
1701 #else
1702 true
1703 #endif
1704 , 0);
1707 /* We need to set the table to allsubentries. */
1708 dptr = tagtree_get_entry(tc, tc->selected_item);
1710 /* Insert a single track? */
1711 if (dptr->newtable == PLAYTRACK)
1713 if (tagtree_get_filename(tc, buf, sizeof buf) < 0)
1715 logf("tagtree_get_filename failed");
1716 return false;
1718 playlist_insert_track(NULL, buf, position, queue, true);
1720 return true;
1723 if (dptr->newtable == NAVIBROWSE)
1725 tagtree_enter(tc);
1726 tagtree_load(tc);
1727 dptr = tagtree_get_entry(tc, tc->selected_item);
1729 else if (dptr->newtable != ALLSUBENTRIES)
1731 logf("unsupported table: %d", dptr->newtable);
1732 return false;
1735 /* Now the current table should be allsubentries. */
1736 if (dptr->newtable != PLAYTRACK)
1738 tagtree_enter(tc);
1739 tagtree_load(tc);
1740 dptr = tagtree_get_entry(tc, tc->selected_item);
1742 /* And now the newtable should be playtrack. */
1743 if (dptr->newtable != PLAYTRACK)
1745 logf("newtable: %d !!", dptr->newtable);
1746 tc->dirlevel = dirlevel;
1747 return false;
1751 if (tc->filesindir <= 0)
1752 splash(HZ, ID2P(LANG_END_PLAYLIST));
1753 else
1755 logf("insert_all_playlist");
1756 if (!insert_all_playlist(tc, position, queue))
1757 splash(HZ*2, ID2P(LANG_FAILED));
1760 /* Finally return the dirlevel to its original value. */
1761 while (tc->dirlevel > dirlevel)
1762 tagtree_exit(tc);
1763 tagtree_load(tc);
1765 return true;
1768 static int tagtree_play_folder(struct tree_context* c)
1770 if (playlist_create(NULL, NULL) < 0)
1772 logf("Failed creating playlist\n");
1773 return -1;
1776 if (!insert_all_playlist(c, PLAYLIST_INSERT_LAST, false))
1777 return -2;
1779 if (global_settings.playlist_shuffle)
1780 c->selected_item = playlist_shuffle(current_tick, c->selected_item);
1781 if (!global_settings.play_selected)
1782 c->selected_item = 0;
1783 gui_synclist_select_item(&tree_lists, c->selected_item);
1785 playlist_start(c->selected_item,0);
1786 playlist_get_current()->num_inserted_tracks = 0; /* make warn on playlist erase work */
1787 return 0;
1790 struct tagentry* tagtree_get_entry(struct tree_context *c, int id)
1792 struct tagentry *entry = (struct tagentry *)c->dircache;
1793 int realid = id - current_offset;
1795 /* Load the next chunk if necessary. */
1796 if (realid >= current_entry_count || realid < 0)
1798 cpu_boost(true);
1799 if (retrieve_entries(c, MAX(0, id - (current_entry_count / 2)),
1800 false) < 0)
1802 logf("retrieve failed");
1803 cpu_boost(false);
1804 return NULL;
1806 realid = id - current_offset;
1807 cpu_boost(false);
1810 return &entry[realid];
1813 char *tagtree_get_title(struct tree_context* c)
1815 switch (c->currtable)
1817 case ROOT:
1818 return menu->title;
1820 case NAVIBROWSE:
1821 case ALLSUBENTRIES:
1822 return current_title[c->currextra];
1825 return "?";
1828 int tagtree_get_attr(struct tree_context* c)
1830 int attr = -1;
1831 switch (c->currtable)
1833 case NAVIBROWSE:
1834 if (csi->tagorder[c->currextra] == tag_title)
1835 attr = FILE_ATTR_AUDIO;
1836 else
1837 attr = ATTR_DIRECTORY;
1838 break;
1840 case ALLSUBENTRIES:
1841 attr = FILE_ATTR_AUDIO;
1842 break;
1844 default:
1845 attr = ATTR_DIRECTORY;
1846 break;
1849 return attr;
1852 int tagtree_get_icon(struct tree_context* c)
1854 int icon = Icon_Folder;
1856 if (tagtree_get_attr(c) == FILE_ATTR_AUDIO)
1857 icon = Icon_Audio;
1859 return icon;