SongSort.cxx 2.5 KB
Newer Older
1
/*
Max Kellermann's avatar
Max Kellermann committed
2
 * Copyright 2003-2017 The Music Player Daemon Project
3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
 * http://www.musicpd.org
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, write to the Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
 */

20
#include "config.h"
21
#include "SongSort.hxx"
22
#include "Song.hxx"
23
#include "tag/Tag.hxx"
24
#include "lib/icu/Collate.hxx"
25 26

#include <stdlib.h>
27

28 29 30
static int
compare_utf8_string(const char *a, const char *b)
{
31 32
	if (a == nullptr)
		return b == nullptr ? 0 : -1;
33

34
	if (b == nullptr)
35 36
		return 1;

37
	return IcuCollate(a, b);
38 39 40 41
}

/**
 * Compare two string tag values, ignoring case.  Either one may be
42
 * nullptr.
43 44
 */
static int
45
compare_string_tag_item(const Tag &a, const Tag &b,
46
			TagType type)
47
{
48 49
	return compare_utf8_string(a.GetValue(type),
				   b.GetValue(type));
50 51
}

52 53
/**
 * Compare two tag values which should contain an integer value
54
 * (e.g. disc or track number).  Either one may be nullptr.
55 56 57 58
 */
static int
compare_number_string(const char *a, const char *b)
{
59 60
	long ai = a == nullptr ? 0 : strtol(a, nullptr, 10);
	long bi = b == nullptr ? 0 : strtol(b, nullptr, 10);
61 62 63 64 65 66 67 68 69 70 71

	if (ai <= 0)
		return bi <= 0 ? 0 : -1;

	if (bi <= 0)
		return 1;

	return ai - bi;
}

static int
72
compare_tag_item(const Tag &a, const Tag &b, TagType type)
73
{
74 75
	return compare_number_string(a.GetValue(type),
				     b.GetValue(type));
76 77
}

78
/* Only used for sorting/searchin a songvec, not general purpose compares */
79 80 81
gcc_pure
static bool
song_cmp(const Song &a, const Song &b)
82
{
83 84
	int ret;

85
	/* first sort by album */
86
	ret = compare_string_tag_item(a.tag, b.tag, TAG_ALBUM);
87
	if (ret != 0)
88
		return ret < 0;
89 90

	/* then sort by disc */
91
	ret = compare_tag_item(a.tag, b.tag, TAG_DISC);
92
	if (ret != 0)
93
		return ret < 0;
94 95

	/* then by track number */
96
	ret = compare_tag_item(a.tag, b.tag, TAG_TRACK);
97
	if (ret != 0)
98
		return ret < 0;
99 100

	/* still no difference?  compare file name */
101
	return IcuCollate(a.uri, b.uri) < 0;
102 103
}

104
void
105
song_list_sort(SongList &songs)
106
{
107
	songs.sort(song_cmp);
108
}