Add more pycodestyle fixes

This commit is contained in:
Daniel Ahn 2018-07-20 12:57:00 -07:00
parent f01de206d8
commit 4dea39a068
7 changed files with 463 additions and 405 deletions

View File

@ -1,19 +1,23 @@
from configparser import SafeConfigParser, DEFAULTSECT
import argparse import argparse
import ast
import codecs
import re
import os import os
import sys import sys
import ast from configparser import SafeConfigParser, DEFAULTSECT
from syncplay import constants, utils, version, milestone from syncplay import constants, utils, version, milestone
from syncplay.messages import getMessage, setLanguage, isValidLanguage from syncplay.messages import getMessage, setLanguage, isValidLanguage
from syncplay.players.playerFactory import PlayerFactory from syncplay.players.playerFactory import PlayerFactory
from syncplay.utils import isMacOS from syncplay.utils import isMacOS
import codecs
import re
class InvalidConfigValue(Exception): class InvalidConfigValue(Exception):
def __init__(self, message): def __init__(self, message):
Exception.__init__(self, message) Exception.__init__(self, message)
class ConfigurationGetter(object): class ConfigurationGetter(object):
def __init__(self): def __init__(self):
self._config = { self._config = {
@ -175,7 +179,8 @@ class ConfigurationGetter(object):
self._iniStructure = { self._iniStructure = {
"server_data": ["host", "port", "password"], "server_data": ["host", "port", "password"],
"client_settings": ["name", "room", "playerPath", "client_settings": [
"name", "room", "playerPath",
"perPlayerArguments", "slowdownThreshold", "perPlayerArguments", "slowdownThreshold",
"rewindThreshold", "fastforwardThreshold", "rewindThreshold", "fastforwardThreshold",
"slowOnDesync", "rewindOnDesync", "slowOnDesync", "rewindOnDesync",
@ -187,7 +192,8 @@ class ConfigurationGetter(object):
"sharedPlaylistEnabled", "loopAtEndOfPlaylist", "sharedPlaylistEnabled", "loopAtEndOfPlaylist",
"loopSingleFiles", "loopSingleFiles",
"onlySwitchToTrustedDomains", "trustedDomains", "publicServers"], "onlySwitchToTrustedDomains", "trustedDomains", "publicServers"],
"gui": ["showOSD", "showOSDWarnings", "showSlowdownOSD", "gui": [
"showOSD", "showOSDWarnings", "showSlowdownOSD",
"showDifferentRoomOSD", "showSameRoomOSD", "showDifferentRoomOSD", "showSameRoomOSD",
"showNonControllerOSD", "showDurationNotification", "showNonControllerOSD", "showDurationNotification",
"chatInputEnabled", "chatInputFontUnderline", "chatInputEnabled", "chatInputFontUnderline",
@ -202,7 +208,8 @@ class ConfigurationGetter(object):
"chatMoveOSD", "chatOSDMargin", "chatMoveOSD", "chatOSDMargin",
"notificationTimeout", "alertTimeout", "notificationTimeout", "alertTimeout",
"chatTimeout", "chatOutputEnabled"], "chatTimeout", "chatOutputEnabled"],
"general": ["language", "checkForUpdatesAutomatically", "general": [
"language", "checkForUpdatesAutomatically",
"lastCheckedForUpdates"] "lastCheckedForUpdates"]
} }
@ -224,7 +231,7 @@ class ConfigurationGetter(object):
try: try:
if varToTest == "" or varToTest is None: if varToTest == "" or varToTest is None:
return False return False
if str(varToTest).isdigit() == False: if not str(varToTest).isdigit():
return False return False
varToTest = int(varToTest) varToTest = int(varToTest)
if varToTest > 65535 or varToTest < 1: if varToTest > 65535 or varToTest < 1:
@ -269,13 +276,14 @@ class ConfigurationGetter(object):
self._config["playerClass"] = player self._config["playerClass"] = player
else: else:
raise InvalidConfigValue(getMessage("player-path-config-error")) raise InvalidConfigValue(getMessage("player-path-config-error"))
playerPathErrors = player.getPlayerPathErrors(self._config["playerPath"], self._config['file'] if self._config['file'] else None) playerPathErrors = player.getPlayerPathErrors(
self._config["playerPath"], self._config['file'] if self._config['file'] else None)
if playerPathErrors: if playerPathErrors:
raise InvalidConfigValue(playerPathErrors) raise InvalidConfigValue(playerPathErrors)
elif key == "host": elif key == "host":
self._config["host"], self._config["port"] = self._splitPortAndHost(self._config["host"]) self._config["host"], self._config["port"] = self._splitPortAndHost(self._config["host"])
hostNotValid = (self._config["host"] == "" or self._config["host"] is None) hostNotValid = (self._config["host"] == "" or self._config["host"] is None)
portNotValid = (_isPortValid(self._config["port"]) == False) portNotValid = (not _isPortValid(self._config["port"]))
if hostNotValid: if hostNotValid:
raise InvalidConfigValue(getMessage("no-hostname-config-error")) raise InvalidConfigValue(getMessage("no-hostname-config-error"))
elif portNotValid: elif portNotValid:
@ -408,7 +416,6 @@ class ConfigurationGetter(object):
if changed: if changed:
parser.write(codecs.open(iniPath, "wb", "utf_8_sig")) parser.write(codecs.open(iniPath, "wb", "utf_8_sig"))
def _forceGuiPrompt(self): def _forceGuiPrompt(self):
from syncplay.ui.GuiConfiguration import GuiConfiguration from syncplay.ui.GuiConfiguration import GuiConfiguration
try: try:
@ -452,7 +459,8 @@ class ConfigurationGetter(object):
# #
if self._config['language']: if self._config['language']:
setLanguage(self._config['language']) setLanguage(self._config['language'])
self._argparser = argparse.ArgumentParser(description=getMessage("argument-description"), self._argparser = argparse.ArgumentParser(
description=getMessage("argument-description"),
epilog=getMessage("argument-epilog")) epilog=getMessage("argument-epilog"))
self._argparser.add_argument('--no-gui', action='store_true', help=getMessage("nogui-argument")) self._argparser.add_argument('--no-gui', action='store_true', help=getMessage("nogui-argument"))
self._argparser.add_argument('-a', '--host', metavar='hostname', type=str, help=getMessage("host-argument")) self._argparser.add_argument('-a', '--host', metavar='hostname', type=str, help=getMessage("host-argument"))
@ -514,6 +522,7 @@ class ConfigurationGetter(object):
self._saveConfig(path) self._saveConfig(path)
self._config = backup self._config = backup
class SafeConfigParserUnicode(SafeConfigParser): class SafeConfigParserUnicode(SafeConfigParser):
def write(self, fp): def write(self, fp):
"""Write an .ini-format representation of the configuration state.""" """Write an .ini-format representation of the configuration state."""

View File

@ -1,19 +1,24 @@
import os
import sys
import threading
from datetime import datetime
from syncplay import constants
from syncplay import utils
from syncplay.messages import getMessage, getLanguages, setLanguage, getInitialLanguage
from syncplay.players.playerFactory import PlayerFactory
from syncplay.utils import isBSD, isLinux, isMacOS, isWindows
from syncplay.utils import resourcespath, posixresourcespath
from syncplay.vendor.Qt import QtCore, QtWidgets, QtGui, __binding__, IsPySide, IsPySide2 from syncplay.vendor.Qt import QtCore, QtWidgets, QtGui, __binding__, IsPySide, IsPySide2
from syncplay.vendor.Qt.QtCore import Qt, QSettings, QCoreApplication, QSize, QPoint, QUrl, QLine, QEventLoop, Signal from syncplay.vendor.Qt.QtCore import Qt, QSettings, QCoreApplication, QSize, QPoint, QUrl, QLine, QEventLoop, Signal
from syncplay.vendor.Qt.QtWidgets import QApplication, QLineEdit, QLabel, QCheckBox, QButtonGroup, QRadioButton, QDoubleSpinBox, QPlainTextEdit from syncplay.vendor.Qt.QtWidgets import QApplication, QLineEdit, QLabel, QCheckBox, QButtonGroup, QRadioButton, QDoubleSpinBox, QPlainTextEdit
from syncplay.vendor.Qt.QtGui import QCursor, QIcon, QImage, QDesktopServices from syncplay.vendor.Qt.QtGui import QCursor, QIcon, QImage, QDesktopServices
if IsPySide2: if IsPySide2:
from PySide2.QtCore import QStandardPaths from PySide2.QtCore import QStandardPaths
from syncplay.players.playerFactory import PlayerFactory
from datetime import datetime
from syncplay import utils
import os
import sys
import threading
from syncplay.messages import getMessage, getLanguages, setLanguage, getInitialLanguage
from syncplay import constants
from syncplay.utils import isBSD, isLinux, isMacOS, isWindows
from syncplay.utils import resourcespath, posixresourcespath
class GuiConfiguration: class GuiConfiguration:
def __init__(self, config, error=None, defaultConfig=None): def __init__(self, config, error=None, defaultConfig=None):
self.defaultConfig = defaultConfig self.defaultConfig = defaultConfig
@ -82,8 +87,10 @@ class ConfigDialog(QtWidgets.QDialog):
def automaticUpdatePromptCheck(self): def automaticUpdatePromptCheck(self):
if self.automaticupdatesCheckbox.checkState() == Qt.PartiallyChecked: if self.automaticupdatesCheckbox.checkState() == Qt.PartiallyChecked:
reply = QtWidgets.QMessageBox.question(self, "Syncplay", reply = QtWidgets.QMessageBox.question(
getMessage("promptforupdate-label"), QtWidgets.QMessageBox.StandardButton.Yes | QtWidgets.QMessageBox.StandardButton.No) self, "Syncplay",
getMessage("promptforupdate-label"),
QtWidgets.QMessageBox.StandardButton.Yes | QtWidgets.QMessageBox.StandardButton.No)
if reply == QtWidgets.QMessageBox.Yes: if reply == QtWidgets.QMessageBox.Yes:
self.automaticupdatesCheckbox.setChecked(True) self.automaticupdatesCheckbox.setChecked(True)
else: else:
@ -91,7 +98,7 @@ class ConfigDialog(QtWidgets.QDialog):
def moreToggled(self): def moreToggled(self):
self.setSizePolicy(QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Minimum) self.setSizePolicy(QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Minimum)
if self.moreToggling == False: if not self.moreToggling:
self.moreToggling = True self.moreToggling = True
if self.showmoreCheckbox.isChecked(): if self.showmoreCheckbox.isChecked():
@ -154,7 +161,7 @@ class ConfigDialog(QtWidgets.QDialog):
settings.endGroup() settings.endGroup()
foundpath = "" foundpath = ""
if playerpath != None and playerpath != "": if playerpath is not None and playerpath != "":
if utils.isURL(playerpath): if utils.isURL(playerpath):
foundpath = playerpath foundpath = playerpath
self.executablepathCombobox.addItem(foundpath) self.executablepathCombobox.addItem(foundpath)
@ -162,7 +169,7 @@ class ConfigDialog(QtWidgets.QDialog):
else: else:
if not os.path.isfile(playerpath): if not os.path.isfile(playerpath):
expandedpath = PlayerFactory().getExpandedPlayerPathByPath(playerpath) expandedpath = PlayerFactory().getExpandedPlayerPathByPath(playerpath)
if expandedpath != None and os.path.isfile(expandedpath): if expandedpath is not None and os.path.isfile(expandedpath):
playerpath = expandedpath playerpath = expandedpath
if os.path.isfile(playerpath): if os.path.isfile(playerpath):
@ -252,7 +259,8 @@ class ConfigDialog(QtWidgets.QDialog):
elif isBSD(): elif isBSD():
defaultdirectory = "/usr/local/bin" defaultdirectory = "/usr/local/bin"
fileName, filtr = QtWidgets.QFileDialog.getOpenFileName(self, fileName, filtr = QtWidgets.QFileDialog.getOpenFileName(
self,
"Browse for media player executable", "Browse for media player executable",
defaultdirectory, defaultdirectory,
browserfilter, "", options) browserfilter, "", options)
@ -387,7 +395,8 @@ class ConfigDialog(QtWidgets.QDialog):
else: else:
defaultdirectory = "" defaultdirectory = ""
browserfilter = "All files (*)" browserfilter = "All files (*)"
fileName, filtr = QtWidgets.QFileDialog.getOpenFileName(self, "Browse for media files", defaultdirectory, fileName, filtr = QtWidgets.QFileDialog.getOpenFileName(
self, "Browse for media files", defaultdirectory,
browserfilter, "", options) browserfilter, "", options)
if fileName: if fileName:
self.mediapathTextbox.setText(os.path.normpath(fileName)) self.mediapathTextbox.setText(os.path.normpath(fileName))
@ -542,10 +551,10 @@ class ConfigDialog(QtWidgets.QDialog):
config = self.config config = self.config
playerpaths = self.playerpaths playerpaths = self.playerpaths
error = self.error error = self.error
if self.datacleared == True: if self.datacleared:
error = constants.ERROR_MESSAGE_MARKER + "{}".format(getMessage("gui-data-cleared-notification")) error = constants.ERROR_MESSAGE_MARKER + "{}".format(getMessage("gui-data-cleared-notification"))
self.error = error self.error = error
if config['host'] == None: if config['host'] is None:
host = "" host = ""
elif ":" in config['host']: elif ":" in config['host']:
host = config['host'] host = config['host']
@ -566,7 +575,7 @@ class ConfigDialog(QtWidgets.QDialog):
serverAddressPort = publicServer[1] serverAddressPort = publicServer[1]
self.hostCombobox.addItem(serverAddressPort) self.hostCombobox.addItem(serverAddressPort)
self.hostCombobox.setItemData(i, serverTitle, Qt.ToolTipRole) self.hostCombobox.setItemData(i, serverTitle, Qt.ToolTipRole)
if not serverAddressPort in self.publicServerAddresses: if serverAddressPort not in self.publicServerAddresses:
self.publicServerAddresses.append(serverAddressPort) self.publicServerAddresses.append(serverAddressPort)
i += 1 i += 1
self.hostCombobox.setEditable(True) self.hostCombobox.setEditable(True)
@ -1224,7 +1233,7 @@ class ConfigDialog(QtWidgets.QDialog):
def populateEmptyServerList(self): def populateEmptyServerList(self):
if self.publicServers is None: if self.publicServers is None:
if self.config["checkForUpdatesAutomatically"] == True: if self.config["checkForUpdatesAutomatically"]:
self.updateServerList() self.updateServerList()
else: else:
currentServer = self.hostCombobox.currentText() currentServer = self.hostCombobox.currentText()
@ -1264,7 +1273,7 @@ class ConfigDialog(QtWidgets.QDialog):
self._playerProbeThread.done.connect(self._updateExecutableIcon) self._playerProbeThread.done.connect(self._updateExecutableIcon)
self._playerProbeThread.start() self._playerProbeThread.start()
if self.config['clearGUIData'] == True: if self.config['clearGUIData']:
self.config['clearGUIData'] = False self.config['clearGUIData'] = False
self.clearGUIData() self.clearGUIData()
@ -1305,7 +1314,7 @@ class ConfigDialog(QtWidgets.QDialog):
self.addBottomLayout() self.addBottomLayout()
self.updatePasswordVisibilty() self.updatePasswordVisibilty()
if self.getMoreState() == False: if not self.getMoreState():
self.tabListFrame.hide() self.tabListFrame.hide()
self.resetButton.hide() self.resetButton.hide()
self.playerargsTextbox.hide() self.playerargsTextbox.hide()

View File

@ -1,15 +1,18 @@
import os import os
if "QT_PREFERRED_BINDING" not in os.environ: if "QT_PREFERRED_BINDING" not in os.environ:
os.environ["QT_PREFERRED_BINDING"] = os.pathsep.join( os.environ["QT_PREFERRED_BINDING"] = os.pathsep.join(
["PySide2", "PySide", "PyQt5", "PyQt4"] ["PySide2", "PySide", "PyQt5", "PyQt4"]
) )
try: try:
from syncplay.ui.gui import MainWindow as GraphicalUI from syncplay.ui.gui import MainWindow as GraphicalUI
except ImportError: except ImportError:
pass pass
from syncplay.ui.consoleUI import ConsoleUI from syncplay.ui.consoleUI import ConsoleUI
def getUi(graphical=True): def getUi(graphical=True):
if graphical: # TODO: Add graphical ui if graphical: # TODO: Add graphical ui
ui = GraphicalUI() ui = GraphicalUI()

View File

@ -1,14 +1,16 @@
import re
import sys
import threading import threading
import time import time
import syncplay import syncplay
import re
from syncplay import utils
from syncplay import constants from syncplay import constants
from syncplay import utils
from syncplay.messages import getMessage from syncplay.messages import getMessage
import sys
from syncplay.utils import formatTime from syncplay.utils import formatTime
class ConsoleUI(threading.Thread): class ConsoleUI(threading.Thread):
def __init__(self): def __init__(self):
self.promptMode = threading.Event() self.promptMode = threading.Event()
@ -157,7 +159,7 @@ class ConsoleUI(threading.Thread):
self._syncplayClient.setPaused(not self._syncplayClient.getPlayerPaused()) self._syncplayClient.setPaused(not self._syncplayClient.getPlayerPaused())
elif command.group('command') in constants.COMMANDS_ROOM: elif command.group('command') in constants.COMMANDS_ROOM:
room = command.group('parameter') room = command.group('parameter')
if room == None: if room is None:
if self._syncplayClient.userlist.currentUser.file: if self._syncplayClient.userlist.currentUser.file:
room = self._syncplayClient.userlist.currentUser.file["name"] room = self._syncplayClient.userlist.currentUser.file["name"]
else: else:
@ -167,7 +169,7 @@ class ConsoleUI(threading.Thread):
self._syncplayClient.sendRoom() self._syncplayClient.sendRoom()
elif command.group('command') in constants.COMMANDS_CREATE: elif command.group('command') in constants.COMMANDS_CREATE:
roombasename = command.group('parameter') roombasename = command.group('parameter')
if roombasename == None: if roombasename is None:
roombasename = self._syncplayClient.getRoom() roombasename = self._syncplayClient.getRoom()
roombasename = utils.stripRoomName(roombasename) roombasename = utils.stripRoomName(roombasename)
self._syncplayClient.createControlledRoom(roombasename) self._syncplayClient.createControlledRoom(roombasename)

View File

@ -1,28 +1,34 @@
import os
import re
import sys
import time
import urllib.error
import urllib.parse
import urllib.request
from datetime import datetime
from functools import wraps
from twisted.internet import task
from syncplay import utils, constants, version, revision, release_number
from syncplay.messages import getMessage
from syncplay.ui.consoleUI import ConsoleUI
from syncplay.utils import resourcespath
from syncplay.utils import isLinux, isWindows, isMacOS
from syncplay.utils import formatTime, sameFilename, sameFilesize, sameFileduration, RoomPasswordProvider, formatSize, isURL
from syncplay.vendor import Qt from syncplay.vendor import Qt
from syncplay.vendor.Qt import QtWidgets, QtGui, __binding__, __binding_version__, __qt_version__, IsPySide, IsPySide2 from syncplay.vendor.Qt import QtWidgets, QtGui, __binding__, __binding_version__, __qt_version__, IsPySide, IsPySide2
from syncplay.vendor.Qt.QtCore import Qt, QSettings, QSize, QPoint, QUrl, QLine, QDateTime from syncplay.vendor.Qt.QtCore import Qt, QSettings, QSize, QPoint, QUrl, QLine, QDateTime
from platform import python_version from platform import python_version
if IsPySide2: if IsPySide2:
from PySide2.QtCore import QStandardPaths from PySide2.QtCore import QStandardPaths
from syncplay import utils, constants, version, revision, release_number
from syncplay.messages import getMessage
from syncplay.utils import resourcespath
import sys
import time
import urllib.request, urllib.parse, urllib.error
from datetime import datetime
from syncplay.utils import isLinux, isWindows, isMacOS
import re
import os
from syncplay.utils import formatTime, sameFilename, sameFilesize, sameFileduration, RoomPasswordProvider, formatSize, isURL
from functools import wraps
from twisted.internet import task
from syncplay.ui.consoleUI import ConsoleUI
if isMacOS() and IsPySide: if isMacOS() and IsPySide:
from Foundation import NSURL from Foundation import NSURL
from Cocoa import NSString, NSUTF8StringEncoding from Cocoa import NSString, NSUTF8StringEncoding
lastCheckedForUpdates = None lastCheckedForUpdates = None
class ConsoleInGUI(ConsoleUI): class ConsoleInGUI(ConsoleUI):
def showMessage(self, message, noTimestamp=False): def showMessage(self, message, noTimestamp=False):
self._syncplayClient.ui.showMessage(message, True) self._syncplayClient.ui.showMessage(message, True)
@ -39,6 +45,7 @@ class ConsoleInGUI(ConsoleUI):
def getUserlist(self): def getUserlist(self):
self._syncplayClient.showUserList(self) self._syncplayClient.showUserList(self)
class UserlistItemDelegate(QtWidgets.QStyledItemDelegate): class UserlistItemDelegate(QtWidgets.QStyledItemDelegate):
def __init__(self): def __init__(self):
QtWidgets.QStyledItemDelegate.__init__(self) QtWidgets.QStyledItemDelegate.__init__(self)
@ -73,7 +80,7 @@ class UserlistItemDelegate(QtWidgets.QStyledItemDelegate):
midY - 8, midY - 8,
tickIconQPixmap.scaled(16, 16, Qt.KeepAspectRatio)) tickIconQPixmap.scaled(16, 16, Qt.KeepAspectRatio))
elif userReady == False and not crossIconQPixmap.isNull(): elif not userReady and not crossIconQPixmap.isNull():
itemQPainter.drawPixmap( itemQPainter.drawPixmap(
(optionQStyleOptionViewItem.rect.x()-10), (optionQStyleOptionViewItem.rect.x()-10),
midY - 8, midY - 8,
@ -102,6 +109,7 @@ class UserlistItemDelegate(QtWidgets.QStyledItemDelegate):
optionQStyleOptionViewItem.rect.setX(optionQStyleOptionViewItem.rect.x()+16) optionQStyleOptionViewItem.rect.setX(optionQStyleOptionViewItem.rect.x()+16)
QtWidgets.QStyledItemDelegate.paint(self, itemQPainter, optionQStyleOptionViewItem, indexQModelIndex) QtWidgets.QStyledItemDelegate.paint(self, itemQPainter, optionQStyleOptionViewItem, indexQModelIndex)
class AboutDialog(QtWidgets.QDialog): class AboutDialog(QtWidgets.QDialog):
def __init__(self, parent=None): def __init__(self, parent=None):
super(AboutDialog, self).__init__(parent) super(AboutDialog, self).__init__(parent)
@ -117,9 +125,14 @@ class AboutDialog(QtWidgets.QDialog):
linkLabel = QtWidgets.QLabel("<center><a href=\"https://syncplay.pl\">syncplay.pl</a></center>") linkLabel = QtWidgets.QLabel("<center><a href=\"https://syncplay.pl\">syncplay.pl</a></center>")
linkLabel.setOpenExternalLinks(True) linkLabel.setOpenExternalLinks(True)
versionExtString = version + revision versionExtString = version + revision
versionLabel = QtWidgets.QLabel("<p><center>" + getMessage("about-dialog-release").format(versionExtString, release_number) + "<br />Python " + python_version() + " - " + __binding__ + " " + __binding_version__ + " - Qt " + __qt_version__ + "</center></p>") versionLabel = QtWidgets.QLabel(
"<p><center>" + getMessage("about-dialog-release").format(versionExtString, release_number) +
"<br />Python " + python_version() + " - " + __binding__ + " " + __binding_version__ +
" - Qt " + __qt_version__ + "</center></p>")
# versionLabel = QtWidgets.QLabel("<p><center>Version 1.5.4 release 62<br />Python 3.4.5 - PySide 1.2.4 - Qt 4.8.7</center></p>") # versionLabel = QtWidgets.QLabel("<p><center>Version 1.5.4 release 62<br />Python 3.4.5 - PySide 1.2.4 - Qt 4.8.7</center></p>")
licenseLabel = QtWidgets.QLabel("<center><p>Copyright &copy; 2012&ndash;2018 Syncplay</p><p>" + getMessage("about-dialog-license-text") + "</p></center>") licenseLabel = QtWidgets.QLabel(
"<center><p>Copyright &copy; 2012&ndash;2018 Syncplay</p><p>" +
getMessage("about-dialog-license-text") + "</p></center>")
aboutIconPixmap = QtGui.QPixmap(resourcespath + "syncplay.png") aboutIconPixmap = QtGui.QPixmap(resourcespath + "syncplay.png")
aboutIconLabel = QtWidgets.QLabel() aboutIconLabel = QtWidgets.QLabel()
aboutIconLabel.setPixmap(aboutIconPixmap.scaled(65, 65, Qt.KeepAspectRatio)) aboutIconLabel.setPixmap(aboutIconPixmap.scaled(65, 65, Qt.KeepAspectRatio))
@ -154,6 +167,7 @@ class AboutDialog(QtWidgets.QDialog):
else: else:
QtGui.QDesktopServices.openUrl(QUrl("file://" + resourcespath + "third-party-notices.rtf")) QtGui.QDesktopServices.openUrl(QUrl("file://" + resourcespath + "third-party-notices.rtf"))
class MainWindow(QtWidgets.QMainWindow): class MainWindow(QtWidgets.QMainWindow):
insertPosition = None insertPosition = None
playlistState = [] playlistState = []
@ -347,8 +361,6 @@ class MainWindow(QtWidgets.QMainWindow):
else: else:
super(MainWindow.PlaylistWidget, self).dropEvent(event) super(MainWindow.PlaylistWidget, self).dropEvent(event)
class topSplitter(QtWidgets.QSplitter): class topSplitter(QtWidgets.QSplitter):
def createHandle(self): def createHandle(self):
return self.topSplitterHandle(self.orientation(), self) return self.topSplitterHandle(self.orientation(), self)
@ -470,9 +482,16 @@ class MainWindow(QtWidgets.QMainWindow):
def showUserList(self, currentUser, rooms): def showUserList(self, currentUser, rooms):
self._usertreebuffer = QtGui.QStandardItemModel() self._usertreebuffer = QtGui.QStandardItemModel()
self._usertreebuffer.setHorizontalHeaderLabels( self._usertreebuffer.setHorizontalHeaderLabels(
(getMessage("roomuser-heading-label"), getMessage("size-heading-label"), getMessage("duration-heading-label"), getMessage("filename-heading-label") )) (
getMessage("roomuser-heading-label"), getMessage("size-heading-label"),
getMessage("duration-heading-label"), getMessage("filename-heading-label")
))
usertreeRoot = self._usertreebuffer.invisibleRootItem() usertreeRoot = self._usertreebuffer.invisibleRootItem()
if self._syncplayClient.userlist.currentUser.file and self._syncplayClient.userlist.currentUser.file and os.path.isfile(self._syncplayClient.userlist.currentUser.file["path"]): if (
self._syncplayClient.userlist.currentUser.file and
self._syncplayClient.userlist.currentUser.file and
os.path.isfile(self._syncplayClient.userlist.currentUser.file["path"])
):
self._syncplayClient.fileSwitch.setCurrentDirectory(os.path.dirname(self._syncplayClient.userlist.currentUser.file["path"])) self._syncplayClient.fileSwitch.setCurrentDirectory(os.path.dirname(self._syncplayClient.userlist.currentUser.file["path"]))
for room in rooms: for room in rooms:
@ -613,7 +632,6 @@ class MainWindow(QtWidgets.QMainWindow):
menu.addAction(QtGui.QPixmap(resourcespath + "shield_edit.png"), getMessage("settrusteddomains-menu-label"), lambda: self.openSetTrustedDomainsDialog()) menu.addAction(QtGui.QPixmap(resourcespath + "shield_edit.png"), getMessage("settrusteddomains-menu-label"), lambda: self.openSetTrustedDomainsDialog())
menu.exec_(self.playlist.viewport().mapToGlobal(position)) menu.exec_(self.playlist.viewport().mapToGlobal(position))
def openRoomMenu(self, position): def openRoomMenu(self, position):
# TODO: Deselect items after right click # TODO: Deselect items after right click
indexes = self.listTreeView.selectedIndexes() indexes = self.listTreeView.selectedIndexes()
@ -694,7 +712,7 @@ class MainWindow(QtWidgets.QMainWindow):
def updateReadyState(self, newState): def updateReadyState(self, newState):
oldState = self.readyPushButton.isChecked() oldState = self.readyPushButton.isChecked()
if newState != oldState and newState != None: if newState != oldState and newState is not None:
self.readyPushButton.blockSignals(True) self.readyPushButton.blockSignals(True)
self.readyPushButton.setChecked(newState) self.readyPushButton.setChecked(newState)
self.readyPushButton.blockSignals(False) self.readyPushButton.blockSignals(False)
@ -768,7 +786,7 @@ class MainWindow(QtWidgets.QMainWindow):
@needsClient @needsClient
def joinRoom(self, room=None): def joinRoom(self, room=None):
if room == None: if room is None:
room = self.roomInput.text() room = self.roomInput.text()
if room == "": if room == "":
if self._syncplayClient.userlist.currentUser.file: if self._syncplayClient.userlist.currentUser.file:
@ -781,14 +799,13 @@ class MainWindow(QtWidgets.QMainWindow):
self._syncplayClient.sendRoom() self._syncplayClient.sendRoom()
def seekPositionDialog(self): def seekPositionDialog(self):
seekTime, ok = QtWidgets.QInputDialog.getText(self, getMessage("seektime-menu-label"), seekTime, ok = QtWidgets.QInputDialog.getText(
self, getMessage("seektime-menu-label"),
getMessage("seektime-msgbox-label"), QtWidgets.QLineEdit.Normal, getMessage("seektime-msgbox-label"), QtWidgets.QLineEdit.Normal,
"0:00") "0:00")
if ok and seekTime != '': if ok and seekTime != '':
self.seekPosition(seekTime) self.seekPosition(seekTime)
def seekFromButton(self): def seekFromButton(self):
self.seekPosition(self.seekInput.text()) self.seekPosition(self.seekInput.text())
@ -871,7 +888,7 @@ class MainWindow(QtWidgets.QMainWindow):
@needsClient @needsClient
def browseMediapath(self): def browseMediapath(self):
if self._syncplayClient._player.customOpenDialog == True: if self._syncplayClient._player.customOpenDialog:
self._syncplayClient._player.openCustomOpenDialog() self._syncplayClient._player.openCustomOpenDialog()
return return
@ -887,7 +904,8 @@ class MainWindow(QtWidgets.QMainWindow):
else: else:
defaultdirectory = self.getInitialMediaDirectory() defaultdirectory = self.getInitialMediaDirectory()
browserfilter = "All files (*)" browserfilter = "All files (*)"
fileName, filtr = QtWidgets.QFileDialog.getOpenFileName(self, getMessage("browseformedia-label"), defaultdirectory, fileName, filtr = QtWidgets.QFileDialog.getOpenFileName(
self, getMessage("browseformedia-label"), defaultdirectory,
browserfilter, "", options) browserfilter, "", options)
if fileName: if fileName:
if isWindows(): if isWindows():
@ -899,7 +917,7 @@ class MainWindow(QtWidgets.QMainWindow):
@needsClient @needsClient
def OpenAddFilesToPlaylistDialog(self): def OpenAddFilesToPlaylistDialog(self):
if self._syncplayClient._player.customOpenDialog == True: if self._syncplayClient._player.customOpenDialog:
self._syncplayClient._player.openCustomOpenDialog() self._syncplayClient._player.openCustomOpenDialog()
return return
@ -915,7 +933,8 @@ class MainWindow(QtWidgets.QMainWindow):
else: else:
defaultdirectory = self.getInitialMediaDirectory() defaultdirectory = self.getInitialMediaDirectory()
browserfilter = "All files (*)" browserfilter = "All files (*)"
fileNames, filtr = QtWidgets.QFileDialog.getOpenFileNames(self, getMessage("browseformedia-label"), defaultdirectory, fileNames, filtr = QtWidgets.QFileDialog.getOpenFileNames(
self, getMessage("browseformedia-label"), defaultdirectory,
browserfilter, "", options) browserfilter, "", options)
self.updatingPlaylist = True self.updatingPlaylist = True
if fileNames: if fileNames:
@ -1046,6 +1065,7 @@ class MainWindow(QtWidgets.QMainWindow):
if result == QtWidgets.QDialog.Accepted: if result == QtWidgets.QDialog.Accepted:
newTrustedDomains = utils.convertMultilineStringToList(TrustedDomainsTextbox.toPlainText()) newTrustedDomains = utils.convertMultilineStringToList(TrustedDomainsTextbox.toPlainText())
self._syncplayClient.setTrustedDomains(newTrustedDomains) self._syncplayClient.setTrustedDomains(newTrustedDomains)
@needsClient @needsClient
def addTrustedDomain(self, newDomain): def addTrustedDomain(self, newDomain):
trustedDomains = self.config["trustedDomains"][:] trustedDomains = self.config["trustedDomains"][:]
@ -1059,7 +1079,8 @@ class MainWindow(QtWidgets.QMainWindow):
options = QtWidgets.QFileDialog.Options(QtWidgets.QFileDialog.ShowDirsOnly | QtWidgets.QFileDialog.DontUseNativeDialog) options = QtWidgets.QFileDialog.Options(QtWidgets.QFileDialog.ShowDirsOnly | QtWidgets.QFileDialog.DontUseNativeDialog)
else: else:
options = QtWidgets.QFileDialog.Options(QtWidgets.QFileDialog.ShowDirsOnly) options = QtWidgets.QFileDialog.Options(QtWidgets.QFileDialog.ShowDirsOnly)
folderName = str(QtWidgets.QFileDialog.getExistingDirectory(self,None,self.getInitialMediaDirectory(includeUserSpecifiedDirectories=False),options)) folderName = str(QtWidgets.QFileDialog.getExistingDirectory(
self, None, self.getInitialMediaDirectory(includeUserSpecifiedDirectories=False), options))
if folderName: if folderName:
existingMediaDirs = MediaDirectoriesTextbox.toPlainText() existingMediaDirs = MediaDirectoriesTextbox.toPlainText()
@ -1073,15 +1094,16 @@ class MainWindow(QtWidgets.QMainWindow):
@needsClient @needsClient
def promptForStreamURL(self): def promptForStreamURL(self):
streamURL, ok = QtWidgets.QInputDialog.getText(self, getMessage("promptforstreamurl-msgbox-label"), streamURL, ok = QtWidgets.QInputDialog.getText(
getMessage("promptforstreamurlinfo-msgbox-label"), QtWidgets.QLineEdit.Normal, self, getMessage("promptforstreamurl-msgbox-label"),
"") getMessage("promptforstreamurlinfo-msgbox-label"), QtWidgets.QLineEdit.Normal, "")
if ok and streamURL != '': if ok and streamURL != '':
self._syncplayClient._player.openFile(streamURL) self._syncplayClient._player.openFile(streamURL)
@needsClient @needsClient
def createControlledRoom(self): def createControlledRoom(self):
controlroom, ok = QtWidgets.QInputDialog.getText(self, getMessage("createcontrolledroom-msgbox-label"), controlroom, ok = QtWidgets.QInputDialog.getText(
self, getMessage("createcontrolledroom-msgbox-label"),
getMessage("controlledroominfo-msgbox-label"), QtWidgets.QLineEdit.Normal, getMessage("controlledroominfo-msgbox-label"), QtWidgets.QLineEdit.Normal,
utils.stripRoomName(self._syncplayClient.getRoom())) utils.stripRoomName(self._syncplayClient.getRoom()))
if ok and controlroom != '': if ok and controlroom != '':
@ -1106,9 +1128,9 @@ class MainWindow(QtWidgets.QMainWindow):
@needsClient @needsClient
def setOffset(self): def setOffset(self):
newoffset, ok = QtWidgets.QInputDialog.getText(self, getMessage("setoffset-msgbox-label"), newoffset, ok = QtWidgets.QInputDialog.getText(
getMessage("offsetinfo-msgbox-label"), QtWidgets.QLineEdit.Normal, self, getMessage("setoffset-msgbox-label"),
"") getMessage("offsetinfo-msgbox-label"), QtWidgets.QLineEdit.Normal, "")
if ok and newoffset != '': if ok and newoffset != '':
o = re.match(constants.UI_OFFSET_REGEX, "o " + newoffset) o = re.match(constants.UI_OFFSET_REGEX, "o " + newoffset)
if o: if o:
@ -1187,7 +1209,8 @@ class MainWindow(QtWidgets.QMainWindow):
window.chatInput = QtWidgets.QLineEdit() window.chatInput = QtWidgets.QLineEdit()
window.chatInput.setMaxLength(constants.MAX_CHAT_MESSAGE_LENGTH) window.chatInput.setMaxLength(constants.MAX_CHAT_MESSAGE_LENGTH)
window.chatInput.returnPressed.connect(self.sendChatMessage) window.chatInput.returnPressed.connect(self.sendChatMessage)
window.chatButton = QtWidgets.QPushButton(QtGui.QPixmap(resourcespath + 'email_go.png'), window.chatButton = QtWidgets.QPushButton(
QtGui.QPixmap(resourcespath + 'email_go.png'),
getMessage("sendmessage-label")) getMessage("sendmessage-label"))
window.chatButton.pressed.connect(self.sendChatMessage) window.chatButton.pressed.connect(self.sendChatMessage)
window.chatLayout = QtWidgets.QHBoxLayout() window.chatLayout = QtWidgets.QHBoxLayout()
@ -1242,7 +1265,8 @@ class MainWindow(QtWidgets.QMainWindow):
window.roomInput = QtWidgets.QLineEdit() window.roomInput = QtWidgets.QLineEdit()
window.roomInput.setMaxLength(constants.MAX_ROOM_NAME_LENGTH) window.roomInput.setMaxLength(constants.MAX_ROOM_NAME_LENGTH)
window.roomInput.returnPressed.connect(self.joinRoom) window.roomInput.returnPressed.connect(self.joinRoom)
window.roomButton = QtWidgets.QPushButton(QtGui.QPixmap(resourcespath + 'door_in.png'), window.roomButton = QtWidgets.QPushButton(
QtGui.QPixmap(resourcespath + 'door_in.png'),
getMessage("joinroom-label")) getMessage("joinroom-label"))
window.roomButton.pressed.connect(self.joinRoom) window.roomButton.pressed.connect(self.joinRoom)
window.roomLayout = QtWidgets.QHBoxLayout() window.roomLayout = QtWidgets.QHBoxLayout()
@ -1405,7 +1429,6 @@ class MainWindow(QtWidgets.QMainWindow):
getMessage("setmediadirectories-menu-label")) getMessage("setmediadirectories-menu-label"))
window.openAction.triggered.connect(self.openSetMediaDirectoriesDialog) window.openAction.triggered.connect(self.openSetMediaDirectoriesDialog)
window.exitAction = window.fileMenu.addAction(QtGui.QPixmap(resourcespath + 'cross.png'), window.exitAction = window.fileMenu.addAction(QtGui.QPixmap(resourcespath + 'cross.png'),
getMessage("exit-menu-label")) getMessage("exit-menu-label"))
window.exitAction.triggered.connect(self.exitSyncplay) window.exitAction.triggered.connect(self.exitSyncplay)
@ -1414,13 +1437,21 @@ class MainWindow(QtWidgets.QMainWindow):
# Playback menu # Playback menu
window.playbackMenu = QtWidgets.QMenu(getMessage("playback-menu-label"), self) window.playbackMenu = QtWidgets.QMenu(getMessage("playback-menu-label"), self)
window.playAction = window.playbackMenu.addAction(QtGui.QPixmap(resourcespath + 'control_play_blue.png'), getMessage("play-menu-label")) window.playAction = window.playbackMenu.addAction(
QtGui.QPixmap(resourcespath + 'control_play_blue.png'),
getMessage("play-menu-label"))
window.playAction.triggered.connect(self.play) window.playAction.triggered.connect(self.play)
window.pauseAction = window.playbackMenu.addAction(QtGui.QPixmap(resourcespath + 'control_pause_blue.png'), getMessage("pause-menu-label")) window.pauseAction = window.playbackMenu.addAction(
QtGui.QPixmap(resourcespath + 'control_pause_blue.png'),
getMessage("pause-menu-label"))
window.pauseAction.triggered.connect(self.pause) window.pauseAction.triggered.connect(self.pause)
window.seekAction = window.playbackMenu.addAction(QtGui.QPixmap(resourcespath + 'clock_go.png'), getMessage("seektime-menu-label")) window.seekAction = window.playbackMenu.addAction(
QtGui.QPixmap(resourcespath + 'clock_go.png'),
getMessage("seektime-menu-label"))
window.seekAction.triggered.connect(self.seekPositionDialog) window.seekAction.triggered.connect(self.seekPositionDialog)
window.unseekAction = window.playbackMenu.addAction(QtGui.QPixmap(resourcespath + 'arrow_undo.png'), getMessage("undoseek-menu-label")) window.unseekAction = window.playbackMenu.addAction(
QtGui.QPixmap(resourcespath + 'arrow_undo.png'),
getMessage("undoseek-menu-label"))
window.unseekAction.triggered.connect(self.undoSeek) window.unseekAction.triggered.connect(self.undoSeek)
window.menuBar.addMenu(window.playbackMenu) window.menuBar.addMenu(window.playbackMenu)
@ -1428,10 +1459,12 @@ class MainWindow(QtWidgets.QMainWindow):
# Advanced menu # Advanced menu
window.advancedMenu = QtWidgets.QMenu(getMessage("advanced-menu-label"), self) window.advancedMenu = QtWidgets.QMenu(getMessage("advanced-menu-label"), self)
window.setoffsetAction = window.advancedMenu.addAction(QtGui.QPixmap(resourcespath + 'timeline_marker.png'), window.setoffsetAction = window.advancedMenu.addAction(
QtGui.QPixmap(resourcespath + 'timeline_marker.png'),
getMessage("setoffset-menu-label")) getMessage("setoffset-menu-label"))
window.setoffsetAction.triggered.connect(self.setOffset) window.setoffsetAction.triggered.connect(self.setOffset)
window.setTrustedDomainsAction = window.advancedMenu.addAction(QtGui.QPixmap(resourcespath + 'shield_edit.png'), window.setTrustedDomainsAction = window.advancedMenu.addAction(
QtGui.QPixmap(resourcespath + 'shield_edit.png'),
getMessage("settrusteddomains-menu-label")) getMessage("settrusteddomains-menu-label"))
window.setTrustedDomainsAction.triggered.connect(self.openSetTrustedDomainsDialog) window.setTrustedDomainsAction.triggered.connect(self.openSetTrustedDomainsDialog)
window.createcontrolledroomAction = window.advancedMenu.addAction( window.createcontrolledroomAction = window.advancedMenu.addAction(
@ -1456,21 +1489,23 @@ class MainWindow(QtWidgets.QMainWindow):
window.autoplayAction.triggered.connect(self.updateAutoplayVisibility) window.autoplayAction.triggered.connect(self.updateAutoplayVisibility)
window.menuBar.addMenu(window.windowMenu) window.menuBar.addMenu(window.windowMenu)
# Help menu # Help menu
window.helpMenu = QtWidgets.QMenu(getMessage("help-menu-label"), self) window.helpMenu = QtWidgets.QMenu(getMessage("help-menu-label"), self)
window.userguideAction = window.helpMenu.addAction(QtGui.QPixmap(resourcespath + 'help.png'), window.userguideAction = window.helpMenu.addAction(
QtGui.QPixmap(resourcespath + 'help.png'),
getMessage("userguide-menu-label")) getMessage("userguide-menu-label"))
window.userguideAction.triggered.connect(self.openUserGuide) window.userguideAction.triggered.connect(self.openUserGuide)
window.updateAction = window.helpMenu.addAction(QtGui.QPixmap(resourcespath + 'application_get.png'), window.updateAction = window.helpMenu.addAction(
getMessage("update-menu-label")) QtGui.QPixmap(resourcespath + 'application_get.png'),
etMessage("update-menu-label"))
window.updateAction.triggered.connect(self.userCheckForUpdates) window.updateAction.triggered.connect(self.userCheckForUpdates)
if not isMacOS(): if not isMacOS():
window.helpMenu.addSeparator() window.helpMenu.addSeparator()
window.about = window.helpMenu.addAction(QtGui.QPixmap(resourcespath + 'syncplay.png'), window.about = window.helpMenu.addAction(
QtGui.QPixmap(resourcespath + 'syncplay.png'),
getMessage("about-menu-label")) getMessage("about-menu-label"))
else: else:
window.about = window.helpMenu.addAction("&About") window.about = window.helpMenu.addAction("&About")
@ -1528,7 +1563,7 @@ class MainWindow(QtWidgets.QMainWindow):
def updateAutoPlayState(self, newState): def updateAutoPlayState(self, newState):
oldState = self.autoplayPushButton.isChecked() oldState = self.autoplayPushButton.isChecked()
if newState != oldState and newState != None: if newState != oldState and newState is not None:
self.autoplayPushButton.blockSignals(True) self.autoplayPushButton.blockSignals(True)
self.autoplayPushButton.setChecked(newState) self.autoplayPushButton.setChecked(newState)
self.autoplayPushButton.blockSignals(False) self.autoplayPushButton.blockSignals(False)
@ -1591,10 +1626,11 @@ class MainWindow(QtWidgets.QMainWindow):
else: else:
import syncplay import syncplay
updateMessage = getMessage("update-check-failed-notification").format(syncplay.version) updateMessage = getMessage("update-check-failed-notification").format(syncplay.version)
if userInitiated == True: if userInitiated:
updateURL = constants.SYNCPLAY_DOWNLOAD_URL updateURL = constants.SYNCPLAY_DOWNLOAD_URL
if updateURL is not None: if updateURL is not None:
reply = QtWidgets.QMessageBox.question(self, "Syncplay", reply = QtWidgets.QMessageBox.question(
self, "Syncplay",
updateMessage, QtWidgets.QMessageBox.StandardButton.Yes | QtWidgets.QMessageBox.StandardButton.No) updateMessage, QtWidgets.QMessageBox.StandardButton.Yes | QtWidgets.QMessageBox.StandardButton.No)
if reply == QtWidgets.QMessageBox.Yes: if reply == QtWidgets.QMessageBox.Yes:
self.QtGui.QDesktopServices.openUrl(QUrl(updateURL)) self.QtGui.QDesktopServices.openUrl(QUrl(updateURL))
@ -1624,7 +1660,7 @@ class MainWindow(QtWidgets.QMainWindow):
dropfilepath = os.path.abspath(NSURL.URLWithString_(pathString).filePathURL().path()) dropfilepath = os.path.abspath(NSURL.URLWithString_(pathString).filePathURL().path())
else: else:
dropfilepath = os.path.abspath(str(url.toLocalFile())) dropfilepath = os.path.abspath(str(url.toLocalFile()))
if rewindFile == False: if not rewindFile:
self._syncplayClient._player.openFile(dropfilepath) self._syncplayClient._player.openFile(dropfilepath)
else: else:
self._syncplayClient.setPosition(0) self._syncplayClient.setPosition(0)

View File

@ -38,9 +38,9 @@ LICENSE
""" """
import os import os
import shutil
import sys import sys
import types import types
import shutil
__version__ = "1.1.0" __version__ = "1.1.0"
@ -1437,7 +1437,6 @@ def _qInstallMessageHandler(handler):
return Qt._QtCore.qInstallMessageHandler(passObject) return Qt._QtCore.qInstallMessageHandler(passObject)
def _convert(lines): def _convert(lines):
"""Convert compiled .ui file from PySide2 to Qt.py """Convert compiled .ui file from PySide2 to Qt.py