FS#11968 by Peter Lecky - Slovak language update
[maemo-rb.git] / apps / tagtree.c
blob575ab221ac4fbf0eddb34118417f1279160564cd
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 /* Statusbar text of the current view. */
160 static char current_title[MAX_TAGS][128];
162 static struct menu_root *menus[TAGMENU_MAX_MENUS];
163 static struct menu_root *menu;
164 static struct search_instruction *csi;
165 static const char *strp;
166 static int menu_count;
167 static int rootmenu;
169 static int current_offset;
170 static int current_entry_count;
172 static struct tree_context *tc;
174 static int get_token_str(char *buf, int size)
176 /* Find the start. */
177 while (*strp != '"' && *strp != '\0')
178 strp++;
180 if (*strp == '\0' || *(++strp) == '\0')
181 return -1;
183 /* Read the data. */
184 while (*strp != '"' && *strp != '\0' && --size > 0)
185 *(buf++) = *(strp++);
187 *buf = '\0';
188 if (*strp != '"')
189 return -2;
191 strp++;
193 return 0;
196 #define MATCH(tag,str1,str2,settag) \
197 if (!strcasecmp(str1, str2)) { \
198 *tag = settag; \
199 return 1; \
202 static int get_tag(int *tag)
204 char buf[128];
205 int i;
207 /* Find the start. */
208 while ((*strp == ' ' || *strp == '>') && *strp != '\0')
209 strp++;
211 if (*strp == '\0' || *strp == '?')
212 return 0;
214 for (i = 0; i < (int)sizeof(buf)-1; i++)
216 if (*strp == '\0' || *strp == ' ')
217 break ;
218 buf[i] = *strp;
219 strp++;
221 buf[i] = '\0';
223 MATCH(tag, buf, "album", tag_album);
224 MATCH(tag, buf, "artist", tag_artist);
225 MATCH(tag, buf, "bitrate", tag_bitrate);
226 MATCH(tag, buf, "composer", tag_composer);
227 MATCH(tag, buf, "comment", tag_comment);
228 MATCH(tag, buf, "albumartist", tag_albumartist);
229 MATCH(tag, buf, "ensemble", tag_albumartist);
230 MATCH(tag, buf, "grouping", tag_grouping);
231 MATCH(tag, buf, "genre", tag_genre);
232 MATCH(tag, buf, "length", tag_length);
233 MATCH(tag, buf, "Lm", tag_virt_length_min);
234 MATCH(tag, buf, "Ls", tag_virt_length_sec);
235 MATCH(tag, buf, "Pm", tag_virt_playtime_min);
236 MATCH(tag, buf, "Ps", tag_virt_playtime_sec);
237 MATCH(tag, buf, "title", tag_title);
238 MATCH(tag, buf, "filename", tag_filename);
239 MATCH(tag, buf, "tracknum", tag_tracknumber);
240 MATCH(tag, buf, "discnum", tag_discnumber);
241 MATCH(tag, buf, "year", tag_year);
242 MATCH(tag, buf, "playcount", tag_playcount);
243 MATCH(tag, buf, "rating", tag_rating);
244 MATCH(tag, buf, "lastplayed", tag_lastplayed);
245 MATCH(tag, buf, "lastoffset", tag_lastoffset);
246 MATCH(tag, buf, "commitid", tag_commitid);
247 MATCH(tag, buf, "entryage", tag_virt_entryage);
248 MATCH(tag, buf, "autoscore", tag_virt_autoscore);
249 MATCH(tag, buf, "%sort", var_sorttype);
250 MATCH(tag, buf, "%limit", var_limit);
251 MATCH(tag, buf, "%strip", var_strip);
252 MATCH(tag, buf, "%menu_start", var_menu_start);
253 MATCH(tag, buf, "%include", var_include);
254 MATCH(tag, buf, "%root_menu", var_rootmenu);
255 MATCH(tag, buf, "%format", var_format);
256 MATCH(tag, buf, "->", menu_next);
257 MATCH(tag, buf, "==>", menu_load);
259 logf("NO MATCH: %s\n", buf);
260 if (buf[0] == '?')
261 return 0;
263 return -1;
266 static int get_clause(int *condition)
268 char buf[4];
269 int i;
271 /* Find the start. */
272 while (*strp == ' ' && *strp != '\0')
273 strp++;
275 if (*strp == '\0')
276 return 0;
278 for (i = 0; i < (int)sizeof(buf)-1; i++)
280 if (*strp == '\0' || *strp == ' ')
281 break ;
282 buf[i] = *strp;
283 strp++;
285 buf[i] = '\0';
287 MATCH(condition, buf, "=", clause_is);
288 MATCH(condition, buf, "==", clause_is);
289 MATCH(condition, buf, "!=", clause_is_not);
290 MATCH(condition, buf, ">", clause_gt);
291 MATCH(condition, buf, ">=", clause_gteq);
292 MATCH(condition, buf, "<", clause_lt);
293 MATCH(condition, buf, "<=", clause_lteq);
294 MATCH(condition, buf, "~", clause_contains);
295 MATCH(condition, buf, "!~", clause_not_contains);
296 MATCH(condition, buf, "^", clause_begins_with);
297 MATCH(condition, buf, "!^", clause_not_begins_with);
298 MATCH(condition, buf, "$", clause_ends_with);
299 MATCH(condition, buf, "!$", clause_not_ends_with);
300 MATCH(condition, buf, "@", clause_oneof);
302 return 0;
305 static bool read_clause(struct tagcache_search_clause *clause)
307 char buf[SEARCHSTR_SIZE];
308 unsigned int i;
310 if (get_tag(&clause->tag) <= 0)
311 return false;
313 if (get_clause(&clause->type) <= 0)
314 return false;
316 if (get_token_str(buf, sizeof buf) < 0)
317 return false;
319 for (i=0; i<ARRAYLEN(id3_to_search_mapping); i++)
321 if (!strcasecmp(buf, id3_to_search_mapping[i].string))
322 break;
325 if (i<ARRAYLEN(id3_to_search_mapping)) /* runtime search operand found */
327 clause->source = source_runtime+i;
328 clause->str = buffer_alloc(SEARCHSTR_SIZE);
330 else
332 clause->source = source_constant;
333 clause->str = buffer_alloc(strlen(buf)+1);
334 strcpy(clause->str, buf);
337 if (TAGCACHE_IS_NUMERIC(clause->tag))
339 clause->numeric = true;
340 clause->numeric_data = atoi(clause->str);
342 else
343 clause->numeric = false;
345 logf("got clause: %d/%d [%s]", clause->tag, clause->type, clause->str);
347 return true;
350 static bool read_variable(char *buf, int size)
352 int condition;
354 if (!get_clause(&condition))
355 return false;
357 if (condition != clause_is)
358 return false;
360 if (get_token_str(buf, size) < 0)
361 return false;
363 return true;
366 /* "%3d. %s" autoscore title %sort = "inverse" %limit = "100" */
367 static int get_format_str(struct display_format *fmt)
369 int ret;
370 char buf[128];
371 int i;
373 memset(fmt, 0, sizeof(struct display_format));
375 if (get_token_str(fmt->name, sizeof fmt->name) < 0)
376 return -10;
378 /* Determine the group id */
379 fmt->group_id = 0;
380 for (i = 0; i < format_count; i++)
382 if (!strcasecmp(formats[i]->name, fmt->name))
384 fmt->group_id = formats[i]->group_id;
385 break;
388 if (formats[i]->group_id > fmt->group_id)
389 fmt->group_id = formats[i]->group_id;
392 if (i == format_count)
393 fmt->group_id++;
395 logf("format: (%d) %s", fmt->group_id, fmt->name);
397 if (get_token_str(buf, sizeof buf) < 0)
398 return -10;
400 fmt->formatstr = buffer_alloc(strlen(buf) + 1);
401 strcpy(fmt->formatstr, buf);
403 while (fmt->tag_count < MAX_TAGS)
405 ret = get_tag(&fmt->tags[fmt->tag_count]);
406 if (ret < 0)
407 return -11;
409 if (ret == 0)
410 break;
412 switch (fmt->tags[fmt->tag_count]) {
413 case var_sorttype:
414 if (!read_variable(buf, sizeof buf))
415 return -12;
416 if (!strcasecmp("inverse", buf))
417 fmt->sort_inverse = true;
418 break;
420 case var_limit:
421 if (!read_variable(buf, sizeof buf))
422 return -13;
423 fmt->limit = atoi(buf);
424 break;
426 case var_strip:
427 if (!read_variable(buf, sizeof buf))
428 return -14;
429 fmt->strip = atoi(buf);
430 break;
432 default:
433 fmt->tag_count++;
437 return 1;
440 static int add_format(const char *buf)
442 strp = buf;
444 if (formats[format_count] == NULL)
445 formats[format_count] = buffer_alloc(sizeof(struct display_format));
447 memset(formats[format_count], 0, sizeof(struct display_format));
448 if (get_format_str(formats[format_count]) < 0)
450 logf("get_format_str() parser failed!");
451 return -4;
454 while (*strp != '\0' && *strp != '?')
455 strp++;
457 if (*strp == '?')
459 int clause_count = 0;
460 strp++;
462 while (1)
464 if (clause_count >= TAGCACHE_MAX_CLAUSES)
466 logf("too many clauses");
467 break;
470 formats[format_count]->clause[clause_count] =
471 buffer_alloc(sizeof(struct tagcache_search_clause));
473 if (!read_clause(formats[format_count]->clause[clause_count]))
474 break;
476 clause_count++;
479 formats[format_count]->clause_count = clause_count;
482 format_count++;
484 return 1;
487 static int get_condition(struct search_instruction *inst)
489 int clause_count;
490 char buf[128];
492 switch (*strp)
494 case '=':
496 int i;
498 if (get_token_str(buf, sizeof buf) < 0)
499 return -1;
501 for (i = 0; i < format_count; i++)
503 if (!strcasecmp(formats[i]->name, buf))
504 break;
507 if (i == format_count)
509 logf("format not found: %s", buf);
510 return -2;
513 inst->format_id[inst->tagorder_count] = formats[i]->group_id;
514 return 1;
516 case '?':
517 case ' ':
518 case '&':
519 strp++;
520 return 1;
521 case '-':
522 case '\0':
523 return 0;
526 clause_count = inst->clause_count[inst->tagorder_count];
527 if (clause_count >= TAGCACHE_MAX_CLAUSES)
529 logf("Too many clauses");
530 return false;
533 inst->clause[inst->tagorder_count][clause_count] =
534 buffer_alloc(sizeof(struct tagcache_search_clause));
536 if (!read_clause(inst->clause[inst->tagorder_count][clause_count]))
537 return -1;
539 inst->clause_count[inst->tagorder_count]++;
541 return 1;
544 /* example search:
545 * "Best" artist ? year >= "2000" & title !^ "crap" & genre = "good genre" \
546 * : album ? year >= "2000" : songs
547 * ^ begins with
548 * * contains
549 * $ ends with
552 static bool parse_search(struct menu_entry *entry, const char *str)
554 int ret;
555 int type;
556 struct search_instruction *inst = entry->si;
557 char buf[MAX_PATH];
558 int i;
559 struct menu_root *new_menu;
561 strp = str;
563 /* Parse entry name */
564 if (get_token_str(entry->name, sizeof entry->name) < 0)
566 logf("No name found.");
567 return false;
570 /* Parse entry type */
571 if (get_tag(&entry->type) <= 0)
572 return false;
574 if (entry->type == menu_load)
576 if (get_token_str(buf, sizeof buf) < 0)
577 return false;
579 /* Find the matching root menu or "create" it */
580 for (i = 0; i < menu_count; i++)
582 if (!strcasecmp(menus[i]->id, buf))
584 entry->link = i;
585 return true;
589 if (menu_count >= TAGMENU_MAX_MENUS)
591 logf("max menucount reached");
592 return false;
595 /* Allocate a new menu unless link is found. */
596 menus[menu_count] = buffer_alloc(sizeof(struct menu_root));
597 new_menu = menus[menu_count];
598 memset(new_menu, 0, sizeof(struct menu_root));
599 strlcpy(new_menu->id, buf, MAX_MENU_ID_SIZE);
600 entry->link = menu_count;
601 ++menu_count;
603 return true;
606 if (entry->type != menu_next)
607 return false;
609 while (inst->tagorder_count < MAX_TAGS)
611 ret = get_tag(&inst->tagorder[inst->tagorder_count]);
612 if (ret < 0)
614 logf("Parse error #1");
615 logf("%s", strp);
616 return false;
619 if (ret == 0)
620 break ;
622 logf("tag: %d", inst->tagorder[inst->tagorder_count]);
624 while ( (ret = get_condition(inst)) > 0 ) ;
625 if (ret < 0)
626 return false;
628 inst->tagorder_count++;
630 if (get_tag(&type) <= 0 || type != menu_next)
631 break;
634 return true;
637 static int compare(const void *p1, const void *p2)
639 struct tagentry *e1 = (struct tagentry *)p1;
640 struct tagentry *e2 = (struct tagentry *)p2;
642 if (sort_inverse)
643 return strncasecmp(e2->name, e1->name, MAX_PATH);
645 return strncasecmp(e1->name, e2->name, MAX_PATH);
648 static void tagtree_buffer_event(void *data)
650 struct tagcache_search tcs;
651 struct mp3entry *id3 = (struct mp3entry*)data;
653 /* Do not gather data unless proper setting has been enabled. */
654 if (!global_settings.runtimedb && !global_settings.autoresume_enable)
655 return;
657 logf("be:%s", id3->path);
659 while (! tagcache_is_fully_initialized())
660 yield();
662 if (!tagcache_find_index(&tcs, id3->path))
664 logf("tc stat: not found: %s", id3->path);
665 return;
668 if (global_settings.runtimedb)
670 id3->playcount = tagcache_get_numeric(&tcs, tag_playcount);
671 if (!id3->rating)
672 id3->rating = tagcache_get_numeric(&tcs, tag_rating);
673 id3->lastplayed = tagcache_get_numeric(&tcs, tag_lastplayed);
674 id3->score = tagcache_get_numeric(&tcs, tag_virt_autoscore) / 10;
675 id3->playtime = tagcache_get_numeric(&tcs, tag_playtime);
677 logf("-> %ld/%ld", id3->playcount, id3->playtime);
680 #if CONFIG_CODEC == SWCODEC
681 if (global_settings.autoresume_enable)
683 /* Load current file resume offset if not already defined (by
684 another resume mechanism) */
685 if (id3->offset == 0)
687 id3->offset = tagcache_get_numeric(&tcs, tag_lastoffset);
689 logf("tagtree_buffer_event: Set offset for %s to %lX\n",
690 str_or_empty(id3->title), id3->offset);
693 #endif
695 /* Store our tagcache index pointer. */
696 id3->tagcache_idx = tcs.idx_id+1;
698 tagcache_search_finish(&tcs);
701 static void tagtree_track_finish_event(void *data)
703 long lastplayed;
704 long tagcache_idx;
705 struct mp3entry *id3 = (struct mp3entry*)data;
707 /* Do not gather data unless proper setting has been enabled. */
708 if (!global_settings.runtimedb && !global_settings.autoresume_enable)
710 logf("runtimedb gathering and autoresume not enabled");
711 return;
714 tagcache_idx=id3->tagcache_idx;
715 if (!tagcache_idx)
717 logf("No tagcache index pointer found");
718 return;
720 tagcache_idx--;
722 /* Don't process unplayed tracks, or tracks interrupted within the
723 first 15 seconds. */
724 if (id3->elapsed == 0
725 #if CONFIG_CODEC == SWCODEC /* HWCODEC doesn't have automatic_skip */
726 || (id3->elapsed < 15 * 1000 && !audio_automatic_skip())
727 #endif
730 logf("not logging unplayed or skipped track");
731 return;
734 lastplayed = tagcache_increase_serial();
735 if (lastplayed < 0)
737 logf("incorrect tc serial:%ld", lastplayed);
738 return;
741 if (global_settings.runtimedb)
743 long playcount;
744 long playtime;
746 playcount = id3->playcount + 1;
748 /* Ignore the last 15s (crossfade etc.) */
749 playtime = id3->playtime + MIN(id3->length, id3->elapsed + 15 * 1000);
751 logf("ube:%s", id3->path);
752 logf("-> %ld/%ld", playcount, playtime);
753 logf("-> %ld/%ld/%ld", id3->elapsed, id3->length,
754 MIN(id3->length, id3->elapsed + 15 * 1000));
756 /* Queue the updates to the tagcache system. */
757 tagcache_update_numeric(tagcache_idx, tag_playcount, playcount);
758 tagcache_update_numeric(tagcache_idx, tag_playtime, playtime);
759 tagcache_update_numeric(tagcache_idx, tag_lastplayed, lastplayed);
762 #if CONFIG_CODEC == SWCODEC
763 if (global_settings.autoresume_enable)
765 unsigned long offset
766 = audio_automatic_skip() ? 0 : id3->offset;
768 tagcache_update_numeric(tagcache_idx, tag_lastoffset, offset);
770 logf("tagtree_track_finish_event: Save offset for %s: %lX",
771 str_or_empty(id3->title), offset);
773 #endif
776 bool tagtree_export(void)
778 struct tagcache_search tcs;
780 splash(0, str(LANG_CREATING));
781 if (!tagcache_create_changelog(&tcs))
783 splash(HZ*2, ID2P(LANG_FAILED));
786 return false;
789 bool tagtree_import(void)
791 splash(0, ID2P(LANG_WAIT));
792 if (!tagcache_import_changelog())
794 splash(HZ*2, ID2P(LANG_FAILED));
797 return false;
800 static bool parse_menu(const char *filename);
802 static int parse_line(int n, const char *buf, void *parameters)
804 char data[256];
805 int variable;
806 static bool read_menu;
807 int i;
809 (void)parameters;
811 logf("parse:%d/%s", n, buf);
813 /* First line, do initialisation. */
814 if (n == 0)
816 if (strcasecmp(TAGNAVI_VERSION, buf))
818 logf("Version mismatch");
819 return -1;
822 read_menu = false;
825 if (buf[0] == '#')
826 return 0;
828 if (buf[0] == '\0')
830 if (read_menu)
832 /* End the menu */
833 read_menu = false;
835 return 0;
838 if (!read_menu)
840 strp = buf;
841 if (get_tag(&variable) <= 0)
842 return 0;
844 switch (variable)
846 case var_format:
847 if (add_format(strp) < 0)
849 logf("Format add fail: %s", data);
851 break;
853 case var_include:
854 if (get_token_str(data, sizeof(data)) < 0)
856 logf("%%include empty");
857 return 0;
860 if (!parse_menu(data))
862 logf("Load menu fail: %s", data);
864 break;
866 case var_menu_start:
867 if (menu_count >= TAGMENU_MAX_MENUS)
869 logf("max menucount reached");
870 return 0;
873 if (get_token_str(data, sizeof data) < 0)
875 logf("%%menu_start id empty");
876 return 0;
879 menu = NULL;
880 for (i = 0; i < menu_count; i++)
882 if (!strcasecmp(menus[i]->id, data))
884 menu = menus[i];
888 if (menu == NULL)
890 menus[menu_count] = buffer_alloc(sizeof(struct menu_root));
891 menu = menus[menu_count];
892 ++menu_count;
893 memset(menu, 0, sizeof(struct menu_root));
894 strlcpy(menu->id, data, MAX_MENU_ID_SIZE);
897 if (get_token_str(menu->title, sizeof(menu->title)) < 0)
899 logf("%%menu_start title empty");
900 return 0;
902 logf("menu: %s", menu->title);
903 read_menu = true;
904 break;
906 case var_rootmenu:
907 /* Only set root menu once. */
908 if (rootmenu >= 0)
909 break;
911 if (get_token_str(data, sizeof(data)) < 0)
913 logf("%%rootmenu empty");
914 return 0;
917 for (i = 0; i < menu_count; i++)
919 if (!strcasecmp(menus[i]->id, data))
921 rootmenu = i;
924 break;
927 return 0;
930 if (menu->itemcount >= TAGMENU_MAX_ITEMS)
932 logf("max itemcount reached");
933 return 0;
936 /* Allocate */
937 if (menu->items[menu->itemcount] == NULL)
939 menu->items[menu->itemcount] = buffer_alloc(sizeof(struct menu_entry));
940 memset(menu->items[menu->itemcount], 0, sizeof(struct menu_entry));
941 menu->items[menu->itemcount]->si = buffer_alloc(sizeof(struct search_instruction));
944 memset(menu->items[menu->itemcount]->si, 0, sizeof(struct search_instruction));
945 if (!parse_search(menu->items[menu->itemcount], buf))
946 return 0;
948 menu->itemcount++;
950 return 0;
953 static bool parse_menu(const char *filename)
955 int fd;
956 char buf[1024];
958 if (menu_count >= TAGMENU_MAX_MENUS)
960 logf("max menucount reached");
961 return false;
964 fd = open(filename, O_RDONLY);
965 if (fd < 0)
967 logf("Search instruction file not found.");
968 return false;
971 /* Now read file for real, parsing into si */
972 fast_readline(fd, buf, sizeof buf, NULL, parse_line);
973 close(fd);
975 return true;
978 void tagtree_init(void)
980 format_count = 0;
981 menu_count = 0;
982 menu = NULL;
983 rootmenu = -1;
984 parse_menu(FILE_SEARCH_INSTRUCTIONS);
986 /* If no root menu is set, assume it's the first single menu
987 * we have. That shouldn't normally happen. */
988 if (rootmenu < 0)
989 rootmenu = 0;
991 uniqbuf = buffer_alloc(UNIQBUF_SIZE);
993 add_event(PLAYBACK_EVENT_TRACK_BUFFER, false, tagtree_buffer_event);
994 add_event(PLAYBACK_EVENT_TRACK_FINISH, false, tagtree_track_finish_event);
997 static bool show_search_progress(bool init, int count)
999 static int last_tick = 0;
1001 /* Don't show splashes for 1/2 second after starting search */
1002 if (init)
1004 last_tick = current_tick + HZ/2;
1005 return true;
1008 /* Update progress every 1/10 of a second */
1009 if (TIME_AFTER(current_tick, last_tick + HZ/10))
1011 splashf(0, str(LANG_PLAYLIST_SEARCH_MSG), count, str(LANG_OFF_ABORT));
1012 if (action_userabort(TIMEOUT_NOBLOCK))
1013 return false;
1014 last_tick = current_tick;
1015 yield();
1018 return true;
1021 static int format_str(struct tagcache_search *tcs, struct display_format *fmt,
1022 char *buf, int buf_size)
1024 char fmtbuf[8];
1025 bool read_format = false;
1026 int fmtbuf_pos = 0;
1027 int parpos = 0;
1028 int buf_pos = 0;
1029 int i;
1031 memset(buf, 0, buf_size);
1032 for (i = 0; fmt->formatstr[i] != '\0'; i++)
1034 if (fmt->formatstr[i] == '%')
1036 read_format = true;
1037 fmtbuf_pos = 0;
1038 if (parpos >= fmt->tag_count)
1040 logf("too many format tags");
1041 return -1;
1045 if (read_format)
1047 fmtbuf[fmtbuf_pos++] = fmt->formatstr[i];
1048 if (fmtbuf_pos >= buf_size)
1050 logf("format parse error");
1051 return -2;
1054 if (fmt->formatstr[i] == 's')
1056 fmtbuf[fmtbuf_pos] = '\0';
1057 read_format = false;
1058 if (fmt->tags[parpos] == tcs->type)
1060 snprintf(&buf[buf_pos], buf_size - buf_pos, fmtbuf, tcs->result);
1062 else
1064 /* Need to fetch the tag data. */
1065 if (!tagcache_retrieve(tcs, tcs->idx_id, fmt->tags[parpos],
1066 &buf[buf_pos], buf_size - buf_pos))
1068 logf("retrieve failed");
1069 return -3;
1072 buf_pos += strlen(&buf[buf_pos]);
1073 parpos++;
1075 else if (fmt->formatstr[i] == 'd')
1077 fmtbuf[fmtbuf_pos] = '\0';
1078 read_format = false;
1079 snprintf(&buf[buf_pos], buf_size - buf_pos, fmtbuf,
1080 tagcache_get_numeric(tcs, fmt->tags[parpos]));
1081 buf_pos += strlen(&buf[buf_pos]);
1082 parpos++;
1084 continue;
1087 buf[buf_pos++] = fmt->formatstr[i];
1089 if (buf_pos - 1 >= buf_size)
1091 logf("buffer overflow");
1092 return -4;
1096 buf[buf_pos++] = '\0';
1098 return 0;
1101 static int retrieve_entries(struct tree_context *c, int offset, bool init)
1103 struct tagcache_search tcs;
1104 struct tagentry *dptr = (struct tagentry *)c->dircache;
1105 struct display_format *fmt;
1106 int i;
1107 int namebufused = 0;
1108 int total_count = 0;
1109 int special_entry_count = 0;
1110 int level = c->currextra;
1111 int tag;
1112 bool sort = false;
1113 int sort_limit;
1114 int strip;
1116 /* Show search progress straight away if the disk needs to spin up,
1117 otherwise show it after the normal 1/2 second delay */
1118 show_search_progress(
1119 #ifdef HAVE_DISK_STORAGE
1120 storage_disk_is_active()
1121 #else
1122 true
1123 #endif
1124 , 0);
1126 if (c->currtable == ALLSUBENTRIES)
1128 tag = tag_title;
1129 level--;
1131 else
1132 tag = csi->tagorder[level];
1134 if (!tagcache_search(&tcs, tag))
1135 return -1;
1137 /* Prevent duplicate entries in the search list. */
1138 tagcache_search_set_uniqbuf(&tcs, uniqbuf, UNIQBUF_SIZE);
1140 if (level || csi->clause_count[0] || TAGCACHE_IS_NUMERIC(tag))
1141 sort = true;
1143 for (i = 0; i < level; i++)
1145 if (TAGCACHE_IS_NUMERIC(csi->tagorder[i]))
1147 static struct tagcache_search_clause cc;
1149 memset(&cc, 0, sizeof(struct tagcache_search_clause));
1150 cc.tag = csi->tagorder[i];
1151 cc.type = clause_is;
1152 cc.numeric = true;
1153 cc.numeric_data = csi->result_seek[i];
1154 tagcache_search_add_clause(&tcs, &cc);
1156 else
1158 tagcache_search_add_filter(&tcs, csi->tagorder[i],
1159 csi->result_seek[i]);
1163 for (i = 0; i <= level; i++)
1165 int j;
1167 for (j = 0; j < csi->clause_count[i]; j++)
1168 tagcache_search_add_clause(&tcs, csi->clause[i][j]);
1171 current_offset = offset;
1172 current_entry_count = 0;
1173 c->dirfull = false;
1175 fmt = NULL;
1176 for (i = 0; i < format_count; i++)
1178 if (formats[i]->group_id == csi->format_id[level])
1179 fmt = formats[i];
1182 if (fmt)
1184 sort_inverse = fmt->sort_inverse;
1185 sort_limit = fmt->limit;
1186 strip = fmt->strip;
1187 sort = true;
1189 else
1191 sort_inverse = false;
1192 sort_limit = 0;
1193 strip = 0;
1196 if (tag != tag_title && tag != tag_filename)
1198 if (offset == 0)
1200 dptr->newtable = ALLSUBENTRIES;
1201 dptr->name = str(LANG_TAGNAVI_ALL_TRACKS);
1202 dptr++;
1203 current_entry_count++;
1205 if (offset <= 1)
1207 dptr->newtable = NAVIBROWSE;
1208 dptr->name = str(LANG_TAGNAVI_RANDOM);
1209 dptr->extraseek = -1;
1210 dptr++;
1211 current_entry_count++;
1213 special_entry_count+=2;
1216 total_count += special_entry_count;
1218 while (tagcache_get_next(&tcs))
1220 if (total_count++ < offset)
1221 continue;
1223 if ( strcmp(tcs.result , UNTAGGED ) == 0)
1225 tcs.result_len = strlcpy(tcs.result,
1226 str(LANG_TAGNAVI_UNTAGGED), TAG_MAXLEN )+1;
1229 dptr->newtable = NAVIBROWSE;
1230 if (tag == tag_title || tag == tag_filename)
1232 dptr->newtable = PLAYTRACK;
1233 dptr->extraseek = tcs.idx_id;
1235 else
1236 dptr->extraseek = tcs.result_seek;
1238 fmt = NULL;
1239 /* Check the format */
1240 for (i = 0; i < format_count; i++)
1242 if (formats[i]->group_id != csi->format_id[level])
1243 continue;
1245 if (tagcache_check_clauses(&tcs, formats[i]->clause,
1246 formats[i]->clause_count))
1248 fmt = formats[i];
1249 break;
1253 if (!tcs.ramresult || fmt)
1255 char buf[MAX_PATH];
1257 if (fmt)
1259 if (format_str(&tcs, fmt, buf, sizeof buf) < 0)
1261 logf("format_str() failed");
1262 tagcache_search_finish(&tcs);
1263 return 0;
1267 dptr->name = &c->name_buffer[namebufused];
1268 if (fmt)
1269 namebufused += strlen(buf)+1;
1270 else
1271 namebufused += tcs.result_len;
1273 if (namebufused >= c->name_buffer_size)
1275 logf("chunk mode #2: %d", current_entry_count);
1276 c->dirfull = true;
1277 sort = false;
1278 break ;
1280 if (fmt)
1281 strcpy(dptr->name, buf);
1282 else
1283 strcpy(dptr->name, tcs.result);
1285 else
1286 dptr->name = tcs.result;
1288 dptr++;
1289 current_entry_count++;
1291 if (current_entry_count >= global_settings.max_files_in_dir)
1293 logf("chunk mode #3: %d", current_entry_count);
1294 c->dirfull = true;
1295 sort = false;
1296 break ;
1299 if (init && !tcs.ramsearch)
1301 if (!show_search_progress(false, total_count))
1302 { /* user aborted */
1303 tagcache_search_finish(&tcs);
1304 return current_entry_count;
1309 if (sort)
1310 qsort(c->dircache + special_entry_count * c->dentry_size,
1311 current_entry_count - special_entry_count,
1312 c->dentry_size, compare);
1314 if (!init)
1316 tagcache_search_finish(&tcs);
1317 return current_entry_count;
1320 while (tagcache_get_next(&tcs))
1322 if (!tcs.ramsearch)
1324 if (!show_search_progress(false, total_count))
1325 break;
1327 total_count++;
1330 tagcache_search_finish(&tcs);
1332 if (!sort && (sort_inverse || sort_limit))
1334 splashf(HZ*4, ID2P(LANG_SHOWDIR_BUFFER_FULL), total_count);
1335 logf("Too small dir buffer");
1336 return 0;
1339 if (sort_limit)
1340 total_count = MIN(total_count, sort_limit);
1342 if (strip)
1344 dptr = c->dircache;
1345 for (i = 0; i < total_count; i++, dptr++)
1347 int len = strlen(dptr->name);
1349 if (len < strip)
1350 continue;
1352 dptr->name = &dptr->name[strip];
1356 return total_count;
1360 static int load_root(struct tree_context *c)
1362 struct tagentry *dptr = (struct tagentry *)c->dircache;
1363 int i;
1365 tc = c;
1366 c->currtable = ROOT;
1367 if (c->dirlevel == 0)
1368 c->currextra = rootmenu;
1370 menu = menus[c->currextra];
1371 if (menu == NULL)
1372 return 0;
1374 for (i = 0; i < menu->itemcount; i++)
1376 dptr->name = menu->items[i]->name;
1377 switch (menu->items[i]->type)
1379 case menu_next:
1380 dptr->newtable = NAVIBROWSE;
1381 dptr->extraseek = i;
1382 break;
1384 case menu_load:
1385 dptr->newtable = ROOT;
1386 dptr->extraseek = menu->items[i]->link;
1387 break;
1390 dptr++;
1393 current_offset = 0;
1394 current_entry_count = i;
1396 return i;
1399 int tagtree_load(struct tree_context* c)
1401 int count;
1402 int table = c->currtable;
1404 c->dentry_size = sizeof(struct tagentry);
1405 c->dirsindir = 0;
1407 if (!table)
1409 c->dirfull = false;
1410 table = ROOT;
1411 c->currtable = table;
1412 c->currextra = rootmenu;
1415 switch (table)
1417 case ROOT:
1418 count = load_root(c);
1419 break;
1421 case ALLSUBENTRIES:
1422 case NAVIBROWSE:
1423 logf("navibrowse...");
1424 cpu_boost(true);
1425 count = retrieve_entries(c, 0, true);
1426 cpu_boost(false);
1427 break;
1429 default:
1430 logf("Unsupported table %d\n", table);
1431 return -1;
1434 if (count < 0)
1436 c->dirlevel = 0;
1437 count = load_root(c);
1438 splash(HZ, str(LANG_TAGCACHE_BUSY));
1441 /* The _total_ numer of entries available. */
1442 c->dirlength = c->filesindir = count;
1444 return count;
1447 int tagtree_enter(struct tree_context* c)
1449 int rc = 0;
1450 struct tagentry *dptr;
1451 struct mp3entry *id3;
1452 int newextra;
1453 int seek;
1454 int source;
1456 dptr = tagtree_get_entry(c, c->selected_item);
1458 c->dirfull = false;
1459 seek = dptr->extraseek;
1460 if (seek == -1)
1462 if(c->filesindir<=2)
1463 return 0;
1464 srand(current_tick);
1465 dptr = (tagtree_get_entry(c, 2+(rand() % (c->filesindir-2))));
1466 seek = dptr->extraseek;
1468 newextra = dptr->newtable;
1470 if (c->dirlevel >= MAX_DIR_LEVELS)
1471 return 0;
1473 c->selected_item_history[c->dirlevel]=c->selected_item;
1474 c->table_history[c->dirlevel] = c->currtable;
1475 c->extra_history[c->dirlevel] = c->currextra;
1476 c->pos_history[c->dirlevel] = c->firstpos;
1477 c->dirlevel++;
1479 switch (c->currtable) {
1480 case ROOT:
1481 c->currextra = newextra;
1483 if (newextra == ROOT)
1485 menu = menus[seek];
1486 c->currextra = seek;
1489 else if (newextra == NAVIBROWSE)
1491 int i, j;
1493 csi = menu->items[seek]->si;
1494 c->currextra = 0;
1496 strlcpy(current_title[c->currextra], dptr->name,
1497 sizeof(current_title[0]));
1499 /* Read input as necessary. */
1500 for (i = 0; i < csi->tagorder_count; i++)
1502 for (j = 0; j < csi->clause_count[i]; j++)
1504 char* searchstring;
1505 source = csi->clause[i][j]->source;
1507 if (source == source_constant)
1508 continue;
1510 searchstring=csi->clause[i][j]->str;
1511 *searchstring = '\0';
1513 id3 = audio_current_track();
1515 if (source == source_current_path && id3)
1517 char *e;
1518 strlcpy(searchstring, id3->path, SEARCHSTR_SIZE);
1519 e = strrchr(searchstring, '/');
1520 if (e)
1521 *e = '\0';
1523 else if (source > source_runtime && id3)
1526 int k = source-source_runtime;
1527 int offset = id3_to_search_mapping[k].id3_offset;
1528 char **src = (char**)((char*)id3 + offset);
1529 if (*src)
1531 strlcpy(searchstring, *src, SEARCHSTR_SIZE);
1534 else
1536 rc = kbd_input(searchstring, SEARCHSTR_SIZE);
1537 if (rc < 0 || !searchstring[0])
1539 tagtree_exit(c);
1540 return 0;
1542 if (csi->clause[i][j]->numeric)
1543 csi->clause[i][j]->numeric_data = atoi(searchstring);
1550 c->currtable = newextra;
1552 break;
1554 case NAVIBROWSE:
1555 case ALLSUBENTRIES:
1556 if (newextra == PLAYTRACK)
1558 if (global_settings.party_mode && audio_status()) {
1559 splash(HZ, ID2P(LANG_PARTY_MODE));
1560 break;
1562 c->dirlevel--;
1563 /* about to create a new current playlist...
1564 allow user to cancel the operation */
1565 if (!warn_on_pl_erase())
1566 break;
1567 if (tagtree_play_folder(c) >= 0)
1568 rc = 2;
1569 break;
1572 c->currtable = newextra;
1573 csi->result_seek[c->currextra] = seek;
1574 if (c->currextra < csi->tagorder_count-1)
1575 c->currextra++;
1576 else
1577 c->dirlevel--;
1579 /* Update the statusbar title */
1580 strlcpy(current_title[c->currextra], dptr->name,
1581 sizeof(current_title[0]));
1582 break;
1584 default:
1585 c->dirlevel--;
1586 break;
1589 c->selected_item=0;
1590 gui_synclist_select_item(&tree_lists, c->selected_item);
1592 return rc;
1595 void tagtree_exit(struct tree_context* c)
1597 c->dirfull = false;
1598 if (c->dirlevel > 0)
1599 c->dirlevel--;
1600 c->selected_item=c->selected_item_history[c->dirlevel];
1601 gui_synclist_select_item(&tree_lists, c->selected_item);
1602 c->currtable = c->table_history[c->dirlevel];
1603 c->currextra = c->extra_history[c->dirlevel];
1604 c->firstpos = c->pos_history[c->dirlevel];
1607 int tagtree_get_filename(struct tree_context* c, char *buf, int buflen)
1609 struct tagcache_search tcs;
1610 struct tagentry *entry;
1612 entry = tagtree_get_entry(c, c->selected_item);
1614 if (!tagcache_search(&tcs, tag_filename))
1615 return -1;
1617 if (!tagcache_retrieve(&tcs, entry->extraseek, tcs.type, buf, buflen))
1619 tagcache_search_finish(&tcs);
1620 return -2;
1623 tagcache_search_finish(&tcs);
1625 return 0;
1628 static bool insert_all_playlist(struct tree_context *c, int position, bool queue)
1630 struct tagcache_search tcs;
1631 int i;
1632 char buf[MAX_PATH];
1633 int from, to, direction;
1634 int files_left = c->filesindir;
1636 cpu_boost(true);
1637 if (!tagcache_search(&tcs, tag_filename))
1639 splash(HZ, ID2P(LANG_TAGCACHE_BUSY));
1640 cpu_boost(false);
1641 return false;
1644 if (position == PLAYLIST_REPLACE)
1646 if (playlist_remove_all_tracks(NULL) == 0)
1647 position = PLAYLIST_INSERT_LAST;
1648 else
1650 cpu_boost(false);
1651 return false;
1655 if (position == PLAYLIST_INSERT_FIRST)
1657 from = c->filesindir - 1;
1658 to = -1;
1659 direction = -1;
1661 else
1663 from = 0;
1664 to = c->filesindir;
1665 direction = 1;
1668 for (i = from; i != to; i += direction)
1670 /* Count back to zero */
1671 if (!show_search_progress(false, files_left--))
1672 break;
1674 if (!tagcache_retrieve(&tcs, tagtree_get_entry(c, i)->extraseek,
1675 tcs.type, buf, sizeof buf))
1677 continue;
1680 if (playlist_insert_track(NULL, buf, position, queue, false) < 0)
1682 logf("playlist_insert_track failed");
1683 break;
1685 yield();
1687 playlist_sync(NULL);
1688 tagcache_search_finish(&tcs);
1689 cpu_boost(false);
1691 return true;
1694 bool tagtree_insert_selection_playlist(int position, bool queue)
1696 struct tagentry *dptr;
1697 char buf[MAX_PATH];
1698 int dirlevel = tc->dirlevel;
1700 show_search_progress(
1701 #ifdef HAVE_DISK_STORAGE
1702 storage_disk_is_active()
1703 #else
1704 true
1705 #endif
1706 , 0);
1709 /* We need to set the table to allsubentries. */
1710 dptr = tagtree_get_entry(tc, tc->selected_item);
1712 /* Insert a single track? */
1713 if (dptr->newtable == PLAYTRACK)
1715 if (tagtree_get_filename(tc, buf, sizeof buf) < 0)
1717 logf("tagtree_get_filename failed");
1718 return false;
1720 playlist_insert_track(NULL, buf, position, queue, true);
1722 return true;
1725 if (dptr->newtable == NAVIBROWSE)
1727 tagtree_enter(tc);
1728 tagtree_load(tc);
1729 dptr = tagtree_get_entry(tc, tc->selected_item);
1731 else if (dptr->newtable != ALLSUBENTRIES)
1733 logf("unsupported table: %d", dptr->newtable);
1734 return false;
1737 /* Now the current table should be allsubentries. */
1738 if (dptr->newtable != PLAYTRACK)
1740 tagtree_enter(tc);
1741 tagtree_load(tc);
1742 dptr = tagtree_get_entry(tc, tc->selected_item);
1744 /* And now the newtable should be playtrack. */
1745 if (dptr->newtable != PLAYTRACK)
1747 logf("newtable: %d !!", dptr->newtable);
1748 tc->dirlevel = dirlevel;
1749 return false;
1753 if (tc->filesindir <= 0)
1754 splash(HZ, ID2P(LANG_END_PLAYLIST));
1755 else
1757 logf("insert_all_playlist");
1758 if (!insert_all_playlist(tc, position, queue))
1759 splash(HZ*2, ID2P(LANG_FAILED));
1762 /* Finally return the dirlevel to its original value. */
1763 while (tc->dirlevel > dirlevel)
1764 tagtree_exit(tc);
1765 tagtree_load(tc);
1767 return true;
1770 static int tagtree_play_folder(struct tree_context* c)
1772 if (playlist_create(NULL, NULL) < 0)
1774 logf("Failed creating playlist\n");
1775 return -1;
1778 if (!insert_all_playlist(c, PLAYLIST_INSERT_LAST, false))
1779 return -2;
1781 if (global_settings.playlist_shuffle)
1782 c->selected_item = playlist_shuffle(current_tick, c->selected_item);
1783 if (!global_settings.play_selected)
1784 c->selected_item = 0;
1785 gui_synclist_select_item(&tree_lists, c->selected_item);
1787 playlist_start(c->selected_item,0);
1788 playlist_get_current()->num_inserted_tracks = 0; /* make warn on playlist erase work */
1789 return 0;
1792 struct tagentry* tagtree_get_entry(struct tree_context *c, int id)
1794 struct tagentry *entry = (struct tagentry *)c->dircache;
1795 int realid = id - current_offset;
1797 /* Load the next chunk if necessary. */
1798 if (realid >= current_entry_count || realid < 0)
1800 cpu_boost(true);
1801 if (retrieve_entries(c, MAX(0, id - (current_entry_count / 2)),
1802 false) < 0)
1804 logf("retrieve failed");
1805 cpu_boost(false);
1806 return NULL;
1808 realid = id - current_offset;
1809 cpu_boost(false);
1812 return &entry[realid];
1815 char *tagtree_get_title(struct tree_context* c)
1817 switch (c->currtable)
1819 case ROOT:
1820 return menu->title;
1822 case NAVIBROWSE:
1823 case ALLSUBENTRIES:
1824 return current_title[c->currextra];
1827 return "?";
1830 int tagtree_get_attr(struct tree_context* c)
1832 int attr = -1;
1833 switch (c->currtable)
1835 case NAVIBROWSE:
1836 if (csi->tagorder[c->currextra] == tag_title)
1837 attr = FILE_ATTR_AUDIO;
1838 else
1839 attr = ATTR_DIRECTORY;
1840 break;
1842 case ALLSUBENTRIES:
1843 attr = FILE_ATTR_AUDIO;
1844 break;
1846 default:
1847 attr = ATTR_DIRECTORY;
1848 break;
1851 return attr;
1854 int tagtree_get_icon(struct tree_context* c)
1856 int icon = Icon_Folder;
1858 if (tagtree_get_attr(c) == FILE_ATTR_AUDIO)
1859 icon = Icon_Audio;
1861 return icon;