码迷,mamicode.com
首页 > 其他好文 > 详细

小例子

时间:2015-07-16 15:36:57      阅读:152      评论:0      收藏:0      [点我收藏+]

标签:

#!/usr/bin/env python3

 

# LICENSING TERMS:

# This program is free software; you may modify and redistribute it under

# the terms of the MIT License.

 

# This program should have included a copy of the license for

# your convenience.

 

# Python 2 compatibility

from __future__ import print_function

 

# Import all those little necessities that Akane needs to run:

import os.path

from os import system

import sys

 

if sys.version_info[0] >= 3:

    def unicode(data):

        return str(data)

 

try: __file__

except: __file__ = sys.executable

app_lib = os.path.dirname(os.path.realpath(__file__))

sys.path.append(app_lib)

app_icons = os.path.join(app_lib, "icons")

 

from TranslationManager import *

 

from xml.sax.saxutils import escape, quoteattr

 

try: from urllib.parse import unquote, quote

except ImportError:

    try: from urllib import unquote, quote

    except:

        doNothing()

 

try: from urllib.request import urlretrieve

except ImportError:

    try: from urllib import urlretrieve

    except:

        doNothing()

 

import arietta_pyqt4

from RWebView import *

from QAkaneGeneric import *

from AWebBrowser import *

from AMovableWidgets import *

from DownloadManager import *

from ATimeEdit import *

from SystemTerminal import *

from QMoodbar import *

from QMediaProgressBar import *

from arietta_pyqt4 import *

from arietta import *

 

downloadManagerGUI = None

 

if sys.platform.startswith("win"):

    from mainwindow import Ui_MainWindow

 

def doNothing():

    return

 

import json

from json import load, dump

import pickle

from subprocess import Popen, PIPE

aria2 = False

try: aria2 = Popen(["which", "aria2c"], stdout=PIPE).communicate()[0]

except:

    do_nothing()

axel = False

try: axel = Popen(["which", "axel"], stdout=PIPE).communicate()[0]

except:

    do_nothing()

 

mainFolder = os.path.expanduser("~")

app_home = os.path.expanduser(os.path.join("~", ".app-data"))

app_webbrowser = None

app_homepage = "about:blank"

app_unity = "no"

if sys.platform.startswith("linux"):

    app_unity = readTerminalOutput("echo $DESKTOP_SESSION")

app_name = "Untitled Application"

version = "of unknown variety"

codename = "Anonymous"

mobile_ua = "Mozilla/5.0 (Linux; U; Android 2.2; en-us; Nexus One Build/FRF91) AppleWebKit/533.1 (KHTML, like Gecko) Version/4.0 Mobile Safari/533.1"

metadatafile = os.path.join(app_lib, "info.json")

required_collection_type = 0

collection_type = 0

unix_icon = os.path.join(app_lib, "icons", "akane_logo-unix.svg")

 

if os.path.exists(metadatafile):

    readfile = open(metadatafile, "r")

    metadata = load(readfile)

    readfile.close()

    try: app_name = unicode(metadata["app_name"])

    except:

        doNothing()

    try: app_homepage = unicode(metadata["app_homepage"])

    except:

        doNothing()

    try: version = unicode(metadata["major_version"]) + "." + unicode(metadata["minor_version"]) + "." + unicode(metadata["update"])

    except:

        doNothing()

    try: codename = metadata[‘codename‘]

    except:

        doNothing()

    try: required_collection_type = metadata[‘required_collection_type‘]

    except: doNothing()

    try: app_home = os.path.expanduser(os.path.join("~", metadata[‘app_home‘]))

    except:

        doNothing()

 

if os.path.exists(os.path.join(app_home, "profile.json")):

    readfile = open(os.path.join(app_home, "profile.json"), "r")

    collection_type = load(readfile)

    readfile.close()

    os.remove(os.path.join(app_home, "profile.json"))

if os.path.exists(os.path.join(app_home, "profilev.json")):

    readfile = open(os.path.join(app_home, "profilev.json"), "r")

    collection_type = load(readfile)

    readfile.close()

 

import random

if sys.version_info[0] <= 2:

    import string

import webbrowser

 

if sys.version_info[0] >= 3:

    import stagger

    globalSettingsFile = os.path.join(app_home, "settings.json")

else:

    import id3, mutagen

    globalSettingsFile = os.path.join(app_home, "settings.json")

try: from PyQt4 import QtGui, QtCore, QtNetwork, QtWebKit

except:

    if sys.version_info[0] >= 3:

        args = ""

        for arg in sys.argv:

            args = args + " " + arg

        system("python \"" + os.path.realpath(__file__) + "\"" + args)

        sys.exit()

    else:

        from Tkinter import *

        root = Tk()

        root.title("Error!")

        w = Label(root, text="In order to run properly, " + app_name + " requires PyQt4 to be installed\n(ideally for Python 3). Please install PyQt4 and try again!")

        w.pack()

        button = Button(root, text="OK", command=sys.exit)

        button.pack()

        root.mainloop()

else:    

    from PyQt4.phonon import Phonon

    if not sys.platform.startswith("win"):

        from PyQt4 import uic

if not sys.platform.startswith("win"):

    import moodbar

 

app_cookiejar = QtNetwork.QNetworkCookieJar(QtCore.QCoreApplication.instance())

 

extensions = [".mp3", ".m3a", ".mka", ".mkv", ".m4a", ".ogg", ".ogv",\

".oga", ".wav", ".mid", ".midi", ".mp4", ".flv", ".m3a", "mp2",\

".webm", ".3gp", ".act", ".aac", ".aiff", ".flac", ".raw", ".vox",\

".wma", ".ape", ".m2a", ".mpg", ".mpeg", ".mpeg2", ".mpeg1", ".mpg2"]

 

mimetypes = ["audio/mpeg",  "video/mpeg", "audio/midi",\

"audio/x-wav", "audio/vnd.wave", "audio/ogg", "video/ogg", \

"audio/vorbis", "audio/flac", "audio/webm", "video/webm", \

"audio/x-ms-wma", "audio/x-ms-wax", "video/x-ms-wmv", \

"video/x-matroska", "audio/x-matroska",\

"audio/mp4", "video/mp4", "video/quicktime"]

 

def getMimeType(filename):

    return arietta_pyqt4.getMimeType(filename)

 

def showWebBrowser():

    app_webbrowser.show()

 

def showDownloadManagerGUI():

    downloadManagerGUI.show()

 

if os.path.exists(os.path.join(app_lib, "plugins")):

    sys.path.append(os.path.join(app_lib, "plugins"))

    if os.path.exists(os.path.join(app_lib, "plugins", "modules")):

        sys.path.append(os.path.join(app_lib, "plugins", "modules"))

if os.path.exists(os.path.join(app_home, "plugins")):

    sys.path.append(os.path.join(app_home, "plugins"))

    if os.path.exists(os.path.join(app_home, "plugins", "modules")):

        sys.path.append(os.path.join(app_home, "plugins", "modules"))

 

def getTags(path, l=True):

    return arietta_pyqt4.getTags(path, l)

 

class ADialog(QDeletableDialog):

    pass

 

class ClickableLabel(QClickableLabel):

    pass

 

class MoodbarView(QMoodbar):

    pass

 

class MoodbarWriter(QMoodbarThread):

    pass

 

moodbarWriter = MoodbarWriter()

 

class AkSlider(QMediaProgressBar):

    pass

 

class PlaylistList(arietta_pyqt4.QPlaylist):

    def __init__(self, parent = None):

        super(PlaylistList, self).__init__()

        self.setParent(parent)

        self.acceptDrops = True

        self.fromHere = False

    def rewritePlaylist(self):

        playlistFile = os.path.join(app_home, "playlist.akp")

        self.savePlaylistTo(playlistFile)

    def endDropEvent(self):

        self.rewritePlaylist()

 

class CollectionBuilder(QtCore.QThread):

    collectionRebuilt = QtCore.pyqtSignal()

    def __init__(self, parent=None):

        QtCore.QThread.__init__(self, parent)

        self.folderList = []

    def exec_(self):

        self.rebuildCollection()

    def run(self):

        self.rebuildCollection()

        print(tr(‘collectionYay‘))

    def rebuildCollection(self):

        collectionManager.folders = []

        for line in range(len(self.folderList)):

            collectionManager.folders.append(unicode(self.folderList[line]))

        collectionManager.save()

        collectionManager.collection = []

        print(tr(‘preparingScan‘), collectionManager.folders)

        for folder in collectionManager.folders:

            if os.path.exists(folder):

                if os.path.isdir(folder):

                    self.recursiveCollectionBuild(folder)

                else:

                    add = False

                    if not sys.platform.startswith("win"):

                        m = getMimeType(folder)

                        for mimetype in mimetypes:

                            if m == mimetype:

                                add = True

                                break

                    if add == False:

                        for extension in extensions:

                            if unicode(folder).lower().endswith(extension):

                                add = True

                                break

                    if add == True:

                        collectionManager.advancedAppend(folder)

        collectionManager.save()

        self.collectionRebuilt.emit()

    def recursiveCollectionBuild(self, folder=""):

        if os.path.exists(folder) and os.path.isdir(folder):

            contents = os.listdir(folder)

            for fname in contents:

                if os.path.exists(os.path.join(folder, fname)):

                    if os.path.isdir(os.path.join(folder, fname)):

                        self.recursiveCollectionBuild(os.path.join(folder, fname))

                    else:

                        add = False

                        if not sys.platform.startswith("win"):

                            m = getMimeType(os.path.join(folder, fname))

                            for mimetype in mimetypes:

                                if m == mimetype:

                                    add = True

                                    break

                        if add == False:

                            for extension in extensions:

                                if unicode(os.path.join(folder, fname)).lower().endswith(extension):

                                    add = True

                                    break

                        if add == True:

                            collectionManager.advancedAppend(unicode(os.path.join(folder, fname)))

 

class CollectionManager():

    def __init__(self):

        self.version = ""

        self.folders = []

        self.collection = []

        self.path = ""

        self.app_home = app_home

        self.reload()

    def reload(self):

        if os.path.exists(os.path.join(self.app_home, "collection.json")):

            newCollectionFile = open(os.path.join(self.app_home, "collection.json"), "r")

            self.collection = load(newCollectionFile)

            newCollectionFile.close()

            newFoldersFile = open(os.path.join(self.app_home, "folders.json"), "r")

            self.folders = load(newFoldersFile)

            newFoldersFile.close()

    def save(self):

        collectionFile = open(os.path.join(self.app_home, "collection.json"), "w")

        dump(self.collection, collectionFile)

        collectionFile.close()

        foldersFile = open(os.path.join(self.app_home, "folders.json"), "w")

        dump(self.folders, foldersFile)

        foldersFile.close()

        profileFile = open(os.path.join(self.app_home, "profilev.json"), "w")

        dump(required_collection_type, profileFile)

        profileFile.close()

    def append(self, path, title=tr(‘untitled‘), artist=tr(‘unknownArtist‘), album=tr(‘unknownAlbum‘), year=tr(‘unknownYear‘), genre=tr(‘unknownGenre‘), length=0):

        try: self.collection.append({‘path‘ : unicode(path), ‘title‘ : unicode(title), ‘artist‘ : unicode(artist), ‘album‘ : unicode(album), ‘year‘ : unicode(year), ‘date‘ : unicode(year), ‘genre‘ : unicode(genre), ‘length‘ : unicode(length)})

        except:

            print(tr(‘trackFail‘), path)

    def advancedAppend(self, path):

        tags = getTags(path, False)

        title = tags[‘title‘]

        artist = tags[‘artist‘]

        album = tags[‘album‘]

        date = tags[‘date‘]

        genre = tags[‘genre‘]

        length = tags[‘length‘]

        self.append(path, title, artist, album, date, genre, length)

        

collectionManager = CollectionManager()

collectionBuilder = CollectionBuilder()

 

class CollectionList(arietta_pyqt4.QCollectionList):

    pass

 

class XSPFReader(arietta_pyqt4.XSPFReader):

    pass

 

xspfReader = XSPFReader()

 

class SettingsManager():

    def __init__(self):

        if sys.platform.startswith(‘win‘):

            self.settings = {"messagesOn" : True, ‘showMenuBar‘ : True, "cTitleBar" : True, "wikipediaOff" : False, "lastfmOff" : False, "lyricsOff" : False, "lyricSource" : False, "jamendoOff" : False, "ngOff" : False}

        else:

            self.settings = {"messagesOn" : True, "cTitleBar" : False, ‘showMenuBar‘ : True, "wikipediaOff" : False, "lastfmOff" : False, "lyricsOff" : False, "lyricSource" : False, "jamendoOff" : False, "ngOff" : False}

 

settingsManager = SettingsManager()

 

def writeSettings(self):

    settingsFile = open(globalSettingsFile, "w")

    dump(settingsManager.settings, settingsFile)

    settingsFile.close()

 

def loadSettings():

    global settingsManager

    if os.path.exists(globalSettingsFile):

        settingsFile = open(globalSettingsFile, "r")

        settingsManager.settings = load(settingsFile)

        settingsFile.close()

 

if os.path.exists(globalSettingsFile):

    loadSettings()

 

# The ADialogHandler class (which borrows heavily from Komichi) is meant to provide an easier way to load different types of dialog as Akane becomes more complex. However, since Akane is still quite simple, including ADialogHandler seems a bit like overkill for a program of its size:

 

class ADialogHandler(QtGui.QMainWindow):

    def __init__(self):

        super(ADialogHandler, self).__init__()

        self.seizedFocus = False

 

        # Define about dialog

        self.about = AMovableWindow()

        panel = QtGui.QWidget()

        self.about.setCentralWidget(panel)

        layout = QtGui.QVBoxLayout()

        panel.setLayout(layout)

        self.winIcon = QtGui.QLabel()

        self.winIcon.setAlignment(QtCore.Qt.AlignCenter)

        self.winIcon.setFixedWidth(192)

        self.winIcon.setFixedHeight(219)

        layout.addWidget(self.winIcon)

        layout.setAlignment(self.winIcon, QtCore.Qt.AlignCenter)

        self.aboutLabel = QtGui.QLabel()

        self.aboutLabel.linkActivated.connect(self.openLink)

        self.aboutLabel.setAlignment(QtCore.Qt.AlignCenter)

        layout.addWidget(self.aboutLabel)

        self.aboutButtons = QtGui.QDialogButtonBox()

        self.aboutButtons.addButton(tr(‘license‘), QtGui.QDialogButtonBox.ActionRole)

        self.aboutButtons.addButton(tr(‘close‘), QtGui.QDialogButtonBox.ActionRole)

        self.aboutButtons.clicked.connect(self.aboutButtonClicked)

        layout.addWidget(self.aboutButtons)

        hideAboutAction = QtGui.QAction(self)

        hideAboutAction.triggered.connect(self.about.hide)

        hideAboutAction.setShortcut("Esc")

        self.about.addAction(hideAboutAction)

        self.about.setWindowModality(QtCore.Qt.ApplicationModal)

        self.about.layout().setSizeConstraint(QtGui.QLayout.SetFixedSize)

        panel.layout().setSizeConstraint(QtGui.QLayout.SetFixedSize)

 

        # Define license dialog

        self.license = AMovableWindow()

        self.licenseToolBar = QtGui.QToolBar(tr(‘licensingToolBar‘))

        self.licenseToolBar.setStyleSheet("QToolBar { background: palette(window); }")

        self.licenseToolBar.setMovable(False)

        self.license.addToolBar(self.licenseToolBar)

        self.licenseToolBar.setToolButtonStyle(QtCore.Qt.ToolButtonTextOnly)

        self.licenseToolBar.setContextMenuPolicy(QtCore.Qt.CustomContextMenu)

        self.license.setWindowTitle(tr(‘licensingTerms‘))

        akaneAction = QtGui.QAction("" + app_name + "", self)

        akaneAction.setShortcut("Alt+A")

        akaneAction.setToolTip("<b>" + tr(‘licensingFor‘) + " " + app_name + "</b><br>Alt+A")

        akaneAction.triggered.connect(self.akaneLicense)

        self.licenseToolBar.addAction(akaneAction)

        qtAction = QtGui.QAction("Qt", self)

        qtAction.setShortcut("Alt+Q")

        qtAction.setToolTip("<b>" + tr(‘licenseQt‘) + "</b><br>Alt+Q")

        qtAction.triggered.connect(self.qtLicense)

        self.licenseToolBar.addAction(qtAction)

        pyqtAction = QtGui.QAction("PyQt", self)

        pyqtAction.setShortcut("Alt+P")

        pyqtAction.setToolTip("<b>" + tr(‘licensePyQt‘) + "</b><br>Alt+P")

        pyqtAction.triggered.connect(self.pyqtLicense)

        self.licenseToolBar.addAction(pyqtAction)

        mutagenAction = QtGui.QAction("Mutagen", self)

        mutagenAction.setShortcut("Alt+M")

#        mutagenAction.setToolTip("<b>" + tr(‘licensemutagen‘) + "</b><br>Alt+Q")

        mutagenAction.triggered.connect(self.mutagenLicense)

        self.licenseToolBar.addAction(mutagenAction)

        staggerAction = QtGui.QAction("Stagger", self)

        staggerAction.setShortcut("Alt+S")

        staggerAction.setToolTip("<b>" + tr(‘licenseStagger‘) + "</b><br>Alt+S")

        staggerAction.triggered.connect(self.staggerLicense)

        self.licenseToolBar.addAction(staggerAction)

