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,95 +1,99 @@
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 = {
"host": None, "host": None,
"port": constants.DEFAULT_PORT, "port": constants.DEFAULT_PORT,
"name": None, "name": None,
"debug": False, "debug": False,
"forceGuiPrompt": True, "forceGuiPrompt": True,
"noGui": False, "noGui": False,
"noStore": False, "noStore": False,
"room": "", "room": "",
"password": None, "password": None,
"playerPath": None, "playerPath": None,
"perPlayerArguments": None, "perPlayerArguments": None,
"mediaSearchDirectories": None, "mediaSearchDirectories": None,
"sharedPlaylistEnabled": True, "sharedPlaylistEnabled": True,
"loopAtEndOfPlaylist": False, "loopAtEndOfPlaylist": False,
"loopSingleFiles" : False, "loopSingleFiles": False,
"onlySwitchToTrustedDomains": True, "onlySwitchToTrustedDomains": True,
"trustedDomains": constants.DEFAULT_TRUSTED_DOMAINS, "trustedDomains": constants.DEFAULT_TRUSTED_DOMAINS,
"file": None, "file": None,
"playerArgs": [], "playerArgs": [],
"playerClass": None, "playerClass": None,
"slowdownThreshold": constants.DEFAULT_SLOWDOWN_KICKIN_THRESHOLD, "slowdownThreshold": constants.DEFAULT_SLOWDOWN_KICKIN_THRESHOLD,
"rewindThreshold": constants.DEFAULT_REWIND_THRESHOLD, "rewindThreshold": constants.DEFAULT_REWIND_THRESHOLD,
"fastforwardThreshold": constants.DEFAULT_FASTFORWARD_THRESHOLD, "fastforwardThreshold": constants.DEFAULT_FASTFORWARD_THRESHOLD,
"rewindOnDesync": True, "rewindOnDesync": True,
"slowOnDesync": True, "slowOnDesync": True,
"fastforwardOnDesync": True, "fastforwardOnDesync": True,
"dontSlowDownWithMe": False, "dontSlowDownWithMe": False,
"filenamePrivacyMode": constants.PRIVACY_SENDRAW_MODE, "filenamePrivacyMode": constants.PRIVACY_SENDRAW_MODE,
"filesizePrivacyMode": constants.PRIVACY_SENDRAW_MODE, "filesizePrivacyMode": constants.PRIVACY_SENDRAW_MODE,
"pauseOnLeave": False, "pauseOnLeave": False,
"readyAtStart": False, "readyAtStart": False,
"unpauseAction": constants.UNPAUSE_IFOTHERSREADY_MODE, "unpauseAction": constants.UNPAUSE_IFOTHERSREADY_MODE,
"autoplayInitialState" : None, "autoplayInitialState": None,
"autoplayMinUsers" : -1, "autoplayMinUsers": -1,
"autoplayRequireSameFilenames": True, "autoplayRequireSameFilenames": True,
"clearGUIData": False, "clearGUIData": False,
"language" : "", "language": "",
"checkForUpdatesAutomatically" : None, "checkForUpdatesAutomatically": None,
"lastCheckedForUpdates" : "", "lastCheckedForUpdates": "",
"resetConfig" : False, "resetConfig": False,
"showOSD" : True, "showOSD": True,
"showOSDWarnings" : True, "showOSDWarnings": True,
"showSlowdownOSD" : True, "showSlowdownOSD": True,
"showDifferentRoomOSD" : False, "showDifferentRoomOSD": False,
"showSameRoomOSD" : True, "showSameRoomOSD": True,
"showNonControllerOSD" : False, "showNonControllerOSD": False,
"showContactInfo" : True, "showContactInfo": True,
"showDurationNotification" : True, "showDurationNotification": True,
"chatInputEnabled" : True, "chatInputEnabled": True,
"chatInputFontFamily" : 'sans-serif', "chatInputFontFamily": 'sans-serif',
"chatInputRelativeFontSize" : constants.DEFAULT_CHAT_FONT_SIZE, "chatInputRelativeFontSize": constants.DEFAULT_CHAT_FONT_SIZE,
"chatInputFontWeight" : constants.DEFAULT_CHAT_FONT_WEIGHT, "chatInputFontWeight": constants.DEFAULT_CHAT_FONT_WEIGHT,
"chatInputFontUnderline": False, "chatInputFontUnderline": False,
"chatInputFontColor": constants.DEFAULT_CHAT_INPUT_FONT_COLOR, "chatInputFontColor": constants.DEFAULT_CHAT_INPUT_FONT_COLOR,
"chatInputPosition": constants.INPUT_POSITION_TOP, "chatInputPosition": constants.INPUT_POSITION_TOP,
"chatDirectInput": False, "chatDirectInput": False,
"chatOutputEnabled": True, "chatOutputEnabled": True,
"chatOutputFontFamily": 'sans-serif', "chatOutputFontFamily": 'sans-serif',
"chatOutputRelativeFontSize": constants.DEFAULT_CHAT_FONT_SIZE, "chatOutputRelativeFontSize": constants.DEFAULT_CHAT_FONT_SIZE,
"chatOutputFontWeight": constants.DEFAULT_CHAT_FONT_WEIGHT, "chatOutputFontWeight": constants.DEFAULT_CHAT_FONT_WEIGHT,
"chatOutputFontUnderline": False, "chatOutputFontUnderline": False,
"chatOutputMode": constants.CHATROOM_MODE, "chatOutputMode": constants.CHATROOM_MODE,
"chatMaxLines": 7, "chatMaxLines": 7,
"chatTopMargin": 25, "chatTopMargin": 25,
"chatLeftMargin": 20, "chatLeftMargin": 20,
"chatBottomMargin": 30, "chatBottomMargin": 30,
"chatMoveOSD": True, "chatMoveOSD": True,
"chatOSDMargin": 110, "chatOSDMargin": 110,
"notificationTimeout": 3, "notificationTimeout": 3,
"alertTimeout": 5, "alertTimeout": 5,
"chatTimeout": 7, "chatTimeout": 7,
"publicServers" : [] "publicServers": []
} }
self._defaultConfig = self._config.copy() self._defaultConfig = self._config.copy()
@ -97,47 +101,47 @@ class ConfigurationGetter(object):
# Custom validation in self._validateArguments # Custom validation in self._validateArguments
# #
self._required = [ self._required = [
"host", "host",
"port", "port",
"room", "room",
"playerPath", "playerPath",
"playerClass", "playerClass",
] ]
self._boolean = [ self._boolean = [
"debug", "debug",
"forceGuiPrompt", "forceGuiPrompt",
"noGui", "noGui",
"noStore", "noStore",
"dontSlowDownWithMe", "dontSlowDownWithMe",
"pauseOnLeave", "pauseOnLeave",
"readyAtStart", "readyAtStart",
"autoplayRequireSameFilenames", "autoplayRequireSameFilenames",
"clearGUIData", "clearGUIData",
"rewindOnDesync", "rewindOnDesync",
"slowOnDesync", "slowOnDesync",
"fastforwardOnDesync", "fastforwardOnDesync",
"pauseOnLeave", "pauseOnLeave",
"clearGUIData", "clearGUIData",
"resetConfig", "resetConfig",
"showOSD", "showOSD",
"showOSDWarnings", "showOSDWarnings",
"showSlowdownOSD", "showSlowdownOSD",
"showDifferentRoomOSD", "showDifferentRoomOSD",
"showSameRoomOSD", "showSameRoomOSD",
"showNonControllerOSD", "showNonControllerOSD",
"showDurationNotification", "showDurationNotification",
"sharedPlaylistEnabled", "sharedPlaylistEnabled",
"loopAtEndOfPlaylist", "loopAtEndOfPlaylist",
"loopSingleFiles", "loopSingleFiles",
"onlySwitchToTrustedDomains", "onlySwitchToTrustedDomains",
"chatInputEnabled", "chatInputEnabled",
"chatInputFontUnderline", "chatInputFontUnderline",
"chatDirectInput", "chatDirectInput",
"chatMoveOSD", "chatMoveOSD",
"chatOutputEnabled", "chatOutputEnabled",
"chatOutputFontUnderline" "chatOutputFontUnderline"
] ]
self._tristate = [ self._tristate = [
"checkForUpdatesAutomatically", "checkForUpdatesAutomatically",
"autoplayInitialState", "autoplayInitialState",
@ -174,37 +178,40 @@ class ConfigurationGetter(object):
] ]
self._iniStructure = { self._iniStructure = {
"server_data": ["host", "port", "password"], "server_data": ["host", "port", "password"],
"client_settings": ["name", "room", "playerPath", "client_settings": [
"perPlayerArguments", "slowdownThreshold", "name", "room", "playerPath",
"rewindThreshold", "fastforwardThreshold", "perPlayerArguments", "slowdownThreshold",
"slowOnDesync", "rewindOnDesync", "rewindThreshold", "fastforwardThreshold",
"fastforwardOnDesync", "dontSlowDownWithMe", "slowOnDesync", "rewindOnDesync",
"forceGuiPrompt", "filenamePrivacyMode", "fastforwardOnDesync", "dontSlowDownWithMe",
"filesizePrivacyMode", "unpauseAction", "forceGuiPrompt", "filenamePrivacyMode",
"pauseOnLeave", "readyAtStart", "autoplayMinUsers", "filesizePrivacyMode", "unpauseAction",
"autoplayInitialState", "mediaSearchDirectories", "pauseOnLeave", "readyAtStart", "autoplayMinUsers",
"sharedPlaylistEnabled", "loopAtEndOfPlaylist", "autoplayInitialState", "mediaSearchDirectories",
"loopSingleFiles", "sharedPlaylistEnabled", "loopAtEndOfPlaylist",
"onlySwitchToTrustedDomains", "trustedDomains","publicServers"], "loopSingleFiles",
"gui": ["showOSD", "showOSDWarnings", "showSlowdownOSD", "onlySwitchToTrustedDomains", "trustedDomains", "publicServers"],
"showDifferentRoomOSD", "showSameRoomOSD", "gui": [
"showNonControllerOSD", "showDurationNotification", "showOSD", "showOSDWarnings", "showSlowdownOSD",
"chatInputEnabled","chatInputFontUnderline", "showDifferentRoomOSD", "showSameRoomOSD",
"chatInputFontFamily", "chatInputRelativeFontSize", "showNonControllerOSD", "showDurationNotification",
"chatInputFontWeight", "chatInputFontColor", "chatInputEnabled", "chatInputFontUnderline",
"chatInputPosition","chatDirectInput", "chatInputFontFamily", "chatInputRelativeFontSize",
"chatOutputFontFamily", "chatOutputRelativeFontSize", "chatInputFontWeight", "chatInputFontColor",
"chatOutputFontWeight", "chatOutputFontUnderline", "chatInputPosition", "chatDirectInput",
"chatOutputMode", "chatMaxLines", "chatOutputFontFamily", "chatOutputRelativeFontSize",
"chatTopMargin", "chatLeftMargin", "chatOutputFontWeight", "chatOutputFontUnderline",
"chatBottomMargin", "chatDirectInput", "chatOutputMode", "chatMaxLines",
"chatMoveOSD", "chatOSDMargin", "chatTopMargin", "chatLeftMargin",
"notificationTimeout", "alertTimeout", "chatBottomMargin", "chatDirectInput",
"chatTimeout","chatOutputEnabled"], "chatMoveOSD", "chatOSDMargin",
"general": ["language", "checkForUpdatesAutomatically", "notificationTimeout", "alertTimeout",
"lastCheckedForUpdates"] "chatTimeout", "chatOutputEnabled"],
} "general": [
"language", "checkForUpdatesAutomatically",
"lastCheckedForUpdates"]
}
self._playerFactory = PlayerFactory() self._playerFactory = PlayerFactory()
@ -215,7 +222,7 @@ class ConfigurationGetter(object):
self._config = self._defaultConfig self._config = self._defaultConfig
self._config['language'] = language self._config['language'] = language
self._config['checkForUpdatesAutomatically'] = checkForUpdatesAutomatically self._config['checkForUpdatesAutomatically'] = checkForUpdatesAutomatically
raise InvalidConfigValue("*"+getMessage("config-cleared-notification")) raise InvalidConfigValue("*" + getMessage("config-cleared-notification"))
if not isValidLanguage(self._config['language']): if not isValidLanguage(self._config['language']):
self._config['language'] = "" self._config['language'] = ""
@ -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:
@ -325,12 +333,12 @@ class ConfigurationGetter(object):
if configFile: if configFile:
return configFile return configFile
for name in constants.CONFIG_NAMES: for name in constants.CONFIG_NAMES:
configFile = self._expandConfigPath(name, xdg = False) configFile = self._expandConfigPath(name, xdg=False)
if os.path.isfile(configFile): if os.path.isfile(configFile):
return configFile return configFile
return self._expandConfigPath() return self._expandConfigPath()
def _expandConfigPath(self, name = None, xdg = True): def _expandConfigPath(self, name=None, xdg=True):
if os.name != 'nt': if os.name != 'nt':
if xdg: if xdg:
prefix = self._getXdgConfigHome() prefix = self._getXdgConfigHome()
@ -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,8 +459,9 @@ 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(
epilog=getMessage("argument-epilog")) description=getMessage("argument-description"),
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"))
self._argparser.add_argument('-n', '--name', metavar='username', type=str, help=getMessage("name-argument")) self._argparser.add_argument('-n', '--name', metavar='username', type=str, help=getMessage("name-argument"))
@ -481,7 +489,7 @@ class ConfigurationGetter(object):
if not (IsPySide2 or IsPySide): if not (IsPySide2 or IsPySide):
raise ImportError raise ImportError
if QCoreApplication.instance() is None: if QCoreApplication.instance() is None:
self.app = QtWidgets.QApplication(sys.argv) self.app = QtWidgets.QApplication(sys.argv)
qt5reactor.install() qt5reactor.install()
if isMacOS(): if isMacOS():
import appnope import appnope
@ -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():
@ -123,7 +130,7 @@ class ConfigDialog(QtWidgets.QDialog):
self.mediabrowseButton.show() self.mediabrowseButton.show()
self.saveMoreState(False) self.saveMoreState(False)
self.stackedLayout.setCurrentIndex(0) self.stackedLayout.setCurrentIndex(0)
newHeight = self.connectionSettingsGroup.minimumSizeHint().height()+self.mediaplayerSettingsGroup.minimumSizeHint().height()+self.bottomButtonFrame.minimumSizeHint().height()+3 newHeight = self.connectionSettingsGroup.minimumSizeHint().height() + self.mediaplayerSettingsGroup.minimumSizeHint().height() + self.bottomButtonFrame.minimumSizeHint().height() + 3
if self.error: if self.error:
newHeight += self.errorLabel.height()+3 newHeight += self.errorLabel.height()+3
self.stackedFrame.setFixedHeight(newHeight) self.stackedFrame.setFixedHeight(newHeight)
@ -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):
@ -226,7 +233,7 @@ class ConfigDialog(QtWidgets.QDialog):
if currentplayerpath: if currentplayerpath:
NewPlayerArgs = self.playerargsTextbox.text().split(" ") if self.playerargsTextbox.text() else "" NewPlayerArgs = self.playerargsTextbox.text().split(" ") if self.playerargsTextbox.text() else ""
self.perPlayerArgs[self.executablepathCombobox.currentText()]=NewPlayerArgs self.perPlayerArgs[self.executablepathCombobox.currentText()] = NewPlayerArgs
def languageChanged(self): def languageChanged(self):
setLanguage(str(self.languageCombobox.itemData(self.languageCombobox.currentIndex()))) setLanguage(str(self.languageCombobox.itemData(self.languageCombobox.currentIndex())))
@ -252,10 +259,11 @@ 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(
"Browse for media player executable", self,
defaultdirectory, "Browse for media player executable",
browserfilter, "", options) defaultdirectory,
browserfilter, "", options)
if fileName: if fileName:
if isMacOS() and fileName.endswith('.app'): # see GitHub issue #91 if isMacOS() and fileName.endswith('.app'): # see GitHub issue #91
# Mac OS X application bundles contain a Info.plist in the Contents subdirectory of the .app. # Mac OS X application bundles contain a Info.plist in the Contents subdirectory of the .app.
@ -286,7 +294,7 @@ class ConfigDialog(QtWidgets.QDialog):
# Step 3: use the first executable in the list if no executable was found # Step 3: use the first executable in the list if no executable was found
try: try:
if not foundExe: if not foundExe:
fileName = execFiles[0] fileName = execFiles[0]
except IndexError: # whoops, looks like this .app doesn't contain a executable file at all except IndexError: # whoops, looks like this .app doesn't contain a executable file at all
pass pass
@ -387,8 +395,9 @@ 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(
browserfilter, "", options) self, "Browse for media files", defaultdirectory,
browserfilter, "", options)
if fileName: if fileName:
self.mediapathTextbox.setText(os.path.normpath(fileName)) self.mediapathTextbox.setText(os.path.normpath(fileName))
self.mediadirectory = os.path.dirname(fileName) self.mediadirectory = os.path.dirname(fileName)
@ -412,7 +421,7 @@ class ConfigDialog(QtWidgets.QDialog):
self.processWidget(self, lambda w: self.saveValues(w)) self.processWidget(self, lambda w: self.saveValues(w))
if self.hostCombobox.currentText(): if self.hostCombobox.currentText():
self.config['host'] = self.hostCombobox.currentText() if ":" in self.hostCombobox.currentText() else self.hostCombobox.currentText() + ":" + str(constants.DEFAULT_PORT) self.config['host'] = self.hostCombobox.currentText() if ":" in self.hostCombobox.currentText() else self.hostCombobox.currentText() + ":" + str(constants.DEFAULT_PORT)
self.config['host'] = self.config['host'].replace(" ","").replace("\t", "").replace("\n","").replace("\r","") self.config['host'] = self.config['host'].replace(" ", "").replace("\t", "").replace("\n", "").replace("\r", "")
else: else:
self.config['host'] = None self.config['host'] = None
self.config['playerPath'] = str(self.safenormcaseandpath(self.executablepathCombobox.currentText())) self.config['playerPath'] = str(self.safenormcaseandpath(self.executablepathCombobox.currentText()))
@ -437,7 +446,7 @@ class ConfigDialog(QtWidgets.QDialog):
def keyPressEvent(self, event): def keyPressEvent(self, event):
if event.key() == Qt.Key_Escape: if event.key() == Qt.Key_Escape:
sys.exit() sys.exit()
def dragEnterEvent(self, event): def dragEnterEvent(self, event):
data = event.mimeData() data = event.mimeData()
@ -495,7 +504,7 @@ class ConfigDialog(QtWidgets.QDialog):
else: else:
widget.setChecked(self.config[valueName] != inverted) widget.setChecked(self.config[valueName] != inverted)
elif isinstance(widget, QRadioButton): elif isinstance(widget, QRadioButton):
radioName, radioValue = valueName.split(constants.CONFIG_NAME_MARKER)[1].split(constants.CONFIG_VALUE_MARKER) radioName, radioValue = valueName.split(constants.CONFIG_NAME_MARKER)[1].split(constants.CONFIG_VALUE_MARKER)
if self.config[radioName] == radioValue: if self.config[radioName] == radioValue:
widget.setChecked(True) widget.setChecked(True)
elif isinstance(widget, QLineEdit): elif isinstance(widget, QLineEdit):
@ -517,7 +526,7 @@ class ConfigDialog(QtWidgets.QDialog):
inverted = False inverted = False
self.config[valueName] = widget.isChecked() != inverted self.config[valueName] = widget.isChecked() != inverted
elif isinstance(widget, QRadioButton): elif isinstance(widget, QRadioButton):
radioName, radioValue = valueName.split(constants.CONFIG_NAME_MARKER)[1].split(constants.CONFIG_VALUE_MARKER) radioName, radioValue = valueName.split(constants.CONFIG_NAME_MARKER)[1].split(constants.CONFIG_VALUE_MARKER)
if widget.isChecked(): if widget.isChecked():
self.config[radioName] = radioValue self.config[radioName] = radioValue
elif isinstance(widget, QLineEdit): elif isinstance(widget, QLineEdit):
@ -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)
@ -649,8 +658,8 @@ class ConfigDialog(QtWidgets.QDialog):
self.mediaplayerSettingsLayout.addWidget(self.executablepathCombobox, 0, 2) self.mediaplayerSettingsLayout.addWidget(self.executablepathCombobox, 0, 2)
self.mediaplayerSettingsLayout.addWidget(self.executablebrowseButton, 0, 3) self.mediaplayerSettingsLayout.addWidget(self.executablebrowseButton, 0, 3)
self.mediaplayerSettingsLayout.addWidget(self.mediapathLabel, 1, 0) self.mediaplayerSettingsLayout.addWidget(self.mediapathLabel, 1, 0)
self.mediaplayerSettingsLayout.addWidget(self.mediapathTextbox , 1, 2) self.mediaplayerSettingsLayout.addWidget(self.mediapathTextbox, 1, 2)
self.mediaplayerSettingsLayout.addWidget(self.mediabrowseButton , 1, 3) self.mediaplayerSettingsLayout.addWidget(self.mediabrowseButton, 1, 3)
self.mediaplayerSettingsLayout.addWidget(self.playerargsLabel, 2, 0, 1, 2) self.mediaplayerSettingsLayout.addWidget(self.playerargsLabel, 2, 0, 1, 2)
self.mediaplayerSettingsLayout.addWidget(self.playerargsTextbox, 2, 2, 1, 2) self.mediaplayerSettingsLayout.addWidget(self.playerargsTextbox, 2, 2, 1, 2)
self.mediaplayerSettingsGroup.setLayout(self.mediaplayerSettingsLayout) self.mediaplayerSettingsGroup.setLayout(self.mediaplayerSettingsLayout)
@ -836,7 +845,7 @@ class ConfigDialog(QtWidgets.QDialog):
self.desyncFrame.setMidLineWidth(0) self.desyncFrame.setMidLineWidth(0)
self.desyncSettingsLayout.addWidget(self.slowdownCheckbox, 0, 0, 1, 2, Qt.AlignLeft) self.desyncSettingsLayout.addWidget(self.slowdownCheckbox, 0, 0, 1, 2, Qt.AlignLeft)
self.desyncSettingsLayout.addWidget(self.rewindCheckbox, 1, 0,1,2, Qt.AlignLeft) self.desyncSettingsLayout.addWidget(self.rewindCheckbox, 1, 0, 1, 2, Qt.AlignLeft)
self.desyncSettingsLayout.setAlignment(Qt.AlignLeft) self.desyncSettingsLayout.setAlignment(Qt.AlignLeft)
self.desyncSettingsGroup.setLayout(self.desyncSettingsLayout) self.desyncSettingsGroup.setLayout(self.desyncSettingsLayout)
@ -854,7 +863,7 @@ class ConfigDialog(QtWidgets.QDialog):
self.othersyncSettingsLayout.addWidget(self.dontslowwithmeCheckbox, 2, 0, 1, 2, Qt.AlignLeft) self.othersyncSettingsLayout.addWidget(self.dontslowwithmeCheckbox, 2, 0, 1, 2, Qt.AlignLeft)
self.othersyncSettingsLayout.setAlignment(Qt.AlignLeft) self.othersyncSettingsLayout.setAlignment(Qt.AlignLeft)
self.othersyncSettingsLayout.addWidget(self.fastforwardCheckbox, 3, 0,1,2, Qt.AlignLeft) self.othersyncSettingsLayout.addWidget(self.fastforwardCheckbox, 3, 0, 1, 2, Qt.AlignLeft)
## Trusted domains ## Trusted domains
@ -891,13 +900,13 @@ class ConfigDialog(QtWidgets.QDialog):
self.chatInputGroup.setLayout(self.chatInputLayout) self.chatInputGroup.setLayout(self.chatInputLayout)
self.chatInputEnabledCheckbox = QCheckBox(getMessage("chatinputenabled-label")) self.chatInputEnabledCheckbox = QCheckBox(getMessage("chatinputenabled-label"))
self.chatInputEnabledCheckbox.setObjectName("chatInputEnabled") self.chatInputEnabledCheckbox.setObjectName("chatInputEnabled")
self.chatInputLayout.addWidget(self.chatInputEnabledCheckbox, 1, 0, 1,1, Qt.AlignLeft) self.chatInputLayout.addWidget(self.chatInputEnabledCheckbox, 1, 0, 1, 1, Qt.AlignLeft)
self.chatDirectInputCheckbox = QCheckBox(getMessage("chatdirectinput-label")) self.chatDirectInputCheckbox = QCheckBox(getMessage("chatdirectinput-label"))
self.chatDirectInputCheckbox.setObjectName("chatDirectInput") self.chatDirectInputCheckbox.setObjectName("chatDirectInput")
self.chatDirectInputCheckbox.setStyleSheet( self.chatDirectInputCheckbox.setStyleSheet(
constants.STYLE_SUBCHECKBOX.format(self.posixresourcespath + "chevrons_right.png")) constants.STYLE_SUBCHECKBOX.format(self.posixresourcespath + "chevrons_right.png"))
self.chatInputLayout.addWidget(self.chatDirectInputCheckbox, 2, 0, 1,1, Qt.AlignLeft) self.chatInputLayout.addWidget(self.chatDirectInputCheckbox, 2, 0, 1, 1, Qt.AlignLeft)
self.inputFontLayout = QtWidgets.QHBoxLayout() self.inputFontLayout = QtWidgets.QHBoxLayout()
self.inputFontLayout.setContentsMargins(0, 0, 0, 0) self.inputFontLayout.setContentsMargins(0, 0, 0, 0)
@ -959,7 +968,7 @@ class ConfigDialog(QtWidgets.QDialog):
self.chatOutputGroup.setLayout(self.chatOutputLayout) self.chatOutputGroup.setLayout(self.chatOutputLayout)
self.chatOutputEnabledCheckbox = QCheckBox(getMessage("chatoutputenabled-label")) self.chatOutputEnabledCheckbox = QCheckBox(getMessage("chatoutputenabled-label"))
self.chatOutputEnabledCheckbox.setObjectName("chatOutputEnabled") self.chatOutputEnabledCheckbox.setObjectName("chatOutputEnabled")
self.chatOutputLayout.addWidget(self.chatOutputEnabledCheckbox, 1, 0, 1,1, Qt.AlignLeft) self.chatOutputLayout.addWidget(self.chatOutputEnabledCheckbox, 1, 0, 1, 1, Qt.AlignLeft)
self.outputFontLayout = QtWidgets.QHBoxLayout() self.outputFontLayout = QtWidgets.QHBoxLayout()
self.outputFontLayout.setContentsMargins(0, 0, 0, 0) self.outputFontLayout.setContentsMargins(0, 0, 0, 0)
@ -1002,7 +1011,7 @@ class ConfigDialog(QtWidgets.QDialog):
self.chatOutputLayout.addWidget(self.chatOutputModeFrame) self.chatOutputLayout.addWidget(self.chatOutputModeFrame)
self.subitems['chatOutputEnabled'] = [self.chatOutputModeLabel.objectName(), self.chatOutputChatroomOption.objectName(), self.subitems['chatOutputEnabled'] = [self.chatOutputModeLabel.objectName(), self.chatOutputChatroomOption.objectName(),
self.chatOutputScrollingOption.objectName(),self.chatOutputFontButton.objectName(), self.chatOutputScrollingOption.objectName(), self.chatOutputFontButton.objectName(),
self.chatOutputFontLabel.objectName()] self.chatOutputFontLabel.objectName()]
# chatFrame # chatFrame
self.chatFrame.setLayout(self.chatLayout) self.chatFrame.setLayout(self.chatLayout)
@ -1010,7 +1019,7 @@ class ConfigDialog(QtWidgets.QDialog):
def fontDialog(self, configName): def fontDialog(self, configName):
font = QtGui.QFont() font = QtGui.QFont()
font.setFamily(self.config[configName+ "FontFamily"]) font.setFamily(self.config[configName + "FontFamily"])
font.setPointSize(self.config[configName + "RelativeFontSize"]) font.setPointSize(self.config[configName + "RelativeFontSize"])
font.setWeight(self.config[configName + "FontWeight"]) font.setWeight(self.config[configName + "FontWeight"])
font.setUnderline(self.config[configName + "FontUnderline"]) font.setUnderline(self.config[configName + "FontUnderline"])
@ -1023,7 +1032,7 @@ class ConfigDialog(QtWidgets.QDialog):
def colourDialog(self, configName): def colourDialog(self, configName):
oldColour = QtGui.QColor() oldColour = QtGui.QColor()
oldColour.setNamedColor(self.config[configName+ "FontColor"]) oldColour.setNamedColor(self.config[configName + "FontColor"])
colour = QtWidgets.QColorDialog.getColor(oldColour, self) colour = QtWidgets.QColorDialog.getColor(oldColour, self)
if colour.isValid(): if colour.isValid():
self.config[configName + "FontColor"] = colour.name() self.config[configName + "FontColor"] = colour.name()
@ -1145,11 +1154,11 @@ class ConfigDialog(QtWidgets.QDialog):
self.bottomButtonLayout.addWidget(self.runButton) self.bottomButtonLayout.addWidget(self.runButton)
self.bottomButtonLayout.addWidget(self.storeAndRunButton) self.bottomButtonLayout.addWidget(self.storeAndRunButton)
self.bottomButtonFrame.setLayout(self.bottomButtonLayout) self.bottomButtonFrame.setLayout(self.bottomButtonLayout)
self.bottomButtonLayout.setContentsMargins(5,0,5,0) self.bottomButtonLayout.setContentsMargins(5, 0, 5, 0)
self.mainLayout.addWidget(self.bottomButtonFrame, 1, 0, 1, 2) self.mainLayout.addWidget(self.bottomButtonFrame, 1, 0, 1, 2)
self.bottomCheckboxFrame = QtWidgets.QFrame() self.bottomCheckboxFrame = QtWidgets.QFrame()
self.bottomCheckboxFrame.setContentsMargins(0,0,0,0) self.bottomCheckboxFrame.setContentsMargins(0, 0, 0, 0)
self.bottomCheckboxLayout = QtWidgets.QGridLayout() self.bottomCheckboxLayout = QtWidgets.QGridLayout()
self.alwaysshowCheckbox = QCheckBox(getMessage("forceguiprompt-label")) self.alwaysshowCheckbox = QCheckBox(getMessage("forceguiprompt-label"))
@ -1166,12 +1175,12 @@ class ConfigDialog(QtWidgets.QDialog):
self.tabListLayout = QtWidgets.QHBoxLayout() self.tabListLayout = QtWidgets.QHBoxLayout()
self.tabListFrame = QtWidgets.QFrame() self.tabListFrame = QtWidgets.QFrame()
self.tabListWidget = QtWidgets.QListWidget() self.tabListWidget = QtWidgets.QListWidget()
self.tabListWidget.addItem(QtWidgets.QListWidgetItem(QtGui.QIcon(resourcespath + "house.png"),getMessage("basics-label"))) self.tabListWidget.addItem(QtWidgets.QListWidgetItem(QtGui.QIcon(resourcespath + "house.png"), getMessage("basics-label")))
self.tabListWidget.addItem(QtWidgets.QListWidgetItem(QtGui.QIcon(resourcespath + "control_pause_blue.png"),getMessage("readiness-label"))) self.tabListWidget.addItem(QtWidgets.QListWidgetItem(QtGui.QIcon(resourcespath + "control_pause_blue.png"), getMessage("readiness-label")))
self.tabListWidget.addItem(QtWidgets.QListWidgetItem(QtGui.QIcon(resourcespath + "film_link.png"),getMessage("sync-label"))) self.tabListWidget.addItem(QtWidgets.QListWidgetItem(QtGui.QIcon(resourcespath + "film_link.png"), getMessage("sync-label")))
self.tabListWidget.addItem(QtWidgets.QListWidgetItem(QtGui.QIcon(resourcespath + "user_comment.png"), getMessage("chat-label"))) self.tabListWidget.addItem(QtWidgets.QListWidgetItem(QtGui.QIcon(resourcespath + "user_comment.png"), getMessage("chat-label")))
self.tabListWidget.addItem(QtWidgets.QListWidgetItem(QtGui.QIcon(resourcespath + "error.png"),getMessage("messages-label"))) self.tabListWidget.addItem(QtWidgets.QListWidgetItem(QtGui.QIcon(resourcespath + "error.png"), getMessage("messages-label")))
self.tabListWidget.addItem(QtWidgets.QListWidgetItem(QtGui.QIcon(resourcespath + "cog.png"),getMessage("misc-label"))) self.tabListWidget.addItem(QtWidgets.QListWidgetItem(QtGui.QIcon(resourcespath + "cog.png"), getMessage("misc-label")))
self.tabListLayout.addWidget(self.tabListWidget) self.tabListLayout.addWidget(self.tabListWidget)
self.tabListFrame.setLayout(self.tabListLayout) self.tabListFrame.setLayout(self.tabListLayout)
self.tabListFrame.setFixedWidth(self.tabListFrame.minimumSizeHint().width() + constants.TAB_PADDING) self.tabListFrame.setFixedWidth(self.tabListFrame.minimumSizeHint().width() + constants.TAB_PADDING)
@ -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()
@ -1275,7 +1284,7 @@ class ConfigDialog(QtWidgets.QDialog):
resourcespath = utils.findWorkingDir() + "\\resources\\" resourcespath = utils.findWorkingDir() + "\\resources\\"
else: else:
resourcespath = utils.findWorkingDir() + "/resources/" resourcespath = utils.findWorkingDir() + "/resources/"
self.posixresourcespath = utils.findWorkingDir().replace("\\","/") + "/resources/" self.posixresourcespath = utils.findWorkingDir().replace("\\", "/") + "/resources/"
self.resourcespath = resourcespath self.resourcespath = resourcespath
super(ConfigDialog, self).__init__() super(ConfigDialog, self).__init__()
@ -1290,7 +1299,7 @@ class ConfigDialog(QtWidgets.QDialog):
self.mainLayout = QtWidgets.QGridLayout() self.mainLayout = QtWidgets.QGridLayout()
self.mainLayout.setSpacing(0) self.mainLayout.setSpacing(0)
self.mainLayout.setContentsMargins(0,0,0,0) self.mainLayout.setContentsMargins(0, 0, 0, 0)
self.storedPassword = self.config['password'] self.storedPassword = self.config['password']
self.addBasicTab() self.addBasicTab()
@ -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()
@ -1321,7 +1330,7 @@ class ConfigDialog(QtWidgets.QDialog):
self.mediabrowseButton.show() self.mediabrowseButton.show()
newHeight = self.connectionSettingsGroup.minimumSizeHint().height()+self.mediaplayerSettingsGroup.minimumSizeHint().height()+self.bottomButtonFrame.minimumSizeHint().height()+3 newHeight = self.connectionSettingsGroup.minimumSizeHint().height()+self.mediaplayerSettingsGroup.minimumSizeHint().height()+self.bottomButtonFrame.minimumSizeHint().height()+3
if self.error: if self.error:
newHeight +=self.errorLabel.height()+3 newHeight += self.errorLabel.height() + 3
self.stackedFrame.setFixedHeight(newHeight) self.stackedFrame.setFixedHeight(newHeight)
else: else:
self.showmoreCheckbox.setChecked(True) self.showmoreCheckbox.setChecked(True)

