summaryrefslogtreecommitdiff
path: root/winMain.py
blob: 4668dc2686e1da00e5d0a42c69a1a8d9a90af30d (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
802
803
804
805
806
807
808
809
810
811
812
813
from clMonty import monty
from clLibrary import Library
from winConnect import winConnect
from PyQt4 import QtGui, QtCore
from traceback import *
import time
import sys
from misc import *


clrRowSel=QtGui.QColor(180,180,180)

class SongList(QtGui.QWidget):
	# CONFIGURATION VARIABLES
	# height of line in pxl
	lineHeight=20
	margin=4
	scrollbarWidth=15
	minHeaderWidth=50
	# alternating colors
	colors=[QtGui.QColor(255,255,255), QtGui.QColor(230,230,255)]
	clrSel=QtGui.QColor(100,100,180)	# color of selection
	clrBg=QtGui.QColor(200,200,230)	# background color

	onDoubleClick=None

	# array( (header, width, visible)+ )
	headers=None
	songs=None	# original songs
	numSongs=None	# number of songs
	fSongs=None	# filtered songs
	fNumSongs=None	# number of filtered songs

	vScrollbar=None
	hScrollbar=None

	topRow=-1
	numRows=-1
	selRange=None	# array of ranges of rows currently selected; relative to 0

	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.fNumSongs=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 updateSongs(self, songs):
		self.songs=songs
		self.numSongs=len(songs)
		self.fSongs=songs
		self.fNumSongs=self.numSongs

		self.selRows=[]
		self.selMode=False

		self.resizeEvent(None)
		self.update()

	def selectedSongs(self):
		ret=[]
		for range in self.selRows:
			songs=filter(lambda song: song._data['id']>=range[0] and song._data['id']<=range[1], self.songs)
			for song in songs:
				ret.append(song)
		return ret

	def filter(self, strFilter):
		self.fSongs=filter(lambda song: strFilter in str(song).lower(), self.songs)
		self.fNumSongs=len(self.fSongs)

		self.resizeEvent(None)
		self.update()

	def colorID(self, id, clr):
		self.clrID=[id, clr]
		self.redrawID=id

		self.update()

	def selectRow(self, row):
		self.selRows=[[row,row]]
		
		self.update()
	
	def showColumn(self, column, show=True):
		self.headers[column][2]=show
		
		self.update()

	def autoSizeColumn(self, column):
		self.resizeColumn=column

		self.update()

	def visibleSongs(self):
		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):
		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.fNumSongs:
			value=self.fNumSongs
		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 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):
		self.numRows=int(self.height()/self.lineHeight)+1
		
		# check vertical scrollbar
		if self.numRows+1>=self.fNumSongs:
			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.fNumSongs-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
		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)

			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 mouseReleaseEvent(self, event):
		if self.selMode:
			self.selMode=False
			# find all consecutive ranges
			fSongs=self.fSongs
			self.selRows.sort()
			ranges=[]
			curRange=[]
			for song in fSongs[min(self.selRows[0]):max(self.selRows[0])+1]:
				id=song.getID()
				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=[]
			for range in ranges:
				self.selRows.append([range[0], range[-1]])
			self.update()
		
		elif self.resizeCol!=None:
			self.resizeCol=None
			self.update()


	def mousePressEvent(self, event):
		self.setFocus()
		pos=event.pos()
		row=self._pos2row(pos)
		self.scrollMult=1
		if row==-1:
			self.resizeCol=None
			x=0+self.xOffset
			i=0
			for hdr in self.headers:
				if hdr[2]:
					x+=hdr[1]
				if abs(x-pos.x())<4:
					self.resizeCol=i
				i+=1
			if self.resizeCol==None:
				self.selMode=True
				self.selRows=[[0, self.fNumSongs-1]]
		elif event.button()==QtCore.Qt.LeftButton:
			self.selRows=[[self.topRow+row,self.topRow+row]]
			self.selMode=True
		
		self.update()

	def mouseMoveEvent(self, event):
		pos=event.pos()
		row=self._pos2row(pos)
		if self.selMode:
			if row<0:
				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:
				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:
				self.scrollMult=1
			self.selRows[0][1]=row+self.topRow
			self.update()
		elif self.resizeCol!=None:
			prev=0
			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
			if self.headers[self.resizeCol][1]<self.minHeaderWidth:
				self.headers[self.resizeCol][1]=self.minHeaderWidth
			self.resizeEvent(None)
			self.update()
	
	def mouseDoubleClickEvent(self, event):
		pos=event.pos()
		row=self._pos2row(pos)
		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 _paintRow(self, p, row, y, 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): hover, selection, special row color!
		clr=self.colors[row%2]
		clrTxt=QtCore.Qt.black
		for range in self.selRows:
			if self.selMode==False and id>=range[0] and id<=range[1]:
				clr=self.clrSel
				clrTxt=QtCore.Qt.white
			elif self.selMode and row>=min(range) and row<=max(range):
				clr=self.clrSel
				clrTxt=QtCore.Qt.white
		if id==int(self.clrID[0]):
			clrTxt=QtCore.Qt.white
			clr=self.clrID[1]

		p.fillRect(QtCore.QRect(2, y, width-3, lineHeight), QtGui.QBrush(clr))
		p.setPen(QtGui.QColor(230,230,255))
		p.drawRect(QtCore.QRect(2, y, width-3, lineHeight))
		p.setPen(QtCore.Qt.black)
		x=margin+self.xOffset
		for hdr in self.headers:
			if hdr[2]:
				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:
					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 paintEvent(self, event):
		lineHeight=self.lineHeight
		margin=self.margin

		# OTHER VARS
		p=QtGui.QPainter(self)
		selRows=self.selRows
		width=self.width()
		if self.vScrollbar.isVisible():
			width-=self.scrollbarWidth

		if self.resizeColumn!=None:
			hdr=self.headers[self.resizeColumn][0]
			w=self.minHeaderWidth
			for song in self.songs:
				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:
			y=lineHeight
			for row in xrange(self.topRow, min(self.fNumSongs, self.topRow+self.numRows)):
				if self.fSongs[row]._data['id']==self.redrawID:
					self._paintRow(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.fNumSongs, self.topRow+self.numRows)):
			self._paintRow(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))

		# 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))