#        self.licenseToolBar.addSeparator()

        self.eLabel = QtGui.QLabel("")

        self.eLabel.setSizePolicy(QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Preferred)

        self.licenseToolBar.addWidget(self.eLabel)

        sourceAction = QtGui.QAction(tr(‘sourceCode‘), self)

        sourceAction.setShortcut("Alt+C")

        sourceAction.setToolTip("<b>" + tr(‘sourceSources‘) + "</b><br>Alt+C")

        sourceAction.triggered.connect(self.sourceCode)

        self.licenseToolBar.addAction(sourceAction)

 

        self.license.addToolBarBreak()

 

        self.lToolBar = QtGui.QToolBar()

        self.lToolBar.setMovable(False)

        self.lToolBar.setContextMenuPolicy(QtCore.Qt.CustomContextMenu)

        self.lToolBar.setStyleSheet("QToolBar { background: palette(window); border-bottom: 1px solid palette(shadow); }")

        self.license.addToolBar(self.lToolBar)

 

        self.licenseLabel = QtGui.QLabel("")

        self.licenseLabel.setSizePolicy(QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Preferred)

        self.lToolBar.addWidget(self.licenseLabel)

 

        hideLicenseAction = QtGui.QAction(self)

        hideLicenseAction.triggered.connect(self.license.hide)

        hideLicenseAction.setShortcut("Esc")

        self.license.addAction(hideLicenseAction)

        self.license.setWindowModality(QtCore.Qt.ApplicationModal)

        self.license.resize(800, 480)

        self.licenseView = QtGui.QTextEdit()

        self.licenseText = app_name +\

        " should have come with an assortment of licensing terms. " + \

        "If you‘re seeing this text instead of a license, then odds are it " + \

        "probably didn‘t. To view the licensing terms, visit " + app_homepage +\

        " and download another copy of " + app_name + ", which should " + \

        "(hopefully) include the licensing terms."

        self.akaneLicense()

        self.licenseView.textChanged.connect(self.setLicenseText)

        self.license.setCentralWidget(self.licenseView)

 

        # Define Web dialog

        self.webDialog = AMovableWindow()

        self.webQuitAction = QtGui.QAction(self)

        self.webQuitAction.setShortcut("Esc")

        self.webQuitAction.triggered.connect(self.webDialog.hide)

        self.webDialog.addAction(self.webQuitAction)

        self.webView = QtWebKit.QWebView()

        self.webToolBar = QtGui.QToolBar(tr(‘webDialogToolBar‘))

        self.webToolBar.setStyleSheet("QToolBar { background: palette(window); border-bottom: 1px solid palette(shadow); }")

        self.webToolBar.setContextMenuPolicy(QtCore.Qt.CustomContextMenu)

        self.webToolBar.setMovable(False)

        self.webToolBar.setToolButtonStyle(QtCore.Qt.ToolButtonTextBesideIcon)

        self.webBackAction = QtGui.QAction(QtGui.QIcon().fromTheme("go-previous", QtGui.QIcon(os.path.join(app_lib, "icons", ‘web-back.png‘))), tr(‘back‘), self)

        self.webBackAction.setShortcut("Alt+Left")

        self.webBackAction.triggered.connect(self.webView.back)

        self.webToolBar.addAction(self.webBackAction)

        self.webNextAction = QtGui.QAction(QtGui.QIcon().fromTheme("go-next", QtGui.QIcon(os.path.join(app_lib, "icons", ‘web-next.png‘))), tr(‘next‘), self)

        self.webNextAction.setShortcut("Alt+Right")

        self.webNextAction.triggered.connect(self.webView.forward)

        self.webToolBar.addAction(self.webNextAction)

        self.webReloadAction = QtGui.QAction(QtGui.QIcon().fromTheme("view-refresh", QtGui.QIcon(os.path.join(app_lib, "icons", ‘reload.png‘))), tr(‘reload‘), self)

        self.webReloadAction.setShortcuts(["Ctrl+R", "F5"])

        self.webReloadAction.triggered.connect(self.webView.reload)

        self.webToolBar.addAction(self.webReloadAction)

        self.webDialog.addToolBar(self.webToolBar)

        self.webDialog.setCentralWidget(self.webView)

 

        self.yes = QtGui.QMessageBox.Yes

        self.no = QtGui.QMessageBox.No

 

    def confirmBox(self, content="", title=tr(‘confirm‘)):

        message = QtGui.QMessageBox.question(self, title, content, self.yes | self.no)

        return message

 

    def setLicenseText(self):

        if not self.licenseView.toPlainText() == self.licenseText:

            self.licenseView.setText(self.licenseText)

 

    def sourceCode(self):

        self.licenseLabel.setText("")

        if os.path.exists(os.path.join(app_lib, "sources.txt")):

            self.licenseText = ""

            l = open(os.path.join(app_lib, "sources.txt"), "r")

            ll = l.readlines()

            l.close()

            for line in ll:

                self.licenseText = self.licenseText + line

        self.licenseView.setText(self.licenseText)

 

    def akaneLicense(self):

        self.licenseLabel.setText(tr(‘appLicenseLabel1‘) + app_name + tr(‘appLicenseLabel2‘))

        if os.path.exists(os.path.join(app_lib, "license-akane.txt")):

            self.licenseText = ""

            l = open(os.path.join(app_lib, "license-akane.txt"), "r")

            ll = l.readlines()

            l.close()

            for line in ll:

                self.licenseText = self.licenseText + line

        self.licenseView.setText(self.licenseText)

 

    def qtLicense(self):

        self.licenseLabel.setText(tr(‘qtLicenseLabel‘))

        if os.path.exists(os.path.join(app_lib, "license-qt.txt")):

            self.licenseText = ""

            l = open(os.path.join(app_lib, "license-qt.txt"), "r")

            ll = l.readlines()

            l.close()

            for line in ll:

                self.licenseText = self.licenseText + line

        self.licenseView.setText(self.licenseText)

 

    def pyqtLicense(self):

        self.licenseLabel.setText(tr(‘pyqtLicenseLabel‘))

        if os.path.exists(os.path.join(app_lib, "license-pyqt.txt")):

            self.licenseText = ""   

            l = open(os.path.join(app_lib, "license-pyqt.txt"), "r")

            ll = l.readlines()

            l.close()

            for line in ll:

                self.licenseText = self.licenseText + line

        self.licenseView.setText(self.licenseText)

 

    def staggerLicense(self):

        self.licenseLabel.setText(tr(‘staggerLicenseLabel‘))

        if os.path.exists(os.path.join(app_lib, "license-stagger.txt")):

            self.licenseText = ""

            l = open(os.path.join(app_lib, "license-stagger.txt"), "r")

            ll = l.readlines()

            l.close()

            for line in ll:

                self.licenseText = self.licenseText + line

        self.licenseView.setText(self.licenseText)

 

    def mutagenLicense(self):

        self.licenseLabel.setText(tr(‘mutagenLicenseLabel‘))

        if os.path.exists(os.path.join(app_lib, "license-mutagen.txt")):

            self.licenseText = ""

            l = open(os.path.join(app_lib, "license-mutagen.txt"), "r")

            ll = l.readlines()

            l.close()

            for line in ll:

                self.licenseText = self.licenseText + line

        self.licenseView.setText(self.licenseText)

 

    def aboutButtonClicked(self, button):

        if unicode(button.text()) == tr(‘license‘):

            self.showLicense()

        else:

            self.about.hide()

 

    def openLink(self, url):

        webbrowser.open(unicode(url))

 

    def urlDialog(self, url=""):

        self.webView.load(QtCore.QUrl(unicode(url)))

        qr = self.webDialog.frameGeometry()

        cp = QtGui.QDesktopWidget().availableGeometry().center()

        qr.moveCenter(cp)

        self.webDialog.move(qr.topLeft())

        self.webDialog.show()

 

    # Generic input box:

    def inputBox(self, text=tr(‘enterSomething‘), title=tr(‘query‘),value=""):

        self.seizedFocus = True

        text, ok = QtGui.QInputDialog.getText(self, title, 

            text, QtGui.QLineEdit.Normal, value)

        self.seizedFocus = False

        return text

 

    # Generic directory selection dialog:

    def folderDialog(self):

        self.seizedFocus = True

        loadDialog = QtGui.QFileDialog.getExistingDirectory(None, tr(‘selectFolder‘), os.getcwd())

        self.seizedFocus = False

        return loadDialog

 

    def loadDialog(self, filters = tr(‘allFiles‘) +  " (*)"):

        self.seizedFocus = True

        loadDialog = QtGui.QFileDialog.getOpenFileName(None, tr(‘openFiles‘), os.getcwd(), filters)

        self.seizedFocus = False

        return loadDialog

 

    def multiLoadDialog(self, filters = tr(‘allFiles‘) + " (*)"):

        self.seizedFocus = True

        loadDialog = QtGui.QFileDialog.getOpenFileNames(None, tr(‘openFiles‘), os.getcwd(), filters)

        self.seizedFocus = False

        return loadDialog

 

    # Generic save dialog:

    def saveDialog(self, fname="", filters = tr(‘allFiles‘) + " (*)"):

        self.seizedFocus = True

        saveDialog = QtGui.QFileDialog.getSaveFileName(None, tr(‘saveAs‘), os.path.join(os.getcwd(), fname), filters)

        self.seizedFocus = False

        return saveDialog

 

    # Generic message box:

    def message(self, data=tr(‘dummyMessage‘), title=tr(‘alert‘), icon="info"):

        self.seizedFocus = True

        message = QtGui.QMessageBox()

        message.setWindowTitle(title)

        message.setText(unicode(unicode(data)))

        message.addButton(QtGui.QMessageBox.Ok)

        if unicode(icon).lower() == "info" or unicode(icon).lower() == "information":

            message.setIcon(QtGui.QMessageBox.Information)

        elif unicode(icon).lower() == "warn" or unicode(icon).lower() == "warning":

            message.setIcon(QtGui.QMessageBox.Warning)

        elif unicode(icon).lower() == "critical":

            message.setIcon(QtGui.QMessageBox.Question)

        elif unicode(icon).lower() == "query" or unicode(icon).lower() == "question":

            message.setIcon(QtGui.QMessageBox.Question)

        elif unicode(icon).lower() == "query" or unicode(icon).lower() == "question":

            message.setIcon(QtGui.QMessageBox.Question)

        elif unicode(icon).lower() == "none" or unicode(icon).lower() == "noicon":

            message.setIcon(QtGui.QMessageBox.NoIcon)

        else:

            message.setIcon(QtGui.QMessageBox.Information)

        message.exec_()

        self.seizedFocus = False

 

    def showLicense(self):

        self.license.show()

        qr = self.license.frameGeometry()

        cp = QtGui.QDesktopWidget().availableGeometry().center()

        qr.moveCenter(cp)

        self.license.move(qr.topLeft())        

 

    # "About" message box:

    def aboutMessage(self, data=tr(‘dummyMessage‘), title=tr(‘alert‘), icon=""):

        self.winIcon.setPixmap(QtGui.QPixmap(icon))

        self.aboutLabel.setText(data)

        self.about.setWindowTitle(title)

        self.about.show()

        qr = self.about.frameGeometry()

        cp = QtGui.QDesktopWidget().availableGeometry().center()

        qr.moveCenter(cp)

        self.about.move(qr.topLeft())

 

if not sys.platform.startswith("win"):

    class Ui_MainWindow():

        pass

 

# The MainWindow class defines almost all of " + app_name + "‘s interface components:

 

class AWebView(RWebView):

    def primeWebView(self):

        self.setCookieJar(app_cookiejar)

        self.downloadManager = downloadManagerGUI

 

class MainWindow(AMovableWindow, Ui_MainWindow):

    def __init__(self):

 

        ###################

        ## PREPARATIONS: ##

        ###################

        super(MainWindow, self).__init__(None)

        self.dialogHandler = dialogHandler

 

        ##########################

        ## COUNTERS AND FIELDS: ##

        ##########################

        self.userIsMovingProgress = False

        self.version = version

        self.codename = codename

        self.playlistPosition = 0

        self.loopPlaylist = False

        self.moodbarColors = []

        self.moodbarCss = ""

        self.killCookies = False

        self.currentPath = ""

        self.moodbarNum = 1

        self.pWhitelist = []

        self.pBlacklist = []

        if not os.path.exists(os.path.join(app_home, "plugins")):

            os.mkdir(os.path.join(app_home, "plugins"))

        f = os.path.join(app_home, "pwhitelist.conf")

        if not os.path.exists(f):

            fwrite = open(f, "a")

            for line in self.pWhitelist:

                fwrite.write(line + "\n")

            fwrite.close()

        self.loopTrack = False

        self.playStart = False

        self.searchOn = False

        self.menuShown = False

        self.menu2Shown = False

        sheet = "QMenuBar {border: 0; background: transparent;} QMenuBar::item { padding: 2px; padding-left: 6px; padding-right: 6px; border: 0;  color: palette(window-text); } QMenuBar::item:pressed { color: palette(highlighted-text); background: palette(highlight); } "

        modSheet = """

QPushButton {

min-width: 16px;

min-height: 16px;

border: 1px solid transparent;

padding: 0px;

padding-left: 4px;

padding-right: 4px;

border-radius: 4px;

 

}

 

QPushButton:hover {

border: 1px solid palette(shadow);

background: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1, stop:0 palette(light), stop:1 palette(button));

}

 

QPushButton:pressed {

border: 1px solid palette(shadow);

background: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1, stop:0 palette(shadow), stop:1 palette(button));

}

"""

        tabmodder = """

QTabBar::tab:top {

padding: 4px;

border: 1px solid palette(shadow);

}

 

QTabBar::tab:top {

border-top-left-radius: 4px;

border-top-right-radius:4px;

border-bottom: 1px solid palette(shadow);

background: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1, stop:0 palette(window), stop:1 palette(midlight));

}

 

QTabBar::tab:top:selected {

border-bottom: 0;

padding-bottom: 5px;

background: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1, stop:0 palette(light), stop:1 palette(window));

"""

        self.customTitleBarMenuBarSheet = sheet + " " + modSheet

        self.setStyleSheet(sheet)

        self.customTitleBarSheetNormal = sheet + " #titleToolBar { margin-top: 1px; margin-left: 1px; margin-right: 2px !important; margin-bottom: 0; background: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1, stop:0 palette(light), stop:1 palette(window)); border-bottom: 1px solid palette(shadow); } #mainToolBar { margin-left: 1px; margin-right: 2px !important; margin-bottom: 0; } #statusBar { border: 0; background: transparent; } QMainWindow { padding: 1px; border: 1px solid palette(shadow);  }"

        self.customTitleBarSheetMaximized = sheet + " #titleToolBar { background: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1, stop:0 palette(light), stop: 1 palette(window)); border-bottom: 1px solid palette(shadow); margin-top: 0 !important; margin-left: 0 !important; margin-right: 0 !important; margin-bottom: 0; } #mainToolBar { margin-bottom: 0; }"

        self.nativeTitleBarSheetNormal = sheet + " #titleToolBar { background: transparent; border-bottom: 1px solid palette(shadow); }"

        self.nativeTitleBarSheetMaximized = sheet + " #titleToolBar { background: transparent; border-bottom: 1px solid palette(shadow); }"

        if sys.platform.startswith("win"):

            self.customTitleBarSheetNormal = self.customTitleBarSheetNormal + tabmodder

            self.customTitleBarSheetMaximized = self.customTitleBarSheetMaximized + tabmodder

            self.nativeTitleBarSheetNormal = self.nativeTitleBarSheetNormal + tabmodder

            self.nativeTitleBarSheetMaximized = self.nativeTitleBarSheetMaximized + tabmodder

        self.menu3Shown = False

        self.ascending = False

 

        collectionFile = os.path.join(app_home, "folders.json")

        if not os.path.exists(collectionFile):

            collectionManager.folders.append(os.path.expanduser(os.path.join("~", "Music")))

            if sys.platform.startswith("linux"):

                collectionManager.folders.append(os.path.expanduser(os.path.join("~", "music")))

        else:

            collectionManager.reload()

 

        self.initUI()

 

    def initUI(self):

 

        if sys.platform.startswith("win"):

            self.setupUi(self)

        else:

            uic.loadUi(os.path.join(app_lib, "mainwindow.ui"), self)

        self.setDockOptions(QtGui.QMainWindow.VerticalTabs)

 

        #######################################

        ## Show warning if collection mismatch:

        autoRebuild = False

        if required_collection_type != collection_type:

            self.dialogHandler.message(app_name + tr(‘collectionError1A‘) + "<b>"\

            + unicode(required_collection_type) + \

            "</b>" + tr(‘collectionError1B‘) + "<b>" \

            + unicode(collection_type) + "</b>" + tr(‘collectionError1C‘) + "" +\

            tr(‘collectionError1D‘), tr(‘warning‘), "warn")

            collectionManager.reload()

            collectionBuilder.folderList = collectionManager.folders

            collectionBuilder.start()

 

        #######################

        ## NON-GUI ELEMENTS: ##

        #######################

        if sys.version_info[0] >= 3:

            self.cookieFile = os.path.join(app_home, "cookies.pkl")

        else:

            self.cookieFile = os.path.join(app_home, "cookies-py2.pkl")

        self.mediaObject = Phonon.MediaObject()

        self.mediaObject.finished.connect(self.advanceTrack)

        self.mediaObject.totalTimeChanged.connect(self.setProgressBarMax)

        self.mediaObject.currentSourceChanged.connect(self.loadMoodbar)

        audioOutput = Phonon.AudioOutput(Phonon.MusicCategory, self)

        Phonon.createPath(self.mediaObject, audioOutput)

        self.mediaObject.setTickInterval(1)

        self.mediaObject.tick.connect(self.updateProgressBar)

        self.mediaObject.metaDataChanged.connect(self.updateMetaData)

        self.mediaObject.metaDataChanged.connect(self.trayMessage)

 

        self.moodbarTimer = QtCore.QTimer()

 

        self.cookies = app_cookiejar

        app_cookiejar.setParent(QtCore.QCoreApplication.instance())

        cookies = []

        for c in self.loadCookies():

            cookies.append(QtNetwork.QNetworkCookie().parseCookies(c)[0])

        self.cookies.setAllCookies(cookies)

 

        ###################

        ## GUI ELEMENTS: ##

        ###################

 

        # TITLE TOOLBAR

        self.titleToolBarContent = QtGui.QWidget()

        self.titleToolBarLayout = QtGui.QHBoxLayout()

        self.titleToolBarLayout.setContentsMargins(0,0,0,0)

        self.titleToolBarLayout.setSpacing(0)

        self.blankTitleLabel = QtGui.QLabel(" ", self)

        self.title = AMovableLabel(self)

        self.title.setText("<b>" + app_name + "</b>")

        self.title.setSizePolicy(QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Preferred)

        self.menuBarContainer = QtGui.QWidget()

        self.menuBarContainer.setSizePolicy(QtGui.QSizePolicy.Preferred, QtGui.QSizePolicy.Preferred)

        self.menuBarContainerLayout = QtGui.QHBoxLayout()

        self.menuBarContainerLayout.setContentsMargins(0,0,0,0)

        self.menuBarContainerLayout.setSpacing(0)

        self.windowControls = QtGui.QWidget()

        self.windowControls.setStyleSheet(self.customTitleBarMenuBarSheet)

        self.windowControlsLayout = QtGui.QHBoxLayout()

        self.windowControlsLayout.setContentsMargins(0,0,0,0)

        self.windowControlsLayout.setSpacing(0)

        self.minimizeButton = QtGui.QPushButton(QtGui.QIcon(os.path.join(app_lib, "icons", "minimize.png")), "", self)

        self.minimizeButton.setFocusPolicy(QtCore.Qt.NoFocus)

        self.maximizeButton = QtGui.QPushButton(QtGui.QIcon(os.path.join(app_lib, "icons", "maximize.png")), "", self)

        self.maximizeButton.setFocusPolicy(QtCore.Qt.NoFocus)

        self.closeButton = QtGui.QPushButton(QtGui.QIcon(os.path.join(app_lib, "icons", "close.png")), "", self)

        self.closeButton.setFocusPolicy(QtCore.Qt.NoFocus)

 

        # MENUBAR

        self.menuBar = QtGui.QMenuBar(self)

        self.menuBar.setSizePolicy(QtGui.QSizePolicy.Preferred, QtGui.QSizePolicy.Preferred)

        self.musicMenu = QtGui.QMenu(tr(‘musicMenu‘), self)

        self.editMenu = QtGui.QMenu(tr(‘editMenu‘), self)

        self.viewMenu = QtGui.QMenu(tr(‘viewMenu‘), self)

        self.toolsMenu = QtGui.QMenu(tr(

        ‘toolsMenu‘), self)

        self.helpMenu = QtGui.QMenu(tr(‘helpMenu‘), self)

 

        ## MAIN TOOLBAR:

        blankLabel = QtGui.QLabel(" ", self)

        self.goPreviousButton = QtGui.QPushButton(QtGui.QIcon().fromTheme("media-skip-backward", QtGui.QIcon(os.path.join(app_lib, "icons", "previous.png"))), "", self)

        self.playPauseButton = QtGui.QPushButton(QtGui.QIcon().fromTheme("media-playback-start", QtGui.QIcon(os.path.join(app_lib, "icons", "play.png"))), "", self)

        self.goNextButton = QtGui.QPushButton(QtGui.QIcon().fromTheme("media-skip-forward", QtGui.QIcon(os.path.join(app_lib, "icons", "next.png"))), "", self)

        self.timeEdit = ATimeEdit(self)

        self.remainingTimeLabel = QtGui.QLabel("-0:00/0:00")

        self.collectionList = CollectionList()

 

        ## Trackbar widget:

        self.progressWidget = QtGui.QWidget()

        self.progressLayout = QtGui.QVBoxLayout()

        self.progressLayout.setContentsMargins(0,0,0,0)

        self.progressLayout.setSpacing(0)

        self.progressWidget.setLayout(self.progressLayout)

        self.progressBar = AkSlider(QtCore.Qt.Horizontal, self)

        self.progressBar.setFixedHeight(18)

        self.progressBar.setStyleSheet("""

QProgressBar:horizontal { border: 1px solid palette(shadow); border-radius: 3px; background: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 palette(midlight), stop: 1 palette(light)); padding: 1px; } QProgressBar::chunk:horizontal { background: palette(highlight); width: 1px; } """)

        self.progressLayout.addWidget(self.progressBar)

        if os.path.exists("/usr/bin/moodbar"):

            moodbarWriter.moodbarWritten.connect(self.updateMoodbar)

            self.moodbarViewer = MoodbarView()

            self.moodbarViewer.setHtml("<html><body style=\"border: 1px solid ThreeDShadow; margin: 0; background: black;\"></body></html>")

            self.moodbarViewer.settings().setAttribute(QtWebKit.QWebSettings.JavascriptEnabled, False)

            self.moodbarViewer.settings().setAttribute(QtWebKit.QWebSettings.PrivateBrowsingEnabled, True)

            self.moodbarViewer.setFixedHeight(10)

            self.moodbarViewer.page().mainFrame().setScrollBarPolicy(QtCore.Qt.Horizontal, QtCore.Qt.ScrollBarAlwaysOff)

            self.moodbarViewer.page().mainFrame().setScrollBarPolicy(QtCore.Qt.Vertical, QtCore.Qt.ScrollBarAlwaysOff)

            self.progressLayout.addWidget(self.moodbarViewer)

        self.progressBar.setMaximumWidth(3200)

 

        ## MAIN TOOLBAR:

        self.loopBox = QtGui.QCheckBox(tr(‘loop‘))

        self.loopBox.setTristate(True)

        self.mainMenu = QtGui.QMenu()

 

        ## SETTINGS DIALOG:

        self.settingsDialog = AMovableWindow()

        self.settingsDialog.setWindowTitle("" + app_name + " " + tr(‘preferences‘))

        self.settingsDialog.setWindowModality(QtCore.Qt.ApplicationModal)

        self.settingsTabs = QtGui.QTabWidget()

        self.settingsDialogBox = QtGui.QWidget()

        settingsDialogLayout = QtGui.QGridLayout()

        nLabel = QtGui.QLabel("<b>" + tr(‘appearanceLabel‘) + "</b>")

        self.messagesBox = QtGui.QCheckBox(tr(‘messagesBox‘))

        self.titleBox = QtGui.QCheckBox(tr(‘titleBox‘))

        self.menuBarBox = QtGui.QCheckBox(tr(‘menuBarBox‘))

        self.webSettingsBox = QtGui.QWidget()

        wLabel = QtGui.QLabel("<b>" + tr(‘storesLabel‘) + "</b>")

        self.jamendoBox = QtGui.QCheckBox(tr(‘jamendoBox‘))

        self.ngBox = QtGui.QCheckBox(tr(‘ngBox‘))

        pLabel = QtGui.QLabel("<b>" + tr(‘panelsLabel‘) + "</b>")

        self.wikipediaBox = QtGui.QCheckBox(tr(‘wikipediaBox‘))

        self.lastfmBox = QtGui.QCheckBox(tr(‘lastfmBox‘))

        self.lyricsBox = QtGui.QCheckBox(tr(‘lyricsBox‘))

        sLabel = QtGui.QLabel("<b>" + tr(‘sourcesLabel‘) + "</b>")

        lyricSubBox = QtGui.QWidget()

        lyricSubBoxLayout = QtGui.QGridLayout()

        lyricSubBoxLayout.setContentsMargins(0,0,0,0)

        lyricsLabel = QtGui.QLabel(tr(‘defaultLyricsSource‘))

        self.lyricSourceBox = QtGui.QComboBox()

        self.lyricSourceBox.addItem("Lyrics007")

        self.lyricSourceBox.addItem("MetroLyrics")

        self.lyricSourceBox.addItem("eLyrics")

        self.settingsDialogToolBar = QtGui.QToolBar(tr(‘preferencesDialogToolBar‘))

        self.settingsDialogToolBar.setStyleSheet("QToolBar {background: transparent; border-top: 0;}")

        self.settingsDialogToolBar.setContextMenuPolicy(QtCore.Qt.CustomContextMenu)

        self.settingsDialogToolBar.setMovable(False)

        self.saveSettingsButton = QtGui.QPushButton(tr(‘save‘), self)

        self.cancelSettingsButton = QtGui.QPushButton(tr(‘close‘), self)

        self.cancelSettings = QtGui.QAction(self)

        self.cancelSettings.triggered.connect(self.settingsDialog.close)

        self.cancelSettings.setShortcuts(["Ctrl+Alt+P", "Ctrl+,"])

        self.settingsDialog.addAction(self.cancelSettings)

 

        ## COLLECTION EDITOR:

        self.collectionEditor = AMovableWindow()

        self.collectionEditor.setWindowModality(QtCore.Qt.ApplicationModal)

        self.collectionEditor.setWindowTitle(tr(‘collectionManager‘))

        self.collectionEditorToolBar = QtGui.QToolBar(tr(‘collectionManagerToolBar‘))

        self.collectionEditorToolBar.setStyleSheet("QToolBar {border-top: 0; background: transparent;}")

        self.collectionEditorToolBar.setContextMenuPolicy(QtCore.Qt.CustomContextMenu)

        self.collectionEditorToolBar.setMovable(False)

        self.addFilesButton = QtGui.QPushButton(tr(‘addFiles‘), self)

        self.addFolderButton = QtGui.QPushButton(tr(‘addFolder‘), self)

        self.removeFolderButton = QtGui.QPushButton(tr(‘remove‘), self)

        self.folderList = QtGui.QListWidget()

 

        ## PLUGINS DOCK:

