Few more fixes, notably make audiobufend static.
[kugel-rb.git] / apps / tagtree.c
blobd28928dbd5b72b9f33b0b681462681aa98342a25
1 /***************************************************************************
2 * __________ __ ___.
3 * Open \______ \ ____ ____ | | _\_ |__ _______ ___
4 * Source | _// _ \_/ ___\| |/ /| __ \ / _ \ \/ /
5 * Jukebox | | ( <_> ) \___| < | \_\ ( <_> > < <
6 * Firmware |____|_ /\____/ \___ >__|_ \|___ /\____/__/\_ \
7 * \/ \/ \/ \/ \/
8 * $Id$
10 * Copyright (C) 2005 by Miika Pekkarinen
12 * This program is free software; you can redistribute it and/or
13 * modify it under the terms of the GNU General Public License
14 * as published by the Free Software Foundation; either version 2
15 * of the License, or (at your option) any later version.
17 * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
18 * KIND, either express or implied.
20 ****************************************************************************/
22 /**
23 * Basic structure on this file was copied from dbtree.c and modified to
24 * support the tag cache interface.
27 /*#define LOGF_ENABLE*/
29 #include <stdio.h>
30 #include <stdlib.h>
31 #include "string-extra.h"
32 #include "config.h"
33 #include "system.h"
34 #include "kernel.h"
35 #include "splash.h"
36 #include "icons.h"
37 #include "tree.h"
38 #include "action.h"
39 #include "settings.h"
40 #include "tagcache.h"
41 #include "tagtree.h"
42 #include "lang.h"
43 #include "logf.h"
44 #include "playlist.h"
45 #include "keyboard.h"
46 #include "gui/list.h"
47 #include "buffer.h"
48 #include "yesno.h"
49 #include "misc.h"
50 #include "filetypes.h"
51 #include "audio.h"
52 #include "appevents.h"
53 #include "storage.h"
54 #include "dir.h"
55 #include "playback.h"
57 #define str_or_empty(x) (x ? x : "(NULL)")
59 #define FILE_SEARCH_INSTRUCTIONS ROCKBOX_DIR "/tagnavi.config"
61 static int tagtree_play_folder(struct tree_context* c);
63 #define SEARCHSTR_SIZE 256
65 enum table {
66 ROOT = 1,
67 NAVIBROWSE,
68 ALLSUBENTRIES,
69 PLAYTRACK,
72 static const struct id3_to_search_mapping {
73 char *string;
74 size_t id3_offset;
75 } id3_to_search_mapping[] = {
76 { "", 0 }, /* offset n/a */
77 { "#directory#", 0 }, /* offset n/a */
78 { "#title#", offsetof(struct mp3entry, title) },
79 { "#artist#", offsetof(struct mp3entry, artist) },
80 { "#album#", offsetof(struct mp3entry, album) },
81 { "#genre#", offsetof(struct mp3entry, genre_string) },
82 { "#composer#", offsetof(struct mp3entry, composer) },
83 { "#albumartist#", offsetof(struct mp3entry, albumartist) },
85 enum variables {
86 var_sorttype = 100,
87 var_limit,
88 var_strip,
89 var_menu_start,
90 var_include,
91 var_rootmenu,
92 var_format,
93 menu_next,
94 menu_load,
97 /* Capacity 10 000 entries (for example 10k different artists) */
98 #define UNIQBUF_SIZE (64*1024)
99 static long *uniqbuf;
101 #define MAX_TAGS 5
102 #define MAX_MENU_ID_SIZE 32
104 static bool sort_inverse;
107 * "%3d. %s" autoscore title %sort = "inverse" %limit = "100"
109 * valid = true
110 * formatstr = "%-3d. %s"
111 * tags[0] = tag_autoscore
112 * tags[1] = tag_title
113 * tag_count = 2
115 * limit = 100
116 * sort_inverse = true
118 struct display_format {
119 char name[32];
120 struct tagcache_search_clause *clause[TAGCACHE_MAX_CLAUSES];
121 int clause_count;
122 char *formatstr;
123 int group_id;
124 int tags[MAX_TAGS];
125 int tag_count;
127 int limit;
128 int strip;
129 bool sort_inverse;
132 static struct display_format *formats[TAGMENU_MAX_FMTS];
133 static int format_count;
135 struct search_instruction {
136 char name[64];
137 int tagorder[MAX_TAGS];
138 int tagorder_count;
139 struct tagcache_search_clause *clause[MAX_TAGS][TAGCACHE_MAX_CLAUSES];
140 int format_id[MAX_TAGS];
141 int clause_count[MAX_TAGS];
142 int result_seek[MAX_TAGS];
145 struct menu_entry {
146 char name[64];
147 int type;
148 struct search_instruction *si;
149 int link;
152 struct menu_root {
153 char title[64];
154 char id[MAX_MENU_ID_SIZE];
155 int itemcount;
156 struct menu_entry *items[TAGMENU_MAX_ITEMS];
159 struct match
161 const char* str;
162 int symbol;
165 /* Statusbar text of the current view. */
166 static char current_title[MAX_TAGS][128];
168 static struct menu_root *menus[TAGMENU_MAX_MENUS];
169 static struct menu_root *menu;
170 static struct search_instruction *csi;
171 static const char *strp;
172 static int menu_count;
173 static int rootmenu;
175 static int current_offset;
176 static int current_entry_count;
178 static struct tree_context *tc;
180 static int get_token_str(char *buf, int size)
182 /* Find the start. */
183 while (*strp != '"' && *strp != '\0')
184 strp++;
186 if (*strp == '\0' || *(++strp) == '\0')
187 return -1;
189 /* Read the data. */
190 while (*strp != '"' && *strp != '\0' && --size > 0)
191 *(buf++) = *(strp++);
193 *buf = '\0';
194 if (*strp != '"')
195 return -2;
197 strp++;
199 return 0;
202 static int get_tag(int *tag)
204 static const struct match get_tag_match[] =
206 {"album", tag_album},
207 {"artist", tag_artist},
208 {"bitrate", tag_bitrate},
209 {"composer", tag_composer},
210 {"comment", tag_comment},
211 {"albumartist", tag_albumartist},
212 {"ensemble", tag_albumartist},
213 {"grouping", tag_grouping},
214 {"genre", tag_genre},
215 {"length", tag_length},
216 {"Lm", tag_virt_length_min},
217 {"Ls", tag_virt_length_sec},
218 {"Pm", tag_virt_playtime_min},
219 {"Ps", tag_virt_playtime_sec},
220 {"title", tag_title},
221 {"filename", tag_filename},
222 {"tracknum", tag_tracknumber},
223 {"discnum", tag_discnumber},
224 {"year", tag_year},
225 {"playcount", tag_playcount},
226 {"rating", tag_rating},
227 {"lastplayed", tag_lastplayed},
228 {"lastoffset", tag_lastoffset},
229 {"commitid", tag_commitid},
230 {"entryage", tag_virt_entryage},
231 {"autoscore", tag_virt_autoscore},
232 {"%sort", var_sorttype},
233 {"%limit", var_limit},
234 {"%strip", var_strip},
235 {"%menu_start", var_menu_start},
236 {"%include", var_include},
237 {"%root_menu", var_rootmenu},
238 {"%format", var_format},
239 {"->", menu_next},
240 {"==>", menu_load}
242 char buf[128];
243 unsigned int i;
245 /* Find the start. */
246 while ((*strp == ' ' || *strp == '>') && *strp != '\0')
247 strp++;
249 if (*strp == '\0' || *strp == '?')
250 return 0;
252 for (i = 0; i < sizeof(buf)-1; i++)
254 if (*strp == '\0' || *strp == ' ')
255 break ;
256 buf[i] = *strp;
257 strp++;
259 buf[i] = '\0';
261 for (i = 0; i < ARRAYLEN(get_tag_match); i++)
263 if (!strcasecmp(buf, get_tag_match[i].str))
265 *tag = get_tag_match[i].symbol;
266 return 1;
270 logf("NO MATCH: %s\n", buf);
271 if (buf[0] == '?')
272 return 0;
274 return -1;
277 static int get_clause(int *condition)
279 static const struct match get_clause_match[] =
281 {"=", clause_is},
282 {"==", clause_is},
283 {"!=", clause_is_not},
284 {">", clause_gt},
285 {">=", clause_gteq},
286 {"<", clause_lt},
287 {"<=", clause_lteq},
288 {"~", clause_contains},
289 {"!~", clause_not_contains},
290 {"^", clause_begins_with},
291 {"!^", clause_not_begins_with},
292 {"$", clause_ends_with},
293 {"!$", clause_not_ends_with},
294 {"@", clause_oneof}
297 char buf[4];
298 unsigned int i;
300 /* Find the start. */
301 while (*strp == ' ' && *strp != '\0')
302 strp++;
304 if (*strp == '\0')
305 return 0;
307 for (i = 0; i < sizeof(buf)-1; i++)
309 if (*strp == '\0' || *strp == ' ')
310 break ;
311 buf[i] = *strp;
312 strp++;
314 buf[i] = '\0';
316 for (i = 0; i < ARRAYLEN(get_clause_match); i++)
318 if (!strcasecmp(buf, get_clause_match[i].str))
320 *condition = get_clause_match[i].symbol;
321 return 1;
325 return 0;
328 static bool read_clause(struct tagcache_search_clause *clause)
330 char buf[SEARCHSTR_SIZE];
331 unsigned int i;
333 if (get_tag(&clause->tag) <= 0)
334 return false;
336 if (get_clause(&clause->type) <= 0)
337 return false;
339 if (get_token_str(buf, sizeof buf) < 0)
340 return false;
342 for (i=0; i<ARRAYLEN(id3_to_search_mapping); i++)
344 if (!strcasecmp(buf, id3_to_search_mapping[i].string))
345 break;
348 if (i<ARRAYLEN(id3_to_search_mapping)) /* runtime search operand found */
350 clause->source = source_runtime+i;
351 clause->str = buffer_alloc(SEARCHSTR_SIZE);
353 else
355 clause->source = source_constant;
356 clause->str = buffer_alloc(strlen(buf)+1);
357 strcpy(clause->str, buf);
360 if (TAGCACHE_IS_NUMERIC(clause->tag))
362 clause->numeric = true;
363 clause->numeric_data = atoi(clause->str);
365 else
366 clause->numeric = false;
368 logf("got clause: %d/%d [%s]", clause->tag, clause->type, clause->str);
370 return true;
373 static bool read_variable(char *buf, int size)
375 int condition;
377 if (!get_clause(&condition))
378 return false;
380 if (condition != clause_is)
381 return false;
383 if (get_token_str(buf, size) < 0)
384 return false;
386 return true;
389 /* "%3d. %s" autoscore title %sort = "inverse" %limit = "100" */
390 static int get_format_str(struct display_format *fmt)
392 int ret;
393 char buf[128];
394 int i;
396 memset(fmt, 0, sizeof(struct display_format));
398 if (get_token_str(fmt->name, sizeof fmt->name) < 0)
399 return -10;
401 /* Determine the group id */
402 fmt->group_id = 0;
403 for (i = 0; i < format_count; i++)
405 if (!strcasecmp(formats[i]->name, fmt->name))
407 fmt->group_id = formats[i]->group_id;
408 break;
411 if (formats[i]->group_id > fmt->group_id)
412 fmt->group_id = formats[i]->group_id;
415 if (i == format_count)
416 fmt->group_id++;
418 logf("format: (%d) %s", fmt->group_id, fmt->name);
420 if (get_token_str(buf, sizeof buf) < 0)
421 return -10;
423 fmt->formatstr = buffer_alloc(strlen(buf) + 1);
424 strcpy(fmt->formatstr, buf);
426 while (fmt->tag_count < MAX_TAGS)
428 ret = get_tag(&fmt->tags[fmt->tag_count]);
429 if (ret < 0)
430 return -11;
432 if (ret == 0)
433 break;
435 switch (fmt->tags[fmt->tag_count]) {
436 case var_sorttype:
437 if (!read_variable(buf, sizeof buf))
438 return -12;
439 if (!strcasecmp("inverse", buf))
440 fmt->sort_inverse = true;
441 break;
443 case var_limit:
444 if (!read_variable(buf, sizeof buf))
445 return -13;
446 fmt->limit = atoi(buf);
447 break;
449 case var_strip:
450 if (!read_variable(buf, sizeof buf))
451 return -14;
452 fmt->strip = atoi(buf);
453 break;
455 default:
456 fmt->tag_count++;
460 return 1;
463 static int add_format(const char *buf)
465 strp = buf;
467 if (formats[format_count] == NULL)
468 formats[format_count] = buffer_alloc(sizeof(struct display_format));
470 memset(formats[format_count], 0, sizeof(struct display_format));
471 if (get_format_str(formats[format_count]) < 0)
473 logf("get_format_str() parser failed!");
474 return -4;
477 while (*strp != '\0' && *strp != '?')
478 strp++;
480 if (*strp == '?')
482 int clause_count = 0;
483 strp++;
485 while (1)
487 struct tagcache_search_clause *newclause;
489 if (clause_count >= TAGCACHE_MAX_CLAUSES)
491 logf("too many clauses");
492 break;
495 newclause = buffer_alloc(sizeof(struct tagcache_search_clause));
497 formats[format_count]->clause[clause_count] = newclause;
498 if (!read_clause(newclause))
499 break;
501 clause_count++;
504 formats[format_count]->clause_count = clause_count;
507 format_count++;
509 return 1;
512 static int get_condition(struct search_instruction *inst)
514 struct tagcache_search_clause *new_clause;
515 int clause_count;
516 char buf[128];
518 switch (*strp)
520 case '=':
522 int i;
524 if (get_token_str(buf, sizeof buf) < 0)
525 return -1;
527 for (i = 0; i < format_count; i++)
529 if (!strcasecmp(formats[i]->name, buf))
530 break;
533 if (i == format_count)
535 logf("format not found: %s", buf);
536 return -2;
539 inst->format_id[inst->tagorder_count] = formats[i]->group_id;
540 return 1;
542 case '?':
543 case ' ':
544 case '&':
545 strp++;
546 return 1;
547 case '-':
548 case '\0':
549 return 0;
552 clause_count = inst->clause_count[inst->tagorder_count];
553 if (clause_count >= TAGCACHE_MAX_CLAUSES)
555 logf("Too many clauses");
556 return false;
559 new_clause = buffer_alloc(sizeof(struct tagcache_search_clause));
560 inst->clause[inst->tagorder_count][clause_count] = new_clause;
562 if (*strp == '|')
564 strp++;
565 new_clause->type = clause_logical_or;
567 else if (!read_clause(new_clause))
568 return -1;
570 inst->clause_count[inst->tagorder_count]++;
572 return 1;
575 /* example search:
576 * "Best" artist ? year >= "2000" & title !^ "crap" & genre = "good genre" \
577 * : album ? year >= "2000" : songs
578 * ^ begins with
579 * * contains
580 * $ ends with
583 static bool parse_search(struct menu_entry *entry, const char *str)
585 int ret;
586 int type;
587 struct search_instruction *inst = entry->si;
588 char buf[MAX_PATH];
589 int i;
590 struct menu_root *new_menu;
592 strp = str;
594 /* Parse entry name */
595 if (get_token_str(entry->name, sizeof entry->name) < 0)
597 logf("No name found.");
598 return false;
601 /* Parse entry type */
602 if (get_tag(&entry->type) <= 0)
603 return false;
605 if (entry->type == menu_load)
607 if (get_token_str(buf, sizeof buf) < 0)
608 return false;
610 /* Find the matching root menu or "create" it */
611 for (i = 0; i < menu_count; i++)
613 if (!strcasecmp(menus[i]->id, buf))
615 entry->link = i;
616 return true;
620 if (menu_count >= TAGMENU_MAX_MENUS)
622 logf("max menucount reached");
623 return false;
626 /* Allocate a new menu unless link is found. */
627 menus[menu_count] = buffer_alloc(sizeof(struct menu_root));
628 new_menu = menus[menu_count];
629 memset(new_menu, 0, sizeof(struct menu_root));
630 strlcpy(new_menu->id, buf, MAX_MENU_ID_SIZE);
631 entry->link = menu_count;
632 ++menu_count;
634 return true;
637 if (entry->type != menu_next)
638 return false;
640 while (inst->tagorder_count < MAX_TAGS)
642 ret = get_tag(&inst->tagorder[inst->tagorder_count]);
643 if (ret < 0)
645 logf("Parse error #1");
646 logf("%s", strp);
647 return false;
650 if (ret == 0)
651 break ;
653 logf("tag: %d", inst->tagorder[inst->tagorder_count]);
655 while ( (ret = get_condition(inst)) > 0 ) ;
656 if (ret < 0)
657 return false;
659 inst->tagorder_count++;
661 if (get_tag(&type) <= 0 || type != menu_next)
662 break;
665 return true;
668 static int compare(const void *p1, const void *p2)
670 struct tagentry *e1 = (struct tagentry *)p1;
671 struct tagentry *e2 = (struct tagentry *)p2;
673 if (sort_inverse)
674 return strncasecmp(e2->name, e1->name, MAX_PATH);
676 return strncasecmp(e1->name, e2->name, MAX_PATH);
679 static void tagtree_buffer_event(void *data)
681 struct tagcache_search tcs;
682 struct mp3entry *id3 = (struct mp3entry*)data;
684 /* Do not gather data unless proper setting has been enabled. */
685 if (!global_settings.runtimedb && !global_settings.autoresume_enable)
686 return;
688 logf("be:%s", id3->path);
690 while (! tagcache_is_fully_initialized())
691 yield();
693 if (!tagcache_find_index(&tcs, id3->path))
695 logf("tc stat: not found: %s", id3->path);
696 return;
699 if (global_settings.runtimedb)
701 id3->playcount = tagcache_get_numeric(&tcs, tag_playcount);
702 if (!id3->rating)
703 id3->rating = tagcache_get_numeric(&tcs, tag_rating);
704 id3->lastplayed = tagcache_get_numeric(&tcs, tag_lastplayed);
705 id3->score = tagcache_get_numeric(&tcs, tag_virt_autoscore) / 10;
706 id3->playtime = tagcache_get_numeric(&tcs, tag_playtime);
708 logf("-> %ld/%ld", id3->playcount, id3->playtime);
711 #if CONFIG_CODEC == SWCODEC
712 if (global_settings.autoresume_enable)
714 /* Load current file resume offset if not already defined (by
715 another resume mechanism) */
716 if (id3->offset == 0)
718 id3->offset = tagcache_get_numeric(&tcs, tag_lastoffset);
720 logf("tagtree_buffer_event: Set offset for %s to %lX\n",
721 str_or_empty(id3->title), id3->offset);
724 #endif
726 /* Store our tagcache index pointer. */
727 id3->tagcache_idx = tcs.idx_id+1;
729 tagcache_search_finish(&tcs);
732 static void tagtree_track_finish_event(void *data)
734 long lastplayed;
735 long tagcache_idx;
736 struct mp3entry *id3 = (struct mp3entry*)data;
738 /* Do not gather data unless proper setting has been enabled. */
739 if (!global_settings.runtimedb && !global_settings.autoresume_enable)
741 logf("runtimedb gathering and autoresume not enabled");
742 return;
745 tagcache_idx=id3->tagcache_idx;
746 if (!tagcache_idx)
748 logf("No tagcache index pointer found");
749 return;
751 tagcache_idx--;
753 /* Don't process unplayed tracks, or tracks interrupted within the
754 first 15 seconds. */
755 if (id3->elapsed == 0
756 #if CONFIG_CODEC == SWCODEC /* HWCODEC doesn't have automatic_skip */
757 || (id3->elapsed < 15 * 1000 && !audio_automatic_skip())
758 #endif
761 logf("not logging unplayed or skipped track");
762 return;
765 lastplayed = tagcache_increase_serial();
766 if (lastplayed < 0)
768 logf("incorrect tc serial:%ld", lastplayed);
769 return;
772 if (global_settings.runtimedb)
774 long playcount;
775 long playtime;
777 playcount = id3->playcount + 1;
779 /* Ignore the last 15s (crossfade etc.) */
780 playtime = id3->playtime + MIN(id3->length, id3->elapsed + 15 * 1000);
782 logf("ube:%s", id3->path);
783 logf("-> %ld/%ld", playcount, playtime);
784 logf("-> %ld/%ld/%ld", id3->elapsed, id3->length,
785 MIN(id3->length, id3->elapsed + 15 * 1000));
787 /* Queue the updates to the tagcache system. */
788 tagcache_update_numeric(tagcache_idx, tag_playcount, playcount);
789 tagcache_update_numeric(tagcache_idx, tag_playtime, playtime);
790 tagcache_update_numeric(tagcache_idx, tag_lastplayed, lastplayed);
793 #if CONFIG_CODEC == SWCODEC
794 if (global_settings.autoresume_enable)
796 unsigned long offset
797 = audio_automatic_skip() ? 0 : id3->offset;
799 tagcache_update_numeric(tagcache_idx, tag_lastoffset, offset);
801 logf("tagtree_track_finish_event: Save offset for %s: %lX",
802 str_or_empty(id3->title), offset);
804 #endif
807 bool tagtree_export(void)
809 struct tagcache_search tcs;
811 splash(0, str(LANG_CREATING));
812 if (!tagcache_create_changelog(&tcs))
814 splash(HZ*2, ID2P(LANG_FAILED));
817 return false;
820 bool tagtree_import(void)
822 splash(0, ID2P(LANG_WAIT));
823 if (!tagcache_import_changelog())
825 splash(HZ*2, ID2P(LANG_FAILED));
828 return false;
831 static bool parse_menu(const char *filename);
833 static int parse_line(int n, const char *buf, void *parameters)
835 char data[256];
836 int variable;
837 static bool read_menu;
838 int i;
840 (void)parameters;
842 logf("parse:%d/%s", n, buf);
844 /* First line, do initialisation. */
845 if (n == 0)
847 if (strcasecmp(TAGNAVI_VERSION, buf))
849 logf("Version mismatch");
850 return -1;
853 read_menu = false;
856 if (buf[0] == '#')
857 return 0;
859 if (buf[0] == '\0')
861 if (read_menu)
863 /* End the menu */
864 read_menu = false;
866 return 0;
869 if (!read_menu)
871 strp = buf;
872 if (get_tag(&variable) <= 0)
873 return 0;
875 switch (variable)
877 case var_format:
878 if (add_format(strp) < 0)
880 logf("Format add fail: %s", data);
882 break;
884 case var_include:
885 if (get_token_str(data, sizeof(data)) < 0)
887 logf("%%include empty");
888 return 0;
891 if (!parse_menu(data))
893 logf("Load menu fail: %s", data);
895 break;
897 case var_menu_start:
898 if (menu_count >= TAGMENU_MAX_MENUS)
900 logf("max menucount reached");
901 return 0;
904 if (get_token_str(data, sizeof data) < 0)
906 logf("%%menu_start id empty");
907 return 0;
910 menu = NULL;
911 for (i = 0; i < menu_count; i++)
913 if (!strcasecmp(menus[i]->id, data))
915 menu = menus[i];
919 if (menu == NULL)
921 menus[menu_count] = buffer_alloc(sizeof(struct menu_root));
922 menu = menus[menu_count];
923 ++menu_count;
924 memset(menu, 0, sizeof(struct menu_root));
925 strlcpy(menu->id, data, MAX_MENU_ID_SIZE);
928 if (get_token_str(menu->title, sizeof(menu->title)) < 0)
930 logf("%%menu_start title empty");
931 return 0;
933 logf("menu: %s", menu->title);
934 read_menu = true;
935 break;
937 case var_rootmenu:
938 /* Only set root menu once. */
939 if (rootmenu >= 0)
940 break;
942 if (get_token_str(data, sizeof(data)) < 0)
944 logf("%%rootmenu empty");
945 return 0;
948 for (i = 0; i < menu_count; i++)
950 if (!strcasecmp(menus[i]->id, data))
952 rootmenu = i;
955 break;
958 return 0;
961 if (menu->itemcount >= TAGMENU_MAX_ITEMS)
963 logf("max itemcount reached");
964 return 0;
967 /* Allocate */
968 if (menu->items[menu->itemcount] == NULL)
970 menu->items[menu->itemcount] = buffer_alloc(sizeof(struct menu_entry));
971 memset(menu->items[menu->itemcount], 0, sizeof(struct menu_entry));
972 menu->items[menu->itemcount]->si = buffer_alloc(sizeof(struct search_instruction));
975 memset(menu->items[menu->itemcount]->si, 0, sizeof(struct search_instruction));
976 if (!parse_search(menu->items[menu->itemcount], buf))
977 return 0;
979 menu->itemcount++;
981 return 0;
984 static bool parse_menu(const char *filename)
986 int fd;
987 char buf[1024];
989 if (menu_count >= TAGMENU_MAX_MENUS)
991 logf("max menucount reached");
992 return false;
995 fd = open(filename, O_RDONLY);
996 if (fd < 0)
998 logf("Search instruction file not found.");
999 return false;
1002 /* Now read file for real, parsing into si */
1003 fast_readline(fd, buf, sizeof buf, NULL, parse_line);
1004 close(fd);
1006 return true;
1009 void tagtree_init(void)
1011 format_count = 0;
1012 menu_count = 0;
1013 menu = NULL;
1014 rootmenu = -1;
1015 parse_menu(FILE_SEARCH_INSTRUCTIONS);
1017 /* If no root menu is set, assume it's the first single menu
1018 * we have. That shouldn't normally happen. */
1019 if (rootmenu < 0)
1020 rootmenu = 0;
1022 uniqbuf = buffer_alloc(UNIQBUF_SIZE);
1024 add_event(PLAYBACK_EVENT_TRACK_BUFFER, false, tagtree_buffer_event);
1025 add_event(PLAYBACK_EVENT_TRACK_FINISH, false, tagtree_track_finish_event);
1028 static bool show_search_progress(bool init, int count)
1030 static int last_tick = 0;
1032 /* Don't show splashes for 1/2 second after starting search */
1033 if (init)
1035 last_tick = current_tick + HZ/2;
1036 return true;
1039 /* Update progress every 1/10 of a second */
1040 if (TIME_AFTER(current_tick, last_tick + HZ/10))
1042 splashf(0, str(LANG_PLAYLIST_SEARCH_MSG), count, str(LANG_OFF_ABORT));
1043 if (action_userabort(TIMEOUT_NOBLOCK))
1044 return false;
1045 last_tick = current_tick;
1046 yield();
1049 return true;
1052 static int format_str(struct tagcache_search *tcs, struct display_format *fmt,
1053 char *buf, int buf_size)
1055 char fmtbuf[8];
1056 bool read_format = false;
1057 int fmtbuf_pos = 0;
1058 int parpos = 0;
1059 int buf_pos = 0;
1060 int i;
1062 memset(buf, 0, buf_size);
1063 for (i = 0; fmt->formatstr[i] != '\0'; i++)
1065 if (fmt->formatstr[i] == '%')
1067 read_format = true;
1068 fmtbuf_pos = 0;
1069 if (parpos >= fmt->tag_count)
1071 logf("too many format tags");
1072 return -1;
1076 if (read_format)
1078 fmtbuf[fmtbuf_pos++] = fmt->formatstr[i];
1079 if (fmtbuf_pos >= buf_size)
1081 logf("format parse error");
1082 return -2;
1085 if (fmt->formatstr[i] == 's')
1087 fmtbuf[fmtbuf_pos] = '\0';
1088 read_format = false;
1089 if (fmt->tags[parpos] == tcs->type)
1091 snprintf(&buf[buf_pos], buf_size - buf_pos, fmtbuf, tcs->result);
1093 else
1095 /* Need to fetch the tag data. */
1096 if (!tagcache_retrieve(tcs, tcs->idx_id, fmt->tags[parpos],
1097 &buf[buf_pos], buf_size - buf_pos))
1099 logf("retrieve failed");
1100 return -3;
1103 buf_pos += strlen(&buf[buf_pos]);
1104 parpos++;
1106 else if (fmt->formatstr[i] == 'd')
1108 fmtbuf[fmtbuf_pos] = '\0';
1109 read_format = false;
1110 snprintf(&buf[buf_pos], buf_size - buf_pos, fmtbuf,
1111 tagcache_get_numeric(tcs, fmt->tags[parpos]));
1112 buf_pos += strlen(&buf[buf_pos]);
1113 parpos++;
1115 continue;
1118 buf[buf_pos++] = fmt->formatstr[i];
1120 if (buf_pos - 1 >= buf_size)
1122 logf("buffer overflow");
1123 return -4;
1127 buf[buf_pos++] = '\0';
1129 return 0;
1132 static int retrieve_entries(struct tree_context *c, int offset, bool init)
1134 struct tagcache_search tcs;
1135 struct tagentry *dptr = (struct tagentry *)c->dircache;
1136 struct display_format *fmt;
1137 int i;
1138 int namebufused = 0;
1139 int total_count = 0;
1140 int special_entry_count = 0;
1141 int level = c->currextra;
1142 int tag;
1143 bool sort = false;
1144 int sort_limit;
1145 int strip;
1147 /* Show search progress straight away if the disk needs to spin up,
1148 otherwise show it after the normal 1/2 second delay */
1149 show_search_progress(
1150 #ifdef HAVE_DISK_STORAGE
1151 storage_disk_is_active()
1152 #else
1153 true
1154 #endif
1155 , 0);
1157 if (c->currtable == ALLSUBENTRIES)
1159 tag = tag_title;
1160 level--;
1162 else
1163 tag = csi->tagorder[level];
1165 if (!tagcache_search(&tcs, tag))
1166 return -1;
1168 /* Prevent duplicate entries in the search list. */
1169 tagcache_search_set_uniqbuf(&tcs, uniqbuf, UNIQBUF_SIZE);
1171 if (level || csi->clause_count[0] || TAGCACHE_IS_NUMERIC(tag))
1172 sort = true;
1174 for (i = 0; i < level; i++)
1176 if (TAGCACHE_IS_NUMERIC(csi->tagorder[i]))
1178 static struct tagcache_search_clause cc;
1180 memset(&cc, 0, sizeof(struct tagcache_search_clause));
1181 cc.tag = csi->tagorder[i];
1182 cc.type = clause_is;
1183 cc.numeric = true;
1184 cc.numeric_data = csi->result_seek[i];
1185 tagcache_search_add_clause(&tcs, &cc);
1187 else
1189 tagcache_search_add_filter(&tcs, csi->tagorder[i],
1190 csi->result_seek[i]);
1194 for (i = 0; i <= level; i++)
1196 int j;
1198 for (j = 0; j < csi->clause_count[i]; j++)
1199 tagcache_search_add_clause(&tcs, csi->clause[i][j]);
1202 current_offset = offset;
1203 current_entry_count = 0;
1204 c->dirfull = false;
1206 fmt = NULL;
1207 for (i = 0; i < format_count; i++)
1209 if (formats[i]->group_id == csi->format_id[level])
1210 fmt = formats[i];
1213 if (fmt)
1215 sort_inverse = fmt->sort_inverse;
1216 sort_limit = fmt->limit;
1217 strip = fmt->strip;
1218 sort = true;
1220 else
1222 sort_inverse = false;
1223 sort_limit = 0;
1224 strip = 0;
1227 if (tag != tag_title && tag != tag_filename)
1229 if (offset == 0)
1231 dptr->newtable = ALLSUBENTRIES;
1232 dptr->name = str(LANG_TAGNAVI_ALL_TRACKS);
1233 dptr++;
1234 current_entry_count++;
1236 if (offset <= 1)
1238 dptr->newtable = NAVIBROWSE;
1239 dptr->name = str(LANG_TAGNAVI_RANDOM);
1240 dptr->extraseek = -1;
1241 dptr++;
1242 current_entry_count++;
1244 special_entry_count+=2;
1247 total_count += special_entry_count;
1249 while (tagcache_get_next(&tcs))
1251 if (total_count++ < offset)
1252 continue;
1254 if ( strcmp(tcs.result , UNTAGGED ) == 0)
1256 tcs.result_len = strlcpy(tcs.result,
1257 str(LANG_TAGNAVI_UNTAGGED), TAG_MAXLEN )+1;
1260 dptr->newtable = NAVIBROWSE;
1261 if (tag == tag_title || tag == tag_filename)
1263 dptr->newtable = PLAYTRACK;
1264 dptr->extraseek = tcs.idx_id;
1266 else
1267 dptr->extraseek = tcs.result_seek;
1269 fmt = NULL;
1270 /* Check the format */
1271 for (i = 0; i < format_count; i++)
1273 if (formats[i]->group_id != csi->format_id[level])
1274 continue;
1276 if (tagcache_check_clauses(&tcs, formats[i]->clause,
1277 formats[i]->clause_count))
1279 fmt = formats[i];
1280 break;
1284 if (!tcs.ramresult || fmt)
1286 char buf[MAX_PATH];
1288 if (fmt)
1290 if (format_str(&tcs, fmt, buf, sizeof buf) < 0)
1292 logf("format_str() failed");
1293 tagcache_search_finish(&tcs);
1294 return 0;
1298 dptr->name = &c->name_buffer[namebufused];
1299 if (fmt)
1300 namebufused += strlen(buf)+1;
1301 else
1302 namebufused += tcs.result_len;
1304 if (namebufused >= c->name_buffer_size)
1306 logf("chunk mode #2: %d", current_entry_count);
1307 c->dirfull = true;
1308 sort = false;
1309 break ;
1311 if (fmt)
1312 strcpy(dptr->name, buf);
1313 else
1314 strcpy(dptr->name, tcs.result);
1316 else
1317 dptr->name = tcs.result;
1319 dptr++;
1320 current_entry_count++;
1322 if (current_entry_count >= c->dircache_count)
1324 logf("chunk mode #3: %d", current_entry_count);
1325 c->dirfull = true;
1326 sort = false;
1327 break ;
1330 if (init && !tcs.ramsearch)
1332 if (!show_search_progress(false, total_count))
1333 { /* user aborted */
1334 tagcache_search_finish(&tcs);
1335 return current_entry_count;
1340 if (sort)
1341 qsort(c->dircache + special_entry_count * c->dentry_size,
1342 current_entry_count - special_entry_count,
1343 c->dentry_size, compare);
1345 if (!init)
1347 tagcache_search_finish(&tcs);
1348 return current_entry_count;
1351 while (tagcache_get_next(&tcs))
1353 if (!tcs.ramsearch)
1355 if (!show_search_progress(false, total_count))
1356 break;
1358 total_count++;
1361 tagcache_search_finish(&tcs);
1363 if (!sort && (sort_inverse || sort_limit))
1365 splashf(HZ*4, ID2P(LANG_SHOWDIR_BUFFER_FULL), total_count);
1366 logf("Too small dir buffer");
1367 return 0;
1370 if (sort_limit)
1371 total_count = MIN(total_count, sort_limit);
1373 if (strip)
1375 dptr = c->dircache;
1376 for (i = 0; i < total_count; i++, dptr++)
1378 int len = strlen(dptr->name);
1380 if (len < strip)
1381 continue;
1383 dptr->name = &dptr->name[strip];
1387 return total_count;
1391 static int load_root(struct tree_context *c)
1393 struct tagentry *dptr = (struct tagentry *)c->dircache;
1394 int i;
1396 tc = c;
1397 c->currtable = ROOT;
1398 if (c->dirlevel == 0)
1399 c->currextra = rootmenu;
1401 menu = menus[c->currextra];
1402 if (menu == NULL)
1403 return 0;
1405 for (i = 0; i < menu->itemcount; i++)
1407 dptr->name = menu->items[i]->name;
1408 switch (menu->items[i]->type)
1410 case menu_next:
1411 dptr->newtable = NAVIBROWSE;
1412 dptr->extraseek = i;
1413 break;
1415 case menu_load:
1416 dptr->newtable = ROOT;
1417 dptr->extraseek = menu->items[i]->link;
1418 break;
1421 dptr++;
1424 current_offset = 0;
1425 current_entry_count = i;
1427 return i;
1430 int tagtree_load(struct tree_context* c)
1432 int count;
1433 int table = c->currtable;
1435 c->dentry_size = sizeof(struct tagentry);
1436 c->dirsindir = 0;
1438 if (!table)
1440 c->dirfull = false;
1441 table = ROOT;
1442 c->currtable = table;
1443 c->currextra = rootmenu;
1446 switch (table)
1448 case ROOT:
1449 count = load_root(c);
1450 break;
1452 case ALLSUBENTRIES:
1453 case NAVIBROWSE:
1454 logf("navibrowse...");
1455 cpu_boost(true);
1456 count = retrieve_entries(c, 0, true);
1457 cpu_boost(false);
1458 break;
1460 default:
1461 logf("Unsupported table %d\n", table);
1462 return -1;
1465 if (count < 0)
1467 c->dirlevel = 0;
1468 count = load_root(c);
1469 splash(HZ, str(LANG_TAGCACHE_BUSY));
1472 /* The _total_ numer of entries available. */
1473 c->dirlength = c->filesindir = count;
1475 return count;
1478 int tagtree_enter(struct tree_context* c)
1480 int rc = 0;
1481 struct tagentry *dptr;
1482 struct mp3entry *id3;
1483 int newextra;
1484 int seek;
1485 int source;
1487 dptr = tagtree_get_entry(c, c->selected_item);
1489 c->dirfull = false;
1490 seek = dptr->extraseek;
1491 if (seek == -1)
1493 if(c->filesindir<=2)
1494 return 0;
1495 srand(current_tick);
1496 dptr = (tagtree_get_entry(c, 2+(rand() % (c->filesindir-2))));
1497 seek = dptr->extraseek;
1499 newextra = dptr->newtable;
1501 if (c->dirlevel >= MAX_DIR_LEVELS)
1502 return 0;
1504 c->selected_item_history[c->dirlevel]=c->selected_item;
1505 c->table_history[c->dirlevel] = c->currtable;
1506 c->extra_history[c->dirlevel] = c->currextra;
1507 c->pos_history[c->dirlevel] = c->firstpos;
1508 c->dirlevel++;
1510 switch (c->currtable) {
1511 case ROOT:
1512 c->currextra = newextra;
1514 if (newextra == ROOT)
1516 menu = menus[seek];
1517 c->currextra = seek;
1520 else if (newextra == NAVIBROWSE)
1522 int i, j;
1524 csi = menu->items[seek]->si;
1525 c->currextra = 0;
1527 strlcpy(current_title[c->currextra], dptr->name,
1528 sizeof(current_title[0]));
1530 /* Read input as necessary. */
1531 for (i = 0; i < csi->tagorder_count; i++)
1533 for (j = 0; j < csi->clause_count[i]; j++)
1535 char* searchstring;
1537 if (csi->clause[i][j]->type == clause_logical_or)
1538 continue;
1540 source = csi->clause[i][j]->source;
1542 if (source == source_constant)
1543 continue;
1545 searchstring=csi->clause[i][j]->str;
1546 *searchstring = '\0';
1548 id3 = audio_current_track();
1550 if (source == source_current_path && id3)
1552 char *e;
1553 strlcpy(searchstring, id3->path, SEARCHSTR_SIZE);
1554 e = strrchr(searchstring, '/');
1555 if (e)
1556 *e = '\0';
1558 else if (source > source_runtime && id3)
1561 int k = source-source_runtime;
1562 int offset = id3_to_search_mapping[k].id3_offset;
1563 char **src = (char**)((char*)id3 + offset);
1564 if (*src)
1566 strlcpy(searchstring, *src, SEARCHSTR_SIZE);
1569 else
1571 rc = kbd_input(searchstring, SEARCHSTR_SIZE);
1572 if (rc < 0 || !searchstring[0])
1574 tagtree_exit(c);
1575 return 0;
1577 if (csi->clause[i][j]->numeric)
1578 csi->clause[i][j]->numeric_data = atoi(searchstring);
1585 c->currtable = newextra;
1587 break;
1589 case NAVIBROWSE:
1590 case ALLSUBENTRIES:
1591 if (newextra == PLAYTRACK)
1593 if (global_settings.party_mode && audio_status()) {
1594 splash(HZ, ID2P(LANG_PARTY_MODE));
1595 break;
1597 c->dirlevel--;
1598 /* about to create a new current playlist...
1599 allow user to cancel the operation */
1600 if (!warn_on_pl_erase())
1601 break;
1602 if (tagtree_play_folder(c) >= 0)
1603 rc = 2;
1604 break;
1607 c->currtable = newextra;
1608 csi->result_seek[c->currextra] = seek;
1609 if (c->currextra < csi->tagorder_count-1)
1610 c->currextra++;
1611 else
1612 c->dirlevel--;
1614 /* Update the statusbar title */
1615 strlcpy(current_title[c->currextra], dptr->name,
1616 sizeof(current_title[0]));
1617 break;
1619 default:
1620 c->dirlevel--;
1621 break;
1624 c->selected_item=0;
1625 gui_synclist_select_item(&tree_lists, c->selected_item);
1627 return rc;
1630 void tagtree_exit(struct tree_context* c)
1632 c->dirfull = false;
1633 if (c->dirlevel > 0)
1634 c->dirlevel--;
1635 c->selected_item=c->selected_item_history[c->dirlevel];
1636 gui_synclist_select_item(&tree_lists, c->selected_item);
1637 c->currtable = c->table_history[c->dirlevel];
1638 c->currextra = c->extra_history[c->dirlevel];
1639 c->firstpos = c->pos_history[c->dirlevel];
1642 int tagtree_get_filename(struct tree_context* c, char *buf, int buflen)
1644 struct tagcache_search tcs;
1645 struct tagentry *entry;
1647 entry = tagtree_get_entry(c, c->selected_item);
1649 if (!tagcache_search(&tcs, tag_filename))
1650 return -1;
1652 if (!tagcache_retrieve(&tcs, entry->extraseek, tcs.type, buf, buflen))
1654 tagcache_search_finish(&tcs);
1655 return -2;
1658 tagcache_search_finish(&tcs);
1660 return 0;
1663 static bool insert_all_playlist(struct tree_context *c, int position, bool queue)
1665 struct tagcache_search tcs;
1666 int i;
1667 char buf[MAX_PATH];
1668 int from, to, direction;
1669 int files_left = c->filesindir;
1671 cpu_boost(true);
1672 if (!tagcache_search(&tcs, tag_filename))
1674 splash(HZ, ID2P(LANG_TAGCACHE_BUSY));
1675 cpu_boost(false);
1676 return false;
1679 if (position == PLAYLIST_REPLACE)
1681 if (playlist_remove_all_tracks(NULL) == 0)
1682 position = PLAYLIST_INSERT_LAST;
1683 else
1685 cpu_boost(false);
1686 return false;
1690 if (position == PLAYLIST_INSERT_FIRST)
1692 from = c->filesindir - 1;
1693 to = -1;
1694 direction = -1;
1696 else
1698 from = 0;
1699 to = c->filesindir;
1700 direction = 1;
1703 for (i = from; i != to; i += direction)
1705 /* Count back to zero */
1706 if (!show_search_progress(false, files_left--))
1707 break;
1709 if (!tagcache_retrieve(&tcs, tagtree_get_entry(c, i)->extraseek,
1710 tcs.type, buf, sizeof buf))
1712 continue;
1715 if (playlist_insert_track(NULL, buf, position, queue, false) < 0)
1717 logf("playlist_insert_track failed");
1718 break;
1720 yield();
1722 playlist_sync(NULL);
1723 tagcache_search_finish(&tcs);
1724 cpu_boost(false);
1726 return true;
1729 bool tagtree_insert_selection_playlist(int position, bool queue)
1731 struct tagentry *dptr;
1732 char buf[MAX_PATH];
1733 int dirlevel = tc->dirlevel;
1735 show_search_progress(
1736 #ifdef HAVE_DISK_STORAGE
1737 storage_disk_is_active()
1738 #else
1739 true
1740 #endif
1741 , 0);
1744 /* We need to set the table to allsubentries. */
1745 dptr = tagtree_get_entry(tc, tc->selected_item);
1747 /* Insert a single track? */
1748 if (dptr->newtable == PLAYTRACK)
1750 if (tagtree_get_filename(tc, buf, sizeof buf) < 0)
1752 logf("tagtree_get_filename failed");
1753 return false;
1755 playlist_insert_track(NULL, buf, position, queue, true);
1757 return true;
1760 if (dptr->newtable == NAVIBROWSE)
1762 tagtree_enter(tc);
1763 tagtree_load(tc);
1764 dptr = tagtree_get_entry(tc, tc->selected_item);
1766 else if (dptr->newtable != ALLSUBENTRIES)
1768 logf("unsupported table: %d", dptr->newtable);
1769 return false;
1772 /* Now the current table should be allsubentries. */
1773 if (dptr->newtable != PLAYTRACK)
1775 tagtree_enter(tc);
1776 tagtree_load(tc);
1777 dptr = tagtree_get_entry(tc, tc->selected_item);
1779 /* And now the newtable should be playtrack. */
1780 if (dptr->newtable != PLAYTRACK)
1782 logf("newtable: %d !!", dptr->newtable);
1783 tc->dirlevel = dirlevel;
1784 return false;
1788 if (tc->filesindir <= 0)
1789 splash(HZ, ID2P(LANG_END_PLAYLIST));
1790 else
1792 logf("insert_all_playlist");
1793 if (!insert_all_playlist(tc, position, queue))
1794 splash(HZ*2, ID2P(LANG_FAILED));
1797 /* Finally return the dirlevel to its original value. */
1798 while (tc->dirlevel > dirlevel)
1799 tagtree_exit(tc);
1800 tagtree_load(tc);
1802 return true;
1805 static int tagtree_play_folder(struct tree_context* c)
1807 if (playlist_create(NULL, NULL) < 0)
1809 logf("Failed creating playlist\n");
1810 return -1;
1813 if (!insert_all_playlist(c, PLAYLIST_INSERT_LAST, false))
1814 return -2;
1816 if (global_settings.playlist_shuffle)
1817 c->selected_item = playlist_shuffle(current_tick, c->selected_item);
1818 if (!global_settings.play_selected)
1819 c->selected_item = 0;
1820 gui_synclist_select_item(&tree_lists, c->selected_item);
1822 playlist_start(c->selected_item,0);
1823 playlist_get_current()->num_inserted_tracks = 0; /* make warn on playlist erase work */
1824 return 0;
1827 struct tagentry* tagtree_get_entry(struct tree_context *c, int id)
1829 struct tagentry *entry = (struct tagentry *)c->dircache;
1830 int realid = id - current_offset;
1832 /* Load the next chunk if necessary. */
1833 if (realid >= current_entry_count || realid < 0)
1835 cpu_boost(true);
1836 if (retrieve_entries(c, MAX(0, id - (current_entry_count / 2)),
1837 false) < 0)
1839 logf("retrieve failed");
1840 cpu_boost(false);
1841 return NULL;
1843 realid = id - current_offset;
1844 cpu_boost(false);
1847 return &entry[realid];
1850 char *tagtree_get_title(struct tree_context* c)
1852 switch (c->currtable)
1854 case ROOT:
1855 return menu->title;
1857 case NAVIBROWSE:
1858 case ALLSUBENTRIES:
1859 return current_title[c->currextra];
1862 return "?";
1865 int tagtree_get_attr(struct tree_context* c)
1867 int attr = -1;
1868 switch (c->currtable)
1870 case NAVIBROWSE:
1871 if (csi->tagorder[c->currextra] == tag_title)
1872 attr = FILE_ATTR_AUDIO;
1873 else
1874 attr = ATTR_DIRECTORY;
1875 break;
1877 case ALLSUBENTRIES:
1878 attr = FILE_ATTR_AUDIO;
1879 break;
1881 default:
1882 attr = ATTR_DIRECTORY;
1883 break;
1886 return attr;
1889 int tagtree_get_icon(struct tree_context* c)
1891 int icon = Icon_Folder;
1893 if (tagtree_get_attr(c) == FILE_ATTR_AUDIO)
1894 icon = Icon_Audio;
1896 return icon;