class Playlist(QtGui.QWidget):
	name=None
	txtFilter=None
	lstSongs=None
	headers=None
	winMain=None
	onKeyPress=None
	_timerID=None

	def __init__(self, parent, wMain, headers, name, onDoubleClick, onKeyPress):
		QtGui.QWidget.__init__(self, parent)
		
		self.name=name
		self.headers=headers
		self.winMain=wMain
		
		self.onKeyPress=onKeyPress
		
		self.txtFilter=QtGui.QLineEdit()
		self.lstSongs=SongList(parent, headers, onDoubleClick)
		
		frame=QtGui.QVBoxLayout()
		frame.addWidget(self.txtFilter)
		frame.addWidget(self.lstSongs)
		self.setLayout(frame)
		
		self.connect(self.txtFilter, QtCore.SIGNAL('textChanged(const QString&)'), self.txtFilterChange)
		self.connect(self.txtFilter, QtCore.SIGNAL('editingFinished()'), self.txtFilterQuit)
	
	_prevTxtFilter=None
	def timerEvent(self, event):
		if self.txtFilter.text()!=self._prevTxtFilter:
			self.filter()
	def keyPressEvent(self, event):
		self.onKeyPress(event)
	def txtFilterChange(self):
		if self._timerID==None:
			self._timerID=self.startTimer(500)
	def txtFilterQuit(self):
		if self._timerID:
			self.killTimer(self._timerID)
			self._timerID=None
	def update(self, songs):
		self.lstSongs.updateSongs(songs)
		if len(self.txtFilter.text()):
			self.filter()

	def selectedSongs(self):
		return self.lstSongs.selectedSongs()
	def selectedIds(self):
		return map(lambda song: song._data['id'], self.lstSongs.selectedSongs())
	def getSelItemID(self):
		try:
			return self.lstSongs.selectedSongs()[0].getID()
		except:
			return -1

	def filter(self):
		self.lstSongs.filter(str(self.txtFilter.text()).strip().lower())
	
	def colorID(self, id, clr):
		self.lstSongs.colorID(id, clr)
	
	def showColumn(self, column, show=True):
		self.lstSongs.showColumn(column, show)
	def selectRow(self, row):
		self.lstSongs.selectRow(row)
	def ensureVisible(self, id):
		self.lstSongs.ensureVisible(id)