#        self.pluginsDock = QtGui.QDockWidget("&Plugins")

        pluginsWindow = QtGui.QWidget()

        pluginsLayout = QtGui.QVBoxLayout()

        self.editPluginsButton = QtGui.QPushButton(tr(‘togglePlugin‘))

        self.editPluginsButton.setFocusPolicy(QtCore.Qt.TabFocus)

        self.pluginsEditor = AMovableWindow()

        self.pluginsEditor.setWindowTitle(tr(‘pluginsBlacklist‘))

        self.pluginsEditor.setWindowModality(QtCore.Qt.ApplicationModal)

        self.pluginsEditor.resize(400, 240)

        pluginsSubLayout = QtGui.QGridLayout()

        eplabel = QtGui.QLabel("<b>" + tr(‘enabledPlugins‘) + "</b>")

        dplabel = QtGui.QLabel("<b>" + tr(‘disabledPlugins‘) + "</b>")

        self.enabledPluginsList = QtGui.QListWidget()

        self.disabledPluginsList = QtGui.QListWidget()

 

        ## TABS:

#        self.mediaTabs.setStyleSheet()

 

        ## TAG EDITOR:

        self.tagEditor = AMovableWindow()

        self.tagEditor.setWindowTitle(tr(‘tagEditor‘))

        self.tagEditor.setWindowModality(QtCore.Qt.ApplicationModal)

        self.tagEditor.resize(400, 240)

        self.tagEditorBox = QtGui.QWidget()

        tagEditorLayout = QtGui.QGridLayout()

#        if not sys.version_info[0] >= 3:

#            title = QtGui.QLabel(tr(‘noTagsInPy2‘))

#        else:

#        if 1:

        title = QtGui.QLabel(tr(‘titleLabel‘))

        self.titleTagField = QtGui.QLineEdit()

        artist = QtGui.QLabel(tr(‘artistLabel‘))

        self.artistTagField = QtGui.QLineEdit()

        album = QtGui.QLabel(tr(‘albumLabel‘))

        self.albumTagField = QtGui.QLineEdit()

        date = QtGui.QLabel(tr(‘yearLabel‘))

        self.dateTagField = QtGui.QLineEdit()

        genre = QtGui.QLabel(tr(‘genreLabel‘))

        self.genreTagField = QtGui.QLineEdit()

        path = QtGui.QLabel(tr(‘pathLabel‘))

        self.pathTagField = QtGui.QLineEdit()

        self.tagEditorToolBar = QtGui.QToolBar(tr(‘tagEditorToolBar‘))

        self.tagEditorToolBar.setStyleSheet("QToolBar {border-top: 0; background: transparent;}")

        self.tagEditorToolBar.setContextMenuPolicy(QtCore.Qt.CustomContextMenu)

        self.tagEditorToolBar.setMovable(False)

        self.saveTagsButton = QtGui.QPushButton(tr(‘save‘), self)

        self.cancelTagsButton = QtGui.QPushButton(tr(‘close‘), self)

 

        ## PLAYLIST EDITOR:

        self.playlistEditor = AMovableWindow()

        self.playlistEditor.setWindowTitle(tr(‘playlistEditor‘))

        self.playlistEditorBox = QtGui.QTextEdit()

        self.playlistEditorToolBar = QtGui.QToolBar(tr(‘playlistEditorToolBar‘))

        self.playlistEditorToolBar.setStyleSheet("QToolBar {border-top: 0; background: transparent;}")

        self.playlistEditorToolBar.setContextMenuPolicy(QtCore.Qt.CustomContextMenu)

        self.playlistEditorToolBar.setMovable(False)

        self.savePlaylistButton = QtGui.QPushButton(tr(‘save‘), self)

        self.hidePlaylistEditorButton = QtGui.QPushButton(tr(‘close‘), self)

 

        self.sortMenu = QtGui.QMenu(tr(‘sortPlaylistBy‘))

        self.sortMenu.setIcon(QtGui.QIcon().fromTheme("view-sort-ascending", QtGui.QIcon(os.path.join(app_lib, "icons", "sort.png"))))

 

        self.playlist = PlaylistList()

        self.playlistMenu = QtGui.QMenu()

 

        self.trayIcon = app_trayIcon

        self.trayIcon.setVisible(True)

        self.trayIcon.setContextMenu(self.mainMenu)

        if not "ubuntu" in app_unity:

            self.goPreviousIcon = QtGui.QSystemTrayIcon(QtGui.QIcon().fromTheme("media-skip-backward", QtGui.QIcon(os.path.join(app_lib, "icons", "previous.png"))), self)

            self.seekBackwardIcon = QtGui.QSystemTrayIcon(QtGui.QIcon().fromTheme("media-seek-backward", QtGui.QIcon(os.path.join(app_lib, "icons", "backward.png"))), self)

            self.playPauseIcon = QtGui.QSystemTrayIcon(QtGui.QIcon().fromTheme("media-playback-start", QtGui.QIcon(os.path.join(app_lib, "icons", "play.png"))), self)

            self.seekForwardIcon = QtGui.QSystemTrayIcon(QtGui.QIcon().fromTheme("media-seek-forward", QtGui.QIcon(os.path.join(app_lib, "icons", "forward.png"))), self)

            self.goNextIcon = QtGui.QSystemTrayIcon(QtGui.QIcon().fromTheme("media-skip-forward", QtGui.QIcon(os.path.join(app_lib, "icons", "next.png"))), self)

 

        self.collectionCount = QtGui.QLabel(tr(‘emptyPlaylist‘))

        self.collectionCount.setSizePolicy(QtGui.QSizePolicy.Preferred, QtGui.QSizePolicy.Preferred)

 

        ##############

        ## ACTIONS: ##

        ##############

        goPreviousAction = QtGui.QAction(QtGui.QIcon().fromTheme("media-skip-backward", QtGui.QIcon(os.path.join(app_lib, "icons", "previous-16.png"))), tr(‘prevTrack‘), self)

        goPreviousAction.setIconVisibleInMenu(True)

        self.seekBackwardAction = QtGui.QAction(QtGui.QIcon().fromTheme("media-seek-backward", QtGui.QIcon(os.path.join(app_lib, "icons", "backward-16.png"))), tr(‘seekBack‘), self)

        self.seekBackwardAction.setIconVisibleInMenu(True)

        self.restoreAction = QtGui.QAction(tr(‘showHide‘), self)

        self.playPauseAction = QtGui.QAction(QtGui.QIcon().fromTheme("media-playback-start", QtGui.QIcon(os.path.join(app_lib, "icons", "play-16.png"))), tr(‘playPause‘), self)

        self.playPauseAction.setIconVisibleInMenu(True)

        self.seekForwardAction = QtGui.QAction(QtGui.QIcon().fromTheme("media-seek-forward", QtGui.QIcon(os.path.join(app_lib, "icons", "forward-16.png"))), tr(‘seekFwd‘), self)

        self.seekForwardAction.setIconVisibleInMenu(True)

        goNextAction = QtGui.QAction(QtGui.QIcon().fromTheme("media-skip-forward", QtGui.QIcon(os.path.join(app_lib, "icons", "next-16.png"))), tr(‘nextTrack‘), self)

        goNextAction.setIconVisibleInMenu(True)

        focusTimeAction = QtGui.QAction(self)

        self.changeLoopAction = QtGui.QAction(tr(‘noLoop‘), self)

        self.changeLoopAction.setIconVisibleInMenu(True)

        self.shuffleAction = QtGui.QAction(QtGui.QIcon().fromTheme("media-playlist-shuffle", QtGui.QIcon(os.path.join(app_lib, "icons", "shuffle.png"))), tr(‘shuffle‘), self)

        self.shuffleAction.setIconVisibleInMenu(True)

        aboutAction = QtGui.QAction(QtGui.QIcon().fromTheme("help-about", QtGui.QIcon(os.path.join(app_lib, "icons", "about-16.png"))), tr(‘about‘), self)

        aboutAction.setIconVisibleInMenu(True)

        helpAction = QtGui.QAction(QtGui.QIcon().fromTheme("help-contents", QtGui.QIcon(os.path.join(app_lib, "icons", "help.png"))), tr(‘helpContents‘), self)

        helpAction.setIconVisibleInMenu(True)

        helpAction.setToolTip("<b>" + tr(‘viewHelp‘) + "</b><br>F1")

        self.openMenuButton = QtGui.QAction(QtGui.QIcon(os.path.join(app_lib, "icons", "akane_logo-unix-22px.svg")), tr(‘menu‘), self)

#        self.openMenuButton.setStyleSheet(

        """

        """#)

        preferencesAction = QtGui.QAction(QtGui.QIcon().fromTheme("preferences-system", QtGui.QIcon(os.path.join(app_lib, "icons", "settings-16.png"))), tr(‘preferencesMenuOption‘), self)

        preferencesAction.setIconVisibleInMenu(True)

        self.clearCookiesAction = QtGui.QAction(QtGui.QIcon().fromTheme("edit-clear", QtGui.QIcon(os.path.join(app_lib, "icons", "clear-16.png"))), tr(‘clearCookies‘), self)

        self.wbAction = QtGui.QAction(tr(‘webBrowser‘), self)

        self.downloadsAction = QtGui.QAction(tr(‘downloadsHKey‘), self)

        self.clearCookiesAction.setIconVisibleInMenu(True)

        quitAction = QtGui.QAction(QtGui.QIcon().fromTheme("system-log-out", QtGui.QIcon(os.path.join(app_lib, "icons", "quit-16.png"))), tr(‘quit‘), self)

        quitAction.setIconVisibleInMenu(True)

 

        focusSearchBarAction = QtGui.QAction(self)

        self.rebuildCollectionAction = QtGui.QAction(QtGui.QIcon().fromTheme("view-refresh", QtGui.QIcon(os.path.join(app_lib, "icons", "reload-16.png"))), tr(‘rebuildCollection‘), self)

        self.rebuildCollectionAction.setIconVisibleInMenu(True)

        self.collectionEditAction = QtGui.QAction(tr(‘collection‘), self)

        self.hideCollectionAction = QtGui.QAction("Hide Collection Editor", self)

        focusCollection = QtGui.QAction(self)

        

        self.onlineMusicViewer = AWebView(self)

        self.ngWindow = QtGui.QMainWindow()

        self.ngToolBar = QtGui.QToolBar()

        ngUserLabel = QtGui.QLabel(tr(‘ngUserLabel‘))

        self.ngUserLoader = QtGui.QLineEdit()

        self.ngMusicViewer = AWebView(self)

 

        self.removePlaylistItemAction = QtGui.QAction(QtGui.QIcon().fromTheme("list-remove", QtGui.QIcon(os.path.join(app_lib, "icons", "remove-16.png"))), tr(‘removeFromPlaylist‘), self)

        addToPlaylistAction = QtGui.QAction(QtGui.QIcon().fromTheme("list-add", QtGui.QIcon(os.path.join(app_lib, "icons", "add-16.png"))), tr(‘openMusic‘), self)

        addToPlaylistAction.setIconVisibleInMenu(True)

        removeFromPlaylistAction = QtGui.QAction(self)

        clearPlaylistAction = QtGui.QAction(QtGui.QIcon().fromTheme("edit-clear", QtGui.QIcon(os.path.join(app_lib, "icons", "clear-16.png"))), tr(‘clearPlaylist‘), self)

        clearPlaylistAction.setIconVisibleInMenu(True)

        loadPlaylistAction = QtGui.QAction(QtGui.QIcon().fromTheme("document-open", QtGui.QIcon(os.path.join(app_lib, "icons", "load-16.png"))), tr(‘loadPlaylist‘), self)

        loadPlaylistAction.setIconVisibleInMenu(True)

        savePlaylistAsAction = QtGui.QAction(QtGui.QIcon().fromTheme("document-save", QtGui.QIcon(os.path.join(app_lib, "icons", "save-16.png"))), tr(‘savePlaylistAs‘), self)

        savePlaylistAsAction.setIconVisibleInMenu(True)

        editTagsAction = QtGui.QAction(QtGui.QIcon(os.path.join(app_lib, "icons", "edit.png")), tr(‘editTags‘), self)

        editTagsAction.setIconVisibleInMenu(True)

        hideTagAction = QtGui.QAction(self)

        playlistEdit = QtGui.QAction(self)

        self.hidePlaylistAction = QtGui.QAction(self)

        sortTitle = QtGui.QAction(tr(‘sortTitle‘), self)

        b = QtGui.QFont()

        b.setBold(True)

        sortAction = QtGui.QAction(self)

        sortTitle.setFont(b)

        sortByTitleAction = QtGui.QAction(tr(‘sortByTitle‘), self)

        sortByArtistAction = QtGui.QAction(tr(‘sortByArtist‘), self)

        sortByAlbumAction = QtGui.QAction(tr(‘sortByAlbum‘), self)

        sortByYearAction = QtGui.QAction(tr(‘sortByYear‘), self)

        sortByGenreAction = QtGui.QAction(tr(‘sortByGenre‘), self)

 

        focusPlaylistAction = QtGui.QAction(self)

 

        ############

        ## ICONS: ##

        ############

        self.loopBox.setIcon(QtGui.QIcon(os.path.join(app_lib, "icons", "noloop.png")))

        self.editTagsButton.setIcon(QtGui.QIcon(os.path.join(app_lib, "icons", "edit.png")))

        self.playlistEditButton.setIcon(QtGui.QIcon(os.path.join(app_lib, "icons", "edit-playlist.png")))

        if sys.platform.startswith("win"):

            self.openMenuButton.setIcon(QtGui.QIcon(os.path.join(app_lib, "icons", "akane_logo-unix-22px.png")))

            self.trayIcon.setIcon(QtGui.QIcon(os.path.join(app_lib, "icons", "akane_logo-unix-16px.png")))

            self.goNextIcon.setIcon(QtGui.QIcon(os.path.join(app_lib, "icons", "next-16.png")))

            self.seekForwardIcon.setIcon(QtGui.QIcon(os.path.join(app_lib, "icons", "forward-16.png")))

            self.playPauseIcon.setIcon(QtGui.QIcon(os.path.join(app_lib, "icons", "play-16.png")))

            self.seekBackwardIcon.setIcon(QtGui.QIcon(os.path.join(app_lib, "icons", "backward-16.png")))

            self.goPreviousIcon.setIcon(QtGui.QIcon(os.path.join(app_lib, "icons", "previous-16.png")))

 

        #################

        ## ICON SIZES: ##

        #################

        self.loopBox.setIconSize(QtCore.QSize(20, 20))

#        if 1:

        self.goPreviousButton.setIconSize(QtCore.QSize(22, 22))

        self.playPauseButton.setIconSize(QtCore.QSize(22, 22))

        self.goNextButton.setIconSize(QtCore.QSize(22, 22))

