forked from newmonade/Foo.cd
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.py
488 lines (416 loc) · 17 KB
/
main.py
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
# -*- coding: utf-8 -*-
import sys
import os
from PyQt4.QtCore import Qt
from PyQt4.QtGui import (QWidget, QApplication, QFileDialog, QMessageBox)
from PyQt4 import QtCore
from PyQt4 import QtGui
from gi.repository import GObject
from gi.repository import Gst
from configparser import RawConfigParser
import song
from song import Song
import thread
from thread import WorkThread, WorkThreadPipe
from player import Player, ReplayGain
import widget
from widget import PlaybackButtons, SearchArea, VolumeSlider, Image, Equalizer, Retagging
from tree import Tree
from table_playlist import Table
from table_radio import TableRadio
class Foo(QtGui.QMainWindow):
def __init__(self):
super(Foo, self).__init__()
self.initUI()
def initUI(self):
config = Foo.readConfig('options')
self.timeOut = -1
self.radio = False
self.statusBar().showMessage('Ready')
self.createMenu()
self.setWindowTitle("Foo.cd")
self.player = Player(Foo.readConfig('audio'))
self.player.bus.connect('message::eos', self.stop)
self.player.bus.connect('message::duration-changed', self.onDurationChanged)
self.tree = Tree(self, config['tree_order'])
self.tree.addSongs.connect(self.addSongsFromTree)
self.tree.customContextMenuRequested.connect(self.tmpTag)
if not self.radio:
self.table=Table( self, config)
self.handlerATF = self.player.playbin.connect("about-to-finish", self.onAboutToFinish)
self.table.runAction.connect(self.tableAction)
else:
configRadio = Foo.readConfigRadios()
self.table=TableRadio( self, configRadio)
self.table.runAction.connect(self.tableAction)
self.handlerT = self.player.bus.connect('message::tag', self.table.onTag)
self.playbackButtons = PlaybackButtons(None)
self.playbackButtons.buttonPlay.clicked.connect(self.toggleSong)
self.playbackButtons.buttonStop.clicked.connect(self.stop)
self.playbackButtons.buttonPrev.clicked.connect(self.previous)
self.playbackButtons.buttonNext.clicked.connect(self.next)
self.volumeSlider = VolumeSlider(self)
self.scrollSlider = widget.createScrollSlider(self)
self.scrollSlider.sliderMoved.connect(self.player.seek)
self.scrollSlider.sliderPressed.connect(self.player.toggle)
self.scrollSlider.sliderReleased.connect(self.player.toggle)
self.volumeSlider.sliderMoved.connect(self.player.setVolume)
self.pixmap = Image(self, config['cover_names'], config['extensions'])
# Album cover connections
self.tree.selectionModel().selectionChanged.connect(lambda: self.pixmap.onSelectionChanged(self.tree.getChildren()[0].get('file', None)))
self.table.selectionModel().selectionChanged.connect(lambda: self.pixmap.onSelectionChanged(self.table.getSelection().get('file', None)))
self.searchArea = SearchArea(self)
self.searchArea.searchLine.returnPressed.connect(self.startSearch)
self.playbackButtons.addWidget(self.volumeSlider)
self.playbackButtons.addWidget(self.scrollSlider)
splitterLeftRight = QtGui.QSplitter()
self.splitterTopBottom = QtGui.QSplitter(Qt.Vertical, self)
self.infoFrame = QtGui.QFrame()
infoLayout = QtGui.QVBoxLayout()
infoLayout.setContentsMargins(0,0,0,0)
infoLayout.addLayout(self.playbackButtons)
infoLayout.addWidget(self.pixmap)
self.infoFrame.setLayout(infoLayout)
libLayout = QtGui.QVBoxLayout()
libLayout.setContentsMargins(0,0,0,0)
libLayout.addWidget(self.tree)
libLayout.addLayout(self.searchArea)
libFrame = QtGui.QFrame()
libFrame.setLayout(libLayout)
self.splitterTopBottom.addWidget(self.table)
self.splitterTopBottom.addWidget(self.infoFrame)
self.splitterTopBottom.setStretchFactor(0,3)
self.splitterTopBottom.setStretchFactor(1,1)
splitterLeftRight.addWidget(libFrame)
splitterLeftRight.addWidget(self.splitterTopBottom)
splitterLeftRight.setStretchFactor(0,2)
splitterLeftRight.setStretchFactor(1,3)
mainLayout = QtGui.QGridLayout()
mainLayout.setContentsMargins(4, 4, 4, 4)
mainLayout.addWidget(splitterLeftRight)
dummyWidget = QtGui.QWidget()
dummyWidget.setLayout(mainLayout)
self.setCentralWidget(dummyWidget)
self.setTabOrder(self.tree, self.table)
dictShortcuts = self.readConfig('shortcuts')
modifier = dictShortcuts['modifier']+'+'
self.shortQuit = QtGui.QShortcut(QtGui.QKeySequence(modifier+dictShortcuts['quit']), self, self.close)
self.shortStop = QtGui.QShortcut(QtGui.QKeySequence(modifier+dictShortcuts['stop']), self, self.stop)
self.shortPlayPause = QtGui.QShortcut(QtGui.QKeySequence(modifier+dictShortcuts['play_pause']), self, self.toggleSong)
self.shortSongPrevious = QtGui.QShortcut(QtGui.QKeySequence(modifier+dictShortcuts['previous']), self, self.previous)
self.shortSongNext = QtGui.QShortcut(QtGui.QKeySequence(modifier+dictShortcuts['next']), self, self.next)
self.shortVolDown = QtGui.QShortcut(QtGui.QKeySequence(modifier+dictShortcuts['volume_down']), self, self.volumeSlider.decr)
self.shortVolUp = QtGui.QShortcut(QtGui.QKeySequence(modifier+dictShortcuts['volume_up']), self, self.volumeSlider.incr)
self.shortRadioMode = QtGui.QShortcut(QtGui.QKeySequence(modifier+dictShortcuts['radio_mode']), self, self.toggleRadio)
self.shortEqualizer = QtGui.QShortcut(QtGui.QKeySequence(modifier+dictShortcuts['equalizer']), self, self.openEqualizer)
pipeWorker = WorkThreadPipe()
pipeWorker.hotKey.connect(self.onHotKey)
pipeWorker.start()
self.show()
def keyReleaseEvent(self, event):
if event.key() == Qt.Key_Alt:
self.menuBar().setVisible(not self.menuBar().isVisible())
else:
QWidget.keyPressEvent(self, event)
# Triggered by player end of stream event
# or called by hand to stop the stream
def stop(self, bus=None, msg=None):
self.player.stop()
self.scrollSlider.setValue(0)
self.table.displayPlayToStop()
self.stopStatusEmission('Ready')
def previous(self):
if self.table.playingId > 0:
self.player.stop()
self.table.playingId-=1
self.player.add(self.table.model().item(self.table.playingId,0).data()['file'])
self.player.play()
def next(self):
if self.table.model().rowCount()-1 > self.table.playingId:
self.player.stop()
self.table.playingId+=1
self.player.add(self.table.model().item(self.table.playingId,0).data()['file'])
self.player.play()
def toggleSong(self):
state = self.player.playbin.get_state(Gst.State.NULL)
if state[1] == Gst.State.PLAYING:
self.table.displayPlayToPause()
self.player.toggle()
status = self.statusBar().currentMessage().replace('Playing', 'Paused')
self.stopStatusEmission(status)
else:
self.table.displayPauseToPlay(self.table.playingId)
self.player.toggle()
#self.onDurationChanged(0,0)
status = self.table.getStatus()
self.setStatusEmission(status)
# Triggered by player when a song starts
def onDurationChanged(self, bus, msg):
self.table.displayNext()
print('Duration changed signal !')
# Triggered by player at the end of a song
def onAboutToFinish(self, bus):
if self.table.model().rowCount()-1 > self.table.playingId:
print('About to finish !')
self.table.playingId+=1
self.player.add(self.table.model().item(self.table.playingId,0).data()['file'])
def addSongsFromTree(self, list, play):
if not self.radio:
i = self.table.model().rowCount()
for l in list:
self.table.addRow(l)
self.table.resizeRowsToContents()
if play:
self.stop()
self.player.add(list[0]['file'])
self.player.play()
self.table.displayStopToPlay(i)
status = self.table.getStatus()
self.setStatusEmission(status)
def setStatusEmission(self, status):
if self.timeOut > 0:
GObject.source_remove(self.timeOut)
self.timeOut = GObject.timeout_add(1000, self.update, status)
def stopStatusEmission(self, status):
if self.timeOut > 0:
GObject.source_remove(self.timeOut)
self.timeOut = GObject.timeout_add(0, self.update, status)
self.timeOut=-1
def update(self, status):
print('.')
try:
duration_nanosecs = self.player.getDuration()
duration = float(duration_nanosecs) / 1000000000
self.scrollSlider.setRange(0, duration)
nanosecs = self.player.getPosition()
position = float(nanosecs) // 1000000000
self.scrollSlider.setValue(position)
m, s = divmod(position, 60)
self.statusBar().showMessage(status.replace('%',"%02d:%02d" % (m, s)))
except Exception as e:
print(e)
pass
if 'Playing' in status:
return True
else:
return False
def tableAction(self, str):
if str == 'stop':
self.stop()
elif str == 'play':
if self.table.selectedIndexes():
index = self.table.selectedIndexes()[0]
else:
index= self.table.model().index(self.table.selectionModel().currentIndex().row(),0)
songURI = index.model().itemFromIndex(index).data()['file']
self.player.stop()
self.player.add(songURI)
self.player.play()
self.table.displayStopToPlay(index.row())
status = self.table.getStatus()
self.setStatusEmission(status)
@staticmethod
def readConfig(section):
parser = RawConfigParser()
if getattr(sys, 'frozen', False):
# frozen
parser.read(os.path.dirname(os.path.realpath(sys.executable))+'/config')
else:
# unfrozen
parser.read(os.path.dirname(os.path.realpath(__file__))+'/config')
return dict(parser.items(section))
#Create menu bar
def createMenu(self):
self.menuBar()
self.menuBar().setVisible(False)
actionMenu = self.menuBar().addMenu('&Action')
scanMusicFolderAction = QtGui.QAction('Scan Music Folder', self)
showShortcutAction = QtGui.QAction('Show Shortcut',self)
addFolderToLibraryAction = QtGui.QAction('Add Folder to Library',self)
self.toggleRadioAction= QtGui.QAction('Switch to Radio mode',self)
if not self.radio:
self.toggleRadioAction.setText('Switch to Radio mode')
else:
self.toggleRadioAction.setText('Switch to Library mode')
#scanMusicFolderAction.setShortcut('Ctrl+N')
#scanMusicFolderAction.setStatusTip('Create new file')
scanMusicFolderAction.triggered.connect(self.scanMusicFolder)
actionMenu.addAction(scanMusicFolderAction)
showShortcutAction.triggered.connect(self.showShortcut)
actionMenu.addAction(showShortcutAction)
addFolderToLibraryAction.triggered.connect(self.addFolderToLibrary)
actionMenu.addAction(addFolderToLibraryAction)
self.toggleRadioAction.triggered.connect(self.toggleRadio)
actionMenu.addAction(self.toggleRadioAction)
# Menu Action 1
def scanMusicFolder(self):
self.thread = WorkThread(Foo.readConfig('options')['music_folder'], False)
self.thread.finished.connect(self.tree.initUI)
self.thread.start()
# Menu Action 2
def showShortcut(self):
dictSC = Foo.readConfig('shortcuts')
message = '''<b>'''+dictSC['modifier']+'''+'''+dictSC['stop']+'''</b> : Stop<br/>''' + '''
<b>'''+dictSC['modifier']+'''+'''+dictSC['quit']+'''</b> : Quit<br/>''' + '''
<b>'''+dictSC['modifier']+'''+'''+dictSC['play_pause']+'''</b> : Play/Pause <br/>''' + '''
<b>'''+dictSC['modifier']+'''+'''+dictSC['previous']+'''</b> : Previous<br/>''' + '''
<b>'''+dictSC['modifier']+'''+'''+dictSC['next']+'''</b> : Next<br/>''' + '''
<b>'''+dictSC['modifier']+'''+'''+dictSC['volume_down']+'''</b> : Volume down<br/>''' + '''
<b>'''+dictSC['modifier']+'''+'''+dictSC['volume_up']+'''</b> : Volume up<br/>''' + '''
<b>'''+dictSC['modifier']+'''+'''+dictSC['radio_mode']+'''</b> : Toggle radio mode<br/>''' + '''
<b>'''+dictSC['modifier']+'''+'''+dictSC['equalizer']+'''</b> : Equalizer<br/>'''
print(len(self.findChildren(QtCore.QObject)))
box = QMessageBox.about(self, 'About Shortcuts',
message)
print(len(self.findChildren(QtCore.QObject)))
print('must delete')
# Menu Action3
# Must be subdirectory of music folder otherwise wont be rescanned
def addFolderToLibrary(self):
dir = QFileDialog.getExistingDirectory(None,
"Open Directory",
Foo.readConfig('options')['music_folder'],
QFileDialog.ShowDirsOnly
| QFileDialog.DontResolveSymlinks)
self.thread = WorkThread(dir, True)
self.thread.finished.connect(self.tree.initUI)
self.thread.start()
# Menu Action4
def toggleRadio(self):
self.table.deleteLater()
self.table.close()
if not self.radio:
configRadio = Foo.readConfig('radios')
self.table=TableRadio(self.tree, configRadio)
self.toggleRadioAction.setText('Switch to Library mode')
self.radio=True
self.player.playbin.disconnect(self.handlerATF)
self.handlerT=self.player.bus.connect('message::tag', self.table.onTag)
else:
config = Foo.readConfig('options')
self.table=Table( self.tree, config)
self.toggleRadioAction.setText('Switch to Radio mode')
self.radio=False
self.handlerATF = self.player.playbin.connect("about-to-finish",self.onAboutToFinish)
self.player.bus.disconnect(self.handlerT)
self.splitterTopBottom.addWidget(self.table)
# Since the frame is already attached to the splitter,
# it only moves it to the new position
self.splitterTopBottom.addWidget(self.infoFrame)
self.splitterTopBottom.setStretchFactor(0,3)
self.splitterTopBottom.setStretchFactor(1,1)
self.table.runAction.connect(self.tableAction)
self.setTabOrder(self.tree, self.table)
@QtCore.pyqtSlot()
def startSearch(self):
input = self.searchArea.searchLine.text()
db = thread.load()
songList = []
songGenerator = (Song(self.tree.comm, **dict) for dict in db)
self.tree.model().removeRows(0, self.tree.model().rowCount())
if self.searchArea.searchExact.isChecked():
songList = [ e for e in songGenerator if e.exactMatch(input) ]
elif self.searchArea.searchPrecise.isChecked():
songList = [ e for e in songGenerator if e.preciseMatch(input) ]
else:
songList = [ e for e in songGenerator if e.fuzzyMatch(input) ]
del db[:]
songList.sort(key=self.tree.sortFunc)
self.tree.populateTree(songList)
@QtCore.pyqtSlot(str)
def onHotKey(self, key):
print('Hotkey was pressed', key)
if key == 'quit':
self.shortQuit.activated.emit()
if key == 'stop':
self.shortStop.activated.emit()
if key == 'play_pause':
self.shortPlayPause.activated.emit()
if key == 'volume_up':
self.shortVolUp.activated.emit()
if key == 'volume_down':
self.shortVolDown.activated.emit()
if key == 'song_next':
self.shortSongNext.activated.emit()
if key == 'song_prev':
self.shortSongPrev.activated.emit()
if key == 'tree_up':
if self.radio:
self.table.keyPressEvent(QtGui.QKeyEvent(QtCore.QEvent.KeyPress, Qt.Key_Up, Qt.KeyboardModifier(), ''))
else:
self.tree.keyPressEvent(QtGui.QKeyEvent(QtCore.QEvent.KeyPress, Qt.Key_Up, Qt.KeyboardModifier(), ''))
if key == 'tree_down':
if self.radio:
self.table.keyPressEvent(QtGui.QKeyEvent(QtCore.QEvent.KeyPress, Qt.Key_Down, Qt.KeyboardModifier(), ''))
else:
self.tree.keyPressEvent(QtGui.QKeyEvent(QtCore.QEvent.KeyPress, Qt.Key_Down, Qt.KeyboardModifier(), ''))
if key == 'tree_left':
if not self.radio:
self.tree.keyPressEvent(QtGui.QKeyEvent(QtCore.QEvent.KeyPress, Qt.Key_Left, Qt.KeyboardModifier(), ''))
if key == 'tree_right':
if not self.radio:
self.tree.keyPressEvent(QtGui.QKeyEvent(QtCore.QEvent.KeyPress, Qt.Key_Right, Qt.KeyboardModifier(), ''))
if key == 'tree_validate':
if self.radio:
self.table.keyPressEvent(QtGui.QKeyEvent(QtCore.QEvent.KeyPress, Qt.Key_Return, Qt.KeyboardModifier(), ''))
else:
self.tree.keyPressEvent(QtGui.QKeyEvent(QtCore.QEvent.KeyPress, Qt.Key_Return, Qt.KeyboardModifier(), ''))
if key == 'tree_append':
if not self.radio:
self.tree.keyPressEvent(QtGui.QKeyEvent(QtCore.QEvent.KeyPress, Qt.Key_Return, Qt.KeyboardModifier(QtCore.Qt.ShiftModifier), ''))
if key == 'radio_mode':
self.shortRadioMode.activated.emit()
def tmpTag(self, position):
menu = QtGui.QMenu()
tagging = QtGui.QAction('Tagging',self)
replayGain = QtGui.QAction('ReplayGain',self)
tagging.triggered.connect(self.openTagging)
replayGain.triggered.connect(self.startReplayGain)
menu.addAction(tagging)
menu.addAction(replayGain)
menu.exec_(self.tree.viewport().mapToGlobal(position))
def startReplayGain(self):
children = self.tree.getChildren()
self.RG = ReplayGain([x['file'] for x in children])
self.RG.exec_()
def openTagging(self):
children = self.tree.getChildren()
#[7:] to drop the 'file://' appended for gstreamer
retag = Retagging([x['file'][7:] for x in children])
res = retag.exec_()
if res:
self.tree.initUI()
print(res)
def openEqualizer(self):
from configparser import RawConfigParser
equa = Equalizer(self, Foo.readConfig('audio'))
equa.equalize.connect(self.applyEqua)
if equa.exec_():
parser = RawConfigParser()
parser.read(os.path.dirname(os.path.realpath(__file__))+'/config')
parser['audio']['settings']= str(equa.config)
with open(os.path.dirname(os.path.realpath(__file__))+'/config', 'w') as configfile:
parser.write(configfile)
def applyEqua(self,band, value):
print('receiving equa', str(band), value)
if str(band) == 'band0' and value == 0:
self.player.equalizer.set_property('band0', 0.01)
else:
self.player.equalizer.set_property(str(band), value)
def main():
app = QApplication(sys.argv)
ex = Foo()
sys.exit(app.exec_())
if __name__ == '__main__':
'''import cProfile, pstats, io
pr = cProfile.Profile()
pr.enable()
main()
pr.disable()
s = io.StringIO()
sortby = 'cumulative'
ps = pstats.Stats(pr, stream=s).sort_stats(sortby)
ps.print_stats()
print(s.getvalue())
'''
main()