clean up some debugging output.
[kugel-rb.git] / apps / tagtree.c
blobef4591fe0448b798d5e2ff2e1cbc054ef2de017d
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.
26 #include <stdio.h>
27 #include <string.h>
28 #include <stdlib.h>
29 #include "config.h"
30 #include "system.h"
31 #include "kernel.h"
32 #include "splash.h"
33 #include "icons.h"
34 #include "tree.h"
35 #include "action.h"
36 #include "settings.h"
37 #include "tagcache.h"
38 #include "tagtree.h"
39 #include "lang.h"
40 #include "logf.h"
41 #include "playlist.h"
42 #include "keyboard.h"
43 #include "gui/list.h"
44 #include "buffer.h"
45 #include "playback.h"
46 #include "yesno.h"
47 #include "misc.h"
48 #include "filetypes.h"
49 #include "audio.h"
50 #include "events.h"
52 #define FILE_SEARCH_INSTRUCTIONS ROCKBOX_DIR "/tagnavi.config"
54 static int tagtree_play_folder(struct tree_context* c);
56 #define SEARCHSTR_SIZE 256
58 static const struct id3_to_search_mapping {
59 char *string;
60 size_t id3_offset;
61 } id3_to_search_mapping[] = {
62 { "", 0 }, /* offset n/a */
63 { "#directory#", 0 }, /* offset n/a */
64 { "#title#", offsetof(struct mp3entry, title) },
65 { "#artist#", offsetof(struct mp3entry, artist) },
66 { "#album#", offsetof(struct mp3entry, album) },
67 { "#genre#", offsetof(struct mp3entry, genre_string) },
68 { "#composer#", offsetof(struct mp3entry, composer) },
69 { "#albumartist#", offsetof(struct mp3entry, albumartist) },
71 enum variables {
72 var_sorttype = 100,
73 var_limit,
74 var_strip,
75 var_menu_start,
76 var_include,
77 var_rootmenu,
78 var_format,
79 menu_next,
80 menu_load,
83 /* Capacity 10 000 entries (for example 10k different artists) */
84 #define UNIQBUF_SIZE (64*1024)
85 static long *uniqbuf;
87 #define MAX_TAGS 5
88 #define MAX_MENU_ID_SIZE 32
90 static struct tagcache_search tcs, tcs2;
91 static bool sort_inverse;
94 * "%3d. %s" autoscore title %sort = "inverse" %limit = "100"
96 * valid = true
97 * formatstr = "%-3d. %s"
98 * tags[0] = tag_autoscore
99 * tags[1] = tag_title
100 * tag_count = 2
102 * limit = 100
103 * sort_inverse = true
105 struct display_format {
106 char name[32];
107 struct tagcache_search_clause *clause[TAGCACHE_MAX_CLAUSES];
108 int clause_count;
109 char *formatstr;
110 int group_id;
111 int tags[MAX_TAGS];
112 int tag_count;
114 int limit;
115 int strip;
116 bool sort_inverse;
117 bool sort;
120 static struct display_format *formats[TAGMENU_MAX_FMTS];
121 static int format_count;
123 struct search_instruction {
124 char name[64];
125 int tagorder[MAX_TAGS];
126 int tagorder_count;
127 struct tagcache_search_clause *clause[MAX_TAGS][TAGCACHE_MAX_CLAUSES];
128 int format_id[MAX_TAGS];
129 int clause_count[MAX_TAGS];
130 int result_seek[MAX_TAGS];
133 struct menu_entry {
134 char name[64];
135 int type;
136 struct search_instruction *si;
137 int link;
140 struct root_menu {
141 char title[64];
142 char id[MAX_MENU_ID_SIZE];
143 int itemcount;
144 struct menu_entry *items[TAGMENU_MAX_ITEMS];
147 /* Statusbar text of the current view. */
148 static char current_title[MAX_TAGS][128];
150 static struct root_menu *menus[TAGMENU_MAX_MENUS];
151 static struct root_menu *menu;
152 static struct search_instruction *csi;
153 static const char *strp;
154 static int menu_count;
155 static int root_menu;
157 static int current_offset;
158 static int current_entry_count;
160 static int format_count;
161 static struct tree_context *tc;
163 static int get_token_str(char *buf, int size)
165 /* Find the start. */
166 while (*strp != '"' && *strp != '\0')
167 strp++;
169 if (*strp == '\0' || *(++strp) == '\0')
170 return -1;
172 /* Read the data. */
173 while (*strp != '"' && *strp != '\0' && --size > 0)
174 *(buf++) = *(strp++);
176 *buf = '\0';
177 if (*strp != '"')
178 return -2;
180 strp++;
182 return 0;
185 #define MATCH(tag,str1,str2,settag) \
186 if (!strcasecmp(str1, str2)) { \
187 *tag = settag; \
188 return 1; \
191 static int get_tag(int *tag)
193 char buf[128];
194 int i;
196 /* Find the start. */
197 while ((*strp == ' ' || *strp == '>') && *strp != '\0')
198 strp++;
200 if (*strp == '\0' || *strp == '?')
201 return 0;
203 for (i = 0; i < (int)sizeof(buf)-1; i++)
205 if (*strp == '\0' || *strp == ' ')
206 break ;
207 buf[i] = *strp;
208 strp++;
210 buf[i] = '\0';
212 MATCH(tag, buf, "album", tag_album);
213 MATCH(tag, buf, "artist", tag_artist);
214 MATCH(tag, buf, "bitrate", tag_bitrate);
215 MATCH(tag, buf, "composer", tag_composer);
216 MATCH(tag, buf, "comment", tag_comment);
217 MATCH(tag, buf, "albumartist", tag_albumartist);
218 MATCH(tag, buf, "ensemble", tag_albumartist);
219 MATCH(tag, buf, "grouping", tag_grouping);
220 MATCH(tag, buf, "genre", tag_genre);
221 MATCH(tag, buf, "length", tag_length);
222 MATCH(tag, buf, "Lm", tag_virt_length_min);
223 MATCH(tag, buf, "Ls", tag_virt_length_sec);
224 MATCH(tag, buf, "Pm", tag_virt_playtime_min);
225 MATCH(tag, buf, "Ps", tag_virt_playtime_sec);
226 MATCH(tag, buf, "title", tag_title);
227 MATCH(tag, buf, "filename", tag_filename);
228 MATCH(tag, buf, "tracknum", tag_tracknumber);
229 MATCH(tag, buf, "discnum", tag_discnumber);
230 MATCH(tag, buf, "year", tag_year);
231 MATCH(tag, buf, "playcount", tag_playcount);
232 MATCH(tag, buf, "rating", tag_rating);
233 MATCH(tag, buf, "lastplayed", tag_lastplayed);
234 MATCH(tag, buf, "commitid", tag_commitid);
235 MATCH(tag, buf, "entryage", tag_virt_entryage);
236 MATCH(tag, buf, "autoscore", tag_virt_autoscore);
237 MATCH(tag, buf, "%sort", var_sorttype);
238 MATCH(tag, buf, "%limit", var_limit);
239 MATCH(tag, buf, "%strip", var_strip);
240 MATCH(tag, buf, "%menu_start", var_menu_start);
241 MATCH(tag, buf, "%include", var_include);
242 MATCH(tag, buf, "%root_menu", var_rootmenu);
243 MATCH(tag, buf, "%format", var_format);
244 MATCH(tag, buf, "->", menu_next);
245 MATCH(tag, buf, "==>", menu_load);
247 logf("NO MATCH: %s\n", buf);
248 if (buf[0] == '?')
249 return 0;
251 return -1;
254 static int get_clause(int *condition)
256 char buf[4];
257 int i;
259 /* Find the start. */
260 while (*strp == ' ' && *strp != '\0')
261 strp++;
263 if (*strp == '\0')
264 return 0;
266 for (i = 0; i < (int)sizeof(buf)-1; i++)
268 if (*strp == '\0' || *strp == ' ')
269 break ;
270 buf[i] = *strp;
271 strp++;
273 buf[i] = '\0';
275 MATCH(condition, buf, "=", clause_is);
276 MATCH(condition, buf, "==", clause_is);
277 MATCH(condition, buf, "!=", clause_is_not);
278 MATCH(condition, buf, ">", clause_gt);
279 MATCH(condition, buf, ">=", clause_gteq);
280 MATCH(condition, buf, "<", clause_lt);
281 MATCH(condition, buf, "<=", clause_lteq);
282 MATCH(condition, buf, "~", clause_contains);
283 MATCH(condition, buf, "!~", clause_not_contains);
284 MATCH(condition, buf, "^", clause_begins_with);
285 MATCH(condition, buf, "!^", clause_not_begins_with);
286 MATCH(condition, buf, "$", clause_ends_with);
287 MATCH(condition, buf, "!$", clause_not_ends_with);
288 MATCH(condition, buf, "@", clause_oneof);
290 return 0;
293 static bool read_clause(struct tagcache_search_clause *clause)
295 char buf[SEARCHSTR_SIZE];
296 unsigned int i;
298 if (get_tag(&clause->tag) <= 0)
299 return false;
301 if (get_clause(&clause->type) <= 0)
302 return false;
304 if (get_token_str(buf, sizeof buf) < 0)
305 return false;
307 for (i=0; i<ARRAYLEN(id3_to_search_mapping); i++)
309 if (!strcasecmp(buf, id3_to_search_mapping[i].string))
310 break;
313 if (i<ARRAYLEN(id3_to_search_mapping)) /* runtime search operand found */
315 clause->source = source_runtime+i;
316 clause->str = buffer_alloc(SEARCHSTR_SIZE);
318 else
320 clause->source = source_constant;
321 clause->str = buffer_alloc(strlen(buf)+1);
322 strcpy(clause->str, buf);
325 if (tagcache_is_numeric_tag(clause->tag))
327 clause->numeric = true;
328 clause->numeric_data = atoi(clause->str);
330 else
331 clause->numeric = false;
333 logf("got clause: %d/%d [%s]", clause->tag, clause->type, clause->str);
335 return true;
338 static bool read_variable(char *buf, int size)
340 int condition;
342 if (!get_clause(&condition))
343 return false;
345 if (condition != clause_is)
346 return false;
348 if (get_token_str(buf, size) < 0)
349 return false;
351 return true;
354 /* "%3d. %s" autoscore title %sort = "inverse" %limit = "100" */
355 static int get_format_str(struct display_format *fmt)
357 int ret;
358 char buf[128];
359 int i;
361 memset(fmt, 0, sizeof(struct display_format));
363 if (get_token_str(fmt->name, sizeof fmt->name) < 0)
364 return -10;
366 /* Determine the group id */
367 fmt->group_id = 0;
368 for (i = 0; i < format_count; i++)
370 if (!strcasecmp(formats[i]->name, fmt->name))
372 fmt->group_id = formats[i]->group_id;
373 break;
376 if (formats[i]->group_id > fmt->group_id)
377 fmt->group_id = formats[i]->group_id;
380 if (i == format_count)
381 fmt->group_id++;
383 logf("format: (%d) %s", fmt->group_id, fmt->name);
385 if (get_token_str(buf, sizeof buf) < 0)
386 return -10;
388 fmt->formatstr = buffer_alloc(strlen(buf) + 1);
389 strcpy(fmt->formatstr, buf);
391 while (fmt->tag_count < MAX_TAGS)
393 ret = get_tag(&fmt->tags[fmt->tag_count]);
394 if (ret < 0)
395 return -11;
397 if (ret == 0)
398 break;
400 switch (fmt->tags[fmt->tag_count]) {
401 case var_sorttype:
402 if (!read_variable(buf, sizeof buf))
403 return -12;
404 if (!strcasecmp("inverse", buf))
405 fmt->sort_inverse = true;
407 fmt->sort = true;
408 break;
410 case var_limit:
411 if (!read_variable(buf, sizeof buf))
412 return -13;
413 fmt->limit = atoi(buf);
414 break;
416 case var_strip:
417 if (!read_variable(buf, sizeof buf))
418 return -14;
419 fmt->strip = atoi(buf);
420 break;
422 default:
423 fmt->tag_count++;
427 return 1;
430 static int add_format(const char *buf)
432 strp = buf;
434 if (formats[format_count] == NULL)
435 formats[format_count] = buffer_alloc(sizeof(struct display_format));
437 memset(formats[format_count], 0, sizeof(struct display_format));
438 if (get_format_str(formats[format_count]) < 0)
440 logf("get_format_str() parser failed!");
441 return -4;
444 while (*strp != '\0' && *strp != '?')
445 strp++;
447 if (*strp == '?')
449 int clause_count = 0;
450 strp++;
452 while (1)
454 if (clause_count >= TAGCACHE_MAX_CLAUSES)
456 logf("too many clauses");
457 break;
460 formats[format_count]->clause[clause_count] =
461 buffer_alloc(sizeof(struct tagcache_search_clause));
463 if (!read_clause(formats[format_count]->clause[clause_count]))
464 break;
466 clause_count++;
469 formats[format_count]->clause_count = clause_count;
472 format_count++;
474 return 1;
477 static int get_condition(struct search_instruction *inst)
479 int clause_count;
480 char buf[128];
482 switch (*strp)
484 case '=':
486 int i;
488 if (get_token_str(buf, sizeof buf) < 0)
489 return -1;
491 for (i = 0; i < format_count; i++)
493 if (!strcasecmp(formats[i]->name, buf))
494 break;
497 if (i == format_count)
499 logf("format not found: %s", buf);
500 return -2;
503 inst->format_id[inst->tagorder_count] = formats[i]->group_id;
504 return 1;
506 case '?':
507 case ' ':
508 case '&':
509 strp++;
510 return 1;
511 case '-':
512 case '\0':
513 return 0;
516 clause_count = inst->clause_count[inst->tagorder_count];
517 if (clause_count >= TAGCACHE_MAX_CLAUSES)
519 logf("Too many clauses");
520 return false;
523 inst->clause[inst->tagorder_count][clause_count] =
524 buffer_alloc(sizeof(struct tagcache_search_clause));
526 if (!read_clause(inst->clause[inst->tagorder_count][clause_count]))
527 return -1;
529 inst->clause_count[inst->tagorder_count]++;
531 return 1;
534 /* example search:
535 * "Best" artist ? year >= "2000" & title !^ "crap" & genre = "good genre" \
536 * : album ? year >= "2000" : songs
537 * ^ begins with
538 * * contains
539 * $ ends with
542 static bool parse_search(struct menu_entry *entry, const char *str)
544 int ret;
545 int type;
546 struct search_instruction *inst = entry->si;
547 char buf[MAX_PATH];
548 int i;
549 struct root_menu *new_menu;
551 strp = str;
553 /* Parse entry name */
554 if (get_token_str(entry->name, sizeof entry->name) < 0)
556 logf("No name found.");
557 return false;
560 /* Parse entry type */
561 if (get_tag(&entry->type) <= 0)
562 return false;
564 if (entry->type == menu_load)
566 if (get_token_str(buf, sizeof buf) < 0)
567 return false;
569 /* Find the matching root menu or "create" it */
570 for (i = 0; i < menu_count; i++)
572 if (!strcasecmp(menus[i]->id, buf))
574 entry->link = i;
575 return true;
579 if (menu_count >= TAGMENU_MAX_MENUS)
581 logf("max menucount reached");
582 return false;
585 /* Allocate a new menu unless link is found. */
586 menus[menu_count] = buffer_alloc(sizeof(struct root_menu));
587 new_menu = menus[menu_count];
588 memset(new_menu, 0, sizeof(struct root_menu));
589 strncpy(new_menu->id, buf, MAX_MENU_ID_SIZE-1);
590 entry->link = menu_count;
591 ++menu_count;
593 return true;
596 if (entry->type != menu_next)
597 return false;
599 while (inst->tagorder_count < MAX_TAGS)
601 ret = get_tag(&inst->tagorder[inst->tagorder_count]);
602 if (ret < 0)
604 logf("Parse error #1");
605 logf("%s", strp);
606 return false;
609 if (ret == 0)
610 break ;
612 logf("tag: %d", inst->tagorder[inst->tagorder_count]);
614 while ( (ret = get_condition(inst)) > 0 ) ;
615 if (ret < 0)
616 return false;
618 inst->tagorder_count++;
620 if (get_tag(&type) <= 0 || type != menu_next)
621 break;
624 return true;
627 static int compare(const void *p1, const void *p2)
629 struct tagentry *e1 = (struct tagentry *)p1;
630 struct tagentry *e2 = (struct tagentry *)p2;
632 if (sort_inverse)
633 return strncasecmp(e2->name, e1->name, MAX_PATH);
635 return strncasecmp(e1->name, e2->name, MAX_PATH);
638 static void tagtree_buffer_event(struct mp3entry *id3)
640 /* Do not gather data unless proper setting has been enabled. */
641 if (!global_settings.runtimedb)
642 return;
644 logf("be:%s", id3->path);
646 if (!tagcache_find_index(&tcs, id3->path))
648 logf("tc stat: not found: %s", id3->path);
649 return;
652 id3->playcount = tagcache_get_numeric(&tcs, tag_playcount);
653 if (!id3->rating)
654 id3->rating = tagcache_get_numeric(&tcs, tag_rating);
655 id3->lastplayed = tagcache_get_numeric(&tcs, tag_lastplayed);
656 id3->score = tagcache_get_numeric(&tcs, tag_virt_autoscore) / 10;
657 id3->playtime = tagcache_get_numeric(&tcs, tag_playtime);
659 /* Store our tagcache index pointer. */
660 id3->tagcache_idx = tcs.idx_id+1;
662 tagcache_search_finish(&tcs);
665 static void tagtree_track_finish_event(struct mp3entry *id3)
667 long playcount;
668 long playtime;
669 long lastplayed;
670 long tagcache_idx;
672 /* Do not gather data unless proper setting has been enabled. */
673 if (!global_settings.runtimedb)
675 logf("runtimedb gathering not enabled");
676 return;
679 tagcache_idx=id3->tagcache_idx;
680 if (!tagcache_idx)
682 logf("No tagcache index pointer found");
683 return;
685 tagcache_idx--;
687 /* Don't process unplayed tracks. */
688 if (id3->elapsed == 0)
690 logf("not logging unplayed track");
691 return;
694 playcount = id3->playcount + 1;
695 lastplayed = tagcache_increase_serial();
696 if (lastplayed < 0)
698 logf("incorrect tc serial:%ld", lastplayed);
699 return;
702 /* Ignore the last 15s (crossfade etc.) */
703 playtime = id3->playtime + MIN(id3->length, id3->elapsed + 15 * 1000);
705 logf("ube:%s", id3->path);
706 logf("-> %ld/%ld", playcount, playtime);
707 logf("-> %ld/%ld/%ld", id3->elapsed, id3->length, MIN(id3->length, id3->elapsed + 15 * 1000));
709 /* Queue the updates to the tagcache system. */
710 tagcache_update_numeric(tagcache_idx, tag_playcount, playcount);
711 tagcache_update_numeric(tagcache_idx, tag_playtime, playtime);
712 tagcache_update_numeric(tagcache_idx, tag_lastplayed, lastplayed);
715 bool tagtree_export(void)
717 gui_syncsplash(0, str(LANG_CREATING));
718 if (!tagcache_create_changelog(&tcs))
720 gui_syncsplash(HZ*2, ID2P(LANG_FAILED));
723 return false;
726 bool tagtree_import(void)
728 gui_syncsplash(0, ID2P(LANG_WAIT));
729 if (!tagcache_import_changelog())
731 gui_syncsplash(HZ*2, ID2P(LANG_FAILED));
734 return false;
737 static bool parse_menu(const char *filename);
739 static int parse_line(int n, const char *buf, void *parameters)
741 char data[256];
742 int variable;
743 static bool read_menu;
744 int i;
746 (void)parameters;
748 logf("parse:%d/%s", n, buf);
750 /* First line, do initialisation. */
751 if (n == 0)
753 if (strcasecmp(TAGNAVI_VERSION, buf))
755 logf("Version mismatch");
756 return -1;
759 read_menu = false;
762 if (buf[0] == '#')
763 return 0;
765 if (buf[0] == '\0')
767 if (read_menu)
769 /* End the menu */
770 read_menu = false;
772 return 0;
775 if (!read_menu)
777 strp = buf;
778 if (get_tag(&variable) <= 0)
779 return 0;
781 switch (variable)
783 case var_format:
784 if (add_format(strp) < 0)
786 logf("Format add fail: %s", data);
788 break;
790 case var_include:
791 if (get_token_str(data, sizeof(data)) < 0)
793 logf("%%include empty");
794 return 0;
797 if (!parse_menu(data))
799 logf("Load menu fail: %s", data);
801 break;
803 case var_menu_start:
804 if (menu_count >= TAGMENU_MAX_MENUS)
806 logf("max menucount reached");
807 return 0;
810 if (get_token_str(data, sizeof data) < 0)
812 logf("%%menu_start id empty");
813 return 0;
816 menu = NULL;
817 for (i = 0; i < menu_count; i++)
819 if (!strcasecmp(menus[i]->id, data))
821 menu = menus[i];
825 if (menu == NULL)
827 menus[menu_count] = buffer_alloc(sizeof(struct root_menu));
828 menu = menus[menu_count];
829 ++menu_count;
830 memset(menu, 0, sizeof(struct root_menu));
831 strncpy(menu->id, data, MAX_MENU_ID_SIZE-1);
834 if (get_token_str(menu->title, sizeof(menu->title)) < 0)
836 logf("%%menu_start title empty");
837 return 0;
839 logf("menu: %s", menu->title);
840 read_menu = true;
841 break;
843 case var_rootmenu:
844 /* Only set root menu once. */
845 if (root_menu >= 0)
846 break;
848 if (get_token_str(data, sizeof(data)) < 0)
850 logf("%%root_menu empty");
851 return 0;
854 for (i = 0; i < menu_count; i++)
856 if (!strcasecmp(menus[i]->id, data))
858 root_menu = i;
861 break;
864 return 0;
867 if (menu->itemcount >= TAGMENU_MAX_ITEMS)
869 logf("max itemcount reached");
870 return 0;
873 /* Allocate */
874 if (menu->items[menu->itemcount] == NULL)
876 menu->items[menu->itemcount] = buffer_alloc(sizeof(struct menu_entry));
877 memset(menu->items[menu->itemcount], 0, sizeof(struct menu_entry));
878 menu->items[menu->itemcount]->si = buffer_alloc(sizeof(struct search_instruction));
881 memset(menu->items[menu->itemcount]->si, 0, sizeof(struct search_instruction));
882 if (!parse_search(menu->items[menu->itemcount], buf))
883 return 0;
885 menu->itemcount++;
887 return 0;
890 static bool parse_menu(const char *filename)
892 int fd;
893 char buf[1024];
895 if (menu_count >= TAGMENU_MAX_MENUS)
897 logf("max menucount reached");
898 return false;
901 fd = open(filename, O_RDONLY);
902 if (fd < 0)
904 logf("Search instruction file not found.");
905 return false;
908 /* Now read file for real, parsing into si */
909 fast_readline(fd, buf, sizeof buf, NULL, parse_line);
910 close(fd);
912 return true;
915 void tagtree_init(void)
917 format_count = 0;
918 menu_count = 0;
919 menu = NULL;
920 root_menu = -1;
921 parse_menu(FILE_SEARCH_INSTRUCTIONS);
923 /* If no root menu is set, assume it's the first single menu
924 * we have. That shouldn't normally happen. */
925 if (root_menu < 0)
926 root_menu = 0;
928 uniqbuf = buffer_alloc(UNIQBUF_SIZE);
930 add_event(PLAYBACK_EVENT_TRACK_BUFFER, false, tagtree_buffer_event);
931 add_event(PLAYBACK_EVENT_TRACK_FINISH, false, tagtree_track_finish_event);
934 static bool show_search_progress(bool init, int count)
936 static int last_tick = 0;
938 /* Don't show splashes for 1/2 second after starting search */
939 if (init)
941 last_tick = current_tick + HZ/2;
942 return true;
945 /* Update progress every 1/10 of a second */
946 if (current_tick - last_tick > HZ/10)
948 gui_syncsplash(0, str(LANG_PLAYLIST_SEARCH_MSG), count,
949 str(LANG_OFF_ABORT));
950 if (action_userabort(TIMEOUT_NOBLOCK))
951 return false;
952 last_tick = current_tick;
953 yield();
956 return true;
959 static int format_str(struct tagcache_search *tcs, struct display_format *fmt,
960 char *buf, int buf_size)
962 char fmtbuf[8];
963 bool read_format = false;
964 int fmtbuf_pos = 0;
965 int parpos = 0;
966 int buf_pos = 0;
967 int i;
969 memset(buf, 0, buf_size);
970 for (i = 0; fmt->formatstr[i] != '\0'; i++)
972 if (fmt->formatstr[i] == '%')
974 read_format = true;
975 fmtbuf_pos = 0;
976 if (parpos >= fmt->tag_count)
978 logf("too many format tags");
979 return -1;
983 if (read_format)
985 fmtbuf[fmtbuf_pos++] = fmt->formatstr[i];
986 if (fmtbuf_pos >= buf_size)
988 logf("format parse error");
989 return -2;
992 if (fmt->formatstr[i] == 's')
994 fmtbuf[fmtbuf_pos] = '\0';
995 read_format = false;
996 if (fmt->tags[parpos] == tcs->type)
998 snprintf(&buf[buf_pos], buf_size - buf_pos, fmtbuf, tcs->result);
1000 else
1002 /* Need to fetch the tag data. */
1003 if (!tagcache_retrieve(tcs, tcs->idx_id, fmt->tags[parpos],
1004 &buf[buf_pos], buf_size - buf_pos))
1006 logf("retrieve failed");
1007 return -3;
1010 buf_pos += strlen(&buf[buf_pos]);
1011 parpos++;
1013 else if (fmt->formatstr[i] == 'd')
1015 fmtbuf[fmtbuf_pos] = '\0';
1016 read_format = false;
1017 snprintf(&buf[buf_pos], buf_size - buf_pos, fmtbuf,
1018 tagcache_get_numeric(tcs, fmt->tags[parpos]));
1019 buf_pos += strlen(&buf[buf_pos]);
1020 parpos++;
1022 continue;
1025 buf[buf_pos++] = fmt->formatstr[i];
1027 if (buf_pos - 1 >= buf_size)
1029 logf("buffer overflow");
1030 return -4;
1034 buf[buf_pos++] = '\0';
1036 return 0;
1039 static int retrieve_entries(struct tree_context *c, struct tagcache_search *tcs,
1040 int offset, bool init)
1042 struct tagentry *dptr = (struct tagentry *)c->dircache;
1043 struct display_format *fmt;
1044 int i;
1045 int namebufused = 0;
1046 int total_count = 0;
1047 int special_entry_count = 0;
1048 int level = c->currextra;
1049 int tag;
1050 bool sort = false;
1051 int sort_limit;
1052 int strip;
1054 if (init
1055 #ifdef HAVE_TC_RAMCACHE
1056 && !tagcache_is_ramcache()
1057 #endif
1060 /* Show search progress straight away if the disk needs to spin up,
1061 otherwise show it after the normal 1/2 second delay */
1062 show_search_progress(
1063 #if !defined(HAVE_FLASH_STORAGE) && !defined(SIMULATOR)
1064 ata_disk_is_active()
1065 #else
1066 true
1067 #endif
1068 , 0);
1071 if (c->currtable == allsubentries)
1073 tag = tag_title;
1074 level--;
1076 else
1077 tag = csi->tagorder[level];
1079 if (!tagcache_search(tcs, tag))
1080 return -1;
1082 /* Prevent duplicate entries in the search list. */
1083 tagcache_search_set_uniqbuf(tcs, uniqbuf, UNIQBUF_SIZE);
1085 if (level || csi->clause_count[0] || tagcache_is_numeric_tag(tag))
1086 sort = true;
1088 for (i = 0; i < level; i++)
1090 if (tagcache_is_numeric_tag(csi->tagorder[i]))
1092 static struct tagcache_search_clause cc;
1094 memset(&cc, 0, sizeof(struct tagcache_search_clause));
1095 cc.tag = csi->tagorder[i];
1096 cc.type = clause_is;
1097 cc.numeric = true;
1098 cc.numeric_data = csi->result_seek[i];
1099 tagcache_search_add_clause(tcs, &cc);
1101 else
1103 tagcache_search_add_filter(tcs, csi->tagorder[i],
1104 csi->result_seek[i]);
1108 for (i = 0; i <= level; i++)
1110 int j;
1112 for (j = 0; j < csi->clause_count[i]; j++)
1113 tagcache_search_add_clause(tcs, csi->clause[i][j]);
1116 current_offset = offset;
1117 current_entry_count = 0;
1118 c->dirfull = false;
1120 fmt = NULL;
1121 for (i = 0; i < format_count; i++)
1123 if (formats[i]->group_id == csi->format_id[level])
1124 fmt = formats[i];
1127 if (fmt)
1129 sort_inverse = fmt->sort_inverse;
1130 sort_limit = fmt->limit;
1131 strip = fmt->strip;
1133 /* Check if sorting is forced. */
1134 if (fmt->sort)
1135 sort = true;
1137 else
1139 sort_inverse = false;
1140 sort_limit = 0;
1141 strip = 0;
1144 if (tag != tag_title && tag != tag_filename)
1146 if (offset == 0)
1148 dptr->newtable = allsubentries;
1149 dptr->name = str(LANG_TAGNAVI_ALL_TRACKS);
1150 dptr++;
1151 current_entry_count++;
1153 if (offset <= 1)
1155 dptr->newtable = navibrowse;
1156 dptr->name = str(LANG_TAGNAVI_RANDOM);
1157 dptr->extraseek = -1;
1158 dptr++;
1159 current_entry_count++;
1161 special_entry_count+=2;
1164 total_count += special_entry_count;
1166 while (tagcache_get_next(tcs))
1168 if (total_count++ < offset)
1169 continue;
1171 dptr->newtable = navibrowse;
1172 if (tag == tag_title || tag == tag_filename)
1174 dptr->newtable = playtrack;
1175 dptr->extraseek = tcs->idx_id;
1177 else
1178 dptr->extraseek = tcs->result_seek;
1180 fmt = NULL;
1181 /* Check the format */
1182 for (i = 0; i < format_count; i++)
1184 if (formats[i]->group_id != csi->format_id[level])
1185 continue;
1187 if (tagcache_check_clauses(tcs, formats[i]->clause,
1188 formats[i]->clause_count))
1190 fmt = formats[i];
1191 break;
1195 if (!tcs->ramresult || fmt)
1197 char buf[MAX_PATH];
1199 if (fmt)
1201 if (format_str(tcs, fmt, buf, sizeof buf) < 0)
1203 logf("format_str() failed");
1204 return 0;
1208 dptr->name = &c->name_buffer[namebufused];
1209 if (fmt)
1210 namebufused += strlen(buf)+1;
1211 else
1212 namebufused += tcs->result_len;
1214 if (namebufused >= c->name_buffer_size)
1216 logf("chunk mode #2: %d", current_entry_count);
1217 c->dirfull = true;
1218 sort = false;
1219 break ;
1221 if (fmt)
1222 strcpy(dptr->name, buf);
1223 else
1224 strcpy(dptr->name, tcs->result);
1226 else
1227 dptr->name = tcs->result;
1229 dptr++;
1230 current_entry_count++;
1232 if (current_entry_count >= global_settings.max_files_in_dir)
1234 logf("chunk mode #3: %d", current_entry_count);
1235 c->dirfull = true;
1236 sort = false;
1237 break ;
1240 if (init && !tcs->ramsearch)
1242 if (!show_search_progress(false, total_count))
1244 tagcache_search_finish(tcs);
1245 return current_entry_count;
1250 if (sort)
1251 qsort(c->dircache + special_entry_count * c->dentry_size,
1252 current_entry_count - special_entry_count,
1253 c->dentry_size, compare);
1255 if (!init)
1257 tagcache_search_finish(tcs);
1258 return current_entry_count;
1261 while (tagcache_get_next(tcs))
1263 if (!tcs->ramsearch)
1265 if (!show_search_progress(false, total_count))
1266 break;
1268 total_count++;
1271 tagcache_search_finish(tcs);
1273 if (!sort && (sort_inverse || sort_limit))
1275 gui_syncsplash(HZ*4, ID2P(LANG_SHOWDIR_BUFFER_FULL), total_count);
1276 logf("Too small dir buffer");
1277 return 0;
1280 if (sort_limit)
1281 total_count = MIN(total_count, sort_limit);
1283 if (strip)
1285 dptr = c->dircache;
1286 for (i = 0; i < total_count; i++, dptr++)
1288 int len = strlen(dptr->name);
1290 if (len < strip)
1291 continue;
1293 dptr->name = &dptr->name[strip];
1297 return total_count;
1300 static int load_root(struct tree_context *c)
1302 struct tagentry *dptr = (struct tagentry *)c->dircache;
1303 int i;
1305 tc = c;
1306 c->currtable = root;
1307 if (c->dirlevel == 0)
1308 c->currextra = root_menu;
1310 menu = menus[c->currextra];
1311 if (menu == NULL)
1312 return 0;
1314 for (i = 0; i < menu->itemcount; i++)
1316 dptr->name = menu->items[i]->name;
1317 switch (menu->items[i]->type)
1319 case menu_next:
1320 dptr->newtable = navibrowse;
1321 dptr->extraseek = i;
1322 break;
1324 case menu_load:
1325 dptr->newtable = root;
1326 dptr->extraseek = menu->items[i]->link;
1327 break;
1330 dptr++;
1333 current_offset = 0;
1334 current_entry_count = i;
1336 return i;
1339 int tagtree_load(struct tree_context* c)
1341 int count;
1342 int table = c->currtable;
1344 c->dentry_size = sizeof(struct tagentry);
1345 c->dirsindir = 0;
1347 if (!table)
1349 c->dirfull = false;
1350 table = root;
1351 c->currtable = table;
1352 c->currextra = root_menu;
1355 switch (table)
1357 case root:
1358 count = load_root(c);
1359 break;
1361 case allsubentries:
1362 case navibrowse:
1363 logf("navibrowse...");
1364 cpu_boost(true);
1365 count = retrieve_entries(c, &tcs, 0, true);
1366 cpu_boost(false);
1367 break;
1369 default:
1370 logf("Unsupported table %d\n", table);
1371 return -1;
1374 if (count < 0)
1376 c->dirlevel = 0;
1377 count = load_root(c);
1378 gui_syncsplash(HZ, str(LANG_TAGCACHE_BUSY));
1381 /* The _total_ numer of entries available. */
1382 c->dirlength = c->filesindir = count;
1384 return count;
1387 int tagtree_enter(struct tree_context* c)
1389 int rc = 0;
1390 struct tagentry *dptr;
1391 struct mp3entry *id3;
1392 int newextra;
1393 int seek;
1394 int source;
1396 dptr = tagtree_get_entry(c, c->selected_item);
1398 c->dirfull = false;
1399 seek = dptr->extraseek;
1400 if (seek == -1)
1402 if(c->filesindir<=2)
1403 return 0;
1404 srand(current_tick);
1405 dptr = (tagtree_get_entry(c, 2+(rand() % (c->filesindir-2))));
1406 seek = dptr->extraseek;
1408 newextra = dptr->newtable;
1410 if (c->dirlevel >= MAX_DIR_LEVELS)
1411 return 0;
1413 c->selected_item_history[c->dirlevel]=c->selected_item;
1414 c->table_history[c->dirlevel] = c->currtable;
1415 c->extra_history[c->dirlevel] = c->currextra;
1416 c->pos_history[c->dirlevel] = c->firstpos;
1417 c->dirlevel++;
1419 switch (c->currtable) {
1420 case root:
1421 c->currextra = newextra;
1423 if (newextra == root)
1425 menu = menus[seek];
1426 c->currextra = seek;
1429 else if (newextra == navibrowse)
1431 int i, j;
1433 csi = menu->items[seek]->si;
1434 c->currextra = 0;
1436 strncpy(current_title[c->currextra], dptr->name,
1437 sizeof(current_title[0]) - 1);
1439 /* Read input as necessary. */
1440 for (i = 0; i < csi->tagorder_count; i++)
1442 for (j = 0; j < csi->clause_count[i]; j++)
1444 char* searchstring;
1445 source = csi->clause[i][j]->source;
1447 if (source == source_constant)
1448 continue;
1450 searchstring=csi->clause[i][j]->str;
1451 *searchstring = '\0';
1453 id3 = audio_current_track();
1455 if (source == source_current_path && id3)
1457 char *e;
1458 strncpy(searchstring, id3->path, SEARCHSTR_SIZE);
1459 e = strrchr(searchstring, '/');
1460 if (e)
1461 *e = '\0';
1463 else if (source > source_runtime && id3)
1466 int k = source-source_runtime;
1467 int offset = id3_to_search_mapping[k].id3_offset;
1468 char **src = (char**)((char*)id3 + offset);
1469 if (*src)
1471 strncpy(searchstring, *src, SEARCHSTR_SIZE);
1472 searchstring[SEARCHSTR_SIZE-1] = '\0';
1475 else
1477 rc = kbd_input(searchstring, SEARCHSTR_SIZE);
1478 if (rc == -1 || !searchstring[0])
1480 tagtree_exit(c);
1481 return 0;
1483 if (csi->clause[i][j]->numeric)
1484 csi->clause[i][j]->numeric_data = atoi(searchstring);
1491 c->currtable = newextra;
1493 break;
1495 case navibrowse:
1496 case allsubentries:
1497 if (newextra == playtrack)
1499 c->dirlevel--;
1500 /* about to create a new current playlist...
1501 allow user to cancel the operation */
1502 if (!warn_on_pl_erase())
1503 break;
1505 if (tagtree_play_folder(c) >= 0)
1506 rc = 2;
1507 break;
1510 c->currtable = newextra;
1511 csi->result_seek[c->currextra] = seek;
1512 if (c->currextra < csi->tagorder_count-1)
1513 c->currextra++;
1514 else
1515 c->dirlevel--;
1517 /* Update the statusbar title */
1518 strncpy(current_title[c->currextra], dptr->name,
1519 sizeof(current_title[0]) - 1);
1520 break;
1522 default:
1523 c->dirlevel--;
1524 break;
1527 c->selected_item=0;
1528 gui_synclist_select_item(&tree_lists, c->selected_item);
1530 return rc;
1533 void tagtree_exit(struct tree_context* c)
1535 c->dirfull = false;
1536 if (c->dirlevel > 0)
1537 c->dirlevel--;
1538 c->selected_item=c->selected_item_history[c->dirlevel];
1539 gui_synclist_select_item(&tree_lists, c->selected_item);
1540 c->currtable = c->table_history[c->dirlevel];
1541 c->currextra = c->extra_history[c->dirlevel];
1542 c->firstpos = c->pos_history[c->dirlevel];
1545 int tagtree_get_filename(struct tree_context* c, char *buf, int buflen)
1547 struct tagentry *entry;
1549 entry = tagtree_get_entry(c, c->selected_item);
1551 if (!tagcache_search(&tcs, tag_filename))
1552 return -1;
1554 if (!tagcache_retrieve(&tcs, entry->extraseek, tcs.type, buf, buflen))
1556 tagcache_search_finish(&tcs);
1557 return -2;
1560 tagcache_search_finish(&tcs);
1562 return 0;
1565 static bool insert_all_playlist(struct tree_context *c, int position, bool queue)
1567 int i;
1568 char buf[MAX_PATH];
1569 int from, to, direction;
1570 int files_left = c->filesindir;
1572 cpu_boost(true);
1573 if (!tagcache_search(&tcs, tag_filename))
1575 gui_syncsplash(HZ, ID2P(LANG_TAGCACHE_BUSY));
1576 cpu_boost(false);
1577 return false;
1580 if (position == PLAYLIST_REPLACE)
1582 if (playlist_remove_all_tracks(NULL) == 0)
1583 position = PLAYLIST_INSERT_LAST;
1584 else
1586 cpu_boost(false);
1587 return false;
1591 if (position == PLAYLIST_INSERT_FIRST)
1593 from = c->filesindir - 1;
1594 to = -1;
1595 direction = -1;
1597 else
1599 from = 0;
1600 to = c->filesindir;
1601 direction = 1;
1604 for (i = from; i != to; i += direction)
1606 /* Count back to zero */
1607 if (!show_search_progress(false, files_left--))
1608 break;
1610 if (!tagcache_retrieve(&tcs, tagtree_get_entry(c, i)->extraseek,
1611 tcs.type, buf, sizeof buf))
1613 continue;
1616 if (playlist_insert_track(NULL, buf, position, queue, false) < 0)
1618 logf("playlist_insert_track failed");
1619 break;
1621 yield();
1623 playlist_sync(NULL);
1624 tagcache_search_finish(&tcs);
1625 cpu_boost(false);
1627 return true;
1630 bool tagtree_insert_selection_playlist(int position, bool queue)
1632 struct tagentry *dptr;
1633 char buf[MAX_PATH];
1634 int dirlevel = tc->dirlevel;
1636 /* We need to set the table to allsubentries. */
1637 show_search_progress(true, 0);
1639 dptr = tagtree_get_entry(tc, tc->selected_item);
1641 /* Insert a single track? */
1642 if (dptr->newtable == playtrack)
1644 if (tagtree_get_filename(tc, buf, sizeof buf) < 0)
1646 logf("tagtree_get_filename failed");
1647 return false;
1649 playlist_insert_track(NULL, buf, position, queue, true);
1651 return true;
1654 if (dptr->newtable == navibrowse)
1656 tagtree_enter(tc);
1657 tagtree_load(tc);
1658 dptr = tagtree_get_entry(tc, tc->selected_item);
1660 else if (dptr->newtable != allsubentries)
1662 logf("unsupported table: %d", dptr->newtable);
1663 return false;
1666 /* Now the current table should be allsubentries. */
1667 if (dptr->newtable != playtrack)
1669 tagtree_enter(tc);
1670 tagtree_load(tc);
1671 dptr = tagtree_get_entry(tc, tc->selected_item);
1673 /* And now the newtable should be playtrack. */
1674 if (dptr->newtable != playtrack)
1676 logf("newtable: %d !!", dptr->newtable);
1677 tc->dirlevel = dirlevel;
1678 return false;
1682 if (tc->filesindir <= 0)
1683 gui_syncsplash(HZ, ID2P(LANG_END_PLAYLIST));
1684 else
1686 logf("insert_all_playlist");
1687 if (!insert_all_playlist(tc, position, queue))
1688 gui_syncsplash(HZ*2, ID2P(LANG_FAILED));
1691 /* Finally return the dirlevel to its original value. */
1692 while (tc->dirlevel > dirlevel)
1693 tagtree_exit(tc);
1694 tagtree_load(tc);
1696 return true;
1699 static int tagtree_play_folder(struct tree_context* c)
1701 if (playlist_create(NULL, NULL) < 0)
1703 logf("Failed creating playlist\n");
1704 return -1;
1707 if (!insert_all_playlist(c, PLAYLIST_INSERT_LAST, false))
1708 return -2;
1710 if (global_settings.playlist_shuffle)
1711 c->selected_item = playlist_shuffle(current_tick, c->selected_item);
1712 if (!global_settings.play_selected)
1713 c->selected_item = 0;
1714 gui_synclist_select_item(&tree_lists, c->selected_item);
1716 playlist_start(c->selected_item,0);
1718 return 0;
1721 struct tagentry* tagtree_get_entry(struct tree_context *c, int id)
1723 struct tagentry *entry = (struct tagentry *)c->dircache;
1724 int realid = id - current_offset;
1726 /* Load the next chunk if necessary. */
1727 if (realid >= current_entry_count || realid < 0)
1729 cpu_boost(true);
1730 if (retrieve_entries(c, &tcs2, MAX(0, id - (current_entry_count / 2)),
1731 false) < 0)
1733 logf("retrieve failed");
1734 cpu_boost(false);
1735 return NULL;
1737 realid = id - current_offset;
1738 cpu_boost(false);
1741 return &entry[realid];
1744 char *tagtree_get_title(struct tree_context* c)
1746 switch (c->currtable)
1748 case root:
1749 return menu->title;
1751 case navibrowse:
1752 case allsubentries:
1753 return current_title[c->currextra];
1756 return "?";
1759 int tagtree_get_attr(struct tree_context* c)
1761 int attr = -1;
1762 switch (c->currtable)
1764 case navibrowse:
1765 if (csi->tagorder[c->currextra] == tag_title)
1766 attr = FILE_ATTR_AUDIO;
1767 else
1768 attr = ATTR_DIRECTORY;
1769 break;
1771 case allsubentries:
1772 attr = FILE_ATTR_AUDIO;
1773 break;
1775 default:
1776 attr = ATTR_DIRECTORY;
1777 break;
1780 return attr;
1783 int tagtree_get_icon(struct tree_context* c)
1785 int icon = Icon_Folder;
1787 if (tagtree_get_attr(c) == FILE_ATTR_AUDIO)
1788 icon = Icon_Audio;
1790 return icon;