#            self.openMenuButton.setIconSize(QtCore.QSize(22, 22))

        self.rebuildCollectionButton.setIconSize(QtCore.QSize(22, 22))

        self.collectionEditButton.setIconSize(QtCore.QSize(22, 22))

        self.addToPlaylistButton.setIconSize(QtCore.QSize(22, 22))

        self.removeFromPlaylistButton.setIconSize(QtCore.QSize(22, 22))

        self.clearPlaylistButton.setIconSize(QtCore.QSize(22, 22))

        self.loadPlaylistButton.setIconSize(QtCore.QSize(22, 22))

        self.savePlaylistAsButton.setIconSize(QtCore.QSize(22, 22))

        self.editTagsButton.setIconSize(QtCore.QSize(22, 22))

        self.playlistEditButton.setIconSize(QtCore.QSize(22, 22))

        self.sortButton.setIconSize(QtCore.QSize(22, 22))

 

        ################

        ## SHORTCUTS: ##

        ################

        goPreviousAction.setShortcut("Alt+Left")

        self.seekBackwardAction.setShortcut("Left")

        self.playPauseAction.setShortcut("Space")

        self.seekForwardAction.setShortcut("Right")

        goNextAction.setShortcut("Alt+Right")

        focusTimeAction.setShortcut("Ctrl+T")

        self.shuffleAction.setShortcut("Ctrl+R")

        aboutAction.setShortcut("F2")

        helpAction.setShortcut("F1")

        self.openMenuButton.setShortcut("Alt+M")

        self.saveSettingsButton.setShortcut("Ctrl+S")

        self.cancelSettingsButton.setShortcut("Esc")

        preferencesAction.setShortcuts(["Ctrl+Alt+P", "Ctrl+,"])

        self.wbAction.setShortcut("Ctrl+Shift+N")

        self.downloadsAction.setShortcuts(["Ctrl+Shift+Y", "Ctrl+J"])

        self.clearCookiesAction.setShortcut("Ctrl+Shift+Del")

        quitAction.setShortcuts(["Ctrl+Q", "Ctrl+Shift+Q"])

 

        focusSearchBarAction.setShortcut("Ctrl+K")

        self.rebuildCollectionAction.setShortcuts(["Ctrl+Shift+R", "Shift+F5"])

        self.collectionEditAction.setShortcuts(["Ctrl+M"])

        self.addFilesButton.setShortcut("Ctrl+Shift+O")

        self.addFolderButton.setShortcut("Ctrl+O")

        self.hideCollectionAction.setShortcuts(["Ctrl+M", "Esc"])

        focusCollection.setShortcut("Ctrl+Shift+L")

 

        self.removePlaylistItemAction.setShortcut("Del")

        addToPlaylistAction.setShortcut("Ctrl+O")

        clearPlaylistAction.setShortcut("Ctrl+N")

        loadPlaylistAction.setShortcut("Ctrl+L")

        savePlaylistAsAction.setShortcut("Ctrl+S")

        hideTagAction.setShortcut("Esc")

        self.saveTagsButton.setShortcut("Ctrl+S")

        self.cancelTagsButton.setShortcut("Ctrl+C")

        playlistEdit.setShortcuts(["Ctrl+E"])

        self.hidePlaylistAction.setShortcuts(["Ctrl+E", "Esc"])

        self.savePlaylistButton.setShortcut("Ctrl+S")

        self.hidePlaylistEditorButton.setShortcut("Ctrl+C")

        sortAction.setShortcut("Alt+S")

 

        focusPlaylistAction.setShortcut("Ctrl+P")

 

        ###############

        ## TOOLTIPS: ##

        ###############

        self.minimizeButton.setToolTip(tr(‘minimize‘))

        self.maximizeButton.setToolTip(tr(‘maximize‘))

        self.closeButton.setToolTip(tr(‘closeWindow‘))

        self.goPreviousButton.setToolTip("<b>" + tr(‘skipBackwardTip‘) + "</b><br>Alt+Left")

        self.playPauseButton.setToolTip("<b>" + tr(‘playPauseTip‘) + "</b><br>Space (while playlist has focus)")

        self.goNextButton.setToolTip("<b>" + tr(‘skipForwardTip‘) + "</b><br>Alt+Right")

        self.timeEdit.setToolTip("<b>" + tr(‘progressTip‘) + "</b><br>Ctrl+T to focus")#/Remaining")

        self.progressBar.setToolTip("<b>" + tr(‘progressTip‘) + "</b><br>Left Arrow to seek backward<br>Right Arrow to seek forward")

        self.remainingTimeLabel.setToolTip("<b>" + tr(‘progressTip‘) + "</b><br>Remaining/Total")#/Remaining")

        self.loopBox.setToolTip("<b>" + tr(‘loopTip‘) + "</b><br>Alt+L")

        self.shuffleAction.setToolTip("<b>" + tr(‘shuffleTip‘) + "</b><br>Ctrl+R")

        self.openMenuButton.setToolTip("<b>" + tr(‘menuTip‘) + "</b><br>Alt+M")

        self.saveSettingsButton.setToolTip("<b>" + tr(‘shortcutLabel‘) + "</b> Ctrl+S")

        self.cancelSettingsButton.setToolTip("<b>" + tr(‘shortcutLabel‘) + "</b> Esc")

 

        self.searchBar.setToolTip("<b>" + tr(‘search‘) + "</b><br>Ctrl+K/Ctrl+F to focus")

        self.rebuildCollectionButton.setToolTip("<b>" + tr(‘rebuildCollectionTip‘) + "</b><br>Ctrl+Shift+R/Shift+F5")

        self.collectionEditButton.setToolTip("<b>" + tr(‘editCollectionTip‘) + "</b><br>Ctrl+M")

        self.addFilesButton.setToolTip("<b>" + tr(‘shortcutLabel‘) + "</b> Ctrl+Shift+O")

        self.addFolderButton.setToolTip("<b>" + tr(‘shortcutLabel‘) + "</b> Ctrl+O")

        self.removeFolderButton.setToolTip("<b>" + tr(‘shortcutLabel‘) + "</b> Del (while list widget has focus)")

 

        self.editPluginsButton.setToolTip("<b>" + tr("editPluginsTip") + "</b><br>Enter (while a list is focused), or double-click the item you want to enable/disable")

        self.enabledPluginsList.setToolTip("<b>" + tr("editPluginsTip") + "</b><br>Enter (while a list is focused), or double-click the item you want to enable/disable")

        self.disabledPluginsList.setToolTip("<b>" + tr("editPluginsTip") + "</b><br>Enter (while a list is focused), or double-click the item you want to enable/disable")

 

        self.addToPlaylistButton.setToolTip("<b>" + tr(‘addToPlaylistTip‘) + "</b><br>Ctrl+O")

        self.removeFromPlaylistButton.setToolTip("<b>" + tr(‘removeFromPlaylist‘) + "</b><br>Del (while playlist has focus)")

        self.clearPlaylistButton.setToolTip("<b>" + tr(‘clearPlaylistTip‘) + "</b><br>Ctrl+N")

        self.loadPlaylistButton.setToolTip("<b>" + tr("loadPlaylistTip") + "</b><br>Ctrl+L")

        self.savePlaylistAsButton.setToolTip("<b>" + tr("savePlaylistAsTip") + "</b><br>Ctrl+S")

        self.editTagsButton.setToolTip("<b>" + tr("editTagsTip") + "</b><br>No keyboard shortcut")

        self.saveTagsButton.setToolTip("<b>" + tr(‘shortcutLabel‘) + "</b>Ctrl+S")

        self.cancelTagsButton.setToolTip("<b>" + tr(‘shortcutLabel‘) + "</b>Ctrl+C")

        self.playlistEditButton.setToolTip("<b>" + tr("editPlaylistTip") + "</b><br>Ctrl+E")

        self.savePlaylistButton.setToolTip("<b>" + tr(‘shortcutLabel‘) + "</b> Ctrl+S")

        self.hidePlaylistEditorButton.setToolTip("<b>" + tr(‘shortcutLabel‘) + "</b> Ctrl+C")

        self.sortButton.setToolTip("<b>" + tr(‘sortTitle‘) + "</b><br>Alt+S")

 

        self.playlist.setToolTip("<b>" + tr(‘playlist‘) + "</b><br>Ctrl+P to focus")

 

        self.trayIcon.setToolTip(unicode("" + app_name + ""))

        if not "ubuntu" in app_unity:        

            self.goNextIcon.setToolTip(unicode(tr("skipForwardTip")))

            self.seekForwardIcon.setToolTip(unicode(tr(‘seekForwardTip‘)))

            self.playPauseIcon.setToolTip(unicode("Play"))

            self.seekBackwardIcon.setToolTip(unicode(tr("seekBackwardTip")))

            self.goPreviousIcon.setToolTip(unicode(tr("skipBackwardTip")))

 

        #####################

        ## FOCUS POLICIES: ##

        #####################

        self.goPreviousButton.setFocusPolicy(QtCore.Qt.TabFocus)

        self.playPauseButton.setFocusPolicy(QtCore.Qt.TabFocus)

        self.goNextButton.setFocusPolicy(QtCore.Qt.TabFocus)

        self.loopBox.setFocusPolicy(QtCore.Qt.TabFocus)

#        self.openMenuButton.setFocusPolicy(QtCore.Qt.TabFocus)

 

        ##################################

        ## GUI SIGNAL-SLOT CONNECTIONS: ##

        ##################################

        self.minimizeButton.clicked.connect(self.minimize)

        self.maximizeButton.clicked.connect(self.maximize)

        self.closeButton.clicked.connect(self.close)

 

        self.goPreviousButton.clicked.connect(self.goPrevious)

        self.playPauseButton.setCheckable(True)

        self.playPauseButton.toggled.connect(self.playPause)

        self.goNextButton.clicked.connect(self.goNext)

        try: self.moodbarViewer.valueSig.connect(self.forceUpdateTrackbar)

        except:

            doNothing()

        try: self.moodbarViewer.sliderPressed.connect(self.progressBarPressed)

        except:

            doNothing()

        try: self.moodbarViewer.sliderReleased.connect(self.progressBarReleased)

        except:

            doNothing()

        self.timeEdit.editingFinished.connect(self.setTime)

        self.progressBar.sliderPressed.connect(self.progressBarPressed)

        self.progressBar.sliderMoved.connect(self.seek)

        self.progressBar.sliderMoved.connect(self.updateProgressBar)

        self.progressBar.sliderReleased.connect(self.progressBarReleased)

        self.loopBox.stateChanged.connect(self.changeLoop)

 

        self.messagesBox.stateChanged.connect(self.enableDisableMessages)

        self.titleBox.stateChanged.connect(self.enableDisableCTitleBar)

        self.menuBarBox.stateChanged.connect(self.enableDisableMenuBarBox)

        self.wikipediaBox.stateChanged.connect(self.enableDisableWikipedia)

        self.lastfmBox.stateChanged.connect(self.enableDisableLastfm)

        self.lyricsBox.stateChanged.connect(self.enableDisableLyrics)

        self.jamendoBox.stateChanged.connect(self.enableDisableJamendo)

        self.ngBox.stateChanged.connect(self.enableDisableNG)

        self.lyricSourceBox.currentIndexChanged.connect(self.setLyricSource)

        self.saveSettingsButton.clicked.connect(writeSettings)

        self.saveSettingsButton.clicked.connect(self.savePlugins)

        self.cancelSettingsButton.clicked.connect(self.settingsDialog.hide)

 

        self.searchBar.textChanged.connect(self.search)

        self.rebuildCollectionButton.clicked.connect(self.rebuildCollectionWithWarning)

        self.rebuildCollectionButton.clicked.connect(self.searchBar.clear)

        self.collectionEditButton.clicked.connect(self.changeCollection)

        self.collectionList.itemActivated.connect(self.addMedia)

        self.collectionList.focusedIn.connect(self.enableDisableSpace)

        self.collectionList.focusedOut.connect(self.enableDisableSpace)

 

        self.addFilesButton.clicked.connect(self.addCollectionFiles)

        self.addFolderButton.clicked.connect(self.addCollectionItem)

        self.removeFolderButton.clicked.connect(self.removeCollectionItem)

 

        try: settingsManager.settings[‘jamendoOff‘]

        except:

            settingsManager.settings[‘jamendoOff‘] = False

        if not settingsManager.settings[‘jamendoOff‘]:

            self.mediaTabs.addTab(self.onlineMusicViewer, tr(‘jamendo‘))

        try: settingsManager.settings[‘ngOff‘]

        except:

            settingsManager.settings[‘ngOff‘] = False

        if not settingsManager.settings[‘ngOff‘]:

            self.ngWindow.addToolBar(self.ngToolBar)

            self.ngToolBar.addWidget(ngUserLabel)

            self.ngToolBar.addWidget(self.ngUserLoader)

            self.ngWindow.setCentralWidget(self.ngMusicViewer)

            self.mediaTabs.addTab(self.ngWindow, tr(‘newgrounds‘))

 

        self.lyrics007Button.clicked.connect(self.loadLyrics007)

        self.metroLyricsButton.clicked.connect(self.loadMetroLyrics)

        self.eLyricsButton.clicked.connect(self.loadELyrics)

 

        self.editPluginsButton.clicked.connect(self.enableDisablePlugin)

        self.enabledPluginsList.itemActivated.connect(self.enableDisablePlugin)

        self.disabledPluginsList.itemActivated.connect(self.enableDisablePlugin)

 

        self.addToPlaylistButton.clicked.connect(self.addToPlaylist)

        self.removeFromPlaylistButton.clicked.connect(self.removeFromPlaylist)

        self.clearPlaylistButton.clicked.connect(self.clearPlaylist)

        self.loadPlaylistButton.clicked.connect(self.openPlaylist)

        self.savePlaylistAsButton.clicked.connect(self.savePlaylistAs)

        self.editTagsButton.clicked.connect(self.editTags)

#        if sys.version_info[0] >= 3:

#        if 1:

        self.titleTagField.returnPressed.connect(self.saveTags)

        self.titleTagField.returnPressed.connect(self.tagEditor.hide)

        self.artistTagField.returnPressed.connect(self.saveTags)

        self.artistTagField.returnPressed.connect(self.tagEditor.hide)

        self.albumTagField.returnPressed.connect(self.saveTags)

        self.albumTagField.returnPressed.connect(self.tagEditor.hide)

        self.dateTagField.returnPressed.connect(self.saveTags)

        self.dateTagField.returnPressed.connect(self.tagEditor.hide)

        self.genreTagField.returnPressed.connect(self.saveTags)

        self.genreTagField.returnPressed.connect(self.tagEditor.hide)

        self.pathTagField.textChanged.connect(self.resetPath)

        self.saveTagsButton.clicked.connect(self.saveTags)

        self.cancelTagsButton.clicked.connect(self.tagEditor.hide)

        self.playlistEditButton.clicked.connect(self.editPlaylist)

        self.savePlaylistButton.clicked.connect(self.savePlaylist)

        self.hidePlaylistEditorButton.clicked.connect(self.hidePlaylistEditor)

        self.sortButton.clicked.connect(self.showSortMenu)

 

        self.playlist.focusedIn.connect(self.enableDisableSpace)

        self.playlist.focusedOut.connect(self.enableDisableSpace)

        self.playlist.fileNotFound.connect(self.fileNotFound)

        self.playlist.dragEntered.connect(self.setUnsorted)

        self.playlist.dragLeft.connect(self.setUnsorted)

        self.playlist.setContextMenuPolicy(QtCore.Qt.CustomContextMenu)

        self.playlist.customContextMenuRequested.connect(self.showPlaylistMenu)

        self.playlist.itemActivated.connect(self.itemLoadPosition)

 

        self.ngUserLoader.returnPressed.connect(self.loadNGUser)

 

        self.trayIcon.activated.connect(self.trayIconActivated)

        if not "ubuntu" in app_unity:

            self.goNextIcon.activated.connect(self.goNext)

            self.seekForwardIcon.activated.connect(self.seekForward)

            self.playPauseIcon.activated.connect(self.playPauseButton.toggle)

            self.seekBackwardIcon.activated.connect(self.seekBackward)

            self.goPreviousIcon.activated.connect(self.goPrevious)

 

        #####################################

        ## ACTION SIGNAL-SLOT CONNECTIONS: ##

        #####################################

        goPreviousAction.triggered.connect(self.goPrevious)

        self.seekBackwardAction.triggered.connect(self.seekBackward)

        self.restoreAction.triggered.connect(self.forceTrayIconActivated)

        self.playPauseAction.triggered.connect(self.togglePlayPause)

        self.seekForwardAction.triggered.connect(self.seekForward)

        goNextAction.triggered.connect(self.goNext)

        focusTimeAction.triggered.connect(self.timeEdit.setFocus)

        self.changeLoopAction.triggered.connect(self.toggleLoop)

        self.changeLoopAction.triggered.connect(self.changeLoopActionText)

        self.shuffleAction.triggered.connect(self.shufflePlaylist)

        aboutAction.triggered.connect(self.aboutDialog)

        helpAction.triggered.connect(self.help)

        self.openMenuButton.triggered.connect(self.showMenu)

        preferencesAction.triggered.connect(self.settingsDialog.show)

        self.wbAction.triggered.connect(showWebBrowser)

        self.downloadsAction.triggered.connect(showDownloadManagerGUI)

        self.clearCookiesAction.triggered.connect(self.toggleClearCookies)

        quitAction.triggered.connect(self.quit)

 

        focusSearchBarAction.triggered.connect(self.focusSearchBar)

        self.rebuildCollectionAction.triggered.connect(self.rebuildCollectionWithWarning)

        self.rebuildCollectionAction.triggered.connect(self.searchBar.clear)

        self.collectionEditAction.triggered.connect(self.changeCollection)

        self.hideCollectionAction.triggered.connect(self.hideCollectionEditor)

        focusCollection.triggered.connect(self.collectionList.setFocus)

        focusCollection.triggered.connect(self.raiseCollection)

 

        self.removePlaylistItemAction.triggered.connect(self.removePlaylistItem)

        addToPlaylistAction.triggered.connect(self.addToPlaylist)

        removeFromPlaylistAction.triggered.connect(self.removeFromPlaylist)

        clearPlaylistAction.triggered.connect(self.clearPlaylist)

        loadPlaylistAction.triggered.connect(self.openPlaylist)

        savePlaylistAsAction.triggered.connect(self.savePlaylistAs)

        editTagsAction.triggered.connect(self.editTags)

        hideTagAction.triggered.connect(self.tagEditor.hide)

        playlistEdit.triggered.connect(self.editPlaylist)

        self.hidePlaylistAction.triggered.connect(self.hidePlaylistEditor)

        sortAction.triggered.connect(self.showSortMenu)

        sortByTitleAction.triggered.connect(self.sortByTitle)

        sortByArtistAction.triggered.connect(self.sortByArtist)

        sortByAlbumAction.triggered.connect(self.sortByAlbum)

        sortByYearAction.triggered.connect(self.sortByYear)

        sortByGenreAction.triggered.connect(self.sortByGenre)

 

        focusPlaylistAction.triggered.connect(self.playlist.setFocus)

 

        ####################################

        ## OTHER SIGNAL-SLOT CONNECTIONS: ##

        ####################################

        collectionBuilder.collectionRebuilt.connect(self.refreshCollection)

        collectionBuilder.collectionRebuilt.connect(self.collectionYay)

        self.moodbarTimer.timeout.connect(self.updateMoodbar)

 

        ###################

        ## TRANSLATIONS: ##

        ###################

        self.collectionDock.setWindowTitle(tr(‘collectionDock‘))

        self.wikiDock.setWindowTitle(tr(‘wikiDock‘))

        self.lastfmDock.setWindowTitle(tr(‘lastfmDock‘))

        self.lyricsDock.setWindowTitle(tr(‘lyricsDock‘))

        self.mediaTabs.setTabText(0, tr(‘playlistTab‘))

        

        #########################

        ## OTHER PREPARATIONS: ##

        #########################

        self.wikipedia.settings().setAttribute(QtWebKit.QWebSettings.JavascriptEnabled, False)

        self.wikipedia.settings().setAttribute(QtWebKit.QWebSettings.PrivateBrowsingEnabled, True)

        self.wikipedia.load(QtCore.QUrl(os.path.join(app_lib, "notrack.html")))

        self.ngToolBar.setStyleSheet("QToolBar { border-top: 0; background: transparent; }")

        self.ngToolBar.setMovable(False)

        self.ngToolBar.setContextMenuPolicy(QtCore.Qt.CustomContextMenu)