class winMain(QtGui.QWidget):
	"Elements"
	" label with info"
	lblInfo=None
	" label with current status, at the bottom"
	lblStatus=None
	" lstLibrary of songs"
	lstLibrary=None
	" current lstPlaylist"
	lstPlaylist=None
	" slider for current time"
	slrTime=None
	" slider for volume"
	slrVolume=None
	" control buttons"
	btnPlayPause=None
	btnStop=None
	btnPrevious=None
	btnNext=None
	
	" system tray object"
	sysTray=None

	"Models"
	" model of the lstLibrary"
	mLibrary=None

	"Other vars"
	" array containing objects to disable/enable on disconnect/connect"
	disableObjects=None
	" current highlighted line"
	curLine=None
	_timerID=None

	def __init__(self, parent=None):
		QtGui.QWidget.__init__(self, parent)
		self.setWindowTitle("montypc - An MPD client")

		self.curLine=None

		" set GUI stuff"
		self.lstPlaylist=Playlist(parent, self, ['artist', 'title', 'album'], 'The Playlist'
				, self.onPlaylistDoubleClick, self.onPlaylistKeyPress)
		self.lstLibrary=Playlist(parent, self, ['song'], 'The Library'
				, self.onLibraryDoubleClick, self.onLibraryKeyPress)
		self.lblStatus=QtGui.QLabel()
		self.lblInfo=QtGui.QLabel()
		self.lblInfo.setMinimumWidth(400)
		self.txtFilterPlaylist=QtGui.QLineEdit()
		self.slrTime=QtGui.QSlider(QtCore.Qt.Horizontal, self)
		self.slrVolume=QtGui.QSlider(QtCore.Qt.Horizontal, self)
		self.slrVolume.setMaximum(100)
		self.slrVolume.setMinimumWidth(100)
		self.slrVolume.setMaximumWidth(400)
		self.btnPlayPause=Button("play", self.onBtnPlayPauseClick)
		self.btnStop=Button("stop", self.onBtnStopClick)
		self.btnPrevious=Button("prev", self.onBtnPreviousClick)
		self.btnNext=Button("next", self.onBtnNextClick)

		self.lstLibrary.showColumn(0,False)
		
		" set the layouts"
		window=QtGui.QVBoxLayout()
		tables=QtGui.QHBoxLayout()
		lib=QtGui.QVBoxLayout()
		plList=QtGui.QVBoxLayout()
		controls=QtGui.QHBoxLayout()
		info=QtGui.QHBoxLayout()
		self.setLayout(window)
		
		" add the widgets"
		window.addLayout(info)
		window.addLayout(controls)
		window.addLayout(tables)
		window.addWidget(self.lblStatus)
		tables.addWidget(self.lstLibrary)
		tables.addWidget(self.lstPlaylist)
		controls.addWidget(self.btnPrevious)
		controls.addWidget(self.btnPlayPause)
		controls.addWidget(self.btnStop)
		controls.addWidget(self.btnNext)
		controls.addWidget(self.slrTime)
		info.addWidget(self.lblInfo)
		info.addStretch()
		info.addWidget(self.slrVolume)

		self.resize(1024,960)

		self.disableObjects=[self.lstPlaylist, self.lstLibrary, self.slrTime
				, self.slrVolume
				, self.btnPlayPause, self.btnStop, self.btnPrevious
				, self.btnNext]

		" add event handlers"
		self.connect(self.slrVolume, QtCore.SIGNAL('valueChanged(int)'),
			self.onVolumeSliderChange)

		self.connect(self.slrTime, QtCore.SIGNAL('sliderReleased()'),
			self.onTimeSliderChange)

		monty.addListener('onSongChange', self.onSongChange)
		monty.addListener('onTimeChange', self.onTimeChange)
		monty.addListener('onStateChange', self.onStateChange)
		monty.addListener('onVolumeChange', self.onVolumeChange)
		monty.addListener('onReady', self.onReady)
		monty.addListener('onConnect', self.onConnect)
		monty.addListener('onDisconnect', self.onDisconnect)

		self.enableObjects(self.disableObjects, False)
		# set icon in system tray
		self.sysTray=QtGui.QSystemTrayIcon(QtGui.QIcon('gfx/icon.png'), parent)
		self.sysTray.show()
		self.connect(self.sysTray, QtCore.SIGNAL('activated (QSystemTrayIcon::ActivationReason)')
			, self.onSysTrayClick)

		wConnect=winConnect()
		wConnect.monitor()

		self.updatePlayingInfo()
		self.show()
		doEvents()


	
	def setStatus(self, status):
		self.lblStatus.setText(status)

	def updatePlayingInfo(self):
		status=monty.getStatus()
		curSong=monty.getCurrentSong()
		line=["Status:\t", "Song:\t", "Time:\t"]

		try:
			line[0]="%s%s"%(line[0], {'play':'playing', 'stop':'not playing', 'pause':'paused'}[status['state']])
			if status['state']!='stop':
				line[1]="%s%s by %s [%s]"% (line[1], curSong.getTitle(), curSong.getArtist(), curSong.getAlbum())
				line[2]="%s%s/%s" % (line[2], sec2min(self.slrTime.value()), sec2min(status['length']))
		except:
			pass
		# merge lines
		self.lblInfo.setText(reduce(lambda x, y: x+'\n'+y, line))

		self.sysTray.setToolTip("%s\n%s" % ('montypc', self.lblInfo.text()))

	_rowColorModifier=0
	_rowColorAdder=1
	def timerEvent(self, event):
		curSong=monty.getCurrentSong()
		if curSong:
			lst=self.lstPlaylist
			# color current playing song
			lst.colorID(curSong.getID(),
				QtGui.QColor(140-self._rowColorModifier*5,140-self._rowColorModifier*5,180))

			# make sure color changes nicely over time
			self._rowColorModifier=self._rowColorModifier+self._rowColorAdder
			if abs(self._rowColorModifier)>4:
				self._rowColorAdder=-1*self._rowColorAdder

	def addLibrarySelToPlaylist(self):
		paths=[]
		songs=self.lstLibrary.selectedSongs()
		cnt=len(songs)
		steps=5*cnt/100+1
		row=-1
		for song in songs:
			row+=1
			paths.append(song.getFilepath())

			if row % steps==0:
				self.setStatus('Adding '+str(cnt)+' songs to library ...'+str(int(100*row/cnt))+'%')
				doEvents()
		monty.addToPlaylist(paths)
		self.setStatus('')
		doEvents()
		self.fillPlaylist()

	def onSysTrayClick(self, reason):
		if self.isVisible():
			self.hide()
		else:
			self.show()

	def onPlaylistKeyPress(self, event):
		lst=self.lstPlaylist
		" remove selection from playlist using DELETE-key"
		if event.matches(QtGui.QKeySequence.Delete):
			ids=lst.selectedIds()
			self.setStatus('Deleting '+str(len(ids))+' songs from playlist ...')
			doEvents()

			monty.deleteFromPlaylist(ids)

			self.setStatus('')
			doEvents()

			self.fillPlaylist()
		return QtGui.QWidget.keyPressEvent(self, event)
	
	def onLibraryKeyPress(self, event):
		" add selection, or entire library to playlist using ENTER-key"
		if event.key()==QtCore.Qt.Key_Enter or event.key()==QtCore.Qt.Key_Return:
			self.addLibrarySelToPlaylist()
		return QtGui.QWidget.keyPressEvent(self, event)

	def enableObjects(self, objects, enable):
		for object in objects:
			object.setEnabled(enable)

	def onStateChange(self, params):
		self.updatePlayingInfo()
		newState=params['newState']

		self.enableObjects([self.slrTime, self.btnStop, self.btnNext, self.btnPrevious], newState!='stop')

		if newState=='play':
			self.btnPlayPause.setText('pause')
		elif newState=='pause' or newState=='stop':
			self.btnPlayPause.setText('play')

	def onTimeChange(self, params):
		self.updatePlayingInfo()
		if self.slrTime.isSliderDown()==False:
			self.slrTime.setValue(params['newTime'])

	def onSongChange(self, params):
		lst=self.lstPlaylist
		lst.colorID(int(params['newSongID']), clrRowSel)

		if params['newSongID']==-1:
			self.slrTime.setEnabled(False)
		else:
			try:
				self.slrTime.setMaximum(monty.getStatus()['length'])
				self.slrTime.setEnabled(True)
				lst.ensureVisible(params['newSongID'])
			except:
				pass
	
	def onVolumeChange(self, params):
		self.slrVolume.setValue(params['newVolume'])

	def onReady(self, params):
		self.initialiseData()
		self._timerID=self.startTimer(200)

	def onConnect(self, params):
		self.setStatus('Restoring library ...')
		doEvents()

	def initialiseData(self):
		self.setStatus("Retrieving library ...")
		doEvents()
		self.mLibrary=Library()
		doEvents()

		self.setStatus("Filling library ...")
		doEvents()
		self.fillLibrary()
		doEvents()
		
		self.setStatus("Filling playlist ...")
		doEvents()
		self.fillPlaylist()
		doEvents()
		
		self.setStatus("Doing the rest ...")
		doEvents()
		self.enableObjects(self.disableObjects, True)
		self.updatePlayingInfo()
		self.setStatus("")
		doEvents()

	
	def onDisconnect(self, params):
		self.enableObjects(self.disableObjects, False)


	def fillPlaylist(self):
		self.lstPlaylist.update(monty.listPlaylist())

	def fillLibrary(self):
		self.lstLibrary.update(self.mLibrary.list())
	
	def onLibraryDoubleClick(self):
		self.addLibrarySelToPlaylist()

	def onPlaylistDoubleClick(self):
		monty.play(self.lstPlaylist.getSelItemID())
	
	def onTimeSliderChange(self):
		monty.seek(self.slrTime.value())
	
	def onVolumeSliderChange(self):
		monty.setVolume(self.slrVolume.value())

	def onBtnPlayPauseClick(self):
		status=monty.getStatus()
		if status['state']=='play':
			monty.pause()
		elif status['state']=='stop':
			if self.lstPlaylist.getSelItemID()==-1:
				self.lstPlaylist.selectRow(0)
			self.onPlaylistDoubleClick()
		else:
			monty.resume()
		self.updatePlayingInfo()

	def onBtnStopClick(self):
		monty.stop()
		self.updatePlayingInfo()
	
	def onBtnPreviousClick(self):
		monty.previous()
		self.updatePlayingInfo()
	def onBtnNextClick(self):
		monty.next()
		self.updatePlayingInfo()