summaryrefslogtreecommitdiff
path: root/nephilim/plugins/Playlist.py
blob: dc26f0c1c6f87a8683a44f9ed586cc75f078f9cf (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
#
#    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 ..plugin import Plugin
from ..common import MIMETYPES, SongsMimeData
from ..song   import PlaylistEntryRef

class Playlist(Plugin):
    # public, const
    info = 'Shows the playlist.'

    # public, read-only
    o        = None

    # private
    DEFAULTS  = {'columns': ['track', 'title', 'artist', 'date', 'album', 'length'], 'header_state' : QtCore.QByteArray()}

    def _load(self):
        self.o = PlaylistWidget(self)

    def _unload(self):
        self.o = None

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

class PlaylistWidget(QtGui.QWidget):
    plugin   = None
    playlist = None


    def __init__(self, plugin):
        QtGui.QWidget.__init__(self)
        self.plugin = plugin

        self.playlist = PlaylistTree(self.plugin)

        self.setLayout(QtGui.QVBoxLayout())
        self.layout().setSpacing(0)
        self.layout().setMargin(0)
        self.layout().addWidget(self.playlist)

        self.plugin.mpclient.playlist(self.playlist.fill)

class PlaylistTree(QtGui.QTreeWidget):
    plugin = None

    ### PRIVATE ###
    # popup menu
    _menu      = None
    # add same... menu
    _same_menu = None

    def __init__(self, plugin):
        QtGui.QTreeWidget.__init__(self)
        self.plugin = plugin

        self.setSelectionMode(QtGui.QTreeWidget.ExtendedSelection)
        self.setAlternatingRowColors(True)
        self.setRootIsDecorated(False)

        # drag&drop
        self.viewport().setAcceptDrops(True)
        self.setDropIndicatorShown(True)
        self.setDragDropMode(QtGui.QAbstractItemView.DragDrop)

        columns = self.plugin.settings.value(self.plugin.name + '/columns')
        self.setColumnCount(len(columns))
        self.setHeaderLabels(columns)
        self.header().restoreState(self.plugin.settings.value(self.plugin.name + '/header_state'))

        # menu
        self._menu      = QtGui.QMenu()
        self._same_menu = self._menu.addMenu('Add same...')
        self.setContextMenuPolicy(QtCore.Qt.CustomContextMenu)
        self.customContextMenuRequested.connect(self._show_context_menu)

        self.itemActivated.connect(self._song_activated)
        self.header().geometriesChanged.connect(self._save_state)
        self.plugin.mpclient.playlist_changed.connect(lambda :self.plugin.mpclient.playlist(self.fill))
        self.plugin.mpclient.connect_changed.connect(self._update_menu)

    def _save_state(self):
        self.plugin.settings.setValue(self.plugin.name + '/header_state', self.header().saveState())

    def _song_activated(self, item):
        self.plugin.mpclient.play(item.song['id'])

    def fill(self, songs):
        columns = self.plugin.settings.value(self.plugin.name + '/columns')
        self.clear()
        for song in songs:
            item = PlaylistSongItem(PlaylistEntryRef(self.plugin.mpclient, song['id']))
            for i in range(len(columns)):
                item.setText(i, song['?' + columns[i]])
            self.addTopLevelItem(item)

    def keyPressEvent(self, event):
        if event.matches(QtGui.QKeySequence.Delete):
            ids = []
            for item in self.selectedItems():
                ids.append(item.song['id'])

            self.plugin.mpclient.delete(ids)
        else:
            QtGui.QTreeWidget.keyPressEvent(self, event)

    def mimeData(self, items):
        data = SongsMimeData()
        data.set_plistsongs([items[0].song['id']])
        return data

    def dropMimeData(self, parent, index, data, action):
        if data.hasFormat(MIMETYPES['plistsongs']):
            if parent:
                index = self.indexOfTopLevelItem(parent)
            elif index >= self.topLevelItemCount():
                index = self.topLevelItemCount() - 1
            self.plugin.mpclient.move(data.plistsongs()[0], index)
            return True
        elif data.hasFormat(MIMETYPES['songs']):
            if parent:
                index = self.indexOfTopLevelItem(parent)
            self.plugin.mpclient.add(data.songs(), index)
            return True
        return False

    def supportedDropActions(self):
        return QtCore.Qt.CopyAction | QtCore.Qt.MoveAction

    def mimeTypes(self):
        return [MIMETYPES['songs'], MIMETYPES['plistsongs']]

    def _update_menu(self):
        """Update popup menu. Invoked on (dis)connect."""
        self._same_menu.clear()
        for tag in self.plugin.mpclient.tagtypes:
            self._same_menu.addAction(tag, lambda tag = tag: self._add_selected_same(tag))

    def _add_selected_same(self, tag):
        """Adds all tracks in DB with tag 'tag' same as selected tracks."""
        for it in self.selectedItems():
            self.plugin.mpclient.findadd(tag, it.song['?' + tag])

    def _show_context_menu(self, pos):
        if not self.indexAt(pos).isValid():
            return
        self._menu.popup(self.mapToGlobal(pos))

class PlaylistSongItem(QtGui.QTreeWidgetItem):
    ### PUBLIC ###
    song = None

    def __init__(self, song):
        QtGui.QTreeWidgetItem.__init__(self)
        self.song = song