#        self.ngMusicViewer.settings().setAttribute(QtWebKit.QWebSettings.PluginsEnabled, True)

        try: settingsManager.settings[‘jamendoOff‘]

        except:

            settingsManager.settings[‘jamendoOff‘] = False

            self.onlineMusicViewer.load(QtCore.QUrl("http://www.jamendo.com/"))

            self.jamendoBox.setCheckState(QtCore.Qt.Checked)

        else:

            if settingsManager.settings[‘jamendoOff‘] == False:

                self.onlineMusicViewer.load(QtCore.QUrl("http://www.jamendo.com/"))

                self.jamendoBox.setCheckState(QtCore.Qt.Checked)

        try: settingsManager.settings[‘ngOff‘]

        except:

            settingsManager.settings[‘ngOff‘] = False

            self.ngMusicViewer.load(QtCore.QUrl("http://www.newgrounds.com/audio/"))

            self.ngBox.setCheckState(QtCore.Qt.Checked)

        else:

            if settingsManager.settings[‘ngOff‘] == False:

                self.ngMusicViewer.load(QtCore.QUrl("http://www.newgrounds.com/audio/"))

                self.ngBox.setCheckState(QtCore.Qt.Checked)

        self.lastfm.settings().setAttribute(QtWebKit.QWebSettings.JavascriptEnabled, False)

        self.lastfm.settings().setAttribute(QtWebKit.QWebSettings.PrivateBrowsingEnabled, True)

        self.lastfm.load(QtCore.QUrl(os.path.join(app_lib, "notrack.html")))

 

        self.lyrics.settings().setAttribute(QtWebKit.QWebSettings.JavascriptEnabled, False)

        self.lyrics.settings().setAttribute(QtWebKit.QWebSettings.PrivateBrowsingEnabled, True)

        self.lyrics.load(QtCore.QUrl(os.path.join(app_lib, "notrack.html")))

 

#        self.pluginsDock.setContextMenuPolicy(QtCore.Qt.CustomContextMenu)

#        self.pluginsDock.setFeatures(QtGui.QDockWidget.NoDockWidgetFeatures)

        pluginsLayout.setSpacing(0)

        pluginsLayout.setContentsMargins(0,0,0,0)

 

        self.loadPlaylist(True)

        self.refreshCollection()

 

        #########################

        ## ADD WIDGETS TO GUI: ##

        #########################

        self.titleToolBar.addWidget(self.titleToolBarContent)

        self.titleToolBarContent.setLayout(self.titleToolBarLayout)

        self.titleToolBarLayout.addWidget(self.blankTitleLabel)

        self.titleToolBarLayout.addWidget(self.title)

        self.titleToolBarLayout.addWidget(self.menuBarContainer)

        self.menuBarContainer.setLayout(self.menuBarContainerLayout)

        self.menuBarContainer.layout().addWidget(self.menuBar)

        self.titleToolBarLayout.addWidget(self.windowControls)

        self.menuBar.addMenu(self.musicMenu)

        self.musicMenu.addAction(addToPlaylistAction)

        self.musicMenu.addAction(loadPlaylistAction)

        self.musicMenu.addSeparator()

        self.musicMenu.addAction(savePlaylistAsAction)

        self.musicMenu.addSeparator()

        self.musicMenu.addAction(goPreviousAction)

        self.musicMenu.addAction(self.seekBackwardAction)

        self.musicMenu.addAction(self.playPauseAction)

        self.musicMenu.addAction(self.seekForwardAction)

        self.musicMenu.addAction(goNextAction)

        self.musicMenu.addSeparator()

        self.musicMenu.addAction(quitAction)

        self.menuBar.addMenu(self.editMenu)

        self.editMenu.addAction(editTagsAction)

        self.editMenu.addAction(self.collectionEditAction)

        self.editMenu.addAction(preferencesAction)

        self.menuBar.addMenu(self.viewMenu)

        self.viewMenu.addAction(clearPlaylistAction)

        self.menuBar.addMenu(self.toolsMenu)

        self.toolsMenu.addAction(self.changeLoopAction)

        self.toolsMenu.addAction(self.shuffleAction)

        self.toolsMenu.addAction(self.rebuildCollectionAction)

        self.toolsMenu.addSeparator()

        self.toolsMenu.addAction(self.wbAction)

        self.toolsMenu.addAction(self.downloadsAction)

        self.toolsMenu.addAction(self.clearCookiesAction)

        self.menuBar.addMenu(self.helpMenu)

        self.helpMenu.addAction(helpAction)

        self.helpMenu.addAction(aboutAction)

        self.windowControls.setLayout(self.windowControlsLayout)

        self.windowControlsLayout.addWidget(self.minimizeButton)

        self.windowControlsLayout.addWidget(self.maximizeButton)

        self.windowControlsLayout.addWidget(self.closeButton)

        self.mainToolBar.addWidget(blankLabel)

        self.mainToolBar.addWidget(self.goPreviousButton)

        self.mainToolBar.addWidget(self.playPauseButton)

        self.mainToolBar.addWidget(self.goNextButton)

        self.mainToolBar.addWidget(self.timeEdit)

        self.mainToolBar.addWidget(self.progressWidget)

        self.mainToolBar.addWidget(self.remainingTimeLabel)

        self.mainToolBar.addSeparator()

        self.mainToolBar.addWidget(self.loopBox)

        self.mainToolBar.addAction(self.shuffleAction)

        self.mainToolBar.addSeparator()

        self.mainToolBar.addAction(helpAction)

        self.mainToolBar.addAction(self.openMenuButton)

 

        self.settingsDialogBox.setLayout(settingsDialogLayout)

        self.settingsDialog.setCentralWidget(self.settingsTabs)

        self.settingsTabs.addTab(self.settingsDialogBox, "&Main")

        self.settingsTabs.addTab(pluginsWindow, "&Plugins")

        settingsDialogLayout.addWidget(nLabel, 0, 0)

        settingsDialogLayout.addWidget(self.messagesBox, 1, 0)

        settingsDialogLayout.addWidget(self.titleBox, 1, 1)

        settingsDialogLayout.addWidget(self.menuBarBox, 2, 0)

        settingsDialogLayout.addWidget(pLabel, 3, 0)

        settingsDialogLayout.addWidget(self.wikipediaBox, 4, 0)

        settingsDialogLayout.addWidget(self.lastfmBox, 5, 0)

        settingsDialogLayout.addWidget(self.lyricsBox, 6, 0)

        settingsDialogLayout.addWidget(wLabel, 3, 1)

        settingsDialogLayout.addWidget(self.jamendoBox, 4, 1)

        settingsDialogLayout.addWidget(self.ngBox, 5, 1)

        settingsDialogLayout.addWidget(sLabel, 7, 0)

        settingsDialogLayout.addWidget(lyricSubBox, 8, 0)

        lyricSubBox.setLayout(lyricSubBoxLayout)

        lyricSubBoxLayout.addWidget(lyricsLabel, 0, 0)

        lyricSubBoxLayout.addWidget(self.lyricSourceBox, 0, 1)

 

        pluginsWindow.setLayout(pluginsLayout)

        pluginsLayout.addWidget(self.editPluginsButton)

        pluginsLayout.addLayout(pluginsSubLayout)

        pluginsSubLayout.addWidget(eplabel, 0, 0)

        pluginsSubLayout.addWidget(dplabel, 0, 1)

        pluginsSubLayout.addWidget(self.enabledPluginsList, 1, 0)

        pluginsSubLayout.addWidget(self.disabledPluginsList, 1, 1)

 

        self.settingsDialogToolBar.addWidget(self.saveSettingsButton)

        self.settingsDialogToolBar.addWidget(self.cancelSettingsButton)

        self.settingsDialog.addToolBar(QtCore.Qt.BottomToolBarArea, self.settingsDialogToolBar)

 

        self.collectionEditorToolBar.addWidget(self.addFilesButton)

        self.collectionEditorToolBar.addWidget(self.addFolderButton)

        self.collectionEditorToolBar.addWidget(self.removeFolderButton)

        self.collectionEditor.addToolBar(QtCore.Qt.RightToolBarArea, self.collectionEditorToolBar)

        self.collectionEditor.setCentralWidget(self.folderList)

        self.collectionEditor.addAction(self.hideCollectionAction)

        self.collectionEditor.addAction(self.removePlaylistItemAction)

        self.collectionDock.widget().layout().addWidget(self.collectionList)

 

#        self.pluginsDock.setWidget(pluginsWindow)

#        self.addDockWidget(QtCore.Qt.LeftDockWidgetArea, self.pluginsDock)

 

#        if not sys.version_info[0] >= 3:

#            tagEditorLayout.addWidget(title, 0, 0)

#        else:

#        if 1:

        tagEditorLayout.addWidget(title, 0, 0)

        tagEditorLayout.addWidget(self.titleTagField, 0, 1)

        tagEditorLayout.addWidget(artist, 1, 0)

        tagEditorLayout.addWidget(self.artistTagField, 1, 1)

        tagEditorLayout.addWidget(album, 2, 0)

        tagEditorLayout.addWidget(self.albumTagField, 2, 1)

        tagEditorLayout.addWidget(date, 3, 0)

        tagEditorLayout.addWidget(self.dateTagField, 3, 1)

        tagEditorLayout.addWidget(genre, 4, 0)

        tagEditorLayout.addWidget(self.genreTagField, 4, 1)

        tagEditorLayout.addWidget(path, 5, 0)

        tagEditorLayout.addWidget(self.pathTagField, 5, 1)

        self.tagEditorBox.setLayout(tagEditorLayout)

        self.tagEditor.setCentralWidget(self.tagEditorBox)

        self.playlistEditor.setCentralWidget(self.playlistEditorBox)

        self.playlistEditorToolBar.addWidget(self.savePlaylistButton)

        self.playlistEditorToolBar.addWidget(self.hidePlaylistEditorButton)

        self.playlistEditor.addToolBar(QtCore.Qt.RightToolBarArea, self.playlistEditorToolBar)

 

        self.mainLayout.addWidget(self.playlist)

 

        self.statusBar.addWidget(self.collectionCount)

 

        ###########################################

        ## ADD REMAINING ACTIONS TO APPLICATION: ##

        ###########################################

        self.addAction(goPreviousAction)

        self.addAction(self.seekBackwardAction)

        self.addAction(self.playPauseAction)

        self.addAction(self.seekForwardAction)

        self.addAction(goNextAction)

        self.addAction(focusTimeAction)

        self.addAction(self.changeLoopAction)

        self.addAction(aboutAction)

        self.addAction(preferencesAction)

        self.addAction(self.wbAction)

        self.addAction(self.downloadsAction)

        self.addAction(self.clearCookiesAction)

        self.addAction(quitAction)

 

        self.mainMenu.addAction(self.restoreAction)

        self.mainMenu.addSeparator()

        self.mainMenu.addAction(self.playPauseAction)

        self.mainMenu.addAction(goPreviousAction)

        self.mainMenu.addAction(self.seekBackwardAction)

        self.mainMenu.addAction(self.seekForwardAction)

        self.mainMenu.addAction(goNextAction)

        self.mainMenu.addSeparator()

        self.mainMenu.addAction(self.changeLoopAction)

        self.mainMenu.addAction(self.shuffleAction)

        self.mainMenu.addSeparator()

        self.mainMenu.addAction(preferencesAction)

        self.mainMenu.addAction(self.clearCookiesAction)

        self.mainMenu.addSeparator()

        self.mainMenu.addAction(helpAction)

        self.mainMenu.addAction(aboutAction)

        self.mainMenu.addSeparator()

        self.mainMenu.addAction(quitAction)

 

        self.addAction(focusSearchBarAction)

        self.addAction(self.rebuildCollectionAction)

        self.addAction(self.collectionEditAction)

        self.addAction(focusCollection)

 

        self.addAction(self.removePlaylistItemAction)

        self.addAction(addToPlaylistAction)

        self.addAction(removeFromPlaylistAction)

        self.addAction(clearPlaylistAction)

        self.addAction(loadPlaylistAction)

        self.addAction(savePlaylistAsAction)

        self.addAction(editTagsAction)

        self.tagEditor.addAction(hideTagAction)

        self.tagEditorToolBar.addWidget(self.saveTagsButton)

        self.tagEditorToolBar.addWidget(self.cancelTagsButton)

        self.tagEditor.addToolBar(QtCore.Qt.BottomToolBarArea, self.tagEditorToolBar)

        self.addAction(playlistEdit)

        self.playlistEditor.addAction(self.hidePlaylistAction)

        self.addAction(sortAction)

        self.sortMenu.addAction(sortTitle)

        self.sortMenu.addSeparator()

        self.sortMenu.addAction(sortByTitleAction)

        self.sortMenu.addAction(sortByArtistAction)

        self.sortMenu.addAction(sortByAlbumAction)

        self.sortMenu.addAction(sortByYearAction)

        self.sortMenu.addAction(sortByGenreAction)

 

        self.playlistMenu.addAction(editTagsAction)

        self.playlistMenu.addMenu(self.sortMenu)

        self.addAction(focusPlaylistAction)

 

        ###################

        ## CLEAN UP GUI: ##

        ###################

        self.tabifyDockWidget(self.collectionDock, self.wikiDock)

        self.tabifyDockWidget(self.collectionDock, self.lastfmDock)

        self.tabifyDockWidget(self.collectionDock, self.lyricsDock)

        self.collectionDock.raise_()

        self.playlistEditor.resize(640, 480)

 

        #########################

        ## FINAL PREPARATIONS: ##

        #########################

        if self.playStart == True:

            self.loadMedia(self.playlist.item(self.playlist.count()-1))

            self.playStart = False

            self.playlist.setCurrentRow(self.playlist.count()-1)

 

        self.loadSettings()

        self.settingsDialog.show()

        qr = self.settingsDialog.frameGeometry()

        cp = QtGui.QDesktopWidget().availableGeometry().center()

        qr.moveCenter(cp)

        self.settingsDialog.move(qr.topLeft())

 

        self.folderList.clear()

        if self.collectionEditor.isHidden() == True:

            for line in collectionManager.folders:

                newline = line.replace("\n", "")

                self.folderList.addItem(unicode(newline))

        if not os.path.exists(os.path.join(app_home, "collection.json")):

            self.rebuildCollection()

        elif autoRebuild == True:

            self.rebuildCollection()

 

        self.settingsDialog.hide()

 

        self.loadPluginsLists()

 

        enabledplugins = []

        disabledplugins = []

 

        if os.path.exists(os.path.join(app_lib, "plugins")):

            plugins_folder = os.listdir(os.path.join(app_lib, "plugins"))

            for fname in plugins_folder:

                if fname in self.pWhitelist:

                    try: plugin = open(os.path.join(app_lib, "plugins", fname))

                    except:

                        doNothing()

                    else:

                        try: pluginContents = plugin.readlines()

                        except:

                            plugin.close()

                        else:

                            plugin.close()

                            enabledplugins.append(fname)

                            errors = 0

                            for line in pluginContents:

                                try: exec(line)

                                except:

                                    errors += 1

                            print("Plugin", fname, "was loaded with", errors, "errors.")

                else:

                    try: plugin = open(os.path.join(app_lib, "plugins", fname))

                    except:

                        doNothing()

                    else:

                        plugin.close()

                        disabledplugins.append(fname)

                        print("Plugin", fname, "was disabled and thus not loaded.")

            del plugins_folder

    

        if os.path.exists(os.path.join(app_home, "plugins")):

            plugins_folder = os.listdir(os.path.join(app_home, "plugins"))

            for fname in plugins_folder:

                if fname in self.pWhitelist:

                    try: plugin = open(os.path.join(app_home, "plugins", fname))

                    except:

                        doNothing()

                    else:

                        try: pluginContents = plugin.readlines()

                        except:

                            plugin.close()

                        else:

                            plugin.close()

                            enabledplugins.append(fname)

                            errors = 0

                            for line in pluginContents:

                                try: exec(line)

                                except:

                                    errors += 1

                            print("Plugin", fname, "was loaded with", errors, "errors.")

                else:

                    try: plugin = open(os.path.join(app_home, "plugins", fname))

                    except:

                        doNothing()

                    else:

                        plugin.close()

                        disabledplugins.append(fname)

                        print("Plugin", fname, "was disabled and thus not loaded.")

            del plugins_folder

 

        self.enabledPluginsList.clear()

        for plugin in enabledplugins:

            self.enabledPluginsList.addItem(unicode(plugin))

        self.enabledPluginsList.sortItems(QtCore.Qt.AscendingOrder)

        self.disabledPluginsList.clear()

        for plugin in disabledplugins:

            self.disabledPluginsList.addItem(unicode(plugin))

        self.disabledPluginsList.sortItems(QtCore.Qt.AscendingOrder)

        del enabledplugins

        del disabledplugins

 

        if settingsManager.settings[‘cTitleBar‘]:

            self.normalStyleSheet = self.customTitleBarSheetNormal

            self.maximizedStyleSheet = self.customTitleBarSheetMaximized

            self.menuBar.setStyleSheet(self.customTitleBarMenuBarSheet)

        else:

            self.normalStyleSheet = self.nativeTitleBarSheetNormal

            self.maximizedStyleSheet = self.nativeTitleBarSheetMaximized

        if not self.isMaximized():

            self.setStyleSheet(self.normalStyleSheet)

        else:

            self.setStyleSheet(self.maximizedStyleSheet)

 

## UNORGANIZED

#################################################################################################################################

