summaryrefslogtreecommitdiff
path: root/nephilim/plugins/Library.py
blob: 50079ada94974e434ac79e0aa23ccda18f0e55ba (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
#
#    Copyright (C) 2009 Anton Khirnov <wyskas@gmail.com>
#
#    Nephilim 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 3 of the License, or
#    (at your option) any later version.
#
#    Nephilim 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 Nephilim.  If not, see <http://www.gnu.org/licenses/>.
#

from PyQt4 import QtGui, QtCore
from PyQt4.QtCore import QVariant

from ..plugin import Plugin

class Library(Plugin):
    # public, const
    info = 'Display MPD database as a tree.'

    # public, read-only
    o         = None

    # private
    DEFAULTS  = {'grouping' : QtCore.QStringList(['albumartist', 'album'])}

    def _load(self):
        self.o = LibraryWidget(self)
    def _unload(self):
        self.o = None

    def _get_dock_widget(self):
        return self._create_dock(self.o)

    def fill_library(self):
        if not self.o:
            return
        self.o.fill_library()

    class SettingsWidgetLibrary(Plugin.SettingsWidget):
        taglist = None
        def __init__(self, plugin):
            Plugin.SettingsWidget.__init__(self, plugin)
            self.settings.beginGroup(self.plugin.name)

            tags_enabled = self.settings.value('grouping').toStringList()
            tags         = self.plugin.mpclient.tagtypes()
            self.taglist = QtGui.QListWidget(self)
            self.taglist.setDragDropMode(QtGui.QAbstractItemView.InternalMove)
            for tag in [tag for tag in tags_enabled if tag in tags]:
                it = QtGui.QListWidgetItem(tag)
                it.setCheckState(QtCore.Qt.Checked)
                self.taglist.addItem(it)
            for tag in [tag for tag in tags if tag not in tags_enabled]:
                it = QtGui.QListWidgetItem(tag)
                it.setCheckState(QtCore.Qt.Unchecked)
                self.taglist.addItem(it)

            self.setLayout(QtGui.QVBoxLayout())
            self._add_widget(self.taglist, label = 'Group', tooltip = 'Checked items and their order determines,\n'
                                      'by what tags will songs be grouped in Library. Use drag and drop to change the\n'
                                      'order of tags.')

            self.settings.endGroup()

        def save_settings(self):
            self.settings.beginGroup(self.plugin.name)

            tags = QtCore.QStringList()
            for i in range(self.taglist.count()):
                it = self.taglist.item(i)
                if it.checkState() == QtCore.Qt.Checked:
                    tags.append(it.text())
            self.settings.setValue('grouping', QtCore.QVariant(tags))

            self.settings.endGroup()
            self.plugin.fill_library()

    def get_settings_widget(self):
        return self.SettingsWidgetLibrary(self)

class LibraryWidget(QtGui.QWidget):
    library_view   = None
    library_model  = None
    search_txt     = None
    grouping       = None
    settings       = None
    plugin         = None
    logger         = None
    filtered_items = None
    filter         = None

    class LibrarySongItem(QtGui.QStandardItem):
        # public
        "Song path"
        path    = None

    class LibraryModel(QtGui.QStandardItemModel):
        def fill(self, songs, grouping):
            self.clear()

            tree = [{},self.invisibleRootItem()]
            for song in songs:
                cur_item = tree
                for part in grouping:
                    tag = song[part]
                    if not tag:
                        tag = 'Unknown'
                    if tag in cur_item[0]:
                        cur_item = cur_item[0][tag]
                    else:
                        it = QtGui.QStandardItem(tag)
                        it.setFlags(QtCore.Qt.ItemIsSelectable|QtCore.Qt.ItemIsEnabled)
                        cur_item[1].appendRow(it)
                        cur_item[0][tag] = [{}, it]
                        cur_item = cur_item[0][tag]
                it = LibraryWidget.LibrarySongItem('%s%02d %s'%(song['disc'] + '/' if 'disc' in song else '',
                                         song['tracknum'], song['title']))
                it.path = song['file']
                it.setFlags(QtCore.Qt.ItemIsSelectable|QtCore.Qt.ItemIsEnabled)
                cur_item[1].appendRow(it)

            self.sort(0, QtCore.Qt.AscendingOrder)

    class LibraryView(QtGui.QTreeView):
        def __init__(self):
            QtGui.QTreeView.__init__(self)

            self.setAlternatingRowColors(True)
            self.setSelectionMode(QtGui.QAbstractItemView.ExtendedSelection)
            self.setUniformRowHeights(True)
            self.setHeaderHidden(True)

        def selectedItems(self):
            ret = []
            for index in self.selectedIndexes():
                ret.append(self.model().itemFromIndex(index))

            return ret

    def __init__(self, plugin):
        QtGui.QWidget.__init__(self)
        self.plugin         = plugin
        self.logger         = plugin.logger
        self.settings       = QtCore.QSettings()
        self.filter         = QtCore.QString()
        self.filtered_items = []
        self.settings.beginGroup(self.plugin.name)

        self.grouping = QtGui.QLabel()

        self.search_txt = QtGui.QLineEdit()
        self.search_txt.setToolTip('Filter library')
        self.search_txt.textChanged.connect(self.filter_library)
        self.search_txt.returnPressed.connect(self.add_filtered)

        #construct the library
        self.library_model = self.LibraryModel()
        self.fill_library()

        self.library_view  = self.LibraryView()
        self.library_view.setModel(self.library_model)
        self.library_view.activated.connect(self.add_selection)

        self.setLayout(QtGui.QVBoxLayout())
        self.layout().setSpacing(2)
        self.layout().setMargin(0)
        self.layout().addWidget(self.grouping)
        self.layout().addWidget(self.search_txt)
        self.layout().addWidget(self.library_view)

        self.plugin.mpclient.connect_changed.connect(self.fill_library)
        self.plugin.mpclient.db_updated.connect(self.fill_library)

    def fill_library(self):
        self.logger.info('Refreshing library.')
        self.grouping.setText(self.settings.value('grouping').toStringList().join('/'))
        self.library_model.fill(self.plugin.mpclient.library(), self.settings.value('grouping').toStringList())

    @QtCore.pyqtSlot(QtCore.QString)
    def filter_library(self, text):
        """Hide all items that don't contain text."""
        to_hide        = []
        to_show        = []
        filtered_items = []
        if not text:    # show all items
            to_show = self.library_model.findItems('*', QtCore.Qt.MatchWildcard|QtCore.Qt.MatchRecursive)
        elif self.filter and text.contains(self.filter, QtCore.Qt.CaseInsensitive):
            for item in self.filtered_items:
                if item.text().contains(text, QtCore.Qt.CaseInsensitive):
                    filtered_items.append(item)
                    while item:
                        to_show.append(item)
                        item = item.parent()
                else:
                    while item:
                        to_hide.append(item)
                        item = item.parent()
        else:
            for item in self.library_model.findItems('*', QtCore.Qt.MatchWildcard|QtCore.Qt.MatchRecursive):
                if item.text().contains(text, QtCore.Qt.CaseInsensitive):
                    filtered_items.append(item)
                    while item:
                        to_show.append(item)
                        item = item.parent()
                else:
                    while item:
                        to_hide.append(item)
                        item = item.parent()
        for item in to_hide:
            self.library_view.setRowHidden(item.row(), self.library_model.indexFromItem(item.parent()), True)
        for item in to_show:
            self.library_view.setRowHidden(item.row(), self.library_model.indexFromItem(item.parent()), False)

        if len(filtered_items) < 5:
            for item in filtered_items:
                while item:
                    item = item.parent()
                    self.library_view.setExpanded(self.library_model.indexFromItem(item), True)

        self.filtered_items = filtered_items
        self.filter         = text

    def add_filtered(self):
        self.add_items(self.filtered_items)
        self.search_txt.clear()

    def add_selection(self):
        self.add_items(self.library_view.selectedItems())

    def add_items(self, items):
        paths = []
        for item in items:
            self.item_to_playlist(item, paths)
        self.plugin.mpclient.add(paths)

    def item_to_playlist(self, item, add_queue):
        if isinstance(item, self.LibrarySongItem):
            add_queue.append(item.path)
        else:
            for i in range(item.rowCount()):
                self.item_to_playlist(item.child(i), add_queue)