Source

VPlayer / gui.py

Full commit
  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
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
# -*- coding: utf-8 -*-

import os
import sys
import copy
from time import sleep

import mutagen
from PyQt4 import QtGui
from PyQt4 import QtSql
from PyQt4 import QtCore

from logger import log
from login import Login
from track import Track
from length import Length
from lyrics import Lyrics
from vplayer import common
from options import Options
from minigui import MiniGui
from vplayer.about import About
from lastfm import GetTrackInfo
from lastfm import LastfmScrobbler
from resultsmodel import ResultsModel
from mainwindow_qt import Ui_MainWindow
from vplayer.fileloader import read_files
from searchprocessor import SearchProcessor
from guicomponents.playlists import Playlists
from guicomponents.fileswidget import FilesWidget
from guicomponents.searchwidget import SearchWidget
from guicomponents.controlwidget import ControlWidget
from guicomponents.playlistwidget import PlaylistWidget
from guicomponents.trackinfowidget import TrackinfoWidget
from guicomponents.collectionwidget import CollectionWidget



try:
    from shortcuts import Shortcuts
    XLIB_SHORTCUTS = True
except:
    XLIB_SHORTCUTS = False


class MainWindow(QtGui.QMainWindow):
    player = None
    lastfm = None
    last_track = 0
    tray_icon = None
    minigui = None
    track_info = None
    track_lyrics = None
    track_bitrate = None
    threads_to_kill_on_new_track = []
    plugins = []
    options = None
    pages = [] # list of tabs
    login_thread = None

    def __init__(self):
        QtGui.QMainWindow.__init__(self)
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self.ui.tabWidget.removeTab(0)


        from collectionmodel import CollectionModel


        settings = QtCore.QSettings()

        #loading player backend
        audio = settings.value('audio', QtCore.QVariant(1)).toInt()[0]
        if audio == 0:
            try:
                from vplayer.player_phonon import Player
            except:
                try:
                    from vplayer.player_gst import Player
                except:
                    QtGui.QMessageBox.critical(self, self.tr('Error'),
                                  self.tr('Could not load any player backend'))
        else:
            try:
                from vplayer.player_gst import Player
            except:
                try:
                    from vplayer.player_phonon import Player
                except:
                    QtGui.QMessageBox.critical(self, self.tr('Error'),
                                  self.tr('Could not load any player backend'))

        self.playlists_window = Playlists(self)

        #progressbar construction
        self.sbar_bar = QtGui.QProgressBar()
        self.sbar = QtGui.QStatusBar(self)
        self.sbar_label = QtGui.QLabel()
        self.sbar_label.setText('...')
        self.sbar_cancel = QtGui.QPushButton()
        self.sbar_cancel.setFixedWidth(25)
        self.sbar_cancel.setFixedHeight(25)
        self.sbar.addWidget(self.sbar_label)
        self.sbar.addWidget(self.sbar_bar)
        self.sbar.addWidget(self.sbar_cancel)
        self.sbar.setVisible(True)
        self.setStatusBar(self.sbar)
        self.sbar.setMaximumHeight(25)
        self.set_sbar('norm', self.tr('Waiting for user actions...'))


        self.icon_updater()

        self.connect_slots()

        self.slider_can_move = True

        self.last_track = 0

        #def make_mousepresser(view):
            #def mousepress(event):
                #"Save mouse click point"
                #if event.button() == QtCore.Qt.LeftButton:
                    #setattr(view, 'dragstart', copy.copy(event.pos()))
                #return QtGui.QTreeView.mousePressEvent(view, event)
            #return mousepress
        #self.playlistwidget.ui.playlist_view.mousePressEvent = \
                                    #make_mousepresser(self.playlistwidget.ui.playlist_view)

        #def make_mousemover(view):
            #def mousemove(event):
                #"Start drag if mouse moved move then 30 pixels left or right"
                #if not event.buttons() & QtCore.Qt.LeftButton:
                    #return QtGui.QTreeView.mouseMoveEvent(view, event)
                #start = getattr(view, 'dragstart')
                #if abs(event.x() - start.x()) < 50:
                    #view.scrollTo(view.indexAt(event.pos()))
                    #view.setSelection(QtCore.QRect(event.pos(), start),
                                        #QtGui.QItemSelectionModel.Rows | \
                                        #QtGui.QItemSelectionModel.Select)
                    #event.accept()
                    #return
                #else:
                    #return QtGui.QTreeView.mouseMoveEvent(view, event)
            #return mousemove
        #self.playlistwidget.ui.playlist_view.mouseMoveEvent = \
                                        #make_mousemover(self.playlistwidget.ui.playlist_view)



        self.collectionwidget = CollectionWidget(self)
        self.pages.append(self.collectionwidget)

        self.fileswidget = FilesWidget(self)
        self.pages.append(self.fileswidget)


        self.set_icons()

        vol = settings.value('player/volume', QtCore.QVariant(100)).toInt()[0]
        #self.ui.volumeSlider.setSliderPosition(vol)

        self.searchwidget = SearchWidget(self)
        self.search_processor = SearchProcessor()
        QtCore.QObject.connect(self.searchwidget, QtCore.SIGNAL('play'), self.play)
        #QtCore.QObject.connect(self.searchwidget, QtCore.SIGNAL('search'), self.play)
        QtCore.QObject.connect(self.search_processor, QtCore.SIGNAL('results'),
                               self.searchwidget.results_receiver)
        QtCore.QObject.connect(self.search_processor,
                               QtCore.SIGNAL('addresults'),
                               self.searchwidget.more_results_receiver)
        QtCore.QObject.connect(self.search_processor, QtCore.SIGNAL('progress'),
                               self.search_handler)
        QtCore.QObject.connect(self.searchwidget, QtCore.SIGNAL('search'),
                               self.search_processor.search_base)
        QtCore.QObject.connect(self.searchwidget, QtCore.SIGNAL('search_more'),
                               self.search_processor.search_more)
        self.search_processor.start()

        #insertTab ( int index, QWidget * page, const QString & label )
        self.pages.append(self.searchwidget)

        self.playlistwidget = PlaylistWidget(self)
        QtCore.QObject.connect(self.playlistwidget, QtCore.SIGNAL('play'), self.play)
        QtCore.QObject.connect(self.playlistwidget, QtCore.SIGNAL('guisearch'),
                               self.searchwidget.guisearch)
        QtCore.QObject.connect(self.playlistwidget, QtCore.SIGNAL('statusbar'),
                               lambda args: self.set_sbar(*args))
        QtCore.QObject.connect(self.searchwidget, QtCore.SIGNAL('add_tracks'),
                               self.playlistwidget.track_receiver)
        self.pages.append(self.playlistwidget)

        QtCore.QObject.connect(self, QtCore.SIGNAL('add_tracks'),
                               self.playlistwidget.track_receiver)
        QtCore.QObject.connect(self.fileswidget, QtCore.SIGNAL('add_tracks'),
                               self.playlistwidget.track_receiver)
        QtCore.QObject.connect(self.collectionwidget, QtCore.SIGNAL('add_tracks'),
                               self.playlistwidget.track_receiver)

        self.load_plugins()


        #self.playlistwidget.ui.playlist_view.keyReleaseEvent = self.playlist_keypress
        #self.searchwidget.ui.results_list.keyReleaseEvent = self.searchresults_keypress


        #context menus for tables
        #self.playlistwidget.ui.playlist_view.contextMenuEvent = self.playlist_context_menu

        self.resize_started = 3
        def make_resizer(view):
            def resizer(event):
                if not event.oldSize().width():
                    return
                coef = float(event.size().width())/event.oldSize().width()
                if self.resize_started:
                    self.resize_started -= 1
                    return
                if abs(coef) > 100 or abs(coef)<0.001:
                    return
                for n in range(3):
                    old = view.columnWidth(n)
                    o = float(old)/event.oldSize().width()
                    new = event.size().width()*o
                    if new <10:
                        new = 10
                    if new > 10000:
                        new = 100
                    view.setColumnWidth(n, new)
                event.accept()
            return resizer
        #self.searchwidget.ui.results_list.resizeEvent = make_resizer(self.ui.tableView)
        #self.playlistwidget.ui.playlist_view.resizeEvent = make_resizer(self.ui.tableView_2)

        self.player = Player()
        #self.connect(self.player, QtCore.SIGNAL('status'),) self.playing_processor)
        #self.connect(self.player, QtCore.SIGNAL('bitrate'),
                     #self._bitrate_receiver)
        self.connect(self.player, QtCore.SIGNAL('database_changed'),
                        self.collectionwidget.update)#collection_model.update)
        self.connect(self.player, QtCore.SIGNAL('status'),
                        self.icon_updater)
        self.connect(self.player, QtCore.SIGNAL('status'),
                     self.playlistwidget.status_receiver)
        self.player.start()

        if settings.value('lastfm/use', QtCore.QVariant(False)).toBool():
            self.connect_lastfm()



        self.set_shortcuts()

        self.control = ControlWidget(self)
        self.ui.control_box.layout().addWidget(self.control)
        QtCore.QObject.connect(self.control, QtCore.SIGNAL('control'),
                               self.playlistwidget.control)
        QtCore.QObject.connect(self.control, QtCore.SIGNAL('control'),
                               self.player.control)
        QtCore.QObject.connect(self.player, QtCore.SIGNAL('time'),
                               self.control.update_time)
        QtCore.QObject.connect(self.control, QtCore.SIGNAL('seek'),
                               self.player.seek)
        QtCore.QObject.connect(self.control, QtCore.SIGNAL('volume'),
                               self.volume)
        QtCore.QObject.connect(self.control.ui.minimode,
                               QtCore.SIGNAL('clicked()'),
                               self.minimode)
        QtCore.QObject.connect(self.control.ui.playlist,
                               QtCore.SIGNAL('clicked()'),
                               self.toggle_playlist)

        self.trackinfowidget = TrackinfoWidget(self)
        self.pages.append(self.trackinfowidget)
        QtCore.QObject.connect(self.player,
                               QtCore.SIGNAL('bitrate'),
                               self.trackinfowidget._bitrate_receiver)
        QtCore.QObject.connect(self.player,
                               QtCore.SIGNAL('status'),
                               self.trackinfowidget._status_receiver)

        QtCore.QObject.connect(self.player,
                               QtCore.SIGNAL('status'),
                               self.control.control_back)

        self.connect(self.ui.actionQuit,
                     QtCore.SIGNAL('triggered()'),
                     self.quit)

        self.connect(self.ui.actionOpen,
                     QtCore.SIGNAL('triggered()'),
                     self.open_file)

        self.connect(self.ui.actionAbout,
                     QtCore.SIGNAL('triggered()'),
                     self.about)

        self.connect(self.ui.actionOptions,
                      QtCore.SIGNAL("triggered()"),
                      self.show_options)

        #if XLIB_SHORTCUTS:
        self.register_xshortcuts()

        self.update_tabwidget()

        settings.beginGroup("MainWindow")
        self.ui.splitter.restoreState(settings.value("splitter").toByteArray())
        self.ui.tabWidget.setCurrentIndex(settings.value("tab").toInt()[0])
        self.resize(settings.value("size",
                            QtCore.QVariant(QtCore.QSize(800, 600))).toSize())
        self.move(settings.value("pos",
                            QtCore.QVariant(QtCore.QPoint(0, 0))).toPoint())
        self.ui.splitter.restoreState(settings.value("splitter").toByteArray())
        settings.endGroup()

        cookie = unicode(settings.value('cookies', QtCore.QVariant('')).toString())
        if not cookie:
            self.login()

        self.open_dialog = None

        self.about_window = About(self)


        self.playlists_window.autoload()

        #self.minigui = MiniGui(self)

    def update_tabwidget(self):
        self.ui.tabWidget.clear()
        for page in self.pages:
            if hasattr(page, 'update_columns'):
                page.update_columns()
            if self.ui.tabWidget_2.indexOf(page) != -1:
                continue
            self.ui.tabWidget.addTab(page)

    def register_xshortcuts(self, restart = False):
        log.debug("Registering X shortcuts...")
        if not XLIB_SHORTCUTS:
            log.error("No Xlib bindings found")
            return
        if restart:
            self.shortcuts_thread.stop()
            sleep(0.5)
        self.shortcuts_thread = Shortcuts()
        QtCore.QObject.connect(self.shortcuts_thread,
                               QtCore.SIGNAL("control"),
                               self.playlistwidget.control)
        QtCore.QObject.connect(self.shortcuts_thread,
                               QtCore.SIGNAL("control"),
                               self.player.control)
        self.shortcuts_thread.start()

    def open_file(self):
        if not self.open_dialog:
            self.open_dialog = QtGui.QFileDialog()
            self.open_dialog.setNameFilter(self.tr("Audio files (*.flac *.mp3 *.ogg *.wav *.wma)"))
        files = self.open_dialog.getOpenFileNames(self, self.tr("Open files"))
        tracks = read_files([unicode(name) for name in files])
        if tracks:
            self.emit(QtCore.SIGNAL('add_tracks'), tracks)

    def login(self):
        if self.login_thread:
            while self.login_thread.isRunning():
                sleep(0.1)
        sets = QtCore.QSettings()
        login = unicode(sets.value('login/email', QtCore.QVariant('')).toString())
        if not login:
            log.debug("No login in coonfig file: not logging in")
            return
        self.login_thread = Login()
        self.connect(self.login_thread, QtCore.SIGNAL('status'),
                     self.login_processor)
        self.login_thread.start()

    def login_processor(self, message = None):
        if message == 'start':
            self.set_sbar('prog', self.tr('Logging in...'), 0, (0,0))
        elif message == 'error':
            self.set_sbar('norm', self.tr('Could not login. Maybe connection problem.'))
        elif message == 'wronglogin':
            self.set_sbar('norm', self.tr('Could not login. Wrong login data.'))
        elif message == 'ok':
            self.set_sbar('norm', self.tr('Login successfull.'))
        else:
            self.set_sbar('norm', '')


    def connect_lastfm(self):
        if self.lastfm and self.lastfm.active: return
        self.lastfm = LastfmScrobbler()
        QtCore.QObject.connect(self.player, QtCore.SIGNAL('status'),
                               self.lastfm.signal_handler)
        self.lastfm.start()
        log.info('Lastfm scrobbler started')

    def set_shortcuts(self):
        copy = QtGui.QShortcut(self.playlistwidget.ui.playlist_view)
        copy.setKey(QtCore.Qt.CTRL + QtCore.Qt.Key_C)
        self.connect(copy, QtCore.SIGNAL('activated()'), self.copy_to_clipboard)

    def copy_to_clipboard(self):
        "Copy tracks clipboard."
        "If something selected in playlist and it is focues, copy selected"
        "If something selected in search list and it is focues, copy selected"
        "If none selected or none of above focused, copy current playing track"
        data = unicode()
        def copy_current_playing():
            if self.player:
                if self.player.track:
                    track = self.player.track
                    data = track.artist+u' - '+track.title
                    return data
            return None
        def copy_treeview_selected(view):
            rows = []
            for index in view.selectedIndexes():
                if index.row() not in rows:
                    rows.append(index.row())
            if len(rows):
                tracks = []
                for row in rows:
                    track = view.model().tracks[row]
                    tracks.append(track.artist + u' - ' + track.title)
                data = '\n'.join(tracks)
                return data
            else:
                return copy_current_playing()
        if self.playlistwidget.ui.playlist_view.hasFocus():
            data = copy_treeview_selected(self.playlistwidget.ui.playlist_view)
        elif self.searchwidget.ui.results_list.hasFocus():
            data = copy_treeview_selected(self.searchwidget.ui.search_view)
        else:
            data = copy_current_playing()
        clip = QtGui.QApplication.clipboard()
        clip.setText(data)


    def playlist_keypress(self, event):
        if event.key() == QtCore.Qt.Key_Delete:
            self.remove_from_playlist()
        elif event.key() == QtCore.Qt.Key_Return:
            indexes = []
            for index in self.playlistwidget.ui.playlist_view.selectedIndexes():
                if index.column() == 0:
                    if index.row() not in indexes:
                        indexes.append(index.row())
            indexes.sort()
            if len(indexes)>0:
                self.play(self.playlist_model.tracks[indexes[0]])

    def load_plugins(self):
        plugin_dir = common.get_plugins_dir()
        if os.path.exists(plugin_dir):
            sys.path.append(plugin_dir)
            from base_plugin import BasePlugin
            import inspect
            for fname in os.listdir(plugin_dir):
                if not fname.endswith(".py"):
                    continue
                module_name = fname[: -3]
                if module_name == "__init__" or module_name == 'base_plugin':
                    continue
                obj = __import__(module_name)
                for objn in dir(obj):
                    objm = getattr(obj, objn)
                    if inspect.isclass(objm):
                        if issubclass (objm, BasePlugin):
                            self.load_plugin(objm)

    def set_sbar(self, btype = 'norm', text = '...', prog = 0, range = (0,100)):
        if btype == 'norm':
            self.sbar_label.setText(text)
            self.sbar_bar.setVisible(False)
            self.sbar_cancel.setVisible(False)
        elif btype == 'prog':
            self.sbar_label.setText(text)
            self.sbar_bar.setVisible(True)
            self.sbar_bar.setRange(range[0], range[1])
            self.sbar_bar.setValue(prog)
            self.sbar_cancel.setVisible(True)

    def set_icons(self):

        icon_image = QtGui.QIcon()
        icon_image.addPixmap(QtGui.QPixmap(":/icons/icon-normal.svg"),
                             QtGui.QIcon.Normal, QtGui.QIcon.Off)
        self.setWindowIcon(icon_image)

        style = self.style()
        cancel_icon = style.standardIcon(QtGui.QStyle.SP_BrowserStop)

        #progressbar
        self.sbar_cancel.setIcon(cancel_icon)

        #playlist 2nd tabw setup
        self.ui.tabWidget_2.tabBar().hide()
        self.ui.tabWidget_2.hide()
        self.ui.tabWidget_2.removeTab(0)

        #search_icon = QtGui.QIcon()
        #search_icon.addPixmap(QtGui.QPixmap(":/icons/images/search.png"))
        #self.ui.tabWidget.setTabIcon(0, search_icon )

        #playlist_icon = QtGui.QIcon()
        #playlist_icon.addPixmap(QtGui.QPixmap(":/icons/images/playlist.png"))
        #self.ui.tabWidget.setTabIcon(1, playlist_icon )

        #collection_icon = QtGui.QIcon()
        #collection_icon.addPixmap(QtGui.QPixmap(":/icons/images/collection.png"))
        #self.ui.tabWidget.setTabIcon(2, collection_icon )

        #files_icon = QtGui.QIcon()
        #files_icon.addPixmap(QtGui.QPixmap(":/icons/images/hdd.png"))
        #self.ui.tabWidget.setTabIcon(3, files_icon )

        #info_icon = QtGui.QIcon()
        #info_icon.addPixmap(QtGui.QPixmap(":/icons/images/info.png"))
        #self.ui.tabWidget.setTabIcon(4, info_icon )

    def _connect(self, obj, slot_name, func):
        QtCore.QObject.connect(obj,QtCore.SIGNAL(slot_name), func)

    def connect_slots(self):
        ui = self.ui
        #self._connect(ui.pushButton_6,"clicked()",self.stop)
        #self._connect(ui.pushButton_7,"clicked()",self.pause)
        #self._connect(ui.pushButton_8,"clicked()",self.play_button)
        #self._connect(ui.pushButton_10,"clicked()",
        #                                    self.remove_from_playlist)
        #self._connect(ui.pushButton_11,"clicked()", self.show_minigui)
        self._connect(self.sbar_cancel,"clicked()",
                                            self.stop_search)
        #self._connect(ui.pushButton_14,"clicked()",
                                            #self.add_from_collection)



        #self._connect(ui.horizontalSlider,"sliderReleased()",self.seek)
        #self._connect(ui.horizontalSlider,"sliderPressed()",
                                                   #self.slider_pressed)
        #self._connect(ui.volumeSlider, "sliderMoved(int)", self.volume)
        self._connect(self.tray_icon,
                    "activated(QSystemTrayIcon::ActivationReason)",
                                                self.icon_clicked)

        #player control buttons
        #self._connect(ui.pushButton_18,"clicked()",self.play_prev)
        #self._connect(ui.pushButton_19,"clicked()",self.play_next)

        #add file to playlist
        #self._connect(ui.pushButton_20, "clicked()", self.add_file)

        #toggle playlist
        #self._connect(ui.pushButton_22, "clicked()", self.toggle_playlist)

        #self._connect(ui.tabWidget, "currentChanged(int)", self.tab_changed)

        self._connect(self, 'status', self.self_status_handler)

    def toggle_playlist(self, state = None):
        def show():
            if self.width()<970:
                self.resize(971, self.height())
                return
            self.ui.tabWidget_2.addTab(self.playlistwidget, '')
            self.ui.tabWidget_2.show()
        def hide():
            self.ui.tabWidget.addTab(self.playlistwidget)
            self.ui.tabWidget_2.hide()

        if state == 'show': show()
        elif state == 'hide': hide()
        else:
            if self.ui.tabWidget.indexOf(self.playlistwidget) > -1: show()
            else: hide()

    def volume(self, pos):
        if self.player:
            self.player.set_volume(pos)
        settings = QtCore.QSettings()
        settings.setValue('volume', QtCore.QVariant(pos))
        settings.sync()

    def show_options(self):
        log.debug('Trying to show options...')
        if not self.options:
            self.options = Options(parent = self)
        self.options.show()

    def icon_clicked(self, reason):
        if reason == QtGui.QSystemTrayIcon.MiddleClick:
            self.control.pause()
        if reason == QtGui.QSystemTrayIcon.Trigger:
            if self.isVisible():
                self.last_pos = self.pos()
                self.hide()
            else:
                self.move(self.last_pos)
                self.show()

    def search_handler(self, message):
        if message == 0:
            log.debug('Got search begin signal')
            self.set_sbar('prog', self.tr('Progress:'), 0, (0,0))
        elif message == 100:
            log.debug('Got search end signal')
            self.set_sbar('norm', self.tr('Search completed successfully.'))
        elif message == -1:
            log.debug('Got search error signal')
            self.set_sbar('norm', self.tr('Some error happened. Seach failed.'))
        elif message == -2:
            log.debug('Got nothing found signal')
            self.set_sbar('norm', self.tr('Nothing found.'))
        elif message == -3:
            self.set_sbar('norm', self.tr('You have not set login information. Can not search without it.'))
        elif message == -4:
            self.set_sbar('norm', self.tr('Your login information is not correct. Can not search.'))
        else:
            log.debug('Unhandled search status message: %s' % str(message))

    def fill_handler(self, message):
        if type(message) == int:
            self.set_sbar('prog',  self.tr('Progress:'),message,(0,100))
        elif message == 'done':
            self.set_sbar('norm',  self.tr('Playlist filled successfully.'))
        elif message == 'error':
            self.set_sbar('norm', self.tr('Could not fill playlist.'))
        elif message == 'begin':
            self.set_sbar('prog',  self.tr('Progress:'),0,(0,100))
        elif message == 'nologin':
            self.set_sbar('norm', self.tr('You have not set login information. Can not search without it.'))
        elif message == 'wronglogin':
            self.set_sbar('norm', self.tr('Your login information is not correct. Can not search.'))

    def play(self, track):
        self.control.update_track(track)
        log.debug('Starting player...')
        self.player.play_track(track, self.control.ui.volume.value())
        uselfm = QtCore.QSettings().value('lastfm/use', QtCore.QVariant(False))
        if uselfm.toBool():
            log.info('Submiting now_plaing to lastfm')
            if not self.lastfm:
                self.connect_lastfm()
            self.lastfm.now_playing(track)

    def stop(self):
        if self.player:
            self.player.stop()
            self.set_tray_icon('none')

    def playing_processor(self, status):
        self.emit(QtCore.SIGNAL('playerstatus'), status)

    def stop_search(self):
        self.search_processor.stop_search()

    def _error(self, message, title = None):
        if title is None:
            title =  self.tr('Error')
        if not message:
            return
        QtGui.QMessageBox.critical(None, title, message)

    def _message(self, message, title = None):
        if title is None:
            title =  self.tr('Information')
        if not message:
            return
        QtGui.QMessageBox.information(None, title, message)

    def show_minigui(self):
        if not self.minigui:
            self.minigui = MiniGui(self)
        self.hide()
        self.minigui.show()

    def self_status_handler(self, status):
        if status == 'playing_new_track':
            log.debug('Calling self._playing_new_track_processor')
            self._playing_new_track_processor()

    def _playing_new_track_processor(self):
        log.debug('_playing_new_track_processor called')
        self.ui.label_13.clear()
        self.ui.label_8.setText(self.tr('Unknown'))
        self.ui.label_12.setText(self.tr('Unknown'))
        self.ui.label_18.setText(self.tr('Unknown'))
        self.ui.textBrowser.clear()
        self.track_lyrics = None
        self.track_info = None
        for thread in self.threads_to_kill_on_new_track:
            thread.terminate()
        self.threads_to_kill_on_new_track = []
        #infoindex = 4
        #if self.separate_playlist:
        #    infoindex -= 1
        #if self.ui.tabWidget.currentIndex() == infoindex:
        self.fill_track_info()


    def fill_track_info(self):
        if self.player:
            if self.player.track:
                self.ui.label_6.setText(self.player.track.artist)
                self.ui.label_10.setText(self.player.track.title)
                self.get_track_lyrics(self.player.track)
                self.get_track_info(self.player.track)

    #def tab_changed(self, index):
        #infoindex = 4
        #if self.separate_playlist:
            #infoindex -= 1
        #if index == infoindex:
            #self.fill_track_info()

    def resizeEvent(self, event):
        if event.oldSize().width() == -1:
            if self.width() > 900: self.toggle_playlist('show')
            else: self.toggle_playlist('hide')
        if event.oldSize().width() > 900 and event.size().width() < 900:
            self.toggle_playlist('hide')
        if event.oldSize().width() < 900 and event.size().width() > 900:
            self.toggle_playlist('show')

    def closeEvent(self, event):
        sets = QtCore.QSettings()
        minimize = sets.value('MainWindow/minimize_on_close').toBool()
        if minimize:
            if self.isVisible():
                self.last_pos = self.pos()
                self.hide()
            event.ignore()
        else:
            event.accept()

    def quit(self):
        self.playlists_window.autosave()

        settings = QtCore.QSettings()
        settings.beginGroup("MainWindow")
        settings.setValue("size", QtCore.QVariant(self.size()))
        settings.setValue("pos", QtCore.QVariant(self.pos()))
        settings.setValue("tab", QtCore.QVariant(self.ui.tabWidget.currentIndex()))
        settings.setValue("splitter", QtCore.QVariant(self.ui.splitter.saveState()))
        settings.endGroup()
        settings.sync()

        self.playlistwidget.save_state()
        self.searchwidget.save_state()
        self.control.save_state()
        self.collectionwidget.save_state()

        if self.player:
            self.player.stop()
        if self.lastfm:
            self.lastfm.terminate()
        for thread in self.threads_to_kill_on_new_track:
            thread.terminate()
        if self.search_processor:
            self.search_processor.terminate()
        for plugin in self.plugins:
            plugin.terminate()

        self.tray_icon.hide()

        log.debug('Closing...')
        QtGui.QApplication.quit()


    def load_plugin(self, plugin):
        log.debug('Loading plugin %s' % unicode(plugin))
        instance = plugin(self)
        self.plugins.append(instance)
        instance.start()

    def add_from_collection(self):
        for index in self.ui.treeView.selectedIndexes():
            index = self.collection_model_proxy.mapToSource(index)
            item = index.internalPointer().data
            if isinstance(item, Track):
                self.playlist_model.add_data(copy.copy(item))
            elif isinstance(item, tuple):
                artist = self.collection_model.root.children[index.parent().row()].children
                album = artist[index.row()]
                for track in album.children:
                    self.playlist_model.add_data(copy.copy(track.data))
            elif isinstance(item, unicode):
                albums = self.collection_model.root.children[index.row()].children
                for album in albums:
                    for track in album.children:
                        self.playlist_model.add_data(copy.copy(track.data))

    def icon_updater(self, state = ('None', None)):
        """Slot for updating tray icon. Should be connected to player's status
        messages"""
        state = state[0]

        def menu():
            menu = QtGui.QMenu(self)
            menu.addAction(QtGui.QIcon(':/icons/images/play.png'),
                        self.tr('Play'), lambda: self.control.control('play'))
            menu.addAction(QtGui.QIcon(':/icons/images/pause.png'),
                        self.tr('Pause'), lambda: self.control.pause())
            menu.addAction(QtGui.QIcon(':/icons/images/stop.png'),
                        self.tr('Stop'), lambda: self.control.control('stop'))
            menu.addAction(QtGui.QIcon(':/icons/images/prev.png'),
                        self.tr('Previous'), lambda: self.control.control('previous'))
            menu.addAction(QtGui.QIcon(':/icons/images/next.png'),
                        self.tr('Next'), lambda: self.control.control('next'))
            menu.addAction(QtGui.QIcon(':/icons/images/exit.png'),
                        self.tr('Exit'), lambda: self.quit())
            return menu

        if not self.tray_icon:
            self.tray_icon = QtGui.QSystemTrayIcon()
            self.tray_icon.setContextMenu(menu())

        tray_icon_image = QtGui.QIcon()
        if state in ('paused', 'pause'):
            tray_icon_image.addPixmap(QtGui.QPixmap(":/icons/icon-pause.svg"),
                                      QtGui.QIcon.Normal, QtGui.QIcon.Off)
        elif state in ('playing', 'start', 'unpause'):
            tray_icon_image.addPixmap(QtGui.QPixmap(":/icons/icon-playing.svg"),
                                      QtGui.QIcon.Normal, QtGui.QIcon.Off)
        else:
            tray_icon_image.addPixmap(QtGui.QPixmap(":/icons/icon-normal.svg"),
                                      QtGui.QIcon.Normal, QtGui.QIcon.Off)
        self.tray_icon.setIcon(tray_icon_image)
        self.tray_icon.show()

    def scan_processor(self, message):
        if message == 'start':
            self.set_sbar('prog',  self.tr('Scanning collection:'), 0, (0,100))
        elif message == 'end':
            self.set_sbar('norm',  self.tr('Scan complete.'))
        else:
            self.set_sbar('prog',  self.tr('Scanning collection:'), message, (0,100))

    def about(self):
        self.about_window.show()

    def minimode(self):
        if not self.minigui:
            self.minigui = MiniGui(self)
        self.minigui.show()
        self.hide()