#################################################################################################################################

 

    def loadSettings(self):

        try: settingsManager.settings["messagesOn"]

        except:

            settingsManager.settings["messagesOn"] = True

        self.messagesBox.setChecked(settingsManager.settings["messagesOn"])

        try: settingsManager.settings["showMenuBar"]

        except:

            settingsManager.settings["showMenuBar"] = True

        self.menuBarBox.setChecked(settingsManager.settings[‘showMenuBar‘])

        try: settingsManager.settings["cTitleBar"]

        except:

            if sys.platform.startswith("win"):

                settingsManager.settings["cTitleBar"] = True

            else:

                settingsManager.settings["cTitleBar"] = False

        self.titleBox.setChecked(settingsManager.settings["cTitleBar"])

        self.applyCTitleBar()

        try: settingsManager.settings["wikipediaOff"]

        except:

            settingsManager.settings["wikipediaOff"] = False

        self.wikipediaBox.setCheckState(QtCore.Qt.Checked)

        self.wikipediaBox.setChecked(not settingsManager.settings[‘wikipediaOff‘])

        try: settingsManager.settings[‘lastfmOff‘]

        except:

            settingsManager.settings[‘lastfmOff‘] = False

        self.lastfmBox.setChecked(True)

        self.lastfmBox.setChecked(not settingsManager.settings[‘lastfmOff‘])

        try: settingsManager.settings[‘lyricsOff‘]

        except:

            settingsManager.settings[‘lyricsOff‘] = False

        self.lyricsBox.setChecked(True)

        self.lyricsBox.setChecked(not settingsManager.settings[‘lyricsOff‘])

        try: settingsManager.settings[‘lyricSource‘]

        except:

            settingsManager.settings[‘lyricSource‘] = 0

        self.lyricSourceBox.setCurrentIndex(settingsManager.settings[‘lyricSource‘])

    

    def applyCTitleBar(self):

        if settingsManager.settings[‘cTitleBar‘]:

            self.setWindowFlags(QtCore.Qt.FramelessWindowHint)

            self.blankTitleLabel.setVisible(True)

            self.windowControls.setVisible(True)

            self.title.setVisible(True)

            self.menuBar.setStyleSheet(self.customTitleBarMenuBarSheet)

            self.normalStyleSheet = self.customTitleBarSheetNormal

            self.maximizedStyleSheet = self.customTitleBarSheetMaximized

            if settingsManager.settings[‘showMenuBar‘]:

                self.menuBar.show()

                self.openMenuButton.setVisible(False)

            else:

                self.menuBar.hide()

                self.openMenuButton.setVisible(True)

            self.titleToolBar.show()

        else:

            self.setWindowFlags(QtCore.Qt.Widget)

            self.blankTitleLabel.setVisible(False)

            self.windowControls.setVisible(False)

            self.title.setVisible(False)

            self.menuBar.setStyleSheet("")

            self.normalStyleSheet = self.nativeTitleBarSheetNormal

            self.maximizedStyleSheet = self.nativeTitleBarSheetMaximized

            if settingsManager.settings[‘showMenuBar‘]:

                self.menuBar.show()

                self.openMenuButton.setVisible(False)

                if not "ubuntu" in app_unity:

                    self.titleToolBar.show()

                else:

                    self.titleToolBar.hide()

            else:

                self.menuBar.hide()

                self.openMenuButton.setVisible(True)

                self.titleToolBar.hide()

        if not self.isMaximized():

            self.setStyleSheet(self.normalStyleSheet)

        else:

            self.setStyleSheet(self.maximizedStyleSheet)

        self.show()

 

    def maximize(self):

        if self.isMaximized():

            self.setStyleSheet(self.normalStyleSheet)

            self.setWindowState(QtCore.Qt.WindowNoState)

            self.maximizeButton.setIcon(QtGui.QIcon(os.path.join(app_lib, "icons", "maximize.png")))

            self.maximizeButton.setToolTip("Maximize Window")

        else:

            self.setStyleSheet(self.maximizedStyleSheet)

            self.setWindowState(QtCore.Qt.WindowMaximized)

            self.maximizeButton.setIcon(QtGui.QIcon(os.path.join(app_lib, "icons", "restore.png")))

            self.maximizeButton.setToolTip("Restore Window")

 

    def quit(self):

        self.saveCookies()

        QtCore.QCoreApplication.instance().quit()

        sys.exit()

 

    def saveCookies(self):

        if self.killCookies == False:

            cookieFile = open(self.cookieFile, "wb")

            cookies = []

            for c in self.cookies.allCookies():

                cookies.append(c.toRawForm())

            pickle.dump(cookies, cookieFile)

            cookieFile.close()

        else:

            try: os.remove(self.cookieFile)

            except:

                doNothing()

 

    def toggleClearCookies(self):

        self.killCookies = not self.killCookies

        if self.killCookies:

            self.clearCookiesAction.setText(tr(‘preserveCookies‘))

            self.dialogHandler.message(tr(‘willClearCookies‘), tr(‘notice‘), "info")

        else:

            self.clearCookiesAction.setText(tr(‘clearCookies‘))

            self.dialogHandler.message(tr(‘willSaveCookies‘), tr(‘notice‘), "info")

 

    def loadCookies(self):

        if os.path.exists(self.cookieFile):

            cookieFile = open(self.cookieFile, "rb")

            cookies = []

            try: cookies = pickle.load(cookieFile)

            except:

                print(tr(‘cookieError‘))

            else:

                doNothing()

            cookieFile.close()

            return cookies

        else:

            return []

 

    def enableDisableSpace(self):

        if not self.playlist.hasFocus():

            self.seekBackwardAction.setShortcut("")

            self.seekForwardAction.setShortcut("")

            if not self.collectionList.hasFocus():

                self.playPauseAction.setShortcut("")

            else:

                self.playPauseAction.setShortcut("Space")                

        else:

            self.seekBackwardAction.setShortcut("Left")

            self.seekForwardAction.setShortcut("Right")

            self.playPauseAction.setShortcut("Space")

 

    def closeEvent(self, event):

        event.ignore()

        self.trayIconActivated(QtGui.QSystemTrayIcon.Trigger)

        self.trayIcon.showMessage("" + app_name + tr(‘minimizedToTrayTitle‘), tr(‘minimizedToTrayBody‘))

 

    def enableDisableMessages(self):

        if self.messagesBox.isChecked():

            settingsManager.settings["messagesOn"] = True

        else:

            settingsManager.settings["messagesOn"] = False

 

    def enableDisableCTitleBar(self):

        settingsManager.settings[‘cTitleBar‘] = self.titleBox.isChecked()

        self.applyCTitleBar()

 

    def enableDisableMenuBarBox(self):

        settingsManager.settings[‘showMenuBar‘] = self.menuBarBox.isChecked()

        self.applyCTitleBar()

 

    def enableDisableWikipedia(self):

        if not self.wikipediaBox.isChecked():

            settingsManager.settings["wikipediaOff"] = True

            self.wikiDock.hide()

        else:

            settingsManager.settings["wikipediaOff"] = False

            self.wikiDock.show()

 

    def enableDisableLastfm(self):

        if not self.lastfmBox.isChecked():

            settingsManager.settings[‘lastfmOff‘] = True

            self.lastfmDock.hide()

        else:

            settingsManager.settings[‘lastfmOff‘] = False

            self.lastfmDock.show()

 

    def enableDisableLyrics(self):

        if not self.lyricsBox.isChecked():

            settingsManager.settings[‘lyricsOff‘] = True

            self.lyricsDock.hide()

        else:

            settingsManager.settings[‘lyricsOff‘] = False

            self.lyricsDock.show()

 

    def enableDisableJamendo(self):

        if not self.jamendoBox.isChecked():

            settingsManager.settings[‘jamendoOff‘] = True

        else:

            settingsManager.settings[‘jamendoOff‘] = False

 

    def enableDisableNG(self):

        if not self.ngBox.isChecked():

            settingsManager.settings[‘ngOff‘] = True

        else:

            settingsManager.settings[‘ngOff‘] = False

 

    def loadNGUser(self):

        self.ngMusicViewer.load(QtCore.QUrl("http://" + self.ngUserLoader.text() + ".newgrounds.com/audio/"))

 

    def setLyricSource(self):

        settingsManager.settings[‘lyricSource‘] = self.lyricSourceBox.currentIndex()

 

    def fileNotFound(self, path):

        if path != "" and path != None:

            self.dialogHandler.message(path + tr(‘fileError‘), tr(‘error‘), "warn")

    def raiseCollection(self):

        self.collectionDock.raise_()

 

    def setUnsorted(self):

        self.orderLabel.setText(tr(‘unsorted‘))

        self.collectionCount.setText(unicode(self.playlist.count()) + tr(‘inPlaylist‘) + unicode(len(collectionManager.collection)) + tr(‘inCollection‘))

        print("Playlist changed; assuming that it has become unsorted.")

 

    def setOrderText(self):

        if self.ascending == True:

            self.orderLabel.setText(tr(‘normalOrder‘))

            print("in normal order.")

        else:

            self.orderLabel.setText(tr(‘reverseOrder‘))

            print("in reverse order.")

    def sortByTitle(self):

        if self.ascending == False:

            self.playlist.sortByColumn(0, QtCore.Qt.AscendingOrder)

        else:

            self.playlist.sortByColumn(0, QtCore.Qt.DescendingOrder)

        self.ascending = not self.ascending

        print(tr(‘sortedByTitle‘), end="")

        self.setOrderText()

    def sortByArtist(self):

        if self.ascending == False:

            self.playlist.sortByColumn(2, QtCore.Qt.AscendingOrder)

        else:

            self.playlist.sortByColumn(2, QtCore.Qt.DescendingOrder)

        self.ascending = not self.ascending

        print(tr(‘sortedByArtist‘), end="")

        self.setOrderText()

    def sortByAlbum(self):

        if self.ascending == False:

            self.playlist.sortByColumn(3, QtCore.Qt.AscendingOrder)

        else:

            self.playlist.sortByColumn(3, QtCore.Qt.DescendingOrder)

        self.ascending = not self.ascending

        print(tr(‘sortedByAlbum‘), end="")

        self.setOrderText()

    def sortByYear(self):

        if self.ascending == False:

            self.playlist.sortByColumn(4, QtCore.Qt.AscendingOrder)

        else:

            self.playlist.sortByColumn(4, QtCore.Qt.DescendingOrder)

        self.ascending = not self.ascending

        print(tr(‘sortedByYear‘), end="")

        self.setOrderText()

    def sortByGenre(self):

        if self.ascending == False:

            self.playlist.sortByColumn(5, QtCore.Qt.AscendingOrder)

        else:

            self.playlist.sortByColumn(5, QtCore.Qt.DescendingOrder)

        self.ascending = not self.ascending

        print(tr(‘sortedByGenre‘), end="")

        self.setOrderText()

    def aboutDialog(self):

        self.dialogHandler.aboutMessage("<h1 style=‘margin-bottom: 0;‘>" + app_name + " " + self.version + "</h1><h3 style=‘margin-top: 0; margin-bottom: 0;‘>\"" + self.codename + "\"</h3><h4 style=‘margin-top: 0; margin-bottom: 0;‘>" + tr(‘using‘) + "Qt " + unicode(QtCore.qVersion()) + "/Python " + unicode(sys.version_info[0]) + "." + unicode(sys.version_info[1]) + "." + unicode(sys.version_info[2]) + "</h4>Copyright (c) 2011-2012 by foxhead128<br><a href=‘" + app_homepage + "‘>" + app_homepage + "</a>", tr(‘aboutTitle‘) + app_name + "", os.path.join(app_lib, "images", "aboutimage.png"))

    def showSortMenu(self):

        if self.menu2Shown == False:

            self.sortMenu.move(QtGui.QApplication.desktop().size().width(), QtGui.QApplication.desktop().size().height())

            self.sortMenu.show()

            self.menu2Shown = True

        if QtGui.QCursor.pos().x() < self.sortMenu.width():

            x = 0

        else:

            x = self.sortMenu.width()

        if QtGui.QCursor.pos().y() + self.sortMenu.height() > QtGui.QApplication.desktop().size().height():

            y = self.sortMenu.height()

        else:

            y = 0

        self.sortMenu.move(QtCore.QPoint(QtGui.QCursor.pos().x() - x, QtGui.QCursor.pos().y() - y))

        self.sortMenu.show()

    def showPlaylistMenu(self):

        if self.menu3Shown == False:

            self.playlistMenu.move(QtGui.QApplication.desktop().size().width(), QtGui.QApplication.desktop().size().height())

            self.playlistMenu.show()

            self.menu3Shown = True

        if QtGui.QCursor.pos().x() + self.playlistMenu.width() > QtGui.QApplication.desktop().size().width():

            x = self.playlistMenu.width()

        else:

            x = 0

        if QtGui.QCursor.pos().y() + self.playlistMenu.height() > QtGui.QApplication.desktop().size().height():

            y = self.playlistMenu.height()

        else:

            y = 0

        self.playlistMenu.move(QtCore.QPoint(QtGui.QCursor.pos().x() - x, QtGui.QCursor.pos().y() - y))

        self.playlistMenu.show()

    def showMenu(self):

        if self.menuShown == False:

            self.mainMenu.move(QtGui.QApplication.desktop().size().width(), QtGui.QApplication.desktop().size().height())

            self.mainMenu.show()

            self.menuShown = True

        if QtGui.QCursor.pos().x() < self.mainMenu.width():

            x = 0

        else:

            x = self.mainMenu.width()

        if QtGui.QCursor.pos().y() + self.mainMenu.height() > QtGui.QApplication.desktop().size().height():

            y = self.mainMenu.height()

        else:

            y = 0

        self.mainMenu.move(QtCore.QPoint(QtGui.QCursor.pos().x() - x, QtGui.QCursor.pos().y() - y))

        self.mainMenu.show()

    def help(self):

        if sys.platform.startswith("win"):

            webbrowser.open("file://" + os.path.join(app_lib, "help", "index.html"))

        else:

            self.dialogHandler.urlDialog(os.path.join(app_lib, "help", "index.html"))

            self.dialogHandler.webDialog.setWindowTitle("" + app_name + " " + tr(‘documentation‘))

            self.dialogHandler.webDialog.setWindowIcon(QtGui.QIcon().fromTheme("help-contents", QtGui.QIcon(os.path.join(app_lib, "icons", "help.png"))))

 

    def changeLoopActionText(self):

        if self.loopBox.checkState() == QtCore.Qt.Unchecked:

            self.changeLoopAction.setText(tr("noLoop"))

        elif self.loopBox.checkState() == QtCore.Qt.PartiallyChecked:

            self.changeLoopAction.setText(tr("loopPlaylist"))

        else:

            self.changeLoopAction.setText(tr("loopTrack"))

 

    def forceTrayIconActivated(self):

        self.trayIconActivated(QtGui.QSystemTrayIcon.Trigger)

    

    def trayIconActivated(self, reason):

        if reason == QtGui.QSystemTrayIcon.Trigger:

            self.setVisible(not self.isVisible())

            if not "ubuntu" in app_unity:

                if self.isVisible() == False:

                    self.goNextIcon.setVisible(True)

                    self.seekForwardIcon.setVisible(True)

                    self.playPauseIcon.setVisible(True)

                    self.seekBackwardIcon.setVisible(True)

                    self.goPreviousIcon.setVisible(True)

                else:

                    self.goNextIcon.setVisible(False)

                    self.seekForwardIcon.setVisible(False)

                    self.playPauseIcon.setVisible(False)

                    self.seekBackwardIcon.setVisible(False)

                    self.goPreviousIcon.setVisible(False)

 

    def changeCollection(self):

        self.folderList.clear()

        self.collectionEditor.show()

        collectionFileContents = collectionManager.folders

        for line in collectionFileContents:

            newline = line.replace("\n", "")

            self.folderList.addItem(unicode(newline))

        qr = self.collectionEditor.frameGeometry()

        cp = QtGui.QDesktopWidget().availableGeometry().center()

        qr.moveCenter(cp)

        self.collectionEditor.move(qr.topLeft())

 

    # Define various methods for " + app_name + ":

    def hidePlaylistEditor(self):

        self.playlistEditor.hide()

    def hideCollectionEditor(self):

        self.collectionEditor.hide()

    def addCollectionItem(self):

        NewFolder = self.dialogHandler.folderDialog()

        if NewFolder:

            self.folderList.addItem(unicode(NewFolder))

            self.rebuildCollectionWithWarning()

    def addCollectionFiles(self):

        filters = tr(‘allSupportedAudio‘) + " ("

        for extension in extensions:

            filters = filters + "*" + extension + " "

        filters = filters + ");;" + tr(‘allFiles‘) + " (*)"

        NewFiles = self.dialogHandler.multiLoadDialog(filters)

        if NewFiles:

            for File in range(NewFiles.count()):

                self.folderList.addItem(unicode(NewFiles[File - 1]))

            self.rebuildCollectionWithWarning()

    def removeCollectionItem(self):

        self.folderList.takeItem(self.folderList.currentRow())

        self.rebuildCollectionWithWarning()

    def refreshCollection(self):

        self.collectionList.clear()

        itemNum = QtGui.QTreeWidgetItem(["0-9", "", "", "", "", ""])

        self.collectionList.addTopLevelItem(itemNum)

        for char in range(0, 26):

            exec("item" + chr(65 + char) + ‘ = QtGui.QTreeWidgetItem(["‘ + chr(65 + char) + ‘", "", "", "", "", ""])‘)

            exec("self.collectionList.addTopLevelItem(" + "item" + chr(65 + char) + ")")

        itemOther = QtGui.QTreeWidgetItem(["Other", "", "", "", "", ""])

        self.collectionList.addTopLevelItem(itemOther)

        for item in collectionManager.collection:

            try: newItem = QtGui.QTreeWidgetItem([item[‘artist‘], item[‘title‘] + "\n" + item[‘path‘]])

            except:

                newItem = QtGui.QTreeWidgetItem([item[2], item[1] + "\n" + item[0]])

            wasAdded = False

            try: item[‘artist‘]

            except:

                for num in range(0, 9):

                    if unicode(item[2]).startswith(unicode(num)):

                        itemNum.addChild(newItem)

                        wasAdded = True

                        break

                if wasAdded == False:

                    for char in range(0, 26):

                        if unicode(item[2]).upper().startswith(chr(65 + char).upper()):

                            exec("item" + chr(65 + char) + ".addChild(newItem)")

                            wasAdded = True

                            break

            else:

                for num in range(0, 9):

                    if unicode(item[‘artist‘]).startswith(unicode(num)):

                        itemNum.addChild(newItem)

                        wasAdded = True

                        break

                if wasAdded == False:

                    for char in range(0, 26):

                        if unicode(item[‘artist‘]).upper().startswith(chr(65 + char).upper()):

                            exec("item" + chr(65 + char) + ".addChild(newItem)")

                            wasAdded = True

                            break

            if wasAdded == False:

                itemOther.addChild(newItem)

        self.collectionCount.setText(unicode(self.playlist.count()) + tr(‘inPlaylist‘) + unicode(len(collectionManager.collection)) + tr(‘inCollection‘))

        itemNum.sortChildren(0, QtCore.Qt.AscendingOrder)

        for char in range(0, 26):

            exec("item" + chr(65 + char) + ".sortChildren(0, QtCore.Qt.AscendingOrder)")

        itemOther.sortChildren(0, QtCore.Qt.AscendingOrder)

        #self.collectionList.sortByColumn(1, QtCore.Qt.AscendingOrder)

    def moodbarWarning(self):

        if not os.path.exists(os.path.join(os.path.split(unicode(self.mediaObject.currentSource().url().toString()).replace("file://",""))[0], "." + os.path.split(unicode(self.mediaObject.currentSource().url().toString()).replace("file://",""))[1] + ".mood")):

            print("Generating moodbar...")

    def rebuildCollectionWithWarning(self):

        self.trayIcon.showMessage("" + app_name + tr(‘rebuildingCollection‘), "")

        self.rebuildCollection()

    def rebuildCollection(self):

        collectionBuilder.folderList = []

        for item in range(self.folderList.count()):

            collectionBuilder.folderList.append(self.folderList.item(item).text())

        collectionBuilder.start()

        self.updateMetaData()

    def collectionYay(self):

        self.trayIcon.showMessage(tr(‘collectionYay‘), "")

    def focusSearchBar(self):

        self.searchBar.setFocus()

        self.searchBar.selectAll()

    def search(self, terms):

        self.collectionList.clear()

        if len(terms) == 0:

            self.searchOn = False

        if len(terms) == 1:

            self.searchOn = True

            collectionManager.reload()

        term = unicode(terms)

        operator = True

        fields = {‘title‘ : True, ‘artist‘ : True, ‘album‘ : True, \

        ‘year‘ : True, ‘date‘ : True, ‘genre‘ : True, ‘path‘ : False}

        if len(term) == 0:

            self.refreshCollection()

        else:

            if term.startswith("+") or term.startswith("-"):

                for char in term:

                    if char == "+":

                        operator = True

                        term = term.strip(‘+‘)

                    elif char == "-":

                        operator = False

                        term = term.strip(‘-‘)

                    elif char == " ":

                        term = term.strip(‘ ‘)

                        break

                    else:

                        if char.lower() == ‘t‘:

                            fields[‘title‘] = operator

                            term = term.strip(‘t‘)

                            term = term.strip(‘T‘)

                        elif char.lower() == ‘b‘:

                            fields[‘artist‘] = operator

                            term = term.strip(‘b‘)

                            term = term.strip(‘B‘)

                        elif char.lower() == ‘a‘:

                            fields[‘album‘] = operator

                            term = term.strip(‘a‘)

                            term = term.strip(‘A‘)

                        elif char.lower() == ‘y‘ or char.lower() == ‘d‘:

                            fields[‘year‘] = operator

                            fields[‘date‘] = operator

                            term = term.strip(‘y‘)

                            term = term.strip(‘Y‘)

                            term = term.strip(‘d‘)

                            term = term.strip(‘D‘)

                        elif char.lower() == ‘g‘:

                            fields[‘genre‘] = operator

                            term = term.strip(‘g‘)

                            term = term.strip(‘G‘)

                        elif char.lower() == ‘p‘:

                            fields[‘path‘] = operator

                            term = term.strip(‘p‘)

                            term = term.strip(‘P‘)

            for item in collectionManager.collection:

                if os.path.exists(item[‘path‘]):

                    split = os.path.split(item[‘path‘])

                    metadata = ""

                    append = False

                    for value in item:

                        try: fields[value]

                        except:

                            doNothing()

                        else:

                            if fields[value] == True:

                                try: term.lower()

                                except:

                                    doNothing()

                                else:

                                    try: unicode(value).lower()

                                    except:

                                        doNothing()

                                    else:

                                        if term.lower() in unicode(item[value]).lower():

                                            append = True

                                            break

                    if append:

                        try: newItem = QtGui.QTreeWidgetItem([item[‘artist‘], item[‘title‘] + "\n" + item[‘path‘]])

                        except:

                            newItem = QtGui.QTreeWidgetItem([item[2], item[1] + "/n" + item[0]])

                        self.collectionList.addTopLevelItem(newItem)

            self.collectionList.sortByColumn(0, QtCore.Qt.AscendingOrder)

    def addToPlaylist(self):

        filters = tr(‘allSupportedAudio‘) + " ("

        for extension in extensions:

            filters = filters + "*" + extension + " "

        filters = filters + ");;" + tr(‘allFiles‘) + " (*)"

        items = self.dialogHandler.multiLoadDialog(filters)

        if items:

            for item in range(len(items)):

                self.playlist.addItem(unicode(items[item - 1]))

            self.orderLabel.setText(tr(‘unsorted‘))

            self.playlist.rewritePlaylist()

    def removeFromPlaylist(self):

        self.removePlaylistItem(True)

    def clearPlaylist(self):

        yesNo = self.dialogHandler.confirmBox(tr(‘confirmClearPlaylist‘))

        if yesNo == QtGui.QMessageBox.Yes:

            self.playlist.clear()

            self.rewritePlaylist()

    def addMedia(self, item=""):

        if sys.version_info[0] <= 2:

            text = unicode(item.data(1, 0).toString()).partition("\n")[2]

        else:

            text = unicode(item.data(1, 0)).partition("\n")[2]

        self.playlist.addItem(unicode(text))

        if self.playPauseButton.isChecked() == False:

            self.playlist.setCurrentRow(self.playlist.count()-1)

            self.loadMedia(self.playlist.currentItem())

            self.playPause(True)

            self.setPosition()

        if len(text) > 0:

            self.setUnsorted()

        self.rewritePlaylist()

    def loadLyrics007(self):

        titleToLoad = ""

        try:

            self.mediaObject.metaData(Phonon.TitleMetaData)[0]

        except:

            doNothing()

            title = tr(‘untitled‘)

        else:

            if self.mediaObject.metaData(Phonon.TitleMetaData)[0] == "":

                title = tr(‘untitled‘)

            else:

                titleToLoad = self.mediaObject.metaData(Phonon.TitleMetaData)[0]

        artistToLoad = ""

        try:

            self.mediaObject.metaData(Phonon.ArtistMetaData)[0]

        except:

            doNothing()

            artist = tr(‘unknownArtist‘)

        else:

            artistToLoad = self.mediaObject.metaData(Phonon.ArtistMetaData)[0]

            if self.mediaObject.metaData(Phonon.ArtistMetaData)[0] == "":

               artist = tr(‘unknownArtist‘)

        self.lyricSettings = self.lyrics.settings()

        self.lyricSettings.setUserStyleSheetUrl(QtCore.QUrl("file://" + os.path.join(app_lib, "lyrics007.css")))

        self.lyrics.load(QtCore.QUrl("http://www.lyrics007.com/" + artistToLoad + " Lyrics/" + titleToLoad + " Lyrics.html"))

        print("Loaded lyrics from Lyrics007.")

    def loadMetroLyrics(self):

        titleToLoad = ""

        try:

            self.mediaObject.metaData(Phonon.TitleMetaData)[0]

        except:

            doNothing()

            title = tr(‘untitled‘)

        else:

            if self.mediaObject.metaData(Phonon.TitleMetaData)[0] == "":

                title = tr(‘untitled‘)

            else:

                titleToLoad = self.mediaObject.metaData(Phonon.TitleMetaData)[0]

        artistToLoad = ""

        try:

            self.mediaObject.metaData(Phonon.ArtistMetaData)[0]

        except:

            doNothing()

            artist = tr(‘unknownArtist‘)

        else:

            artistToLoad = self.mediaObject.metaData(Phonon.ArtistMetaData)[0]

            if self.mediaObject.metaData(Phonon.ArtistMetaData)[0] == "":

               artist = tr(‘unknownArtist‘)

        self.lyricSettings = self.lyrics.settings()

        self.lyricSettings.setUserStyleSheetUrl(QtCore.QUrl("file://" + os.path.join(app_lib, "null.css")))

        self.lyrics.load(QtCore.QUrl("http://m.metrolyrics.com/" + titleToLoad.replace(" ", "-") + "-" + artistToLoad.replace(" ", "-") + ".html"))

        print("Loaded lyrics from MetroLyrics.")

    def loadELyrics(self):

        titleToLoad = ""

        try:

            self.mediaObject.metaData(Phonon.TitleMetaData)[0]

        except:

            doNothing()

            title = tr(‘untitled‘)

        else:

            if self.mediaObject.metaData(Phonon.TitleMetaData)[0] == "":

                title = tr(‘untitled‘)

            else:

                titleToLoad = self.mediaObject.metaData(Phonon.TitleMetaData)[0]

        artistToLoad = ""

        try:

            self.mediaObject.metaData(Phonon.ArtistMetaData)[0]

        except:

            doNothing()

            artist = tr(‘unknownArtist‘)

        else:

            artistToLoad = self.mediaObject.metaData(Phonon.ArtistMetaData)[0]

            if self.mediaObject.metaData(Phonon.ArtistMetaData)[0] == "":

               artist = tr(‘unknownArtist‘)

        self.lyricSettings = self.lyrics.settings()

        self.lyricSettings.setUserStyleSheetUrl(QtCore.QUrl("file://" + os.path.join(app_lib, "elyrics.css")))

        self.lyrics.load(QtCore.QUrl("http://www.elyrics.net/read/" + unicode(artistToLoad[0]).lower() + "/" + unicode(artistToLoad.replace(" ", "-")).lower() + "-lyrics/" + unicode(titleToLoad.replace(" ", "-")).lower() + "-lyrics.html"))

        print("Loaded lyrics from eLyrics.")

    def trayMessage(self):

        checked = self.playPauseButton.isChecked()

        title = tr(‘untitled‘)

        try: title = self.mediaObject.metaData(Phonon.TitleMetaData)[0]

        except:

            doNothing()

        artist = tr(‘unknownArtist‘)

        try: artist = self.mediaObject.metaData(Phonon.ArtistMetaData)[0]

        except:

            doNothing()

        album = tr(‘unknownAlbum‘)

        try: album = self.mediaObject.metaData(Phonon.AlbumMetaData)[0]

        except:

            doNothing()

        try: settingsManager.settings["messagesOn"]

        except:

            settingsManager.settings["messagesOn"] = True

        if settingsManager.settings["messagesOn"]:

            if checked == True:

                self.mediaObject.play()

                self.trayIcon.showMessage(unicode(tr(‘nowPlayingLabel‘)) + unicode(title), "" + tr(‘artistLabel‘) + unicode(artist) + " | " + tr(‘albumLabel‘) + unicode(album) + "\n" + tr(‘clickToClose‘))

            else:

                self.mediaObject.pause()

                self.trayIcon.showMessage(unicode(tr(‘pausedLabel‘)) + unicode(title), tr(‘artistLabel‘) + unicode(artist) + " | " + tr(‘albumLabel‘) + unicode(album) + "\n" + tr("clickToClose"))

    def updateMetaData(self, loadpages = True):

        title = tr(‘untitled‘)

        titleToLoad = ""

        currentSource = unicode(self.mediaObject.currentSource().url().toString()).replace("file://", "")

        split = os.path.split(unicode(unicode(self.mediaObject.currentSource().url().toString())).replace("file://", ""))

        try:

            album = self.mediaObject.metaData(Phonon.TitleMetaData)[0]

        except:

            doNothing()

        else:

            if not self.mediaObject.metaData(Phonon.TitleMetaData)[0] == "":

                title = self.mediaObject.metaData(Phonon.TitleMetaData)[0]

        artist = tr(‘unknownArtist‘)

        try:

            artist = self.mediaObject.metaData(Phonon.ArtistMetaData)[0]

        except:

            doNothing()

            self.wikipedia.load(QtCore.QUrl(os.path.join(app_lib, "artistfail.html")))

            self.lastfm.load(QtCore.QUrl(os.path.join(app_lib, "artistfail.html")))

        else:

            if not self.mediaObject.metaData(Phonon.ArtistMetaData)[0] == "":

                artist = self.mediaObject.metaData(Phonon.ArtistMetaData)[0]

            if self.mediaObject.metaData(Phonon.ArtistMetaData)[0] == "":

                if settingsManager.settings["wikipediaOff"] == False:

                    self.wikipedia.load(QtCore.QUrl(os.path.join(app_lib, "artistfail.html")))

                if settingsManager.settings[‘lastfmOff‘] == False:

                    self.lastfm.load(QtCore.QUrl(os.path.join(app_lib, "artistfail.html")))

            else:

                if settingsManager.settings["wikipediaOff"] == False:

                    self.wikipedia.load(QtCore.QUrl("http://en.m.wikipedia.org/wiki/" + artist))

                if settingsManager.settings[‘lastfmOff‘] == False:

                    self.lastfm.load(QtCore.QUrl("http://m.last.fm/music/" + artist + "/+wiki"))

        if loadpages == True and settingsManager.settings[‘lyricsOff‘] == False:

            if settingsManager.settings[‘lyricSource‘] == 1:

                self.loadMetroLyrics()

            elif settingsManager.settings[‘lyricSource‘] == 2:

                self.loadELyrics()

            else:

                self.loadLyrics007()

        self.setWindowTitle(title + " by " + artist + " - " + app_name + "")

        self.title.setText("<b>" + title + " by " + artist + " - " + app_name + "</b>")

    def loadMoodbar(self):

        if sys.platform.startswith("linux") and os.path.exists("/usr/bin/moodbar"):

            self.moodbarViewer.setHtml("<html><body style=\"border: 1px solid ThreeDShadow; color: ThreeDShadow; font-family: sans-serif; font-size: 6px; margin: 0; background-repeat: no-repeat; background-image: url(data:image/gif;base64,R0lGODlhAQABAOcAAAAAAAEBAQICAgMDAwQEBAUFBQYGBgcHBwgICAkJCQoKCgsLCwwMDA0NDQ4ODg8PDxAQEBERERISEhMTExQUFBUVFRYWFhcXFxgYGBkZGRoaGhsbGxwcHB0dHR4eHh8fHyAgICEhISIiIiMjIyQkJCUlJSYmJicnJygoKCkpKSoqKisrKywsLC0tLS4uLi8vLzAwMDExMTIyMjMzMzQ0NDU1NTY2Njc3Nzg4ODk5OTo6Ojs7Ozw8PD09PT4+Pj8/P0BAQEFBQUJCQkNDQ0REREVFRUZGRkdHR0hISElJSUpKSktLS0xMTE1NTU5OTk9PT1BQUFFRUVJSUlNTU1RUVFVVVVZWVldXV1hYWFlZWVpaWltbW1xcXF1dXV5eXl9fX2BgYGFhYWJiYmNjY2RkZGVlZWZmZmdnZ2hoaGlpaWpqamtra2xsbG1tbW5ubm9vb3BwcHFxcXJycnNzc3R0dHV1dXZ2dnd3d3h4eHl5eXp6ent7e3x8fH19fX5+fn9/f4CAgIGBgYKCgoODg4SEhIWFhYaGhoeHh4iIiImJiYqKiouLi4yMjI2NjY6Ojo+Pj5CQkJGRkZKSkpOTk5SUlJWVlZaWlpeXl5iYmJmZmZqampubm5ycnJ2dnZ6enp+fn6CgoKGhoaKioqOjo6SkpKWlpaampqenp6ioqKmpqaqqqqurq6ysrK2tra6urq+vr7CwsLGxsbKysrOzs7S0tLW1tba2tre3t7i4uLm5ubq6uru7u7y8vL29vb6+vr+/v8DAwMHBwcLCwsPDw8TExMXFxcbGxsfHx8jIyMnJycrKysvLy8zMzM3Nzc7Ozs/Pz9DQ0NHR0dLS0tPT09TU1NXV1dbW1tfX19jY2NnZ2dra2tvb29zc3N3d3d7e3t/f3+Dg4OHh4eLi4uPj4+Tk5OXl5ebm5ufn5+jo6Onp6erq6uvr6+zs7O3t7e7u7u/v7/Dw8PHx8fLy8vPz8/T09PX19fb29vf39/j4+Pn5+fr6+vv7+/z8/P39/f7+/v///yH/C05FVFNDQVBFMi4wAwEAAAAh/hFDcmVhdGVkIHdpdGggR0lNUAAh+QQABQD/ACwAAAAAAQABAAAIBAABBAQAIfkEAAUA/wAsAAAAAAEAAQAACAQAAQQEACH5BAAFAP8ALAAAAAABAAEAAAgEAAEEBAAh+QQABQD/ACwAAAAAAQABAAAIBAABBAQAIfkEAAUA/wAsAAAAAAEAAQAACAQAAQQEACH5BAAFAP8ALAAAAAABAAEAAAgEAAEEBAAh+QQABQD/ACwAAAAAAQABAAAIBAABBAQAIfkEAAUA/wAsAAAAAAEAAQAACAQAAQQEACH5BAEFAP8ALAAAAAABAAEAAAgEAD8EBAAh+QQBBQD/ACwAAAAAAQABAAAIBAB/BAQAIfkEAQUA/wAsAAAAAAEAAQAACAQAvwQEACH5BAEFAP8ALAAAAAABAAEAAAgEAP8EBAAh+QQBBQD/ACwAAAAAAQABAAAIBAA/BQQAIfkEAQUA/wAsAAAAAAEAAQAACAQAfwUEACH5BAEFAP8ALAAAAAABAAEAAAgEAL8FBAAh+QQBBQD+ACwAAAAAAQABAAAIBAD/BQQAIfkEAQUA/gAsAAAAAAEAAQAACAQA/wUEACH5BAEFAP4ALAAAAAABAAEAAAgEAP8FBAAh+QQBBQD+ACwAAAAAAQABAAAIBAD/BQQAIfkEAQUA/gAsAAAAAAEAAQAACAQA/wUEACH5BAEFAP4ALAAAAAABAAEAAAgEAP8FBAAh+QQBBQD+ACwAAAAAAQABAAAIBAD/BQQAIfkEAQUA/gAsAAAAAAEAAQAACAQA/wUEACH5BAEFAP8ALAAAAAABAAEAAAgEAL8FBAAh+QQBBQD/ACwAAAAAAQABAAAIBAB/BQQAIfkEAQUA/wAsAAAAAAEAAQAACAQAPwUEACH5BAEFAP8ALAAAAAABAAEAAAgEAP8EBAAh+QQBBQD/ACwAAAAAAQABAAAIBAC/BAQAIfkEAQUA/wAsAAAAAAEAAQAACAQAfwQEACH5BAEFAP8ALAAAAAABAAEAAAgEAD8EBAA7);  background-size: 100%;\"><center></center></body></html>")

            self.moodbarWarning()

            if not os.path.exists(os.path.join(os.path.split(unicode(self.mediaObject.currentSource().url().toString()).replace("file://",""))[0], "." + os.path.split(unicode(self.mediaObject.currentSource().url().toString()).replace("file://",""))[1] + ".mood")):

                self.moodbarFinish()

            else:

                self.updateMoodbar()

    def moodbarFinish(self):

        if not os.path.exists(os.path.join(os.path.split(unicode(self.mediaObject.currentSource().url().toString()).replace("file://",""))[0], "." + os.path.split(unicode(self.mediaObject.currentSource().url().toString()).replace("file://",""))[1] + ".mood")) and os.path.exists("/usr/bin/moodbar"):

            moodbarWriter.media = self.mediaObject.currentSource().url().toString()

            moodbarWriter.start()

    def updateMoodbar(self):

        if os.path.exists(os.path.join(os.path.split(unicode(self.mediaObject.currentSource().url().toString()).replace("file://",""))[0], "." + os.path.split(unicode(self.mediaObject.currentSource().url().toString()).replace("file://",""))[1] + ".mood")):

            self.moodbarColors = moodbar.read(os.path.join(os.path.split(unicode(self.mediaObject.currentSource().url().toString()).replace("file://",""))[0], "." + os.path.split(unicode(self.mediaObject.currentSource().url().toString()).replace("file://",""))[1] + ".mood"))

            self.moodbarCss = moodbar.toCss(os.path.join(os.path.split(unicode(self.mediaObject.currentSource().url().toString()).replace("file://",""))[0], "." + os.path.split(unicode(self.mediaObject.currentSource().url().toString()).replace("file://",""))[1] + ".mood"))

        else:

            self.moodbarColors = []

            self.moodbarCss = ""

        if len(self.moodbarColors) > 0:

            if os.path.exists("/usr/bin/moodbar"):

               self.moodbarViewer.setHtml("<html><body style=\"border: 1px solid ThreeDShadow; margin: 0; " + self.moodbarCss + "\"></body></html>")

            self.moodbarTimer.stop()

    def setPosition(self):

        self.playlistPosition = self.playlist.currentRow()

        print("Moved to position", self.playlistPosition, "in the playlist.")

    def itemLoadPosition(self, item=""):

        self.loadMedia(item)

        self.setPosition()

    def loadMedia(self, item=""):

        if type(item) is str or type(item) is unicode:

            text = item

        elif type(item) is QtGui.QTreeWidgetItem:

            text = unicode(self.playlist.rowPathFromItem(item))

        else:

            text = unicode(self.playlist.rowPathFromIndex(item))

        self.mediaObject.seek(0)

        self.mediaObject.setCurrentSource(Phonon.MediaSource(text))

        self.progressBar.setValue(0)

        self.playPauseButton.setChecked(True)

        self.playPause(True)

    def toggleLoop(self):

        self.loopBox.nextCheckState()

 

    def changeLoop(self):

        if self.loopBox.checkState() == QtCore.Qt.Unchecked:

            self.loopPlaylist = False

            self.loopTrack = False

            self.loopBox.setIcon(QtGui.QIcon(os.path.join(app_lib, "icons", "noloop.png")))

        elif self.loopBox.checkState() == QtCore.Qt.PartiallyChecked:

            self.loopPlaylist = True

            self.loopTrack = False

            self.loopBox.setIcon(QtGui.QIcon(os.path.join(app_lib, "icons", "loopplaylist.png")))

        elif self.loopBox.checkState() == QtCore.Qt.Checked:

            self.loopPlaylist = False

            self.loopTrack = True

            self.loopBox.setIcon(QtGui.QIcon(os.path.join(app_lib, "icons", "looptrack.png")))

        self.changeLoopActionText()

 

    def shufflePlaylist(self):

        playlist = []

        for index in range(self.playlist.count()):

            playlist.append(self.playlist.rowPathFromIndex(index))

        self.playlist.clear()

        random.shuffle(playlist)

        for path in playlist:

            self.playlist.addItem(path)

        self.setUnsorted()

    def goPrevious(self):

        self.playlistPosition -= 1

        if self.playlistPosition == -1:

            self.playlistPosition = self.playlist.count() - 1

        self.loadMedia(self.playlist.item(self.playlistPosition))

        self.playlist.setCurrentRow(self.playlistPosition)

        print("Moved to position", self.playlistPosition, "in the playlist.")

    def goNext(self):

        self.playlistPosition += 1

        if self.playlistPosition == self.playlist.count():

            self.playlistPosition = 0

        self.loadMedia(self.playlist.item(self.playlistPosition))

        self.playlist.setCurrentRow(self.playlistPosition)

        print("Moved to position", self.playlistPosition, "in the playlist.")

    def advanceTrack(self):

        if self.loopTrack == False:

            self.playlistPosition += 1

        if self.playlistPosition == self.playlist.count() and self.loopPlaylist == True:

            self.playlistPosition = 0

        self.loadMedia(self.playlist.item(self.playlistPosition))

        self.playlist.setCurrentRow(self.playlistPosition)

        print("Moved to position", self.playlistPosition, "in the playlist.")

    def removePlaylistItem(self, force = False):

        if self.playlist.hasFocus() == True or force == True:

            for item in self.playlist.selectedItems():

                try: self.playlist.takeTopLevelItem(self.playlist.indexOfTopLevelItem(item))

                except:

                    doNothing()

            self.playlist.rewritePlaylist()

        elif self.folderList.hasFocus() == True:

            self.removeCollectionItem()

        self.collectionCount.setText(unicode(self.playlist.count()) + tr(‘inPlaylist‘) + unicode(len(collectionManager.collection)) + tr(‘inCollection‘))

 

    def savePlaylist(self):

        playlistFile = os.path.join(app_home, "playlist.akp")

        playlistFileWrite = open(playlistFile, "w")

        playlistFileWrite.write(self.playlistEditorBox.toPlainText())

        playlistFileWrite.close()

        self.loadPlaylist()

 

    def savePlaylistAs(self):

        name = self.dialogHandler.inputBox(tr(‘enterPlaylistName‘))

        if name:

            filename = self.dialogHandler.saveDialog("*.xspf", tr(‘allSupportedPlaylists‘) + " (*.xspf *.m3u *.akp *.txt);;" + tr(‘xspf‘) + " (*.xspf);;" + tr(‘m3u‘) + " (*.m3u);;" + tr(‘plaintext‘) + " (*.akp *.txt);;" + tr("allFiles") + " (*)")

            if filename:

                filename = unicode(filename)

                if filename.endswith(".m3u"):

                    playlistWrite = open(filename, "w")

                    playlistWrite.write("")

                    playlistWrite.close()

                    playlistWrite = open(filename, "a")

                    playlistWrite.write("#EXTM3U\n")

                    playlistWrite.write("#PLAYLIST: " + name + "\n")

                    for track in range(self.playlist.count()):

                        tags = getTags(self.playlist.rowPathFromIndex(track))

                        title = tags[‘title‘]

                        artist = tags[‘artist‘]

                        try: playlistWrite.write("#EXTINF:" + artist + " - " + title + "\nfile://" + quote(self.playlist.rowPathFromIndex(track)) + "\n")

                        except:

                            print("Error in line", unicode(track) + "!")

                    playlistWrite.close()

                elif filename.endswith(".akp") or filename.endswith(".txt"):

                    playlistWrite = open(filename, "w")

                    playlistWrite.write("")

                    playlistWrite.close()

                    playlistWrite = open(filename, "a")

                    for track in range(self.playlist.count()):

                        try: playlistWrite.write("file://" + quote(self.playlist.rowPathFromIndex(track)) + "\n")

                        except:

                            print("Error in line", unicode(track) + "!")

                    playlistWrite.close()

                else:

                    if not filename.endswith(".xspf"):

                        filename = filename + ".xspf"

                    playlistWrite = open(filename, "w")

                    playlistWrite.write("")

                    playlistWrite.close()

                    playlistWrite = open(filename, "a")

                    playlistWrite.write(‘<?xml version="1.0" encoding="UTF-8"?>\n<playlist version="1" xmlns="http://xspf.org/ns/0/">\n  <title>‘ + escape(name) + ‘</title>\n  <trackList>\n‘)

                    for track in range(self.playlist.count()):

                        tags = getTags(self.playlist.rowPathFromIndex(track))

                        title = tags[‘title‘]

                        artist = tags[‘artist‘]

                        album = tags[‘album‘]

                        try: playlistWrite.write("    <track>\n      <album>" + escape(album) + "</album>\n      <creator>" + escape(artist) + "</creator>\n      <title>" + escape(title) + "</title>\n      <location>file://" + quote(self.playlist.rowPathFromIndex(track)) + "</location>\n    </track>\n")

                        except:

                            print("Error in line", unicode(track) + "!")

                    playlistWrite.write("  </trackList>\n</playlist>")

                    playlistWrite.close()

                print("Playlist", name , "saved to file", filename)

 

    def openPlaylist(self):

        filename = self.dialogHandler.loadDialog(tr(‘allSupportedPlaylists‘) + " (*.xspf *.m3u *.akp *.txt);;" + tr(‘xspf‘) + " (*.xspf);;" + tr(‘m3u‘) + " (*.m3u);;" + tr(‘plaintext‘) + " (*.akp *.txt);;All files (*)")

        if filename:

            loadpage = open(filename.replace("file://", ""))

            loadpage.seek(0)

            event_list = loadpage.readlines()

            loadpage.close()

            xml = False

            for line in event_list:

                if ‘<?xml‘ in line:

                    xml = True

                    break

            if xml == True:

                self.playlist.clear()

                print("Assuming that this is an XSPF playlist...")

                event_contents = ""

                for line in event_list:

                    event_contents = event_contents + line

                xspfReader.feed(event_contents)

 

                for track in xspfReader.playlist:

                    self.playlist.addItem(track)

                print("Playlist successfully loaded!")

                self.rewritePlaylist()

            else:

                self.playlist.clear()

                print("Assuming that this is a plain text playlist...")

                for line in event_list:

                    path = metaunquote(line.replace("\n", "").replace("file://", "")).replace("%20", " ")

                    if os.path.exists(path):

                        self.playlist.addItem(path)

                print("Playlist successfully loaded!")

                self.rewritePlaylist()

 

    def enableDisablePlugin(self):

        if self.enabledPluginsList.hasFocus():

            plugin = self.enabledPluginsList.currentItem().text()

            self.enabledPluginsList.takeItem(self.enabledPluginsList.row(self.enabledPluginsList.currentItem()))

            self.disabledPluginsList.addItem(plugin)

            self.disabledPluginsList.sortItems(QtCore.Qt.AscendingOrder)

        elif self.disabledPluginsList.hasFocus():

            plugin = self.disabledPluginsList.currentItem().text()

            self.disabledPluginsList.takeItem(self.disabledPluginsList.row(self.disabledPluginsList.currentItem()))

            self.enabledPluginsList.addItem(plugin)

            self.enabledPluginsList.sortItems(QtCore.Qt.AscendingOrder)

 

    def savePlugins(self):

        f = os.path.join(app_home, "pwhitelist.conf")

        fwrite = open(f, "w")

        fwrite.write("")

        fwrite.close()

        fwrite = open(f, "a")

        for item in range(0, self.enabledPluginsList.count()):

            fwrite.write(self.enabledPluginsList.item(item).text() + "\n")

        fwrite.close()

        self.loadPluginsLists()

        print("Changes to plugin blacklist saved. Please restart " + app_name + " for these changes to take effect.")

        self.dialogHandler.message(tr(‘restart1‘) + app_name + tr(‘restart2‘), tr(‘alert‘), "info")

    def loadPluginsLists(self):

        save = False

        f = os.path.join(app_home, "plugins.conf")

        if os.path.exists(f):

            save = True

            self.pBlacklist = []

            fread = open(f, "r")

            playlistFileContents = fread.readlines()

            fread.close()

            for line in playlistFileContents:

                self.pBlacklist.append(line.replace("\n", ""))

            print("The following plugins are currently disabled:", self.pBlacklist)

            plugins = ""

            for line in playlistFileContents:

                plugins = plugins + line

            self.disabledPluginsList.clear()

            for item in self.pBlacklist:

                self.disabledPluginsList.addItem(item)

            os.remove(f)

        f = os.path.join(app_home, "pwhitelist.conf")

        if os.path.exists(f):

            self.pWhitelist = []

            fread = open(f, "r")

            playlistFileContents = fread.readlines()

            fread.close()

            for line in playlistFileContents:

                self.pWhitelist.append(line.replace("\n", ""))

            print("The following plugins are currently enabled:", self.pWhitelist)

            plugins = ""

            for line in playlistFileContents:

                plugins = plugins + line

            for ditem in range(0, len(self.pBlacklist)):

                try: self.pBlacklist[ditem]

                except:

                    do_nothing()

                else:

                    for eitem in range(0, len(self.pWhitelist)):

                        try: self.pWhitelist[eitem]

                        except:

                            do_nothing()

                        else:

                            if self.pWhitelist[eitem] == self.pBlacklist[ditem]:

                                del self.pWhitelist[eitem]

            self.enabledPluginsList.clear()

            for item in self.pWhitelist:

                self.enabledPluginsList.addItem(item)

        if save:

            self.savePlugins()

    def resetPath(self):

        if unicode(self.pathTagField.text()) != self.currentPath:

            self.pathTagField.setText(self.currentPath)

    def editTags(self):

