summaryrefslogtreecommitdiff
path: root/winMain.py
blob: c471c62411c1e6f5631a4be0378991124b0fa938 (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
from PyQt4 import QtGui, QtCore, QtSvg
from traceback import print_exc
import time
import sys

from misc import *
from clSettings import settings
from clMonty import monty

from winConnect import winConnect
from winSettings import winSettings

from wgSongList import SongList
from wgPlaylist import Playlist


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

class winMain(QtGui.QWidget):
	"""The winMain class is mpc's main window, showing the playlists and control-interface"""
	"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
	
	btnSettings=None
	
	" system tray object"
	sysTray=None

	"Other vars"
	" all objects which should be disabled when there is no connection"
	controlObjects=None

	" timerID created by startTimer"
	_timerID=None

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

		" 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)
		# set to some value that'll never be chosen, that way onChange will be called automatically :)
		self.slrVolume.setValue(3.141595)	
		self.svgVolume=QtSvg.QSvgWidget()
		self.svgVolume.resize(64,64)
		self.btnPlayPause=Button("play", self.onBtnPlayPauseClick, 'gfx/media-playback-start.svg', True)
		self.btnStop=Button("stop", self.onBtnStopClick, 'gfx/media-playback-stop.svg', True)
		self.btnPrevious=Button("prev", self.onBtnPreviousClick, 'gfx/media-skip-backward.svg', True)
		self.btnNext=Button("next", self.onBtnNextClick, 'gfx/media-skip-forward.svg', True)
		self.btnSettings=Button("settings", self.onBtnSettingsClick, 'gfx/gtk-preferences.svg')

		self.lstLibrary.showColumn(0,False)
		self.lstLibrary.setMode('library', 'artist/album')
		self.lstPlaylist.setMode('playlist')
		
		" 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)
		info.addWidget(self.svgVolume)
		info.addWidget(self.btnSettings)

		self.resize(1024,960)

		self.controlObjects=[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.controlObjects, False)
		self.setWindowIcon(appIcon)
		# set icon in system tray
		self.sysTray=QtGui.QSystemTrayIcon(appIcon, 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):
		"""Set the text of the statusbar."""
		self.lblStatus.setText(status)

	def updatePlayingInfo(self):
		"""Update status, current song, and current song time."""
		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):
		"""Add the library selection to the playlist."""
		songs=self.lstLibrary.selectedSongs()
		self.setStatus('Adding '+str(len(songs))+' songs to library ...')
		doEvents()

		# add filepaths of selected songs to path
		paths=map(lambda song: song.getFilepath(), songs)
		monty.addToPlaylist(paths)

		self.setStatus('')
		doEvents()
		self.fillPlaylist()

	def onSysTrayClick(self, reason):
		self.setVisible(not(self.isVisible()))

	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):
		if event.key()==QtCore.Qt.Key_Enter or event.key()==QtCore.Qt.Key_Return:
			# Add selection, or entire library to playlist using ENTER-key.
			self.addLibrarySelToPlaylist()
		return QtGui.QWidget.keyPressEvent(self, event)

	def enableObjects(self, objects, enable):
		"""Enables or disables all $objects"""
		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.changeIcon('gfx/media-playback-pause.svg')
			self.btnPlayPause.setText('pauze')
		elif newState=='pause' or newState=='stop':
			self.btnPlayPause.changeIcon('gfx/media-playback-start.svg')
			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 and playlist ...')
		doEvents()

	def initialiseData(self):
		"""Initialise the library, playlist and some other small things"""
		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.controlObjects, True)
		self.updatePlayingInfo()
		self.setStatus("")
		doEvents()

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

	def fillPlaylist(self):
		"""Fill the playlist."""
		self.lstPlaylist.update(monty.listPlaylist())

	def fillLibrary(self):
		"""Fill the library."""
		self.lstLibrary.update(monty.listLibrary())
	
	def onLibraryDoubleClick(self):
		self.addLibrarySelToPlaylist()

	def onPlaylistDoubleClick(self):
		monty.play(self.lstPlaylist.getSelItemID())
	
	def onTimeSliderChange(self):
		monty.seek(self.slrTime.value())
	
	def onVolumeSliderChange(self):
		v=self.slrVolume.value()
		monty.setVolume(v)
		if v<=1:
			mode='mute'
		else:
			mode=('0', 'min', 'med', 'max')[int(3*v/100)]
		self.svgVolume.load('gfx/stock_volume-%s.svg'%(mode))

	def onBtnPlayPauseClick(self):
		status=monty.getStatus()
		if status['state']=='play':
			monty.pause()
		elif status['state']=='stop':
			if self.lstPlaylist.getSelItemID()==-1:
				# if nothing selected, set it on first row
				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()
	
	def onBtnSettingsClick(self):
		self.winSettings=winSettings()
		self.winSettings.show()