Add "elfzip" target to make which creates a zip of all elf files, as mapzip does...
[maemo-rb.git] / apps / tagtree.c
blobecc9f44d4d28cc37a11d3973d5b169b444a3b62e
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, or tracks interrupted within the
726 first 15 seconds. */
727 if (id3->elapsed == 0
728 #if CONFIG_CODEC == SWCODEC /* HWCODEC doesn't have automatic_skip */
729 || (id3->elapsed < 15 * 1000 && !automatic_skip)
730 #endif
733 logf("not logging unplayed or skipped track");
734 return;
737 lastplayed = tagcache_increase_serial();
738 if (lastplayed < 0)
740 logf("incorrect tc serial:%ld", lastplayed);
741 return;
744 if (global_settings.runtimedb)
746 long playcount;
747 long playtime;
749 playcount = id3->playcount + 1;
751 /* Ignore the last 15s (crossfade etc.) */
752 playtime = id3->playtime + MIN(id3->length, id3->elapsed + 15 * 1000);
754 logf("ube:%s", id3->path);
755 logf("-> %ld/%ld", playcount, playtime);
756 logf("-> %ld/%ld/%ld", id3->elapsed, id3->length,
757 MIN(id3->length, id3->elapsed + 15 * 1000));
759 /* Queue the updates to the tagcache system. */
760 tagcache_update_numeric(tagcache_idx, tag_playcount, playcount);
761 tagcache_update_numeric(tagcache_idx, tag_playtime, playtime);
762 tagcache_update_numeric(tagcache_idx, tag_lastplayed, lastplayed);
765 #if CONFIG_CODEC == SWCODEC
766 if (global_settings.autoresume_enable)
768 unsigned long offset
769 = automatic_skip ? 0 : id3->offset;
771 tagcache_update_numeric(tagcache_idx, tag_lastoffset, offset);
773 logf("tagtree_track_finish_event: Save offset for %s: %lX",
774 str_or_empty(id3->title), offset);
776 #endif
779 bool tagtree_export(void)
781 struct tagcache_search tcs;
783 splash(0, str(LANG_CREATING));
784 if (!tagcache_create_changelog(&tcs))
786 splash(HZ*2, ID2P(LANG_FAILED));
789 return false;
792 bool tagtree_import(void)
794 splash(0, ID2P(LANG_WAIT));
795 if (!tagcache_import_changelog())
797 splash(HZ*2, ID2P(LANG_FAILED));
800 return false;
803 static bool parse_menu(const char *filename);
805 static int parse_line(int n, const char *buf, void *parameters)
807 char data[256];
808 int variable;
809 static bool read_menu;
810 int i;
812 (void)parameters;
814 logf("parse:%d/%s", n, buf);
816 /* First line, do initialisation. */
817 if (n == 0)
819 if (strcasecmp(TAGNAVI_VERSION, buf))
821 logf("Version mismatch");
822 return -1;
825 read_menu = false;
828 if (buf[0] == '#')
829 return 0;
831 if (buf[0] == '\0')
833 if (read_menu)
835 /* End the menu */
836 read_menu = false;
838 return 0;
841 if (!read_menu)
843 strp = buf;
844 if (get_tag(&variable) <= 0)
845 return 0;
847 switch (variable)
849 case var_format:
850 if (add_format(strp) < 0)
852 logf("Format add fail: %s", data);
854 break;
856 case var_include:
857 if (get_token_str(data, sizeof(data)) < 0)
859 logf("%%include empty");
860 return 0;
863 if (!parse_menu(data))
865 logf("Load menu fail: %s", data);
867 break;
869 case var_menu_start:
870 if (menu_count >= TAGMENU_MAX_MENUS)
872 logf("max menucount reached");
873 return 0;
876 if (get_token_str(data, sizeof data) < 0)
878 logf("%%menu_start id empty");
879 return 0;
882 menu = NULL;
883 for (i = 0; i < menu_count; i++)
885 if (!strcasecmp(menus[i]->id, data))
887 menu = menus[i];
891 if (menu == NULL)
893 menus[menu_count] = buffer_alloc(sizeof(struct menu_root));
894 menu = menus[menu_count];
895 ++menu_count;
896 memset(menu, 0, sizeof(struct menu_root));
897 strlcpy(menu->id, data, MAX_MENU_ID_SIZE);
900 if (get_token_str(menu->title, sizeof(menu->title)) < 0)
902 logf("%%menu_start title empty");
903 return 0;
905 logf("menu: %s", menu->title);
906 read_menu = true;
907 break;
909 case var_rootmenu:
910 /* Only set root menu once. */
911 if (rootmenu >= 0)
912 break;
914 if (get_token_str(data, sizeof(data)) < 0)
916 logf("%%rootmenu empty");
917 return 0;
920 for (i = 0; i < menu_count; i++)
922 if (!strcasecmp(menus[i]->id, data))
924 rootmenu = i;
927 break;
930 return 0;
933 if (menu->itemcount >= TAGMENU_MAX_ITEMS)
935 logf("max itemcount reached");
936 return 0;
939 /* Allocate */
940 if (menu->items[menu->itemcount] == NULL)
942 menu->items[menu->itemcount] = buffer_alloc(sizeof(struct menu_entry));
943 memset(menu->items[menu->itemcount], 0, sizeof(struct menu_entry));
944 menu->items[menu->itemcount]->si = buffer_alloc(sizeof(struct search_instruction));
947 memset(menu->items[menu->itemcount]->si, 0, sizeof(struct search_instruction));
948 if (!parse_search(menu->items[menu->itemcount], buf))
949 return 0;
951 menu->itemcount++;
953 return 0;
956 static bool parse_menu(const char *filename)
958 int fd;
959 char buf[1024];
961 if (menu_count >= TAGMENU_MAX_MENUS)
963 logf("max menucount reached");
964 return false;
967 fd = open(filename, O_RDONLY);
968 if (fd < 0)
970 logf("Search instruction file not found.");
971 return false;
974 /* Now read file for real, parsing into si */
975 fast_readline(fd, buf, sizeof buf, NULL, parse_line);
976 close(fd);
978 return true;
981 void tagtree_init(void)
983 format_count = 0;
984 menu_count = 0;
985 menu = NULL;
986 rootmenu = -1;
987 parse_menu(FILE_SEARCH_INSTRUCTIONS);
989 /* If no root menu is set, assume it's the first single menu
990 * we have. That shouldn't normally happen. */
991 if (rootmenu < 0)
992 rootmenu = 0;
994 uniqbuf = buffer_alloc(UNIQBUF_SIZE);
996 add_event(PLAYBACK_EVENT_TRACK_BUFFER, false, tagtree_buffer_event);
997 add_event(PLAYBACK_EVENT_TRACK_FINISH, false, tagtree_track_finish_event);
1000 static bool show_search_progress(bool init, int count)
1002 static int last_tick = 0;
1004 /* Don't show splashes for 1/2 second after starting search */
1005 if (init)
1007 last_tick = current_tick + HZ/2;
1008 return true;
1011 /* Update progress every 1/10 of a second */
1012 if (TIME_AFTER(current_tick, last_tick + HZ/10))
1014 splashf(0, str(LANG_PLAYLIST_SEARCH_MSG), count, str(LANG_OFF_ABORT));
1015 if (action_userabort(TIMEOUT_NOBLOCK))
1016 return false;
1017 last_tick = current_tick;
1018 yield();
1021 return true;
1024 static int format_str(struct tagcache_search *tcs, struct display_format *fmt,
1025 char *buf, int buf_size)
1027 char fmtbuf[8];
1028 bool read_format = false;
1029 int fmtbuf_pos = 0;
1030 int parpos = 0;
1031 int buf_pos = 0;
1032 int i;
1034 memset(buf, 0, buf_size);
1035 for (i = 0; fmt->formatstr[i] != '\0'; i++)
1037 if (fmt->formatstr[i] == '%')
1039 read_format = true;
1040 fmtbuf_pos = 0;
1041 if (parpos >= fmt->tag_count)
1043 logf("too many format tags");
1044 return -1;
1048 if (read_format)
1050 fmtbuf[fmtbuf_pos++] = fmt->formatstr[i];
1051 if (fmtbuf_pos >= buf_size)
1053 logf("format parse error");
1054 return -2;
1057 if (fmt->formatstr[i] == 's')
1059 fmtbuf[fmtbuf_pos] = '\0';
1060 read_format = false;
1061 if (fmt->tags[parpos] == tcs->type)
1063 snprintf(&buf[buf_pos], buf_size - buf_pos, fmtbuf, tcs->result);
1065 else
1067 /* Need to fetch the tag data. */
1068 if (!tagcache_retrieve(tcs, tcs->idx_id, fmt->tags[parpos],
1069 &buf[buf_pos], buf_size - buf_pos))
1071 logf("retrieve failed");
1072 return -3;
1075 buf_pos += strlen(&buf[buf_pos]);
1076 parpos++;
1078 else if (fmt->formatstr[i] == 'd')
1080 fmtbuf[fmtbuf_pos] = '\0';
1081 read_format = false;
1082 snprintf(&buf[buf_pos], buf_size - buf_pos, fmtbuf,
1083 tagcache_get_numeric(tcs, fmt->tags[parpos]));
1084 buf_pos += strlen(&buf[buf_pos]);
1085 parpos++;
1087 continue;
1090 buf[buf_pos++] = fmt->formatstr[i];
1092 if (buf_pos - 1 >= buf_size)
1094 logf("buffer overflow");
1095 return -4;
1099 buf[buf_pos++] = '\0';
1101 return 0;
1104 static int retrieve_entries(struct tree_context *c, int offset, bool init)
1106 struct tagcache_search tcs;
1107 struct tagentry *dptr = (struct tagentry *)c->dircache;
1108 struct display_format *fmt;
1109 int i;
1110 int namebufused = 0;
1111 int total_count = 0;
1112 int special_entry_count = 0;
1113 int level = c->currextra;
1114 int tag;
1115 bool sort = false;
1116 int sort_limit;
1117 int strip;
1119 /* Show search progress straight away if the disk needs to spin up,
1120 otherwise show it after the normal 1/2 second delay */
1121 show_search_progress(
1122 #ifdef HAVE_DISK_STORAGE
1123 storage_disk_is_active()
1124 #else
1125 true
1126 #endif
1127 , 0);
1129 if (c->currtable == ALLSUBENTRIES)
1131 tag = tag_title;
1132 level--;
1134 else
1135 tag = csi->tagorder[level];
1137 if (!tagcache_search(&tcs, tag))
1138 return -1;
1140 /* Prevent duplicate entries in the search list. */
1141 tagcache_search_set_uniqbuf(&tcs, uniqbuf, UNIQBUF_SIZE);
1143 if (level || csi->clause_count[0] || TAGCACHE_IS_NUMERIC(tag))
1144 sort = true;
1146 for (i = 0; i < level; i++)
1148 if (TAGCACHE_IS_NUMERIC(csi->tagorder[i]))
1150 static struct tagcache_search_clause cc;
1152 memset(&cc, 0, sizeof(struct tagcache_search_clause));
1153 cc.tag = csi->tagorder[i];
1154 cc.type = clause_is;
1155 cc.numeric = true;
1156 cc.numeric_data = csi->result_seek[i];
1157 tagcache_search_add_clause(&tcs, &cc);
1159 else
1161 tagcache_search_add_filter(&tcs, csi->tagorder[i],
1162 csi->result_seek[i]);
1166 for (i = 0; i <= level; i++)
1168 int j;
1170 for (j = 0; j < csi->clause_count[i]; j++)
1171 tagcache_search_add_clause(&tcs, csi->clause[i][j]);
1174 current_offset = offset;
1175 current_entry_count = 0;
1176 c->dirfull = false;
1178 fmt = NULL;
1179 for (i = 0; i < format_count; i++)
1181 if (formats[i]->group_id == csi->format_id[level])
1182 fmt = formats[i];
1185 if (fmt)
1187 sort_inverse = fmt->sort_inverse;
1188 sort_limit = fmt->limit;
1189 strip = fmt->strip;
1190 sort = true;
1192 else
1194 sort_inverse = false;
1195 sort_limit = 0;
1196 strip = 0;
1199 if (tag != tag_title && tag != tag_filename)
1201 if (offset == 0)
1203 dptr->newtable = ALLSUBENTRIES;
1204 dptr->name = str(LANG_TAGNAVI_ALL_TRACKS);
1205 dptr++;
1206 current_entry_count++;
1208 if (offset <= 1)
1210 dptr->newtable = NAVIBROWSE;
1211 dptr->name = str(LANG_TAGNAVI_RANDOM);
1212 dptr->extraseek = -1;
1213 dptr++;
1214 current_entry_count++;
1216 special_entry_count+=2;
1219 total_count += special_entry_count;
1221 while (tagcache_get_next(&tcs))
1223 if (total_count++ < offset)
1224 continue;
1226 if ( strcmp(tcs.result , UNTAGGED ) == 0)
1228 tcs.result_len = strlcpy(tcs.result,
1229 str(LANG_TAGNAVI_UNTAGGED), TAG_MAXLEN )+1;
1232 dptr->newtable = NAVIBROWSE;
1233 if (tag == tag_title || tag == tag_filename)
1235 dptr->newtable = PLAYTRACK;
1236 dptr->extraseek = tcs.idx_id;
1238 else
1239 dptr->extraseek = tcs.result_seek;
1241 fmt = NULL;
1242 /* Check the format */
1243 for (i = 0; i < format_count; i++)
1245 if (formats[i]->group_id != csi->format_id[level])
1246 continue;
1248 if (tagcache_check_clauses(&tcs, formats[i]->clause,
1249 formats[i]->clause_count))
1251 fmt = formats[i];
1252 break;
1256 if (!tcs.ramresult || fmt)
1258 char buf[MAX_PATH];
1260 if (fmt)
1262 if (format_str(&tcs, fmt, buf, sizeof buf) < 0)
1264 logf("format_str() failed");
1265 tagcache_search_finish(&tcs);
1266 return 0;
1270 dptr->name = &c->name_buffer[namebufused];
1271 if (fmt)
1272 namebufused += strlen(buf)+1;
1273 else
1274 namebufused += tcs.result_len;
1276 if (namebufused >= c->name_buffer_size)
1278 logf("chunk mode #2: %d", current_entry_count);
1279 c->dirfull = true;
1280 sort = false;
1281 break ;
1283 if (fmt)
1284 strcpy(dptr->name, buf);
1285 else
1286 strcpy(dptr->name, tcs.result);
1288 else
1289 dptr->name = tcs.result;
1291 dptr++;
1292 current_entry_count++;
1294 if (current_entry_count >= global_settings.max_files_in_dir)
1296 logf("chunk mode #3: %d", current_entry_count);
1297 c->dirfull = true;
1298 sort = false;
1299 break ;
1302 if (init && !tcs.ramsearch)
1304 if (!show_search_progress(false, total_count))
1305 { /* user aborted */
1306 tagcache_search_finish(&tcs);
1307 return current_entry_count;
1312 if (sort)
1313 qsort(c->dircache + special_entry_count * c->dentry_size,
1314 current_entry_count - special_entry_count,
1315 c->dentry_size, compare);
1317 if (!init)
1319 tagcache_search_finish(&tcs);
1320 return current_entry_count;
1323 while (tagcache_get_next(&tcs))
1325 if (!tcs.ramsearch)
1327 if (!show_search_progress(false, total_count))
1328 break;
1330 total_count++;
1333 tagcache_search_finish(&tcs);
1335 if (!sort && (sort_inverse || sort_limit))
1337 splashf(HZ*4, ID2P(LANG_SHOWDIR_BUFFER_FULL), total_count);
1338 logf("Too small dir buffer");
1339 return 0;
1342 if (sort_limit)
1343 total_count = MIN(total_count, sort_limit);
1345 if (strip)
1347 dptr = c->dircache;
1348 for (i = 0; i < total_count; i++, dptr++)
1350 int len = strlen(dptr->name);
1352 if (len < strip)
1353 continue;
1355 dptr->name = &dptr->name[strip];
1359 return total_count;
1363 static int load_root(struct tree_context *c)
1365 struct tagentry *dptr = (struct tagentry *)c->dircache;
1366 int i;
1368 tc = c;
1369 c->currtable = ROOT;
1370 if (c->dirlevel == 0)
1371 c->currextra = rootmenu;
1373 menu = menus[c->currextra];
1374 if (menu == NULL)
1375 return 0;
1377 for (i = 0; i < menu->itemcount; i++)
1379 dptr->name = menu->items[i]->name;
1380 switch (menu->items[i]->type)
1382 case menu_next:
1383 dptr->newtable = NAVIBROWSE;
1384 dptr->extraseek = i;
1385 break;
1387 case menu_load:
1388 dptr->newtable = ROOT;
1389 dptr->extraseek = menu->items[i]->link;
1390 break;
1393 dptr++;
1396 current_offset = 0;
1397 current_entry_count = i;
1399 return i;
1402 int tagtree_load(struct tree_context* c)
1404 int count;
1405 int table = c->currtable;
1407 c->dentry_size = sizeof(struct tagentry);
1408 c->dirsindir = 0;
1410 if (!table)
1412 c->dirfull = false;
1413 table = ROOT;
1414 c->currtable = table;
1415 c->currextra = rootmenu;
1418 switch (table)
1420 case ROOT:
1421 count = load_root(c);
1422 break;
1424 case ALLSUBENTRIES:
1425 case NAVIBROWSE:
1426 logf("navibrowse...");
1427 cpu_boost(true);
1428 count = retrieve_entries(c, 0, true);
1429 cpu_boost(false);
1430 break;
1432 default:
1433 logf("Unsupported table %d\n", table);
1434 return -1;
1437 if (count < 0)
1439 c->dirlevel = 0;
1440 count = load_root(c);
1441 splash(HZ, str(LANG_TAGCACHE_BUSY));
1444 /* The _total_ numer of entries available. */
1445 c->dirlength = c->filesindir = count;
1447 return count;
1450 int tagtree_enter(struct tree_context* c)
1452 int rc = 0;
1453 struct tagentry *dptr;
1454 struct mp3entry *id3;
1455 int newextra;
1456 int seek;
1457 int source;
1459 dptr = tagtree_get_entry(c, c->selected_item);
1461 c->dirfull = false;
1462 seek = dptr->extraseek;
1463 if (seek == -1)
1465 if(c->filesindir<=2)
1466 return 0;
1467 srand(current_tick);
1468 dptr = (tagtree_get_entry(c, 2+(rand() % (c->filesindir-2))));
1469 seek = dptr->extraseek;
1471 newextra = dptr->newtable;
1473 if (c->dirlevel >= MAX_DIR_LEVELS)
1474 return 0;
1476 c->selected_item_history[c->dirlevel]=c->selected_item;
1477 c->table_history[c->dirlevel] = c->currtable;
1478 c->extra_history[c->dirlevel] = c->currextra;
1479 c->pos_history[c->dirlevel] = c->firstpos;
1480 c->dirlevel++;
1482 switch (c->currtable) {
1483 case ROOT:
1484 c->currextra = newextra;
1486 if (newextra == ROOT)
1488 menu = menus[seek];
1489 c->currextra = seek;
1492 else if (newextra == NAVIBROWSE)
1494 int i, j;
1496 csi = menu->items[seek]->si;
1497 c->currextra = 0;
1499 strlcpy(current_title[c->currextra], dptr->name,
1500 sizeof(current_title[0]));
1502 /* Read input as necessary. */
1503 for (i = 0; i < csi->tagorder_count; i++)
1505 for (j = 0; j < csi->clause_count[i]; j++)
1507 char* searchstring;
1508 source = csi->clause[i][j]->source;
1510 if (source == source_constant)
1511 continue;
1513 searchstring=csi->clause[i][j]->str;
1514 *searchstring = '\0';
1516 id3 = audio_current_track();
1518 if (source == source_current_path && id3)
1520 char *e;
1521 strlcpy(searchstring, id3->path, SEARCHSTR_SIZE);
1522 e = strrchr(searchstring, '/');
1523 if (e)
1524 *e = '\0';
1526 else if (source > source_runtime && id3)
1529 int k = source-source_runtime;
1530 int offset = id3_to_search_mapping[k].id3_offset;
1531 char **src = (char**)((char*)id3 + offset);
1532 if (*src)
1534 strlcpy(searchstring, *src, SEARCHSTR_SIZE);
1537 else
1539 rc = kbd_input(searchstring, SEARCHSTR_SIZE);
1540 if (rc < 0 || !searchstring[0])
1542 tagtree_exit(c);
1543 return 0;
1545 if (csi->clause[i][j]->numeric)
1546 csi->clause[i][j]->numeric_data = atoi(searchstring);
1553 c->currtable = newextra;
1555 break;
1557 case NAVIBROWSE:
1558 case ALLSUBENTRIES:
1559 if (newextra == PLAYTRACK)
1561 if (global_settings.party_mode && audio_status()) {
1562 splash(HZ, ID2P(LANG_PARTY_MODE));
1563 break;
1565 c->dirlevel--;
1566 /* about to create a new current playlist...
1567 allow user to cancel the operation */
1568 if (!warn_on_pl_erase())
1569 break;
1570 if (tagtree_play_folder(c) >= 0)
1571 rc = 2;
1572 break;
1575 c->currtable = newextra;
1576 csi->result_seek[c->currextra] = seek;
1577 if (c->currextra < csi->tagorder_count-1)
1578 c->currextra++;
1579 else
1580 c->dirlevel--;
1582 /* Update the statusbar title */
1583 strlcpy(current_title[c->currextra], dptr->name,
1584 sizeof(current_title[0]));
1585 break;
1587 default:
1588 c->dirlevel--;
1589 break;
1592 c->selected_item=0;
1593 gui_synclist_select_item(&tree_lists, c->selected_item);
1595 return rc;
1598 void tagtree_exit(struct tree_context* c)
1600 c->dirfull = false;
1601 if (c->dirlevel > 0)
1602 c->dirlevel--;
1603 c->selected_item=c->selected_item_history[c->dirlevel];
1604 gui_synclist_select_item(&tree_lists, c->selected_item);
1605 c->currtable = c->table_history[c->dirlevel];
1606 c->currextra = c->extra_history[c->dirlevel];
1607 c->firstpos = c->pos_history[c->dirlevel];
1610 int tagtree_get_filename(struct tree_context* c, char *buf, int buflen)
1612 struct tagcache_search tcs;
1613 struct tagentry *entry;
1615 entry = tagtree_get_entry(c, c->selected_item);
1617 if (!tagcache_search(&tcs, tag_filename))
1618 return -1;
1620 if (!tagcache_retrieve(&tcs, entry->extraseek, tcs.type, buf, buflen))
1622 tagcache_search_finish(&tcs);
1623 return -2;
1626 tagcache_search_finish(&tcs);
1628 return 0;
1631 static bool insert_all_playlist(struct tree_context *c, int position, bool queue)
1633 struct tagcache_search tcs;
1634 int i;
1635 char buf[MAX_PATH];
1636 int from, to, direction;
1637 int files_left = c->filesindir;
1639 cpu_boost(true);
1640 if (!tagcache_search(&tcs, tag_filename))
1642 splash(HZ, ID2P(LANG_TAGCACHE_BUSY));
1643 cpu_boost(false);
1644 return false;
1647 if (position == PLAYLIST_REPLACE)
1649 if (playlist_remove_all_tracks(NULL) == 0)
1650 position = PLAYLIST_INSERT_LAST;
1651 else
1653 cpu_boost(false);
1654 return false;
1658 if (position == PLAYLIST_INSERT_FIRST)
1660 from = c->filesindir - 1;
1661 to = -1;
1662 direction = -1;
1664 else
1666 from = 0;
1667 to = c->filesindir;
1668 direction = 1;
1671 for (i = from; i != to; i += direction)
1673 /* Count back to zero */
1674 if (!show_search_progress(false, files_left--))
1675 break;
1677 if (!tagcache_retrieve(&tcs, tagtree_get_entry(c, i)->extraseek,
1678 tcs.type, buf, sizeof buf))
1680 continue;
1683 if (playlist_insert_track(NULL, buf, position, queue, false) < 0)
1685 logf("playlist_insert_track failed");
1686 break;
1688 yield();
1690 playlist_sync(NULL);
1691 tagcache_search_finish(&tcs);
1692 cpu_boost(false);
1694 return true;
1697 bool tagtree_insert_selection_playlist(int position, bool queue)
1699 struct tagentry *dptr;
1700 char buf[MAX_PATH];
1701 int dirlevel = tc->dirlevel;
1703 show_search_progress(
1704 #ifdef HAVE_DISK_STORAGE
1705 storage_disk_is_active()
1706 #else
1707 true
1708 #endif
1709 , 0);
1712 /* We need to set the table to allsubentries. */
1713 dptr = tagtree_get_entry(tc, tc->selected_item);
1715 /* Insert a single track? */
1716 if (dptr->newtable == PLAYTRACK)
1718 if (tagtree_get_filename(tc, buf, sizeof buf) < 0)
1720 logf("tagtree_get_filename failed");
1721 return false;
1723 playlist_insert_track(NULL, buf, position, queue, true);
1725 return true;
1728 if (dptr->newtable == NAVIBROWSE)
1730 tagtree_enter(tc);
1731 tagtree_load(tc);
1732 dptr = tagtree_get_entry(tc, tc->selected_item);
1734 else if (dptr->newtable != ALLSUBENTRIES)
1736 logf("unsupported table: %d", dptr->newtable);
1737 return false;
1740 /* Now the current table should be allsubentries. */
1741 if (dptr->newtable != PLAYTRACK)
1743 tagtree_enter(tc);
1744 tagtree_load(tc);
1745 dptr = tagtree_get_entry(tc, tc->selected_item);
1747 /* And now the newtable should be playtrack. */
1748 if (dptr->newtable != PLAYTRACK)
1750 logf("newtable: %d !!", dptr->newtable);
1751 tc->dirlevel = dirlevel;
1752 return false;
1756 if (tc->filesindir <= 0)
1757 splash(HZ, ID2P(LANG_END_PLAYLIST));
1758 else
1760 logf("insert_all_playlist");
1761 if (!insert_all_playlist(tc, position, queue))
1762 splash(HZ*2, ID2P(LANG_FAILED));
1765 /* Finally return the dirlevel to its original value. */
1766 while (tc->dirlevel > dirlevel)
1767 tagtree_exit(tc);
1768 tagtree_load(tc);
1770 return true;
1773 static int tagtree_play_folder(struct tree_context* c)
1775 if (playlist_create(NULL, NULL) < 0)
1777 logf("Failed creating playlist\n");
1778 return -1;
1781 if (!insert_all_playlist(c, PLAYLIST_INSERT_LAST, false))
1782 return -2;
1784 if (global_settings.playlist_shuffle)
1785 c->selected_item = playlist_shuffle(current_tick, c->selected_item);
1786 if (!global_settings.play_selected)
1787 c->selected_item = 0;
1788 gui_synclist_select_item(&tree_lists, c->selected_item);
1790 playlist_start(c->selected_item,0);
1791 playlist_get_current()->num_inserted_tracks = 0; /* make warn on playlist erase work */
1792 return 0;
1795 struct tagentry* tagtree_get_entry(struct tree_context *c, int id)
1797 struct tagentry *entry = (struct tagentry *)c->dircache;
1798 int realid = id - current_offset;
1800 /* Load the next chunk if necessary. */
1801 if (realid >= current_entry_count || realid < 0)
1803 cpu_boost(true);
1804 if (retrieve_entries(c, MAX(0, id - (current_entry_count / 2)),
1805 false) < 0)
1807 logf("retrieve failed");
1808 cpu_boost(false);
1809 return NULL;
1811 realid = id - current_offset;
1812 cpu_boost(false);
1815 return &entry[realid];
1818 char *tagtree_get_title(struct tree_context* c)
1820 switch (c->currtable)
1822 case ROOT:
1823 return menu->title;
1825 case NAVIBROWSE:
1826 case ALLSUBENTRIES:
1827 return current_title[c->currextra];
1830 return "?";
1833 int tagtree_get_attr(struct tree_context* c)
1835 int attr = -1;
1836 switch (c->currtable)
1838 case NAVIBROWSE:
1839 if (csi->tagorder[c->currextra] == tag_title)
1840 attr = FILE_ATTR_AUDIO;
1841 else
1842 attr = ATTR_DIRECTORY;
1843 break;
1845 case ALLSUBENTRIES:
1846 attr = FILE_ATTR_AUDIO;
1847 break;
1849 default:
1850 attr = ATTR_DIRECTORY;
1851 break;
1854 return attr;
1857 int tagtree_get_icon(struct tree_context* c)
1859 int icon = Icon_Folder;
1861 if (tagtree_get_attr(c) == FILE_ATTR_AUDIO)
1862 icon = Icon_Audio;
1864 return icon;