class E5NetworkIcon(QLabel): """ Class implementing a statusbar icon tracking the network status. @signal onlineStateChanged(online) emitted to indicate a change of the network state """ onlineStateChanged = pyqtSignal(bool) def __init__(self, parent=None): """ Constructor @param parent reference to the parent widget @type QWidget """ super(E5NetworkIcon, self).__init__(parent) self.__networkManager = QNetworkConfigurationManager(self) self.__online = self.__networkManager.isOnline() self.__onlineStateChanged(self.__online) self.__networkManager.onlineStateChanged.connect( self.__onlineStateChanged) @pyqtSlot(bool) def __onlineStateChanged(self, online): """ Private slot handling online state changes. @param online flag indicating the online status @type bool """ if online: self.setPixmap(UI.PixmapCache.getPixmap("network-online.png")) else: self.setPixmap(UI.PixmapCache.getPixmap("network-offline.png")) tooltip = self.tr("<p>Shows the network status<br/><br/>" "<b>Network:</b> {0}</p>") if self.__networkManager.isOnline(): tooltip = tooltip.format(self.tr("Connected")) else: tooltip = tooltip.format(self.tr("Offline")) self.setToolTip(tooltip) if online != self.__online: self.__online = online self.onlineStateChanged.emit(online) def isOnline(self): """ Public method to get the online state. @return online state @rtype bool """ return self.__networkManager.isOnline()
def run(self): localHostName = QHostInfo.localHostName() hostinfo = QHostInfo.fromName(localHostName) listaddress = hostinfo.addresses() for address in listaddress: if QHostAddress( address).protocol() == QAbstractSocket.IPv4Protocol: address = QHostAddress(address).toString() print(address) host_info = "" confList = QNetworkConfigurationManager().allConfigurations() print("confList = ", confList.__len__()) for conf in confList: if str(conf.bearerTypeName()) == "Ethernet": host_info += "\n" host_info += "name : " + QNetworkConfiguration( conf).name() + "\n" host_info += str(QNetworkConfiguration(conf).isValid()) + "\n" host_info += "bearerType: " + QNetworkConfiguration( conf).bearerTypeName() + "\n" list = QNetworkInterface.allInterfaces() for interface in list: host_info += "\n" host_info += "=============================\n" host_info += "name: " + interface.name() + "\n" host_info += QNetworkInterface(interface).hardwareAddress() + "\n" host_info += str(QNetworkInterface(interface).isValid()) + "\n" host_info += "---------\n" if QNetworkInterface(interface).flags() & QNetworkInterface.IsUp: host_info += "Interface: is up\n" if QNetworkInterface( interface).flags() & QNetworkInterface.IsLoopBack: host_info += "Interface: is loop back\n" # 迴環地址 if QNetworkInterface( interface).flags() & QNetworkInterface.IsRunning: host_info += "Interface: is running \n" # 網絡已經啓動運行 if interface.flags() & QNetworkInterface.CanMulticast: host_info += "Interface: CanMulticast\n" # 多播 if interface.flags() & QNetworkInterface.CanBroadcast: host_info += "Interface: CanBroadcast\n" host_info += "---------\n" entryList = QNetworkInterface(interface).addressEntries() for entry in entryList: address = entry.ip() if QHostAddress(address).protocol( ) == QAbstractSocket.IPv4Protocol: # and \ # str(address.toString()) != "127.0.0.1": host_info += "IP Address: " + QNetworkAddressEntry( entry).ip().toString() + "\n" host_info += "Netmask: " + QNetworkAddressEntry( entry).netmask().toString() + "\n" host_info += "Broadcast: " + QNetworkAddressEntry( entry).broadcast().toString() + "\n" host_info += "=============================\n" self.sig.emit(host_info)
def __init__(self, parent=None): """ Constructor @param parent reference to the parent widget @type QWidget """ super(E5NetworkIcon, self).__init__(parent) self.__networkManager = QNetworkConfigurationManager(self) self.__online = self.__networkManager.isOnline() self.__onlineStateChanged(self.__online) self.__networkManager.onlineStateChanged.connect( self.__onlineStateChanged)
def __init__(self, writeableDirectories, parent=None): """ Constructor @param writeableDirectories list of writable directories @type list of str @param parent reference to the parent widget @type QWidget """ super(ManageDictionariesDialog, self).__init__(parent) self.setupUi(self) self.__refreshButton = self.buttonBox.addButton( self.tr("Refresh"), QDialogButtonBox.ActionRole) self.__installButton = self.buttonBox.addButton( self.tr("Install Selected"), QDialogButtonBox.ActionRole) self.__installButton.setEnabled(False) self.__uninstallButton = self.buttonBox.addButton( self.tr("Uninstall Selected"), QDialogButtonBox.ActionRole) self.__uninstallButton.setEnabled(False) self.__cancelButton = self.buttonBox.addButton( self.tr("Cancel"), QDialogButtonBox.ActionRole) self.__cancelButton.setEnabled(False) self.locationComboBox.addItems(writeableDirectories) self.dictionariesUrlEdit.setText( Preferences.getWebBrowser("SpellCheckDictionariesUrl")) if Preferences.getUI("DynamicOnlineCheck"): self.__networkConfigurationManager = QNetworkConfigurationManager( self) self.__onlineStateChanged( self.__networkConfigurationManager.isOnline()) self.__networkConfigurationManager.onlineStateChanged.connect( self.__onlineStateChanged) else: self.__networkConfigurationManager = None self.__onlineStateChanged(True) self.__replies = [] self.__downloadCancelled = False self.__dictionariesToDownload = [] self.__populateList()
def __init__(self, parent=None): super(Server, self).__init__(parent) self.tcpServer = None self.networkSession = None self.statusLabel = QLabel() quitButton = QPushButton("Quit") quitButton.setAutoDefault(False) manager = QNetworkConfigurationManager() if manager.capabilities( ) & QNetworkConfigurationManager.NetworkSessionRequired: settings = QSettings(QSettings.UserScope, 'QtProject') settings.beginGroup('QtNetwork') id = settings.value('DefaultNetworkConfiguration', '') settings.endGroup() config = manager.configurationFromIdentifier(id) if config.state() & QNetworkConfiguration.Discovered == 0: config = manager.defaultConfiguration() self.networkSession = QNetworkSession(config, self) self.networkSession.opened.connect(self.sessionOpened) self.statusLabel.setText("Opening network session.") self.networkSession.open() else: self.sessionOpened() quitButton.clicked.connect(self.close) self.tcpServer.newConnection.connect(self.sendFortune) buttonLayout = QHBoxLayout() buttonLayout.addStretch(1) buttonLayout.addWidget(quitButton) buttonLayout.addStretch(1) mainLayout = QVBoxLayout() mainLayout.addWidget(self.statusLabel) mainLayout.addLayout(buttonLayout) self.setLayout(mainLayout) self.setWindowTitle("Fortune Server")
def __init__(self, parent=None): super(Server, self).__init__(parent) self.tcpServer = None self.networkSession = None self.statusLabel = QLabel() quitButton = QPushButton("Quit") quitButton.setAutoDefault(False) manager = QNetworkConfigurationManager() if manager.capabilities() & QNetworkConfigurationManager.NetworkSessionRequired: settings = QSettings(QSettings.UserScope, 'QtProject') settings.beginGroup('QtNetwork') id = settings.value('DefaultNetworkConfiguration', '') settings.endGroup() config = manager.configurationFromIdentifier(id) if config.state() & QNetworkConfiguration.Discovered == 0: config = manager.defaultConfiguration() self.networkSession = QNetworkSession(config, self) self.networkSession.opened.connect(self.sessionOpened) self.statusLabel.setText("Opening network session.") self.networkSession.open() else: self.sessionOpened() quitButton.clicked.connect(self.close) self.tcpServer.newConnection.connect(self.sendFortune) buttonLayout = QHBoxLayout() buttonLayout.addStretch(1) buttonLayout.addWidget(quitButton) buttonLayout.addStretch(1) mainLayout = QVBoxLayout() mainLayout.addWidget(self.statusLabel) mainLayout.addLayout(buttonLayout) self.setLayout(mainLayout) self.setWindowTitle("Fortune Server")
class InternetConnectionClass(QObject): ignore = pyqtSignal() def __init__(self, parent=None): super(InternetConnectionClass, self).__init__(parent) self.internetConnectionManager = QNetworkConfigurationManager() @pyqtProperty(bool, notify=ignore) def isThereInternetConnection(self): return self.internetConnectionManager.isOnline()
def __init__(self, username, parent=None): super().__init__(parent) self.username = username self._status = 'UNKNOWN' self.last_session = None self.sessions = [] self.balance = None self.byte = None self.network_manager = QNetworkConfigurationManager(self)
def __init__(self, parent=None, external=False): """ Constructor @param parent parent of this dialog (QWidget) @param external flag indicating an instatiation as a main window (boolean) """ super(PluginRepositoryWidget, self).__init__(parent) self.setupUi(self) self.__updateButton = self.buttonBox.addButton( self.tr("Update"), QDialogButtonBox.ActionRole) self.__downloadButton = self.buttonBox.addButton( self.tr("Download"), QDialogButtonBox.ActionRole) self.__downloadButton.setEnabled(False) self.__downloadInstallButton = self.buttonBox.addButton( self.tr("Download && Install"), QDialogButtonBox.ActionRole) self.__downloadInstallButton.setEnabled(False) self.__downloadCancelButton = self.buttonBox.addButton( self.tr("Cancel"), QDialogButtonBox.ActionRole) self.__installButton = \ self.buttonBox.addButton(self.tr("Close && Install"), QDialogButtonBox.ActionRole) self.__downloadCancelButton.setEnabled(False) self.__installButton.setEnabled(False) self.repositoryUrlEdit.setText( Preferences.getUI("PluginRepositoryUrl6")) self.repositoryList.headerItem().setText( self.repositoryList.columnCount(), "") self.repositoryList.header().setSortIndicator(0, Qt.AscendingOrder) self.__pluginContextMenu = QMenu(self) self.__hideAct = self.__pluginContextMenu.addAction( self.tr("Hide"), self.__hidePlugin) self.__hideSelectedAct = self.__pluginContextMenu.addAction( self.tr("Hide Selected"), self.__hideSelectedPlugins) self.__pluginContextMenu.addSeparator() self.__showAllAct = self.__pluginContextMenu.addAction( self.tr("Show All"), self.__showAllPlugins) self.__pluginContextMenu.addSeparator() self.__pluginContextMenu.addAction( self.tr("Cleanup Downloads"), self.__cleanupDownloads) self.pluginRepositoryFile = \ os.path.join(Utilities.getConfigDir(), "PluginRepository") self.__external = external # attributes for the network objects self.__networkManager = QNetworkAccessManager(self) self.__networkManager.proxyAuthenticationRequired.connect( proxyAuthenticationRequired) if SSL_AVAILABLE: self.__sslErrorHandler = E5SslErrorHandler(self) self.__networkManager.sslErrors.connect(self.__sslErrors) self.__replies = [] self.__networkConfigurationManager = QNetworkConfigurationManager(self) self.__onlineStateChanged( self.__networkConfigurationManager.isOnline()) self.__networkConfigurationManager.onlineStateChanged.connect( self.__onlineStateChanged) self.__doneMethod = None self.__inDownload = False self.__pluginsToDownload = [] self.__pluginsDownloaded = [] self.__isDownloadInstall = False self.__allDownloadedOk = False self.__hiddenPlugins = Preferences.getPluginManager("HiddenPlugins") self.__populateList()
class ManageDictionariesDialog(QDialog, Ui_ManageDictionariesDialog): """ Class implementing a dialog to install spell checking dictionaries. """ FilenameRole = Qt.UserRole UrlRole = Qt.UserRole + 1 DocumentationDirRole = Qt.UserRole + 2 LocalesRole = Qt.UserRole + 3 def __init__(self, writeableDirectories, parent=None): """ Constructor @param writeableDirectories list of writable directories @type list of str @param parent reference to the parent widget @type QWidget """ super(ManageDictionariesDialog, self).__init__(parent) self.setupUi(self) self.__refreshButton = self.buttonBox.addButton( self.tr("Refresh"), QDialogButtonBox.ActionRole) self.__installButton = self.buttonBox.addButton( self.tr("Install Selected"), QDialogButtonBox.ActionRole) self.__installButton.setEnabled(False) self.__uninstallButton = self.buttonBox.addButton( self.tr("Uninstall Selected"), QDialogButtonBox.ActionRole) self.__uninstallButton.setEnabled(False) self.__cancelButton = self.buttonBox.addButton( self.tr("Cancel"), QDialogButtonBox.ActionRole) self.__cancelButton.setEnabled(False) self.locationComboBox.addItems(writeableDirectories) self.dictionariesUrlEdit.setText( Preferences.getWebBrowser("SpellCheckDictionariesUrl")) if Preferences.getUI("DynamicOnlineCheck"): self.__networkConfigurationManager = QNetworkConfigurationManager( self) self.__onlineStateChanged( self.__networkConfigurationManager.isOnline()) self.__networkConfigurationManager.onlineStateChanged.connect( self.__onlineStateChanged) else: self.__networkConfigurationManager = None self.__onlineStateChanged(True) self.__replies = [] self.__downloadCancelled = False self.__dictionariesToDownload = [] self.__populateList() @pyqtSlot(bool) def __onlineStateChanged(self, online): """ Private slot handling online state changes. @param online flag indicating the online status @type bool """ self.__refreshButton.setEnabled(online) if online: msg = self.tr("Network Status: online") else: msg = self.tr("Network Status: offline") self.statusLabel.setText(msg) self.on_dictionariesList_itemSelectionChanged() def __isOnline(self): """ Private method to check the online status. @return flag indicating the online status @rtype bool """ if self.__networkConfigurationManager is not None: return self.__networkConfigurationManager.isOnline() else: return True @pyqtSlot(QAbstractButton) def on_buttonBox_clicked(self, button): """ Private slot to handle the click of a button of the button box. @param button reference to the button pressed @type QAbstractButton """ if button == self.__refreshButton: self.__populateList() elif button == self.__cancelButton: self.__downloadCancel() elif button == self.__installButton: self.__installSelected() elif button == self.__uninstallButton: self.__uninstallSelected() @pyqtSlot() def on_dictionariesList_itemSelectionChanged(self): """ Private slot to handle a change of the selection. """ self.__installButton.setEnabled( self.locationComboBox.count() > 0 and len(self.dictionariesList.selectedItems()) > 0 and self.__isOnline()) self.__uninstallButton.setEnabled( self.locationComboBox.count() > 0 and len([ itm for itm in self.dictionariesList.selectedItems() if itm.checkState() == Qt.Checked ])) @pyqtSlot(bool) def on_dictionariesUrlEditButton_toggled(self, checked): """ Private slot to set the read only status of the dictionaries URL line edit. @param checked state of the push button (boolean) """ self.dictionariesUrlEdit.setReadOnly(not checked) @pyqtSlot(str) def on_locationComboBox_currentTextChanged(self, txt): """ Private slot to handle a change of the installation location. @param txt installation location @type str """ self.__checkInstalledDictionaries() def __populateList(self): """ Private method to populate the list of available plugins. """ self.dictionariesList.clear() self.downloadProgress.setValue(0) url = self.dictionariesUrlEdit.text() if self.__isOnline(): self.__refreshButton.setEnabled(False) self.__installButton.setEnabled(False) self.__uninstallButton.setEnabled(False) self.__cancelButton.setEnabled(True) self.statusLabel.setText(url) self.__downloadCancelled = False request = QNetworkRequest(QUrl(url)) request.setAttribute(QNetworkRequest.CacheLoadControlAttribute, QNetworkRequest.AlwaysNetwork) reply = WebBrowserWindow.networkManager().get(request) reply.finished.connect(lambda: self.__listFileDownloaded(reply)) reply.downloadProgress.connect(self.__downloadProgress) self.__replies.append(reply) else: E5MessageBox.warning( self, self.tr("Error populating list of dictionaries"), self.tr("""<p>Could not download the dictionaries list""" """ from {0}.</p><p>Error: {1}</p>""").format( url, self.tr("Computer is offline."))) def __listFileDownloaded(self, reply): """ Private method called, after the dictionaries list file has been downloaded from the Internet. @param reply reference to the network reply @type QNetworkReply """ self.__refreshButton.setEnabled(True) self.__cancelButton.setEnabled(False) self.__onlineStateChanged(self.__isOnline()) self.downloadProgress.setValue(0) if reply in self.__replies: self.__replies.remove(reply) reply.deleteLater() if reply.error() != QNetworkReply.NoError: if not self.__downloadCancelled: E5MessageBox.warning( self, self.tr("Error downloading dictionaries list"), self.tr("""<p>Could not download the dictionaries list""" """ from {0}.</p><p>Error: {1}</p>""").format( self.dictionariesUrlEdit.text(), reply.errorString())) self.downloadProgress.setValue(0) return listFileData = reply.readAll() # extract the dictionaries from E5XML.SpellCheckDictionariesReader import ( SpellCheckDictionariesReader) reader = SpellCheckDictionariesReader(listFileData, self.addEntry) reader.readXML() url = Preferences.getWebBrowser("SpellCheckDictionariesUrl") if url != self.dictionariesUrlEdit.text(): self.dictionariesUrlEdit.setText(url) E5MessageBox.warning( self, self.tr("Dictionaries URL Changed"), self.tr("""The URL of the spell check dictionaries has""" """ changed. Select the "Refresh" button to get""" """ the new dictionaries list.""")) if self.locationComboBox.count() == 0: # no writable locations available E5MessageBox.warning( self, self.tr("Error installing dictionaries"), self.tr( """<p>None of the dictionary locations is writable by""" """ you. Please download required dictionaries manually""" """ and install them as administrator.</p>""")) self.__checkInstalledDictionaries() def __downloadCancel(self): """ Private slot to cancel the current download. """ if self.__replies: reply = self.__replies[0] self.__downloadCancelled = True self.__dictionariesToDownload = [] reply.abort() def __downloadProgress(self, done, total): """ Private slot to show the download progress. @param done number of bytes downloaded so far @type int @param total total bytes to be downloaded @type int """ if total: self.downloadProgress.setMaximum(total) self.downloadProgress.setValue(done) def addEntry(self, short, filename, url, documentationDir, locales): """ Public method to add an entry to the list. @param short data for the description field @type str @param filename data for the filename field @type str @param url download URL for the dictionary entry @type str @param documentationDir name of the directory containing the dictionary documentation @type str @param locales list of locales @type list of str """ itm = QListWidgetItem( self.tr("{0} ({1})").format(short, " ".join(locales)), self.dictionariesList) itm.setCheckState(Qt.Unchecked) itm.setData(ManageDictionariesDialog.FilenameRole, filename) itm.setData(ManageDictionariesDialog.UrlRole, url) itm.setData(ManageDictionariesDialog.DocumentationDirRole, documentationDir) itm.setData(ManageDictionariesDialog.LocalesRole, locales) def __checkInstalledDictionaries(self): """ Private method to check all installed dictionaries. Note: A dictionary is assumed to be installed, if at least one of its binary dictionaries (*.bdic) is found in the selected dictionaries location. """ if self.locationComboBox.currentText(): installedLocales = { os.path.splitext(os.path.basename(dic))[0] for dic in glob.glob( os.path.join(self.locationComboBox.currentText(), "*.bdic")) } for row in range(self.dictionariesList.count()): itm = self.dictionariesList.item(row) locales = set(itm.data(ManageDictionariesDialog.LocalesRole)) if locales.intersection(installedLocales): itm.setCheckState(Qt.Checked) else: itm.setCheckState(Qt.Unchecked) else: for row in range(self.dictionariesList.count()): itm = self.dictionariesList.item(row) itm.setCheckState(Qt.Unchecked) def __installSelected(self): """ Private method to install the selected dictionaries. """ if self.__isOnline() and bool(self.locationComboBox.currentText()): self.__dictionariesToDownload = [ itm.data(ManageDictionariesDialog.UrlRole) for itm in self.dictionariesList.selectedItems() ] self.__refreshButton.setEnabled(False) self.__installButton.setEnabled(False) self.__uninstallButton.setEnabled(False) self.__cancelButton.setEnabled(True) self.__downloadCancelled = False self.__downloadDictionary() def __downloadDictionary(self): """ Private slot to download a dictionary. """ if self.__isOnline(): if self.__dictionariesToDownload: url = self.__dictionariesToDownload.pop(0) self.statusLabel.setText(url) self.__downloadCancelled = False request = QNetworkRequest(QUrl(url)) request.setAttribute(QNetworkRequest.CacheLoadControlAttribute, QNetworkRequest.AlwaysNetwork) reply = WebBrowserWindow.networkManager().get(request) reply.finished.connect(lambda: self.__installDictionary(reply)) reply.downloadProgress.connect(self.__downloadProgress) self.__replies.append(reply) else: self.__installationFinished() else: E5MessageBox.warning( self, self.tr("Error downloading dictionary file"), self.tr( """<p>Could not download the requested dictionary file""" """ from {0}.</p><p>Error: {1}</p>""").format( url, self.tr("Computer is offline."))) self.__installationFinished() def __installDictionary(self, reply): """ Private slot to install the downloaded dictionary. @param reply reference to the network reply @type QNetworkReply """ if reply in self.__replies: self.__replies.remove(reply) reply.deleteLater() if reply.error() != QNetworkReply.NoError: if not self.__downloadCancelled: E5MessageBox.warning( self, self.tr("Error downloading dictionary file"), self.tr( """<p>Could not download the requested dictionary""" """ file from {0}.</p><p>Error: {1}</p>""").format( reply.url(), reply.errorString())) self.downloadProgress.setValue(0) return archiveData = reply.readAll() archiveFile = io.BytesIO(bytes(archiveData)) archive = zipfile.ZipFile(archiveFile, "r") if archive.testzip() is not None: E5MessageBox.critical( self, self.tr("Error downloading dictionary"), self.tr("""<p>The downloaded dictionary archive is invalid.""" """ Skipping it.</p>""")) else: installDir = self.locationComboBox.currentText() archive.extractall(installDir) if self.__dictionariesToDownload: self.__downloadDictionary() else: self.__installationFinished() def __installationFinished(self): """ Private method called after all selected dictionaries have been installed. """ self.__refreshButton.setEnabled(True) self.__cancelButton.setEnabled(False) self.__onlineStateChanged(self.__isOnline()) self.dictionariesList.clearSelection() self.downloadProgress.setValue(0) self.__checkInstalledDictionaries() def __uninstallSelected(self): """ Private method to uninstall the selected dictionaries. """ installLocation = self.locationComboBox.currentText() if not installLocation: return itemsToDelete = [ itm for itm in self.dictionariesList.selectedItems() if itm.checkState() == Qt.Checked ] for itm in itemsToDelete: documentationDir = itm.data( ManageDictionariesDialog.DocumentationDirRole) shutil.rmtree(os.path.join(installLocation, documentationDir), True) locales = itm.data(ManageDictionariesDialog.LocalesRole) for locale in locales: bdic = os.path.join(installLocation, locale + ".bdic") try: os.remove(bdic) except OSError: # ignore silently pass self.dictionariesList.clearSelection() self.__checkInstalledDictionaries()
def __init__(self, parent=None): super(Client, self).__init__(parent) self.networkSession = None self.blockSize = 0 self.currentFortune = '' hostLabel = QLabel("&Server name:") portLabel = QLabel("S&erver port:") self.hostCombo = QComboBox() self.hostCombo.setEditable(True) name = QHostInfo.localHostName() if name != '': self.hostCombo.addItem(name) domain = QHostInfo.localDomainName() if domain != '': self.hostCombo.addItem(name + '.' + domain) if name != 'localhost': self.hostCombo.addItem('localhost') ipAddressesList = QNetworkInterface.allAddresses() for ipAddress in ipAddressesList: if not ipAddress.isLoopback(): self.hostCombo.addItem(ipAddress.toString()) for ipAddress in ipAddressesList: if ipAddress.isLoopback(): self.hostCombo.addItem(ipAddress.toString()) self.portLineEdit = QLineEdit() self.portLineEdit.setValidator(QIntValidator(1, 65535, self)) hostLabel.setBuddy(self.hostCombo) portLabel.setBuddy(self.portLineEdit) self.statusLabel = QLabel("This examples requires that you run " "the Fortune Server example as well.") self.getFortuneButton = QPushButton("Get Fortune") self.getFortuneButton.setDefault(True) self.getFortuneButton.setEnabled(False) quitButton = QPushButton("Quit") buttonBox = QDialogButtonBox() buttonBox.addButton(self.getFortuneButton, QDialogButtonBox.ActionRole) buttonBox.addButton(quitButton, QDialogButtonBox.RejectRole) self.tcpSocket = QTcpSocket(self) self.hostCombo.editTextChanged.connect(self.enableGetFortuneButton) self.portLineEdit.textChanged.connect(self.enableGetFortuneButton) self.getFortuneButton.clicked.connect(self.requestNewFortune) quitButton.clicked.connect(self.close) self.tcpSocket.readyRead.connect(self.readFortune) self.tcpSocket.error.connect(self.displayError) mainLayout = QGridLayout() mainLayout.addWidget(hostLabel, 0, 0) mainLayout.addWidget(self.hostCombo, 0, 1) mainLayout.addWidget(portLabel, 1, 0) mainLayout.addWidget(self.portLineEdit, 1, 1) mainLayout.addWidget(self.statusLabel, 2, 0, 1, 2) mainLayout.addWidget(buttonBox, 3, 0, 1, 2) self.setLayout(mainLayout) self.setWindowTitle("Fortune Client") self.portLineEdit.setFocus() manager = QNetworkConfigurationManager() if manager.capabilities( ) & QNetworkConfigurationManager.NetworkSessionRequired: settings = QSettings(QSettings.UserScope, 'QtProject') settings.beginGroup('QtNetwork') id = settings.value('DefaultNetworkConfiguration') settings.endGroup() config = manager.configurationFromIdentifier(id) if config.state() & QNetworkConfiguration.Discovered == 0: config = manager.defaultConfiguration() self.networkSession = QNetworkSession(config, self) self.networkSession.opened.connect(self.sessionOpened) self.getFortuneButton.setEnabled(False) self.statusLabel.setText("Opening network session.") self.networkSession.open()
def __init__(self, parent=None): super(Client, self).__init__(parent) self.networkSession = None self.blockSize = 0 self.currentFortune = '' self.title = "扫码收货PC辅助程序" hostLabel = QLabel('IP:') hostLabel.setFont(qtawesome.font('fa', 14)) portLabel = QLabel('端口:') portLabel.setFont(qtawesome.font('fa', 14)) taskCodeLabel = QLabel('任务码:') taskCodeLabel.setFont(qtawesome.font('fa', 14)) self.serverMsgLable = QLabel('来自服务端的消息:') self.serverMsgLable.setFont(qtawesome.font('fa', 14)) self.sendMsgLabel = QLabel('将要发送的消息:') self.sendMsgLabel.setFont(qtawesome.font('fa', 14)) self.hostCombo = QComboBox() self.hostCombo.setEditable(True) name = QHostInfo.localHostName() if name != '': self.hostCombo.addItem(name) domain = QHostInfo.localDomainName() if domain != '': self.hostCombo.addItem(name + '.' + domain) if name != 'localhost': self.hostCombo.addItem('10.286.88.124') ipAddressesList = QNetworkInterface.allAddresses() for ipAddress in ipAddressesList: if not ipAddress.isLoopback(): self.hostCombo.addItem(ipAddress.toString()) for ipAddress in ipAddressesList: if ipAddress.isLoopback(): self.hostCombo.addItem(ipAddress.toString()) self.portLineEdit = QLineEdit() self.portLineEdit.setValidator(QIntValidator(1, 65535, self)) self.portLineEdit.setPlaceholderText("请输入端口") self.taskLineEdit = QLineEdit() self.taskLineEdit.setPlaceholderText("请向组长询问后输入任务码") self.taskLineEdit.setValidator(QIntValidator(1, 9999, self)) self.serverLineEdit = QLineEdit() self.serverLineEdit.setPlaceholderText('服务器发送的消息会显示在这里') self.sendTextEdit = QTextEdit() self.sendTextEdit.setPlaceholderText('请输入先要发送给服务器的消息') hostLabel.setBuddy(self.hostCombo) portLabel.setBuddy(self.portLineEdit) taskCodeLabel.setBuddy(self.taskLineEdit) self.serverMsgLable.setBuddy(self.serverLineEdit) self.sendMsgLabel.setBuddy(self.sendTextEdit) self.statusLabel = QLabel("状态:尚未连接") self.statusLabel.setAutoFillBackground(True) self.statusLabel.setAlignment(Qt.AlignCenter) palette = QPalette() # 新建一个调色板 palette.setColor(QPalette.Window, Qt.red) # 设置颜色 self.statusLabel.setPalette(palette) self.statusLabel.setStyleSheet(''' color:#ffffff; font-size:18px; font-weight:bold; ''') self.getFortuneButton = QPushButton("启动连接") self.getFortuneButton.setDefault(True) self.getFortuneButton.setEnabled(False) quitButton = QPushButton("退出") self.stopButton = QPushButton("中止连接") self.stopButton.setDefault(True) self.stopButton.setEnabled(False) buttonBox = QDialogButtonBox() buttonBox.addButton(self.getFortuneButton, QDialogButtonBox.ActionRole) buttonBox.addButton(self.stopButton, QDialogButtonBox.AcceptRole) buttonBox.addButton(quitButton, QDialogButtonBox.RejectRole) self.sendMsgbutton = QPushButton('发送消息') self.webSocket = QWebSocket() self.hostCombo.editTextChanged.connect(self.enableGetFortuneButton) self.portLineEdit.textChanged.connect(self.enableGetFortuneButton) self.taskLineEdit.textChanged.connect(self.enableGetFortuneButton) self.getFortuneButton.clicked.connect(self.CreateNewConn) self.stopButton.clicked.connect(self.stopCurrentConn) quitButton.clicked.connect(self.close) self.webSocket.connected.connect(self.websocketConnect) self.webSocket.disconnected.connect(self.webSocketDisconnect) self.webSocket.error.connect(self.displayError) self.webSocket.textMessageReceived.connect( self.webSocketMessageReceived) self.sendTextEdit.textChanged.connect(self.enableSendMessageButton) self.sendMsgbutton.clicked.connect(self.sendMsgToServer) mainLayout = QGridLayout() mainLayout.addWidget(hostLabel, 0, 0) mainLayout.addWidget(self.hostCombo, 0, 1) mainLayout.addWidget(portLabel, 1, 0) mainLayout.addWidget(self.portLineEdit, 1, 1) mainLayout.addWidget(taskCodeLabel, 2, 0) mainLayout.addWidget(self.taskLineEdit, 2, 1) mainLayout.addWidget(self.statusLabel, 3, 0, 1, 2) mainLayout.addWidget(buttonBox, 4, 0, 1, 2) mainLayout.addWidget(self.serverMsgLable, 5, 0) mainLayout.addWidget(self.serverLineEdit, 5, 1, 1, 1) mainLayout.addWidget(self.sendMsgLabel, 6, 0) mainLayout.addWidget(self.sendTextEdit, 6, 1) mainLayout.addWidget(self.sendMsgbutton, 7, 0, 1, 5) self.serverLineEdit.setEnabled(False) self.serverMsgLable.setVisible(False) self.serverLineEdit.setVisible(False) self.sendMsgLabel.setVisible(False) self.sendTextEdit.setVisible(False) self.sendMsgbutton.setEnabled(False) self.sendMsgbutton.setVisible(False) self.setLayout(mainLayout) mainLayout.setSpacing(10) self.setWindowTitle(self.title) self.portLineEdit.setFocus() manager = QNetworkConfigurationManager() if manager.capabilities( ) & QNetworkConfigurationManager.NetworkSessionRequired: settings = QSettings(QSettings.UserScope, 'QtProject') settings.beginGroup('QtNetwork') id = settings.value('DefaultNetworkConfiguration') settings.endGroup() config = manager.configurationFromIdentifier(id) if config.state() & QNetworkConfiguration.Discovered == 0: config = manager.defaultConfiguration() self.networkSession = QNetworkSession(config, self) self.networkSession.opened.connect(self.sessionOpened) self.getFortuneButton.setEnabled(False) self.statusLabel.setText("Opening network session.") self.networkSession.open()
def __init__(self, pluginManager, parent=None): """ Constructor @param pluginManager reference to the plugin manager object @type PluginManager @param parent parent of this dialog @type QWidget """ super(PluginRepositoryWidget, self).__init__(parent) self.setupUi(self) if pluginManager is None: # started as external plug-in repository dialog from .PluginManager import PluginManager self.__pluginManager = PluginManager() self.__external = True else: self.__pluginManager = pluginManager self.__external = False self.__updateButton = self.buttonBox.addButton( self.tr("Update"), QDialogButtonBox.ActionRole) self.__downloadButton = self.buttonBox.addButton( self.tr("Download"), QDialogButtonBox.ActionRole) self.__downloadButton.setEnabled(False) self.__downloadInstallButton = self.buttonBox.addButton( self.tr("Download && Install"), QDialogButtonBox.ActionRole) self.__downloadInstallButton.setEnabled(False) self.__downloadCancelButton = self.buttonBox.addButton( self.tr("Cancel"), QDialogButtonBox.ActionRole) self.__downloadCancelButton.setEnabled(False) self.__installButton = self.buttonBox.addButton( self.tr("Close && Install"), QDialogButtonBox.ActionRole) self.__installButton.setEnabled(False) self.__closeButton = self.buttonBox.button(QDialogButtonBox.Close) self.__closeButton.setEnabled(True) self.repositoryUrlEdit.setText( Preferences.getUI("PluginRepositoryUrl6")) self.repositoryList.headerItem().setText( self.repositoryList.columnCount(), "") self.repositoryList.header().setSortIndicator(0, Qt.AscendingOrder) self.__pluginContextMenu = QMenu(self) self.__hideAct = self.__pluginContextMenu.addAction( self.tr("Hide"), self.__hidePlugin) self.__hideSelectedAct = self.__pluginContextMenu.addAction( self.tr("Hide Selected"), self.__hideSelectedPlugins) self.__pluginContextMenu.addSeparator() self.__showAllAct = self.__pluginContextMenu.addAction( self.tr("Show All"), self.__showAllPlugins) self.__pluginContextMenu.addSeparator() self.__pluginContextMenu.addAction( self.tr("Cleanup Downloads"), self.__cleanupDownloads) self.pluginRepositoryFile = os.path.join(Utilities.getConfigDir(), "PluginRepository") # attributes for the network objects self.__networkManager = QNetworkAccessManager(self) self.__networkManager.proxyAuthenticationRequired.connect( proxyAuthenticationRequired) if SSL_AVAILABLE: self.__sslErrorHandler = E5SslErrorHandler(self) self.__networkManager.sslErrors.connect(self.__sslErrors) self.__replies = [] if Preferences.getUI("DynamicOnlineCheck"): self.__networkConfigurationManager = ( QNetworkConfigurationManager(self) ) self.__onlineStateChanged( self.__networkConfigurationManager.isOnline()) self.__networkConfigurationManager.onlineStateChanged.connect( self.__onlineStateChanged) else: self.__networkConfigurationManager = None self.__onlineStateChanged(True) self.__pluginsToDownload = [] self.__pluginsDownloaded = [] self.__isDownloadInstall = False self.__allDownloadedOk = False self.__hiddenPlugins = Preferences.getPluginManager("HiddenPlugins") self.__populateList()
def __init__(self, parent=None): super(Client, self).__init__(parent) self.networkSession = None self.blockSize = 0 self.currentFortune = "" hostLabel = QLabel("&Server name:") portLabel = QLabel("S&erver port:") self.hostCombo = QComboBox() self.hostCombo.setEditable(True) name = QHostInfo.localHostName() if name != "": self.hostCombo.addItem(name) domain = QHostInfo.localDomainName() if domain != "": self.hostCombo.addItem(name + "." + domain) if name != "localhost": self.hostCombo.addItem("localhost") ipAddressesList = QNetworkInterface.allAddresses() for ipAddress in ipAddressesList: if not ipAddress.isLoopback(): self.hostCombo.addItem(ipAddress.toString()) for ipAddress in ipAddressesList: if ipAddress.isLoopback(): self.hostCombo.addItem(ipAddress.toString()) self.portLineEdit = QLineEdit() self.portLineEdit.setValidator(QIntValidator(1, 65535, self)) hostLabel.setBuddy(self.hostCombo) portLabel.setBuddy(self.portLineEdit) self.statusLabel = QLabel("This examples requires that you run " "the Fortune Server example as well.") self.getFortuneButton = QPushButton("Get Fortune") self.getFortuneButton.setDefault(True) self.getFortuneButton.setEnabled(False) quitButton = QPushButton("Quit") buttonBox = QDialogButtonBox() buttonBox.addButton(self.getFortuneButton, QDialogButtonBox.ActionRole) buttonBox.addButton(quitButton, QDialogButtonBox.RejectRole) self.tcpSocket = QTcpSocket(self) self.hostCombo.editTextChanged.connect(self.enableGetFortuneButton) self.portLineEdit.textChanged.connect(self.enableGetFortuneButton) self.getFortuneButton.clicked.connect(self.requestNewFortune) quitButton.clicked.connect(self.close) self.tcpSocket.readyRead.connect(self.readFortune) self.tcpSocket.error.connect(self.displayError) mainLayout = QGridLayout() mainLayout.addWidget(hostLabel, 0, 0) mainLayout.addWidget(self.hostCombo, 0, 1) mainLayout.addWidget(portLabel, 1, 0) mainLayout.addWidget(self.portLineEdit, 1, 1) mainLayout.addWidget(self.statusLabel, 2, 0, 1, 2) mainLayout.addWidget(buttonBox, 3, 0, 1, 2) self.setLayout(mainLayout) self.setWindowTitle("Fortune Client") self.portLineEdit.setFocus() manager = QNetworkConfigurationManager() if manager.capabilities() & QNetworkConfigurationManager.NetworkSessionRequired: settings = QSettings(QSettings.UserScope, "QtProject") settings.beginGroup("QtNetwork") id = settings.value("DefaultNetworkConfiguration") settings.endGroup() config = manager.configurationFromIdentifier(id) if config.state() & QNetworkConfiguration.Discovered == 0: config = manager.defaultConfiguration() self.networkSession = QNetworkSession(config, self) self.networkSession.opened.connect(self.sessionOpened) self.getFortuneButton.setEnabled(False) self.statusLabel.setText("Opening network session.") self.networkSession.open()
def __init__(self, parent=None): super(InternetConnectionClass, self).__init__(parent) self.internetConnectionManager = QNetworkConfigurationManager()
class PluginRepositoryWidget(QWidget, Ui_PluginRepositoryDialog): """ Class implementing a dialog showing the available plugins. @signal closeAndInstall() emitted when the Close & Install button is pressed """ closeAndInstall = pyqtSignal() DescrRole = Qt.UserRole UrlRole = Qt.UserRole + 1 FilenameRole = Qt.UserRole + 2 AuthorRole = Qt.UserRole + 3 PluginStatusUpToDate = 0 PluginStatusNew = 1 PluginStatusLocalUpdate = 2 PluginStatusRemoteUpdate = 3 def __init__(self, parent=None, external=False): """ Constructor @param parent parent of this dialog (QWidget) @param external flag indicating an instatiation as a main window (boolean) """ super(PluginRepositoryWidget, self).__init__(parent) self.setupUi(self) self.__updateButton = self.buttonBox.addButton( self.tr("Update"), QDialogButtonBox.ActionRole) self.__downloadButton = self.buttonBox.addButton( self.tr("Download"), QDialogButtonBox.ActionRole) self.__downloadButton.setEnabled(False) self.__downloadInstallButton = self.buttonBox.addButton( self.tr("Download && Install"), QDialogButtonBox.ActionRole) self.__downloadInstallButton.setEnabled(False) self.__downloadCancelButton = self.buttonBox.addButton( self.tr("Cancel"), QDialogButtonBox.ActionRole) self.__installButton = \ self.buttonBox.addButton(self.tr("Close && Install"), QDialogButtonBox.ActionRole) self.__downloadCancelButton.setEnabled(False) self.__installButton.setEnabled(False) self.repositoryUrlEdit.setText( Preferences.getUI("PluginRepositoryUrl6")) self.repositoryList.headerItem().setText( self.repositoryList.columnCount(), "") self.repositoryList.header().setSortIndicator(0, Qt.AscendingOrder) self.__pluginContextMenu = QMenu(self) self.__hideAct = self.__pluginContextMenu.addAction( self.tr("Hide"), self.__hidePlugin) self.__hideSelectedAct = self.__pluginContextMenu.addAction( self.tr("Hide Selected"), self.__hideSelectedPlugins) self.__pluginContextMenu.addSeparator() self.__showAllAct = self.__pluginContextMenu.addAction( self.tr("Show All"), self.__showAllPlugins) self.__pluginContextMenu.addSeparator() self.__pluginContextMenu.addAction( self.tr("Cleanup Downloads"), self.__cleanupDownloads) self.pluginRepositoryFile = \ os.path.join(Utilities.getConfigDir(), "PluginRepository") self.__external = external # attributes for the network objects self.__networkManager = QNetworkAccessManager(self) self.__networkManager.proxyAuthenticationRequired.connect( proxyAuthenticationRequired) if SSL_AVAILABLE: self.__sslErrorHandler = E5SslErrorHandler(self) self.__networkManager.sslErrors.connect(self.__sslErrors) self.__replies = [] self.__networkConfigurationManager = QNetworkConfigurationManager(self) self.__onlineStateChanged( self.__networkConfigurationManager.isOnline()) self.__networkConfigurationManager.onlineStateChanged.connect( self.__onlineStateChanged) self.__doneMethod = None self.__inDownload = False self.__pluginsToDownload = [] self.__pluginsDownloaded = [] self.__isDownloadInstall = False self.__allDownloadedOk = False self.__hiddenPlugins = Preferences.getPluginManager("HiddenPlugins") self.__populateList() @pyqtSlot(bool) def __onlineStateChanged(self, online): """ Private slot handling online state changes. @param online flag indicating the online status @type bool """ self.__updateButton.setEnabled(online) self.on_repositoryList_itemSelectionChanged() if online: msg = self.tr("Network Status: online") else: msg = self.tr("Network Status: offline") self.statusLabel.setText(msg) @pyqtSlot(QAbstractButton) def on_buttonBox_clicked(self, button): """ Private slot to handle the click of a button of the button box. @param button reference to the button pressed (QAbstractButton) """ if button == self.__updateButton: self.__updateList() elif button == self.__downloadButton: self.__isDownloadInstall = False self.__downloadPlugins() elif button == self.__downloadInstallButton: self.__isDownloadInstall = True self.__allDownloadedOk = True self.__downloadPlugins() elif button == self.__downloadCancelButton: self.__downloadCancel() elif button == self.__installButton: self.__closeAndInstall() def __formatDescription(self, lines): """ Private method to format the description. @param lines lines of the description (list of strings) @return formatted description (string) """ # remove empty line at start and end newlines = lines[:] if len(newlines) and newlines[0] == '': del newlines[0] if len(newlines) and newlines[-1] == '': del newlines[-1] # replace empty lines by newline character index = 0 while index < len(newlines): if newlines[index] == '': newlines[index] = '\n' index += 1 # join lines by a blank return ' '.join(newlines) @pyqtSlot(QPoint) def on_repositoryList_customContextMenuRequested(self, pos): """ Private slot to show the context menu. @param pos position to show the menu (QPoint) """ self.__hideAct.setEnabled( self.repositoryList.currentItem() is not None and len(self.__selectedItems()) == 1) self.__hideSelectedAct.setEnabled( len(self.__selectedItems()) > 1) self.__showAllAct.setEnabled(bool(self.__hasHiddenPlugins())) self.__pluginContextMenu.popup(self.repositoryList.mapToGlobal(pos)) @pyqtSlot(QTreeWidgetItem, QTreeWidgetItem) def on_repositoryList_currentItemChanged(self, current, previous): """ Private slot to handle the change of the current item. @param current reference to the new current item (QTreeWidgetItem) @param previous reference to the old current item (QTreeWidgetItem) """ if self.__repositoryMissing or current is None: return self.urlEdit.setText( current.data(0, PluginRepositoryWidget.UrlRole) or "") self.descriptionEdit.setPlainText( current.data(0, PluginRepositoryWidget.DescrRole) and self.__formatDescription( current.data(0, PluginRepositoryWidget.DescrRole)) or "") self.authorEdit.setText( current.data(0, PluginRepositoryWidget.AuthorRole) or "") def __selectedItems(self): """ Private method to get all selected items without the toplevel ones. @return list of selected items (list) """ ql = self.repositoryList.selectedItems() for index in range(self.repositoryList.topLevelItemCount()): ti = self.repositoryList.topLevelItem(index) if ti in ql: ql.remove(ti) return ql @pyqtSlot() def on_repositoryList_itemSelectionChanged(self): """ Private slot to handle a change of the selection. """ self.__downloadButton.setEnabled( len(self.__selectedItems()) and self.__networkConfigurationManager.isOnline()) self.__downloadInstallButton.setEnabled( len(self.__selectedItems()) and self.__networkConfigurationManager.isOnline()) self.__installButton.setEnabled(len(self.__selectedItems())) def __updateList(self): """ Private slot to download a new list and display the contents. """ url = self.repositoryUrlEdit.text() self.__downloadFile(url, self.pluginRepositoryFile, self.__downloadRepositoryFileDone) def __downloadRepositoryFileDone(self, status, filename): """ Private method called after the repository file was downloaded. @param status flaging indicating a successful download (boolean) @param filename full path of the downloaded file (string) """ self.__populateList() def __downloadPluginDone(self, status, filename): """ Private method called, when the download of a plugin is finished. @param status flag indicating a successful download (boolean) @param filename full path of the downloaded file (string) """ if status: self.__pluginsDownloaded.append(filename) if self.__isDownloadInstall: self.__allDownloadedOk &= status del self.__pluginsToDownload[0] if len(self.__pluginsToDownload): self.__downloadPlugin() else: self.__downloadPluginsDone() def __downloadPlugin(self): """ Private method to download the next plugin. """ self.__downloadFile(self.__pluginsToDownload[0][0], self.__pluginsToDownload[0][1], self.__downloadPluginDone) def __downloadPlugins(self): """ Private slot to download the selected plugins. """ self.__pluginsDownloaded = [] self.__pluginsToDownload = [] self.__downloadButton.setEnabled(False) self.__downloadInstallButton.setEnabled(False) self.__installButton.setEnabled(False) for itm in self.repositoryList.selectedItems(): if itm not in [self.__stableItem, self.__unstableItem, self.__unknownItem]: url = itm.data(0, PluginRepositoryWidget.UrlRole) filename = os.path.join( Preferences.getPluginManager("DownloadPath"), itm.data(0, PluginRepositoryWidget.FilenameRole)) self.__pluginsToDownload.append((url, filename)) self.__downloadPlugin() def __downloadPluginsDone(self): """ Private method called, when the download of the plugins is finished. """ self.__downloadButton.setEnabled(len(self.__selectedItems())) self.__downloadInstallButton.setEnabled(len(self.__selectedItems())) self.__installButton.setEnabled(True) self.__doneMethod = None if not self.__external: ui = e5App().getObject("UserInterface") else: ui = None if ui and ui.notificationsEnabled(): ui.showNotification( UI.PixmapCache.getPixmap("plugin48.png"), self.tr("Download Plugin Files"), self.tr("""The requested plugins were downloaded.""")) if self.__isDownloadInstall: self.closeAndInstall.emit() else: if ui is None or not ui.notificationsEnabled(): E5MessageBox.information( self, self.tr("Download Plugin Files"), self.tr("""The requested plugins were downloaded.""")) self.downloadProgress.setValue(0) # repopulate the list to update the refresh icons self.__populateList() def __resortRepositoryList(self): """ Private method to resort the tree. """ self.repositoryList.sortItems( self.repositoryList.sortColumn(), self.repositoryList.header().sortIndicatorOrder()) def __populateList(self): """ Private method to populate the list of available plugins. """ self.repositoryList.clear() self.__stableItem = None self.__unstableItem = None self.__unknownItem = None self.downloadProgress.setValue(0) self.__doneMethod = None if os.path.exists(self.pluginRepositoryFile): self.__repositoryMissing = False f = QFile(self.pluginRepositoryFile) if f.open(QIODevice.ReadOnly): from E5XML.PluginRepositoryReader import PluginRepositoryReader reader = PluginRepositoryReader(f, self.addEntry) reader.readXML() self.repositoryList.resizeColumnToContents(0) self.repositoryList.resizeColumnToContents(1) self.repositoryList.resizeColumnToContents(2) self.__resortRepositoryList() url = Preferences.getUI("PluginRepositoryUrl6") if url != self.repositoryUrlEdit.text(): self.repositoryUrlEdit.setText(url) E5MessageBox.warning( self, self.tr("Plugins Repository URL Changed"), self.tr( """The URL of the Plugins Repository has""" """ changed. Select the "Update" button to get""" """ the new repository file.""")) else: E5MessageBox.critical( self, self.tr("Read plugins repository file"), self.tr("<p>The plugins repository file <b>{0}</b> " "could not be read. Select Update</p>") .format(self.pluginRepositoryFile)) else: self.__repositoryMissing = True QTreeWidgetItem( self.repositoryList, ["", self.tr( "No plugin repository file available.\nSelect Update.") ]) self.repositoryList.resizeColumnToContents(1) def __downloadFile(self, url, filename, doneMethod=None): """ Private slot to download the given file. @param url URL for the download (string) @param filename local name of the file (string) @param doneMethod method to be called when done """ if self.__networkConfigurationManager.isOnline(): self.__updateButton.setEnabled(False) self.__downloadButton.setEnabled(False) self.__downloadInstallButton.setEnabled(False) self.__downloadCancelButton.setEnabled(True) self.statusLabel.setText(url) self.__doneMethod = doneMethod self.__downloadURL = url self.__downloadFileName = filename self.__downloadIODevice = QFile(self.__downloadFileName + ".tmp") self.__downloadCancelled = False request = QNetworkRequest(QUrl(url)) request.setAttribute(QNetworkRequest.CacheLoadControlAttribute, QNetworkRequest.AlwaysNetwork) reply = self.__networkManager.get(request) reply.finished.connect(self.__downloadFileDone) reply.downloadProgress.connect(self.__downloadProgress) self.__replies.append(reply) else: E5MessageBox.warning( self, self.tr("Error downloading file"), self.tr( """<p>Could not download the requested file""" """ from {0}.</p><p>Error: {1}</p>""" ).format(url, self.tr("Computer is offline."))) def __downloadFileDone(self): """ Private method called, after the file has been downloaded from the internet. """ self.__updateButton.setEnabled(True) self.__downloadCancelButton.setEnabled(False) self.__onlineStateChanged( self.__networkConfigurationManager.isOnline()) ok = True reply = self.sender() if reply in self.__replies: self.__replies.remove(reply) if reply.error() != QNetworkReply.NoError: ok = False if not self.__downloadCancelled: E5MessageBox.warning( self, self.tr("Error downloading file"), self.tr( """<p>Could not download the requested file""" """ from {0}.</p><p>Error: {1}</p>""" ).format(self.__downloadURL, reply.errorString()) ) self.downloadProgress.setValue(0) self.__downloadURL = None self.__downloadIODevice.remove() self.__downloadIODevice = None if self.repositoryList.topLevelItemCount(): if self.repositoryList.currentItem() is None: self.repositoryList.setCurrentItem( self.repositoryList.topLevelItem(0)) else: self.__downloadButton.setEnabled( len(self.__selectedItems())) self.__downloadInstallButton.setEnabled( len(self.__selectedItems())) reply.deleteLater() return self.__downloadIODevice.open(QIODevice.WriteOnly) self.__downloadIODevice.write(reply.readAll()) self.__downloadIODevice.close() if QFile.exists(self.__downloadFileName): QFile.remove(self.__downloadFileName) self.__downloadIODevice.rename(self.__downloadFileName) self.__downloadIODevice = None self.__downloadURL = None reply.deleteLater() if self.__doneMethod is not None: self.__doneMethod(ok, self.__downloadFileName) def __downloadCancel(self): """ Private slot to cancel the current download. """ if self.__replies: reply = self.__replies[0] self.__downloadCancelled = True self.__pluginsToDownload = [] reply.abort() def __downloadProgress(self, done, total): """ Private slot to show the download progress. @param done number of bytes downloaded so far (integer) @param total total bytes to be downloaded (integer) """ if total: self.downloadProgress.setMaximum(total) self.downloadProgress.setValue(done) def addEntry(self, name, short, description, url, author, version, filename, status): """ Public method to add an entry to the list. @param name data for the name field (string) @param short data for the short field (string) @param description data for the description field (list of strings) @param url data for the url field (string) @param author data for the author field (string) @param version data for the version field (string) @param filename data for the filename field (string) @param status status of the plugin (string [stable, unstable, unknown]) """ pluginName = filename.rsplit("-", 1)[0] if pluginName in self.__hiddenPlugins: return if status == "stable": if self.__stableItem is None: self.__stableItem = \ QTreeWidgetItem(self.repositoryList, [self.tr("Stable")]) self.__stableItem.setExpanded(True) parent = self.__stableItem elif status == "unstable": if self.__unstableItem is None: self.__unstableItem = \ QTreeWidgetItem(self.repositoryList, [self.tr("Unstable")]) self.__unstableItem.setExpanded(True) parent = self.__unstableItem else: if self.__unknownItem is None: self.__unknownItem = \ QTreeWidgetItem(self.repositoryList, [self.tr("Unknown")]) self.__unknownItem.setExpanded(True) parent = self.__unknownItem itm = QTreeWidgetItem(parent, [name, version, short]) itm.setData(0, PluginRepositoryWidget.UrlRole, url) itm.setData(0, PluginRepositoryWidget.FilenameRole, filename) itm.setData(0, PluginRepositoryWidget.AuthorRole, author) itm.setData(0, PluginRepositoryWidget.DescrRole, description) updateStatus = self.__updateStatus(filename, version) if updateStatus == PluginRepositoryWidget.PluginStatusUpToDate: itm.setIcon(1, UI.PixmapCache.getIcon("empty.png")) itm.setToolTip(1, self.tr("up-to-date")) elif updateStatus == PluginRepositoryWidget.PluginStatusNew: itm.setIcon(1, UI.PixmapCache.getIcon("download.png")) itm.setToolTip(1, self.tr("new download available")) elif updateStatus == PluginRepositoryWidget.PluginStatusLocalUpdate: itm.setIcon(1, UI.PixmapCache.getIcon("updateLocal.png")) itm.setToolTip(1, self.tr("update installable")) elif updateStatus == PluginRepositoryWidget.PluginStatusRemoteUpdate: itm.setIcon(1, UI.PixmapCache.getIcon("updateRemote.png")) itm.setToolTip(1, self.tr("updated download available")) def __updateStatus(self, filename, version): """ Private method to check, if the given archive update status. @param filename data for the filename field (string) @param version data for the version field (string) @return plug-in update status (integer, one of PluginStatusNew, PluginStatusUpToDate, PluginStatusLocalUpdate, PluginStatusRemoteUpdate) """ archive = os.path.join(Preferences.getPluginManager("DownloadPath"), filename) # check, if it is an update (i.e. we already have archives # with the same pattern) archivesPattern = archive.rsplit('-', 1)[0] + "-*.zip" if len(glob.glob(archivesPattern)) == 0: return PluginRepositoryWidget.PluginStatusNew # check, if the archive exists if not os.path.exists(archive): return PluginRepositoryWidget.PluginStatusRemoteUpdate # check, if the archive is a valid zip file if not zipfile.is_zipfile(archive): return PluginRepositoryWidget.PluginStatusRemoteUpdate zip = zipfile.ZipFile(archive, "r") try: aversion = zip.read("VERSION").decode("utf-8") except KeyError: aversion = "" zip.close() if aversion == version: if not self.__external: # Check against installed/loaded plug-ins pluginManager = e5App().getObject("PluginManager") pluginName = filename.rsplit('-', 1)[0] pluginDetails = pluginManager.getPluginDetails(pluginName) if pluginDetails is None or pluginDetails["version"] < version: return PluginRepositoryWidget.PluginStatusLocalUpdate return PluginRepositoryWidget.PluginStatusUpToDate else: return PluginRepositoryWidget.PluginStatusRemoteUpdate def __sslErrors(self, reply, errors): """ Private slot to handle SSL errors. @param reply reference to the reply object (QNetworkReply) @param errors list of SSL errors (list of QSslError) """ ignored = self.__sslErrorHandler.sslErrorsReply(reply, errors)[0] if ignored == E5SslErrorHandler.NotIgnored: self.__downloadCancelled = True def getDownloadedPlugins(self): """ Public method to get the list of recently downloaded plugin files. @return list of plugin filenames (list of strings) """ return self.__pluginsDownloaded @pyqtSlot(bool) def on_repositoryUrlEditButton_toggled(self, checked): """ Private slot to set the read only status of the repository URL line edit. @param checked state of the push button (boolean) """ self.repositoryUrlEdit.setReadOnly(not checked) def __closeAndInstall(self): """ Private method to close the dialog and invoke the install dialog. """ if not self.__pluginsDownloaded and self.__selectedItems(): for itm in self.__selectedItems(): filename = os.path.join( Preferences.getPluginManager("DownloadPath"), itm.data(0, PluginRepositoryWidget.FilenameRole)) self.__pluginsDownloaded.append(filename) self.closeAndInstall.emit() def __hidePlugin(self): """ Private slot to hide the current plug-in. """ itm = self.__selectedItems()[0] pluginName = (itm.data(0, PluginRepositoryWidget.FilenameRole) .rsplit("-", 1)[0]) self.__updateHiddenPluginsList([pluginName]) def __hideSelectedPlugins(self): """ Private slot to hide all selected plug-ins. """ hideList = [] for itm in self.__selectedItems(): pluginName = (itm.data(0, PluginRepositoryWidget.FilenameRole) .rsplit("-", 1)[0]) hideList.append(pluginName) self.__updateHiddenPluginsList(hideList) def __showAllPlugins(self): """ Private slot to show all plug-ins. """ self.__hiddenPlugins = [] self.__updateHiddenPluginsList([]) def __hasHiddenPlugins(self): """ Private method to check, if there are any hidden plug-ins. @return flag indicating the presence of hidden plug-ins (boolean) """ return bool(self.__hiddenPlugins) def __updateHiddenPluginsList(self, hideList): """ Private method to store the list of hidden plug-ins to the settings. @param hideList list of plug-ins to add to the list of hidden ones (list of string) """ if hideList: self.__hiddenPlugins.extend( [p for p in hideList if p not in self.__hiddenPlugins]) Preferences.setPluginManager("HiddenPlugins", self.__hiddenPlugins) self.__populateList() def __cleanupDownloads(self): """ Private slot to cleanup the plug-in downloads area. """ downloadPath = Preferences.getPluginManager("DownloadPath") downloads = {} # plug-in name as key, file name as value # step 1: extract plug-ins and downloaded files for pluginFile in os.listdir(downloadPath): if not os.path.isfile(os.path.join(downloadPath, pluginFile)): continue pluginName = pluginFile.rsplit("-", 1)[0] if pluginName not in downloads: downloads[pluginName] = [] downloads[pluginName].append(pluginFile) # step 2: delete old entries for pluginName in downloads: downloads[pluginName].sort() if pluginName in self.__hiddenPlugins and \ not Preferences.getPluginManager("KeepHidden"): removeFiles = downloads[pluginName] else: removeFiles = downloads[pluginName][ :-Preferences.getPluginManager("KeepGenerations")] for removeFile in removeFiles: try: os.remove(os.path.join(downloadPath, removeFile)) except (IOError, OSError) as err: E5MessageBox.critical( self, self.tr("Cleanup of Plugin Downloads"), self.tr("""<p>The plugin download <b>{0}</b> could""" """ not be deleted.</p><p>Reason: {1}</p>""") .format(removeFile, str(err)))