summaryrefslogtreecommitdiff
path: root/wgSongList.py
blob: f669c6ab33bee04c15072bc9e6750fe9cd69523a (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
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
from PyQt4 import QtGui, QtCore

import sys
from traceback import print_exc

from misc import *
from clSong import Song

# constants used for fSongs
LIB_ROW=0
LIB_VALUE=1
LIB_INDENT=2
LIB_NEXTROW=3
LIB_EXPANDED=4
LIB_PARENT=5

class SongList(QtGui.QWidget):
	"""The SongList widget is a list optimized for displaying an array of songs, with filtering option."""
	# CONFIGURATION VARIABLES
	" height of line in pxl"
	lineHeight=20
	" margin"
	margin=4
	" width of the vscrollbar"
	scrollbarWidth=15
	" minimum column width"
	minColumnWidth=50
	" colors for alternating rows"
	colors=[QtGui.QColor(255,255,255), QtGui.QColor(230,230,255)]
	" color of selection"
	clrSel=QtGui.QColor(100,100,180)
	" background color"
	clrBg=QtGui.QColor(255,255,255)
	" indentation of hierarchy, in pixels"
	indentation=20

	" what function to call when the list is double clicked"
	onDoubleClick=None

	mode='playlist'	# what mode is the songlist in? values: 'playlist', 'library'
	" the headers: ( (header, width, visible)+ )"
	headers=None
	songs=None	# original songs
	numSongs=None	# number of songs
	
	# 'edited' songs
	# in playlist mode, this can only filtering
	# in library mode, this indicates all entries: (row, tag-value, indentation, next-row, expanded)*
	fSongs=None		# filtered songs
	numVisEntries=None	# number of entries that are visible (including when scrolling)

	
	levels=[]		# levels from the groupBy in library-mode
	groupByStr=''	# groupBy used in library-mode
	
	vScrollbar=None
	hScrollbar=None

	topRow=-1
	numRows=-1	# total number of rows that can be visible in 1 time
	selRows=None	# ranges of selected rows: ( (startROw,endRow)* )
	selIDs=None	# ranges of selected IDs: [ [startID,endID] ]
	selMiscs=None	# array of indexes for selected non-songs in library mode

	selMode=False	# currently in select mode?
	resizeCol=None	# resizing a column?
	clrID=None	# do we have to color a row with certain ID? [ID, color]
	scrollMult=1	# how many rows do we jump when scrolling by dragging
	xOffset=0	# offset for drawing. Is changed by hScrollbar
	resizeColumn=None	# indicates this column should be recalculated
	redrawID=None	# redraw this ID/row only


	def __init__(self, parent, headers, onDoubleClick):
		QtGui.QWidget.__init__(self, parent)
		self.onDoubleClick=onDoubleClick

		# we receive an array of strings; we convert that to an array of (header, width)
		self.headers=map(lambda h: [h, 250, True], headers)
		self.headers.insert(0, ['id', 30, True])
		self.songs=None
		self.numSongs=None
		self.fSongs=None
		self.selMiscs=[]
		self.numVisEntries=None
		self.xOffset=0
		self.resizeColumn=None
		
		self.vScrollbar=QtGui.QScrollBar(QtCore.Qt.Vertical, self)
		self.vScrollbar.setMinimum(0)
		self.vScrollbar.setMaximum(1)
		self.vScrollbar.setValue(0)

		self.hScrollbar=QtGui.QScrollBar(QtCore.Qt.Horizontal, self)
		self.hScrollbar.setMinimum(0)
		self.hScrollbar.setMaximum(1)
		self.hScrollbar.setValue(0)
		self.hScrollbar.setPageStep(200)

		self.topRow=0
		self.numRows=0
		self.selRows=[]
		self.selMode=False
		self.clrID=[-1,0]

		self.updateSongs([])
		doEvents()
		
		self.connect(self.vScrollbar, QtCore.SIGNAL('valueChanged(int)'),self.onVScroll)
		self.connect(self.hScrollbar, QtCore.SIGNAL('valueChanged(int)'),self.onHScroll)
		
		self.setMouseTracking(True)
		self.setFocusPolicy(QtCore.Qt.TabFocus or QtCore.Qt.ClickFocus
				or QtCore.Qt.StrongFocus or QtCore.Qt.WheelFocus)

		self.setAttribute(QtCore.Qt.WA_OpaquePaintEvent)

	def sizeHint(self):
		return QtCore.QSize(10000,10000)
	
	def setMode(self, mode, groupBy=''):
		self.selRows=[]
		self.selIDs=[]
		self.selMode=False

		if mode=='playlist':
			self.fSongs=self.songs
			self.numVisEntries=len(self.fSongs)
		elif mode=='library':
			self.groupBy(groupBy)
		else:
			raise Exception('Unknown mode %' %(mode))
		
		self.mode=mode

		self.resizeEvent(None)
		self.update()
		
	def groupBy(self, groupBy, strFilter=''):
		self.groupByStr=groupBy
		self.levels=groupBy.split('/')
		strFilter=strFilter.strip()

		# TODO also sort by other means, if necessary ...
		if self.levels[0]=='artist':
			compare=lambda left, right: cmp(str(left.getArtist()).lower(), str(right.getArtist()).lower())
		elif self.levels[0]=='album':
			compare=lambda left, right: cmp(left.getAlbum().lower(), right.getAlbum().lower())
		else:
			compare=lambda left, right: 0

		songs=self.songs
		if strFilter!='':
			songs=filter(lambda song: strFilter in str(song).lower(), songs)
		songs=sorted(songs, compare)

		numLevels=len(self.levels)
		self.fSongs=[[0, 'dummy', 0, -1, False]]
		row=0
		# four levels ought to be enough for everyone
		curLevels=[[None,0], [None,0], [None,0], [None,0]]	# contains the values of current levels
		curLevel=0	# current level we're in
		parents=[-1,-1,-1,-1]	# index of parent
		for song in songs:
			for level in xrange(numLevels):
				# does the file have the required tag?
				try:
					tagValue=song._data[self.levels[level]]
				except:
					tagValue=''
					
				if tagValue==curLevels[level][LIB_ROW]:
					pass
				else:
					finalRow=row
					for i in xrange(level,numLevels):
						try:
							tagValue2=song._data[self.levels[i]]
						except:
							tagValue2=''
							pass
						
						self.fSongs[curLevels[i][1]][LIB_NEXTROW]=finalRow
						self.fSongs.append([row, tagValue2, i, row+1, 0, parents[i]])
						parents[i+1]=row
						
						row+=1
						curLevels[i]=[tagValue2, row]
					curLevel=numLevels
			self.fSongs.append([row, song, curLevel, row+1, 2, parents[curLevel]])
			row+=1
		
		# update last entries' next-row of each level
		#  If we have e.g. artist/album, then the last artist and last album of that
		#  artist have to be repointed to the end of the list, else problems arise
		#  showing those entries ...
		# indicate for each level whether we have processed that level yet
		processed=[False, False, False, False, False]
		numFSongs=len(self.fSongs)
		for i in xrange(numFSongs-1,0,-1):
			song=self.fSongs[i]
			# look for last top-level entry
			if song[LIB_INDENT]==0:
				song[LIB_NEXTROW]=numFSongs
				break
			if processed[song[LIB_INDENT]]==False:
				song[LIB_NEXTROW]=numFSongs
				processed[song[LIB_INDENT]]=True
		
		
		# remove the dummy
		self.fSongs.pop(0)
		
		self.numVisEntries=len(filter(lambda entry: entry[LIB_INDENT]==0, self.fSongs))
		self.resizeEvent(None)
	
	def updateSongs(self, songs):
		"""Update the displayed songs and clears selection."""
		self.songs=songs
		self.numSongs=len(songs)
		
		self.setMode(self.mode, self.groupByStr)

		self.resizeEvent(None)
		self.redrawID=None
		self.update()

	def selectedSongs(self):
		"""Returns the list of selected songs."""
		ret=[]
		if self.mode=='playlist':
			cmp=lambda song: song._data['id']>=range[0] and song._data['id']<=range[1]
		elif self.mode=='library':
			cmp=lambda song: song._data['id']>=range[0] and song._data['id']<=range[1]
		for range in self.selIDs:
			# look for the songs in the current range
			songs=filter(cmp, self.songs)
			# add songs in range
			ret.extend(songs)
		return ret

	def filter(self, strFilter):
		"""Filter songs according to $strFilter."""
		if self.mode=='playlist':
			self.fSongs=filter(lambda song: strFilter in str(song).lower(), self.songs)
			self.numVisEntries=len(self.fSongs)
			self.resizeEvent(None)
		else:
			self.groupBy(self.groupByStr, strFilter)

		self.update()

	def colorID(self, id, clr):
		"""Color the row which contains song with id $id $clr."""
		self.clrID=[id, clr]
		self.redrawID=id

		self.update()

	def selectRow(self, row):
		"""Make $row the current selection."""
		self.selRows=[[row,row]]
		
		self.update()
	
	def showColumn(self, column, show=True):
		"""Hide or show column $column."""
		self.headers[column][2]=show
		
		self.update()

	def autoSizeColumn(self, column):
		"""Resizes column $column to fit the widest entry in the non-filtered songs."""
		# we can't calculate it here, as retrieving the text-width can only
		# be done in the paintEvent method ...
		self.resizeColumn=column

		self.update()

	def visibleSongs(self):
		"""Get the songs currently visible."""
		ret=[]()
		for row in xrange(self.topRow, min(self.numSongs, self.topRow+self.numRows)-1):
			ret.append(self.fSongs[row])
		return ret

	def ensureVisible(self, id):
		"""Make sure the song with $id is visible."""
		if len(filter(lambda song: song.getID()==id, self.visibleSongs())):
			return
		row=0
		for song in self.fSongs:
			if song.getID()==id:
				self.vScrollbar.setValue(row-self.numRows/2)
				self.update()
				break
			row+=1

	
	def onVScroll(self, value):
		# 'if value<0' needed because minimum can be after init <0 at some point ...
		if value<0:	value=0
		if value>self.numVisEntries:value=self.numVisEntries
		self.topRow=value

		self.update()
	
	def onHScroll(self, value):
		self.xOffset=-self.hScrollbar.value()*2
		self.update()
	
	def _pos2row(self, pos):
		return int(pos.y()/self.lineHeight)-1
	def _row2entry(self, row):
		entry=self.fSongs[0]
		try:
			while row>0:
				if entry[LIB_EXPANDED]:
					entry=self.fSongs[entry[LIB_ROW]+1]
				else:
					entry=self.fSongs[entry[LIB_NEXTROW]]
				row-=1
		except:
			return None
		return entry

	def focusOutEvent(self, event):
		self.update()
	def focusInEvent(self, event):
		self.update()
	def wheelEvent(self, 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):
		# max nr of rows shown
		self.numRows=int(self.height()/self.lineHeight)
		
		# check vertical scrollbar
		if self.numRows>self.numVisEntries:
			self.vScrollbar.setVisible(False)
			self.vScrollbar.setValue(0)
		else:
			self.vScrollbar.setVisible(True)
			self.vScrollbar.setPageStep(self.numRows-2)
			self.vScrollbar.setMinimum(0)
			self.vScrollbar.setMaximum(self.numVisEntries-self.numRows+1)
			self.vScrollbar.resize(self.scrollbarWidth, self.height()-self.lineHeight-1)
			self.vScrollbar.move(self.width()-self.vScrollbar.width()-1, self.lineHeight-1)
		
		# check horizontal scrollbar
		self.scrollWidth=0
		if self.mode=='playlist':
			for hdr in self.headers:
				if hdr[2]:
					self.scrollWidth+=hdr[1]
		
		if self.scrollWidth>self.width():
			self.hScrollbar.setVisible(True)
			self.hScrollbar.setMinimum(0)
			self.hScrollbar.setMaximum((self.scrollWidth-self.width())/2)
			self.hScrollbar.resize(self.width(), self.lineHeight)
			self.hScrollbar.move(0, self.height()-self.lineHeight-1)

			# some changes because the hScrollbar takes some vertical space ...
			self.vScrollbar.resize(self.vScrollbar.width(), self.vScrollbar.height()-self.lineHeight)
			self.vScrollbar.setMaximum(self.vScrollbar.maximum()+1)

			self.numRows-=1
		else:
			self.hScrollbar.setVisible(False)
			self.hScrollbar.setValue(0)

	


	def mousePressEvent(self, event):
		self.setFocus()
		pos=event.pos()
		row=self._pos2row(pos)

		done=False	# indicates whether some action has been done or not
		if self.mode=='playlist':
			self.scrollMult=1
			if row==-1:
				# we're clicking in the header!
				self.resizeCol=None
				x=0+self.xOffset
				i=0
				# check if we're clicking between two columns, if so: resize mode!
				for hdr in self.headers:
					if hdr[2]:
						x+=hdr[1]
					if abs(x-pos.x())<4:
						self.resizeCol=i
						done=True
					i+=1
		elif self.mode=='library':
			entry=self._row2entry(row+self.topRow)
			if not entry:
				entry=self.fSongs[len(self.fSongs)-1]
			if entry and pos.x()>(1+entry[LIB_INDENT])*self.indentation \
					and pos.x()<(1+entry[LIB_INDENT]+3/2)*self.indentation:
				# we clicked in the margin, to expand or collapse
				expanded=entry[LIB_EXPANDED]
				if expanded!=2:
					# there was a '+' or a '-'!
					entry[LIB_EXPANDED]=(expanded+1)%2
					# we must find out how many entries have appeared/disappeard
					# while collapsing.
					visibles=0	# how many new elements have appeared?
					i=entry[LIB_ROW]+1	# current element looking at
					while i<=entry[LIB_NEXTROW]-1 and i<len(self.fSongs):
						visibles+=1
						entry2=self.fSongs[i]
						if entry2[LIB_EXPANDED]==0:
							i=entry2[LIB_NEXTROW]
						else:
							i+=1

					if expanded==0:
						# if it wasn't expanded, but now is...
						self.numVisEntries+=visibles
					else:
						self.numVisEntries-=visibles
					done=True
					self.resizeEvent(None)
		
		if done==False:
			self.selMode=True
			self.selIDs=[]
			self.selMiscs=[]
			if row==-1 and self.resizeCol==None:
				# we're not resizing, thus we can select all!
				self.selRows=[[0, len(self.fSongs)]]
			elif row>=0:
				# we start selection mode
				if self.mode=='playlist':
					self.selRows=[[self.topRow+row,self.topRow+row]]
				elif self.mode=='library':
					self.selRows=[[entry[LIB_ROW], entry[LIB_NEXTROW]-1]]
				self.selMode=True

		self.update()

	def mouseMoveEvent(self, event):
		pos=event.pos()
		row=self._pos2row(pos)
		if self.selMode:
			# we're in selection mode
			if row<0:
				# scroll automatically when going out of the widget
				row=0
				if self.topRow>0:
					self.scrollMult+=0.1
					jump=int(self.scrollMult)*int(abs(pos.y())/self.lineHeight)
					self.vScrollbar.setValue(self.vScrollbar.value()-jump)
					row=jump
			elif row>=self.numRows:
				# scroll automatically when going out of the widget
				self.scrollMult+=0.1
				jump=int(self.scrollMult)*int(abs(self.height()-pos.y())/self.lineHeight)
				self.vScrollbar.setValue(self.vScrollbar.value()+jump)
				row=self.numRows-jump
			else:
				# reset the scrollMultiplier
				self.scrollMult=1
			
			if self.mode=='playlist':
				self.selRows[0][1]=row+self.topRow
			elif self.mode=='library':
				self.selRows[0][1]=self.libIthVisRowIndex(self.libIthVisRowIndex(0,self.topRow), row)
			self.update()
		elif self.resizeCol!=None:
			row-=1
			# ohla, we're resizing a column!
			prev=0
			# calculate where we are
			for i in xrange(self.resizeCol):
				hdr=self.headers[i]
				if hdr[2]:
					prev+=hdr[1]
			self.headers[self.resizeCol][1]=pos.x()-prev-self.xOffset
			# minimum width check?
			if self.headers[self.resizeCol][1]<self.minColumnWidth:
				self.headers[self.resizeCol][1]=self.minColumnWidth
			self.resizeEvent(None)
			self.update()
	
	def mouseReleaseEvent(self, event):
		if self.selMode and len(self.selRows):
			# we were selecting, but now we're done.
			# We have to transform one range of rows
			# into range of selected IDs
			# The problem is that the list can be filtered, and that
			# consequtive, visible rows aren't always directly
			# consequtive in the unfiltered list.
			self.selMode=False	# exit selection mode
			fSongs=self.fSongs
			self.selMiscs=[]
			ranges=[]
			curRange=[]
			# loop over all rows that are selected
			for entry in fSongs[min(self.selRows[0]):max(self.selRows[0])+1]:
				song=None
				if isinstance(entry,Song):
					song=entry
				elif isinstance(entry[LIB_VALUE],Song):
					song=entry[LIB_VALUE]
				else:
					self.selMiscs.append(entry[LIB_ROW])
				
				if song!=None:
					id=song.getID()
					# is this song directly after the previous row?
					if len(curRange)==0 or curRange[-1]+1==id:
						curRange.append(id)
					else:
						ranges.append(curRange)
						curRange=[id]
			if len(curRange):
				ranges.append(curRange)
			# clean up ranges
			self.selRows=[]
			self.selIDs=[]
			for range in ranges:
				self.selIDs.append([range[0], range[-1]])
			self.update()
		
		elif self.resizeCol!=None:
			# we're not resizing anymore!
			self.resizeCol=None
			self.update()

	def mouseDoubleClickEvent(self, event):
		pos=event.pos()
		row=self._pos2row(pos)-1
		if row>=0:
			self.onDoubleClick()
		else:
			# auto-size column
			x=0+self.xOffset
			i=0
			for hdr in self.headers:
				if hdr[2]:
					x+=hdr[1]
				if abs(x-pos.x())<4:
					self.autoSizeColumn(i)
					break
				i+=1

	def _paintPlaylist(self, p):
		self.redrawID=None
		
		
		lineHeight=self.lineHeight
		margin=self.margin
		selRows=self.selRows
		width=self.width()
		if self.vScrollbar.isVisible():
			width-=self.scrollbarWidth

		if self.resizeColumn!=None:
			# we're autoresizing!
			# must be done here, because only here we can check the textwidth!
			# This is because of limitations it can be only be done in paintEvent
			hdr=self.headers[self.resizeColumn][0]
			w=self.minColumnWidth
			# loop over all visible songs ...
			for song in self.fSongs:
				rect=p.boundingRect(10,10,1,1, QtCore.Qt.AlignLeft, str(song.getTag(hdr)))
				w=max(rect.width(), w)
			self.headers[self.resizeColumn][1]=w+2*margin
			self.resizeColumn=None
			self.resizeEvent(None)
		if self.redrawID!=None:
			# only update one row
			y=lineHeight
			for row in xrange(self.topRow, min(self.numVisEntries, self.topRow+self.numRows)):
				if self.fSongs[row]._data['id']==self.redrawID:
					self._paintPlaylistRow(p, row, y, width)
				y+=lineHeight

			self.redrawID=None
			return

		# paint the headers!
		p.fillRect(QtCore.QRect(0,0,width+self.vScrollbar.width(),lineHeight), QtGui.QBrush(QtCore.Qt.lightGray))
		p.drawRect(QtCore.QRect(0,0,width+self.vScrollbar.width()-1,lineHeight-1))
		x=margin+self.xOffset
		for hdr in self.headers:
			if hdr[2]:
				p.drawText(QtCore.QPoint(x, lineHeight-margin), hdr[0])
				x+=hdr[1]
				p.drawLine(QtCore.QPoint(x-margin,0), QtCore.QPoint(x-margin,lineHeight))

		if self.songs==None:
			return
		# fill the records!
		y=lineHeight
		for row in xrange(self.topRow, min(self.numVisEntries, self.topRow+self.numRows)):
			self._paintPlaylistRow(p, row, y, width)
			y+=lineHeight
		if y<self.height():
			# if we're short on songs, draw up the remaining area in background color
			p.fillRect(QtCore.QRect(0,y,width,self.height()-y), QtGui.QBrush(self.clrBg))

	def _paintPlaylistRow(self, p, row, y, width):
		"""Paint row $row on $p on height $y and with width $width."""
		song=self.fSongs[row]
		lineHeight=self.lineHeight
		margin=self.margin
		id=song._data['id']
		
		# determine color of row. Default is row-color, but can be overridden by
		# (in this order): selection, special row color!
		clr=self.colors[row%2]	# background color of the row
		clrTxt=QtCore.Qt.black	# color of the printed text
		# is it selected?
		values=[]
		if self.selMode:
			checkID=row
			values=self.selRows
		else:
			checkID=id
			values=self.selIDs
		# if values==[], it won't run!
		for range in values:
			# is selected if in range, which depends on the selection-mode
			if checkID>=min(range) and checkID<=max(range):
				clr=self.clrSel
				clrTxt=QtCore.Qt.white
		# it has a VIP-status!
		if id==int(self.clrID[0]):
			clrTxt=QtCore.Qt.white
			clr=self.clrID[1]

		# draw the row background
		p.fillRect(QtCore.QRect(2, y, width-3, lineHeight), QtGui.QBrush(clr))

		# draw a subtile rectangle
		p.setPen(QtGui.QColor(230,230,255))
		p.drawRect(QtCore.QRect(2, y, width-3, lineHeight))

		# Back To Black
		p.setPen(QtCore.Qt.black)

		# draw the column
		x=margin+self.xOffset
		for hdr in self.headers:
			if hdr[2]:
				# only if visible, duh!
				# rectangle we're allowed to print in
				rect=p.boundingRect(x, y, hdr[1]-margin, lineHeight, QtCore.Qt.AlignLeft, str(song.getTag(hdr[0])))
				text=str(song.getTag(hdr[0]))
				p.setPen(clrTxt)
				p.drawText(x, y+1, hdr[1]-margin, lineHeight, QtCore.Qt.AlignLeft, text)
				if rect.width()>hdr[1]-margin:
					# print ellipsis, if necessary
					p.fillRect(x+hdr[1]-15,y+1,15,lineHeight-1, QtGui.QBrush(clr))
					p.drawText(x+hdr[1]-15,y+1,15,lineHeight-1, QtCore.Qt.AlignLeft, "...")
				x+=hdr[1]
				p.setPen(QtCore.Qt.black)
				p.drawLine(QtCore.QPoint(x-margin,y), QtCore.QPoint(x-margin,y+lineHeight))

	def libFirstVisRowIndex(self):
		"""Returns the index of the first visible row in library mode."""
		# if not in library mode, the unthinkable might happen! Wooo!
		# TODO find better initial value
		row=0	# the visible rows we're visiting
		index=0	# what index does the current row have
		entries=self.fSongs
		
		while index<len(entries):
			if row>=self.topRow:
				break
			entry=entries[index]
			if entry[LIB_EXPANDED]==0:
				index=entry[LIB_NEXTROW]
			else:
				index+=1
			row+=1
		return index
	def libIthVisRowIndex(self, index, i=1):
		"""Returns the index of the $i-th next row after $index that is visible (or -1) in library mode."""
		entries=self.fSongs
		while i>0 and index<len(entries):
			i-=1
			entry=self.fSongs[index]
			if entry[LIB_EXPANDED]==0:
				if index<0:
					return -1
				index=entry[LIB_NEXTROW]
			else:
				index+=1

		return index


	def libPrint(self):
		for entry in self.fSongs:
			indent=""
			for i in xrange(entry[2]):
				indent=("%s    ")%(indent)
			print "%s%s" % (indent, entry)
	
	def _paintLibrary(self, p):
		width=self.width()
		height=self.height()
		lineHeight=self.lineHeight
		margin=self.margin
		
		# paint the headers!
		p.fillRect(QtCore.QRect(0,0,width+self.vScrollbar.width(),lineHeight), QtGui.QBrush(QtCore.Qt.lightGray))
		p.drawRect(QtCore.QRect(0,0,width+self.vScrollbar.width()-1,lineHeight-1))
		p.drawText(margin, 1, width, lineHeight, QtCore.Qt.AlignLeft, self.groupByStr)
		
		entries=self.fSongs
		
		y=lineHeight
		x=margin
		indent=self.indentation
		index=self.libFirstVisRowIndex()
		row=0
		while index<len(entries) and y<height:
			entry=entries[index]
			
			level=entry[LIB_INDENT]
			isSong=isinstance(entry[LIB_VALUE], Song)
			
			if isSong:
				text=entry[LIB_VALUE].getTitle()
				#text=str(entry)
			else:
				if entry[LIB_EXPANDED]==1:	prefix='-'
				elif entry[LIB_EXPANDED]==0:	prefix='+'
				text='%s\t%s: %s'%(prefix, self.levels[level], entry[LIB_VALUE])
				#text='%s\t%s: %s'%(prefix, self.levels[level], str(entry))
				
			clr=self.colors[row%2]	# background color of the row
			clrTxt=QtCore.Qt.black

			values=[]
			if self.selMode:
				checkID=index
				values=self.selRows
			elif self.selMode==False and isSong:
				checkID=entry[LIB_VALUE].getID()
				values=self.selIDs
			
			# if values==[], then it won't run!
			for range in values:
				# is selected if in range, which depends on the selection-mode
				if checkID>=min(range) and checkID<=max(range):
					clr=self.clrSel
					clrTxt=QtCore.Qt.white

			for i in self.selMiscs:
				if index==i:
					clr=QtCore.Qt.lightGray
					clrTxt=QtCore.Qt.white
			
			p.fillRect(QtCore.QRect(x+indent*entry[LIB_INDENT]-2,y,width-3,lineHeight), clr)
			p.setPen(clrTxt)
			p.drawText(x+indent*entry[LIB_INDENT],y+1, width, lineHeight, QtCore.Qt.AlignLeft, text)
			p.setPen(QtCore.Qt.black)
			
			y+=lineHeight
			row+=1
			index=self.libIthVisRowIndex(index)
			if index<0:
				break

	def paintEvent(self, event):
		p=QtGui.QPainter(self)
	
		# for the moment, redraw everything ...
		p.fillRect(QtCore.QRect(0,0,self.width(),self.height()), QtGui.QBrush(self.clrBg))
		if self.mode=='playlist':
			self._paintPlaylist(p)
		elif self.mode=='library':
			self._paintLibrary(p)

		# 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='%s - %s' % (self.selMiscs, '')
		#text='%s - %s' % (str(self.selRows), str(self.selIDs))
		r=QtCore.QRect(10,self.height()-40,self.width()-20,20)
		p.fillRect(r, QtGui.QBrush(QtCore.Qt.white))
		p.drawText(r,QtCore.Qt.AlignLeft, text)