summaryrefslogtreecommitdiff
path: root/plugins/Listing.py
blob: 6860cf0ab5303a2fa63a028d496c0bf364955ab6 (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
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
from PyQt4 import QtGui, QtCore
from clPlugin import *

import copy
import sys

class wgListing(QtGui.QWidget):
    """Widget for the listing."""
    # Variables influencing the layout - adapt to your needs
    " height of line in pxl"
    lineHeight=20
    " background color"
    clrBg=QtGui.QColor(255,255,255)
    " colors for alternating rows"
    rowColors=[QtGui.QColor(255,255,255), QtGui.QColor(230,230,255)]
    " indentation at the left"
    leftIndent=10
    " general width or height of items, like a scrollbar"
    S=20
    " size of the button to collapse/expand"
    switchSize=20

    # don't tune these ones
    # widgets
    ## vertical scrollbar at the right
    vScrollbar=None
    ## filter input
    txtFilter=None
    ## clear txtFilter button
    btnClearFilter=None
    ## button for quick menu
    btnMenu=None
    ## the menu
    menu=None

    # variables for songdata, headers ...
    ## list of songs
    songs=[]
    ## [ song-id ]
    ## contains all visible songs. E.g. if len(visSongs)==5, there are 5 songs not filtered
    visSongs=[]
    ## headers: [ [tag, width, visible] ]
    headers=[]

    # information for displaying
    ## max number of lines that can be shown in the widget
    maxNumVisRows=None
    ## some status info at the bottom
    status=None
    ## highlight some row?
    highlightID=None
    ## current selected songs
    ## [ song-id ]
    selSongs=None

    # others
    ## name of this listing
    name="listing"
    ## what groups are there: [ group ]
    definedGroups=None
    ## index to the groups: {group => [group-id -> first-song-index-in-songs]}
    groupIndex={}

    def __init__(self, p, parent=None):
        QtGui.QWidget.__init__(self, parent)
        self.p=p

        # set the headerstuff
        headers=['$album', '$artist', '$track', '$title', '$timems', '$genre']
        self.headers=map(lambda h: [format.compile(h), int(settings.get('l%s.%s.width'%(self.name, self.headerTitle([format.compile(h)])),250))
            , settings.get('l%s.%s.visible'%(self.name,h), '1')=='1'], headers)
        self.headers.insert(0, [format.compile('$id'), 50, settings.get('l%s.%s.visible'%(self.name,'id'),'0')=='1'])

        self.selSongs=[]
        self.maxNumVisRows=0
        self.definedGroups=["album", "artist", "genre"]

        self.updateSongs([])

        # set the scrollbar
        self.vScrollbar=QtGui.QScrollBar(QtCore.Qt.Vertical, self)
        self.vScrollbar.setMinimum(0)
        self.vScrollbar.setMaximum(1)
        self.vScrollbar.setValue(0)

        self.menu=QtGui.QMenu(self)
        self.txtFilter=QtGui.QLineEdit(self)
        self.btnClearFilter=Button("Clear", lambda:self.txtFilter.setText(""), parent=self)
        self.btnMenu=Button("Menu", self.showMenu, parent=self)

        self.onMontyReady(None)

        self.connect(self.vScrollbar, QtCore.SIGNAL('valueChanged(int)'), self.update)
        self.connect(self.txtFilter, QtCore.SIGNAL('textChanged(const QString&)'), self.txtFilterChange)

        self.setMouseTracking(True)
        self.setAttribute(QtCore.Qt.WA_OpaquePaintEvent)
        self.setFocusPolicy(QtCore.Qt.TabFocus or QtCore.Qt.ClickFocus
                or QtCore.Qt.StrongFocus or QtCore.Qt.WheelFocus)

        self.p.monty.addListener('onReady', self.onMontyReady)

    def showMenu(self):
        """Popup the main menu."""
        m=self.menu
        m.setTearOffEnabled(True)
        m.clear()

        sm=m.addMenu("Sort%i: %s"%(0+1, self.definedGroups[0]))
        action=sm.addAction("%s"%(self.definedGroups[1]), lambda: self.moveSortGroup(1, 0))
        action=sm.addAction("%s"%(self.definedGroups[2]), lambda: self.moveSortGroup(2, 0))

        sm=m.addMenu("Sort%i: %s"%(1+1, self.definedGroups[1]))
        action=sm.addAction("%s"%(self.definedGroups[0]), lambda: self.moveSortGroup(0, 1))
        action=sm.addAction("%s"%(self.definedGroups[2]), lambda: self.moveSortGroup(2, 1))

        sm=m.addMenu("Sort%i: %s"%(2+1, self.definedGroups[2]))
        action=sm.addAction("%s"%(self.definedGroups[0]), lambda: self.moveSortGroup(0, 2))
        action=sm.addAction("%s"%(self.definedGroups[1]), lambda: self.moveSortGroup(1, 2))

        m.popup(self.btnMenu.mapToGlobal(QtCore.QPoint(20,20)))

    def moveSortGroup(self, fromi, toi):
        self.definedGroups.insert(toi, self.definedGroups.pop(fromi))
        for song in self.songs:
            song.vis=1
        self._updateAll()

    def onMontyReady(self, p):
        """Callback when self.p.monty's done initializing."""
        self.updateSongs(self.p.monty.listPlaylist())

    def updateVisSongs(self):
        """Ensure all visible songs appear in the playlist."""
        self.visSongs=filter(lambda song: song.vis>0, self.songs)
        i=0
        for song in self.visSongs:
            song.visIndex=i
            i+=1


    def sortSongs(self):
        """Ensure all songs are sorted according to the sort-keys."""
        t=self.definedGroups
        self.songs.sort(key=lambda song: (song.getTag(t[0]), song.getTag(t[1]), song.getTag(t[2])))
        i=0
        total=len(self.songs)
        while i<total:
            self.songs[i].index=i
            i+=1

    def updateGroups(self):
        """Ensure songs are grouped according to their tags."""
        # create groups for the songs
        curID={}
        counts={}
        prevSong={}
        self.groupIndex={}
        # count[0]: songs left, count[1]: songs done
        for group in self.definedGroups:
            curID[group]=0
            counts[group]=[0, 0]
            prevSong[group]=self.songs[0]
            self.groupIndex[group]=[self.songs[0]]
        default='(unk)'

        # set groups, and index of song inside group
        songI=0
        while songI<len(self.songs):
            song=self.songs[songI]
            curID=curID.copy()
            counts=copy.deepcopy(counts)
            for j in xrange(0, len(self.definedGroups)):
                group=self.definedGroups[j]
                if not song.getTag(group, default) or song.getTag(group, default)!=prevSong[group].getTag(group, default):
                    # change of group!
                    curID[group]+=1
                    counts[group][0]=1
                    prevSong[group]=song
                    # note that we assert here that index of song inside groupIndex[group] equals curID[group]
                    # i.e. curID[group]==len(self.groupIndex[group])
                    self.groupIndex[group].append(song)
                    if j>0 and songI>0:
                        prevgroup=self.definedGroups[j-1]
                else:
                    # staying in same group
                    counts[group][0]+=1
            song.groups=curID
            song.counts=counts
            songI+=1

        # set index of song inside group, starting at the end
        i=len(self.songs)-1
        counter={}
        for group in self.definedGroups:
            prevSong[group]=self.songs[i]
            counter[group]=1
        while i>0:
            song=self.songs[i]
            for tag in counts.keys():
                if not song.getTag(tag, default) or song.getTag(tag, default)!=prevSong[tag].getTag(tag, default):
                    counter[tag]=1
                    prevSong[tag]=song
                else:
                    counter[tag]+=1
                song.counts[tag][1]=counter[tag]
            i-=1


    def updateSongs(self, songs):
        """Refresh the playlist's songs."""
        self.songs=songs
        if not self.songs:
            self.songs=[]
            return
        self.visSongs=[]
        for song in self.songs:
            song.vis=1
            song.counts={}
            song.groups={}
            for group in self.definedGroups:
                song.counts[group]=[-1, -1]
                song.groups[group]=-1

        self._updateAll()

    def _updateAll(self):
        self.sortSongs()
        self.updateGroups()
        self.updateVisSongs()


    def collapseGroup(self, group, groupID=None):
        """Collapse all groups/one group for a group."""
        # check if it is usefull to collapse, by checking if we know the group
        if not group in self.songs[0].groups:
            return
        prev=-1
        i=0
        total=len(self.visSongs)
        if groupID==None:
            while i<total:
                groupID=self.visSongs[i].groups[group]
                if groupID!=prev:
                    prev=groupID
                else:
                    self.visSongs[i].vis=0
                i+=1
        else:
            total=len(self.visSongs)
            i=self.groupIndex[group][groupID].visIndex+1
            while i<total and self.visSongs[i].groups[group]==groupID:
                self.visSongs[i].vis=0
                i+=1
        self.updateVisSongs()
        self.updateVScrollbar()

    def expandGroup(self, group, groupID=None):
        """Expand all groups/one group for a group."""
        strFilter=self.txtFilter.text().toLower()
        # check if it is usefull to collapse, by checking if we know the group
        if not group in self.songs[0].groups:
            return
        if groupID==None:
            for song in self.songs:
                song.vis=song.match(strFilter)
        else:
            total=len(self.songs)
            i=self.groupIndex[group][groupID].index
            # expand all next!
            while i<total and self.songs[i].groups[group]==groupID:
                self.songs[i].vis=self.songs[i].match(strFilter)
                i+=1
        self.updateVisSongs()
        self.updateVScrollbar()

    def toggleGroup(self, group, groupID):
        if self.isOpenGroup(group, groupID):
            self.collapseGroup(group, groupID)
        else:
            self.expandGroup(group, groupID)

    def isOpenGroup(self, group, groupID):
        if not group in self.definedGroups:
            return True
        song=self.groupIndex[group][groupID]
        if song.counts[group][1]==1:
            # group with 1 item is always open
            return True
        if song.visIndex+1>=len(self.visSongs):
            # end is visible
            return True
        return song.groups[group]==self.visSongs[song.visIndex+1].groups[group]

    def txtFilterChange(self, str):
        strFilter=self.txtFilter.text().toLower()
        for song in self.songs:
            song.vis=song.match(strFilter)
        self.updateVisSongs()
        self.updateVScrollbar()
        self.update()

    def updateVScrollbar(self):
        """Update the VScrollbar's parameters and values."""
        # max nr of rows shown
        self.maxNumVisRows=int((self.height()-self.txtFilter.height()-self.lineHeight)/self.lineHeight)

        # check vertical scrollbar
        if self.maxNumVisRows>len(self.visSongs):
            self.vScrollbar.setVisible(False)
            self.vScrollbar.setValue(0)
        else:
            self.vScrollbar.setVisible(True)
            self.vScrollbar.setPageStep(self.maxNumVisRows-2)
            self.vScrollbar.setMinimum(0)
            self.vScrollbar.setMaximum(len(self.visSongs)-self.maxNumVisRows+1)
            self.vScrollbar.resize(self.S, self.height()-self.lineHeight-1)
            self.vScrollbar.move(self.width()-self.vScrollbar.width()-1, self.lineHeight)

    def wheelEvent(self, event):
        """Wheel-scroll event."""
        if self.vScrollbar.isVisible():
            event.accept()
            numDegrees=event.delta() / 8
            numSteps=5*numDegrees/15
            self.vScrollbar.setValue(self.vScrollbar.value()-numSteps)

    def resizeEvent(self, event):
        """Resize of widget."""
        # resize txtFilter and move btnClearFilter
        self.btnMenu.move(0, 0)
        self.txtFilter.move(self.btnMenu.width(), 0)
        self.txtFilter.resize(self.width()-self.btnClearFilter.width()-self.btnMenu.width()-self.vScrollbar.width(), self.txtFilter.height())
        self.btnClearFilter.move(self.txtFilter.pos().x()+self.txtFilter.width(), 0)

        self.updateVScrollbar()

    def keyPressEvent(self, event):
        if event.matches(QtGui.QKeySequence.Delete):
            # remove selection from playlist using DELETE-key
            ids=self.selSongs
            self.setStatus('Deleting '+str(len(ids))+' songs from playlist ...')
            doEvents()

            self.p.monty.deleteFromPlaylist(ids)

            self.setStatus('')
            doEvents()

        elif event.key()==QtCore.Qt.Key_Q:
            # queue selected songs
            # Hoho, this one needs the playcontrol plugin!
            plugins.getPlugin('playcontrol').addSongsToQueue(self.selSongs)
        return QtGui.QWidget.keyPressEvent(self, event)
    def _pos2row(self, pos):
        """Returns the row associated with pos (-1 for header, -1+ for rows)."""
        return int((pos.y()-self.txtFilter.height())/self.lineHeight)-1

    def _pos2col(self, pos, border=True):
        """Returns [column associated with pos, distance]; border indicates the region to check."""
        x=self.leftIndent
        for i in xrange(0,len(self.headers)):
            if not border and pos.x()>=x and pos.x()<x+self.headers[i][1]*self.headers[i][2]:
                return [i, pos.x()-x]
            x+=self.headers[i][1]*self.headers[i][2]
            if border and abs(x-pos.x())<15:
                return [i, abs(x-pos.x())]

        return None


    def colorID(self, id):
        self.highlightID=id
        self.update()

    mouseResizeCol=None
    mouseMoveCol=None
    mouseSelRows=None
    mouseSelInc=1
    def mousePressEvent(self, event):
        """Mouse press event."""
        pos=event.pos()
        row=self._pos2row(pos)
        curVisSongRow=row+self.vScrollbar.value()

        if row==-1:
            # header selected
            # now check out if we are on a margin, so we can move ...
            if event.button()==1:
                self.collapseGroup(self.headerTitle(self.headers[self._pos2col(pos, False)[0]]))
            else:
                p=self._pos2col(pos, True)
                if p!=None:
                    self.mouseResizeCol=p[0]
                else:
                    self.mouseMoveCol=self._pos2col(pos, False)[0]
        elif row>=0:
            p=self._pos2col(pos, False)
            col=p[0]
            x=p[1]
            if x<self.switchSize:
                song=self.visSongs[row+self.vScrollbar.value()]
                tag='album' # default tag
                if col:
                    tag=self.headerTitle(self.headers[col])
                if tag in song.groups:
                    if event.button()==1:
                        self.toggleGroup(tag, song.groups[tag])

            if event.button()==1:
                self.mouseSelRows=[curVisSongRow, curVisSongRow]
                self.selSongs=map(lambda row: self.visSongs[row]._data['id'], self.mouseSelRows[1:])

    def mouseMoveEvent(self, event):
        """Mouse move event."""
        pos=event.pos()
        row=self._pos2row(pos)
        curVisSongRow=row+self.vScrollbar.value()
        self.status="row: %i / %i"%(row, curVisSongRow)

        if True:
            col=self._pos2col(pos, False)
            tag=''
            song=''
            count=-1
            groupID=-1
            first=''
            if col:
                tag=self.headerTitle(self.headers[col[0]])
            if row+self.vScrollbar.value()<len(self.visSongs):
                song=self.visSongs[curVisSongRow]
            if song and tag in song.groups:
                groupID=song.groups[tag]
            if song and tag in song.counts:
                count=song.counts[tag]
            if tag in self.groupIndex:
                first=self.groupIndex[tag][groupID].__str__()
            self.status="tag: %s, groupID: %i, count: %s, open: %s, firstInGroup: %s"%(tag, groupID, count.__str__(), self.isOpenGroup(tag, groupID), first)

            self.update()

        if self.mouseResizeCol!=None:
            prevW=self.leftIndent
            for i in xrange(0,self.mouseResizeCol):
                prevW+=self.headers[i][1]*self.headers[i][2]
            self.headers[self.mouseResizeCol][1]=max(50, pos.x()-prevW)
            self.update()
        elif self.mouseMoveCol!=None:
            p=self._pos2col(pos, False)
            if p!=None:
                col=p[0]
                header=self.headers.pop(self.mouseMoveCol)
                self.headers.insert(col, header)
                self.mouseMoveCol=col
                self.update()
        elif self.mouseSelRows:
            # we're selecting
            start=self.mouseSelRows[0]
            r=range(min(start, curVisSongRow+1), max(start, curVisSongRow+1))
            self.mouseSelRows=[self.mouseSelRows[0]]
            self.mouseSelRows.extend(r)
            self.selSongs=map(lambda row: self.visSongs[row]._data['id'], self.mouseSelRows)
            if row<0:
                self.vScrollbar.setValue(self.vScrollbar.value()-self.mouseSelInc)
                self.mouseSelInc*=1.1
            elif row>self.maxNumVisRows:
                self.vScrollbar.setValue(self.vScrollbar.value()+self.mouseSelInc)
                self.mouseSelInc*=1.1
            else:
                self.mouseSelInc=1
            self.update()

    def mouseReleaseEvent(self, event):
        """Mouse release button event."""
        if self.mouseResizeCol:
            # save new size
            settings.set('l%s.%s.width'%(self.name, self.headerTitle(self.headers[self.mouseResizeCol]))
                    , self.headers[self.mouseResizeCol][1])
        if self.mouseMoveCol:
            # TODO save new position
            pass
        self.mouseResizeCol=None
        self.mouseMoveCol=None
        self.mouseSelRows=None
        self.update()

    def mouseDoubleClickEvent(self, event):
        row=self._pos2row(event.pos())
        col=self._pos2col(event.pos(), False)
        if col[1]>self.switchSize and row>=0:
            # only play if on a row, and we're not clicking on a fold
            self.p.monty.play(self.visSongs[row+self.vScrollbar.value()]._data['id'])

    def headerTitle(self, header):
        """Retrieve the tag of a header."""
        return header[0]({'id':'id', 'genre':'genre'
                    , 'title':'title', 'artist':'artist', 'album':'album', 'track':'track'
                    , 'timems':'timems'})

    def ensureVisible(self, id):
        """Make sure song with ID id is visible."""
        song=filter(lambda s: s._data['id']==id, self.songs)[0]

        # get the group which must be visible. E.g. if we want a song to
        # be visible, then it is preferrable to have the album or artist
        # to be completely visible.
        # For now, we'll use the second (third) header.
        group=self.headerTitle(self.headers[2])

        # TODO more efficient
        # TODO expand headers[1] too
        self.expandGroup(group, song.groups[group])
        self.update()

        for row in range(self.vScrollbar.value(), self.vScrollbar.value()+self.maxNumVisRows):
            if self.visSongs[row]._data['id']==id:
                return
        self.vScrollbar.setValue(min(len(self.visSongs), max(0, song.visIndex-self.maxNumVisRows/2)))
        self.update()

    def paintEvent(self, event):
        """Paint event."""
        leftIndent=self.leftIndent
        W=self.width()-self.vScrollbar.width()
        p=QtGui.QPainter(self)

        # we currently redraw everything, by repainting the background for every row ...

        # repaint area under vscrollbar
        p.fillRect(QtCore.QRect(W, 0, self.vScrollbar.width(), self.height()), QtGui.QBrush(QtCore.Qt.lightGray))

        # draw headers
        ## paint an area in light-gray
        p.fillRect(QtCore.QRect(0, self.txtFilter.height(), W,self.lineHeight), QtGui.QBrush(QtCore.Qt.lightGray))
        p.drawRect(QtCore.QRect(0, self.txtFilter.height(), W-1,self.lineHeight-1))

        ## draw the headers self
        y=self.txtFilter.height()
        x=leftIndent
        for header in self.headers:
            if header[2]:
                p.drawText(x, y, (header[1] if x+header[1]<W else W-x), self.lineHeight, QtCore.Qt.AlignLeft, self.headerTitle(header))
                x+=header[1]

        y+=self.lineHeight
        i=self.vScrollbar.value()
        prevGroupID=None
        total=len(self.visSongs)
        headerLen=len(self.headers)
        while y+self.lineHeight<self.height()-self.lineHeight and i<total:
            song=self.visSongs[i]
            highlight=self.highlightID==song._data['id']
            sel=False
            groupID=song.groups
            counts=song.counts
            x=leftIndent

            txtClr=QtCore.Qt.black
            if song._data['id'] in self.selSongs:
                sel=True
            if highlight:
                rowClr=QtGui.QColor(220,220,220)
            else:
                if sel:
                    sel=True
                    rowClr=QtGui.QColor(50,50,220)
                    txtClr=QtCore.Qt.white
                else:
                    rowClr=self.rowColors[i%len(self.rowColors)]

            p.setPen(txtClr)
            p.fillRect(QtCore.QRect(0, y, W, self.lineHeight), QtGui.QBrush(rowClr))

            # which of the groups are folded
            foldeds={}  # the fold for a group
            folded=False# is any of the groups folded
            for group in self.definedGroups:
                foldeds[group]=not self.isOpenGroup(group, groupID[group])
                folded=folded or foldeds[group]

            j=0
            while j<headerLen:
                header=self.headers[j]
                h0=self.headerTitle(header)
                if header[2]:
                    if (highlight or sel or not h0 in groupID or not prevGroupID or groupID[h0]!=prevGroupID[h0]):
                        # if parent-groups are folded, then we don't have to show this one, as it is not really usefull
                        # so we look here if the current item belongs to a closed group. But, ellipsis only has to be
                        # shown when the group is inferior to the folded group. E.g. when sorted by album,artist,genre
                        # one does not have to "ellipsis" album and artist when only genre is folded.
                        ellipsis=False
                        if not h0 in self.definedGroups and folded:
                            # a group is folded, and this tag ain't in a group, so it must be ellipsis'd
                            ellipsis=True
                        elif h0 in foldeds and foldeds[h0]:
                            # check if the fold is above or below us
                            l=self.definedGroups.index(h0)
                            if l>0:
                                for k in range(0, l):
                                    if foldeds[self.definedGroups[k]]:
                                        ellipsis=True

                        if not ellipsis:
                            try:
                                text=QtCore.QString(header[0](song._data))
                            except Exception,e:
                                text=str(e)
                            #if h0 in groupID:
                                #text="%s %i"%(text, groupID[h0])
                            #if h0 in counts:
                                #text="%s %s"%(text, str(counts[h0]))
                            if h0 in counts and counts[h0][0]==1 and counts[h0][1]>1:
                                if i<total-1 and self.visSongs[i+1].groups[h0]==groupID[h0]:
                                    # this one's open
                                    char='-'
                                else:
                                    # this one's closed
                                    char='+'
                                p.drawText(x, y, self.switchSize, self.lineHeight, QtCore.Qt.AlignCenter, char)
                        else:
                            text="..."
                        p.drawText(x+self.switchSize, y, (header[1] if x+header[1]<W else W-x)-self.switchSize
                            , self.lineHeight, QtCore.Qt.AlignLeft, text)
                    elif not highlight and not sel:
                        # we're in the same group as the previous entry, thus we don't need to
                        # restate the value. For now, we'll just draw a green filled rect to
                        # indicate this fact.
                        p.fillRect(x, y, (header[1] if x+header[1]<W else W-x), self.lineHeight, QtGui.QBrush(QtGui.QColor(220,255,220)))
                    x+=header[1]
                j+=1

            # draw a subtle black rect for a selection
            if sel:
                p.setPen(QtCore.Qt.black)
                p.drawRect(QtCore.QRect(0, y, W, self.lineHeight-1))

            y+=self.lineHeight
            if groupID!=prevGroupID:
                prevGroupID=groupID
            i+=1

        p.setPen(QtCore.Qt.black)
        if y<self.height():
            p.fillRect(QtCore.QRect(0, y, W, self.height()-y-1), QtGui.QBrush(self.rowColors[0]))

        # draw vertical, black line indicating the columns
        x=leftIndent
        for header in self.headers:
            if header[2]:
                x+=header[1]
                if x>W:break
                p.drawLine(x-1, self.txtFilter.height(), x-1, self.height())
        # draw a nice line around the widget!
        p.drawRect(QtCore.QRect(0,0,self.width()-1,self.height()-1))
        if self.hasFocus():
            p.drawRect(QtCore.QRect(1,1,self.width()-3,self.height()-3))
        else:
            p.setPen(QtCore.Qt.lightGray)
            p.drawRect(QtCore.QRect(1,1,self.width()-3,self.height()-3))


        text=None
        text="%s visible / %s in library" % (len(self.visSongs), len(self.songs))
        if self.status:
            text="%s%s"%(text, self.status)
        #text='%s - %s' % (self.selMiscs, '')
        #text='%s - %s - %s' % (str(self.topRow), str(self.selRows), str(self.selIDs))
        if text:
            r=QtCore.QRect(self.leftIndent, self.height()-self.lineHeight-2, W-10, self.lineHeight)
            p.fillRect(r, QtGui.QBrush(QtCore.Qt.white))
            p.drawText(r,QtCore.Qt.AlignLeft, text)


class pluginListing(Plugin, plugins.IPlaylist):
    o=None
    monty = None
    def __init__(self, winMain):
        Plugin.__init__(self, winMain, 'Listing')
        self.addMontyListener('onSongChange', self.onSongChange)
        self.monty = winMain.monty
    def _load(self):
        self.o=wgListing(self, None)
        try:
            if self.monty.getCurrentSong():
                self.onSongChange({'newSongID':self.monty.getCurrentSong().getID()})
        except:
            self.exc("Msg")
    def _unload(self):
        self.o=None
    def getInfo(self):
        return "A playlist"

    def _getDockWidget(self):
        return self._createDock(self.o)

    def _getSettings(self):
        return []
    def afterSaveSettings(self):
        return

    def onSongChange(self, params):
        self.o.colorID(int(params['newSongID']))

        if params['newSongID']!=-1:
            self.o.ensureVisible(params['newSongID'])


    def ensureVisible(self, id):
        """Make sure song with ID id is visible."""
        self.o.ensureVisible(id)