summaryrefslogtreecommitdiff
path: root/nephilim/plugins/Library.py
blob: 50f85a34c7e5cb943377adf4d1f7082037d55460 (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
#
#    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
    DEFAULTS  = {'modes' : QtCore.QStringList(['artist',
                           'artist/album',
                           'artist/date/album',
                           'genre',
                           'genre/artist',
                           'genre/artist/album'])}

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

    def getInfo(self):
        return "List showing all the songs allowing filtering and grouping."

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

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

    class SettingsWidgetLibrary(Plugin.SettingsWidget):
        modes = None
        def __init__(self, plugin):
            Plugin.SettingsWidget.__init__(self, plugin)
            self.setLayout(QtGui.QVBoxLayout())

            self.modes = QtGui.QComboBox()
            self.modes.setEditable(True)
            for mode in self.settings.value(self.plugin.name + '/modes').toStringList():
                self.modes.addItem(mode)
            self._add_widget(self.modes, 'Modes', 'How should the songs in library be grouped.\n'
                                                  'Should be written in form tag1/tag2/...,\n'
                                                  'using tags supported by MPD.')

        def save_settings(self):
            modes = QtCore.QStringList()
            for i in range(0, self.modes.count()):
                modes.append(self.modes.itemText(i))
            self.settings.setValue(self.plugin.name + '/modes', QVariant(modes))
            self.plugin.o.refresh_modes()

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


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

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

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

            tree = [{},self.invisibleRootItem()]
            for song in songs:
                cur_item = tree
                for part in mode.split('/'):
                    tag = song[part]
                    if isinstance(tag, list):
                        tag = tag[0]            #FIXME hack to make songs with multiple genres work.
                    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.settings.beginGroup(self.plugin.name)

        self.modes = QtGui.QComboBox()
        self.refresh_modes()
        self.modes.activated.connect(self.modes_activated)

        self.search_txt = QtGui.QLineEdit()
        self.search_txt.textChanged.connect(self.filter_changed)
        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.modes)
        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 refresh_modes(self):
        self.modes.clear()
        for mode in self.settings.value('/modes').toStringList():
            self.modes.addItem(mode)
        self.modes.setCurrentIndex(self.settings.value('current_mode').toInt()[0])

    def fill_library(self):
        self.logger.info('Refreshing library.')
        self.library_model.fill(self.plugin.mpclient.library(), str(self.modes.currentText()))

    def filter_changed(self, text):
        items = self.library_model.findItems(text, QtCore.Qt.MatchContains|QtCore.Qt.MatchRecursive)
        for i in range(self.library_model.rowCount()):
            self.library_view.setRowHidden(i, QtCore.QModelIndex(), True)
        for item in items:
            while item.parent():
                item = item.parent()
            self.library_view.setRowHidden(item.row(), QtCore.QModelIndex(), False)
        self.filtered_items = items

    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)

    def modes_activated(self):
        self.settings.setValue('current_mode', QVariant(self.modes.currentIndex()))
        self.fill_library()