View File

@ -1,17 +1,20 @@
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()
else: else:
ui = ConsoleUI() ui = ConsoleUI()

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()
@ -71,7 +73,7 @@ class ConsoleUI(threading.Thread):
if user.file: if user.file:
message = getMessage("userlist-playing-notification").format(username) message = getMessage("userlist-playing-notification").format(username)
self.showMessage(message, True) self.showMessage(message, True)
message = " {}: '{}' ({})".format(getMessage("userlist-file-notification"),user.file['name'], formatTime(user.file['duration'])) message = " {}: '{}' ({})".format(getMessage("userlist-file-notification"), user.file['name'], formatTime(user.file['duration']))
if currentUser.file: if currentUser.file:
if user.file['name'] == currentUser.file['name'] and user.file['size'] != currentUser.file['size']: if user.file['name'] == currentUser.file['name'] and user.file['size'] != currentUser.file['size']:
message += getMessage("different-filesize-notification") message += getMessage("different-filesize-notification")
@ -103,7 +105,7 @@ class ConsoleUI(threading.Thread):
def showDebugMessage(self, message): def showDebugMessage(self, message):
print(message) print(message)
def showErrorMessage(self, message, criticalerror = False): def showErrorMessage(self, message, criticalerror=False):
print("ERROR:\t" + message) print("ERROR:\t" + message)
def _extractSign(self, m): def _extractSign(self, m):
@ -124,7 +126,7 @@ class ConsoleUI(threading.Thread):
if t is None: if t is None:
return return
if o.group('sign') == "/": if o.group('sign') == "/":
t = self._syncplayClient.getPlayerPosition() - t t = self._syncplayClient.getPlayerPosition() - t
elif sign: elif sign:
t = self._syncplayClient.getUserOffset() + sign * t t = self._syncplayClient.getUserOffset() + sign * t
self._syncplayClient.setUserOffset(t) self._syncplayClient.setUserOffset(t)
@ -151,14 +153,14 @@ class ConsoleUI(threading.Thread):
elif command.group('command') in constants.COMMANDS_LIST: elif command.group('command') in constants.COMMANDS_LIST:
self.getUserlist() self.getUserlist()
elif command.group('command') in constants.COMMANDS_CHAT: elif command.group('command') in constants.COMMANDS_CHAT:
message= command.group('parameter') message = command.group('parameter')
self._syncplayClient.sendChat(message) self._syncplayClient.sendChat(message)
elif command.group('command') in constants.COMMANDS_PAUSE: elif command.group('command') in constants.COMMANDS_PAUSE:
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:
room = self._syncplayClient.defaultRoom room = self._syncplayClient.defaultRoom
@ -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)
@ -62,19 +69,19 @@ class UserlistItemDelegate(QtWidgets.QStyledItemDelegate):
userReady = currentQAbstractItemModel.data(itemQModelIndex, Qt.UserRole + constants.USERITEM_READY_ROLE) userReady = currentQAbstractItemModel.data(itemQModelIndex, Qt.UserRole + constants.USERITEM_READY_ROLE)
if roomController and not controlIconQPixmap.isNull(): if roomController and not controlIconQPixmap.isNull():
itemQPainter.drawPixmap ( itemQPainter.drawPixmap(
optionQStyleOptionViewItem.rect.x()+6, optionQStyleOptionViewItem.rect.x()+6,
midY-8, midY-8,
controlIconQPixmap.scaled(16, 16, Qt.KeepAspectRatio)) controlIconQPixmap.scaled(16, 16, Qt.KeepAspectRatio))
if userReady and not tickIconQPixmap.isNull(): if userReady and not tickIconQPixmap.isNull():
itemQPainter.drawPixmap ( itemQPainter.drawPixmap(
(optionQStyleOptionViewItem.rect.x()-10), (optionQStyleOptionViewItem.rect.x()-10),
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,
crossIconQPixmap.scaled(16, 16, Qt.KeepAspectRatio)) crossIconQPixmap.scaled(16, 16, Qt.KeepAspectRatio))
@ -87,7 +94,7 @@ class UserlistItemDelegate(QtWidgets.QStyledItemDelegate):
fileSwitchRole = currentQAbstractItemModel.data(itemQModelIndex, Qt.UserRole + constants.FILEITEM_SWITCH_ROLE) fileSwitchRole = currentQAbstractItemModel.data(itemQModelIndex, Qt.UserRole + constants.FILEITEM_SWITCH_ROLE)
if fileSwitchRole == constants.FILEITEM_SWITCH_FILE_SWITCH: if fileSwitchRole == constants.FILEITEM_SWITCH_FILE_SWITCH:
fileSwitchIconQPixmap = QtGui.QPixmap(resourcespath + "film_go.png") fileSwitchIconQPixmap = QtGui.QPixmap(resourcespath + "film_go.png")
itemQPainter.drawPixmap ( itemQPainter.drawPixmap(
(optionQStyleOptionViewItem.rect.x()), (optionQStyleOptionViewItem.rect.x()),
midY - 8, midY - 8,
fileSwitchIconQPixmap.scaled(16, 16, Qt.KeepAspectRatio)) fileSwitchIconQPixmap.scaled(16, 16, Qt.KeepAspectRatio))
@ -95,64 +102,71 @@ class UserlistItemDelegate(QtWidgets.QStyledItemDelegate):
elif fileSwitchRole == constants.FILEITEM_SWITCH_STREAM_SWITCH: elif fileSwitchRole == constants.FILEITEM_SWITCH_STREAM_SWITCH:
streamSwitchIconQPixmap = QtGui.QPixmap(resourcespath + "world_go.png") streamSwitchIconQPixmap = QtGui.QPixmap(resourcespath + "world_go.png")
itemQPainter.drawPixmap ( itemQPainter.drawPixmap(
(optionQStyleOptionViewItem.rect.x()), (optionQStyleOptionViewItem.rect.x()),
midY - 8, midY - 8,
streamSwitchIconQPixmap.scaled(16, 16, Qt.KeepAspectRatio)) streamSwitchIconQPixmap.scaled(16, 16, Qt.KeepAspectRatio))
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)
if isMacOS(): if isMacOS():
self.setWindowTitle("") self.setWindowTitle("")
self.setWindowFlags(Qt.Dialog | Qt.WindowTitleHint | Qt.WindowCloseButtonHint | Qt.CustomizeWindowHint) self.setWindowFlags(Qt.Dialog | Qt.WindowTitleHint | Qt.WindowCloseButtonHint | Qt.CustomizeWindowHint)
else:
self.setWindowTitle(getMessage("about-dialog-title"))
if isWindows():
self.setWindowFlags(self.windowFlags() & ~Qt.WindowContextHelpButtonHint)
nameLabel = QtWidgets.QLabel("<center><strong>Syncplay</strong></center>")
nameLabel.setFont(QtGui.QFont("Helvetica", 18))
linkLabel = QtWidgets.QLabel("<center><a href=\"https://syncplay.pl\">syncplay.pl</a></center>")
linkLabel.setOpenExternalLinks(True)
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>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>")
aboutIconPixmap = QtGui.QPixmap(resourcespath + "syncplay.png")
aboutIconLabel = QtWidgets.QLabel()
aboutIconLabel.setPixmap(aboutIconPixmap.scaled(65, 65, Qt.KeepAspectRatio))
aboutLayout = QtWidgets.QGridLayout()
aboutLayout.addWidget(aboutIconLabel, 0, 0, 3, 4, Qt.AlignHCenter)
aboutLayout.addWidget(nameLabel, 3, 0, 1, 4)
aboutLayout.addWidget(linkLabel, 4, 0, 1, 4)
aboutLayout.addWidget(versionLabel, 5, 0, 1, 4)
aboutLayout.addWidget(licenseLabel, 6, 0, 1, 4)
licenseButton = QtWidgets.QPushButton(getMessage("about-dialog-license-button"))
licenseButton.setAutoDefault(False)
licenseButton.clicked.connect(self.openLicense)
aboutLayout.addWidget(licenseButton, 7, 0, 1, 2)
dependenciesButton = QtWidgets.QPushButton(getMessage("about-dialog-dependencies"))
dependenciesButton.setAutoDefault(False)
dependenciesButton.clicked.connect(self.openDependencies)
aboutLayout.addWidget(dependenciesButton, 7, 2, 1, 2)
aboutLayout.setVerticalSpacing(10)
aboutLayout.setSizeConstraint(QtWidgets.QLayout.SetFixedSize)
self.setSizeGripEnabled(False)
self.setLayout(aboutLayout)
def openLicense(self):
if isWindows():
QtGui.QDesktopServices.openUrl(QUrl("file:///" + resourcespath + "license.rtf"))
else: else:
QtGui.QDesktopServices.openUrl(QUrl("file://" + resourcespath + "license.rtf")) self.setWindowTitle(getMessage("about-dialog-title"))
if isWindows():
self.setWindowFlags(self.windowFlags() & ~Qt.WindowContextHelpButtonHint)
nameLabel = QtWidgets.QLabel("<center><strong>Syncplay</strong></center>")
nameLabel.setFont(QtGui.QFont("Helvetica", 18))
linkLabel = QtWidgets.QLabel("<center><a href=\"https://syncplay.pl\">syncplay.pl</a></center>")
linkLabel.setOpenExternalLinks(True)
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>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>")
aboutIconPixmap = QtGui.QPixmap(resourcespath + "syncplay.png")
aboutIconLabel = QtWidgets.QLabel()
aboutIconLabel.setPixmap(aboutIconPixmap.scaled(65, 65, Qt.KeepAspectRatio))
aboutLayout = QtWidgets.QGridLayout()
aboutLayout.addWidget(aboutIconLabel, 0, 0, 3, 4, Qt.AlignHCenter)
aboutLayout.addWidget(nameLabel, 3, 0, 1, 4)
aboutLayout.addWidget(linkLabel, 4, 0, 1, 4)
aboutLayout.addWidget(versionLabel, 5, 0, 1, 4)
aboutLayout.addWidget(licenseLabel, 6, 0, 1, 4)
licenseButton = QtWidgets.QPushButton(getMessage("about-dialog-license-button"))
licenseButton.setAutoDefault(False)
licenseButton.clicked.connect(self.openLicense)
aboutLayout.addWidget(licenseButton, 7, 0, 1, 2)
dependenciesButton = QtWidgets.QPushButton(getMessage("about-dialog-dependencies"))
dependenciesButton.setAutoDefault(False)
dependenciesButton.clicked.connect(self.openDependencies)
aboutLayout.addWidget(dependenciesButton, 7, 2, 1, 2)
aboutLayout.setVerticalSpacing(10)
aboutLayout.setSizeConstraint(QtWidgets.QLayout.SetFixedSize)
self.setSizeGripEnabled(False)
self.setLayout(aboutLayout)
def openLicense(self):
if isWindows():
QtGui.QDesktopServices.openUrl(QUrl("file:///" + resourcespath + "license.rtf"))
else:
QtGui.QDesktopServices.openUrl(QUrl("file://" + resourcespath + "license.rtf"))
def openDependencies(self):
if isWindows():
QtGui.QDesktopServices.openUrl(QUrl("file:///" + resourcespath + "third-party-notices.rtf"))
else:
QtGui.QDesktopServices.openUrl(QUrl("file://" + resourcespath + "third-party-notices.rtf"))
def openDependencies(self):
if isWindows():
QtGui.QDesktopServices.openUrl(QUrl("file:///" + resourcespath + "third-party-notices.rtf"))
else:
QtGui.QDesktopServices.openUrl(QUrl("file://" + resourcespath + "third-party-notices.rtf"))
class MainWindow(QtWidgets.QMainWindow): class MainWindow(QtWidgets.QMainWindow):
insertPosition = None insertPosition = None
@ -175,7 +189,7 @@ class MainWindow(QtWidgets.QMainWindow):
if currentlyPlayingFile: if currentlyPlayingFile:
currentlyplayingIconQPixmap = QtGui.QPixmap(resourcespath + "bullet_right_grey.png") currentlyplayingIconQPixmap = QtGui.QPixmap(resourcespath + "bullet_right_grey.png")
midY = int((optionQStyleOptionViewItem.rect.y() + optionQStyleOptionViewItem.rect.bottomLeft().y()) / 2) midY = int((optionQStyleOptionViewItem.rect.y() + optionQStyleOptionViewItem.rect.bottomLeft().y()) / 2)
itemQPainter.drawPixmap ( itemQPainter.drawPixmap(
(optionQStyleOptionViewItem.rect.x()+4), (optionQStyleOptionViewItem.rect.x()+4),
midY-8, midY-8,
currentlyplayingIconQPixmap.scaled(6, 16, Qt.KeepAspectRatio)) currentlyplayingIconQPixmap.scaled(6, 16, Qt.KeepAspectRatio))
@ -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)
@ -437,7 +449,7 @@ class MainWindow(QtWidgets.QMainWindow):
if filename: if filename:
if filename == getMessage("nofile-note"): if filename == getMessage("nofile-note"):
return constants.FILEITEM_SWITCH_NO_SWITCH return constants.FILEITEM_SWITCH_NO_SWITCH
if self._syncplayClient.userlist.currentUser.file and utils.sameFilename(filename,self._syncplayClient.userlist.currentUser.file['name']): if self._syncplayClient.userlist.currentUser.file and utils.sameFilename(filename, self._syncplayClient.userlist.currentUser.file['name']):
return constants.FILEITEM_SWITCH_NO_SWITCH return constants.FILEITEM_SWITCH_NO_SWITCH
if isURL(filename): if isURL(filename):
return constants.FILEITEM_SWITCH_STREAM_SWITCH return constants.FILEITEM_SWITCH_STREAM_SWITCH
@ -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:
@ -531,7 +550,7 @@ class MainWindow(QtWidgets.QMainWindow):
filenameitem.setFont(underlinefont) filenameitem.setFont(underlinefont)
if not sameSize: if not sameSize:
if formatSize(user.file['size']) == formatSize(currentUser.file['size']): if formatSize(user.file['size']) == formatSize(currentUser.file['size']):
filesizeitem = QtGui.QStandardItem(formatSize(user.file['size'],precise=True)) filesizeitem = QtGui.QStandardItem(formatSize(user.file['size'], precise=True))
filesizeitem.setFont(underlinefont) filesizeitem.setFont(underlinefont)
filesizeitem.setForeground(QtGui.QBrush(QtGui.QColor(constants.STYLE_DIFFERENTITEM_COLOR))) filesizeitem.setForeground(QtGui.QBrush(QtGui.QColor(constants.STYLE_DIFFERENTITEM_COLOR)))
if not sameDuration: if not sameDuration:
@ -590,30 +609,29 @@ class MainWindow(QtWidgets.QMainWindow):
pathFound = self._syncplayClient.fileSwitch.findFilepath(firstFile) if not isURL(firstFile) else None pathFound = self._syncplayClient.fileSwitch.findFilepath(firstFile) if not isURL(firstFile) else None
if self._syncplayClient.userlist.currentUser.file is None or firstFile != self._syncplayClient.userlist.currentUser.file["name"]: if self._syncplayClient.userlist.currentUser.file is None or firstFile != self._syncplayClient.userlist.currentUser.file["name"]:
if isURL(firstFile): if isURL(firstFile):
menu.addAction(QtGui.QPixmap(resourcespath + "world_go.png"), getMessage("openstreamurl-menu-label"), lambda: self.openFile(firstFile,resetPosition=True)) menu.addAction(QtGui.QPixmap(resourcespath + "world_go.png"), getMessage("openstreamurl-menu-label"), lambda: self.openFile(firstFile, resetPosition=True))
elif pathFound: elif pathFound:
menu.addAction(QtGui.QPixmap(resourcespath + "film_go.png"), getMessage("openmedia-menu-label"), lambda: self.openFile(pathFound,resetPosition=True)) menu.addAction(QtGui.QPixmap(resourcespath + "film_go.png"), getMessage("openmedia-menu-label"), lambda: self.openFile(pathFound, resetPosition=True))
if pathFound: if pathFound:
menu.addAction(QtGui.QPixmap(resourcespath + "folder_film.png"), menu.addAction(QtGui.QPixmap(resourcespath + "folder_film.png"),
getMessage('open-containing-folder'), getMessage('open-containing-folder'),
lambda: utils.open_system_file_browser(pathFound)) lambda: utils.open_system_file_browser(pathFound))
if self._syncplayClient.isUntrustedTrustableURI(firstFile): if self._syncplayClient.isUntrustedTrustableURI(firstFile):
domain = utils.getDomainFromURL(firstFile) domain = utils.getDomainFromURL(firstFile)
menu.addAction(QtGui.QPixmap(resourcespath + "shield_add.png"),getMessage("addtrusteddomain-menu-label").format(domain), lambda: self.addTrustedDomain(domain)) menu.addAction(QtGui.QPixmap(resourcespath + "shield_add.png"), getMessage("addtrusteddomain-menu-label").format(domain), lambda: self.addTrustedDomain(domain))
menu.addAction(QtGui.QPixmap(resourcespath + "delete.png"), getMessage("removefromplaylist-menu-label"), lambda: self.deleteSelectedPlaylistItems()) menu.addAction(QtGui.QPixmap(resourcespath + "delete.png"), getMessage("removefromplaylist-menu-label"), lambda: self.deleteSelectedPlaylistItems())
menu.addSeparator() menu.addSeparator()
menu.addAction(QtGui.QPixmap(resourcespath + "arrow_switch.png"), getMessage("shuffleremainingplaylist-menu-label"), lambda: self.shuffleRemainingPlaylist()) menu.addAction(QtGui.QPixmap(resourcespath + "arrow_switch.png"), getMessage("shuffleremainingplaylist-menu-label"), lambda: self.shuffleRemainingPlaylist())
menu.addAction(QtGui.QPixmap(resourcespath + "arrow_switch.png"), getMessage("shuffleentireplaylist-menu-label"), lambda: self.shuffleEntirePlaylist()) menu.addAction(QtGui.QPixmap(resourcespath + "arrow_switch.png"), getMessage("shuffleentireplaylist-menu-label"), lambda: self.shuffleEntirePlaylist())
menu.addAction(QtGui.QPixmap(resourcespath + "arrow_undo.png"), getMessage("undoplaylist-menu-label"), lambda: self.undoPlaylistChange()) menu.addAction(QtGui.QPixmap(resourcespath + "arrow_undo.png"), getMessage("undoplaylist-menu-label"), lambda: self.undoPlaylistChange())
menu.addAction(QtGui.QPixmap(resourcespath + "film_edit.png"), getMessage("editplaylist-menu-label"), lambda: self.openEditPlaylistDialog()) menu.addAction(QtGui.QPixmap(resourcespath + "film_edit.png"), getMessage("editplaylist-menu-label"), lambda: self.openEditPlaylistDialog())
menu.addAction(QtGui.QPixmap(resourcespath + "film_add.png"),getMessage("addfilestoplaylist-menu-label"), lambda: self.OpenAddFilesToPlaylistDialog()) menu.addAction(QtGui.QPixmap(resourcespath + "film_add.png"), getMessage("addfilestoplaylist-menu-label"), lambda: self.OpenAddFilesToPlaylistDialog())
menu.addAction(QtGui.QPixmap(resourcespath + "world_add.png"), getMessage("addurlstoplaylist-menu-label"), lambda: self.OpenAddURIsToPlaylistDialog()) menu.addAction(QtGui.QPixmap(resourcespath + "world_add.png"), getMessage("addurlstoplaylist-menu-label"), lambda: self.OpenAddURIsToPlaylistDialog())
menu.addSeparator() menu.addSeparator()
menu.addAction(QtGui.QPixmap(resourcespath + "film_folder_edit.png"), getMessage("setmediadirectories-menu-label"), lambda: self.openSetMediaDirectoriesDialog()) menu.addAction(QtGui.QPixmap(resourcespath + "film_folder_edit.png"), getMessage("setmediadirectories-menu-label"), lambda: self.openSetMediaDirectoriesDialog())
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()
@ -629,7 +647,7 @@ class MainWindow(QtWidgets.QMainWindow):
elif len(username) < 15: elif len(username) < 15:
shortUsername = getMessage("item-is-others-indicator").format(username) shortUsername = getMessage("item-is-others-indicator").format(username)
else: else:
shortUsername = "{}...".format(getMessage("item-is-others-indicator").format(username[0:12])) # TODO: Enforce username limits in client and server shortUsername = "{}...".format(getMessage("item-is-others-indicator").format(username[0:12])) # TODO: Enforce username limits in client and server
filename = item.sibling(item.row(), 3).data() filename = item.sibling(item.row(), 3).data()
while item.parent().row() != -1: while item.parent().row() != -1:
@ -640,7 +658,7 @@ class MainWindow(QtWidgets.QMainWindow):
elif username and filename and filename != getMessage("nofile-note"): elif username and filename and filename != getMessage("nofile-note"):
if self.config['sharedPlaylistEnabled'] and not self.isItemInPlaylist(filename): if self.config['sharedPlaylistEnabled'] and not self.isItemInPlaylist(filename):
if isURL(filename): if isURL(filename):
menu.addAction(QtGui.QPixmap(resourcespath + "world_add.png"),getMessage("addusersstreamstoplaylist-menu-label").format(shortUsername), lambda: self.addStreamToPlaylist(filename)) menu.addAction(QtGui.QPixmap(resourcespath + "world_add.png"), getMessage("addusersstreamstoplaylist-menu-label").format(shortUsername), lambda: self.addStreamToPlaylist(filename))
else: else:
menu.addAction(QtGui.QPixmap(resourcespath + "film_add.png"), getMessage("addusersfiletoplaylist-menu-label").format(shortUsername), lambda: self.addStreamToPlaylist(filename)) menu.addAction(QtGui.QPixmap(resourcespath + "film_add.png"), getMessage("addusersfiletoplaylist-menu-label").format(shortUsername), lambda: self.addStreamToPlaylist(filename))
@ -653,7 +671,7 @@ class MainWindow(QtWidgets.QMainWindow):
menu.addAction(QtGui.QPixmap(resourcespath + "film_go.png"), getMessage("openusersfile-menu-label").format(shortUsername), lambda: self.openFile(pathFound)) menu.addAction(QtGui.QPixmap(resourcespath + "film_go.png"), getMessage("openusersfile-menu-label").format(shortUsername), lambda: self.openFile(pathFound))
if self._syncplayClient.isUntrustedTrustableURI(filename): if self._syncplayClient.isUntrustedTrustableURI(filename):
domain = utils.getDomainFromURL(filename) domain = utils.getDomainFromURL(filename)
menu.addAction(QtGui.QPixmap(resourcespath + "shield_add.png"),getMessage("addtrusteddomain-menu-label").format(domain), lambda: self.addTrustedDomain(domain)) menu.addAction(QtGui.QPixmap(resourcespath + "shield_add.png"), getMessage("addtrusteddomain-menu-label").format(domain), lambda: self.addTrustedDomain(domain))
if not isURL(filename) and filename != getMessage("nofile-note"): if not isURL(filename) and filename != getMessage("nofile-note"):
path = self._syncplayClient.fileSwitch.findFilepath(filename) path = self._syncplayClient.fileSwitch.findFilepath(filename)
@ -682,7 +700,7 @@ class MainWindow(QtWidgets.QMainWindow):
self.listTreeView.header().setResizeMode(3, QtWidgets.QHeaderView.ResizeToContents) self.listTreeView.header().setResizeMode(3, QtWidgets.QHeaderView.ResizeToContents)
NarrowTabsWidth = self.listTreeView.header().sectionSize(0)+self.listTreeView.header().sectionSize(1)+self.listTreeView.header().sectionSize(2) NarrowTabsWidth = self.listTreeView.header().sectionSize(0)+self.listTreeView.header().sectionSize(1)+self.listTreeView.header().sectionSize(2)
if self.listTreeView.header().width() < (NarrowTabsWidth+self.listTreeView.header().sectionSize(3)): if self.listTreeView.header().width() < (NarrowTabsWidth+self.listTreeView.header().sectionSize(3)):
self.listTreeView.header().resizeSection(3,self.listTreeView.header().width()-NarrowTabsWidth) self.listTreeView.header().resizeSection(3, self.listTreeView.header().width()-NarrowTabsWidth)
else: else:
if IsPySide2: if IsPySide2:
self.listTreeView.header().setSectionResizeMode(3, QtWidgets.QHeaderView.Stretch) self.listTreeView.header().setSectionResizeMode(3, QtWidgets.QHeaderView.Stretch)
@ -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(
getMessage("seektime-msgbox-label"), QtWidgets.QLineEdit.Normal, self, getMessage("seektime-menu-label"),
"0:00") getMessage("seektime-msgbox-label"), QtWidgets.QLineEdit.Normal,
"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,8 +904,9 @@ 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(
browserfilter, "", options) self, getMessage("browseformedia-label"), defaultdirectory,
browserfilter, "", options)
if fileName: if fileName:
if isWindows(): if isWindows():
fileName = fileName.replace("/", "\\") fileName = fileName.replace("/", "\\")
@ -899,15 +917,15 @@ 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
self.loadMediaBrowseSettings() self.loadMediaBrowseSettings()
if isMacOS() and IsPySide: if isMacOS() and IsPySide:
options = QtWidgets.QFileDialog.Options(QtWidgets.QFileDialog.DontUseNativeDialog) options = QtWidgets.QFileDialog.Options(QtWidgets.QFileDialog.DontUseNativeDialog)
else: else:
options = QtWidgets.QFileDialog.Options() options = QtWidgets.QFileDialog.Options()
self.mediadirectory = "" self.mediadirectory = ""
currentdirectory = os.path.dirname(self._syncplayClient.userlist.currentUser.file["path"]) if self._syncplayClient.userlist.currentUser.file else None currentdirectory = os.path.dirname(self._syncplayClient.userlist.currentUser.file["path"]) if self._syncplayClient.userlist.currentUser.file else None
if currentdirectory and os.path.isdir(currentdirectory): if currentdirectory and os.path.isdir(currentdirectory):
@ -915,8 +933,9 @@ 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(
browserfilter, "", options) self, getMessage("browseformedia-label"), defaultdirectory,
browserfilter, "", options)
self.updatingPlaylist = True self.updatingPlaylist = True
if fileNames: if fileNames:
for fileName in fileNames: for fileName in fileNames:
@ -941,7 +960,7 @@ class MainWindow(QtWidgets.QMainWindow):
URIsLayout.addWidget(URIsTextbox, 1, 0, 1, 1) URIsLayout.addWidget(URIsTextbox, 1, 0, 1, 1)
URIsButtonBox = QtWidgets.QDialogButtonBox() URIsButtonBox = QtWidgets.QDialogButtonBox()
URIsButtonBox.setOrientation(Qt.Horizontal) URIsButtonBox.setOrientation(Qt.Horizontal)
URIsButtonBox.setStandardButtons(QtWidgets.QDialogButtonBox.Ok|QtWidgets.QDialogButtonBox.Cancel) URIsButtonBox.setStandardButtons(QtWidgets.QDialogButtonBox.Ok | QtWidgets.QDialogButtonBox.Cancel)
URIsButtonBox.accepted.connect(URIsDialog.accept) URIsButtonBox.accepted.connect(URIsDialog.accept)
URIsButtonBox.rejected.connect(URIsDialog.reject) URIsButtonBox.rejected.connect(URIsDialog.reject)
URIsLayout.addWidget(URIsButtonBox, 2, 0, 1, 1) URIsLayout.addWidget(URIsButtonBox, 2, 0, 1, 1)
@ -977,7 +996,7 @@ class MainWindow(QtWidgets.QMainWindow):
editPlaylistLayout.addWidget(editPlaylistTextbox, 1, 0, 1, 1) editPlaylistLayout.addWidget(editPlaylistTextbox, 1, 0, 1, 1)
editPlaylistButtonBox = QtWidgets.QDialogButtonBox() editPlaylistButtonBox = QtWidgets.QDialogButtonBox()
editPlaylistButtonBox.setOrientation(Qt.Horizontal) editPlaylistButtonBox.setOrientation(Qt.Horizontal)
editPlaylistButtonBox.setStandardButtons(QtWidgets.QDialogButtonBox.Ok|QtWidgets.QDialogButtonBox.Cancel) editPlaylistButtonBox.setStandardButtons(QtWidgets.QDialogButtonBox.Ok | QtWidgets.QDialogButtonBox.Cancel)
editPlaylistButtonBox.accepted.connect(editPlaylistDialog.accept) editPlaylistButtonBox.accepted.connect(editPlaylistDialog.accept)
editPlaylistButtonBox.rejected.connect(editPlaylistDialog.reject) editPlaylistButtonBox.rejected.connect(editPlaylistDialog.reject)
editPlaylistLayout.addWidget(editPlaylistButtonBox, 2, 0, 1, 1) editPlaylistLayout.addWidget(editPlaylistButtonBox, 2, 0, 1, 1)
@ -997,7 +1016,7 @@ class MainWindow(QtWidgets.QMainWindow):
@needsClient @needsClient
def openSetMediaDirectoriesDialog(self): def openSetMediaDirectoriesDialog(self):
MediaDirectoriesDialog = QtWidgets.QDialog() MediaDirectoriesDialog = QtWidgets.QDialog()
MediaDirectoriesDialog.setWindowTitle(getMessage("syncplay-mediasearchdirectories-title")) # TODO: Move to messages_*.py MediaDirectoriesDialog.setWindowTitle(getMessage("syncplay-mediasearchdirectories-title")) # TODO: Move to messages_*.py
MediaDirectoriesLayout = QtWidgets.QGridLayout() MediaDirectoriesLayout = QtWidgets.QGridLayout()
MediaDirectoriesLabel = QtWidgets.QLabel(getMessage("syncplay-mediasearchdirectories-label")) MediaDirectoriesLabel = QtWidgets.QLabel(getMessage("syncplay-mediasearchdirectories-label"))
MediaDirectoriesLayout.addWidget(MediaDirectoriesLabel, 0, 0, 1, 2) MediaDirectoriesLayout.addWidget(MediaDirectoriesLabel, 0, 0, 1, 2)
@ -1007,7 +1026,7 @@ class MainWindow(QtWidgets.QMainWindow):
MediaDirectoriesLayout.addWidget(MediaDirectoriesTextbox, 1, 0, 1, 1) MediaDirectoriesLayout.addWidget(MediaDirectoriesTextbox, 1, 0, 1, 1)
MediaDirectoriesButtonBox = QtWidgets.QDialogButtonBox() MediaDirectoriesButtonBox = QtWidgets.QDialogButtonBox()
MediaDirectoriesButtonBox.setOrientation(Qt.Horizontal) MediaDirectoriesButtonBox.setOrientation(Qt.Horizontal)
MediaDirectoriesButtonBox.setStandardButtons(QtWidgets.QDialogButtonBox.Ok|QtWidgets.QDialogButtonBox.Cancel) MediaDirectoriesButtonBox.setStandardButtons(QtWidgets.QDialogButtonBox.Ok | QtWidgets.QDialogButtonBox.Cancel)
MediaDirectoriesButtonBox.accepted.connect(MediaDirectoriesDialog.accept) MediaDirectoriesButtonBox.accepted.connect(MediaDirectoriesDialog.accept)
MediaDirectoriesButtonBox.rejected.connect(MediaDirectoriesDialog.reject) MediaDirectoriesButtonBox.rejected.connect(MediaDirectoriesDialog.reject)
MediaDirectoriesLayout.addWidget(MediaDirectoriesButtonBox, 2, 0, 1, 1) MediaDirectoriesLayout.addWidget(MediaDirectoriesButtonBox, 2, 0, 1, 1)
@ -1035,7 +1054,7 @@ class MainWindow(QtWidgets.QMainWindow):
TrustedDomainsLayout.addWidget(TrustedDomainsTextbox, 1, 0, 1, 1) TrustedDomainsLayout.addWidget(TrustedDomainsTextbox, 1, 0, 1, 1)
TrustedDomainsButtonBox = QtWidgets.QDialogButtonBox() TrustedDomainsButtonBox = QtWidgets.QDialogButtonBox()
TrustedDomainsButtonBox.setOrientation(Qt.Horizontal) TrustedDomainsButtonBox.setOrientation(Qt.Horizontal)
TrustedDomainsButtonBox.setStandardButtons(QtWidgets.QDialogButtonBox.Ok|QtWidgets.QDialogButtonBox.Cancel) TrustedDomainsButtonBox.setStandardButtons(QtWidgets.QDialogButtonBox.Ok | QtWidgets.QDialogButtonBox.Cancel)
TrustedDomainsButtonBox.accepted.connect(TrustedDomainsDialog.accept) TrustedDomainsButtonBox.accepted.connect(TrustedDomainsDialog.accept)
TrustedDomainsButtonBox.rejected.connect(TrustedDomainsDialog.reject) TrustedDomainsButtonBox.rejected.connect(TrustedDomainsDialog.reject)
TrustedDomainsLayout.addWidget(TrustedDomainsButtonBox, 2, 0, 1, 1) TrustedDomainsLayout.addWidget(TrustedDomainsButtonBox, 2, 0, 1, 1)
@ -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,17 +1094,18 @@ 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(
getMessage("controlledroominfo-msgbox-label"), QtWidgets.QLineEdit.Normal, self, getMessage("createcontrolledroom-msgbox-label"),
utils.stripRoomName(self._syncplayClient.getRoom())) getMessage("controlledroominfo-msgbox-label"), QtWidgets.QLineEdit.Normal,
utils.stripRoomName(self._syncplayClient.getRoom()))
if ok and controlroom != '': if ok and controlroom != '':
self._syncplayClient.createControlledRoom(controlroom) self._syncplayClient.createControlledRoom(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,15 +1209,16 @@ 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(
getMessage("sendmessage-label")) QtGui.QPixmap(resourcespath + 'email_go.png'),
getMessage("sendmessage-label"))
window.chatButton.pressed.connect(self.sendChatMessage) window.chatButton.pressed.connect(self.sendChatMessage)
window.chatLayout = QtWidgets.QHBoxLayout() window.chatLayout = QtWidgets.QHBoxLayout()
window.chatFrame = QtWidgets.QFrame() window.chatFrame = QtWidgets.QFrame()
window.chatFrame.setLayout(self.chatLayout) window.chatFrame.setLayout(self.chatLayout)
window.chatFrame.setContentsMargins(0,0,0,0) window.chatFrame.setContentsMargins(0, 0, 0, 0)
window.chatFrame.setSizePolicy(QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Minimum) window.chatFrame.setSizePolicy(QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Minimum)
window.chatLayout.setContentsMargins(0,0,0,0) window.chatLayout.setContentsMargins(0, 0, 0, 0)
self.chatButton.setToolTip(getMessage("sendmessage-tooltip")) self.chatButton.setToolTip(getMessage("sendmessage-tooltip"))
window.chatLayout.addWidget(window.chatInput) window.chatLayout.addWidget(window.chatInput)
window.chatLayout.addWidget(window.chatButton) window.chatLayout.addWidget(window.chatButton)
@ -1242,15 +1265,16 @@ 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(
getMessage("joinroom-label")) QtGui.QPixmap(resourcespath + 'door_in.png'),
getMessage("joinroom-label"))
window.roomButton.pressed.connect(self.joinRoom) window.roomButton.pressed.connect(self.joinRoom)
window.roomLayout = QtWidgets.QHBoxLayout() window.roomLayout = QtWidgets.QHBoxLayout()
window.roomFrame = QtWidgets.QFrame() window.roomFrame = QtWidgets.QFrame()
window.roomFrame.setLayout(self.roomLayout) window.roomFrame.setLayout(self.roomLayout)
window.roomFrame.setContentsMargins(0,0,0,0) window.roomFrame.setContentsMargins(0, 0, 0, 0)
window.roomFrame.setSizePolicy(QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Minimum) window.roomFrame.setSizePolicy(QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Minimum)
window.roomLayout.setContentsMargins(0,0,0,0) window.roomLayout.setContentsMargins(0, 0, 0, 0)
self.roomButton.setToolTip(getMessage("joinroom-tooltip")) self.roomButton.setToolTip(getMessage("joinroom-tooltip"))
window.roomLayout.addWidget(window.roomInput) window.roomLayout.addWidget(window.roomInput)
window.roomLayout.addWidget(window.roomButton) window.roomLayout.addWidget(window.roomButton)
@ -1261,8 +1285,8 @@ class MainWindow(QtWidgets.QMainWindow):
window.topSplit.addWidget(window.outputFrame) window.topSplit.addWidget(window.outputFrame)
window.topSplit.addWidget(window.listFrame) window.topSplit.addWidget(window.listFrame)
window.topSplit.setStretchFactor(0,4) window.topSplit.setStretchFactor(0, 4)
window.topSplit.setStretchFactor(1,5) window.topSplit.setStretchFactor(1, 5)
window.mainLayout.addWidget(window.topSplit) window.mainLayout.addWidget(window.topSplit)
window.topSplit.setSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Expanding) window.topSplit.setSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Expanding)
@ -1270,7 +1294,7 @@ class MainWindow(QtWidgets.QMainWindow):
window.bottomLayout = QtWidgets.QHBoxLayout() window.bottomLayout = QtWidgets.QHBoxLayout()
window.bottomFrame = QtWidgets.QFrame() window.bottomFrame = QtWidgets.QFrame()
window.bottomFrame.setLayout(window.bottomLayout) window.bottomFrame.setLayout(window.bottomLayout)
window.bottomLayout.setContentsMargins(0,0,0,0) window.bottomLayout.setContentsMargins(0, 0, 0, 0)
self.addPlaybackLayout(window) self.addPlaybackLayout(window)
@ -1322,7 +1346,7 @@ class MainWindow(QtWidgets.QMainWindow):
window.autoplayLayout = QtWidgets.QHBoxLayout() window.autoplayLayout = QtWidgets.QHBoxLayout()
window.autoplayFrame = QtWidgets.QFrame() window.autoplayFrame = QtWidgets.QFrame()
window.autoplayFrame.setVisible(False) window.autoplayFrame.setVisible(False)
window.autoplayLayout.setContentsMargins(0,0,0,0) window.autoplayLayout.setContentsMargins(0, 0, 0, 0)
window.autoplayFrame.setLayout(window.autoplayLayout) window.autoplayFrame.setLayout(window.autoplayLayout)
window.autoplayPushButton = QtWidgets.QPushButton() window.autoplayPushButton = QtWidgets.QPushButton()
autoPlayFont = QtGui.QFont() autoPlayFont = QtGui.QFont()
@ -1357,10 +1381,10 @@ class MainWindow(QtWidgets.QMainWindow):
def addPlaybackLayout(self, window): def addPlaybackLayout(self, window):
window.playbackFrame = QtWidgets.QFrame() window.playbackFrame = QtWidgets.QFrame()
window.playbackFrame.setVisible(False) window.playbackFrame.setVisible(False)
window.playbackFrame.setContentsMargins(0,0,0,0) window.playbackFrame.setContentsMargins(0, 0, 0, 0)
window.playbackLayout = QtWidgets.QHBoxLayout() window.playbackLayout = QtWidgets.QHBoxLayout()
window.playbackLayout.setAlignment(Qt.AlignLeft) window.playbackLayout.setAlignment(Qt.AlignLeft)
window.playbackLayout.setContentsMargins(0,0,0,0) window.playbackLayout.setContentsMargins(0, 0, 0, 0)
window.playbackFrame.setLayout(window.playbackLayout) window.playbackFrame.setLayout(window.playbackLayout)
window.seekInput = QtWidgets.QLineEdit() window.seekInput = QtWidgets.QLineEdit()
window.seekInput.returnPressed.connect(self.seekFromButton) window.seekInput.returnPressed.connect(self.seekFromButton)
@ -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,11 +1459,13 @@ 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(
getMessage("setoffset-menu-label")) QtGui.QPixmap(resourcespath + 'timeline_marker.png'),
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(
getMessage("settrusteddomains-menu-label")) QtGui.QPixmap(resourcespath + 'shield_edit.png'),
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(
QtGui.QPixmap(resourcespath + 'page_white_key.png'), getMessage("createcontrolledroom-menu-label")) QtGui.QPixmap(resourcespath + 'page_white_key.png'), getMessage("createcontrolledroom-menu-label"))
@ -1456,22 +1489,24 @@ 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(
getMessage("userguide-menu-label")) QtGui.QPixmap(resourcespath + 'help.png'),
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(
getMessage("about-menu-label")) QtGui.QPixmap(resourcespath + 'syncplay.png'),
getMessage("about-menu-label"))
else: else:
window.about = window.helpMenu.addAction("&About") window.about = window.helpMenu.addAction("&About")
window.about.triggered.connect(self.openAbout) window.about.triggered.connect(self.openAbout)
@ -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)
@ -1564,7 +1599,7 @@ class MainWindow(QtWidgets.QMainWindow):
if self.config['lastCheckedForUpdates']: if self.config['lastCheckedForUpdates']:
configLastChecked = datetime.strptime(self.config["lastCheckedForUpdates"], "%Y-%m-%d %H:%M:%S.%f") configLastChecked = datetime.strptime(self.config["lastCheckedForUpdates"], "%Y-%m-%d %H:%M:%S.%f")
if self.lastCheckedForUpdates is None or configLastChecked > self.lastCheckedForUpdates.toPython(): if self.lastCheckedForUpdates is None or configLastChecked > self.lastCheckedForUpdates.toPython():
self.lastCheckedForUpdates = QDateTime.fromString(self.config["lastCheckedForUpdates"],'yyyy-MM-dd HH-mm-ss') self.lastCheckedForUpdates = QDateTime.fromString(self.config["lastCheckedForUpdates"], 'yyyy-MM-dd HH-mm-ss')
if self.lastCheckedForUpdates is None: if self.lastCheckedForUpdates is None:
self.checkForUpdates() self.checkForUpdates()
else: else:
@ -1591,11 +1626,12 @@ 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(
updateMessage, QtWidgets.QMessageBox.StandardButton.Yes | QtWidgets.QMessageBox.StandardButton.No) self, "Syncplay",
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))
elif userInitiated: elif userInitiated:
@ -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)
@ -1652,7 +1688,7 @@ class MainWindow(QtWidgets.QMainWindow):
def setPlaylistIndexFilename(self, filename): def setPlaylistIndexFilename(self, filename):
self.playlist.setPlaylistIndexFilename(filename) self.playlist.setPlaylistIndexFilename(filename)
def addFileToPlaylist(self, filePath, index = -1): def addFileToPlaylist(self, filePath, index=-1):
if os.path.isfile(filePath): if os.path.isfile(filePath):
self.removePlaylistNote() self.removePlaylistNote()
filename = os.path.basename(filePath) filename = os.path.basename(filePath)
@ -1698,7 +1734,7 @@ class MainWindow(QtWidgets.QMainWindow):
self.clearedPlaylistNote = True self.clearedPlaylistNote = True
def addFolderToPlaylist(self, folderPath): def addFolderToPlaylist(self, folderPath):
self.showErrorMessage("You tried to add the folder '{}' to the playlist. Syncplay only currently supports adding files to the playlist.".format(folderPath)) # TODO: Implement "add folder to playlist" self.showErrorMessage("You tried to add the folder '{}' to the playlist. Syncplay only currently supports adding files to the playlist.".format(folderPath)) # TODO: Implement "add folder to playlist"
def deleteSelectedPlaylistItems(self): def deleteSelectedPlaylistItems(self):
self.playlist.remove_selected_items() self.playlist.remove_selected_items()

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

View File

@ -350,7 +350,7 @@ class QtEventReactor(QtReactor):
elif val == WAIT_TIMEOUT: elif val == WAIT_TIMEOUT:
pass pass
else: else:
#print 'Got an unexpected return of %r' % val # print 'Got an unexpected return of %r' % val
return return
def _runAction(self, action, fd): def _runAction(self, action, fd):