def rerenderBlackWhiteList(self): tabs = self.parent().parent() if BMConfigParser().get('bitmessagesettings', 'blackwhitelist') == 'black': tabs.setTabText(tabs.indexOf(self), _translate('blacklist', 'Blacklist')) else: tabs.setTabText(tabs.indexOf(self), _translate('blacklist', 'Whitelist')) self.tableWidgetBlacklist.setRowCount(0) listType = BMConfigParser().get('bitmessagesettings', 'blackwhitelist') if listType == 'black': queryreturn = sqlQuery('''SELECT label, address, enabled FROM blacklist''') else: queryreturn = sqlQuery('''SELECT label, address, enabled FROM whitelist''') self.tableWidgetBlacklist.setSortingEnabled(False) for row in queryreturn: label, address, enabled = row self.tableWidgetBlacklist.insertRow(0) newItem = QtGui.QTableWidgetItem(unicode(label, 'utf-8')) if not enabled: newItem.setTextColor(QtGui.QColor(128, 128, 128)) newItem.setIcon(avatarize(address)) self.tableWidgetBlacklist.setItem(0, 0, newItem) newItem = QtGui.QTableWidgetItem(address) newItem.setFlags( QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled) if not enabled: newItem.setTextColor(QtGui.QColor(128, 128, 128)) self.tableWidgetBlacklist.setItem(0, 1, newItem) self.tableWidgetBlacklist.setSortingEnabled(True)
def test (self): try: if self.nmctype == "namecoind": res = self.callRPC ("getinfo", []) vers = res["version"] v3 = vers % 100 vers = vers / 100 v2 = vers % 100 vers = vers / 100 v1 = vers if v3 == 0: versStr = "0.%d.%d" % (v1, v2) else: versStr = "0.%d.%d.%d" % (v1, v2, v3) return ('success', tr._translate("MainWindow",'Success! Namecoind version %1 running.').arg(unicode(versStr)) ) elif self.nmctype == "nmcontrol": res = self.callRPC ("data", ["status"]) prefix = "Plugin data running" if ("reply" in res) and res["reply"][:len(prefix)] == prefix: return ('success', tr._translate("MainWindow",'Success! NMControll is up and running.')) logger.error("Unexpected nmcontrol reply: %s", res) return ('failed', tr._translate("MainWindow",'Couldn\'t understand NMControl.')) else: assert False except Exception: logger.exception("Namecoin connection test failure") return ('failed', "The connection to namecoin failed.")
def query(self, string): slashPos = string.find('/') if slashPos < 0: string = "id/" + string try: if self.nmctype == "namecoind": res = self.callRPC("name_show", [string]) res = res["value"] elif self.nmctype == "nmcontrol": res = self.callRPC("data", ["getValue", string]) res = res["reply"] if res is False: raise RPCError({"code": -4}) else: assert False except RPCError as exc: if exc.error["code"] == -4: return (tr._translate("MainWindow", 'The name %1 was not found.').arg(unicode(string)), None) else: return (tr._translate("MainWindow", 'The namecoin query failed (%1)').arg(unicode(exc.error["message"])), None) except Exception as exc: print("Namecoin query exception: %s" % str (exc)) return (tr._translate("MainWindow", 'The namecoin query failed.'), None) try: val = json.loads(res) except: return (tr._translate("MainWindow", 'The name %1 has no valid JSON data.').arg(unicode(string)), None) if "bitmessage" in val: return (None, val["bitmessage"]) return (tr._translate("MainWindow", 'The name %1 has no associated Bitmessage address.').arg(unicode(string)), None)
def checkQueue(self): gotOne = False # wait until processing is done if not addressGeneratorQueue.empty(): self.setError(None) return while True: try: addressGeneratorReturnValue = apiAddressGeneratorReturnQueue.get(False) except Empty: if gotOne: break else: return else: gotOne = True if len(addressGeneratorReturnValue) == 0: self.setError(_translate("AddressValidator", "Address already present as one of your identities.")) return (QtGui.QValidator.Intermediate, 0) if addressGeneratorReturnValue[0] == 'chan name does not match address': self.setError(_translate("AddressValidator", "Although the Bitmessage address you entered was valid, it doesn\'t match the chan name.")) return (QtGui.QValidator.Intermediate, 0) self.setOK(_translate("MainWindow", "Passphrase and address appear to be valid."))
def _onSuccess(self, addressVersion, streamNumber, ripe): if addressVersion <= 3: self.checkBoxDisplayMessagesAlreadyInInventory.setText(_translate( "MainWindow", "Address is an old type. We cannot display its past" " broadcasts." )) else: Inventory().flush() doubleHashOfAddressData = hashlib.sha512(hashlib.sha512( encodeVarint(addressVersion) + encodeVarint(streamNumber) + ripe ).digest()).digest() tag = doubleHashOfAddressData[32:] self.recent = Inventory().by_type_and_tag(3, tag) count = len(self.recent) if count == 0: self.checkBoxDisplayMessagesAlreadyInInventory.setText( _translate( "MainWindow", "There are no recent broadcasts from this address" " to display." )) else: self.checkBoxDisplayMessagesAlreadyInInventory.setEnabled(True) self.checkBoxDisplayMessagesAlreadyInInventory.setText( _translate( "MainWindow", "Display the %n recent broadcast(s) from this address.", None, QtCore.QCoreApplication.CodecForTr, count ))
def notifyBuild(tried=False): if bmpow: queues.UISignalQueue.put(('updateStatusBar', (tr._translate("proofofwork", "C PoW module built successfully."), 1))) elif tried: queues.UISignalQueue.put(('updateStatusBar', (tr._translate("proofofwork", "Failed to build C PoW module. Please build it manually."), 1))) else: queues.UISignalQueue.put(('updateStatusBar', (tr._translate("proofofwork", "C PoW module unavailable. Please build it."), 1)))
def __init__(self, encoding, data): self.encoding = encoding if self.encoding == BITMESSAGE_ENCODING_EXTENDED: self.decodeExtended(data) elif self.encoding in [BITMESSAGE_ENCODING_SIMPLE, BITMESSAGE_ENCODING_TRIVIAL]: self.decodeSimple(data) else: self.body = _translate("MsgDecode", "The message has an unknown encoding.\nPerhaps you should upgrade Bitmessage.") self.subject = _translate("MsgDecode", "Unknown encoding")
def updateNumberOfBytes(self): """ This function is run every two seconds, so we divide the rate of bytes sent and received by 2. """ self.labelBytesRecvCount.setText(_translate( "networkstatus", "Down: %1/s Total: %2").arg(self.formatByteRate(network.stats.downloadSpeed()), self.formatBytes(network.stats.receivedBytes()))) self.labelBytesSentCount.setText(_translate( "networkstatus", "Up: %1/s Total: %2").arg(self.formatByteRate(network.stats.uploadSpeed()), self.formatBytes(network.stats.sentBytes())))
def run(self): from debug import logger logger.debug("Starting UPnP thread") logger.debug("Local IP: %s", self.localIP) lastSent = 0 while shared.shutdown == 0 and shared.safeConfigGetBoolean('bitmessagesettings', 'upnp'): if time.time() - lastSent > self.sendSleep and len(self.routers) == 0: try: self.sendSearchRouter() except: pass lastSent = time.time() try: while shared.shutdown == 0 and shared.safeConfigGetBoolean('bitmessagesettings', 'upnp'): resp,(ip,port) = self.sock.recvfrom(1000) if resp is None: continue newRouter = Router(resp, ip) for router in self.routers: if router.location == newRouter.location: break else: logger.debug("Found UPnP router at %s", ip) self.routers.append(newRouter) self.createPortMapping(newRouter) shared.UISignalQueue.put(('updateStatusBar', tr._translate("MainWindow",'UPnP port mapping established on port %1').arg(str(self.extPort)))) break except socket.timeout as e: pass except: logger.error("Failure running UPnP router search.", exc_info=True) for router in self.routers: if router.extPort is None: self.createPortMapping(router) try: self.sock.shutdown(socket.SHUT_RDWR) except: pass try: self.sock.close() except: pass deleted = False for router in self.routers: if router.extPort is not None: deleted = True self.deletePortMapping(router) shared.extPort = None if deleted: shared.UISignalQueue.put(('updateStatusBar', tr._translate("MainWindow",'UPnP port mapping removed'))) logger.debug("UPnP thread done")
def updateNumberOfBytes(self): """ This function is run every two seconds, so we divide the rate of bytes sent and received by 2. """ self.labelBytesRecvCount.setText(_translate( "networkstatus", "Down: %1/s Total: %2").arg(self.formatByteRate(shared.numberOfBytesReceived/2), self.formatBytes(self.totalNumberOfBytesReceived))) self.labelBytesSentCount.setText(_translate( "networkstatus", "Up: %1/s Total: %2").arg(self.formatByteRate(shared.numberOfBytesSent/2), self.formatBytes(self.totalNumberOfBytesSent))) self.totalNumberOfBytesReceived += shared.numberOfBytesReceived self.totalNumberOfBytesSent += shared.numberOfBytesSent shared.numberOfBytesReceived = 0 shared.numberOfBytesSent = 0
def validate(self, s, pos): if self.addressObject is None: address = None else: address = str(self.addressObject.text().toUtf8()) if address == "": address = None if self.passPhraseObject is None: passPhrase = "" else: passPhrase = str(self.passPhraseObject.text().toUtf8()) if passPhrase == "": passPhrase = None # no chan name if passPhrase is None: self.setError(_translate("AddressValidator", "Chan name/passphrase needed. You didn't enter a chan name.")) return (QtGui.QValidator.Intermediate, pos) if self.addressMandatory or address is not None: # check if address already exists: if address in getSortedAccounts(): self.setError(_translate("AddressValidator", "Address already present as one of your identities.")) return (QtGui.QValidator.Intermediate, pos) # version too high if decodeAddress(address)[0] == 'versiontoohigh': self.setError(_translate("AddressValidator", "Address too new. Although that Bitmessage address might be valid, its version number is too new for us to handle. Perhaps you need to upgrade Bitmessage.")) return (QtGui.QValidator.Intermediate, pos) # invalid if decodeAddress(address)[0] != 'success': self.setError(_translate("AddressValidator", "The Bitmessage address is not valid.")) return (QtGui.QValidator.Intermediate, pos) # this just disables the OK button without changing the feedback text # but only if triggered by textEdited, not by clicking the Ok button if not self.buttonBox.button(QtGui.QDialogButtonBox.Ok).hasFocus(): self.setError(None) # check through generator if address is None: addressGeneratorQueue.put(('createChan', 4, 1, str_chan + ' ' + str(passPhrase), passPhrase, False)) else: addressGeneratorQueue.put(('joinChan', addBMIfNotPresent(address), str_chan + ' ' + str(passPhrase), passPhrase, False)) if self.buttonBox.button(QtGui.QDialogButtonBox.Ok).hasFocus(): return (self.returnValid(), pos) else: return (QtGui.QValidator.Intermediate, pos)
def addressChanged(self, QString): status, a, b, c = decodeAddress(str(QString)) if status == 'missingbm': self.ui.labelAddressCheck.setText(_translate( "MainWindow", "The address should start with ''BM-''")) elif status == 'checksumfailed': self.ui.labelAddressCheck.setText(_translate( "MainWindow", "The address is not typed or copied correctly (the checksum failed).")) elif status == 'versiontoohigh': self.ui.labelAddressCheck.setText(_translate( "MainWindow", "The version number of this address is higher than this software can support. Please upgrade Bitmessage.")) elif status == 'invalidcharacters': self.ui.labelAddressCheck.setText(_translate( "MainWindow", "The address contains invalid characters.")) elif status == 'ripetooshort': self.ui.labelAddressCheck.setText(_translate( "MainWindow", "Some data encoded in the address is too short.")) elif status == 'ripetoolong': self.ui.labelAddressCheck.setText(_translate( "MainWindow", "Some data encoded in the address is too long.")) elif status == 'varintmalformed': self.ui.labelAddressCheck.setText(_translate( "MainWindow", "Some data encoded in the address is malformed.")) elif status == 'success': self.ui.labelAddressCheck.setText( _translate("MainWindow", "Address is valid."))
def setError(self, string): if string is not None and self.feedBackObject is not None: font = QtGui.QFont() font.setBold(True) self.feedBackObject.setFont(font) self.feedBackObject.setStyleSheet("QLabel { color : red; }") self.feedBackObject.setText(string) self.isValid = False if self.buttonBox: self.buttonBox.button(QtGui.QDialogButtonBox.Ok).setEnabled(False) if string is not None and self.feedBackObject is not None: self.buttonBox.button(QtGui.QDialogButtonBox.Ok).setText(_translate("AddressValidator", "Invalid")) else: self.buttonBox.button(QtGui.QDialogButtonBox.Ok).setText(_translate("AddressValidator", "Validating..."))
def checkackdata(self, data): # Let's check whether this is a message acknowledgement bound for us. if len(data) < 32: return readPosition = 20 # bypass the nonce, time, and object type # chomp version number versionNumber, varIntLength = decodeVarint( data[readPosition:readPosition + 10]) readPosition += varIntLength # chomp stream number streamNumber, varIntLength = decodeVarint( data[readPosition:readPosition + 10]) readPosition += varIntLength if data[readPosition:] in shared.ackdataForWhichImWatching: logger.info('This object is an acknowledgement bound for me.') del shared.ackdataForWhichImWatching[data[readPosition:]] sqlExecute( 'UPDATE sent SET status=?, lastactiontime=? WHERE ackdata=?', 'ackreceived', int(time.time()), data[readPosition:]) queues.UISignalQueue.put( ('updateSentItemStatusByAckdata', (data[readPosition:], tr._translate( "MainWindow", 'Acknowledgement of the message received %1').arg( l10n.formatTimestamp())))) else: logger.debug('This object is not an acknowledgement bound for me.')
def __init__(self, parent=None, config=None): super(SpecialAddressBehaviorDialog, self).__init__(parent) widgets.load('specialaddressbehavior.ui', self) self.address = parent.getCurrentAccount() self.parent = parent self.config = config try: self.address_is_chan = config.safeGetBoolean(self.address, 'chan') except AttributeError: pass else: if self.address_is_chan: # address is a chan address self.radioButtonBehaviorMailingList.setDisabled(True) self.lineEditMailingListName.setText( _translate( "SpecialAddressBehaviorDialog", "This is a chan address. You cannot use it as a" " pseudo-mailing list.")) else: if config.safeGetBoolean(self.address, 'mailinglist'): self.radioButtonBehaviorMailingList.click() else: self.radioButtonBehaveNormalAddress.click() try: mailingListName = config.get(self.address, 'mailinglistname') except: mailingListName = '' self.lineEditMailingListName.setText( unicode(mailingListName, 'utf-8')) QtGui.QWidget.resize(self, QtGui.QWidget.sizeHint(self)) self.show()
def accept(self): self.timer.stop() self.hide() apiAddressGeneratorReturnQueue.queue.clear() if self.chanAddress.text().toUtf8() == "": addressGeneratorQueue.put(('createChan', 4, 1, str_chan + ' ' + str(self.chanPassPhrase.text().toUtf8()), self.chanPassPhrase.text().toUtf8(), True)) else: addressGeneratorQueue.put(('joinChan', addBMIfNotPresent(self.chanAddress.text().toUtf8()), str_chan + ' ' + str(self.chanPassPhrase.text().toUtf8()), self.chanPassPhrase.text().toUtf8(), True)) addressGeneratorReturnValue = apiAddressGeneratorReturnQueue.get(True) if len(addressGeneratorReturnValue) > 0 and addressGeneratorReturnValue[0] != 'chan name does not match address': UISignalQueue.put(('updateStatusBar', _translate("newchandialog", "Successfully created / joined chan %1").arg(unicode(self.chanPassPhrase.text())))) self.parent.ui.tabWidget.setCurrentIndex(3) self.done(QtGui.QDialog.Accepted) else: UISignalQueue.put(('updateStatusBar', _translate("newchandialog", "Chan creation / joining failed"))) self.done(QtGui.QDialog.Rejected)
def __init__(self, parent=None): super(NetworkStatus, self).__init__(parent) widgets.load('networkstatus.ui', self) header = self.tableWidgetConnectionCount.horizontalHeader() header.setResizeMode(QtGui.QHeaderView.ResizeToContents) # Somehow this value was 5 when I tested if header.sortIndicatorSection() > 4: header.setSortIndicator(0, QtCore.Qt.AscendingOrder) self.startup = time.localtime() self.labelStartupTime.setText(_translate("networkstatus", "Since startup on %1").arg( l10n.formatTimestamp(self.startup))) self.UISignalThread = UISignaler.get() QtCore.QObject.connect(self.UISignalThread, QtCore.SIGNAL( "updateNumberOfMessagesProcessed()"), self.updateNumberOfMessagesProcessed) QtCore.QObject.connect(self.UISignalThread, QtCore.SIGNAL( "updateNumberOfPubkeysProcessed()"), self.updateNumberOfPubkeysProcessed) QtCore.QObject.connect(self.UISignalThread, QtCore.SIGNAL( "updateNumberOfBroadcastsProcessed()"), self.updateNumberOfBroadcastsProcessed) QtCore.QObject.connect(self.UISignalThread, QtCore.SIGNAL( "updateNetworkStatusTab(PyQt_PyObject,PyQt_PyObject,PyQt_PyObject)"), self.updateNetworkStatusTab) self.timer = QtCore.QTimer() QtCore.QObject.connect( self.timer, QtCore.SIGNAL("timeout()"), self.runEveryTwoSeconds)
def __init__(self, parent=None): super(NetworkStatus, self).__init__(parent) widgets.load('networkstatus.ui', self) self.tableWidgetConnectionCount.horizontalHeader().setResizeMode( QtGui.QHeaderView.ResizeToContents) self.startup = time.localtime() self.labelStartupTime.setText( _translate("networkstatus", "Since startup on %1").arg( l10n.formatTimestamp(self.startup))) self.UISignalThread = UISignaler.get() QtCore.QObject.connect( self.UISignalThread, QtCore.SIGNAL("updateNumberOfMessagesProcessed()"), self.updateNumberOfMessagesProcessed) QtCore.QObject.connect( self.UISignalThread, QtCore.SIGNAL("updateNumberOfPubkeysProcessed()"), self.updateNumberOfPubkeysProcessed) QtCore.QObject.connect( self.UISignalThread, QtCore.SIGNAL("updateNumberOfBroadcastsProcessed()"), self.updateNumberOfBroadcastsProcessed) QtCore.QObject.connect(self.UISignalThread, QtCore.SIGNAL("updateNetworkStatusTab()"), self.updateNetworkStatusTab) self.timer = QtCore.QTimer() self.timer.start(2000) # milliseconds QtCore.QObject.connect(self.timer, QtCore.SIGNAL("timeout()"), self.runEveryTwoSeconds)
def updateNumberOfBytes(self): """ This function is run every two seconds, so we divide the rate of bytes sent and received by 2. """ self.labelBytesRecvCount.setText( _translate( "networkstatus", "Down: %1/s Total: %2").arg( self.formatByteRate(network.stats.downloadSpeed()), self.formatBytes(network.stats.receivedBytes()))) self.labelBytesSentCount.setText( _translate( "networkstatus", "Up: %1/s Total: %2").arg( self.formatByteRate(network.stats.uploadSpeed()), self.formatBytes(network.stats.sentBytes())))
def data(self, column, role): if column == 0: if role == QtCore.Qt.DisplayRole: return _translate("MainWindow", self.folderName) + ( " (" + str(self.unreadCount) + ")" if self.unreadCount > 0 else "" ) elif role in (QtCore.Qt.EditRole, QtCore.Qt.ToolTipRole): return _translate("MainWindow", self.folderName) elif role == QtCore.Qt.FontRole: font = QtGui.QFont() font.setBold(self.unreadCount > 0) return font elif role == QtCore.Qt.ForegroundRole: return self.folderBrush() return super(Ui_FolderWidget, self).data(column, role)
def accept(self): self.timer.stop() self.hide() apiAddressGeneratorReturnQueue.queue.clear() if self.chanAddress.text().toUtf8() == "": addressGeneratorQueue.put(('createChan', 4, 1, str_chan + ' ' + str(self.chanPassPhrase.text().toUtf8()), self.chanPassPhrase.text().toUtf8(), True)) else: addressGeneratorQueue.put(('joinChan', addBMIfNotPresent(self.chanAddress.text().toUtf8()), str_chan + ' ' + str(self.chanPassPhrase.text().toUtf8()), self.chanPassPhrase.text().toUtf8(), True)) addressGeneratorReturnValue = apiAddressGeneratorReturnQueue.get(True) if len(addressGeneratorReturnValue) > 0 and addressGeneratorReturnValue[0] != 'chan name does not match address': UISignalQueue.put(('updateStatusBar', _translate("newchandialog", "Successfully created / joined chan %1").arg(str(self.chanPassPhrase.text().toUtf8())))) self.parent.ui.tabWidget.setCurrentIndex(3) self.done(QtGui.QDialog.Accepted) else: UISignalQueue.put(('updateStatusBar', _translate("newchandialog", "Chan creation / joining failed"))) self.done(QtGui.QDialog.Rejected)
def __init__(self, parent=None): super(NetworkStatus, self).__init__(parent) widgets.load('networkstatus.ui', self) header = self.tableWidgetConnectionCount.horizontalHeader() header.setResizeMode(QtGui.QHeaderView.ResizeToContents) # Somehow this value was 5 when I tested if header.sortIndicatorSection() > 4: header.setSortIndicator(0, QtCore.Qt.AscendingOrder) self.startup = time.localtime() self.labelStartupTime.setText(_translate("networkstatus", "Since startup on %1").arg( l10n.formatTimestamp(self.startup))) self.UISignalThread = UISignaler.get() # pylint: disable=no-member QtCore.QObject.connect(self.UISignalThread, QtCore.SIGNAL( "updateNumberOfMessagesProcessed()"), self.updateNumberOfMessagesProcessed) QtCore.QObject.connect(self.UISignalThread, QtCore.SIGNAL( "updateNumberOfPubkeysProcessed()"), self.updateNumberOfPubkeysProcessed) QtCore.QObject.connect(self.UISignalThread, QtCore.SIGNAL( "updateNumberOfBroadcastsProcessed()"), self.updateNumberOfBroadcastsProcessed) QtCore.QObject.connect(self.UISignalThread, QtCore.SIGNAL( "updateNetworkStatusTab(PyQt_PyObject,PyQt_PyObject,PyQt_PyObject)"), self.updateNetworkStatusTab) self.timer = QtCore.QTimer() QtCore.QObject.connect(self.timer, QtCore.SIGNAL("timeout()"), self.runEveryTwoSeconds)
def _doGPUPoW(target, initialHash): logger.debug("GPU PoW start") nonce = openclpow.do_opencl_pow(initialHash.encode("hex"), target) trialValue, = unpack( '>Q', hashlib.sha512( hashlib.sha512(pack('>Q', nonce) + initialHash).digest()).digest()[0:8]) #print "{} - value {} < {}".format(nonce, trialValue, target) if trialValue > target: deviceNames = ", ".join(gpu.name for gpu in openclpow.gpus) UISignalQueue.put(( 'updateStatusBar', tr._translate( "MainWindow", 'Your GPU(s) did not calculate correctly, disabling OpenCL. Please report to the developers.' ))) logger.error( "Your GPUs (%s) did not calculate correctly, disabling OpenCL. Please report to the developers.", deviceNames) openclpow.ctx = False raise Exception("GPU did not calculate correctly.") if shutdown != 0: raise Exception("Interrupted") logger.debug("GPU PoW done") return [trialValue, nonce]
def updateNumberOfBroadcastsProcessed(self): """Update the counter for the number of processed broadcasts""" self.updateNumberOfObjectsToBeSynced() self.labelBroadcastCount.setText( _translate("networkstatus", "Processed %n broadcast message(s).", None, QtCore.QCoreApplication.CodecForTr, state.numberOfBroadcastsProcessed))
def reject(self): self.timer.stop() self.hide() UISignalQueue.put(('updateStatusBar', _translate("newchandialog", "Chan creation / joining cancelled"))) self.done(QtGui.QDialog.Rejected)
def defaultLabel(self): """Default label (in case no label is set manually)""" queryreturn = None retval = None if self.type in (AccountMixin.NORMAL, AccountMixin.CHAN, AccountMixin.MAILINGLIST): try: retval = unicode(BMConfigParser().get(self.address, 'label'), 'utf-8') except Exception: queryreturn = sqlQuery( '''select label from addressbook where address=?''', self.address) elif self.type == AccountMixin.SUBSCRIPTION: queryreturn = sqlQuery( '''select label from subscriptions where address=?''', self.address) if queryreturn is not None: if queryreturn != []: for row in queryreturn: retval, = row retval = unicode(retval, 'utf-8') elif self.address is None or self.type == AccountMixin.ALL: return unicode(str(_translate("MainWindow", "All accounts")), 'utf-8') return retval or unicode(self.address, 'utf-8')
def updateNumberOfMessagesProcessed(self): self.updateNumberOfObjectsToBeSynced() self.labelMessageCount.setText( _translate("networkstatus", "Processed %n person-to-person message(s).", None, QtCore.QCoreApplication.CodecForTr, shared.numberOfMessagesProcessed))
def updateNumberOfPubkeysProcessed(self): """Update the counter for the number of processed pubkeys""" self.updateNumberOfObjectsToBeSynced() self.labelPubkeyCount.setText( _translate("networkstatus", "Processed %n public key(s).", None, QtCore.QCoreApplication.CodecForTr, state.numberOfPubkeysProcessed))
def setError(self, string): if string is not None and self.feedBackObject is not None: font = QtGui.QFont() font.setBold(True) self.feedBackObject.setFont(font) self.feedBackObject.setStyleSheet("QLabel { color : red; }") self.feedBackObject.setText(string) self.isValid = False if self.buttonBox: self.buttonBox.button(QtGui.QDialogButtonBox.Ok).setEnabled(False) if string is not None and self.feedBackObject is not None: self.buttonBox.button(QtGui.QDialogButtonBox.Ok).setText( _translate("AddressValidator", "Invalid")) else: self.buttonBox.button(QtGui.QDialogButtonBox.Ok).setText( _translate("AddressValidator", "Validating..."))
def runEveryTwoSeconds(self): """Updates counters, runs every 2 seconds if the timer is running""" self.labelLookupsPerSecond.setText(_translate("networkstatus", "Inventory lookups per second: %1").arg( str(Inventory().numberOfInventoryLookupsPerformed / 2))) Inventory().numberOfInventoryLookupsPerformed = 0 self.updateNumberOfBytes() self.updateNumberOfObjectsToBeSynced()
def checkTimeOffsetNotification(self): if shared.timeOffsetWrongCount >= 4 and not self.connectionIsOrWasFullyEstablished: queues.UISignalQueue.put(( 'updateStatusBar', tr._translate( "MainWindow", "The time on your computer, %1, may be wrong. Please verify your settings." ).arg(datetime.datetime.now().strftime("%H:%M:%S"))))
def notifyBuild(tried=False): """Notify the user of the success or otherwise of building the PoW C module""" if bmpow: queues.UISignalQueue.put( ('updateStatusBar', (tr._translate("proofofwork", "C PoW module built successfully."), 1))) elif tried: queues.UISignalQueue.put(('updateStatusBar', (tr._translate( "proofofwork", "Failed to build C PoW module. Please build it manually."), 1))) else: queues.UISignalQueue.put( ('updateStatusBar', (tr._translate("proofofwork", "C PoW module unavailable. Please build it."), 1)))
def runEveryTwoSeconds(self): self.labelLookupsPerSecond.setText( _translate( "networkstatus", "Inventory lookups per second: %1").arg( str(Inventory().numberOfInventoryLookupsPerformed / 2))) Inventory().numberOfInventoryLookupsPerformed = 0 self.updateNumberOfBytes() self.updateNumberOfObjectsToBeSynced()
def updateNumberOfObjectsToBeSynced(self): """Update the counter for number of objects to be synced""" self.labelSyncStatus.setText( _translate( "networkstatus", "Object(s) to be synced: %n", None, QtCore.QCoreApplication.CodecForTr, network.stats.pendingDownload() + network.stats.pendingUpload()))
def test(self): try: if self.nmctype == "namecoind": try: vers = self.callRPC("getinfo", [])["version"] except RPCError: vers = self.callRPC("getnetworkinfo", [])["version"] v3 = vers % 100 vers = vers / 100 v2 = vers % 100 vers = vers / 100 v1 = vers if v3 == 0: versStr = "0.%d.%d" % (v1, v2) else: versStr = "0.%d.%d.%d" % (v1, v2, v3) return ('success', tr._translate( "MainWindow", 'Success! Namecoind version %1 running.').arg( unicode(versStr))) elif self.nmctype == "nmcontrol": res = self.callRPC("data", ["status"]) prefix = "Plugin data running" if ("reply" in res) and res["reply"][:len(prefix)] == prefix: return ('success', tr._translate( "MainWindow", 'Success! NMControll is up and running.')) logger.error("Unexpected nmcontrol reply: %s", res) return ('failed', tr._translate("MainWindow", 'Couldn\'t understand NMControl.')) else: assert False except Exception: logger.info("Namecoin connection test failure") return ('failed', tr._translate("MainWindow", "The connection to namecoin failed."))
def accept(self): self.hide() # self.buttonBox.enabled = False if self.radioButtonRandomAddress.isChecked(): if self.radioButtonMostAvailable.isChecked(): streamNumberForAddress = 1 else: # User selected 'Use the same stream as an existing # address.' streamNumberForAddress = decodeAddress( self.comboBoxExisting.currentText())[2] queues.addressGeneratorQueue.put(( 'createRandomAddress', 4, streamNumberForAddress, str(self.newaddresslabel.text().toUtf8()), 1, "", self.checkBoxEighteenByteRipe.isChecked() )) else: if self.lineEditPassphrase.text() != \ self.lineEditPassphraseAgain.text(): QtGui.QMessageBox.about( self, _translate("MainWindow", "Passphrase mismatch"), _translate( "MainWindow", "The passphrase you entered twice doesn\'t" " match. Try again.") ) elif self.lineEditPassphrase.text() == "": QtGui.QMessageBox.about( self, _translate("MainWindow", "Choose a passphrase"), _translate( "MainWindow", "You really do need a passphrase.") ) else: # this will eventually have to be replaced by logic # to determine the most available stream number. streamNumberForAddress = 1 queues.addressGeneratorQueue.put(( 'createDeterministicAddresses', 4, streamNumberForAddress, "unused deterministic address", self.spinBoxNumberOfAddressesToMake.value(), self.lineEditPassphrase.text().toUtf8(), self.checkBoxEighteenByteRipe.isChecked() ))
def formatBytes(self, num): for x in [ _translate("networkstatus", "byte(s)", None, QtCore.QCoreApplication.CodecForTr, num), "kB", "MB", "GB" ]: if num < 1000.0: return "%3.0f %s" % (num, x) num /= 1000.0 return "%3.0f %s" % (num, 'TB')
def query(self, string): slashPos = string.find("/") if slashPos < 0: string = "id/" + string try: if self.nmctype == "namecoind": res = self.callRPC("name_show", [string]) res = res["value"] elif self.nmctype == "nmcontrol": res = self.callRPC("data", ["getValue", string]) res = res["reply"] if res == False: raise RPCError({"code": -4}) else: assert False except RPCError as exc: if exc.error["code"] == -4: return (tr._translate("MainWindow", 'The name %1 was not found.').arg( unicode(string)), None) else: return (tr._translate("MainWindow", 'The namecoin query failed (%1)').arg( unicode(exc.error["message"])), None) except Exception as exc: print "Namecoin query exception: %s" % str(exc) return (tr._translate("MainWindow", 'The namecoin query failed.'), None) try: val = json.loads(res) except: return (tr._translate("MainWindow", 'The name %1 has no valid JSON data.').arg( unicode(string)), None) if "bitmessage" in val: return (None, val["bitmessage"]) return (tr._translate( "MainWindow", 'The name %1 has no associated Bitmessage address.').arg( unicode(string)), None)
def _getLabel(self): if self.address is None: return unicode(_translate( "MainWindow", "All accounts").toUtf8(), 'utf-8', 'ignore') else: try: return unicode( BMConfigParser().get(self.address, 'label'), 'utf-8', 'ignore') except: return unicode(self.address, 'utf-8')
def accept(self): if self.valid: self.data = (addBMIfNotPresent(str(self.lineEditAddress.text())), str(self.lineEditLabel.text().toUtf8())) else: queues.UISignalQueue.put( ('updateStatusBar', _translate( "MainWindow", "The address you entered was invalid. Ignoring it."))) super(AddressDataDialog, self).accept()
def accept(self): if self.valid: self.data = ( addBMIfNotPresent(str(self.lineEditAddress.text())), str(self.lineEditLabel.text().toUtf8()) ) else: queues.UISignalQueue.put(('updateStatusBar', _translate( "MainWindow", "The address you entered was invalid. Ignoring it." ))) super(AddressDataDialog, self).accept()
def __init__(self, parent=None, config=None): super(IconGlossaryDialog, self).__init__(parent) widgets.load('iconglossary.ui', self) # FIXME: check the window title visibility here self.groupBox.setTitle('') self.labelPortNumber.setText(_translate( "iconGlossaryDialog", "You are using TCP port %1. (This can be changed in the settings)." ).arg(config.getint('bitmessagesettings', 'port'))) self.setFixedSize(QtGui.QWidget.sizeHint(self))
def __init__(self, parent=None, config=None): super(IconGlossaryDialog, self).__init__(parent) widgets.load('iconglossary.ui', self) # .. todo:: FIXME: check the window title visibility here self.groupBox.setTitle('') self.labelPortNumber.setText(_translate( "iconGlossaryDialog", "You are using TCP port %1. (This can be changed in the settings)." ).arg(config.getint('bitmessagesettings', 'port'))) self.setFixedSize(QtGui.QWidget.sizeHint(self))
def wheelEvent(self, event): """Mouse wheel scroll event handler""" # super will actually automatically take care of zooming super(MessageView, self).wheelEvent(event) if (QtGui.QApplication.queryKeyboardModifiers() & QtCore.Qt.ControlModifier ) == QtCore.Qt.ControlModifier and event.orientation( ) == QtCore.Qt.Vertical: zoom = self.currentFont().pointSize( ) * 100 / self.defaultFontPointSize QtGui.QApplication.activeWindow().statusBar().showMessage( _translate("MainWindow", "Zoom level %1%").arg(str(zoom)))
def query (self, string): slashPos = string.find ("/") if slashPos < 0: string = "id/" + string try: if self.nmctype == "namecoind": res = self.callRPC ("name_show", [string]) res = res["value"] elif self.nmctype == "nmcontrol": res = self.callRPC ("data", ["getValue", string]) res = res["reply"] if res == False: return (tr._translate("MainWindow",'The name %1 was not found.').arg(unicode(string)), None) else: assert False except RPCError as exc: logger.exception("Namecoin query RPC exception") if isinstance(exc.error, dict): errmsg = exc.error["message"] else: errmsg = exc.error return (tr._translate("MainWindow",'The namecoin query failed (%1)').arg(unicode(errmsg)), None) except Exception as exc: logger.exception("Namecoin query exception") return (tr._translate("MainWindow",'The namecoin query failed.'), None) try: val = json.loads (res) except: logger.exception("Namecoin query json exception") return (tr._translate("MainWindow",'The name %1 has no valid JSON data.').arg(unicode(string)), None) if "bitmessage" in val: if "name" in val: ret = "%s <%s>" % (val["name"], val["bitmessage"]) else: ret = val["bitmessage"] return (None, ret) return (tr._translate("MainWindow",'The name %1 has no associated Bitmessage address.').arg(unicode(string)), None)
def click_pushButtonAddBlacklist(self): self.NewBlacklistDialogInstance = AddAddressDialog(self) if self.NewBlacklistDialogInstance.exec_(): if self.NewBlacklistDialogInstance.labelAddressCheck.text() == \ _translate("MainWindow", "Address is valid."): address = addBMIfNotPresent(str( self.NewBlacklistDialogInstance.lineEditAddress.text())) # First we must check to see if the address is already in the # address book. The user cannot add it again or else it will # cause problems when updating and deleting the entry. t = (address,) if BMConfigParser().get('lmessagesettings', 'blackwhitelist') == 'black': sql = '''select * from blacklist where address=?''' else: sql = '''select * from whitelist where address=?''' queryreturn = sqlQuery(sql,*t) if queryreturn == []: self.tableWidgetBlacklist.setSortingEnabled(False) self.tableWidgetBlacklist.insertRow(0) newItem = QtGui.QTableWidgetItem(unicode( self.NewBlacklistDialogInstance.lineEditLabel.text().toUtf8(), 'utf-8')) newItem.setIcon(avatarize(address)) self.tableWidgetBlacklist.setItem(0, 0, newItem) newItem = QtGui.QTableWidgetItem(address) newItem.setFlags( QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled) self.tableWidgetBlacklist.setItem(0, 1, newItem) self.tableWidgetBlacklist.setSortingEnabled(True) t = (str(self.NewBlacklistDialogInstance.lineEditLabel.text().toUtf8()), address, True) if BMConfigParser().get('lmessagesettings', 'blackwhitelist') == 'black': sql = '''INSERT INTO blacklist VALUES (?,?,?)''' else: sql = '''INSERT INTO whitelist VALUES (?,?,?)''' sqlExecute(sql, *t) else: self.statusBar().showMessage(_translate( "MainWindow", "Error: You cannot add the same address to your list twice. Perhaps rename the existing one if you want.")) else: self.statusBar().showMessage(_translate( "MainWindow", "The address you entered was invalid. Ignoring it."))
def accept(self): """Accept callback""" self.hide() # no chans / mailinglists if self.acct.type != AccountMixin.NORMAL: return if not isinstance(self.acct, GatewayAccount): return if self.radioButtonRegister.isChecked() \ or self.radioButtonRegister.isHidden(): email = str(self.lineEditEmail.text().toUtf8()) self.acct.register(email) self.config.set(self.acct.fromAddress, 'label', email) self.config.set(self.acct.fromAddress, 'gateway', 'mailchuck') self.config.save() queues.UISignalQueue.put( ('updateStatusBar', _translate("EmailGatewayDialog", "Sending email gateway registration request"))) elif self.radioButtonUnregister.isChecked(): self.acct.unregister() self.config.remove_option(self.acct.fromAddress, 'gateway') self.config.save() queues.UISignalQueue.put( ('updateStatusBar', _translate("EmailGatewayDialog", "Sending email gateway unregistration request"))) elif self.radioButtonStatus.isChecked(): self.acct.status() queues.UISignalQueue.put( ('updateStatusBar', _translate("EmailGatewayDialog", "Sending email gateway status request"))) elif self.radioButtonSettings.isChecked(): self.data = self.acct super(EmailGatewayDialog, self).accept()
def click_pushButtonAddBlacklist(self): self.NewBlacklistDialogInstance = AddAddressDialog(self) if self.NewBlacklistDialogInstance.exec_(): if self.NewBlacklistDialogInstance.ui.labelAddressCheck.text() == _translate("MainWindow", "Address is valid."): address = addBMIfNotPresent(str( self.NewBlacklistDialogInstance.ui.lineEditAddress.text())) # First we must check to see if the address is already in the # address book. The user cannot add it again or else it will # cause problems when updating and deleting the entry. t = (address,) if BMConfigParser().get('bitmessagesettings', 'blackwhitelist') == 'black': sql = '''select * from blacklist where address=?''' else: sql = '''select * from whitelist where address=?''' queryreturn = sqlQuery(sql,*t) if queryreturn == []: self.tableWidgetBlacklist.setSortingEnabled(False) self.tableWidgetBlacklist.insertRow(0) newItem = QtGui.QTableWidgetItem(unicode( self.NewBlacklistDialogInstance.ui.newAddressLabel.text().toUtf8(), 'utf-8')) newItem.setIcon(avatarize(address)) self.tableWidgetBlacklist.setItem(0, 0, newItem) newItem = QtGui.QTableWidgetItem(address) newItem.setFlags( QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled) self.tableWidgetBlacklist.setItem(0, 1, newItem) self.tableWidgetBlacklist.setSortingEnabled(True) t = (str(self.NewBlacklistDialogInstance.ui.newAddressLabel.text().toUtf8()), address, True) if BMConfigParser().get('bitmessagesettings', 'blackwhitelist') == 'black': sql = '''INSERT INTO blacklist VALUES (?,?,?)''' else: sql = '''INSERT INTO whitelist VALUES (?,?,?)''' sqlExecute(sql, *t) else: self.statusBar().showMessage(_translate( "MainWindow", "Error: You cannot add the same address to your list twice. Perhaps rename the existing one if you want.")) else: self.statusBar().showMessage(_translate( "MainWindow", "The address you entered was invalid. Ignoring it."))
def __init__(self, parent, config=None, account=None): super(EmailGatewayDialog, self).__init__(parent) widgets.load('emailgateway.ui', self) self.parent = parent self.config = config if account: self.acct = account self.setWindowTitle( _translate("EmailGatewayDialog", "Registration failed:")) self.label.setText( _translate( "EmailGatewayDialog", "The requested email address is not available," " please try a new one.")) self.radioButtonRegister.hide() self.radioButtonStatus.hide() self.radioButtonSettings.hide() self.radioButtonUnregister.hide() else: address = parent.getCurrentAccount() self.acct = accountClass(address) try: label = config.get(address, 'label') except AttributeError: pass else: if "@" in label: self.lineEditEmail.setText(label) if isinstance(self.acct, GatewayAccount): self.radioButtonUnregister.setEnabled(True) self.radioButtonStatus.setEnabled(True) self.radioButtonStatus.setChecked(True) self.radioButtonSettings.setEnabled(True) self.lineEditEmail.setEnabled(False) else: self.acct = MailchuckAccount(address) self.lineEditEmail.setFocus() QtGui.QWidget.resize(self, QtGui.QWidget.sizeHint(self))
def accept(self): self.hide() # no chans / mailinglists if self.acct.type != AccountMixin.NORMAL: return if not isinstance(self.acct, GatewayAccount): return if self.radioButtonRegister.isChecked() \ or self.radioButtonRegister.isHidden(): email = str(self.lineEditEmail.text().toUtf8()) self.acct.register(email) self.config.set(self.acct.fromAddress, 'label', email) self.config.set(self.acct.fromAddress, 'gateway', 'mailchuck') self.config.save() queues.UISignalQueue.put(('updateStatusBar', _translate( "EmailGatewayDialog", "Sending email gateway registration request" ))) elif self.radioButtonUnregister.isChecked(): self.acct.unregister() self.config.remove_option(self.acct.fromAddress, 'gateway') self.config.save() queues.UISignalQueue.put(('updateStatusBar', _translate( "EmailGatewayDialog", "Sending email gateway unregistration request" ))) elif self.radioButtonStatus.isChecked(): self.acct.status() queues.UISignalQueue.put(('updateStatusBar', _translate( "EmailGatewayDialog", "Sending email gateway status request" ))) elif self.radioButtonSettings.isChecked(): self.data = self.acct super(EmailGatewayDialog, self).accept()
def __init__(self, parent, config=None, account=None): super(EmailGatewayDialog, self).__init__(parent) widgets.load('emailgateway.ui', self) self.parent = parent self.config = config if account: self.acct = account self.setWindowTitle(_translate( "EmailGatewayDialog", "Registration failed:")) self.label.setText(_translate( "EmailGatewayDialog", "The requested email address is not available," " please try a new one." )) self.radioButtonRegister.hide() self.radioButtonStatus.hide() self.radioButtonSettings.hide() self.radioButtonUnregister.hide() else: address = parent.getCurrentAccount() self.acct = accountClass(address) try: label = config.get(address, 'label') except AttributeError: pass else: if "@" in label: self.lineEditEmail.setText(label) if isinstance(self.acct, GatewayAccount): self.radioButtonUnregister.setEnabled(True) self.radioButtonStatus.setEnabled(True) self.radioButtonStatus.setChecked(True) self.radioButtonSettings.setEnabled(True) self.lineEditEmail.setEnabled(False) else: self.acct = MailchuckAccount(address) self.lineEditEmail.setFocus() QtGui.QWidget.resize(self, QtGui.QWidget.sizeHint(self))
def _doGPUPoW(target, initialHash): logger.debug("GPU PoW start") nonce = openclpow.do_opencl_pow(initialHash.encode("hex"), target) trialValue, = unpack('>Q',hashlib.sha512(hashlib.sha512(pack('>Q',nonce) + initialHash).digest()).digest()[0:8]) #print "{} - value {} < {}".format(nonce, trialValue, target) if trialValue > target: deviceNames = ", ".join(gpu.name for gpu in openclpow.gpus) UISignalQueue.put(('updateStatusBar', tr._translate("MainWindow",'Your GPU(s) did not calculate correctly, disabling OpenCL. Please report to the developers.'))) logger.error("Your GPUs (%s) did not calculate correctly, disabling OpenCL. Please report to the developers.", deviceNames) openclpow.ctx = False raise Exception("GPU did not calculate correctly.") if shutdown != 0: raise Exception("Interrupted") logger.debug("GPU PoW done") return [trialValue, nonce]
def updateNetworkStatusTab(self): totalNumberOfConnectionsFromAllStreams = 0 # One would think we could use len(sendDataQueues) for this but the number doesn't always match: just because we have a sendDataThread running doesn't mean that the connection has been fully established (with the exchange of version messages). streamNumberTotals = {} for host, streamNumber in shared.connectedHostsList.items(): if not streamNumber in streamNumberTotals: streamNumberTotals[streamNumber] = 1 else: streamNumberTotals[streamNumber] += 1 while self.tableWidgetConnectionCount.rowCount() > 0: self.tableWidgetConnectionCount.removeRow(0) for streamNumber, connectionCount in streamNumberTotals.items(): self.tableWidgetConnectionCount.insertRow(0) if streamNumber == 0: newItem = QtGui.QTableWidgetItem("?") else: newItem = QtGui.QTableWidgetItem(str(streamNumber)) newItem.setFlags( QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled) self.tableWidgetConnectionCount.setItem(0, 0, newItem) newItem = QtGui.QTableWidgetItem(str(connectionCount)) newItem.setFlags( QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled) self.tableWidgetConnectionCount.setItem(0, 1, newItem) """for currentRow in range(self.tableWidgetConnectionCount.rowCount()): rowStreamNumber = int(self.tableWidgetConnectionCount.item(currentRow,0).text()) if streamNumber == rowStreamNumber: foundTheRowThatNeedsUpdating = True self.tableWidgetConnectionCount.item(currentRow,1).setText(str(connectionCount)) #totalNumberOfConnectionsFromAllStreams += connectionCount if foundTheRowThatNeedsUpdating == False: #Add a line to the table for this stream number and update its count with the current connection count. self.tableWidgetConnectionCount.insertRow(0) newItem = QtGui.QTableWidgetItem(str(streamNumber)) newItem.setFlags( QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled ) self.tableWidgetConnectionCount.setItem(0,0,newItem) newItem = QtGui.QTableWidgetItem(str(connectionCount)) newItem.setFlags( QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled ) self.tableWidgetConnectionCount.setItem(0,1,newItem) totalNumberOfConnectionsFromAllStreams += connectionCount""" self.labelTotalConnections.setText(_translate( "networkstatus", "Total Connections: %1").arg(str(len(shared.connectedHostsList)))) if len(shared.connectedHostsList) > 0 and shared.statusIconColor == 'red': # FYI: The 'singlelistener' thread sets the icon color to green when it receives an incoming connection, meaning that the user's firewall is configured correctly. self.window().setStatusIcon('yellow') elif len(shared.connectedHostsList) == 0: self.window().setStatusIcon('red')
def __init__(self, parent=None): super(NetworkStatus, self).__init__(parent) widgets.load('networkstatus.ui', self) self.labelStartupTime.setText(_translate("networkstatus", "Since startup on %1").arg( l10n.formatTimestamp())) self.UISignalThread = UISignaler.get() QtCore.QObject.connect(self.UISignalThread, QtCore.SIGNAL( "updateNumberOfMessagesProcessed()"), self.updateNumberOfMessagesProcessed) QtCore.QObject.connect(self.UISignalThread, QtCore.SIGNAL( "updateNumberOfPubkeysProcessed()"), self.updateNumberOfPubkeysProcessed) QtCore.QObject.connect(self.UISignalThread, QtCore.SIGNAL( "updateNumberOfBroadcastsProcessed()"), self.updateNumberOfBroadcastsProcessed) QtCore.QObject.connect(self.UISignalThread, QtCore.SIGNAL( "updateNetworkStatusTab()"), self.updateNetworkStatusTab) self.totalNumberOfBytesReceived = 0 self.totalNumberOfBytesSent = 0 self.timer = QtCore.QTimer() self.timer.start(2000) # milliseconds QtCore.QObject.connect(self.timer, QtCore.SIGNAL("timeout()"), self.runEveryTwoSeconds)
def __init__(self, parent=None, config=None): super(SpecialAddressBehaviorDialog, self).__init__(parent) widgets.load('specialaddressbehavior.ui', self) self.address = parent.getCurrentAccount() self.parent = parent self.config = config try: self.address_is_chan = config.safeGetBoolean( self.address, 'chan' ) except AttributeError: pass else: if self.address_is_chan: # address is a chan address self.radioButtonBehaviorMailingList.setDisabled(True) self.lineEditMailingListName.setText(_translate( "SpecialAddressBehaviorDialog", "This is a chan address. You cannot use it as a" " pseudo-mailing list." )) else: if config.safeGetBoolean(self.address, 'mailinglist'): self.radioButtonBehaviorMailingList.click() else: self.radioButtonBehaveNormalAddress.click() try: mailingListName = config.get( self.address, 'mailinglistname') except: mailingListName = '' self.lineEditMailingListName.setText( unicode(mailingListName, 'utf-8') ) QtGui.QWidget.resize(self, QtGui.QWidget.sizeHint(self)) self.show()
def defaultLabel(self): queryreturn = None retval = None if self.type in (AccountMixin.NORMAL, AccountMixin.CHAN, AccountMixin.MAILINGLIST): try: retval = unicode(BMConfigParser().get(self.address, 'label'), 'utf-8') except Exception as e: queryreturn = sqlQuery( '''select label from addressbook where address=?''', self.address) elif self.type == AccountMixin.SUBSCRIPTION: queryreturn = sqlQuery( '''select label from subscriptions where address=?''', self.address) if queryreturn is not None: if queryreturn != []: for row in queryreturn: retval, = row retval = unicode(retval, 'utf-8') elif self.address is None or self.type == AccountMixin.ALL: return unicode( str(_translate("MainWindow", "All accounts")), 'utf-8') if retval is None: return unicode(self.address, 'utf-8') else: return retval
def init_blacklist_popup_menu(self, connectSignal=True): # Popup menu for the Blacklist page self.blacklistContextMenuToolbar = QtGui.QToolBar() # Actions self.actionBlacklistNew = self.blacklistContextMenuToolbar.addAction( _translate( "MainWindow", "Add new entry"), self.on_action_BlacklistNew) self.actionBlacklistDelete = self.blacklistContextMenuToolbar.addAction( _translate( "MainWindow", "Delete"), self.on_action_BlacklistDelete) self.actionBlacklistClipboard = self.blacklistContextMenuToolbar.addAction( _translate( "MainWindow", "Copy address to clipboard"), self.on_action_BlacklistClipboard) self.actionBlacklistEnable = self.blacklistContextMenuToolbar.addAction( _translate( "MainWindow", "Enable"), self.on_action_BlacklistEnable) self.actionBlacklistDisable = self.blacklistContextMenuToolbar.addAction( _translate( "MainWindow", "Disable"), self.on_action_BlacklistDisable) self.actionBlacklistSetAvatar = self.blacklistContextMenuToolbar.addAction( _translate( "MainWindow", "Set avatar..."), self.on_action_BlacklistSetAvatar) self.tableWidgetBlacklist.setContextMenuPolicy( QtCore.Qt.CustomContextMenu) if connectSignal: self.connect(self.tableWidgetBlacklist, QtCore.SIGNAL( 'customContextMenuRequested(const QPoint&)'), self.on_context_menuBlacklist) self.popMenuBlacklist = QtGui.QMenu(self) # self.popMenuBlacklist.addAction( self.actionBlacklistNew ) self.popMenuBlacklist.addAction(self.actionBlacklistDelete) self.popMenuBlacklist.addSeparator() self.popMenuBlacklist.addAction(self.actionBlacklistClipboard) self.popMenuBlacklist.addSeparator() self.popMenuBlacklist.addAction(self.actionBlacklistEnable) self.popMenuBlacklist.addAction(self.actionBlacklistDisable) self.popMenuBlacklist.addAction(self.actionBlacklistSetAvatar)