#        if sys.version_info[0] >= 3:

#        if 1:

        path = self.playlist.currentItem()

        self.currentPath = path

        tags = getTags(path)

        title = tags[‘title‘]

        if title == tr(‘untitled‘):

            title = ""

        artist = tags[‘artist‘]

        if artist == tr(‘unknownArtist‘):

            artist = ""

        album = tags[‘album‘]

        if album == tr(‘unknownAlbum‘):

            album = ""

        date = tags[‘date‘]

        if date == tr(‘unknown‘):

            date = ""

        genre = tags[‘genre‘]

        if genre == tr(‘unknown‘):

            genre = ""

        self.titleTagField.setText(title)

        self.artistTagField.setText(artist)

        self.albumTagField.setText(album)

        self.dateTagField.setText(date)

        self.genreTagField.setText(genre)

        self.pathTagField.setText(self.currentPath)

        qr = self.tagEditor.frameGeometry()

        cp = QtGui.QDesktopWidget().availableGeometry().center()

        qr.moveCenter(cp)

        self.tagEditor.move(qr.topLeft())

        self.tagEditor.show()

#        if sys.version_info[0] >= 3:

#        if 1:

        self.titleTagField.setFocus()

    def saveTags(self):

        if sys.version_info[0] >= 3:

            try: tags = stagger.read_tag(self.pathTagField.text())

            except:

                tags = ""

            if type(tags) is not str:

                try: tags.title = self.titleTagField.text()

                except:

                    print("Unable to write title tag!")

                try: tags.artist = self.artistTagField.text()

                except:

                    print("Unable to write artist tag!")

                try: tags.album = self.albumTagField.text()

                except:

                    print("Unable to write album tag!")

                try: tags.date = self.dateTagField.text()

                except:

                    print("Unable to write date tag!")

                try: tags.genre = self.genreTagField.text()

                except:

                    print("Unable to write genre tag!")

                tags.write()

            else:

                print("Failed to write tags!")

                self.dialogHandler.message(tr(‘tagFail‘), tr(‘error‘), "warn")

        else:

            try: tags = mutagen.File(unicode(self.pathTagField.text()))

            except:

                tags = ""

            if type(tags) is not str:

                try: tags["title"] = unicode(self.titleTagField.text())

                except:

                    print("Unable to write title tag!")

                try: tags["artist"] = unicode(self.artistTagField.text())

                except:

                    print("Unable to write artist tag!")

                try: tags["album"] = unicode(self.albumTagField.text())

                except:

                    print("Unable to write album tag!")

                try: tags["date"] = unicode(self.dateTagField.text())

                except:

                    print("Unable to write date tag!")

                try: tags["genre"] = unicode(self.genreTagField.text())

                except:

                    print("Unable to write genre tag!")

                tags.save()

            else:

                print("Failed to write tags!")

                self.dialogHandler.message(tr(‘tagFail‘), tr(‘error‘), "warn")

        print("Tags saved. For changes to appear in the collection, you will have to rebuild it.")

        self.loadPlaylist()

            

    def editPlaylist(self):

        playlistFile = os.path.join(app_home, "playlist.akp")

        if os.path.exists(playlistFile):

            playlistFileRead = open(playlistFile, "r")

            playlistFileContents = playlistFileRead.readlines()

            playlistFileRead.close()

            playlist = ""

            for line in playlistFileContents:

                playlist = playlist + line

            self.playlistEditorBox.setText(playlist)

        qr = self.playlistEditor.frameGeometry()

        cp = QtGui.QDesktopWidget().availableGeometry().center()

        qr.moveCenter(cp)

        self.playlistEditor.move(qr.topLeft())

        self.playlistEditor.show()

    def loadPlaylist(self, start = False):

        playlistFile = os.path.join(app_home, "playlist.akp")

        if os.path.exists(playlistFile):

            self.playlist.clear()

            playlistFileRead = open(playlistFile, "r")

            playlistFileContents = playlistFileRead.readlines()

            playlistFileRead.close()

            for line in playlistFileContents:

                self.playlist.addItem(unicode(line.replace("\n","")))

