class ExchangeView(QGroupBox): '''The box containing the rate value''' def __init__(self, title = 'Peak Exchange Matrix', parent = None): '''Initialize''' super(ExchangeView, self).__init__(parent) self.setTitle(title) self._createWidgets() def _createWidgets(self): '''Create the widgets contained in this box''' # Peak number chooser self.numpeaks = [QRadioButton("2"), QRadioButton("3"), QRadioButton("4")] self.numpeaks[0].setToolTip(ttt('Model the exchange of 2 peaks')) self.numpeaks[1].setToolTip(ttt('Model the exchange of 3 peaks')) self.numpeaks[2].setToolTip(ttt('Model the exchange of 4 peaks')) # Make 4x4 matrix of QLabels self.exview = [[QLabel(self) for i in xrange(4)] for j in xrange(4)] for i in xrange(4): for e in self.exview[i]: e.setToolTip(ttt('The current exchange matrix')) # Enforce symmetry button self.symmetry = QCheckBox("Enforce Symmetry", self) self.symmetry.setToolTip(ttt('If symmetry is on then you only need to ' 'manually set the upper triangle of the ' 'exchange matrix. Thse values are ' 'mirrored ' 'in the lower triangle and the diagonals ' 'are automatically set so that each row ' 'sums to 1. ' 'Otherwise you must set every element')) # Exchange picker self.exchooser = QComboBox(self) self.exchooser.setToolTip(ttt('Choose between which two peaks to set ' 'the exchange (relative) rate')) # Exchange value self.exvalue = QLineEdit(self) self.exvalue.setToolTip(ttt('The exchange (relative) rate')) self.exvalue.setValidator(QDoubleValidator(0.0, 1.0, 3, self.exvalue)) def makeConnections(self): '''Connect the widgets together''' # When the table has been resized, tidy it up self.matrix.matrixChanged.connect(self.resetMatrix) # If the check state changed, change the data model self.symmetry.stateChanged.connect(self.changeDataModel) self.numpeaks[0].clicked.connect(self.changeDataModel) self.numpeaks[1].clicked.connect(self.changeDataModel) self.numpeaks[2].clicked.connect(self.changeDataModel) # Attach the chooser to an exchange rate self.exchooser.currentIndexChanged.connect(self.attachExchange) # If the exchange rate is changed, update the matrix self.exvalue.editingFinished.connect(self.newExchange) def initUI(self): '''Lays out the widgets''' nums = QHBoxLayout() nums.addWidget(QLabel("Number of Peaks: ")) nums.addWidget(self.numpeaks[0]) nums.addWidget(self.numpeaks[1]) nums.addWidget(self.numpeaks[2]) val = QHBoxLayout() val.addWidget(QLabel("Exchange: ")) val.addStretch() val.addWidget(self.exchooser) self.exvalue.setMaximumWidth(50) val.addWidget(self.exvalue) ex = QGridLayout() for i in xrange(4): for j in xrange(4): ex.addWidget(self.exview[i][j], i+1, j+1) lo = QVBoxLayout() lo.addLayout(nums) lo.addWidget(self.symmetry) lo.addLayout(val) lo.addLayout(ex) self.setLayout(lo) def setModel(self, model, npmodel): '''Attaches models to the views.''' self.matrix = model self.npmodel = npmodel def setNumPeaks(self, npeaks): '''Manually set the number of peaks''' if npeaks == 2: self.numpeaks[0].click() elif npeaks == 3: self.numpeaks[1].click() elif npeaks == 4: self.numpeaks[2].click() else: error.showMessage('Only valid number of peaks is 2, 3, or 4') def setMatrixSymmetry(self, sym): '''Manually set the matrix symmetry''' self.symmetry.setChecked(sym) def setMatrix(self, Z): '''Manually set the matrix elements with a numpy matrix''' npeaks = self.npmodel.getNumPeaks() self.matrix.matrix = Z[0:npeaks,0:npeaks] self.matrix.updateInternalModel(npeaks) self.resetMatrix() ####### # SLOTS ####### def newExchange(self): '''Prepares an exchange value to be broadcasted''' try: value = round(float(self.exvalue.text()), 3) except ValueError: value = 0.0 indx = self.exchooser.currentIndex() if self.numpeaks[0].isChecked(): npeaks = 2 elif self.numpeaks[1].isChecked(): npeaks = 3 elif self.numpeaks[2].isChecked(): npeaks = 4 self.matrix.updateExchange(value, indx, npeaks) def resetMatrix(self): '''Reset the matrix values''' # Iterate over the matrix and fill the values for index, num in ndenumerate(self.matrix.matrix): self.exview[index[0]][index[1]].setText('{0:.3f}'.format(num)) # Set all other values to two dashes if len(self.matrix.matrix) == 2: for i in xrange(4): for j in xrange(4): if not (i < 2 and j < 2): self.exview[i][j].setText('--') elif len(self.matrix.matrix) == 3: for i in xrange(4): for j in xrange(4): if not (i < 3 and j < 3): self.exview[i][j].setText('--') def changeDataModel(self): '''Change the matrix from symmetric to not or vice versa''' # Change the model for the combo box if self.numpeaks[0].isChecked(): npeaks = 2 elif self.numpeaks[1].isChecked(): npeaks = 3 elif self.numpeaks[2].isChecked(): npeaks = 4 self.npmodel.setNumPeaks(npeaks) self.matrix.sym = self.symmetry.isChecked() if self.matrix.sym: self.exchooser.setModel(self.matrix.symex[npeaks]) else: self.exchooser.setModel(self.matrix.unsymex[npeaks]) # Reset the matrix self.matrix.setMatrix(npeaks) def attachExchange(self, indx): '''Attach a new exchange rate to the chooser''' r = self.matrix.symrate if self.matrix.sym else self.matrix.unsymrate self.exvalue.setText('{0:.3f}'.format(r[self.npmodel.numPeaks][indx]))
class UsbResetter(QWidget): def __init__(self): super(UsbResetter, self).__init__() self.P = UR_thread() self.thr_counter = 0 self.Looping = None self.Hidden = None self.Fhidden = None self.s_error = "QStatusBar{color:red;font-weight:1000;}" self.s_loop = "QStatusBar{color:black;font-weight:1000;}" self.s_norm = "QStatusBar{color:blue;font-style:italic;" self.s_norm += "font-weight:500;}" favicon = r_path("images/favicon.png") logo = r_path("images/logo.png") if name == 'nt': favicon = r_path("images\\favicon.png") logo = r_path("images\\logo.png") self.favicon = QIcon(favicon) self.plogo = logo self.logo = QIcon(logo) self.setStyle() mlayout = QVBoxLayout() self.setAbout(mlayout) self.setUlist(mlayout) self.setCboxs(mlayout) self.setReset(mlayout) self.setLoop(mlayout) self.setSb(mlayout) # functionalities self.set_list() self.rootWarn() # initiation self.activateWindow() self.setLayout(mlayout) self.show() def setSb(self, m): self.statusbar = QStatusBar() m.addWidget(self.statusbar) def setStyle(self): self.setMaximumWidth(350) self.setMinimumWidth(350) self.setMaximumHeight(340) self.setMinimumHeight(340) self.setWindowTitle("usb-resetter 1.0") self.setWindowIcon(self.favicon) self.show() def setAbout(self, m): self.pushButton = QPushButton() self.icon1 = QIcon() self.icon1.addPixmap(QPixmap(self.plogo), QIcon.Normal, QIcon.Off) self.pushButton.setIcon(self.icon1) self.pushButton.setIconSize(QSize(300, 100)) self.pushButton.clicked.connect(self.show_about) m.addWidget(self.pushButton) def setUlist(self, m): self.comboBox = QComboBox() m.addWidget(self.comboBox) def setCboxs(self, m): ml = QVBoxLayout() fl = QHBoxLayout() self.checkBox_2 = QCheckBox("Audio") self.checkBox_3 = QCheckBox("Mass storage") self.checkBox_2.setToolTip("Filter by audio devices") self.checkBox_3.setToolTip("Filter by mass storage devices") fl.addWidget(self.checkBox_2) fl.addWidget(self.checkBox_3) ml.addLayout(fl) sl = QHBoxLayout() self.checkBox_4 = QCheckBox("Network") self.checkBox_4.setToolTip("Filter by network devices") self.checkBox_5 = QCheckBox("Human interface") self.checkBox_5.setToolTip("Filter by Keyboard, mouse, joystick ..etc") sl.addWidget(self.checkBox_4) sl.addWidget(self.checkBox_5) ml.addLayout(sl) self.checkBox_2.clicked.connect(self.set_list) self.checkBox_3.clicked.connect(self.set_list) self.checkBox_4.clicked.connect(self.set_list) self.checkBox_5.clicked.connect(self.set_list) m.addLayout(ml) def setReset(self, m): self.pushButton_2 = QPushButton("Reset it") font = QFont() font.setPointSize(17) font.setWeight(75) font.setBold(True) self.pushButton_2.setFont(font) self.pushButton_2.clicked.connect(self.setbut_reset) m.addWidget(self.pushButton_2) def setLoop(self, m): ml = QHBoxLayout() self.checkBox = QCheckBox("Looping") self.checkBox.setToolTip("To repeat resetting for specified duration") self.lineEdit = QLineEdit() self.lineEdit.setToolTip("Duration in-which the resetting is done") self.pushButton_3 = QPushButton("Stop") self.pushButton_3.setToolTip("Stop looping") ml.addWidget(self.checkBox) ml.addWidget(self.lineEdit) ml.addWidget(self.pushButton_3) self.pushButton_3.setEnabled(False) self.lineEdit.setEnabled(False) self.lineEdit.setPlaceholderText("duration in seconds") self.checkBox.clicked.connect(self.loop_status) self.pushButton_3.clicked.connect(self.in_loop) m.addLayout(ml) # Functionalities def show_about(self): Amsg = "<center>All credit reserved to the author of " Amsg += "usb-resetter version 1.0" Amsg += ", This work is a free, open-source project licensed " Amsg += " under Mozilla Public License version 2.0 . <br><br>" Amsg += " visit us for more infos and how-tos :<br> " Amsg += "<b><a href='https://usb-resetter.github.io/'> " Amsg += "https://usb-resetter.github.io/ </a> </b></center>" Amsgb = "About usb-resetter" v = QMessageBox.about(self, Amsgb, Amsg) v = str(v) return v def closeEvent(self, event=None): if self.Hidden is None: response = QMessageBox.question( self, "Hide or close", "Do you want to hide the application ?", QMessageBox.Yes, QMessageBox.No) if response == QMessageBox.Yes: if event is not None: event.ignore() self.Hidden = True self.hide() elif response == QMessageBox.No: if event is not None: event.accept() return self.exitEvent() else: return False else: return self.exitEvent() def exitEvent(self): if self.P.isRunning(): response = QMessageBox.question( self, "Making sure", "Sure, you want to exit while looping ?", QMessageBox.Yes, QMessageBox.No) if response == QMessageBox.Yes: self.P.stop() exit(0) else: return False else: exit(0) def get_list(self): ol = [] if self.checkBox_2.isChecked(): ol.append(1) if self.checkBox_3.isChecked(): ol.append(8) if self.checkBox_4.isChecked(): ol.append(2) if self.checkBox_5.isChecked(): ol.append(3) if len(ol) >= 1: return listd(ol, True) else: return listd(None, True) def set_list(self): self.comboBox.clear() its = self.get_list() if len(its) >= 1: self.comboBox.addItems(its) self.pushButton_2.setEnabled(True) self.checkBox.setEnabled(True) else: self.pushButton_2.setEnabled(False) self.checkBox.setEnabled(False) self.lineEdit.setEnabled(False) self.pushButton_3.setEnabled(False) def setbut_reset(self): t = self.comboBox.currentText() if self.Looping is None: if resetit(t): self.statusbar.setStyleSheet(self.s_norm) self.statusbar.showMessage( "# Done: usb device got reset") return True self.statusbar.setStyleSheet(self.s_error) if name != 'nt': self.statusbar.showMessage( "# Error: maybe you need sudo permissions") else: self.statusbar.showMessage( "# Error: maybe you need to add device to libusb") return False else: tl = self.lineEdit.text() self.statusbar.setStyleSheet(self.s_error) if len(tl) == 0: self.statusbar.showMessage( "# Error: you must enter duration for looping") return False try: self.thr_counter += 1 tl = int(tl) if tl < 2: self.statusbar.showMessage( "# Error: the least allowed value is 2") return False self.P = UR_thread(t, tl, self.thr_counter) self.P.start() self.P.somesignal.connect(self.handleStatusMessage) self.P.setTerminationEnabled(True) self.in_loop(False) except: self.statusbar.showMessage( "# Error: only valid integers allowed") return False def loop_status(self): if self.Looping: self.Looping = None self.lineEdit.setEnabled(False) self.pushButton_3.setEnabled(False) else: self.Looping = True self.lineEdit.setEnabled(True) return True def in_loop(self, stop=True): if stop: if self.P.isRunning(): self.P.stop() self.pushButton_3.setEnabled(False) self.pushButton_2.setEnabled(True) self.checkBox.setEnabled(True) if self.checkBox.isChecked(): self.lineEdit.setEnabled(True) self.checkBox_2.setEnabled(True) self.checkBox_3.setEnabled(True) self.checkBox_4.setEnabled(True) self.checkBox_5.setEnabled(True) self.comboBox.setEnabled(True) else: self.pushButton_3.setEnabled(True) self.pushButton_2.setEnabled(False) self.checkBox.setEnabled(False) self.lineEdit.setEnabled(False) self.checkBox_2.setEnabled(False) self.checkBox_3.setEnabled(False) self.checkBox_4.setEnabled(False) self.checkBox_5.setEnabled(False) self.comboBox.setEnabled(False) return True def rootWarn(self): if platform[:len(platform) - 1] == "linux": from os import getuid if getuid() != 0: self.statusbar.setStyleSheet(self.s_error) self.statusbar.showMessage( "# Error: you must use sudo on Linux") @Slot(object) def handleStatusMessage(self, message): self.statusbar.setStyleSheet(self.s_loop) if message[:7] == '# Error': self.in_loop() self.statusbar.setStyleSheet(self.s_error) self.statusbar.showMessage(message)
class ConfigDialog(QtGui.QDialog): pressedclosebutton = False moreToggling = False def moreToggled(self): if self.moreToggling == False: self.moreToggling = True if self.showmoreCheckbox.isChecked() and self.showmoreCheckbox.isVisible(): self.showmoreCheckbox.setChecked(False) self.moreSettingsGroup.setChecked(True) self.moreSettingsGroup.show() self.showmoreCheckbox.hide() self.saveMoreState(True) else: self.moreSettingsGroup.setChecked(False) self.moreSettingsGroup.hide() self.showmoreCheckbox.show() self.saveMoreState(False) self.moreToggling = False self.adjustSize() self.setFixedSize(self.sizeHint()) def runButtonTextUpdate(self): if (self.donotstoreCheckbox.isChecked()): self.runButton.setText(getMessage("en", "run-label")) else: self.runButton.setText(getMessage("en", "storeandrun-label")) def openHelp(self): self.QtGui.QDesktopServices.openUrl("http://syncplay.pl/guide/client/") def _tryToFillPlayerPath(self, playerpath, playerpathlist): settings = QSettings("Syncplay", "PlayerList") settings.beginGroup("PlayerList") savedPlayers = settings.value("PlayerList", []) if(not isinstance(savedPlayers, list)): savedPlayers = [] playerpathlist = list(set(os.path.normcase(os.path.normpath(path)) for path in set(playerpathlist + savedPlayers))) settings.endGroup() foundpath = "" if playerpath != None and playerpath != "": if not os.path.isfile(playerpath): expandedpath = PlayerFactory().getExpandedPlayerPathByPath(playerpath) if expandedpath != None and os.path.isfile(expandedpath): playerpath = expandedpath if os.path.isfile(playerpath): foundpath = playerpath self.executablepathCombobox.addItem(foundpath) for path in playerpathlist: if(os.path.isfile(path) and os.path.normcase(os.path.normpath(path)) != os.path.normcase(os.path.normpath(foundpath))): self.executablepathCombobox.addItem(path) if foundpath == "": foundpath = path if foundpath != "": settings.beginGroup("PlayerList") playerpathlist.append(os.path.normcase(os.path.normpath(foundpath))) settings.setValue("PlayerList", list(set(os.path.normcase(os.path.normpath(path)) for path in set(playerpathlist)))) settings.endGroup() return(foundpath) def updateExecutableIcon(self): currentplayerpath = unicode(self.executablepathCombobox.currentText()) iconpath = PlayerFactory().getPlayerIconByPath(currentplayerpath) if iconpath != None and iconpath != "": self.executableiconImage.load(self.resourcespath + iconpath) self.executableiconLabel.setPixmap(QtGui.QPixmap.fromImage(self.executableiconImage)) else: self.executableiconLabel.setPixmap(QtGui.QPixmap.fromImage(QtGui.QImage())) def browsePlayerpath(self): options = QtGui.QFileDialog.Options() defaultdirectory = "" browserfilter = "All files (*)" if os.name == 'nt': browserfilter = "Executable files (*.exe);;All files (*)" if "PROGRAMFILES(X86)" in os.environ: defaultdirectory = os.environ["ProgramFiles(x86)"] elif "PROGRAMFILES" in os.environ: defaultdirectory = os.environ["ProgramFiles"] elif "PROGRAMW6432" in os.environ: defaultdirectory = os.environ["ProgramW6432"] elif sys.platform.startswith('linux'): defaultdirectory = "/usr/bin" fileName, filtr = QtGui.QFileDialog.getOpenFileName(self, "Browse for media player executable", defaultdirectory, browserfilter, "", options) if fileName: self.executablepathCombobox.setEditText(os.path.normpath(fileName)) def loadMediaBrowseSettings(self): settings = QSettings("Syncplay", "MediaBrowseDialog") settings.beginGroup("MediaBrowseDialog") self.mediadirectory = settings.value("mediadir", "") settings.endGroup() def saveMediaBrowseSettings(self): settings = QSettings("Syncplay", "MediaBrowseDialog") settings.beginGroup("MediaBrowseDialog") settings.setValue("mediadir", self.mediadirectory) settings.endGroup() def getMoreState(self): settings = QSettings("Syncplay", "MoreSettings") settings.beginGroup("MoreSettings") morestate = unicode.lower(unicode(settings.value("ShowMoreSettings", "false"))) settings.endGroup() if morestate == "true": return(True) else: return(False) def saveMoreState(self, morestate): settings = QSettings("Syncplay", "MoreSettings") settings.beginGroup("MoreSettings") settings.setValue("ShowMoreSettings", morestate) settings.endGroup() def browseMediapath(self): self.loadMediaBrowseSettings() options = QtGui.QFileDialog.Options() if (os.path.isdir(self.mediadirectory)): defaultdirectory = self.mediadirectory elif (os.path.isdir(QDesktopServices.storageLocation(QDesktopServices.MoviesLocation))): defaultdirectory = QDesktopServices.storageLocation(QDesktopServices.MoviesLocation) elif (os.path.isdir(QDesktopServices.storageLocation(QDesktopServices.HomeLocation))): defaultdirectory = QDesktopServices.storageLocation(QDesktopServices.HomeLocation) else: defaultdirectory = "" browserfilter = "All files (*)" fileName, filtr = QtGui.QFileDialog.getOpenFileName(self, "Browse for media files", defaultdirectory, browserfilter, "", options) if fileName: self.mediapathTextbox.setText(os.path.normpath(fileName)) self.mediadirectory = os.path.dirname(fileName) self.saveMediaBrowseSettings() def _saveDataAndLeave(self): self.config['host'] = self.hostTextbox.text() if ":" in self.hostTextbox.text() else self.hostTextbox.text() + ":" + unicode(constants.DEFAULT_PORT) self.config['name'] = self.usernameTextbox.text() self.config['room'] = self.defaultroomTextbox.text() self.config['password'] = self.serverpassTextbox.text() self.config['playerPath'] = unicode(self.executablepathCombobox.currentText()) if self.mediapathTextbox.text() == "": self.config['file'] = None elif os.path.isfile(os.path.abspath(self.mediapathTextbox.text())): self.config['file'] = os.path.abspath(self.mediapathTextbox.text()) else: self.config['file'] = unicode(self.mediapathTextbox.text()) if self.alwaysshowCheckbox.isChecked() == True: self.config['forceGuiPrompt'] = True else: self.config['forceGuiPrompt'] = False if self.donotstoreCheckbox.isChecked() == True: self.config['noStore'] = True else: self.config['noStore'] = False if self.slowdownCheckbox.isChecked() == True: self.config['slowOnDesync'] = True else: self.config['slowOnDesync'] = False if self.dontslowwithmeCheckbox.isChecked() == True: self.config['dontSlowDownWithMe'] = True else: self.config['dontSlowDownWithMe'] = False if self.pauseonleaveCheckbox.isChecked() == True: self.config['pauseOnLeave'] = True else: self.config['pauseOnLeave'] = False if constants.SHOW_REWIND_ON_DESYNC_CHECKBOX == True: if self.rewindCheckbox.isChecked() == True: self.config['rewindOnDesync'] = True else: self.config['rewindOnDesync'] = False if self.filenameprivacySendRawOption.isChecked() == True: self.config['filenamePrivacyMode'] = constants.PRIVACY_SENDRAW_MODE elif self.filenameprivacySendHashedOption.isChecked() == True: self.config['filenamePrivacyMode'] = constants.PRIVACY_SENDHASHED_MODE elif self.filenameprivacyDontSendOption.isChecked() == True: self.config['filenamePrivacyMode'] = constants.PRIVACY_DONTSEND_MODE if self.filesizeprivacySendRawOption.isChecked() == True: self.config['filesizePrivacyMode'] = constants.PRIVACY_SENDRAW_MODE elif self.filesizeprivacySendHashedOption.isChecked() == True: self.config['filesizePrivacyMode'] = constants.PRIVACY_SENDHASHED_MODE elif self.filesizeprivacyDontSendOption.isChecked() == True: self.config['filesizePrivacyMode'] = constants.PRIVACY_DONTSEND_MODE self.pressedclosebutton = True self.close() return def closeEvent(self, event): if self.pressedclosebutton == False: sys.exit() raise GuiConfiguration.WindowClosed event.accept() def dragEnterEvent(self, event): data = event.mimeData() urls = data.urls() if (urls and urls[0].scheme() == 'file'): event.acceptProposedAction() def dropEvent(self, event): data = event.mimeData() urls = data.urls() if (urls and urls[0].scheme() == 'file'): if sys.platform.startswith('linux'): dropfilepath = unicode(urls[0].path()) else: dropfilepath = unicode(urls[0].path())[1:] # Removes starting slash if dropfilepath[-4:].lower() == ".exe": self.executablepathCombobox.setEditText(dropfilepath) else: self.mediapathTextbox.setText(dropfilepath) def __init__(self, config, playerpaths, error): from syncplay import utils self.config = config self.datacleared = False if config['clearGUIData'] == True: settings = QSettings("Syncplay", "PlayerList") settings.clear() settings = QSettings("Syncplay", "MediaBrowseDialog") settings.clear() settings = QSettings("Syncplay", "MainWindow") settings.clear() settings = QSettings("Syncplay", "MoreSettings") settings.clear() self.datacleared = True self.QtGui = QtGui self.error = error if sys.platform.startswith('linux'): resourcespath = utils.findWorkingDir() + "/resources/" else: resourcespath = utils.findWorkingDir() + "\\resources\\" self.resourcespath = resourcespath super(ConfigDialog, self).__init__() self.setWindowTitle(getMessage("en", "config-window-title")) self.setWindowFlags(self.windowFlags() & Qt.WindowCloseButtonHint & ~Qt.WindowContextHelpButtonHint) self.setWindowIcon(QtGui.QIcon(resourcespath + "syncplay.png")) if(config['host'] == None): host = "" elif(":" in config['host']): host = config['host'] else: host = config['host'] + ":" + str(config['port']) self.connectionSettingsGroup = QtGui.QGroupBox(getMessage("en", "connection-group-title")) self.hostTextbox = QLineEdit(host, self) self.hostLabel = QLabel(getMessage("en", "host-label"), self) self.usernameTextbox = QLineEdit(config['name'], self) self.serverpassLabel = QLabel(getMessage("en", "password-label"), self) self.defaultroomTextbox = QLineEdit(config['room'], self) self.usernameLabel = QLabel(getMessage("en", "username-label"), self) self.serverpassTextbox = QLineEdit(config['password'], self) self.defaultroomLabel = QLabel(getMessage("en", "room-label"), self) if (constants.SHOW_TOOLTIPS == True): self.hostLabel.setToolTip(getMessage("en", "host-tooltip")) self.hostTextbox.setToolTip(getMessage("en", "host-tooltip")) self.usernameLabel.setToolTip(getMessage("en", "username-tooltip")) self.usernameTextbox.setToolTip(getMessage("en", "username-tooltip")) self.serverpassLabel.setToolTip(getMessage("en", "password-tooltip")) self.serverpassTextbox.setToolTip(getMessage("en", "password-tooltip")) self.defaultroomLabel.setToolTip(getMessage("en", "room-tooltip")) self.defaultroomTextbox.setToolTip(getMessage("en", "room-tooltip")) self.connectionSettingsLayout = QtGui.QGridLayout() self.connectionSettingsLayout.addWidget(self.hostLabel, 0, 0) self.connectionSettingsLayout.addWidget(self.hostTextbox, 0, 1) self.connectionSettingsLayout.addWidget(self.serverpassLabel, 1, 0) self.connectionSettingsLayout.addWidget(self.serverpassTextbox, 1, 1) self.connectionSettingsLayout.addWidget(self.usernameLabel, 2, 0) self.connectionSettingsLayout.addWidget(self.usernameTextbox, 2, 1) self.connectionSettingsLayout.addWidget(self.defaultroomLabel, 3, 0) self.connectionSettingsLayout.addWidget(self.defaultroomTextbox, 3, 1) self.connectionSettingsGroup.setLayout(self.connectionSettingsLayout) self.mediaplayerSettingsGroup = QtGui.QGroupBox(getMessage("en", "media-setting-title")) self.executableiconImage = QtGui.QImage() self.executableiconLabel = QLabel(self) self.executableiconLabel.setMinimumWidth(16) self.executablepathCombobox = QtGui.QComboBox(self) self.executablepathCombobox.setEditable(True) self.executablepathCombobox.currentIndexChanged.connect(self.updateExecutableIcon) self.executablepathCombobox.setEditText(self._tryToFillPlayerPath(config['playerPath'], playerpaths)) self.executablepathCombobox.setMinimumWidth(200) self.executablepathCombobox.setMaximumWidth(200) self.executablepathCombobox.editTextChanged.connect(self.updateExecutableIcon) self.executablepathLabel = QLabel(getMessage("en", "executable-path-label"), self) self.executablebrowseButton = QtGui.QPushButton(QtGui.QIcon(resourcespath + 'folder_explore.png'), getMessage("en", "browse-label")) self.executablebrowseButton.clicked.connect(self.browsePlayerpath) self.mediapathTextbox = QLineEdit(config['file'], self) self.mediapathLabel = QLabel(getMessage("en", "media-path-label"), self) self.mediabrowseButton = QtGui.QPushButton(QtGui.QIcon(resourcespath + 'folder_explore.png'), getMessage("en", "browse-label")) self.mediabrowseButton.clicked.connect(self.browseMediapath) if (constants.SHOW_TOOLTIPS == True): self.executablepathLabel.setToolTip(getMessage("en", "executable-path-tooltip")) self.executablepathCombobox.setToolTip(getMessage("en", "executable-path-tooltip")) self.mediapathLabel.setToolTip(getMessage("en", "media-path-tooltip")) self.mediapathTextbox.setToolTip(getMessage("en", "media-path-tooltip")) if constants.SHOW_REWIND_ON_DESYNC_CHECKBOX == True: self.rewindCheckbox = QCheckBox(getMessage("en", "rewind-label")) if (constants.SHOW_TOOLTIPS == True): self.rewindCheckbox.setToolTip(getMessage("en", "rewind-tooltip")) self.mediaplayerSettingsLayout = QtGui.QGridLayout() self.mediaplayerSettingsLayout.addWidget(self.executablepathLabel, 0, 0) self.mediaplayerSettingsLayout.addWidget(self.executableiconLabel, 0, 1) self.mediaplayerSettingsLayout.addWidget(self.executablepathCombobox, 0, 2) self.mediaplayerSettingsLayout.addWidget(self.executablebrowseButton, 0, 3) self.mediaplayerSettingsLayout.addWidget(self.mediapathLabel, 1, 0) self.mediaplayerSettingsLayout.addWidget(self.mediapathTextbox , 1, 2) self.mediaplayerSettingsLayout.addWidget(self.mediabrowseButton , 1, 3) self.mediaplayerSettingsGroup.setLayout(self.mediaplayerSettingsLayout) self.moreSettingsGroup = QtGui.QGroupBox(getMessage("en", "more-title")) self.moreSettingsGroup.setCheckable(True) self.filenameprivacyLabel = QLabel(getMessage("en", "filename-privacy-label"), self) self.filenameprivacyButtonGroup = QButtonGroup() self.filenameprivacySendRawOption = QRadioButton(getMessage("en", "privacy-sendraw-option")) self.filenameprivacySendHashedOption = QRadioButton(getMessage("en", "privacy-sendhashed-option")) self.filenameprivacyDontSendOption = QRadioButton(getMessage("en", "privacy-dontsend-option")) self.filenameprivacyButtonGroup.addButton(self.filenameprivacySendRawOption) self.filenameprivacyButtonGroup.addButton(self.filenameprivacySendHashedOption) self.filenameprivacyButtonGroup.addButton(self.filenameprivacyDontSendOption) self.filesizeprivacyLabel = QLabel(getMessage("en", "filesize-privacy-label"), self) self.filesizeprivacyButtonGroup = QButtonGroup() self.filesizeprivacySendRawOption = QRadioButton(getMessage("en", "privacy-sendraw-option")) self.filesizeprivacySendHashedOption = QRadioButton(getMessage("en", "privacy-sendhashed-option")) self.filesizeprivacyDontSendOption = QRadioButton(getMessage("en", "privacy-dontsend-option")) self.filesizeprivacyButtonGroup.addButton(self.filesizeprivacySendRawOption) self.filesizeprivacyButtonGroup.addButton(self.filesizeprivacySendHashedOption) self.filesizeprivacyButtonGroup.addButton(self.filesizeprivacyDontSendOption) self.slowdownCheckbox = QCheckBox(getMessage("en", "slowdown-label")) self.dontslowwithmeCheckbox = QCheckBox(getMessage("en", "dontslowwithme-label")) self.pauseonleaveCheckbox = QCheckBox(getMessage("en", "pauseonleave-label")) self.alwaysshowCheckbox = QCheckBox(getMessage("en", "alwayshow-label")) self.donotstoreCheckbox = QCheckBox(getMessage("en", "donotstore-label")) filenamePrivacyMode = config['filenamePrivacyMode'] if filenamePrivacyMode == constants.PRIVACY_DONTSEND_MODE: self.filenameprivacyDontSendOption.setChecked(True) elif filenamePrivacyMode == constants.PRIVACY_SENDHASHED_MODE: self.filenameprivacySendHashedOption.setChecked(True) else: self.filenameprivacySendRawOption.setChecked(True) filesizePrivacyMode = config['filesizePrivacyMode'] if filesizePrivacyMode == constants.PRIVACY_DONTSEND_MODE: self.filesizeprivacyDontSendOption.setChecked(True) elif filesizePrivacyMode == constants.PRIVACY_SENDHASHED_MODE: self.filesizeprivacySendHashedOption.setChecked(True) else: self.filesizeprivacySendRawOption.setChecked(True) if config['slowOnDesync'] == True: self.slowdownCheckbox.setChecked(True) if config['dontSlowDownWithMe'] == True: self.dontslowwithmeCheckbox.setChecked(True) if constants.SHOW_REWIND_ON_DESYNC_CHECKBOX == True and config['rewindOnDesync'] == True: self.rewindCheckbox.setChecked(True) if config['pauseOnLeave'] == True: self.pauseonleaveCheckbox.setChecked(True) if (constants.SHOW_TOOLTIPS == True): self.filenameprivacyLabel.setToolTip(getMessage("en", "filename-privacy-tooltip")) self.filenameprivacySendRawOption.setToolTip(getMessage("en", "privacy-sendraw-tooltip")) self.filenameprivacySendHashedOption.setToolTip(getMessage("en", "privacy-sendhashed-tooltip")) self.filenameprivacyDontSendOption.setToolTip(getMessage("en", "privacy-dontsend-tooltip")) self.filesizeprivacyLabel.setToolTip(getMessage("en", "filesize-privacy-tooltip")) self.filesizeprivacySendRawOption.setToolTip(getMessage("en", "privacy-sendraw-tooltip")) self.filesizeprivacySendHashedOption.setToolTip(getMessage("en", "privacy-sendhashed-tooltip")) self.filesizeprivacyDontSendOption.setToolTip(getMessage("en", "privacy-dontsend-tooltip")) self.slowdownCheckbox.setToolTip(getMessage("en", "slowdown-tooltip")) self.dontslowwithmeCheckbox.setToolTip(getMessage("en", "dontslowwithme-tooltip")) self.pauseonleaveCheckbox.setToolTip(getMessage("en", "pauseonleave-tooltip")) self.alwaysshowCheckbox.setToolTip(getMessage("en", "alwayshow-tooltip")) self.donotstoreCheckbox.setToolTip(getMessage("en", "donotstore-tooltip")) self.slowdownCheckbox.setToolTip(getMessage("en", "slowdown-tooltip")) self.moreSettingsLayout = QtGui.QGridLayout() self.privacySettingsLayout = QtGui.QGridLayout() self.privacyFrame = QtGui.QFrame() self.privacyFrame.setLineWidth(0) self.privacyFrame.setMidLineWidth(0) self.privacySettingsLayout.setContentsMargins(0, 0, 0, 0) self.privacySettingsLayout.addWidget(self.filenameprivacyLabel, 0, 0) self.privacySettingsLayout.addWidget(self.filenameprivacySendRawOption, 0, 1, Qt.AlignRight) self.privacySettingsLayout.addWidget(self.filenameprivacySendHashedOption, 0, 2, Qt.AlignRight) self.privacySettingsLayout.addWidget(self.filenameprivacyDontSendOption, 0, 3, Qt.AlignRight) self.privacySettingsLayout.addWidget(self.filesizeprivacyLabel, 1, 0) self.privacySettingsLayout.addWidget(self.filesizeprivacySendRawOption, 1, 1, Qt.AlignRight) self.privacySettingsLayout.addWidget(self.filesizeprivacySendHashedOption, 1, 2, Qt.AlignRight) self.privacySettingsLayout.addWidget(self.filesizeprivacyDontSendOption, 1, 3, Qt.AlignRight) self.privacyFrame.setLayout(self.privacySettingsLayout) self.moreSettingsLayout.addWidget(self.privacyFrame, 0, 0, 1, 4) self.moreSettingsLayout.addWidget(self.slowdownCheckbox, 2, 0, 1, 4) self.moreSettingsLayout.addWidget(self.dontslowwithmeCheckbox, 3, 0, 1, 4) if constants.SHOW_REWIND_ON_DESYNC_CHECKBOX == True: self.moreSettingsLayout.addWidget(self.rewindCheckbox, 4, 0, 1, 4) self.moreSettingsLayout.addWidget(self.pauseonleaveCheckbox, 5, 0, 1, 4) self.moreSettingsLayout.addWidget(self.alwaysshowCheckbox, 6, 0, 1, 4) self.moreSettingsLayout.addWidget(self.donotstoreCheckbox, 7, 0, 1, 4) self.moreSettingsGroup.setLayout(self.moreSettingsLayout) self.showmoreCheckbox = QCheckBox(getMessage("en", "more-title")) if self.getMoreState() == False: self.showmoreCheckbox.setChecked(False) self.moreSettingsGroup.hide() else: self.showmoreCheckbox.hide() self.showmoreCheckbox.toggled.connect(self.moreToggled) self.moreSettingsGroup.toggled.connect(self.moreToggled) if config['forceGuiPrompt'] == True: self.alwaysshowCheckbox.setChecked(True) if (constants.SHOW_TOOLTIPS == True): self.showmoreCheckbox.setToolTip(getMessage("en", "more-tooltip")) self.donotstoreCheckbox.toggled.connect(self.runButtonTextUpdate) self.mainLayout = QtGui.QVBoxLayout() if error: self.errorLabel = QLabel(error, self) self.errorLabel.setAlignment(Qt.AlignCenter) self.errorLabel.setStyleSheet("QLabel { color : red; }") self.mainLayout.addWidget(self.errorLabel) self.mainLayout.addWidget(self.connectionSettingsGroup) self.mainLayout.addSpacing(12) self.mainLayout.addWidget(self.mediaplayerSettingsGroup) self.mainLayout.addSpacing(12) self.mainLayout.addWidget(self.showmoreCheckbox) self.mainLayout.addWidget(self.moreSettingsGroup) self.mainLayout.addSpacing(12) self.topLayout = QtGui.QHBoxLayout() self.helpButton = QtGui.QPushButton(QtGui.QIcon(resourcespath + 'help.png'), getMessage("en", "help-label")) if (constants.SHOW_TOOLTIPS == True): self.helpButton.setToolTip(getMessage("en", "help-tooltip")) self.helpButton.setMaximumSize(self.helpButton.sizeHint()) self.helpButton.pressed.connect(self.openHelp) self.runButton = QtGui.QPushButton(QtGui.QIcon(resourcespath + 'accept.png'), getMessage("en", "storeandrun-label")) self.runButton.pressed.connect(self._saveDataAndLeave) if config['noStore'] == True: self.donotstoreCheckbox.setChecked(True) self.runButton.setText(getMessage("en", "run-label")) self.topLayout.addWidget(self.helpButton, Qt.AlignLeft) self.topLayout.addWidget(self.runButton, Qt.AlignRight) self.mainLayout.addLayout(self.topLayout) self.mainLayout.addStretch(1) self.setLayout(self.mainLayout) self.runButton.setFocus() self.setFixedSize(self.sizeHint()) self.setAcceptDrops(True) if self.datacleared == True: QtGui.QMessageBox.information(self, "Syncplay", getMessage("en", "gui-data-cleared-notification"))
class ConfigDialog(QtGui.QDialog): pressedclosebutton = False malToggling = False def malToggled(self): if self.malToggling == False: self.malToggling = True if self.malenabledCheckbox.isChecked() and self.malenabledCheckbox.isVisible(): self.malenabledCheckbox.setChecked(False) self.malSettingsGroup.setChecked(True) self.malSettingsGroup.show() self.malpasswordLabel.show() self.malpasswordTextbox.show() self.malusernameLabel.show() self.malusernameTextbox.show() self.malenabledCheckbox.hide() else: self.malSettingsGroup.setChecked(False) self.malSettingsGroup.hide() self.malpasswordLabel.hide() self.malpasswordTextbox.hide() self.malusernameLabel.hide() self.malusernameTextbox.hide() self.malenabledCheckbox.show() self.malToggling = False self.adjustSize() self.setFixedSize(self.sizeHint()) def runButtonTextUpdate(self): if (self.donotstoreCheckbox.isChecked()): self.runButton.setText(getMessage("en", "run-label")) else: self.runButton.setText(getMessage("en", "storeandrun-label")) def openHelp(self): if sys.platform.startswith('linux'): self.QtGui.QDesktopServices.openUrl("http://syncplay.pl/guide/linux/") elif sys.platform.startswith('win'): self.QtGui.QDesktopServices.openUrl("http://syncplay.pl/guide/windows/") else: self.QtGui.QDesktopServices.openUrl("http://syncplay.pl/guide/") def _tryToFillPlayerPath(self, playerpath, playerpathlist): foundpath = "" if playerpath != None and playerpath != "" and os.path.isfile(playerpath): foundpath = playerpath self.executablepathCombobox.addItem(foundpath) for path in playerpathlist: if(os.path.isfile(path) and path.lower() != foundpath.lower()): self.executablepathCombobox.addItem(path) if foundpath == None: foundpath = path if foundpath: return(foundpath) else: return("") def browsePlayerpath(self): options = QtGui.QFileDialog.Options() defaultdirectory = "" browserfilter = "All files (*)" if os.name == 'nt': browserfilter = "Executable files (*.exe);;All files (*)" if "PROGRAMFILES(X86)" in os.environ: defaultdirectory = os.environ["ProgramFiles(x86)"] elif "PROGRAMFILES" in os.environ: defaultdirectory = os.environ["ProgramFiles"] elif "PROGRAMW6432" in os.environ: defaultdirectory = os.environ["ProgramW6432"] elif sys.platform.startswith('linux'): defaultdirectory = "/usr/bin" fileName, filtr = QtGui.QFileDialog.getOpenFileName(self, "Browse for media player executable", defaultdirectory, browserfilter, "", options) if fileName: self.executablepathCombobox.setEditText(fileName) def loadMediaBrowseSettings(self): settings = QSettings("Syncplay", "MediaBrowseDialog") settings.beginGroup("MediaBrowseDialog") self.mediadirectory = settings.value("mediadir", "") settings.endGroup() def saveMediaBrowseSettings(self): settings = QSettings("Syncplay", "MediaBrowseDialog") settings.beginGroup("MediaBrowseDialog") settings.setValue("mediadir", self.mediadirectory) settings.endGroup() def browseMediapath(self): self.loadMediaBrowseSettings() options = QtGui.QFileDialog.Options() if (os.path.isdir(self.mediadirectory)): defaultdirectory = self.mediadirectory elif (os.path.isdir(QDesktopServices.storageLocation(QDesktopServices.MoviesLocation))): defaultdirectory = QDesktopServices.storageLocation(QDesktopServices.MoviesLocation) elif (os.path.isdir(QDesktopServices.storageLocation(QDesktopServices.HomeLocation))): defaultdirectory = QDesktopServices.storageLocation(QDesktopServices.HomeLocation) else: defaultdirectory = "" browserfilter = "All files (*)" fileName, filtr = QtGui.QFileDialog.getOpenFileName(self,"Browse for media files",defaultdirectory, browserfilter, "", options) if fileName: self.mediapathTextbox.setText(fileName) self.mediadirectory = os.path.dirname(fileName) self.saveMediaBrowseSettings() def _saveDataAndLeave(self): self.config['host'] = self.hostTextbox.text() self.config['name'] = self.usernameTextbox.text() self.config['room'] = self.defaultroomTextbox.text() self.config['password'] = self.serverpassTextbox.text() self.config['playerPath'] = unicode(self.executablepathCombobox.currentText()) if self.mediapathTextbox.text() == "": self.config['file'] = None elif os.path.isfile(os.path.abspath(self.mediapathTextbox.text())): self.config['file'] = os.path.abspath(self.mediapathTextbox.text()) else: self.config['file'] = unicode(self.mediapathTextbox.text()) if self.alwaysshowCheckbox.isChecked() == True: self.config['forceGuiPrompt'] = True else: self.config['forceGuiPrompt'] = False if self.donotstoreCheckbox.isChecked() == True: self.config['noStore'] = True else: self.config['noStore'] = False if self.slowdownCheckbox.isChecked() == True: self.config['slowOnDesync'] = True else: self.config['slowOnDesync'] = False if constants.SHOW_REWIND_ON_DESYNC_CHECKBOX == True: if self.rewindCheckbox.isChecked() == True: self.config['rewindOnDesync'] = True else: self.config['rewindOnDesync'] = False self.config['malUsername'] = self.malusernameTextbox.text() if self.malSettingsGroup.isChecked(): self.config['malPassword'] = self.malpasswordTextbox.text() else: self.config['malPassword'] = "" self.pressedclosebutton = True self.close() return def closeEvent(self, event): if self.pressedclosebutton == False: sys.exit() raise GuiConfiguration.WindowClosed event.accept() def dragEnterEvent(self, event): data = event.mimeData() urls = data.urls() if (urls and urls[0].scheme() == 'file'): event.acceptProposedAction() def dropEvent(self, event): data = event.mimeData() urls = data.urls() if (urls and urls[0].scheme() == 'file'): if sys.platform.startswith('linux'): dropfilepath = unicode(urls[0].path()) else: dropfilepath = unicode(urls[0].path())[1:] # Removes starting slash if dropfilepath[-4:].lower() == ".exe": self.executablepathCombobox.setEditText(dropfilepath) else: self.mediapathTextbox.setText(dropfilepath) def __init__(self, config, playerpaths, error): from syncplay import utils self.config = config self.QtGui = QtGui self.error = error if sys.platform.startswith('linux'): resourcespath = utils.findWorkingDir() + "/resources/" else: resourcespath = utils.findWorkingDir() + "\\resources\\" super(ConfigDialog, self).__init__() self.setWindowTitle(getMessage("en", "config-window-title")) self.setWindowFlags(self.windowFlags() & ~Qt.WindowContextHelpButtonHint) self.setWindowIcon(QtGui.QIcon(resourcespath + "syncplay.png")) if(config['host'] == None): host = "" elif(":" in config['host']): host = config['host'] else: host = config['host']+":"+str(config['port']) self.connectionSettingsGroup = QtGui.QGroupBox(getMessage("en", "connection-group-title")) self.hostTextbox = QLineEdit(host, self) self.hostLabel = QLabel(getMessage("en", "host-label"), self) self.usernameTextbox = QLineEdit(config['name'],self) self.serverpassLabel = QLabel(getMessage("en", "password-label"), self) self.defaultroomTextbox = QLineEdit(config['room'],self) self.usernameLabel = QLabel(getMessage("en", "username-label"), self) self.serverpassTextbox = QLineEdit(config['password'],self) self.defaultroomLabel = QLabel(getMessage("en", "room-label"), self) if (constants.SHOW_TOOLTIPS == True): self.hostLabel.setToolTip(getMessage("en", "host-tooltip")) self.hostTextbox.setToolTip(getMessage("en", "host-tooltip")) self.usernameLabel.setToolTip(getMessage("en", "username-tooltip")) self.usernameTextbox.setToolTip(getMessage("en", "username-tooltip")) self.serverpassLabel.setToolTip(getMessage("en", "password-tooltip")) self.serverpassTextbox.setToolTip(getMessage("en", "password-tooltip")) self.defaultroomLabel.setToolTip(getMessage("en", "room-tooltip")) self.defaultroomTextbox.setToolTip(getMessage("en", "room-tooltip")) self.connectionSettingsLayout = QtGui.QGridLayout() self.connectionSettingsLayout.addWidget(self.hostLabel, 0, 0) self.connectionSettingsLayout.addWidget(self.hostTextbox, 0, 1) self.connectionSettingsLayout.addWidget(self.serverpassLabel, 1, 0) self.connectionSettingsLayout.addWidget(self.serverpassTextbox, 1, 1) self.connectionSettingsLayout.addWidget(self.usernameLabel, 2, 0) self.connectionSettingsLayout.addWidget(self.usernameTextbox, 2, 1) self.connectionSettingsLayout.addWidget(self.defaultroomLabel, 3, 0) self.connectionSettingsLayout.addWidget(self.defaultroomTextbox, 3, 1) self.connectionSettingsGroup.setLayout(self.connectionSettingsLayout) self.mediaplayerSettingsGroup = QtGui.QGroupBox(getMessage("en", "media-setting-title")) self.executablepathCombobox = QtGui.QComboBox(self) self.executablepathCombobox.setEditable(True) self.executablepathCombobox.setEditText(self._tryToFillPlayerPath(config['playerPath'],playerpaths)) self.executablepathCombobox.setMinimumWidth(200) self.executablepathCombobox.setMaximumWidth(200) self.executablepathLabel = QLabel(getMessage("en", "executable-path-label"), self) self.executablebrowseButton = QtGui.QPushButton(QtGui.QIcon(resourcespath + 'folder_explore.png'),getMessage("en", "browse-label")) self.executablebrowseButton.clicked.connect(self.browsePlayerpath) self.mediapathTextbox = QLineEdit(config['file'], self) self.mediapathLabel = QLabel(getMessage("en", "media-path-label"), self) self.mediabrowseButton = QtGui.QPushButton(QtGui.QIcon(resourcespath + 'folder_explore.png'),getMessage("en", "browse-label")) self.mediabrowseButton.clicked.connect(self.browseMediapath) self.slowdownCheckbox = QCheckBox(getMessage("en", "slowdown-label")) if (constants.SHOW_TOOLTIPS == True): self.executablepathLabel.setToolTip(getMessage("en", "executable-path-tooltip")) self.executablepathCombobox.setToolTip(getMessage("en", "executable-path-tooltip")) self.mediapathLabel.setToolTip(getMessage("en", "media-path-tooltip")) self.mediapathTextbox.setToolTip(getMessage("en", "media-path-tooltip")) self.slowdownCheckbox.setToolTip(getMessage("en", "slowdown-tooltip")) if constants.SHOW_REWIND_ON_DESYNC_CHECKBOX == True: self.rewindCheckbox = QCheckBox(getMessage("en", "rewind-label")) if (constants.SHOW_TOOLTIPS == True): self.rewindCheckbox.setToolTip(getMessage("en", "rewind-tooltip")) self.mediaplayerSettingsLayout = QtGui.QGridLayout() self.mediaplayerSettingsLayout.addWidget(self.executablepathLabel, 0, 0) self.mediaplayerSettingsLayout.addWidget(self.executablepathCombobox , 0, 1) self.mediaplayerSettingsLayout.addWidget(self.executablebrowseButton , 0, 2) self.mediaplayerSettingsLayout.addWidget(self.mediapathLabel, 1, 0) self.mediaplayerSettingsLayout.addWidget(self.mediapathTextbox , 1, 1) self.mediaplayerSettingsLayout.addWidget(self.mediabrowseButton , 1, 2) self.mediaplayerSettingsLayout.addWidget(self.slowdownCheckbox, 2, 0) if constants.SHOW_REWIND_ON_DESYNC_CHECKBOX == True: self.mediaplayerSettingsLayout.addWidget(self.rewindCheckbox, 3, 0) self.mediaplayerSettingsGroup.setLayout(self.mediaplayerSettingsLayout) if config['slowOnDesync'] == True: self.slowdownCheckbox.setChecked(True) if constants.SHOW_REWIND_ON_DESYNC_CHECKBOX == True and config['rewindOnDesync'] == True: self.rewindCheckbox.setChecked(True) self.malSettingsGroup = QtGui.QGroupBox(getMessage("en", "mal-title")) self.malSettingsGroup.setCheckable(True) self.malSettingsGroup.toggled.connect(self.malToggled) self.malSettingsSplit = QtGui.QSplitter(self) self.malusernameTextbox = QLineEdit(config['malUsername'],self) self.malusernameLabel = QLabel(getMessage("en", "mal-username-label"), self) self.malpasswordTextbox = QLineEdit(config['malPassword'],self) self.malpasswordTextbox.setEchoMode(QtGui.QLineEdit.Password) self.malpasswordLabel = QLabel(getMessage("en", "mal-password-label"), self) if (constants.SHOW_TOOLTIPS == True): self.malusernameLabel.setToolTip(getMessage("en", "mal-username-tooltip")) self.malusernameTextbox.setToolTip(getMessage("en", "mal-username-tooltip")) self.malpasswordLabel.setToolTip(getMessage("en", "mal-password-tooltip")) self.malpasswordTextbox.setToolTip(getMessage("en", "mal-password-tooltip")) self.malSettingsLayout = QtGui.QGridLayout() self.malSettingsLayout.addWidget(self.malusernameLabel , 0, 0) self.malSettingsLayout.addWidget(self.malusernameTextbox, 0, 1) self.malSettingsLayout.addWidget(self.malpasswordLabel , 1, 0) self.malSettingsLayout.addWidget(self.malpasswordTextbox, 1, 1) self.malSettingsGroup.setLayout(self.malSettingsLayout) self.malenabledCheckbox = QCheckBox(getMessage("en", "mal-title")) self.malenabledCheckbox.toggled.connect(self.malToggled) if config['malPassword'] == None or config['malPassword'] == "": self.malenabledCheckbox.setChecked(False) self.malSettingsGroup.hide() else: self.malenabledCheckbox.hide() self.alwaysshowCheckbox = QCheckBox(getMessage("en", "alwayshow-label")) if config['forceGuiPrompt'] == True: self.alwaysshowCheckbox.setChecked(True) self.donotstoreCheckbox = QCheckBox(getMessage("en", "donotstore-label")) if (constants.SHOW_TOOLTIPS == True): self.malenabledCheckbox.setToolTip(getMessage("en", "mal-tooltip")) self.alwaysshowCheckbox.setToolTip(getMessage("en", "alwayshow-tooltip")) self.donotstoreCheckbox.setToolTip(getMessage("en", "donotstore-tooltip")) self.donotstoreCheckbox.toggled.connect(self.runButtonTextUpdate) self.mainLayout = QtGui.QVBoxLayout() if error: self.errorLabel = QLabel(error, self) self.errorLabel.setAlignment(Qt.AlignCenter) self.errorLabel.setStyleSheet("QLabel { color : red; }") self.mainLayout.addWidget(self.errorLabel) self.mainLayout.addWidget(self.connectionSettingsGroup) self.mainLayout.addSpacing(12) self.mainLayout.addWidget(self.mediaplayerSettingsGroup) self.mainLayout.addSpacing(12) self.mainLayout.addWidget(self.malenabledCheckbox) self.mainLayout.addWidget(self.malSettingsGroup) self.topLayout = QtGui.QHBoxLayout() self.helpButton = QtGui.QPushButton(QtGui.QIcon(resourcespath + 'help.png'),getMessage("en", "help-label")) if (constants.SHOW_TOOLTIPS == True): self.helpButton.setToolTip(getMessage("en", "help-tooltip")) self.helpButton.setMaximumSize(self.helpButton.sizeHint()) self.helpButton.pressed.connect(self.openHelp) self.runButton = QtGui.QPushButton(QtGui.QIcon(resourcespath + 'accept.png'),getMessage("en", "storeandrun-label")) self.runButton.pressed.connect(self._saveDataAndLeave) if config['noStore'] == True: self.donotstoreCheckbox.setChecked(True) self.runButton.setText(getMessage("en", "run-label")) self.topLayout.addWidget(self.helpButton, Qt.AlignLeft) self.topLayout.addWidget(self.runButton, Qt.AlignRight) self.mainLayout.addWidget(self.alwaysshowCheckbox) self.mainLayout.addWidget(self.donotstoreCheckbox) self.mainLayout.addLayout(self.topLayout) self.mainLayout.addStretch(1) self.setLayout(self.mainLayout) self.runButton.setFocus() self.setFixedSize(self.sizeHint()) self.setAcceptDrops(True)
class beso_gui(QDialog): def __init__(self): super().__init__() self.title = 'BESO Topology Optimization (experimental)' self.left = 250 self.top = 30 self.width = 550 self.height = 730 beso_gui.inp_file = "" beso_gui.beso_dir = os.path.dirname(__file__) self.initUI() # def closeEvent(self, event): # self.close() def initUI(self): self.setWindowTitle(self.title) self.setGeometry(self.left, self.top, self.width, self.height) # Select analysis file button button = QPushButton('Select analysis file', self) button.setToolTip('*.inp CalculiX analysis file.') button.move(10, 10) button.clicked.connect(self.on_click) # Text box - file path and name self.textbox_file_name = QLineEdit(self) self.textbox_file_name.move(120, 15) self.textbox_file_name.resize(420, 20) self.textbox_file_name.setText("None analysis file selected") self.textbox_file_name.setToolTip('Analysis file.') # Update button button1 = QPushButton('Update domains', self) button1.setToolTip( 'Update naming inputs and material data from FreeCAD.') button1.move(10, 50) button1.clicked.connect(self.on_click1) # Domains definition # Label above domains definition label21 = QLabel('Domain 0', self) label21.setStyleSheet("font-weight: bold") label21.move(120, 50) label21 = QLabel('Domain 1', self) label21.setStyleSheet("font-weight: bold") label21.move(260, 50) label21 = QLabel('Domain 2', self) label21.setStyleSheet("font-weight: bold") label21.move(400, 50) label24 = QLabel('Material object', self) label24.move(20, 80) label25 = QLabel('Thickness object', self) label25.move(20, 110) label26 = QLabel('As design domain', self) label26.move(20, 140) label27 = QLabel('Stress limit [MPa]', self) label27.move(20, 170) # Combo box - select domain by material object self.combo = QComboBox(self) self.combo.setToolTip('Material object to define the domain.') self.combo.move(120, 80) self.combo.resize(140, 30) self.combo.currentIndexChanged.connect(self.on_change) self.combo1 = QComboBox(self) self.combo1.setToolTip('Material object to define the domain.') self.combo1.move(260, 80) self.combo1.resize(140, 30) self.combo1.currentIndexChanged.connect(self.on_change1) self.combo2 = QComboBox(self) self.combo2.setToolTip('Material object to define the domain.') self.combo2.move(400, 80) self.combo2.resize(140, 30) self.combo2.currentIndexChanged.connect(self.on_change2) # Combo box - select thickness object self.combo0t = QComboBox(self) self.combo0t.setToolTip( 'Thickness object to specify if domain is for shells.') self.combo0t.move(120, 110) self.combo0t.resize(140, 30) self.combo1t = QComboBox(self) self.combo1t.setToolTip( 'Thickness object to specify if domain is for shells.') self.combo1t.move(260, 110) self.combo1t.resize(140, 30) self.combo2t = QComboBox(self) self.combo2t.setToolTip( 'Thickness object to specify if domain is for shells.') self.combo2t.move(400, 110) self.combo2t.resize(140, 30) self.textbox3 = QLineEdit(self) self.textbox3.move(120, 170) self.textbox3.resize(40, 20) # self.textbox3.setText("") self.textbox3.setToolTip( 'Thickness [mm] of shell elements in the domain.\n' 'This value overwrites thickness defined in FreeCAD') self.textbox4 = QLineEdit(self) self.textbox4.move(260, 170) self.textbox4.resize(40, 20) # self.textbox4.setText("") self.textbox4.setToolTip( 'Thickness [mm] of shell elements in the domain.\n' 'This value overwrites thickness defined in FreeCAD') self.textbox5 = QLineEdit(self) self.textbox5.move(400, 170) self.textbox5.resize(40, 20) # self.textbox5.setText("") self.textbox5.setToolTip( 'Thickness [mm] of shell elements in the domain.\n' 'This value overwrites thickness defined in FreeCAD') # Check box - design or nondesign self.checkbox = QCheckBox('', self) self.checkbox.setChecked(True) self.checkbox.setToolTip('Check to be the design domain.') self.checkbox.move(120, 140) self.checkbox1 = QCheckBox('', self) self.checkbox1.setChecked(True) self.checkbox1.setToolTip('Check to be the design domain.') self.checkbox1.move(260, 140) self.checkbox2 = QCheckBox('', self) self.checkbox2.setChecked(True) self.checkbox2.setToolTip('Check to be the design domain.') self.checkbox2.move(400, 140) # Text box - stress limit self.textbox = QLineEdit(self) self.textbox.move(120, 170) self.textbox.resize(40, 20) # self.textbox.setText("") self.textbox.setToolTip( 'Von Mises stress [MPa] limit, when reached, material removing will stop.' ) self.textbox1 = QLineEdit(self) self.textbox1.move(260, 170) self.textbox1.resize(40, 20) # self.textbox1.setText("") self.textbox1.setToolTip( 'Von Mises stress [MPa] limit, when reached, material removing will stop.' ) self.textbox2 = QLineEdit(self) self.textbox2.move(400, 170) self.textbox2.resize(40, 20) # self.textbox2.setText("") self.textbox2.setToolTip( 'Von Mises stress [MPa] limit, when reached, material removing will stop.' ) # Filters # Label above filter definition label31 = QLabel('Filter 0', self) label31.setStyleSheet("font-weight: bold") label31.move(120, 210) label32 = QLabel('Filter 1', self) label32.setStyleSheet("font-weight: bold") label32.move(260, 210) label33 = QLabel('Filter 2', self) label33.setStyleSheet("font-weight: bold") label33.move(400, 210) label34 = QLabel('Type', self) label34.move(20, 240) label35 = QLabel('Range [mm]', self) label35.move(20, 270) label36 = QLabel('Direction vector', self) label36.move(20, 300) label37 = QLabel('Apply to', self) label37.move(20, 330) # Combo box - select filter type self.combo6 = QComboBox(self) self.combo6.setToolTip( 'Filters:\n' '"simple" to suppress checkerboard effect,\n' '"casting" to prescribe casting direction (opposite to milling direction)\n' 'Recommendation: for casting use as first "casting" and as second "simple"' ) self.combo6.addItem("None") self.combo6.addItem("simple") self.combo6.addItem("casting") self.combo6.setCurrentIndex(1) self.combo6.move(120, 240) self.combo6.currentIndexChanged.connect(self.on_change6) self.combo7 = QComboBox(self) self.combo7.setToolTip( 'Filters:\n' '"simple" to suppress checkerboard effect,\n' '"casting" to prescribe casting direction (opposite to milling direction)\n' 'Recommendation: for casting use as first "casting" and as second "simple"' ) self.combo7.addItem("None") self.combo7.addItem("simple") self.combo7.addItem("casting") self.combo7.move(260, 240) self.combo7.currentIndexChanged.connect(self.on_change7) self.combo8 = QComboBox(self) self.combo8.setToolTip( 'Filters:\n' '"simple" to suppress checkerboard effect,\n' '"casting" to prescribe casting direction (opposite to milling direction)\n' 'Recommendation: for casting use as first "casting" and as second "simple"' ) self.combo8.addItem("None") self.combo8.addItem("simple") self.combo8.addItem("casting") self.combo8.move(400, 240) self.combo8.currentIndexChanged.connect(self.on_change8) # Text box - filter range self.textbox6 = QLineEdit(self) self.textbox6.move(120, 270) self.textbox6.resize(50, 20) # self.textbox6.setText("") self.textbox6.setToolTip( 'Filter range [mm], recommended two times mesh size.') self.textbox7 = QLineEdit(self) self.textbox7.move(260, 270) self.textbox7.resize(50, 20) # self.textbox7.setText("") self.textbox7.setToolTip( 'Filter range [mm], recommended two times mesh size.') self.textbox7.setEnabled(False) self.textbox8 = QLineEdit(self) self.textbox8.move(400, 270) self.textbox8.resize(50, 20) # self.textbox8.setText("") self.textbox8.setToolTip( 'Filter range [mm], recommended two times mesh size.') self.textbox8.setEnabled(False) # Text box - casting direction self.textbox9 = QLineEdit(self) self.textbox9.move(120, 300) self.textbox9.resize(80, 20) self.textbox9.setText("0, 0, 1") self.textbox9.setEnabled(False) self.textbox9.setToolTip( 'Casting direction vector, e.g. direction in z axis:\n' '0, 0, 1\n\n' 'solid void\n' 'XXXXXX.................\n' 'XXX........................\n' 'XX........................... --> z axis\n' 'XXXXX....................\n' 'XXXXXXXXXXX......') self.textbox10 = QLineEdit(self) self.textbox10.move(260, 300) self.textbox10.resize(80, 20) self.textbox10.resize(80, 20) self.textbox10.setText("0, 0, 1") self.textbox10.setEnabled(False) self.textbox10.setToolTip( 'Casting direction vector, e.g. direction in z axis:\n' '0, 0, 1\n\n' 'solid void\n' 'XXXXXX.................\n' 'XXX........................\n' 'XX........................... --> z axis\n' 'XXXXX....................\n' 'XXXXXXXXXXX......') self.textbox11 = QLineEdit(self) self.textbox11.move(400, 300) self.textbox11.resize(80, 20) self.textbox11.setText("0, 0, 1") self.textbox11.setEnabled(False) self.textbox11.setToolTip( 'Casting direction vector, e.g. direction in z axis:\n' '0, 0, 1\n\n' 'solid void\n' 'XXXXXX.................\n' 'XXX........................\n' 'XX........................... --> z axis\n' 'XXXXX....................\n' 'XXXXXXXXXXX......') # list widget - select domains self.widget = QListWidget(self) self.widget.setToolTip( 'Domains affected by the filter.\n' 'Select only from domains which you defined above.') self.widget.move(120, 330) self.widget.resize(140, 120) self.widget.setSelectionMode(QAbstractItemView.MultiSelection) self.widget1 = QListWidget(self) self.widget1.setToolTip( 'Domains affected by the filter.\n' 'Select only from domains which you defined above.') self.widget1.move(260, 330) self.widget1.resize(140, 120) self.widget1.setSelectionMode(QAbstractItemView.MultiSelection) self.widget1.setEnabled(False) self.widget2 = QListWidget(self) self.widget2.setToolTip( 'Domains affected by the filter.\n' 'Select only from domains which you defined above.') self.widget2.move(400, 330) self.widget2.resize(140, 120) self.widget2.setSelectionMode(QAbstractItemView.MultiSelection) self.widget2.setEnabled(False) # Other settings label40 = QLabel('Other settings', self) label40.setStyleSheet("font-weight: bold") label40.move(10, 470) # AR, RR slider label41 = QLabel('Change per iteration: low', self) label41.setFixedWidth(150) label41.move(10, 500) label42 = QLabel('high', self) label42.move(240, 500) self.slider = QSlider(Qt.Horizontal, self) self.slider.setRange(1, 3) self.slider.setSingleStep(1) self.slider.setValue(2) self.slider.move(150, 500) self.slider.resize(80, 30) self.slider.setToolTip( 'Sets mass change per iteration, which is controlled as\n' 'slow: mass_addition_ratio=0.01, mass_removal_ratio=0.02\n' 'middle: mass_addition_ratio=0.015, mass_removal_ratio=0.03\n' 'fast: mass_addition_ratio=0.03, mass_removal_ratio=0.06') # optimization base combobox label51 = QLabel('Optimization base', self) label51.move(10, 530) self.combo51 = QComboBox(self) self.combo51.setToolTip( 'Basic principle to determine if element should remain or be removed:\n' '"stiffness" to maximize stiffness (minimize compliance),\n' '"heat" to maximize heat flow.') self.combo51.addItem("stiffness") self.combo51.addItem("heat") self.combo51.move(120, 530) # mass goal ratio label52 = QLabel('Mass goal ratio', self) label52.move(10, 560) self.textbox52 = QLineEdit(self) self.textbox52.move(120, 560) self.textbox52.resize(50, 20) self.textbox52.setText("0.4") self.textbox52.setToolTip( 'Fraction of all design domains masses to be achieved;\n' 'between 0 and 1.') # generate conf. file button button21 = QPushButton('Generate conf. file', self) button21.setToolTip( 'Writes configuration file with optimization parameters.') button21.move(10, 600) button21.clicked.connect(self.on_click21) # edit conf. file button button22 = QPushButton('Edit conf. file', self) button22.setToolTip('Opens configuration file for hand modifications.') button22.move(10, 630) button22.clicked.connect(self.on_click22) # run optimization button button23 = QPushButton('Run optimization', self) button23.setToolTip('Writes configuration file and runs optimization.') button23.move(10, 660) button23.clicked.connect(self.on_click23) # generate conf file and run optimization button button24 = QPushButton('Generate conf.\nfile and run\noptimization', self) button24.setToolTip('Writes configuration file and runs optimization.') button24.move(120, 600) button24.resize(100, 90) button24.clicked.connect(self.on_click24) # help buttons label41 = QLabel('Help', self) label41.move(440, 560) button31 = QPushButton('Example', self) button31.setToolTip( 'https://github.com/fandaL/beso/wiki/Example-4:-GUI-in-FreeCAD') button31.move(440, 590) # button31.resize(80, 50) button31.clicked.connect(self.on_click31) button32 = QPushButton('Conf. comments', self) button32.setToolTip( 'https://github.com/fandaL/beso/blob/master/beso_conf.py') button32.move(440, 620) # button32.resize(80, 50) button32.clicked.connect(self.on_click32) button33 = QPushButton('Close', self) button33.move(440, 690) # button33.resize(80, 50) button33.clicked.connect(self.on_click33) # open log file button40 = QPushButton('Open log file', self) button40.setToolTip('Opens log file in your text editor.\n' '(Does not refresh automatically.)') button40.move(10, 690) button40.clicked.connect(self.on_click40) self.on_click1() # first update self.show() # @pyqtSlot() def on_click(self): ex2 = SelectFile() self.show() self.textbox_file_name.setText(self.inp_file) def on_click1(self): # get material objects self.materials = [] self.thicknesses = [] for obj in App.ActiveDocument.Objects: if obj.Name[:23] in ["MechanicalSolidMaterial", "SolidMaterial"]: self.materials.append(obj) elif obj.Name[:17] == "ElementGeometry2D": self.thicknesses.append(obj) # update materials combo boxes self.combo.clear() self.combo.addItem("None") self.combo1.clear() self.combo1.addItem("None") self.combo2.clear() self.combo2.addItem("None") self.combo0t.clear() self.combo0t.addItem("None") self.combo1t.clear() self.combo1t.addItem("None") self.combo2t.clear() self.combo2t.addItem("None") self.widget.clear() self.widget.addItem("All defined") self.widget.addItem("Domain 0") self.widget.addItem("Domain 1") self.widget.addItem("Domain 2") self.widget.setCurrentItem(self.widget.item(0)) self.widget1.clear() self.widget1.addItem("All defined") self.widget1.addItem("Domain 0") self.widget1.addItem("Domain 1") self.widget1.addItem("Domain 2") self.widget1.setCurrentItem(self.widget1.item(0)) self.widget2.clear() self.widget2.addItem("All defined") self.widget2.addItem("Domain 0") self.widget2.addItem("Domain 1") self.widget2.addItem("Domain 2") self.widget2.setCurrentItem(self.widget2.item(0)) for mat in self.materials: self.combo.addItem(mat.Label) self.combo1.addItem(mat.Label) self.combo2.addItem(mat.Label) if self.materials: self.combo.setCurrentIndex(1) for th in self.thicknesses: self.combo0t.addItem(th.Label) self.combo1t.addItem(th.Label) self.combo2t.addItem(th.Label) def on_click21(self): """Overwrite beso_conf.py file in the macro directory""" file_name = os.path.split(self.textbox_file_name.text())[1] path = os.path.split(self.textbox_file_name.text())[0] fea = ccxtools.FemToolsCcx() fea.setup_ccx() path_calculix = fea.ccx_binary optimization_base = self.combo51.currentText() elset_id = self.combo.currentIndex() - 1 thickness_id = self.combo0t.currentIndex() - 1 if elset_id != -1: if thickness_id != -1: elset = self.materials[elset_id].Name + self.thicknesses[ thickness_id].Name else: # 0 means None thickness selected elset = self.materials[elset_id].Name + "Solid" modulus = float( self.materials[elset_id].Material["YoungsModulus"].split() [0]) # MPa if self.materials[elset_id].Material["YoungsModulus"].split( )[1] != "MPa": raise Exception(" units not recognised in " + self.materials[elset_id].Name) poisson = float( self.materials[elset_id].Material["PoissonRatio"].split()[0]) try: density = float(self.materials[elset_id].Material["Density"]. split()[0]) * 1e-12 # kg/m3 -> t/mm3 if self.materials[elset_id].Material["Density"].split( )[1] not in ["kg/m^3", "kg/m3"]: raise Exception(" units not recognised in " + self.materials[elset_id].Name) except KeyError: density = 0. try: conductivity = float( self.materials[elset_id].Material["ThermalConductivity"]. split()[0]) # W/m/K if self.materials[elset_id].Material[ "ThermalConductivity"].split()[1] != "W/m/K": raise Exception(" units not recognised in " + self.materials[elset_id].Name) except KeyError: conductivity = 0. try: if self.materials[elset_id].Material[ "ThermalExpansionCoefficient"].split()[1] == "um/m/K": expansion = float(self.materials[elset_id]. Material["ThermalExpansionCoefficient"]. split()[0]) * 1e-6 # um/m/K -> mm/mm/K elif self.materials[elset_id].Material[ "ThermalExpansionCoefficient"].split()[1] == "m/m/K": expansion = float( self.materials[elset_id]. Material["ThermalExpansionCoefficient"].split() [0]) # m/m/K -> mm/mm/K else: raise Exception(" units not recognised in " + self.materials[elset_id].Name) except KeyError: expansion = 0. try: specific_heat = float( self.materials[elset_id].Material["SpecificHeat"].split() [0]) * 1e6 # J/kg/K -> mm^2/s^2/K if self.materials[elset_id].Material["SpecificHeat"].split( )[1] != "J/kg/K": raise Exception(" units not recognised in " + self.materials[elset_id].Name) except KeyError: specific_heat = 0. if thickness_id != -1: thickness = str( self.thicknesses[thickness_id].Thickness).split()[0] # mm if str(self.thicknesses[thickness_id].Thickness).split( )[1] != "mm": raise Exception(" units not recognised in " + self.thicknesses[thickness_id].Name) else: thickness = 0. optimized = self.checkbox.isChecked() if self.textbox.text(): von_mises = float(self.textbox.text()) else: von_mises = 0. elset_id1 = self.combo1.currentIndex() - 1 thickness_id1 = self.combo0t.currentIndex() - 1 if elset_id1 != -1: if thickness_id1 != -1: elset1 = self.materials[elset_id1].Name + self.thicknesses[ thickness_id1].Name else: # 0 means None thickness selected elset1 = self.materials[elset_id1].Name + "Solid" modulus1 = float( self.materials[elset_id1].Material["YoungsModulus"].split() [0]) # MPa if self.materials[elset_id1].Material["YoungsModulus"].split( )[1] != "MPa": raise Exception(" units not recognised in " + self.materials[elset_id1].Name) poisson1 = float( self.materials[elset_id1].Material["PoissonRatio"].split()[0]) try: density1 = float(self.materials[elset_id1].Material["Density"]. split()[0]) * 1e-12 # kg/m3 -> t/mm3 if self.materials[elset_id1].Material["Density"].split( )[1] not in ["kg/m^3", "kg/m3"]: raise Exception(" units not recognised in " + self.materials[elset_id1].Name) except KeyError: density1 = 0. try: conductivity1 = float( self.materials[elset_id1].Material["ThermalConductivity"]. split()[0]) # W/m/K if self.materials[elset_id1].Material[ "ThermalConductivity"].split()[1] != "W/m/K": raise Exception(" units not recognised in " + self.materials[elset_id1].Name) except KeyError: conductivity1 = 0. try: if self.materials[elset_id1].Material[ "ThermalExpansionCoefficient"].split()[1] == "um/m/K": expansion1 = float(self.materials[elset_id1]. Material["ThermalExpansionCoefficient"]. split()[0]) * 1e-6 # um/m/K -> mm/mm/K elif self.materials[elset_id1].Material[ "ThermalExpansionCoefficient"].split()[1] == "m/m/K": expansion1 = float( self.materials[elset_id1]. Material["ThermalExpansionCoefficient"].split() [0]) # m/m/K -> mm/mm/K else: raise Exception(" units not recognised in " + self.materials[elset_id1].Name) except KeyError: expansion1 = 0. try: specific_heat1 = float( self.materials[elset_id1].Material["SpecificHeat"].split() [0]) * 1e6 # J/kg/K -> mm^2/s^2/K if self.materials[elset_id1].Material["SpecificHeat"].split( )[1] != "J/kg/K": raise Exception(" units not recognised in " + self.materials[elset_id1].Name) except KeyError: specific_heat1 = 0. if thickness_id1 != -1: thickness1 = str( self.thicknesses[thickness_id1].Thickness).split()[0] # mm if str(self.thicknesses[thickness_id1].Thickness).split( )[1] != "mm": raise Exception(" units not recognised in " + self.thicknesses[thickness_id1].Name) else: thickness1 = 0. optimized1 = self.checkbox1.isChecked() if self.textbox1.text(): von_mises1 = float(self.textbox1.text()) else: von_mises1 = 0. elset_id2 = self.combo2.currentIndex() - 1 thickness_id2 = self.combo0t.currentIndex() - 1 if elset_id2 != -1: if thickness_id2 != -1: elset2 = self.materials[elset_id2].Name + self.thicknesses[ thickness_id2].Name else: # 0 means None thickness selected else2t = self.materials[elset_id2].Name + "Solid" modulus2 = float( self.materials[elset_id2].Material["YoungsModulus"].split() [0]) # MPa if self.materials[elset_id2].Material["YoungsModulus"].split( )[1] != "MPa": raise Exception(" units not recognised in " + self.materials[elset_id2].Name) poisson2 = float( self.materials[elset_id2].Material["PoissonRatio"].split()[0]) try: density2 = float(self.materials[elset_id2].Material["Density"]. split()[0]) * 1e-12 # kg/m3 -> t/mm3 if self.materials[elset_id2].Material["Density"].split( )[1] not in ["kg/m^3", "kg/m3"]: raise Exception(" units not recognised in " + self.materials[elset_id2].Name) except KeyError: density2 = 0. try: conductivity2 = float( self.materials[elset_id2].Material["ThermalConductivity"]. split()[0]) # W/m/K if self.materials[elset_id2].Material[ "ThermalConductivity"].split()[1] != "W/m/K": raise Exception(" units not recognised in " + self.materials[elset_id2].Name) except KeyError: conductivity2 = 0. try: if self.materials[elset_id2].Material[ "ThermalExpansionCoefficient"].split()[1] == "um/m/K": expansion2 = float(self.materials[elset_id2]. Material["ThermalExpansionCoefficient"]. split()[0]) * 1e-6 # um/m/K -> mm/mm/K elif self.materials[elset_id2].Material[ "ThermalExpansionCoefficient"].split()[1] == "m/m/K": expansion2 = float( self.materials[elset_id2]. Material["ThermalExpansionCoefficient"].split() [0]) # m/m/K -> mm/mm/K else: raise Exception(" units not recognised in " + self.materials[elset_id2].Name) except KeyError: expansion2 = 0. try: specific_heat2 = float( self.materials[elset_id2].Material["SpecificHeat"].split() [0]) * 1e6 # J/kg/K -> mm^2/s^2/K if self.materials[elset_id2].Material["SpecificHeat"].split( )[1] != "J/kg/K": raise Exception(" units not recognised in " + self.materials[elset_id2].Name) except KeyError: specific_heat2 = 0. if thickness_id2 != -1: thickness2 = str( self.thicknesses[thickness_id2].Thickness).split()[0] # mm if str(self.thicknesses[thickness_id2].Thickness).split( )[1] != "mm": raise Exception(" units not recognised in " + self.thicknesses[thickness_id2].Name) else: thickness2 = 0. optimized2 = self.checkbox2.isChecked() if self.textbox2.text(): von_mises2 = float(self.textbox2.text()) else: von_mises2 = 0. with open(os.path.join(self.beso_dir, "beso_conf.py"), "w") as f: f.write( "# This is the configuration file with input parameters. It will be executed as python commands\n" ) f.write("# Written by beso_fc_gui.py at {}\n".format( datetime.datetime.now())) f.write("\n") f.write("path_calculix = '{}'\n".format(path_calculix)) f.write("path = '{}'\n".format(path)) f.write("file_name = '{}'\n".format(file_name)) f.write("\n") if elset_id != -1: f.write("elset_name = '{}'\n".format(elset)) f.write( "domain_optimized[elset_name] = {}\n".format(optimized)) f.write("domain_density[elset_name] = [{}, {}]\n".format( density * 1e-6, density)) if thickness: f.write("domain_thickness[elset_name] = [{}, {}]\n".format( thickness, thickness)) if von_mises: f.write( "domain_FI[elset_name] = [[('stress_von_Mises', {:.6})],\n" .format(von_mises * 1e6)) f.write( " [('stress_von_Mises', {:.6})]]\n" .format(von_mises)) f.write( "domain_material[elset_name] = ['*ELASTIC\\n{:.6}, {}\\n*DENSITY\\n{:.6}\\n*CONDUCTIVITY\\n" "{:.6}\\n*EXPANSION\\n{:.6}\\n*SPECIFIC HEAT\\n{:.6}\\n',\n" .format(modulus * 1e-6, poisson, density * 1e-6, conductivity * 1e-6, expansion * 1e-6, specific_heat * 1e-6)) f.write( " '*ELASTIC\\n{:.6}, {:.6}\\n*DENSITY\\n{:.6}\\n*CONDUCTIVITY\\n" "{:.6}\\n*EXPANSION\\n{:.6}\\n*SPECIFIC HEAT\\n{:.6}\\n']\n" .format(modulus, poisson, density, conductivity, expansion, specific_heat)) f.write("\n") if elset_id1 != -1: f.write("elset_name = '{}'\n".format(elset1)) f.write( "domain_optimized[elset_name] = {}\n".format(optimized1)) f.write("domain_density[elset_name] = [{}, {}]\n".format( density1 * 1e-6, density1)) if thickness1: f.write("domain_thickness[elset_name] = [{}, {}]\n".format( thickness1, thickness1)) if von_mises1: f.write( "domain_FI[elset_name] = [[('stress_von_Mises', {:.6})],\n" .format(von_mises1 * 1e6)) f.write( " [('stress_von_Mises', {:.6})]]\n" .format(von_mises1)) f.write( "domain_material[elset_name] = ['*ELASTIC\\n{:.6}, {:.6}\\n*DENSITY\\n{:.6}\\n*CONDUCTIVITY" "\\n{:.6}\\n*EXPANSION\\n{:.6}\\n*SPECIFIC HEAT\\n{:.6}\\n',\n" .format(modulus1 * 1e-6, poisson1, density1 * 1e-6, conductivity1 * 1e-6, expansion1 * 1e-6, specific_heat1 * 1e-6)) f.write( " '*ELASTIC\\n{:.6}, {:.6}\\n*DENSITY\\n{:.6}\\n*CONDUCTIVITY\\n" "{:.6}\\n" "*EXPANSION\\n{:.6}\\n*SPECIFIC HEAT\\n{:.6}\\n']\n". format(modulus1, poisson1, density1, conductivity1, expansion1, specific_heat1)) f.write("\n") if elset_id2 != -1: f.write("elset_name = '{}'\n".format(elset2)) f.write( "domain_optimized[elset_name] = {}\n".format(optimized2)) f.write("domain_density[elset_name] = [{}, {}]\n".format( density2 * 1e-6, density2)) if thickness2: f.write("domain_thickness[elset_name] = [{}, {}]\n".format( thickness2, thickness2)) if von_mises2: f.write( "domain_FI[elset_name] = [[('stress_von_Mises', {:.6})],\n" .format(von_mises2 * 1e6)) f.write( " [('stress_von_Mises', {:.6})]]\n" .format(von_mises2)) f.write( "domain_material[elset_name] = ['*ELASTIC\\n{:.6}, {:.6}\\n*DENSITY\\n{:.6}\\n*CONDUCTIVITY" "\\n{:.6}\\n*EXPANSION\\n{:.6}\\n*SPECIFIC HEAT\\n{:.6}\\n',\n" .format(modulus2 * 1e-6, poisson2, density2 * 1e-6, conductivity2 * 1e-6, expansion2 * 1e-6, specific_heat2 * 1e-6)) f.write( " '*ELASTIC\\n{:.6}, {:.6}\\n*DENSITY\\n{:.6}\\n*CONDUCTIVITY\\n" "{:.6}\\n*EXPANSION\\n{:.6}\\n*SPECIFIC HEAT\\n{:.6}\\n']\n" .format(modulus2, poisson2, density2, conductivity2, expansion2, specific_heat2)) f.write("\n") f.write("mass_goal_ratio = " + self.textbox52.text()) f.write("\n") f.write("filter_list = [") filter = self.combo6.currentText() range = self.textbox6.text() direction = self.textbox9.text() selection = [item.text() for item in self.widget.selectedItems()] filter_domains = [] if "All defined" not in selection: if "Domain 0" in selection: filter_domains.append(elset) if "Domain 1" in selection: filter_domains.append(elset1) if "Domain 2" in selection: filter_domains.append(elset2) if filter == "simple": f.write("['simple', {}".format(range)) for dn in filter_domains: f.write(", '{}'".format(dn)) f.write("],\n") elif filter == "casting": f.write("['casting', {}, ({})".format(range, direction)) for dn in filter_domains: f.write(", '{}'".format(dn)) f.write("],\n") filter1 = self.combo7.currentText() range1 = self.textbox7.text() direction1 = self.textbox10.text() selection = [item.text() for item in self.widget1.selectedItems()] filter_domains1 = [] if "All defined" not in selection: if "Domain 0" in selection: filter_domains1.append(elset) if "Domain 1" in selection: filter_domains1.append(elset1) if "Domain 2" in selection: filter_domains1.append(elset2) if filter1 == "simple": f.write(" ['simple', {}".format(range1)) for dn in filter_domains1: f.write(", '{}'".format(dn)) f.write("],\n") elif filter1 == "casting": f.write(" ['casting', {}, ({})".format( range1, direction1)) for dn in filter_domains1: f.write(", '{}'".format(dn)) f.write("],\n") filter2 = self.combo8.currentText() range2 = self.textbox8.text() direction2 = self.textbox11.text() selection = [item.text() for item in self.widget2.selectedItems()] filter_domains2 = [] if "All defined" not in selection: if "Domain 0" in selection: filter_domains2.append(elset) if "Domain 1" in selection: filter_domains2.append(elset1) if "Domain 2" in selection: filter_domains2.append(elset2) if filter2 == "simple": f.write(" ['simple', {}".format(range2)) for dn in filter_domains2: f.write(", '{}'".format(dn)) f.write("],\n") elif filter2 == "casting": f.write(" ['casting', {}, ({})".format( range2, direction2)) for dn in filter_domains2: f.write(", '{}'".format(dn)) f.write("],\n") f.write(" ]\n") f.write("\n") f.write("optimization_base = '{}'\n".format(optimization_base)) f.write("\n") slider_position = self.slider.value() if slider_position == 1: f.write("mass_addition_ratio = 0.01\n") f.write("mass_removal_ratio = 0.02\n") if slider_position == 2: f.write("mass_addition_ratio = 0.015\n") f.write("mass_removal_ratio = 0.03\n") if slider_position == 3: f.write("mass_addition_ratio = 0.03\n") f.write("mass_removal_ratio = 0.06\n") f.write("ratio_type = 'relative'\n") f.write("\n") def on_click22(self): """Open beso_conf.py in FreeCAD editor""" FreeCADGui.insert(os.path.join(self.beso_dir, "beso_conf.py")) def on_click23(self): """"Run optimization""" # run in own thread (not freezing FreeCAD): needs also to comment "plt.show()" on the end of beso_main.py # self.optimization_thread = RunOptimization("beso_main") # self.optimization_thread.start() # run in foreground (freeze FreeCAD) exec(open(os.path.join(beso_gui.beso_dir, "beso_main.py")).read()) def on_click24(self): self.on_click21() # generate beso_conf.py self.on_click23() # run optimization def on_click31(self): webbrowser.open_new_tab( "https://github.com/fandaL/beso/wiki/Example-4:-GUI-in-FreeCAD") def on_click32(self): webbrowser.open_new_tab( "https://github.com/fandaL/beso/blob/master/beso_conf.py") def on_click33(self): self.close() def on_click40(self): """Open log file""" if self.textbox_file_name.text() in [ "None analysis file selected", "" ]: print("None analysis file selected") else: log_file = os.path.normpath(self.textbox_file_name.text()[:-4] + ".log") webbrowser.open(log_file) def on_change(self): if self.combo.currentText() == "None": self.combo0t.setEnabled(False) self.checkbox.setEnabled(False) self.textbox.setEnabled(False) else: self.combo0t.setEnabled(True) self.checkbox.setEnabled(True) self.textbox.setEnabled(True) def on_change1(self): if self.combo1.currentText() == "None": self.combo1t.setEnabled(False) self.checkbox1.setEnabled(False) self.textbox1.setEnabled(False) else: self.combo1t.setEnabled(True) self.checkbox1.setEnabled(True) self.textbox1.setEnabled(True) def on_change2(self): if self.combo2.currentText() == "None": self.combo2t.setEnabled(False) self.checkbox2.setEnabled(False) self.textbox2.setEnabled(False) else: self.combo2t.setEnabled(True) self.checkbox2.setEnabled(True) self.textbox2.setEnabled(True) def on_change6(self): if self.combo6.currentText() == "None": self.textbox6.setEnabled(False) self.textbox9.setEnabled(False) self.widget.setEnabled(False) elif self.combo6.currentText() == "casting": self.textbox6.setEnabled(True) self.textbox9.setEnabled(True) self.widget.setEnabled(True) else: self.textbox6.setEnabled(True) self.textbox9.setEnabled(False) self.widget.setEnabled(True) def on_change7(self): if self.combo7.currentText() == "None": self.textbox7.setEnabled(False) self.textbox10.setEnabled(False) self.widget1.setEnabled(False) elif self.combo7.currentText() == "casting": self.textbox7.setEnabled(True) self.textbox10.setEnabled(True) self.widget1.setEnabled(True) else: self.textbox7.setEnabled(True) self.textbox10.setEnabled(False) self.widget1.setEnabled(True) def on_change8(self): if self.combo8.currentText() == "None": self.textbox8.setEnabled(False) self.textbox11.setEnabled(False) self.widget2.setEnabled(False) elif self.combo8.currentText() == "casting": self.textbox8.setEnabled(True) self.textbox11.setEnabled(True) self.widget2.setEnabled(True) else: self.textbox8.setEnabled(True) self.textbox11.setEnabled(False) self.widget2.setEnabled(True)
class DataBrowser(QWidget, Ui_DataBrowser): """ @since: 2011-08-24 """ __author__ = "Moritz Wade" __contact__ = "*****@*****.**" __copyright__ = "Zuse Institute Berlin 2011" def __init__(self, parent, id, dataSet): super(DataBrowser, self).__init__(parent) self.setupUi(self) self._simWorkbench = None self.dataService = None self.id = id self.data = dataSet self.optionsService = OptionsService() # create the custom selectable table header self.selectableHeader = SelectableTableHeader(Qt.Horizontal, self.tableView) self.selectableHeader.setNonSelectableIndexes([0]) self.selectableHeader.sectionSelectionChanged.connect(self.on_columnSelectionChanged) self.tableView.setHorizontalHeader(self.selectableHeader) # create the data model self.dataModel = DataBrowserModel(self, self.id, self.data) self.tableView.setModel(self.dataModel) self._setUpSelectionCheckBox() self._updateInfoPane() if not self.optionsService.getDebug(): self.groupBoxPerturbation.setVisible(False) def getId(self): return self.id def setSimulationWorkbench(self, simWorkbench): self._simWorkbench = simWorkbench def getSelectionCheckBox(self): return self._selectionCheckBox def isSelected(self): checkState = self._selectionCheckBox.checkState() return True if checkState == Qt.Checked else False def _setUpSelectionCheckBox(self): self._selectionCheckBox = QCheckBox() self._selectionCheckBox.setChecked(True) infoText = "Select or deselect this data (e.g. to be included in plots and computations)." self._selectionCheckBox.setStatusTip(infoText) self._selectionCheckBox.setToolTip(infoText) self._selectionCheckBox.stateChanged.connect(self._selectionChanged) def _updateInfoPane(self): """ Updates the info pane with basic info about the loaded data and the data file (if any). """ self.lineEditInfoSpecies.setText(str(self.data.getNumOfRealData())) self.lineEditInfoDataType.setText(self.data.type) # self.lineEditInfoFormat.setText(self.data.format) filepath = self.data.filename if filepath and os.path.exists(filepath): self.lineEditInfoPath.setText(filepath) filesize = os.path.getsize(filepath) filesize = filesize / 1024 # displaying kB self.lineEditInfoFilesize.setText("%s kB" % filesize) timeLastModifiedEpoch = os.path.getmtime(filepath) timeLastModified = time.strftime("%a, %d %b %Y %H:%M:%S", time.localtime(timeLastModifiedEpoch)) self.lineEditInfoLastModified.setText(str(timeLastModified)) else: noFileText = "No File" self.lineEditInfoPath.setText(noFileText) self.lineEditInfoFilesize.setText(noFileText) self.lineEditInfoLastModified.setText(noFileText) def remove(self): """ Cleans up stuff then destroys self. It's not sure whether this is really needed but it might serve to close some memory holes (e.g. dangling references somewhere). """ del self.dataModel del self @Slot() def on_actionPlot_triggered(self): dataDict = {self.data.getId(): self.data} self._simWorkbench.plotExpData(dataDict) @Slot() def on_buttonPerturb_clicked(self): """ Perturbs the data by the % given in self.spinBoxPerturb. """ percentage = self.spinBoxPerturb.value() factor = percentage / 100.0 for entity, entityData in self.data.getData().items(): if not entityData.isSelected(): continue id = entity.getId() if type(entity) == EntityData else str(entity) logging.debug("Perturbing data of EntityData: %s" % id) for i in xrange(len(entityData.datapoints)): value = entityData.datapoints[i] if not value: # for None values continue fraction = value * factor # fraction of value that will be added or substracted #newValue = value + random.uniform(-1 * fraction, fraction) newValue = value + random.uniform(-1, 1) * fraction # newValue = value - fraction if random.random() < 0.5 else value + fraction entityData.setDatapoint(i, newValue) @Slot("") def on_buttonSaveAs_clicked(self): logging.debug("Saving data. Displaying file chooser...") file_choices = "Tab-Delimited Text File *.txt (*.txt)" path = unicode(QFileDialog.getSaveFileName(self, 'Save file', '', file_choices)[0]) if not path.endswith(".txt"): path += ".txt" if path: if not self.dataService: self.dataService = DataService() id = self.data.getId() self.dataService.save_data_as_csv(id, path) logging.info("Saved data to %s" % path) @Slot() def on_buttonTimeshift_clicked(self): """ Timeshift data within this DataBrowser (i.e. DataSet). Not only shift the global timepoints but also the timepoint lists within the individiual EntityData objects. """ try: shiftValue = float(self.lineEditTimeshift.text()) self.dataModel.doTimeshift(shiftValue) except Exception, e: logging.error("DataBrowser.on_buttonTimeshift_clicked(): Error while timeshifting the data: %s" % e)
class DataBrowser(QWidget, Ui_DataBrowser): """ @since: 2011-08-24 """ __author__ = "Moritz Wade" __contact__ = "*****@*****.**" __copyright__ = "Zuse Institute Berlin 2011" def __init__(self, parent, id, dataSet): super(DataBrowser, self).__init__(parent) self.setupUi(self) self._simWorkbench = None self.dataService = None self.id = id self.data = dataSet self.optionsService = OptionsService() # create the custom selectable table header self.selectableHeader = SelectableTableHeader(Qt.Horizontal, self.tableView) self.selectableHeader.setNonSelectableIndexes([0]) self.selectableHeader.sectionSelectionChanged.connect( self.on_columnSelectionChanged) self.tableView.setHorizontalHeader(self.selectableHeader) # create the data model self.dataModel = DataBrowserModel(self, self.id, self.data) self.tableView.setModel(self.dataModel) self._setUpSelectionCheckBox() self._updateInfoPane() if not self.optionsService.getDebug(): self.groupBoxPerturbation.setVisible(False) def getId(self): return self.id def setSimulationWorkbench(self, simWorkbench): self._simWorkbench = simWorkbench def getSelectionCheckBox(self): return self._selectionCheckBox def isSelected(self): checkState = self._selectionCheckBox.checkState() return True if checkState == Qt.Checked else False def _setUpSelectionCheckBox(self): self._selectionCheckBox = QCheckBox() self._selectionCheckBox.setChecked(True) infoText = "Select or deselect this data (e.g. to be included in plots and computations)." self._selectionCheckBox.setStatusTip(infoText) self._selectionCheckBox.setToolTip(infoText) self._selectionCheckBox.stateChanged.connect(self._selectionChanged) def _updateInfoPane(self): """ Updates the info pane with basic info about the loaded data and the data file (if any). """ self.lineEditInfoSpecies.setText(str(self.data.getNumOfRealData())) self.lineEditInfoDataType.setText(self.data.type) # self.lineEditInfoFormat.setText(self.data.format) filepath = self.data.filename if filepath and os.path.exists(filepath): self.lineEditInfoPath.setText(filepath) filesize = os.path.getsize(filepath) filesize = filesize / 1024 # displaying kB self.lineEditInfoFilesize.setText("%s kB" % filesize) timeLastModifiedEpoch = os.path.getmtime(filepath) timeLastModified = time.strftime( "%a, %d %b %Y %H:%M:%S", time.localtime(timeLastModifiedEpoch)) self.lineEditInfoLastModified.setText(str(timeLastModified)) else: noFileText = "No File" self.lineEditInfoPath.setText(noFileText) self.lineEditInfoFilesize.setText(noFileText) self.lineEditInfoLastModified.setText(noFileText) def remove(self): """ Cleans up stuff then destroys self. It's not sure whether this is really needed but it might serve to close some memory holes (e.g. dangling references somewhere). """ del self.dataModel del self @Slot() def on_actionPlot_triggered(self): dataDict = {self.data.getId(): self.data} self._simWorkbench.plotExpData(dataDict) @Slot() def on_buttonPerturb_clicked(self): """ Perturbs the data by the % given in self.spinBoxPerturb. """ percentage = self.spinBoxPerturb.value() factor = percentage / 100.0 for entity, entityData in self.data.getData().items(): if not entityData.isSelected(): continue id = entity.getId() if type(entity) == EntityData else str(entity) logging.debug("Perturbing data of EntityData: %s" % id) for i in xrange(len(entityData.datapoints)): value = entityData.datapoints[i] if not value: # for None values continue fraction = value * factor # fraction of value that will be added or substracted #newValue = value + random.uniform(-1 * fraction, fraction) newValue = value + random.uniform(-1, 1) * fraction # newValue = value - fraction if random.random() < 0.5 else value + fraction entityData.setDatapoint(i, newValue) @Slot("") def on_buttonSaveAs_clicked(self): logging.debug("Saving data. Displaying file chooser...") file_choices = "Tab-Delimited Text File *.txt (*.txt)" path = unicode( QFileDialog.getSaveFileName(self, 'Save file', '', file_choices)[0]) if not path.endswith(".txt"): path += ".txt" if path: if not self.dataService: self.dataService = DataService() id = self.data.getId() self.dataService.save_data_as_csv(id, path) logging.info("Saved data to %s" % path) @Slot() def on_buttonTimeshift_clicked(self): """ Timeshift data within this DataBrowser (i.e. DataSet). Not only shift the global timepoints but also the timepoint lists within the individiual EntityData objects. """ try: shiftValue = float(self.lineEditTimeshift.text()) self.dataModel.doTimeshift(shiftValue) except Exception, e: logging.error( "DataBrowser.on_buttonTimeshift_clicked(): Error while timeshifting the data: %s" % e)
class ScaleView(QGroupBox): '''The box containing the rate value''' def __init__(self, title = 'Window Limits', parent = None): '''Initialize''' super(ScaleView, self).__init__(parent) self.setTitle(title) self._createWidgets() def _createWidgets(self): '''Create the widgets contained in this box''' # The three choosers self.xmin = QLineEdit(self) self.xmin.setToolTip(ttt('The lower limit of the plot, in ' 'wavenumbers')) self.xmax = QLineEdit(self) self.xmax.setToolTip(ttt('The upper limit of the plot, in ' 'wavenumbers')) self.reverse = QCheckBox("Reverse Limits", self) self.reverse.setToolTip(ttt('Display plot with higher frequencies on ' 'the left, not the right')) # Set validators for limits self.xmin.setValidator(QIntValidator(300, 3000, self.xmin)) self.xmax.setValidator(QIntValidator(300, 3000, self.xmax)) # The wavelength selection self.wavenum = QLineEdit(' ') self.wavenum.setReadOnly(True) self.intense = QLineEdit(' ') self.intense.setReadOnly(True) def initUI(self): '''Lays out the widgets''' total = QHBoxLayout() total.addWidget(QLabel("Wavenum: ")) total.addWidget(self.wavenum) total.addWidget(QLabel("Intens.: ")) total.addWidget(self.intense) total.addWidget(QLabel("Lower Limit")) total.addWidget(self.xmin) total.addStretch() total.addWidget(self.reverse) total.addStretch() total.addWidget(QLabel("Upper Limit")) total.addWidget(self.xmax) self.setLayout(total) def makeConnections(self): '''Connect the widgets together''' # If any changes happen, reset the scale self.xmin.editingFinished.connect(self.resetScale) self.xmax.editingFinished.connect(self.resetScale) self.reverse.clicked.connect(self.resetScale) def setModel(self, model): '''Attaches models to the views''' self.model = model def setValue(self, xmin, xmax, reversed): '''Manually sets the values that are viewed''' self.xmin.setText(str(xmin)) self.xmax.setText(str(xmax)) self.reverse.setChecked(reversed) self.reverse.clicked.emit() ####### # SLOTS ####### def resetScale(self): '''Checks that the given scale is valid, then resets if so''' try: xmin = int(self.xmin.text()) except ValueError: return try: xmax = int(self.xmax.text()) except ValueError: return reverse = self.reverse.isChecked() if xmin > xmax: err = "Lower limit cannot be greater than upper limit" error.showMessage(err) return self.model.setScale(xmin, xmax, reverse) def setSelection(self, x, y): '''Displays the current selection''' x = max(min(x, float(self.xmax.text())), float(self.xmin.text())) y = max(min(y, 1.0), 0.0) self.wavenum.setText('{0:.1f}'.format(x)) self.intense.setText('{0:.3f}'.format(y))
class ConfigDialog(QtGui.QDialog): pressedclosebutton = False moreToggling = False def moreToggled(self): if self.moreToggling == False: self.moreToggling = True if self.showmoreCheckbox.isChecked() and self.showmoreCheckbox.isVisible(): self.showmoreCheckbox.setChecked(False) self.moreSettingsGroup.setChecked(True) self.moreSettingsGroup.show() self.showmoreCheckbox.hide() self.saveMoreState(True) else: self.moreSettingsGroup.setChecked(False) self.moreSettingsGroup.hide() self.showmoreCheckbox.show() self.saveMoreState(False) self.moreToggling = False self.adjustSize() self.setFixedSize(self.sizeHint()) def runButtonTextUpdate(self): if (self.donotstoreCheckbox.isChecked()): self.runButton.setText(getMessage("en", "run-label")) else: self.runButton.setText(getMessage("en", "storeandrun-label")) def openHelp(self): self.QtGui.QDesktopServices.openUrl("http://syncplay.pl/guide/client/") def _tryToFillPlayerPath(self, playerpath, playerpathlist): settings = QSettings("Syncplay", "PlayerList") settings.beginGroup("PlayerList") savedPlayers = settings.value("PlayerList", []) if(not isinstance(savedPlayers, list)): savedPlayers = [] playerpathlist = list(set(os.path.normcase(os.path.normpath(path)) for path in set(playerpathlist + savedPlayers))) settings.endGroup() foundpath = "" if playerpath != None and playerpath != "": if not os.path.isfile(playerpath): expandedpath = PlayerFactory().getExpandedPlayerPathByPath(playerpath) if expandedpath != None and os.path.isfile(expandedpath): playerpath = expandedpath if os.path.isfile(playerpath): foundpath = playerpath self.executablepathCombobox.addItem(foundpath) for path in playerpathlist: if(os.path.isfile(path) and os.path.normcase(os.path.normpath(path)) != os.path.normcase(os.path.normpath(foundpath))): self.executablepathCombobox.addItem(path) if foundpath == "": foundpath = path if foundpath != "": settings.beginGroup("PlayerList") playerpathlist.append(os.path.normcase(os.path.normpath(foundpath))) settings.setValue("PlayerList", list(set(os.path.normcase(os.path.normpath(path)) for path in set(playerpathlist)))) settings.endGroup() return(foundpath) def updateExecutableIcon(self): currentplayerpath = unicode(self.executablepathCombobox.currentText()) iconpath = PlayerFactory().getPlayerIconByPath(currentplayerpath) if iconpath != None and iconpath != "": self.executableiconImage.load(self.resourcespath + iconpath) self.executableiconLabel.setPixmap(QtGui.QPixmap.fromImage(self.executableiconImage)) else: self.executableiconLabel.setPixmap(QtGui.QPixmap.fromImage(QtGui.QImage())) def browsePlayerpath(self): options = QtGui.QFileDialog.Options() defaultdirectory = "" browserfilter = "All files (*)" if os.name == 'nt': browserfilter = "Executable files (*.exe);;All files (*)" if "PROGRAMFILES(X86)" in os.environ: defaultdirectory = os.environ["ProgramFiles(x86)"] elif "PROGRAMFILES" in os.environ: defaultdirectory = os.environ["ProgramFiles"] elif "PROGRAMW6432" in os.environ: defaultdirectory = os.environ["ProgramW6432"] elif sys.platform.startswith('linux'): defaultdirectory = "/usr/bin" fileName, filtr = QtGui.QFileDialog.getOpenFileName(self, "Browse for media player executable", defaultdirectory, browserfilter, "", options) if fileName: self.executablepathCombobox.setEditText(os.path.normpath(fileName)) def loadMediaBrowseSettings(self): settings = QSettings("Syncplay", "MediaBrowseDialog") settings.beginGroup("MediaBrowseDialog") self.mediadirectory = settings.value("mediadir", "") settings.endGroup() def saveMediaBrowseSettings(self): settings = QSettings("Syncplay", "MediaBrowseDialog") settings.beginGroup("MediaBrowseDialog") settings.setValue("mediadir", self.mediadirectory) settings.endGroup() def getMoreState(self): settings = QSettings("Syncplay", "MoreSettings") settings.beginGroup("MoreSettings") morestate = unicode.lower(unicode(settings.value("ShowMoreSettings", "false"))) settings.endGroup() if morestate == "true": return(True) else: return(False) def saveMoreState(self, morestate): settings = QSettings("Syncplay", "MoreSettings") settings.beginGroup("MoreSettings") settings.setValue("ShowMoreSettings", morestate) settings.endGroup() def browseMediapath(self): self.loadMediaBrowseSettings() options = QtGui.QFileDialog.Options() if (os.path.isdir(self.mediadirectory)): defaultdirectory = self.mediadirectory elif (os.path.isdir(QDesktopServices.storageLocation(QDesktopServices.MoviesLocation))): defaultdirectory = QDesktopServices.storageLocation(QDesktopServices.MoviesLocation) elif (os.path.isdir(QDesktopServices.storageLocation(QDesktopServices.HomeLocation))): defaultdirectory = QDesktopServices.storageLocation(QDesktopServices.HomeLocation) else: defaultdirectory = "" browserfilter = "All files (*)" fileName, filtr = QtGui.QFileDialog.getOpenFileName(self,"Browse for media files",defaultdirectory, browserfilter, "", options) if fileName: self.mediapathTextbox.setText(os.path.normpath(fileName)) self.mediadirectory = os.path.dirname(fileName) self.saveMediaBrowseSettings() def _saveDataAndLeave(self): self.config['host'] = self.hostTextbox.text() if ":" in self.hostTextbox.text() else self.hostTextbox.text() + ":" + unicode(constants.DEFAULT_PORT) self.config['name'] = self.usernameTextbox.text() self.config['room'] = self.defaultroomTextbox.text() self.config['password'] = self.serverpassTextbox.text() self.config['playerPath'] = unicode(self.executablepathCombobox.currentText()) if self.mediapathTextbox.text() == "": self.config['file'] = None elif os.path.isfile(os.path.abspath(self.mediapathTextbox.text())): self.config['file'] = os.path.abspath(self.mediapathTextbox.text()) else: self.config['file'] = unicode(self.mediapathTextbox.text()) if self.alwaysshowCheckbox.isChecked() == True: self.config['forceGuiPrompt'] = True else: self.config['forceGuiPrompt'] = False if self.donotstoreCheckbox.isChecked() == True: self.config['noStore'] = True else: self.config['noStore'] = False if self.slowdownCheckbox.isChecked() == True: self.config['slowOnDesync'] = True else: self.config['slowOnDesync'] = False if self.pauseonleaveCheckbox.isChecked() == True: self.config['pauseOnLeave'] = True else: self.config['pauseOnLeave'] = False if constants.SHOW_REWIND_ON_DESYNC_CHECKBOX == True: if self.rewindCheckbox.isChecked() == True: self.config['rewindOnDesync'] = True else: self.config['rewindOnDesync'] = False self.config['malUsername'] = self.malusernameTextbox.text() self.config['malPassword'] = self.malpasswordTextbox.text() if self.filenameprivacySendRawOption.isChecked() == True: self.config['filenamePrivacyMode'] = constants.PRIVACY_SENDRAW_MODE elif self.filenameprivacySendHashedOption.isChecked() == True: self.config['filenamePrivacyMode'] = constants.PRIVACY_SENDHASHED_MODE elif self.filenameprivacyDontSendOption.isChecked() == True: self.config['filenamePrivacyMode'] = constants.PRIVACY_DONTSEND_MODE if self.filesizeprivacySendRawOption.isChecked() == True: self.config['filesizePrivacyMode'] = constants.PRIVACY_SENDRAW_MODE elif self.filesizeprivacySendHashedOption.isChecked() == True: self.config['filesizePrivacyMode'] = constants.PRIVACY_SENDHASHED_MODE elif self.filesizeprivacyDontSendOption.isChecked() == True: self.config['filesizePrivacyMode'] = constants.PRIVACY_DONTSEND_MODE self.pressedclosebutton = True self.close() return def closeEvent(self, event): if self.pressedclosebutton == False: sys.exit() raise GuiConfiguration.WindowClosed event.accept() def dragEnterEvent(self, event): data = event.mimeData() urls = data.urls() if (urls and urls[0].scheme() == 'file'): event.acceptProposedAction() def dropEvent(self, event): data = event.mimeData() urls = data.urls() if (urls and urls[0].scheme() == 'file'): if sys.platform.startswith('linux'): dropfilepath = unicode(urls[0].path()) else: dropfilepath = unicode(urls[0].path())[1:] # Removes starting slash if dropfilepath[-4:].lower() == ".exe": self.executablepathCombobox.setEditText(dropfilepath) else: self.mediapathTextbox.setText(dropfilepath) def __init__(self, config, playerpaths, error): from syncplay import utils self.config = config self.datacleared = False if config['clearGUIData'] == True: settings = QSettings("Syncplay","PlayerList") settings.clear() settings = QSettings("Syncplay","MediaBrowseDialog") settings.clear() settings = QSettings("Syncplay","MainWindow") settings.clear() settings = QSettings("Syncplay","MoreSettings") settings.clear() self.datacleared = True self.QtGui = QtGui self.error = error if sys.platform.startswith('linux'): resourcespath = utils.findWorkingDir() + "/resources/" else: resourcespath = utils.findWorkingDir() + "\\resources\\" self.resourcespath = resourcespath super(ConfigDialog, self).__init__() self.setWindowTitle(getMessage("en", "config-window-title")) self.setWindowFlags(self.windowFlags() & Qt.WindowCloseButtonHint & ~Qt.WindowContextHelpButtonHint) self.setWindowIcon(QtGui.QIcon(resourcespath + "syncplay.png")) if(config['host'] == None): host = "" elif(":" in config['host']): host = config['host'] else: host = config['host']+":"+str(config['port']) self.connectionSettingsGroup = QtGui.QGroupBox(getMessage("en", "connection-group-title")) self.hostTextbox = QLineEdit(host, self) self.hostLabel = QLabel(getMessage("en", "host-label"), self) self.usernameTextbox = QLineEdit(config['name'],self) self.serverpassLabel = QLabel(getMessage("en", "password-label"), self) self.defaultroomTextbox = QLineEdit(config['room'],self) self.usernameLabel = QLabel(getMessage("en", "username-label"), self) self.serverpassTextbox = QLineEdit(config['password'],self) self.defaultroomLabel = QLabel(getMessage("en", "room-label"), self) if (constants.SHOW_TOOLTIPS == True): self.hostLabel.setToolTip(getMessage("en", "host-tooltip")) self.hostTextbox.setToolTip(getMessage("en", "host-tooltip")) self.usernameLabel.setToolTip(getMessage("en", "username-tooltip")) self.usernameTextbox.setToolTip(getMessage("en", "username-tooltip")) self.serverpassLabel.setToolTip(getMessage("en", "password-tooltip")) self.serverpassTextbox.setToolTip(getMessage("en", "password-tooltip")) self.defaultroomLabel.setToolTip(getMessage("en", "room-tooltip")) self.defaultroomTextbox.setToolTip(getMessage("en", "room-tooltip")) self.connectionSettingsLayout = QtGui.QGridLayout() self.connectionSettingsLayout.addWidget(self.hostLabel, 0, 0) self.connectionSettingsLayout.addWidget(self.hostTextbox, 0, 1) self.connectionSettingsLayout.addWidget(self.serverpassLabel, 1, 0) self.connectionSettingsLayout.addWidget(self.serverpassTextbox, 1, 1) self.connectionSettingsLayout.addWidget(self.usernameLabel, 2, 0) self.connectionSettingsLayout.addWidget(self.usernameTextbox, 2, 1) self.connectionSettingsLayout.addWidget(self.defaultroomLabel, 3, 0) self.connectionSettingsLayout.addWidget(self.defaultroomTextbox, 3, 1) self.connectionSettingsGroup.setLayout(self.connectionSettingsLayout) self.mediaplayerSettingsGroup = QtGui.QGroupBox(getMessage("en", "media-setting-title")) self.executableiconImage = QtGui.QImage() self.executableiconLabel = QLabel(self) self.executableiconLabel.setMinimumWidth(16) self.executablepathCombobox = QtGui.QComboBox(self) self.executablepathCombobox.setEditable(True) self.executablepathCombobox.currentIndexChanged.connect(self.updateExecutableIcon) self.executablepathCombobox.setEditText(self._tryToFillPlayerPath(config['playerPath'], playerpaths)) self.executablepathCombobox.setMinimumWidth(200) self.executablepathCombobox.setMaximumWidth(200) self.executablepathCombobox.editTextChanged.connect(self.updateExecutableIcon) self.executablepathLabel = QLabel(getMessage("en", "executable-path-label"), self) self.executablebrowseButton = QtGui.QPushButton(QtGui.QIcon(resourcespath + 'folder_explore.png'),getMessage("en", "browse-label")) self.executablebrowseButton.clicked.connect(self.browsePlayerpath) self.mediapathTextbox = QLineEdit(config['file'], self) self.mediapathLabel = QLabel(getMessage("en", "media-path-label"), self) self.mediabrowseButton = QtGui.QPushButton(QtGui.QIcon(resourcespath + 'folder_explore.png'),getMessage("en", "browse-label")) self.mediabrowseButton.clicked.connect(self.browseMediapath) if (constants.SHOW_TOOLTIPS == True): self.executablepathLabel.setToolTip(getMessage("en", "executable-path-tooltip")) self.executablepathCombobox.setToolTip(getMessage("en", "executable-path-tooltip")) self.mediapathLabel.setToolTip(getMessage("en", "media-path-tooltip")) self.mediapathTextbox.setToolTip(getMessage("en", "media-path-tooltip")) if constants.SHOW_REWIND_ON_DESYNC_CHECKBOX == True: self.rewindCheckbox = QCheckBox(getMessage("en", "rewind-label")) if (constants.SHOW_TOOLTIPS == True): self.rewindCheckbox.setToolTip(getMessage("en", "rewind-tooltip")) self.mediaplayerSettingsLayout = QtGui.QGridLayout() self.mediaplayerSettingsLayout.addWidget(self.executablepathLabel, 0, 0) self.mediaplayerSettingsLayout.addWidget(self.executableiconLabel, 0, 1) self.mediaplayerSettingsLayout.addWidget(self.executablepathCombobox, 0, 2) self.mediaplayerSettingsLayout.addWidget(self.executablebrowseButton, 0, 3) self.mediaplayerSettingsLayout.addWidget(self.mediapathLabel, 1, 0) self.mediaplayerSettingsLayout.addWidget(self.mediapathTextbox , 1, 2) self.mediaplayerSettingsLayout.addWidget(self.mediabrowseButton , 1, 3) self.mediaplayerSettingsGroup.setLayout(self.mediaplayerSettingsLayout) self.moreSettingsGroup = QtGui.QGroupBox(getMessage("en", "more-title")) self.moreSettingsGroup.setCheckable(True) self.malSettingsSplit = QtGui.QSplitter(self) self.malusernameTextbox = QLineEdit(config['malUsername'],self) self.malusernameTextbox.setMaximumWidth(115) self.malusernameLabel = QLabel(getMessage("en", "mal-username-label"), self) self.malpasswordTextbox = QLineEdit(config['malPassword'],self) self.malpasswordTextbox.setEchoMode(QtGui.QLineEdit.Password) self.malpasswordLabel = QLabel(getMessage("en", "mal-password-label"), self) ### <MAL DISABLE> self.malpasswordTextbox.hide() self.malpasswordLabel.hide() self.malusernameTextbox.hide() self.malusernameLabel.hide() ### </MAL DISABLE> self.filenameprivacyLabel = QLabel(getMessage("en", "filename-privacy-label"), self) self.filenameprivacyButtonGroup = QButtonGroup() self.filenameprivacySendRawOption = QRadioButton(getMessage("en", "privacy-sendraw-option")) self.filenameprivacySendHashedOption = QRadioButton(getMessage("en", "privacy-sendhashed-option")) self.filenameprivacyDontSendOption = QRadioButton(getMessage("en", "privacy-dontsend-option")) self.filenameprivacyButtonGroup.addButton(self.filenameprivacySendRawOption) self.filenameprivacyButtonGroup.addButton(self.filenameprivacySendHashedOption) self.filenameprivacyButtonGroup.addButton(self.filenameprivacyDontSendOption) self.filesizeprivacyLabel = QLabel(getMessage("en", "filesize-privacy-label"), self) self.filesizeprivacyButtonGroup = QButtonGroup() self.filesizeprivacySendRawOption = QRadioButton(getMessage("en", "privacy-sendraw-option")) self.filesizeprivacySendHashedOption = QRadioButton(getMessage("en", "privacy-sendhashed-option")) self.filesizeprivacyDontSendOption = QRadioButton(getMessage("en", "privacy-dontsend-option")) self.filesizeprivacyButtonGroup.addButton(self.filesizeprivacySendRawOption) self.filesizeprivacyButtonGroup.addButton(self.filesizeprivacySendHashedOption) self.filesizeprivacyButtonGroup.addButton(self.filesizeprivacyDontSendOption) self.slowdownCheckbox = QCheckBox(getMessage("en", "slowdown-label")) self.pauseonleaveCheckbox = QCheckBox(getMessage("en", "pauseonleave-label")) self.alwaysshowCheckbox = QCheckBox(getMessage("en", "alwayshow-label")) self.donotstoreCheckbox = QCheckBox(getMessage("en", "donotstore-label")) filenamePrivacyMode = config['filenamePrivacyMode'] if filenamePrivacyMode == constants.PRIVACY_DONTSEND_MODE: self.filenameprivacyDontSendOption.setChecked(True) elif filenamePrivacyMode == constants.PRIVACY_SENDHASHED_MODE: self.filenameprivacySendHashedOption.setChecked(True) else: self.filenameprivacySendRawOption.setChecked(True) filesizePrivacyMode = config['filesizePrivacyMode'] if filesizePrivacyMode == constants.PRIVACY_DONTSEND_MODE: self.filesizeprivacyDontSendOption.setChecked(True) elif filesizePrivacyMode == constants.PRIVACY_SENDHASHED_MODE: self.filesizeprivacySendHashedOption.setChecked(True) else: self.filesizeprivacySendRawOption.setChecked(True) if config['slowOnDesync'] == True: self.slowdownCheckbox.setChecked(True) if constants.SHOW_REWIND_ON_DESYNC_CHECKBOX == True and config['rewindOnDesync'] == True: self.rewindCheckbox.setChecked(True) if config['pauseOnLeave'] == True: self.pauseonleaveCheckbox.setChecked(True) if (constants.SHOW_TOOLTIPS == True): self.malusernameLabel.setToolTip(getMessage("en", "mal-username-tooltip")) self.malusernameTextbox.setToolTip(getMessage("en", "mal-username-tooltip")) self.malpasswordLabel.setToolTip(getMessage("en", "mal-password-tooltip")) self.malpasswordTextbox.setToolTip(getMessage("en", "mal-password-tooltip")) self.filenameprivacyLabel.setToolTip(getMessage("en", "filename-privacy-tooltip")) self.filenameprivacySendRawOption.setToolTip(getMessage("en", "privacy-sendraw-tooltip")) self.filenameprivacySendHashedOption.setToolTip(getMessage("en", "privacy-sendhashed-tooltip")) self.filenameprivacyDontSendOption.setToolTip(getMessage("en", "privacy-dontsend-tooltip")) self.filesizeprivacyLabel.setToolTip(getMessage("en", "filesize-privacy-tooltip")) self.filesizeprivacySendRawOption.setToolTip(getMessage("en", "privacy-sendraw-tooltip")) self.filesizeprivacySendHashedOption.setToolTip(getMessage("en", "privacy-sendhashed-tooltip")) self.filesizeprivacyDontSendOption.setToolTip(getMessage("en", "privacy-dontsend-tooltip")) self.slowdownCheckbox.setToolTip(getMessage("en", "slowdown-tooltip")) self.pauseonleaveCheckbox.setToolTip(getMessage("en", "pauseonleave-tooltip")) self.alwaysshowCheckbox.setToolTip(getMessage("en", "alwayshow-tooltip")) self.donotstoreCheckbox.setToolTip(getMessage("en", "donotstore-tooltip")) self.slowdownCheckbox.setToolTip(getMessage("en", "slowdown-tooltip")) self.moreSettingsLayout = QtGui.QGridLayout() self.privacySettingsLayout = QtGui.QGridLayout() self.privacyFrame = QtGui.QFrame() self.privacyFrame.setLineWidth(0) self.privacyFrame.setMidLineWidth(0) self.privacySettingsLayout.setContentsMargins(0,0,0,0) self.privacySettingsLayout.addWidget(self.filenameprivacyLabel, 0, 0) self.privacySettingsLayout.addWidget(self.filenameprivacySendRawOption, 0, 1, Qt.AlignRight) self.privacySettingsLayout.addWidget(self.filenameprivacySendHashedOption, 0,2, Qt.AlignRight) self.privacySettingsLayout.addWidget(self.filenameprivacyDontSendOption, 0, 3, Qt.AlignRight) self.privacySettingsLayout.addWidget(self.filesizeprivacyLabel, 1, 0) self.privacySettingsLayout.addWidget(self.filesizeprivacySendRawOption, 1, 1, Qt.AlignRight) self.privacySettingsLayout.addWidget(self.filesizeprivacySendHashedOption, 1, 2, Qt.AlignRight) self.privacySettingsLayout.addWidget(self.filesizeprivacyDontSendOption, 1, 3, Qt.AlignRight) self.privacyFrame.setLayout(self.privacySettingsLayout) self.moreSettingsLayout.addWidget(self.privacyFrame, 0, 0, 1, 4) self.moreSettingsLayout.addWidget(self.malusernameLabel , 1, 0) self.moreSettingsLayout.addWidget(self.malusernameTextbox, 1, 1) self.moreSettingsLayout.addWidget(self.malpasswordLabel , 1, 2) self.moreSettingsLayout.addWidget(self.malpasswordTextbox, 1, 3) self.moreSettingsLayout.addWidget(self.slowdownCheckbox, 2, 0,1,4) if constants.SHOW_REWIND_ON_DESYNC_CHECKBOX == True: self.moreSettingsLayout.addWidget(self.rewindCheckbox, 3, 0, 1, 4) self.moreSettingsLayout.addWidget(self.pauseonleaveCheckbox, 4, 0, 1, 4) self.moreSettingsLayout.addWidget(self.alwaysshowCheckbox, 5, 0, 1, 4) self.moreSettingsLayout.addWidget(self.donotstoreCheckbox, 6, 0, 1, 4) self.moreSettingsGroup.setLayout(self.moreSettingsLayout) self.showmoreCheckbox = QCheckBox(getMessage("en", "more-title")) if self.getMoreState() == False: self.showmoreCheckbox.setChecked(False) self.moreSettingsGroup.hide() else: self.showmoreCheckbox.hide() self.showmoreCheckbox.toggled.connect(self.moreToggled) self.moreSettingsGroup.toggled.connect(self.moreToggled) if config['forceGuiPrompt'] == True: self.alwaysshowCheckbox.setChecked(True) if (constants.SHOW_TOOLTIPS == True): self.showmoreCheckbox.setToolTip(getMessage("en", "more-tooltip")) self.donotstoreCheckbox.toggled.connect(self.runButtonTextUpdate) self.mainLayout = QtGui.QVBoxLayout() if error: self.errorLabel = QLabel(error, self) self.errorLabel.setAlignment(Qt.AlignCenter) self.errorLabel.setStyleSheet("QLabel { color : red; }") self.mainLayout.addWidget(self.errorLabel) self.mainLayout.addWidget(self.connectionSettingsGroup) self.mainLayout.addSpacing(12) self.mainLayout.addWidget(self.mediaplayerSettingsGroup) self.mainLayout.addSpacing(12) self.mainLayout.addWidget(self.showmoreCheckbox) self.mainLayout.addWidget(self.moreSettingsGroup) self.mainLayout.addSpacing(12) self.topLayout = QtGui.QHBoxLayout() self.helpButton = QtGui.QPushButton(QtGui.QIcon(resourcespath + 'help.png'),getMessage("en", "help-label")) if (constants.SHOW_TOOLTIPS == True): self.helpButton.setToolTip(getMessage("en", "help-tooltip")) self.helpButton.setMaximumSize(self.helpButton.sizeHint()) self.helpButton.pressed.connect(self.openHelp) self.runButton = QtGui.QPushButton(QtGui.QIcon(resourcespath + 'accept.png'),getMessage("en", "storeandrun-label")) self.runButton.pressed.connect(self._saveDataAndLeave) if config['noStore'] == True: self.donotstoreCheckbox.setChecked(True) self.runButton.setText(getMessage("en", "run-label")) self.topLayout.addWidget(self.helpButton, Qt.AlignLeft) self.topLayout.addWidget(self.runButton, Qt.AlignRight) self.mainLayout.addLayout(self.topLayout) self.mainLayout.addStretch(1) self.setLayout(self.mainLayout) self.runButton.setFocus() self.setFixedSize(self.sizeHint()) self.setAcceptDrops(True) if self.datacleared == True: QtGui.QMessageBox.information(self,"Syncplay", getMessage("en", "gui-data-cleared-notification"))
class CC_window(QWidget): def __init__(self): super(CC_window, self).__init__() self.version = '0.2' glo = QVBoxLayout(self) self.Runningo = None self.Looping = None self.P = CC_thread() if name == 'nt': ficon = r_path('images\\favicon.png') licon = r_path('images\\logo.png') else: ficon = r_path('images/favicon.png') licon = r_path('images/logo.png') self.tf = QFont("", 13, QFont.Bold) self.sf = QFont("", 10, QFont.Bold) self.SelfIinit(QIcon(ficon)) self.center() self.a_btn(licon, glo) self.ss_btns(glo) self.i_list(glo) self.cl_btn(glo) self.l_btns(glo) self.f_btns(glo) self.ds_bar(glo) self.setLayout(glo) self.activateWindow() self.show() def SelfIinit(self, icon): self.setWindowTitle('chrome-cut ' + self.version) self.setGeometry(300, 300, 200, 150) self.setMinimumWidth(600) self.setMaximumWidth(600) self.setMinimumHeight(500) self.setMaximumHeight(500) # Setting Icon self.setWindowIcon(icon) QToolTip.setFont(self.sf) def msgApp(self, title, msg): uinfo = QMessageBox.question(self, title, msg, QMessageBox.Yes | QMessageBox.No) if uinfo == QMessageBox.Yes: return 'y' if uinfo == QMessageBox.No: return 'n' def closeEvent(self, event=None): if self.P.isRunning(): response = self.msgApp("Making sure", "Sure, you want to exit while looping ?") if response == 'y': if event is not None: event.accept() self.P.stop() exit(0) else: if event is not None: event.ignore() else: if event is not None: event.accept() exit(0) def center(self): qrect = self.frameGeometry() cp = QDesktopWidget().availableGeometry().center() qrect.moveCenter(cp) self.move(qrect.topLeft()) def a_btn(self, icon, glo): def show_about(): Amsg = "<center>All credit reserved to the author of chrome-cut " Amsg += " version " + self.version Amsg += ", This work is a free, open-source project licensed " Amsg += " under Mozilla Public License version 2.0 . <br><br>" Amsg += " visit us for more infos and how-tos :<br> " Amsg += "<b><a href='https://github.io/mrf345/chrome-cut'> " Amsg += "https://github.io/mrf345/chrome-cut </a> </b></center>" Amsgb = "About chrome-cut" return QMessageBox.about(self, Amsgb, Amsg) self.abutton = QPushButton('', self) self.abutton.setIcon(QPixmap(icon)) self.abutton.setIconSize(QSize(500, 100)) self.abutton.setToolTip('About chrome-cut') self.abutton.clicked.connect(show_about) glo.addWidget(self.abutton) def ss_btns(self, glo): self.lebutton = QPushButton('Scan IP address', self) self.lebutton.setToolTip( 'Insert and check if a specific IP is a valid chrome cast') self.lebutton.setFont(self.tf) self.lebutton.clicked.connect(self.sip_input) glo.addWidget(self.lebutton) def sip_input(self): self.lebutton.setEnabled(False) self.s_bar.setStyleSheet(self.s_norm) self.s_bar.showMessage('> Checking out the IP ..') msg = "<center>Enter suspected IP to check : <br><i><u>Usually it is " msg += "on 192.168.what_have_you.188</i></center>" text, okPressed = QInputDialog.getText(self, "Scan IP", msg) if okPressed and text != '': self.setCursor(Qt.BusyCursor) ch = is_ccast(text) if ch: self.il_add([text]) self.unsetCursor() self.lebutton.setEnabled(True) return True else: self.s_bar.setStyleSheet(self.s_error) self.s_bar.showMessage( '! Error: inserted IP is not chrome cast device') self.unsetCursor() self.lebutton.setEnabled(True) return True self.s_bar.clearMessage() self.lebutton.setEnabled(True) return True def i_list(self, glo): self.ci_list = QListWidget() self.ci_list.setToolTip("List of discovered devices") self.ci_list.setEnabled(False) self.setFont(self.sf) glo.addWidget(self.ci_list) def cl_btn(self, glo): self.cle_btn = QPushButton('Clear devices list') self.cle_btn.setToolTip("Remove all devices from the list") self.cle_btn.setFont(self.sf) self.cle_btn.setEnabled(False) self.cle_btn.clicked.connect(self.il_add) glo.addWidget(self.cle_btn) def l_btns(self, glo): hlayout = QHBoxLayout() self.llo = QCheckBox("Looping") self.llo.setToolTip( 'Automate repeating the smae command on the smae device selected ') self.llo.setEnabled(False) self.nlo = QLineEdit() self.nlo.setPlaceholderText("duration in seconds. Default is 10") self.nlo.setEnabled(False) self.nlo.setToolTip("Duration of sleep after each loop") self.lbtn = QPushButton('Stop') self.lbtn.setEnabled(False) self.lbtn.setFont(self.tf) self.llo.setFont(self.sf) self.lbtn.setToolTip("stop on-going command or loop") self.llo.toggled.connect(self.loped) self.lbtn.clicked.connect(partial(self.inloop_state, out=True)) hlayout.addWidget(self.llo) hlayout.addWidget(self.nlo) hlayout.addWidget(self.lbtn) glo.addLayout(hlayout) def loped(self): if self.Looping: self.Looping = None self.llo.setChecked(False) self.nlo.setEnabled(False) else: self.Looping = True self.llo.setChecked(True) self.nlo.setEnabled(True) return True def f_btns(self, glo): hlayout = QHBoxLayout() self.ksbutton = QPushButton('Kill stream', self) self.ksbutton.setToolTip('Kill whetever been streamed') self.ksbutton.setFont(self.tf) self.ksbutton.clicked.connect(self.k_act) self.sbutton = QPushButton('Stream', self) self.sbutton.setFont(self.tf) self.sbutton.setToolTip('Stream a youtube video') self.fbutton = QPushButton('Factory reset', self) self.fbutton.setFont(self.tf) self.fbutton.setToolTip('Factory reset the device') self.fbutton.clicked.connect(self.fr_act) self.sbutton.clicked.connect(self.yv_input) self.ksbutton.setEnabled(False) self.sbutton.setEnabled(False) self.fbutton.setEnabled(False) hlayout.addWidget(self.ksbutton) hlayout.addWidget(self.sbutton) hlayout.addWidget(self.fbutton) glo.addLayout(hlayout) def ch_dur(th=None, dur=10): if len(dur) >= 1: try: dur = int(dur) except: dur = None if dur is None or not isinstance(dur, int): self.s_bar.setStyleSheet(self.s_error) self.s_bar.showMessage( '! Error: wrong duration entery, only integers') return None else: dur = 10 return dur def k_act(self): if self.ci_list.count() >= 1: cr = self.ci_list.currentRow() if cr is None or cr <= 0: cr = 0 ip = self.ci_list.item(cr).text() if self.Looping is not None: dur = self.ch_dur(self.nlo.text()) if dur is None: return True self.P = CC_thread(cancel_app, dur, ip) self.P.start() self.P.somesignal.connect(self.handleStatusMessage) self.P.setTerminationEnabled(True) self.inloop_state() return True else: ch = cancel_app(ip) if ch is None: self.s_bar.setStyleSheet(self.s_error) self.s_bar.showMessage('! Error: failed to kill stream ..') else: self.s_bar.setStyleSheet(self.s_norm) self.s_bar.showMessage('# Stream got killed ') else: self.s_bar.setStyleSheet(self.s_error) self.s_bar.showMessage('! Error: No items selected from the list') self.eout() return True def fr_act(self): if self.ci_list.count() >= 1: cr = self.ci_list.currentRow() if cr is None or cr <= 0: cr = 0 ip = self.ci_list.item(cr).text() if self.Looping is not None: dur = self.ch_dur(self.nlo.text()) if dur is None: return True self.P = CC_thread(reset_cc, dur, ip) self.P.start() self.P.somesignal.connect(self.handleStatusMessage) self.P.setTerminationEnabled(True) self.inloop_state() return True else: ch = reset_cc(ip) if ch is None: self.s_bar.setStyleSheet(self.s_error) self.s_bar.showMessage( '! Error: failed to factory reset ..') else: self.s_bar.setStyleSheet(self.s_norm) self.s_bar.showMessage('# Got factory reseted ') else: self.s_bar.setStyleSheet(self.s_error) self.s_bar.showMessage('! Error: No items selected from the list') self.eout() return True def y_act(self, link=None): if self.ci_list.count() >= 1: cr = self.ci_list.currentRow() if cr is None or cr <= 0: cr = 0 ip = self.ci_list.item(cr).text() if self.Looping is not None: dur = self.ch_dur(self.nlo.text()) if dur is None: return True self.P = CC_thread(send_app, dur, ip, link) self.P.start() self.P.somesignal.connect(self.handleStatusMessage) self.P.setTerminationEnabled(True) self.inloop_state() return True else: ch = reset_cc(ip) if ch is None: self.s_bar.setStyleSheet(self.s_error) self.s_bar.showMessage('! Error: failed to stream link ..') else: self.s_bar.setStyleSheet(self.s_norm) self.s_bar.showMessage('# Streamed the link ') else: self.s_bar.setStyleSheet(self.s_error) self.s_bar.showMessage('! Error: No items selected from the list') self.eout() return True def yv_input(self): text, okPressed = QInputDialog.getText( self, "Stream youtube", "Enter youtube video link to be streamed :") if okPressed and text != '': ntext = text.split('?') if len(ntext) <= 1: self.s_bar.setStyleSheet(self.s_error) self.s_bar.showMessage('! Error: Invalid youtube linkd ') return False ntext = ntext[1] if ntext != '' and len(ntext) > 1 and "youtube" in text: self.y_act(ntext) return True else: self.s_bar.setStyleSheet(self.s_error) self.s_bar.showMessage('! Error: Invalid youtube linkd ') return False @Slot(object) def handleStatusMessage(self, message): self.s_bar.setStyleSheet(self.s_loop) self.s_bar.showMessage(message) def il_add(self, items=[]): if len(items) >= 1: self.s_bar.setStyleSheet(self.s_norm) for i in items: fitem = self.ci_list.findItems(i, Qt.MatchExactly) if len(fitem) >= 1: self.s_bar.setStyleSheet(self.s_error) self.s_bar.showMessage( '! Error: Device exists in the list') else: self.s_bar.setStyleSheet(self.s_norm) self.ci_list.addItem(i) self.s_bar.showMessage('# Device was found and added') if not self.P.isRunning(): self.cle_btn.setEnabled(True) self.ci_list.setEnabled(True) self.llo.setEnabled(True) self.nlo.setEnabled(True) self.ksbutton.setEnabled(True) self.sbutton.setEnabled(True) self.fbutton.setEnabled(True) else: self.s_bar.setStyleSheet(self.s_norm) self.s_bar.showMessage('# Cleard devices list') self.ci_list.clear() self.cle_btn.setEnabled(False) self.ci_list.setEnabled(False) self.ksbutton.setEnabled(False) self.llo.setEnabled(False) self.nlo.setEnabled(False) self.sbutton.setEnabled(False) self.fbutton.setEnabled(False) return True def inloop_state(self, out=False): if not out: self.lbtn.setEnabled(True) self.cle_btn.setEnabled(False) self.ci_list.setEnabled(False) self.ksbutton.setEnabled(False) self.llo.setEnabled(False) self.nlo.setEnabled(False) self.sbutton.setEnabled(False) self.fbutton.setEnabled(False) else: if self.P.isRunning(): self.P.stop() self.lbtn.setEnabled(False) self.cle_btn.setEnabled(True) self.ci_list.setEnabled(True) self.ksbutton.setEnabled(True) self.llo.setEnabled(True) self.nlo.setEnabled(True) self.sbutton.setEnabled(True) self.fbutton.setEnabled(True) self.s_bar.clearMessage() return True def ds_bar(self, glo): self.s_bar = QStatusBar() self.s_error = "QStatusBar{color:red;font-weight:1000;}" self.s_loop = "QStatusBar{color:black;font-weight:1000;}" self.s_norm = "QStatusBar{color:blue;font-style:italic;" self.s_norm += "font-weight:500;}" self.s_bar.setStyleSheet(self.s_norm) glo.addWidget(self.s_bar) def eout(self): msgg = "<center>" msgg += " Opps, a critical error has occurred, we will be " msgg += " grateful if you can help fixing it, by reporting to us " msgg += " at : <br><br> " msgg += "<b><a href='https://github.io/mrf345/chrome-cut'> " msgg += "https://github.io/mrf345/chrome-cut </a></b> </center>" mm = QMessageBox.critical(self, "Critical Error", msgg, QMessageBox.Ok) exit(0)