#                except:

#                    print("Error! Something went wrong. File not added to playlist.")

            self.playlist.rewritePlaylist()

            if start == True:

                if len(sys.argv) > 1:

                    for argnum in range(1, len(sys.argv)):

                        if os.path.exists(metaunquote(sys.argv[argnum]).replace("file://", "")) and not os.path.isdir(metaunquote(sys.argv[argnum]).replace("file://", "")):

                            self.playlist.addItem(sys.argv[argnum])

                            self.playStart = True

                        else:

                            self.playStart = False

                    self.playlist.rewritePlaylist()

    def rewritePlaylist(self):

        self.playlist.rewritePlaylist()

        self.collectionCount.setText(unicode(self.playlist.count()) + tr(‘inPlaylist‘) + unicode(len(collectionManager.collection)) + tr(‘inCollection‘))

    def togglePlayPause(self):

        if self.goPreviousButton.hasFocus():

            self.goPreviousButton.click()

        elif self.goNextButton.hasFocus():

            self.goNextButton.click()

        elif self.loopBox.hasFocus():

            self.loopBox.click()

        elif self.editPluginsButton.hasFocus():

            self.editPluginsButton.click()

        elif self.collectionList.hasFocus():

            if self.collectionList.currentItem().childCount() > 0:

                self.collectionList.currentItem().setExpanded(not self.collectionList.currentItem().isExpanded())

            else:

                self.addMedia(self.collectionList.currentItem())

        else:

            if self.playPauseButton.isChecked() == True:

                self.playPauseButton.setChecked(False)

                self.playPause(False)

            else:

                self.playPauseButton.setChecked(True)

                self.playPause(True)

 

    def playPause(self, checked=True):

        if checked == True:

            self.updateMoodbar()

            if not "ubuntu" in app_unity:

                if sys.platform.startswith("win"):

                    self.playPauseIcon.setIcon(QtGui.QIcon(os.path.join(app_lib, "icons", "pause-16.png")))

                else:

                    self.playPauseIcon.setIcon(QtGui.QIcon().fromTheme("media-playback-pause", QtGui.QIcon(os.path.join(app_lib, "icons", "pause.png"))))

                self.playPauseIcon.setToolTip(unicode(tr(‘pause‘)))

            if self.progressBar.value() != self.mediaObject.currentTime():

                self.mediaObject.seek(self.progressBar.value())

            self.mediaObject.play()

            try: self.moodbarTimer.start(10)

            except:

                doNothing()

        else:

            if not "ubuntu" in app_unity:

                if sys.platform.startswith("win"):

                    self.playPauseIcon.setIcon(QtGui.QIcon(os.path.join(app_lib, "icons", "play-16.png")))

                else:

                    self.playPauseIcon.setIcon(QtGui.QIcon().fromTheme("media-playback-start", QtGui.QIcon(os.path.join(app_lib, "icons", "play.png"))))

                self.playPauseIcon.setToolTip(unicode(tr(‘play‘)))

            self.mediaObject.pause()

        self.trayMessage()

    def seekBackward(self):

        self.updateProgressBar()

        if self.mediaObject.currentTime() - 2000 > 0:

            self.mediaObject.seek(self.mediaObject.currentTime() - 2000)

        else:

            if self.loopPlaylist == True:

                self.goPrevious()

            else:

                self.mediaObject.seek(0)

    def seekForward(self):

        self.updateProgressBar()

        if self.mediaObject.currentTime() + 2000 < self.mediaObject.totalTime():

            self.mediaObject.seek(self.mediaObject.currentTime() + 2000)

        else:

            self.mediaObject.seek(self.mediaObject.totalTime())

    def progressBarPressed(self):

        self.userIsMovingProgress = True

    def progressBarReleased(self):

        self.userIsMovingProgress = False

    def seek(self):

        self.mediaObject.seek(self.progressBar.value())

    def setProgressBarMax(self):

        self.progressBar.setMaximum(self.mediaObject.totalTime())

        self.updateProgressBar()

    def forceUpdateTrackbar(self, value=0):

        self.progressBar.setValue(int(value*self.progressBar.maximum()))

    def setTime(self):

        time = self.timeEdit.time()

        nt = time.hour()*60*60*1000 + time.minute()*60*1000 + time.second()*1000

        if not self.timeEdit.t == nt:

            try: self.mediaObject.seek(time.hour()*60*60*1000 + time.minute()*60*1000 + time.second()*1000 + time.msec())

            except:

                doNothing()

    def updateProgressBar(self):

        if self.dialogHandler.seizedFocus == False:

            if self.userIsMovingProgress == False and self.progressBar.clicked == False:# or not self.progressBar.hasFocus():

                self.progressBar.setValue(self.mediaObject.currentTime())

            else:

                self.mediaObject.seek(self.progressBar.value())

            zero1 = "%.2d" % (self.mediaObject.currentTime()//1000%60)

            zero2 = "%.2d" % (self.mediaObject.totalTime()//1000%60)

            zero3 = "%.2d" % (self.mediaObject.remainingTime()//1000%60)

            if not self.timeEdit.hasFocus():

                self.timeEdit.setTime(QtCore.QTime(self.mediaObject.currentTime()//1000//60//60, self.mediaObject.currentTime()//1000//60%60, self.mediaObject.currentTime()//1000%60%60, self.mediaObject.currentTime()%1000%60%60))

            self.remainingTimeLabel.setText("-" + unicode(self.mediaObject.remainingTime()//1000//60) + ":" + unicode(zero3) + "/" + unicode(self.mediaObject.totalTime()//1000//60) + ":" + unicode(zero2))

 

# This class could easily be written as a function; I just felt like making it a class for some reason. It does make it inanely easy to load Akane as a module, however:

class MainClass():

    def __init__(self):

        self.app = QtGui.QApplication(sys.argv)

 

        # Define the name of the application in DBus to ensure Linux compatibility:

        QtGui.QApplication.setApplicationName("" + app_name + "")

        if os.path.exists(app_home) and not os.path.isdir(app_home):

            os.remove(app_home)

        if not os.path.exists(app_home):

            os.mkdir(app_home)

            global collection_type

            collection_type = required_collection_type

        os.chdir(app_lib)

        global app_webbrowser

        global downloadManagerGUI

        global app_trayIcon

        global dialogHandler

        app_trayIcon = QtGui.QSystemTrayIcon(QtGui.QIcon(os.path.join(app_lib, "icons", "akane_logo-unix-22px.svg")), None)

        dialogHandler = ADialogHandler()

        downloadManagerGUI = DownloadManagerGUI()

        app_webbrowser = AWebBrowser(app_cookiejar, downloadManagerGUI, app_home)

        self.win = MainWindow()

        self.win.setWindowTitle("" + app_name + "")

        windows = ["self.win", "self.win.settingsDialog", "self.win.playlistEditor", "self.win.collectionEditor", "self.win.tagEditor", "self.win.pluginsEditor", "self.win.settingsDialog", "self.win.dialogHandler.about", "self.win.dialogHandler.license"]

        if not sys.platform.startswith("win"):

            for window in windows:

                try: exec(window + ".setWindowIcon(QtGui.QIcon(unix_icon))")

                except:

                    doNothing()

        else:

            for window in windows:

                try: exec(window + ".setWindowIcon(QtGui.QIcon(os.path.join(app_lib, ‘icons‘, ‘akane_logo-unix.png‘)))")

                except:

                    doNothing()

        self.win.resize(840, 520)

        self.win.show()

        self.win.searchBar.setFocus()

        global mainFolder

        os.chdir(mainFolder)

        for folder in collectionManager.folders:

            if os.path.exists(folder) and os.path.isdir(folder):

                mainFolder = folder

                os.chdir(folder)

                break

        self.app.exec_()

 

def main():

    # Because the process of loading the application has been defined as a class, it only takes this one line of code to load everything:

    if "--icons" in sys.argv:

        print(app_icons)

        sys.exit()

    else:

        MainClass()

 

if __name__ == "__main__":

    main()

 

小例子

标签:

原文地址:http://www.cnblogs.com/mhxy13867806343/p/3860928.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!