diff --git a/setup.py b/setup.py
index 3e585b6b..58a80dfc 100644
--- a/setup.py
+++ b/setup.py
@@ -54,7 +54,7 @@ if __name__ == "__main__":
libraries=['pthread', 'crypto'],
)
- installRequires = []
+ installRequires = [] # QtPy
packages = [
'pybitmessage',
'pybitmessage.bitmessageqt',
diff --git a/src/bitmessageqt/__init__.py b/src/bitmessageqt/__init__.py
index 440d36b2..df225757 100644
--- a/src/bitmessageqt/__init__.py
+++ b/src/bitmessageqt/__init__.py
@@ -14,8 +14,7 @@ import time
from datetime import datetime, timedelta
from sqlite3 import register_adapter
-from PyQt4 import QtCore, QtGui
-from PyQt4.QtNetwork import QLocalSocket, QLocalServer
+from qtpy import QtCore, QtGui, QtWidgets, QtNetwork
from debug import logger
from tr import _translate
@@ -87,12 +86,12 @@ class MyForm(settingsmixin.SMainWindow):
newlocale = l10n.getTranslationLanguage()
try:
if not self.qmytranslator.isEmpty():
- QtGui.QApplication.removeTranslator(self.qmytranslator)
+ QtWidgets.QApplication.removeTranslator(self.qmytranslator)
except:
pass
try:
if not self.qsystranslator.isEmpty():
- QtGui.QApplication.removeTranslator(self.qsystranslator)
+ QtWidgets.QApplication.removeTranslator(self.qsystranslator)
except:
pass
@@ -100,7 +99,7 @@ class MyForm(settingsmixin.SMainWindow):
translationpath = os.path.join(
paths.codePath(), 'translations', 'bitmessage_' + newlocale)
self.qmytranslator.load(translationpath)
- QtGui.QApplication.installTranslator(self.qmytranslator)
+ QtWidgets.QApplication.installTranslator(self.qmytranslator)
self.qsystranslator = QtCore.QTranslator()
if paths.frozen:
@@ -111,7 +110,7 @@ class MyForm(settingsmixin.SMainWindow):
str(QtCore.QLibraryInfo.location(
QtCore.QLibraryInfo.TranslationsPath)), 'qt_' + newlocale)
self.qsystranslator.load(translationpath)
- QtGui.QApplication.installTranslator(self.qsystranslator)
+ QtWidgets.QApplication.installTranslator(self.qsystranslator)
lang = locale.normalize(l10n.getTranslationLanguage())
langs = [
@@ -134,49 +133,35 @@ class MyForm(settingsmixin.SMainWindow):
logger.error("Failed to set locale to %s", lang, exc_info=True)
def init_file_menu(self):
- QtCore.QObject.connect(self.ui.actionExit, QtCore.SIGNAL(
- "triggered()"), self.quit)
- QtCore.QObject.connect(self.ui.actionNetworkSwitch, QtCore.SIGNAL(
- "triggered()"), self.network_switch)
- QtCore.QObject.connect(self.ui.actionManageKeys, QtCore.SIGNAL(
- "triggered()"), self.click_actionManageKeys)
- QtCore.QObject.connect(self.ui.actionDeleteAllTrashedMessages,
- QtCore.SIGNAL(
- "triggered()"),
- self.click_actionDeleteAllTrashedMessages)
- QtCore.QObject.connect(self.ui.actionRegenerateDeterministicAddresses,
- QtCore.SIGNAL(
- "triggered()"),
- self.click_actionRegenerateDeterministicAddresses)
- QtCore.QObject.connect(self.ui.pushButtonAddChan, QtCore.SIGNAL(
- "clicked()"),
- self.click_actionJoinChan) # also used for creating chans.
- QtCore.QObject.connect(self.ui.pushButtonNewAddress, QtCore.SIGNAL(
- "clicked()"), self.click_NewAddressDialog)
- QtCore.QObject.connect(self.ui.pushButtonAddAddressBook, QtCore.SIGNAL(
- "clicked()"), self.click_pushButtonAddAddressBook)
- QtCore.QObject.connect(self.ui.pushButtonAddSubscription, QtCore.SIGNAL(
- "clicked()"), self.click_pushButtonAddSubscription)
- QtCore.QObject.connect(self.ui.pushButtonTTL, QtCore.SIGNAL(
- "clicked()"), self.click_pushButtonTTL)
- QtCore.QObject.connect(self.ui.pushButtonClear, QtCore.SIGNAL(
- "clicked()"), self.click_pushButtonClear)
- QtCore.QObject.connect(self.ui.pushButtonSend, QtCore.SIGNAL(
- "clicked()"), self.click_pushButtonSend)
- QtCore.QObject.connect(self.ui.pushButtonFetchNamecoinID, QtCore.SIGNAL(
- "clicked()"), self.click_pushButtonFetchNamecoinID)
- QtCore.QObject.connect(self.ui.actionSettings, QtCore.SIGNAL(
- "triggered()"), self.click_actionSettings)
- QtCore.QObject.connect(self.ui.actionAbout, QtCore.SIGNAL(
- "triggered()"), self.click_actionAbout)
- QtCore.QObject.connect(self.ui.actionSupport, QtCore.SIGNAL(
- "triggered()"), self.click_actionSupport)
- QtCore.QObject.connect(self.ui.actionHelp, QtCore.SIGNAL(
- "triggered()"), self.click_actionHelp)
+ self.ui.actionExit.triggered.connect(self.quit)
+ self.ui.actionNetworkSwitch.triggered.connect(self.network_switch)
+ self.ui.actionManageKeys.triggered.connect(self.click_actionManageKeys)
+ self.ui.actionDeleteAllTrashedMessages.triggered.connect(
+ self.click_actionDeleteAllTrashedMessages)
+ self.ui.actionRegenerateDeterministicAddresses.triggered.connect(
+ self.click_actionRegenerateDeterministicAddresses)
+ self.ui.actionSettings.triggered.connect(self.click_actionSettings)
+ self.ui.actionAbout.triggered.connect(self.click_actionAbout)
+ self.ui.actionSupport.triggered.connect(self.click_actionSupport)
+ self.ui.actionHelp.triggered.connect(self.click_actionHelp)
+
+ # also used for creating chans.
+ self.ui.pushButtonAddChan.clicked.connect(self.click_actionJoinChan)
+ self.ui.pushButtonNewAddress.clicked.connect(
+ self.click_NewAddressDialog)
+ self.ui.pushButtonAddAddressBook.clicked.connect(
+ self.click_pushButtonAddAddressBook)
+ self.ui.pushButtonAddSubscription.clicked.connect(
+ self.click_pushButtonAddSubscription)
+ self.ui.pushButtonTTL.clicked.connect(self.click_pushButtonTTL)
+ self.ui.pushButtonClear.clicked.connect(self.click_pushButtonClear)
+ self.ui.pushButtonSend.clicked.connect(self.click_pushButtonSend)
+ self.ui.pushButtonFetchNamecoinID.clicked.connect(
+ self.click_pushButtonFetchNamecoinID)
def init_inbox_popup_menu(self, connectSignal=True):
# Popup menu for the Inbox tab
- self.ui.inboxContextMenuToolbar = QtGui.QToolBar()
+ self.ui.inboxContextMenuToolbar = QtWidgets.QToolBar()
# Actions
self.actionReply = self.ui.inboxContextMenuToolbar.addAction(_translate(
"MainWindow", "Reply to sender"), self.on_action_InboxReply)
@@ -212,25 +197,22 @@ class MyForm(settingsmixin.SMainWindow):
self.ui.tableWidgetInbox.setContextMenuPolicy(
QtCore.Qt.CustomContextMenu)
if connectSignal:
- self.connect(self.ui.tableWidgetInbox, QtCore.SIGNAL(
- 'customContextMenuRequested(const QPoint&)'),
- self.on_context_menuInbox)
+ self.ui.tableWidgetInbox.customContextMenuRequested.connect(
+ self.on_context_menuInbox)
self.ui.tableWidgetInboxSubscriptions.setContextMenuPolicy(
QtCore.Qt.CustomContextMenu)
if connectSignal:
- self.connect(self.ui.tableWidgetInboxSubscriptions, QtCore.SIGNAL(
- 'customContextMenuRequested(const QPoint&)'),
- self.on_context_menuInbox)
+ self.ui.tableWidgetInboxSubscriptions.customContextMenuRequested.connect(
+ self.on_context_menuInbox)
self.ui.tableWidgetInboxChans.setContextMenuPolicy(
QtCore.Qt.CustomContextMenu)
if connectSignal:
- self.connect(self.ui.tableWidgetInboxChans, QtCore.SIGNAL(
- 'customContextMenuRequested(const QPoint&)'),
- self.on_context_menuInbox)
+ self.ui.tableWidgetInboxChans.customContextMenuRequested.connect(
+ self.on_context_menuInbox)
def init_identities_popup_menu(self, connectSignal=True):
# Popup menu for the Your Identities tab
- self.ui.addressContextMenuToolbarYourIdentities = QtGui.QToolBar()
+ self.ui.addressContextMenuToolbarYourIdentities = QtWidgets.QToolBar()
# Actions
self.actionNewYourIdentities = self.ui.addressContextMenuToolbarYourIdentities.addAction(_translate(
"MainWindow", "New"), self.on_action_YourIdentitiesNew)
@@ -264,9 +246,8 @@ class MyForm(settingsmixin.SMainWindow):
self.ui.treeWidgetYourIdentities.setContextMenuPolicy(
QtCore.Qt.CustomContextMenu)
if connectSignal:
- self.connect(self.ui.treeWidgetYourIdentities, QtCore.SIGNAL(
- 'customContextMenuRequested(const QPoint&)'),
- self.on_context_menuYourIdentities)
+ self.ui.treeWidgetYourIdentities.customContextMenuRequested.connect(
+ self.on_context_menuYourIdentities)
# load all gui.menu plugins with prefix 'address'
self.menu_plugins = {'address': []}
@@ -314,13 +295,12 @@ class MyForm(settingsmixin.SMainWindow):
self.ui.treeWidgetChans.setContextMenuPolicy(
QtCore.Qt.CustomContextMenu)
if connectSignal:
- self.connect(self.ui.treeWidgetChans, QtCore.SIGNAL(
- 'customContextMenuRequested(const QPoint&)'),
- self.on_context_menuChan)
+ self.ui.treeWidgetChans.customContextMenuRequested.connect(
+ self.on_context_menuChan)
def init_addressbook_popup_menu(self, connectSignal=True):
# Popup menu for the Address Book page
- self.ui.addressBookContextMenuToolbar = QtGui.QToolBar()
+ self.ui.addressBookContextMenuToolbar = QtWidgets.QToolBar()
# Actions
self.actionAddressBookSend = self.ui.addressBookContextMenuToolbar.addAction(
_translate(
@@ -351,9 +331,8 @@ class MyForm(settingsmixin.SMainWindow):
self.ui.tableWidgetAddressBook.setContextMenuPolicy(
QtCore.Qt.CustomContextMenu)
if connectSignal:
- self.connect(self.ui.tableWidgetAddressBook, QtCore.SIGNAL(
- 'customContextMenuRequested(const QPoint&)'),
- self.on_context_menuAddressBook)
+ self.ui.tableWidgetAddressBook.customContextMenuRequested.connect(
+ self.on_context_menuAddressBook)
def init_subscriptions_popup_menu(self, connectSignal=True):
# Actions
@@ -380,9 +359,8 @@ class MyForm(settingsmixin.SMainWindow):
self.ui.treeWidgetSubscriptions.setContextMenuPolicy(
QtCore.Qt.CustomContextMenu)
if connectSignal:
- self.connect(self.ui.treeWidgetSubscriptions, QtCore.SIGNAL(
- 'customContextMenuRequested(const QPoint&)'),
- self.on_context_menuSubscriptions)
+ self.ui.treeWidgetSubscriptions.customContextMenuRequested.connect(
+ self.on_context_menuSubscriptions)
def init_sent_popup_menu(self, connectSignal=True):
# Actions
@@ -399,7 +377,7 @@ class MyForm(settingsmixin.SMainWindow):
self.actionSentReply = self.ui.sentContextMenuToolbar.addAction(
_translate("MainWindow", "Send update"),
self.on_action_SentReply)
- # self.popMenuSent = QtGui.QMenu( self )
+ # self.popMenuSent = QtWidgets.QMenu( self )
# self.popMenuSent.addAction( self.actionSentClipboard )
# self.popMenuSent.addAction( self.actionTrashSentMessage )
@@ -413,17 +391,16 @@ class MyForm(settingsmixin.SMainWindow):
treeWidget.header().setSortIndicator(
0, QtCore.Qt.AscendingOrder)
# init dictionary
-
+
db = getSortedSubscriptions(True)
for address in db:
for folder in folders:
- if not folder in db[address]:
+ if folder not in db[address]:
db[address][folder] = {}
-
+
if treeWidget.isSortingEnabled():
treeWidget.setSortingEnabled(False)
- widgets = {}
i = 0
while i < treeWidget.topLevelItemCount():
widget = treeWidget.topLevelItem(i)
@@ -431,8 +408,8 @@ class MyForm(settingsmixin.SMainWindow):
toAddress = widget.address
else:
toAddress = None
-
- if not toAddress in db:
+
+ if toAddress not in db:
treeWidget.takeTopLevelItem(i)
# no increment
continue
@@ -441,7 +418,8 @@ class MyForm(settingsmixin.SMainWindow):
while j < widget.childCount():
subwidget = widget.child(j)
try:
- subwidget.setUnreadCount(db[toAddress][subwidget.folderName]['count'])
+ subwidget.setUnreadCount(
+ db[toAddress][subwidget.folderName]['count'])
unread += db[toAddress][subwidget.folderName]['count']
db[toAddress].pop(subwidget.folderName, None)
except:
@@ -455,45 +433,51 @@ class MyForm(settingsmixin.SMainWindow):
j = 0
for f, c in db[toAddress].iteritems():
try:
- subwidget = Ui_FolderWidget(widget, j, toAddress, f, c['count'])
+ subwidget = Ui_FolderWidget(
+ widget, j, toAddress, f, c['count'])
except KeyError:
subwidget = Ui_FolderWidget(widget, j, toAddress, f, 0)
j += 1
widget.setUnreadCount(unread)
db.pop(toAddress, None)
i += 1
-
+
i = 0
for toAddress in db:
- widget = Ui_SubscriptionWidget(treeWidget, i, toAddress, db[toAddress]["inbox"]['count'], db[toAddress]["inbox"]['label'], db[toAddress]["inbox"]['enabled'])
+ widget = Ui_SubscriptionWidget(
+ treeWidget, i, toAddress, db[toAddress]["inbox"]['count'],
+ db[toAddress]["inbox"]['label'],
+ db[toAddress]["inbox"]['enabled'])
j = 0
unread = 0
for folder in folders:
try:
- subwidget = Ui_FolderWidget(widget, j, toAddress, folder, db[toAddress][folder]['count'])
+ subwidget = Ui_FolderWidget(
+ widget, j, toAddress, folder,
+ db[toAddress][folder]['count'])
unread += db[toAddress][folder]['count']
except KeyError:
- subwidget = Ui_FolderWidget(widget, j, toAddress, folder, 0)
+ subwidget = Ui_FolderWidget(
+ widget, j, toAddress, folder, 0)
j += 1
widget.setUnreadCount(unread)
i += 1
-
- treeWidget.setSortingEnabled(True)
+ treeWidget.setSortingEnabled(True)
def rerenderTabTreeMessages(self):
self.rerenderTabTree('messages')
def rerenderTabTreeChans(self):
self.rerenderTabTree('chan')
-
+
def rerenderTabTree(self, tab):
if tab == 'messages':
treeWidget = self.ui.treeWidgetYourIdentities
elif tab == 'chan':
treeWidget = self.ui.treeWidgetChans
folders = Ui_FolderWidget.folderWeight.keys()
-
+
# sort ascending when creating
if treeWidget.topLevelItemCount() == 0:
treeWidget.header().setSortIndicator(
@@ -501,14 +485,14 @@ class MyForm(settingsmixin.SMainWindow):
# init dictionary
db = {}
enabled = {}
-
+
for toAddress in getSortedAccounts():
isEnabled = BMConfigParser().getboolean(
toAddress, 'enabled')
isChan = BMConfigParser().safeGetBoolean(
toAddress, 'chan')
- isMaillinglist = BMConfigParser().safeGetBoolean(
- toAddress, 'mailinglist')
+ # isMaillinglist = BMConfigParser().safeGetBoolean(
+ # toAddress, 'mailinglist')
if treeWidget == self.ui.treeWidgetYourIdentities:
if isChan:
@@ -520,7 +504,7 @@ class MyForm(settingsmixin.SMainWindow):
db[toAddress] = {}
for folder in folders:
db[toAddress][folder] = 0
-
+
enabled[toAddress] = isEnabled
# get number of (unread) messages
@@ -538,11 +522,10 @@ class MyForm(settingsmixin.SMainWindow):
db[None]["sent"] = 0
db[None]["trash"] = 0
enabled[None] = True
-
+
if treeWidget.isSortingEnabled():
treeWidget.setSortingEnabled(False)
-
- widgets = {}
+
i = 0
while i < treeWidget.topLevelItemCount():
widget = treeWidget.topLevelItem(i)
@@ -550,8 +533,8 @@ class MyForm(settingsmixin.SMainWindow):
toAddress = widget.address
else:
toAddress = None
-
- if not toAddress in db:
+
+ if toAddress not in db:
treeWidget.takeTopLevelItem(i)
# no increment
continue
@@ -560,7 +543,8 @@ class MyForm(settingsmixin.SMainWindow):
while j < widget.childCount():
subwidget = widget.child(j)
try:
- subwidget.setUnreadCount(db[toAddress][subwidget.folderName])
+ subwidget.setUnreadCount(
+ db[toAddress][subwidget.folderName])
if subwidget.folderName not in ["new", "trash", "sent"]:
unread += db[toAddress][subwidget.folderName]
db[toAddress].pop(subwidget.folderName, None)
@@ -583,7 +567,7 @@ class MyForm(settingsmixin.SMainWindow):
widget.setUnreadCount(unread)
db.pop(toAddress, None)
i += 1
-
+
i = 0
for toAddress in db:
widget = Ui_AddressWidget(treeWidget, i, toAddress, db[toAddress]["inbox"], enabled[toAddress])
@@ -598,11 +582,11 @@ class MyForm(settingsmixin.SMainWindow):
j += 1
widget.setUnreadCount(unread)
i += 1
-
+
treeWidget.setSortingEnabled(True)
def __init__(self, parent=None):
- QtGui.QWidget.__init__(self, parent)
+ super(MyForm, self).__init__(parent)
self.ui = Ui_MainWindow()
self.ui.setupUi(self)
@@ -620,11 +604,13 @@ class MyForm(settingsmixin.SMainWindow):
addressInKeysFile)
if addressVersionNumber == 1:
displayMsg = _translate(
- "MainWindow", "One of your addresses, %1, is an old version 1 address. Version 1 addresses are no longer supported. "
- + "May we delete it now?").arg(addressInKeysFile)
- reply = QtGui.QMessageBox.question(
- self, 'Message', displayMsg, QtGui.QMessageBox.Yes, QtGui.QMessageBox.No)
- if reply == QtGui.QMessageBox.Yes:
+ "MainWindow",
+ "One of your addresses, {0}, is an old version 1"
+ " address. Version 1 addresses are no longer supported."
+ " May we delete it now?").format(addressInKeysFile)
+ reply = QtWidgets.QMessageBox.question(
+ self, 'Message', displayMsg, QtWidgets.QMessageBox.Yes, QtWidgets.QMessageBox.No)
+ if reply == QtWidgets.QMessageBox.Yes:
BMConfigParser().remove_section(addressInKeysFile)
BMConfigParser().save()
@@ -670,65 +656,58 @@ class MyForm(settingsmixin.SMainWindow):
self.rerenderSubscriptions()
# Initialize the inbox search
- QtCore.QObject.connect(self.ui.inboxSearchLineEdit, QtCore.SIGNAL(
- "returnPressed()"), self.inboxSearchLineEditReturnPressed)
- QtCore.QObject.connect(self.ui.inboxSearchLineEditSubscriptions, QtCore.SIGNAL(
- "returnPressed()"), self.inboxSearchLineEditReturnPressed)
- QtCore.QObject.connect(self.ui.inboxSearchLineEditChans, QtCore.SIGNAL(
- "returnPressed()"), self.inboxSearchLineEditReturnPressed)
- QtCore.QObject.connect(self.ui.inboxSearchLineEdit, QtCore.SIGNAL(
- "textChanged(QString)"), self.inboxSearchLineEditUpdated)
- QtCore.QObject.connect(self.ui.inboxSearchLineEditSubscriptions, QtCore.SIGNAL(
- "textChanged(QString)"), self.inboxSearchLineEditUpdated)
- QtCore.QObject.connect(self.ui.inboxSearchLineEditChans, QtCore.SIGNAL(
- "textChanged(QString)"), self.inboxSearchLineEditUpdated)
+ for line_edit in (
+ self.ui.inboxSearchLineEdit,
+ self.ui.inboxSearchLineEditSubscriptions,
+ self.ui.inboxSearchLineEditChans,
+ ):
+ line_edit.returnPressed.connect(
+ self.inboxSearchLineEditReturnPressed)
+ line_edit.textChanged.connect(
+ self.inboxSearchLineEditUpdated)
# Initialize addressbook
- QtCore.QObject.connect(self.ui.tableWidgetAddressBook, QtCore.SIGNAL(
- "itemChanged(QTableWidgetItem *)"), self.tableWidgetAddressBookItemChanged)
+ self.ui.tableWidgetAddressBook.itemChanged.connect(
+ self.tableWidgetAddressBookItemChanged)
+
# This is necessary for the completer to work if multiple recipients
- QtCore.QObject.connect(self.ui.lineEditTo, QtCore.SIGNAL(
- "cursorPositionChanged(int, int)"), self.ui.lineEditTo.completer().onCursorPositionChanged)
+ self.ui.lineEditTo.cursorPositionChanged.connect(
+ self.ui.lineEditTo.completer().onCursorPositionChanged)
# show messages from message list
- QtCore.QObject.connect(self.ui.tableWidgetInbox, QtCore.SIGNAL(
- "itemSelectionChanged ()"), self.tableWidgetInboxItemClicked)
- QtCore.QObject.connect(self.ui.tableWidgetInboxSubscriptions, QtCore.SIGNAL(
- "itemSelectionChanged ()"), self.tableWidgetInboxItemClicked)
- QtCore.QObject.connect(self.ui.tableWidgetInboxChans, QtCore.SIGNAL(
- "itemSelectionChanged ()"), self.tableWidgetInboxItemClicked)
+ for table_widget in (
+ self.ui.tableWidgetInbox,
+ self.ui.tableWidgetInboxSubscriptions,
+ self.ui.tableWidgetInboxChans
+ ):
+ table_widget.itemSelectionChanged.connect(
+ self.tableWidgetInboxItemClicked)
# tree address lists
- QtCore.QObject.connect(self.ui.treeWidgetYourIdentities, QtCore.SIGNAL(
- "itemSelectionChanged ()"), self.treeWidgetItemClicked)
- QtCore.QObject.connect(self.ui.treeWidgetYourIdentities, QtCore.SIGNAL(
- "itemChanged (QTreeWidgetItem *, int)"), self.treeWidgetItemChanged)
- QtCore.QObject.connect(self.ui.treeWidgetSubscriptions, QtCore.SIGNAL(
- "itemSelectionChanged ()"), self.treeWidgetItemClicked)
- QtCore.QObject.connect(self.ui.treeWidgetSubscriptions, QtCore.SIGNAL(
- "itemChanged (QTreeWidgetItem *, int)"), self.treeWidgetItemChanged)
- QtCore.QObject.connect(self.ui.treeWidgetChans, QtCore.SIGNAL(
- "itemSelectionChanged ()"), self.treeWidgetItemClicked)
- QtCore.QObject.connect(self.ui.treeWidgetChans, QtCore.SIGNAL(
- "itemChanged (QTreeWidgetItem *, int)"), self.treeWidgetItemChanged)
- QtCore.QObject.connect(
- self.ui.tabWidget, QtCore.SIGNAL("currentChanged(int)"),
- self.tabWidgetCurrentChanged
- )
+ for tree_widget in (
+ self.ui.treeWidgetYourIdentities,
+ self.ui.treeWidgetSubscriptions,
+ self.ui.treeWidgetChans
+ ):
+ tree_widget.itemSelectionChanged.connect(
+ self.treeWidgetItemClicked)
+ tree_widget.itemChanged.connect(self.treeWidgetItemChanged)
+
+ self.ui.tabWidget.currentChanged.connect(self.tabWidgetCurrentChanged)
# Put the colored icon on the status bar
# self.pushButtonStatusIcon.setIcon(QIcon(":/newPrefix/images/yellowicon.png"))
self.setStatusBar(BMStatusBar())
self.statusbar = self.statusBar()
- self.pushButtonStatusIcon = QtGui.QPushButton(self)
+ self.pushButtonStatusIcon = QtWidgets.QPushButton(self)
self.pushButtonStatusIcon.setText('')
self.pushButtonStatusIcon.setIcon(
QtGui.QIcon(':/newPrefix/images/redicon.png'))
self.pushButtonStatusIcon.setFlat(True)
self.statusbar.insertPermanentWidget(0, self.pushButtonStatusIcon)
- QtCore.QObject.connect(self.pushButtonStatusIcon, QtCore.SIGNAL(
- "clicked()"), self.click_pushButtonStatusIcon)
+ self.pushButtonStatusIcon.clicked.connect(
+ self.click_pushButtonStatusIcon)
self.numberOfMessagesProcessed = 0
self.numberOfBroadcastsProcessed = 0
@@ -736,44 +715,41 @@ class MyForm(settingsmixin.SMainWindow):
self.unreadCount = 0
# Set the icon sizes for the identicons
- identicon_size = 3*7
- self.ui.tableWidgetInbox.setIconSize(QtCore.QSize(identicon_size, identicon_size))
- self.ui.treeWidgetChans.setIconSize(QtCore.QSize(identicon_size, identicon_size))
- self.ui.treeWidgetYourIdentities.setIconSize(QtCore.QSize(identicon_size, identicon_size))
- self.ui.treeWidgetSubscriptions.setIconSize(QtCore.QSize(identicon_size, identicon_size))
- self.ui.tableWidgetAddressBook.setIconSize(QtCore.QSize(identicon_size, identicon_size))
-
+ identicon_size = 3 * 7
+ for widget in (
+ self.ui.tableWidgetInbox, self.ui.treeWidgetChans,
+ self.ui.treeWidgetYourIdentities, self.ui.treeWidgetSubscriptions,
+ self.ui.tableWidgetAddressBook
+ ):
+ widget.setIconSize(QtCore.QSize(identicon_size, identicon_size))
+
self.UISignalThread = UISignaler.get()
- QtCore.QObject.connect(self.UISignalThread, QtCore.SIGNAL(
- "writeNewAddressToTable(PyQt_PyObject,PyQt_PyObject,PyQt_PyObject)"), self.writeNewAddressToTable)
- QtCore.QObject.connect(self.UISignalThread, QtCore.SIGNAL(
- "updateStatusBar(PyQt_PyObject)"), self.updateStatusBar)
- QtCore.QObject.connect(self.UISignalThread, QtCore.SIGNAL(
- "updateSentItemStatusByToAddress(PyQt_PyObject,PyQt_PyObject)"), self.updateSentItemStatusByToAddress)
- QtCore.QObject.connect(self.UISignalThread, QtCore.SIGNAL(
- "updateSentItemStatusByAckdata(PyQt_PyObject,PyQt_PyObject)"), self.updateSentItemStatusByAckdata)
- QtCore.QObject.connect(self.UISignalThread, QtCore.SIGNAL(
- "displayNewInboxMessage(PyQt_PyObject,PyQt_PyObject,PyQt_PyObject,PyQt_PyObject,PyQt_PyObject)"), self.displayNewInboxMessage)
- QtCore.QObject.connect(self.UISignalThread, QtCore.SIGNAL(
- "displayNewSentMessage(PyQt_PyObject,PyQt_PyObject,PyQt_PyObject,PyQt_PyObject,PyQt_PyObject,PyQt_PyObject)"), self.displayNewSentMessage)
- QtCore.QObject.connect(self.UISignalThread, QtCore.SIGNAL(
- "setStatusIcon(PyQt_PyObject)"), self.setStatusIcon)
- QtCore.QObject.connect(self.UISignalThread, QtCore.SIGNAL(
- "changedInboxUnread(PyQt_PyObject)"), self.changedInboxUnread)
- QtCore.QObject.connect(self.UISignalThread, QtCore.SIGNAL(
- "rerenderMessagelistFromLabels()"), self.rerenderMessagelistFromLabels)
- QtCore.QObject.connect(self.UISignalThread, QtCore.SIGNAL(
- "rerenderMessgelistToLabels()"), self.rerenderMessagelistToLabels)
- QtCore.QObject.connect(self.UISignalThread, QtCore.SIGNAL(
- "rerenderAddressBook()"), self.rerenderAddressBook)
- QtCore.QObject.connect(self.UISignalThread, QtCore.SIGNAL(
- "rerenderSubscriptions()"), self.rerenderSubscriptions)
- QtCore.QObject.connect(self.UISignalThread, QtCore.SIGNAL(
- "removeInboxRowByMsgid(PyQt_PyObject)"), self.removeInboxRowByMsgid)
- QtCore.QObject.connect(self.UISignalThread, QtCore.SIGNAL(
- "newVersionAvailable(PyQt_PyObject)"), self.newVersionAvailable)
- QtCore.QObject.connect(self.UISignalThread, QtCore.SIGNAL(
- "displayAlert(PyQt_PyObject,PyQt_PyObject,PyQt_PyObject)"), self.displayAlert)
+ self.UISignalThread.writeNewAddressToTable.connect(
+ self.writeNewAddressToTable)
+ self.UISignalThread.updateStatusBar.connect(self.updateStatusBar)
+ self.UISignalThread.updateSentItemStatusByToAddress.connect(
+ self.updateSentItemStatusByToAddress)
+ self.UISignalThread.updateSentItemStatusByAckdata.connect(
+ self.updateSentItemStatusByAckdata)
+ self.UISignalThread.displayNewInboxMessage.connect(
+ self.displayNewInboxMessage)
+ self.UISignalThread.displayNewSentMessage.connect(
+ self.displayNewSentMessage)
+ self.UISignalThread.setStatusIcon.connect(self.setStatusIcon)
+ self.UISignalThread.changedInboxUnread.connect(self.changedInboxUnread)
+ self.UISignalThread.rerenderMessagelistFromLabels.connect(
+ self.rerenderMessagelistFromLabels)
+ self.UISignalThread.rerenderMessagelistToLabels.connect(
+ self.rerenderMessagelistToLabels)
+ self.UISignalThread.rerenderAddressBook.connect(
+ self.rerenderAddressBook)
+ self.UISignalThread.rerenderSubscriptions.connect(
+ self.rerenderSubscriptions)
+ self.UISignalThread.removeInboxRowByMsgid.connect(
+ self.removeInboxRowByMsgid)
+ self.UISignalThread.newVersionAvailable.connect(
+ self.newVersionAvailable)
+ self.UISignalThread.displayAlert.connect(self.displayAlert)
self.UISignalThread.start()
# Key press in tree view
@@ -799,19 +775,18 @@ class MyForm(settingsmixin.SMainWindow):
self.rerenderComboBoxSendFrom()
self.rerenderComboBoxSendFromBroadcast()
-
+
# Put the TTL slider in the correct spot
TTL = BMConfigParser().getint('bitmessagesettings', 'ttl')
- if TTL < 3600: # an hour
+ if TTL < 3600: # an hour
TTL = 3600
- elif TTL > 28*24*60*60: # 28 days
- TTL = 28*24*60*60
- self.ui.horizontalSliderTTL.setSliderPosition((TTL - 3600) ** (1/3.199))
+ elif TTL > 28 * 24 * 60 * 60: # 28 days
+ TTL = 28 * 24 * 60 * 60
+ self.ui.horizontalSliderTTL.setSliderPosition(
+ (TTL - 3600) ** (1 / 3.199))
self.updateHumanFriendlyTTLDescription(TTL)
-
- QtCore.QObject.connect(self.ui.horizontalSliderTTL, QtCore.SIGNAL(
- "valueChanged(int)"), self.updateTTL)
+ self.ui.horizontalSliderTTL.valueChanged.connect(self.updateTTL)
self.initSettings()
self.resetNamecoinConnection()
@@ -855,21 +830,25 @@ class MyForm(settingsmixin.SMainWindow):
BMConfigParser().save()
def updateHumanFriendlyTTLDescription(self, TTL):
- numberOfHours = int(round(TTL / (60*60)))
+ numberOfHours = int(round(TTL / (60 * 60)))
font = QtGui.QFont()
stylesheet = ""
if numberOfHours < 48:
self.ui.labelHumanFriendlyTTLDescription.setText(
- _translate("MainWindow", "%n hour(s)", None, QtCore.QCoreApplication.CodecForTr, numberOfHours) +
- ", " +
- _translate("MainWindow", "not recommended for chans", None, QtCore.QCoreApplication.CodecForTr)
- )
+ _translate(
+ "MainWindow", "%n hour(s)", None, numberOfHours
+ ) + ",\n" +
+ _translate("MainWindow", "not recommended for chans")
+ )
stylesheet = "QLabel { color : red; }"
font.setBold(True)
else:
- numberOfDays = int(round(TTL / (24*60*60)))
- self.ui.labelHumanFriendlyTTLDescription.setText(_translate("MainWindow", "%n day(s)", None, QtCore.QCoreApplication.CodecForTr, numberOfDays))
+ numberOfDays = int(round(TTL / (24 * 60 * 60)))
+ self.ui.labelHumanFriendlyTTLDescription.setText(
+ _translate(
+ "MainWindow", "%n day(s)", None, numberOfDays)
+ )
font.setBold(False)
self.ui.labelHumanFriendlyTTLDescription.setStyleSheet(stylesheet)
self.ui.labelHumanFriendlyTTLDescription.setFont(font)
@@ -976,8 +955,7 @@ class MyForm(settingsmixin.SMainWindow):
# related = related.findItems(msgid, QtCore.Qt.MatchExactly),
# returns an empty list
for rrow in xrange(related.rowCount()):
- if msgid == str(related.item(rrow, 3).data(
- QtCore.Qt.UserRole).toPyObject()):
+ if msgid == related.item(rrow, 3).data(QtCore.Qt.UserRole):
break
else:
rrow = None
@@ -1086,16 +1064,19 @@ class MyForm(settingsmixin.SMainWindow):
if sortingEnabled:
tableWidget.setSortingEnabled(True)
- def addMessageListItemSent(self, tableWidget, toAddress, fromAddress, subject, status, ackdata, lastactiontime):
+ def addMessageListItemSent(
+ self, tableWidget, toAddress, fromAddress, subject, status,
+ ackdata, lastactiontime
+ ):
acct = accountClass(fromAddress)
if acct is None:
acct = BMAccount(fromAddress)
acct.parseMessage(toAddress, fromAddress, subject, "")
items = []
- MessageList_AddressWidget(items, str(toAddress), unicode(acct.toLabel, 'utf-8'))
- MessageList_AddressWidget(items, str(fromAddress), unicode(acct.fromLabel, 'utf-8'))
- MessageList_SubjectWidget(items, str(subject), unicode(acct.subject, 'utf-8', 'replace'))
+ MessageList_AddressWidget(items, toAddress, acct.toLabel)
+ MessageList_AddressWidget(items, fromAddress, acct.fromLabel)
+ MessageList_SubjectWidget(items, subject, acct.subject)
if status == 'awaitingpubkey':
statusText = _translate(
@@ -1107,17 +1088,21 @@ class MyForm(settingsmixin.SMainWindow):
statusText = _translate(
"MainWindow", "Queued.")
elif status == 'msgsent':
- statusText = _translate("MainWindow", "Message sent. Waiting for acknowledgement. Sent at %1").arg(
- l10n.formatTimestamp(lastactiontime))
+ statusText = _translate(
+ "MainWindow",
+ "Message sent. Waiting for acknowledgement. Sent at {0}"
+ ).format(l10n.formatTimestamp(lastactiontime))
elif status == 'msgsentnoackexpected':
- statusText = _translate("MainWindow", "Message sent. Sent at %1").arg(
- l10n.formatTimestamp(lastactiontime))
+ statusText = _translate(
+ "MainWindow", "Message sent. Sent at {0}"
+ ).format(l10n.formatTimestamp(lastactiontime))
elif status == 'doingmsgpow':
statusText = _translate(
"MainWindow", "Doing work necessary to send message.")
elif status == 'ackreceived':
- statusText = _translate("MainWindow", "Acknowledgement of the message received %1").arg(
- l10n.formatTimestamp(lastactiontime))
+ statusText = _translate(
+ "MainWindow", "Acknowledgement of the message received {0}"
+ ).format(l10n.formatTimestamp(lastactiontime))
elif status == 'broadcastqueued':
statusText = _translate(
"MainWindow", "Broadcast queued.")
@@ -1125,23 +1110,31 @@ class MyForm(settingsmixin.SMainWindow):
statusText = _translate(
"MainWindow", "Doing work necessary to send broadcast.")
elif status == 'broadcastsent':
- statusText = _translate("MainWindow", "Broadcast on %1").arg(
- l10n.formatTimestamp(lastactiontime))
+ statusText = _translate("MainWindow", "Broadcast on {0}").format(
+ l10n.formatTimestamp(lastactiontime)
+ )
elif status == 'toodifficult':
- statusText = _translate("MainWindow", "Problem: The work demanded by the recipient is more difficult than you are willing to do. %1").arg(
- l10n.formatTimestamp(lastactiontime))
+ statusText = _translate(
+ "MainWindow",
+ "Problem: The work demanded by the recipient is more"
+ " difficult than you are willing to do. {0}"
+ ).format(l10n.formatTimestamp(lastactiontime))
elif status == 'badkey':
- statusText = _translate("MainWindow", "Problem: The recipient\'s encryption key is no good. Could not encrypt message. %1").arg(
- l10n.formatTimestamp(lastactiontime))
+ statusText = _translate(
+ "MainWindow",
+ "Problem: The recipient\'s encryption key is no good."
+ " Could not encrypt message. {0}"
+ ).format(l10n.formatTimestamp(lastactiontime))
elif status == 'forcepow':
statusText = _translate(
"MainWindow", "Forced difficulty override. Send should start soon.")
else:
- statusText = _translate("MainWindow", "Unknown status: %1 %2").arg(status).arg(
- l10n.formatTimestamp(lastactiontime))
+ statusText = _translate(
+ "MainWindow", "Unknown status: {0} {1}"
+ ).format(status, l10n.formatTimestamp(lastactiontime))
newItem = myTableWidgetItem(statusText)
newItem.setToolTip(statusText)
- newItem.setData(QtCore.Qt.UserRole, QtCore.QByteArray(ackdata))
+ newItem.setData(QtCore.Qt.UserRole, ackdata)
newItem.setData(33, int(lastactiontime))
newItem.setFlags(
QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
@@ -1149,7 +1142,10 @@ class MyForm(settingsmixin.SMainWindow):
self.addMessageListItem(tableWidget, items)
return acct
- def addMessageListItemInbox(self, tableWidget, msgfolder, msgid, toAddress, fromAddress, subject, received, read):
+ def addMessageListItemInbox(
+ self, tableWidget, msgfolder, msgid, toAddress, fromAddress,
+ subject, received, read
+ ):
font = QtGui.QFont()
font.setBold(True)
if toAddress == str_broadcast_subscribers:
@@ -1161,18 +1157,18 @@ class MyForm(settingsmixin.SMainWindow):
if acct is None:
acct = BMAccount(fromAddress)
acct.parseMessage(toAddress, fromAddress, subject, "")
-
+
items = []
- #to
- MessageList_AddressWidget(items, toAddress, unicode(acct.toLabel, 'utf-8'), not read)
+ # to
+ MessageList_AddressWidget(items, toAddress, acct.toLabel, not read)
# from
- MessageList_AddressWidget(items, fromAddress, unicode(acct.fromLabel, 'utf-8'), not read)
+ MessageList_AddressWidget(items, fromAddress, acct.fromLabel, not read)
# subject
- MessageList_SubjectWidget(items, str(subject), unicode(acct.subject, 'utf-8', 'replace'), not read)
+ MessageList_SubjectWidget(items, subject, acct.subject, not read)
# time received
time_item = myTableWidgetItem(l10n.formatTimestamp(received))
time_item.setToolTip(l10n.formatTimestamp(received))
- time_item.setData(QtCore.Qt.UserRole, QtCore.QByteArray(msgid))
+ time_item.setData(QtCore.Qt.UserRole, msgid)
time_item.setData(33, int(received))
time_item.setFlags(
QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
@@ -1203,20 +1199,28 @@ class MyForm(settingsmixin.SMainWindow):
tableWidget.setUpdatesEnabled(False)
tableWidget.setSortingEnabled(False)
tableWidget.setRowCount(0)
- queryreturn = helper_search.search_sql(xAddress, account, "sent", where, what, False)
+ queryreturn = helper_search.search_sql(
+ xAddress, account, "sent", where, what, False)
for row in queryreturn:
toAddress, fromAddress, subject, status, ackdata, lastactiontime = row
- self.addMessageListItemSent(tableWidget, toAddress, fromAddress, subject, status, ackdata, lastactiontime)
+ self.addMessageListItemSent(
+ tableWidget, toAddress, fromAddress,
+ unicode(subject, 'utf-8'), status,
+ ackdata, lastactiontime
+ )
tableWidget.horizontalHeader().setSortIndicator(
3, QtCore.Qt.DescendingOrder)
tableWidget.setSortingEnabled(True)
- tableWidget.horizontalHeaderItem(3).setText(_translate("MainWindow", "Sent", None))
+ tableWidget.horizontalHeaderItem(3).setText(
+ _translate("MainWindow", "Sent"))
tableWidget.setUpdatesEnabled(True)
# Load messages from database file
- def loadMessagelist(self, tableWidget, account, folder="inbox", where="", what="", unreadOnly = False):
+ def loadMessagelist(
+ self, tableWidget, account,
+ folder="inbox", where="", what="", unreadOnly=False):
if folder == 'sent':
self.loadSent(tableWidget, account, where, what)
return
@@ -1236,39 +1240,42 @@ class MyForm(settingsmixin.SMainWindow):
tableWidget.setSortingEnabled(False)
tableWidget.setRowCount(0)
- queryreturn = helper_search.search_sql(xAddress, account, folder, where, what, unreadOnly)
-
+ queryreturn = helper_search.search_sql(
+ xAddress, account, folder, where, what, unreadOnly)
+
for row in queryreturn:
msgfolder, msgid, toAddress, fromAddress, subject, received, read = row
- self.addMessageListItemInbox(tableWidget, msgfolder, msgid, toAddress, fromAddress, subject, received, read)
+ self.addMessageListItemInbox(
+ tableWidget, msgfolder, msgid, toAddress, fromAddress,
+ unicode(subject, 'utf-8'), received, read
+ )
tableWidget.horizontalHeader().setSortIndicator(
3, QtCore.Qt.DescendingOrder)
tableWidget.setSortingEnabled(True)
tableWidget.selectRow(0)
- tableWidget.horizontalHeaderItem(3).setText(_translate("MainWindow", "Received", None))
+ tableWidget.horizontalHeaderItem(3).setText(
+ _translate("MainWindow", "Received"))
tableWidget.setUpdatesEnabled(True)
# create application indicator
def appIndicatorInit(self, app):
self.initTrayIcon("can-icon-24px-red.png", app)
- traySignal = "activated(QSystemTrayIcon::ActivationReason)"
- QtCore.QObject.connect(self.tray, QtCore.SIGNAL(
- traySignal), self.__icon_activated)
+ self.tray.activated.connect(self.__icon_activated)
- m = QtGui.QMenu()
+ m = QtWidgets.QMenu()
- self.actionStatus = QtGui.QAction(_translate(
+ self.actionStatus = QtWidgets.QAction(_translate(
"MainWindow", "Not Connected"), m, checkable=False)
m.addAction(self.actionStatus)
# separator
- actionSeparator = QtGui.QAction('', m, checkable=False)
+ actionSeparator = QtWidgets.QAction('', m, checkable=False)
actionSeparator.setSeparator(True)
m.addAction(actionSeparator)
# show bitmessage
- self.actionShow = QtGui.QAction(_translate(
+ self.actionShow = QtWidgets.QAction(_translate(
"MainWindow", "Show Bitmessage"), m, checkable=True)
self.actionShow.setChecked(not BMConfigParser().getboolean(
'bitmessagesettings', 'startintray'))
@@ -1277,7 +1284,7 @@ class MyForm(settingsmixin.SMainWindow):
m.addAction(self.actionShow)
# quiet mode
- self.actionQuiet = QtGui.QAction(_translate(
+ self.actionQuiet = QtWidgets.QAction(_translate(
"MainWindow", "Quiet Mode"), m, checkable=True)
self.actionQuiet.setChecked(not BMConfigParser().getboolean(
'bitmessagesettings', 'showtraynotifications'))
@@ -1285,25 +1292,25 @@ class MyForm(settingsmixin.SMainWindow):
m.addAction(self.actionQuiet)
# Send
- actionSend = QtGui.QAction(_translate(
+ actionSend = QtWidgets.QAction(_translate(
"MainWindow", "Send"), m, checkable=False)
actionSend.triggered.connect(self.appIndicatorSend)
m.addAction(actionSend)
# Subscribe
- actionSubscribe = QtGui.QAction(_translate(
+ actionSubscribe = QtWidgets.QAction(_translate(
"MainWindow", "Subscribe"), m, checkable=False)
actionSubscribe.triggered.connect(self.appIndicatorSubscribe)
m.addAction(actionSubscribe)
# Channels
- actionSubscribe = QtGui.QAction(_translate(
+ actionSubscribe = QtWidgets.QAction(_translate(
"MainWindow", "Channel"), m, checkable=False)
actionSubscribe.triggered.connect(self.appIndicatorChannel)
m.addAction(actionSubscribe)
# separator
- actionSeparator = QtGui.QAction('', m, checkable=False)
+ actionSeparator = QtWidgets.QAction('', m, checkable=False)
actionSeparator.setSeparator(True)
m.addAction(actionSeparator)
@@ -1421,8 +1428,6 @@ class MyForm(settingsmixin.SMainWindow):
self.tray.showMessage(title, subtitle, 1, 2000)
self._notifier = _simple_notify
- # does nothing if isAvailable returns false
- self._player = QtGui.QSound.play
if not get_plugins:
return
@@ -1435,7 +1440,10 @@ class MyForm(settingsmixin.SMainWindow):
self._theme_player = get_plugin('notification.sound', 'theme')
- if not QtGui.QSound.isAvailable():
+ try:
+ from qtpy import QtMultimedia
+ self._player = QtMultimedia.QSound.play
+ except ImportError:
_plugin = get_plugin(
'notification.sound', 'file', fallback='file.fallback')
if _plugin:
@@ -1459,7 +1467,7 @@ class MyForm(settingsmixin.SMainWindow):
if event.key() == QtCore.Qt.Key_Delete:
self.on_action_AddressBookDelete()
else:
- return QtGui.QTableWidget.keyPressEvent(
+ return QtWidgets.QTableWidget.keyPressEvent(
self.ui.tableWidgetAddressBook, event)
# inbox / sent
@@ -1475,13 +1483,13 @@ class MyForm(settingsmixin.SMainWindow):
messagelist = self.getCurrentMessagelist()
folder = self.getCurrentFolder()
if event.key() == QtCore.Qt.Key_Delete:
- if isinstance(focus, MessageView) or isinstance(focus, QtGui.QTableWidget):
+ if isinstance(focus, (MessageView, QtWidgets.QTableWidget)):
if folder == "sent":
self.on_action_SentTrash()
else:
self.on_action_InboxTrash()
event.ignore()
- elif QtGui.QApplication.queryKeyboardModifiers() == QtCore.Qt.NoModifier:
+ elif QtWidgets.QApplication.queryKeyboardModifiers() == QtCore.Qt.NoModifier:
if event.key() == QtCore.Qt.Key_N:
currentRow = messagelist.currentRow()
if currentRow < messagelist.rowCount() - 1:
@@ -1519,38 +1527,71 @@ class MyForm(settingsmixin.SMainWindow):
return
if isinstance(focus, MessageView):
return MessageView.keyPressEvent(focus, event)
- elif isinstance(focus, QtGui.QTableWidget):
- return QtGui.QTableWidget.keyPressEvent(focus, event)
- elif isinstance(focus, QtGui.QTreeWidget):
- return QtGui.QTreeWidget.keyPressEvent(focus, event)
+ elif isinstance(focus, QtWidgets.QTableWidget):
+ return QtWidgets.QTableWidget.keyPressEvent(focus, event)
+ elif isinstance(focus, QtWidgets.QTreeWidget):
+ return QtWidgets.QTreeWidget.keyPressEvent(focus, event)
# menu button 'manage keys'
def click_actionManageKeys(self):
if 'darwin' in sys.platform or 'linux' in sys.platform:
if state.appdata == '':
- # reply = QtGui.QMessageBox.information(self, 'keys.dat?','You
+ # reply = QtWidgets.QMessageBox.information(self, 'keys.dat?','You
# may manage your keys by editing the keys.dat file stored in
# the same directory as this program. It is important that you
# back up this file.', QMessageBox.Ok)
- reply = QtGui.QMessageBox.information(self, 'keys.dat?', _translate(
- "MainWindow", "You may manage your keys by editing the keys.dat file stored in the same directory as this program. It is important that you back up this file."), QtGui.QMessageBox.Ok)
+ reply = QtWidgets.QMessageBox.information(
+ self, 'keys.dat?', _translate(
+ "MainWindow",
+ "You may manage your keys by editing the keys.dat"
+ " file stored in the same directory as this"
+ " program. It is important that you back up this"
+ " file."), QtWidgets.QMessageBox.Ok)
else:
- QtGui.QMessageBox.information(self, 'keys.dat?', _translate(
- "MainWindow", "You may manage your keys by editing the keys.dat file stored in\n %1 \nIt is important that you back up this file.").arg(state.appdata), QtGui.QMessageBox.Ok)
+ QtWidgets.QMessageBox.information(
+ self, 'keys.dat?',
+ _translate(
+ "MainWindow",
+ "You may manage your keys by editing the keys.dat"
+ " file stored in\n {0} \nIt is important that you"
+ " back up this file."
+ ).format(state.appdata),
+ QtWidgets.QMessageBox.Ok
+ )
elif sys.platform == 'win32' or sys.platform == 'win64':
if state.appdata == '':
- reply = QtGui.QMessageBox.question(self, _translate("MainWindow", "Open keys.dat?"), _translate(
- "MainWindow", "You may manage your keys by editing the keys.dat file stored in the same directory as this program. It is important that you back up this file. Would you like to open the file now? (Be sure to close Bitmessage before making any changes.)"), QtGui.QMessageBox.Yes, QtGui.QMessageBox.No)
+ reply = QtWidgets.QMessageBox.question(
+ self, _translate("MainWindow", "Open keys.dat?"),
+ _translate(
+ "MainWindow",
+ "You may manage your keys by editing the keys.dat"
+ " file stored in the same directory as this"
+ " program. It is important that you back up this"
+ " file. Would you like to open the file now?"
+ " (Be sure to close Bitmessage before making any"
+ " changes.)"
+ ), QtWidgets.QMessageBox.Yes, QtWidgets.QMessageBox.No)
else:
- reply = QtGui.QMessageBox.question(self, _translate("MainWindow", "Open keys.dat?"), _translate(
- "MainWindow", "You may manage your keys by editing the keys.dat file stored in\n %1 \nIt is important that you back up this file. Would you like to open the file now? (Be sure to close Bitmessage before making any changes.)").arg(state.appdata), QtGui.QMessageBox.Yes, QtGui.QMessageBox.No)
- if reply == QtGui.QMessageBox.Yes:
+ reply = QtWidgets.QMessageBox.question(
+ self,
+ _translate("MainWindow", "Open keys.dat?"),
+ _translate(
+ "MainWindow",
+ "You may manage your keys by editing the keys.dat"
+ " file stored in\n {0} \nIt is important that you"
+ " back up this file. Would you like to open the"
+ " file now? (Be sure to close Bitmessage before"
+ " making any changes.)"
+ ).format(state.appdata),
+ QtWidgets.QMessageBox.Yes, QtWidgets.QMessageBox.No
+ )
+ if reply == QtWidgets.QMessageBox.Yes:
shared.openKeysFile()
# menu button 'delete all treshed messages'
def click_actionDeleteAllTrashedMessages(self):
- if QtGui.QMessageBox.question(self, _translate("MainWindow", "Delete trash?"), _translate("MainWindow", "Are you sure you want to delete all trashed messages?"), QtGui.QMessageBox.Yes, QtGui.QMessageBox.No) == QtGui.QMessageBox.No:
+ if QtWidgets.QMessageBox.question(self, _translate("MainWindow", "Delete trash?"), _translate("MainWindow", "Are you sure you want to delete all trashed messages?"), QtWidgets.QMessageBox.Yes, QtWidgets.QMessageBox.No) == QtWidgets.QMessageBox.No:
return
sqlStoredProcedure('deleteandvacuume')
self.rerenderTabTreeMessages()
@@ -1568,7 +1609,7 @@ class MyForm(settingsmixin.SMainWindow):
dialog = dialogs.RegenerateAddressesDialog(self)
if dialog.exec_():
if dialog.lineEditPassphrase.text() == "":
- QtGui.QMessageBox.about(
+ QtWidgets.QMessageBox.about(
self, _translate("MainWindow", "bad passphrase"),
_translate(
"MainWindow",
@@ -1581,7 +1622,7 @@ class MyForm(settingsmixin.SMainWindow):
addressVersionNumber = int(
dialog.lineEditAddressVersionNumber.text())
except:
- QtGui.QMessageBox.about(
+ QtWidgets.QMessageBox.about(
self,
_translate("MainWindow", "Bad address version number"),
_translate(
@@ -1591,7 +1632,7 @@ class MyForm(settingsmixin.SMainWindow):
))
return
if addressVersionNumber < 3 or addressVersionNumber > 4:
- QtGui.QMessageBox.about(
+ QtWidgets.QMessageBox.about(
self,
_translate("MainWindow", "Bad address version number"),
_translate(
@@ -1604,7 +1645,7 @@ class MyForm(settingsmixin.SMainWindow):
addressVersionNumber, streamNumberForAddress,
"regenerated deterministic address",
dialog.spinBoxNumberOfAddressesToMake.value(),
- dialog.lineEditPassphrase.text().toUtf8(),
+ dialog.lineEditPassphrase.text().encode('utf-8'),
dialog.checkBoxEighteenByteRipe.isChecked()
))
self.ui.tabWidget.setCurrentIndex(
@@ -1654,7 +1695,7 @@ class MyForm(settingsmixin.SMainWindow):
pass
def __icon_activated(self, reason):
- if reason == QtGui.QSystemTrayIcon.Trigger:
+ if reason == QtWidgets.QSystemTrayIcon.Trigger:
self.actionShow.setChecked(not self.actionShow.isChecked())
self.appIndicatorShowOrHideWindow()
@@ -1727,7 +1768,7 @@ class MyForm(settingsmixin.SMainWindow):
def initTrayIcon(self, iconFileName, app):
self.currentTrayIconFileName = iconFileName
- self.tray = QtGui.QSystemTrayIcon(
+ self.tray = QtWidgets.QSystemTrayIcon(
self.calcTrayIcon(iconFileName, self.findInboxUnreadCount()), app)
def setTrayIconFile(self, iconFileName):
@@ -1735,7 +1776,7 @@ class MyForm(settingsmixin.SMainWindow):
self.drawTrayIcon(iconFileName, self.findInboxUnreadCount())
def calcTrayIcon(self, iconFileName, inboxUnreadCount):
- pixmap = QtGui.QPixmap(":/newPrefix/images/"+iconFileName)
+ pixmap = QtGui.QPixmap(":/newPrefix/images/" + iconFileName)
if inboxUnreadCount > 0:
# choose font and calculate font parameters
fontName = "Lucida"
@@ -1747,7 +1788,8 @@ class MyForm(settingsmixin.SMainWindow):
rect = fontMetrics.boundingRect(txt)
# margins that we add in the top-right corner
marginX = 2
- marginY = 0 # it looks like -2 is also ok due to the error of metric
+ # it looks like -2 is also ok due to the error of metric
+ marginY = 0
# if it renders too wide we need to change it to a plus symbol
if rect.width() > 20:
txt = "+"
@@ -1756,6 +1798,7 @@ class MyForm(settingsmixin.SMainWindow):
fontMetrics = QtGui.QFontMetrics(font)
rect = fontMetrics.boundingRect(txt)
# draw text
+ # painter = QtGui.QPainter(self)
painter = QtGui.QPainter()
painter.begin(pixmap)
painter.setPen(
@@ -1787,11 +1830,18 @@ class MyForm(settingsmixin.SMainWindow):
return self.unreadCount
def updateSentItemStatusByToAddress(self, toAddress, textToDisplay):
- for sent in [self.ui.tableWidgetInbox, self.ui.tableWidgetInboxSubscriptions, self.ui.tableWidgetInboxChans]:
+ for sent in (
+ self.ui.tableWidgetInbox,
+ self.ui.tableWidgetInboxSubscriptions,
+ self.ui.tableWidgetInboxChans
+ ):
treeWidget = self.widgetConvert(sent)
if self.getCurrentFolder(treeWidget) != "sent":
continue
- if treeWidget in [self.ui.treeWidgetSubscriptions, self.ui.treeWidgetChans] and self.getCurrentAccount(treeWidget) != toAddress:
+ if treeWidget in (
+ self.ui.treeWidgetSubscriptions,
+ self.ui.treeWidgetChans
+ ) and self.getCurrentAccount(treeWidget) != toAddress:
continue
for i in range(sent.rowCount()):
@@ -1799,8 +1849,11 @@ class MyForm(settingsmixin.SMainWindow):
if toAddress == rowAddress:
sent.item(i, 3).setToolTip(textToDisplay)
try:
- newlinePosition = textToDisplay.indexOf('\n')
- except: # If someone misses adding a "_translate" to a string before passing it to this function, this function won't receive a qstring which will cause an exception.
+ newlinePosition = textToDisplay.find('\n')
+ # If someone misses adding a "_translate" to a string
+ # before passing it to this function
+ # ? why textToDisplay isn't unicode
+ except AttributeError:
newlinePosition = 0
if newlinePosition > 1:
sent.item(i, 3).setText(
@@ -1809,9 +1862,11 @@ class MyForm(settingsmixin.SMainWindow):
sent.item(i, 3).setText(textToDisplay)
def updateSentItemStatusByAckdata(self, ackdata, textToDisplay):
- if type(ackdata) is str:
- ackdata = QtCore.QByteArray(ackdata)
- for sent in [self.ui.tableWidgetInbox, self.ui.tableWidgetInboxSubscriptions, self.ui.tableWidgetInboxChans]:
+ for sent in (
+ self.ui.tableWidgetInbox,
+ self.ui.tableWidgetInboxSubscriptions,
+ self.ui.tableWidgetInboxChans
+ ):
treeWidget = self.widgetConvert(sent)
if self.getCurrentFolder(treeWidget) != "sent":
continue
@@ -1819,14 +1874,18 @@ class MyForm(settingsmixin.SMainWindow):
toAddress = sent.item(
i, 0).data(QtCore.Qt.UserRole)
tableAckdata = sent.item(
- i, 3).data(QtCore.Qt.UserRole).toPyObject()
+ i, 3).data(QtCore.Qt.UserRole)
status, addressVersionNumber, streamNumber, ripe = decodeAddress(
toAddress)
+
if ackdata == tableAckdata:
sent.item(i, 3).setToolTip(textToDisplay)
try:
- newlinePosition = textToDisplay.indexOf('\n')
- except: # If someone misses adding a "_translate" to a string before passing it to this function, this function won't receive a qstring which will cause an exception.
+ newlinePosition = textToDisplay.find('\n')
+ # If someone misses adding a "_translate" to a string
+ # before passing it to this function
+ # ? why textToDisplay isn't unicode
+ except AttributeError:
newlinePosition = 0
if newlinePosition > 1:
sent.item(i, 3).setText(
@@ -1843,8 +1902,7 @@ class MyForm(settingsmixin.SMainWindow):
):
i = None
for i in range(inbox.rowCount()):
- if msgid == \
- inbox.item(i, 3).data(QtCore.Qt.UserRole).toPyObject():
+ if msgid == inbox.item(i, 3).data(QtCore.Qt.UserRole):
break
else:
continue
@@ -1861,33 +1919,42 @@ class MyForm(settingsmixin.SMainWindow):
self.notifiedNewVersion = ".".join(str(n) for n in version)
self.updateStatusBar(_translate(
"MainWindow",
- "New version of PyBitmessage is available: %1. Download it"
+ "New version of PyBitmessage is available: {0}. Download it"
" from https://github.com/Bitmessage/PyBitmessage/releases/latest"
- ).arg(self.notifiedNewVersion)
+ ).format(self.notifiedNewVersion)
)
def displayAlert(self, title, text, exitAfterUserClicksOk):
self.updateStatusBar(text)
- QtGui.QMessageBox.critical(self, title, text, QtGui.QMessageBox.Ok)
+ QtWidgets.QMessageBox.critical(
+ self, title, text, QtWidgets.QMessageBox.Ok)
if exitAfterUserClicksOk:
os._exit(0)
def rerenderMessagelistFromLabels(self):
- for messagelist in (self.ui.tableWidgetInbox, self.ui.tableWidgetInboxChans, self.ui.tableWidgetInboxSubscriptions):
+ for messagelist in (
+ self.ui.tableWidgetInbox,
+ self.ui.tableWidgetInboxChans,
+ self.ui.tableWidgetInboxSubscriptions
+ ):
for i in range(messagelist.rowCount()):
messagelist.item(i, 1).setLabel()
def rerenderMessagelistToLabels(self):
- for messagelist in (self.ui.tableWidgetInbox, self.ui.tableWidgetInboxChans, self.ui.tableWidgetInboxSubscriptions):
+ for messagelist in (
+ self.ui.tableWidgetInbox,
+ self.ui.tableWidgetInboxChans,
+ self.ui.tableWidgetInboxSubscriptions
+ ):
for i in range(messagelist.rowCount()):
messagelist.item(i, 0).setLabel()
def rerenderAddressBook(self):
- def addRow (address, label, type):
+ def addRow(address, label, type):
self.ui.tableWidgetAddressBook.insertRow(0)
- newItem = Ui_AddressBookWidgetItemLabel(address, unicode(label, 'utf-8'), type)
+ newItem = Ui_AddressBookWidgetItemLabel(address, label, type)
self.ui.tableWidgetAddressBook.setItem(0, 0, newItem)
- newItem = Ui_AddressBookWidgetItemAddress(address, unicode(label, 'utf-8'), type)
+ newItem = Ui_AddressBookWidgetItemAddress(address, label, type)
self.ui.tableWidgetAddressBook.setItem(0, 1, newItem)
oldRows = {}
@@ -1905,29 +1972,34 @@ class MyForm(settingsmixin.SMainWindow):
queryreturn = sqlQuery('SELECT label, address FROM subscriptions WHERE enabled = 1')
for row in queryreturn:
label, address = row
- newRows[address] = [label, AccountMixin.SUBSCRIPTION]
+ newRows[address] = [unicode(label, 'utf-8'), AccountMixin.SUBSCRIPTION]
# chans
addresses = getSortedAccounts()
for address in addresses:
account = accountClass(address)
- if (account.type == AccountMixin.CHAN and BMConfigParser().safeGetBoolean(address, 'enabled')):
+ if (
+ account.type == AccountMixin.CHAN
+ and BMConfigParser().safeGetBoolean(address, 'enabled')
+ ):
newRows[address] = [account.getLabel(), AccountMixin.CHAN]
# normal accounts
queryreturn = sqlQuery('SELECT * FROM addressbook')
for row in queryreturn:
label, address = row
- newRows[address] = [label, AccountMixin.NORMAL]
+ newRows[address] = [unicode(label, 'utf-8'), AccountMixin.NORMAL]
completerList = []
- for address in sorted(oldRows, key = lambda x: oldRows[x][2], reverse = True):
+ for address in sorted(
+ oldRows, key=lambda x: oldRows[x][2], reverse=True
+ ):
if address in newRows:
- completerList.append(unicode(newRows[address][0], encoding="UTF-8") + " <" + address + ">")
- newRows.pop(address)
+ completerList.append(
+ newRows.pop(address)[0] + " <" + address + ">")
else:
self.ui.tableWidgetAddressBook.removeRow(oldRows[address][2])
for address in newRows:
addRow(address, newRows[address][0], newRows[address][1])
- completerList.append(unicode(newRows[address][0], encoding="UTF-8") + " <" + address + ">")
+ completerList.append(newRows[address][0] + " <" + address + ">")
# sort
self.ui.tableWidgetAddressBook.sortByColumn(
@@ -1939,11 +2011,11 @@ class MyForm(settingsmixin.SMainWindow):
self.rerenderTabTreeSubscriptions()
def click_pushButtonTTL(self):
- QtGui.QMessageBox.information(self, 'Time To Live', _translate(
+ QtWidgets.QMessageBox.information(self, 'Time To Live', _translate(
"MainWindow", """The TTL, or Time-To-Live is the length of time that the network will hold the message.
The recipient must get it during this time. If your Bitmessage client does not hear an acknowledgement, it
will resend the message automatically. The longer the Time-To-Live, the
- more work your computer must do to send the message. A Time-To-Live of four or five days is often appropriate."""), QtGui.QMessageBox.Ok)
+ more work your computer must do to send the message. A Time-To-Live of four or five days is often appropriate."""), QtWidgets.QMessageBox.Ok)
def click_pushButtonClear(self):
self.ui.lineEditSubject.setText("")
@@ -1952,7 +2024,7 @@ class MyForm(settingsmixin.SMainWindow):
self.ui.comboBoxSendFrom.setCurrentIndex(0)
def click_pushButtonSend(self):
- encoding = 3 if QtGui.QApplication.queryKeyboardModifiers() & QtCore.Qt.ShiftModifier else 2
+ encoding = 3 if QtWidgets.QApplication.queryKeyboardModifiers() & QtCore.Qt.ShiftModifier else 2
self.statusbar.clearMessage()
@@ -1960,22 +2032,21 @@ class MyForm(settingsmixin.SMainWindow):
self.ui.tabWidgetSend.indexOf(self.ui.sendDirect):
# message to specific people
sendMessageToPeople = True
- fromAddress = str(self.ui.comboBoxSendFrom.itemData(
+ fromAddress = self.ui.comboBoxSendFrom.itemData(
self.ui.comboBoxSendFrom.currentIndex(),
- QtCore.Qt.UserRole).toString())
- toAddresses = str(self.ui.lineEditTo.text().toUtf8())
- subject = str(self.ui.lineEditSubject.text().toUtf8())
- message = str(
- self.ui.textEditMessage.document().toPlainText().toUtf8())
+ QtCore.Qt.UserRole)
+ toAddresses = self.ui.lineEditTo.text()
+ subject = self.ui.lineEditSubject.text()
+ message = self.ui.textEditMessage.document().toPlainText()
else:
# broadcast message
sendMessageToPeople = False
- fromAddress = str(self.ui.comboBoxSendFromBroadcast.itemData(
+ fromAddress = self.ui.comboBoxSendFromBroadcast.itemData(
self.ui.comboBoxSendFromBroadcast.currentIndex(),
- QtCore.Qt.UserRole).toString())
- subject = str(self.ui.lineEditSubjectBroadcast.text().toUtf8())
- message = str(
- self.ui.textEditMessageBroadcast.document().toPlainText().toUtf8())
+ QtCore.Qt.UserRole)
+ subject = self.ui.lineEditSubjectBroadcast.text()
+ message = \
+ self.ui.textEditMessageBroadcast.document().toPlainText()
"""
The whole network message must fit in 2^18 bytes.
Let's assume 500 bytes of overhead. If someone wants to get that
@@ -1984,23 +2055,27 @@ class MyForm(settingsmixin.SMainWindow):
users can send messages of any length.
"""
if len(message) > (2 ** 18 - 500):
- QtGui.QMessageBox.about(
+ QtWidgets.QMessageBox.about(
self, _translate("MainWindow", "Message too long"),
_translate(
"MainWindow",
"The message that you are trying to send is too long"
- " by %1 bytes. (The maximum is 261644 bytes). Please"
+ " by {0} bytes. (The maximum is 261644 bytes). Please"
" cut it down before sending."
- ).arg(len(message) - (2 ** 18 - 500)))
+ ).format(len(message) - (2 ** 18 - 500)))
return
acct = accountClass(fromAddress)
- if sendMessageToPeople: # To send a message to specific people (rather than broadcast)
- toAddressesList = [s.strip()
- for s in toAddresses.replace(',', ';').split(';')]
- toAddressesList = list(set(
- toAddressesList)) # remove duplicate addresses. If the user has one address with a BM- and the same address without the BM-, this will not catch it. They'll send the message to the person twice.
+ # To send a message to specific people (rather than broadcast)
+ if sendMessageToPeople:
+ toAddressesList = [
+ s.strip() for s in toAddresses.replace(',', ';').split(';')
+ ]
+ # remove duplicate addresses. If the user has one address
+ # with a BM- and the same address without the BM-, this will
+ # not catch it. They'll send the message to the person twice.
+ toAddressesList = list(set(toAddressesList))
for toAddress in toAddressesList:
if toAddress != '':
# label plus address
@@ -2009,18 +2084,32 @@ class MyForm(settingsmixin.SMainWindow):
# email address
if toAddress.find("@") >= 0:
if isinstance(acct, GatewayAccount):
- acct.createMessage(toAddress, fromAddress, subject, message)
+ acct.createMessage(
+ toAddress, fromAddress, subject, message)
subject = acct.subject
toAddress = acct.toAddress
else:
- if QtGui.QMessageBox.question(self, "Sending an email?", _translate("MainWindow",
- "You are trying to send an email instead of a bitmessage. This requires registering with a gateway. Attempt to register?"),
- QtGui.QMessageBox.Yes|QtGui.QMessageBox.No) != QtGui.QMessageBox.Yes:
+ if QtWidgets.QMessageBox.question(
+ self, "Sending an email?",
+ _translate(
+ "MainWindow",
+ "You are trying to send an email"
+ " instead of a bitmessage. This"
+ " requires registering with a"
+ " gateway. Attempt to register?"
+ ), QtWidgets.QMessageBox.Yes
+ | QtWidgets.QMessageBox.No
+ ) != QtWidgets.QMessageBox.Yes:
continue
email = acct.getLabel()
- if email[-14:] != "@mailchuck.com": #attempt register
+ # attempt register
+ if email[-14:] != "@mailchuck.com":
# 12 character random email address
- email = ''.join(random.SystemRandom().choice(string.ascii_lowercase) for _ in range(12)) + "@mailchuck.com"
+ email = ''.join(
+ random.SystemRandom().choice(
+ string.ascii_lowercase
+ ) for _ in range(12)
+ ) + "@mailchuck.com"
acct = MailchuckAccount(fromAddress)
acct.register(email)
BMConfigParser().set(fromAddress, 'label', email)
@@ -2030,76 +2119,80 @@ class MyForm(settingsmixin.SMainWindow):
"MainWindow",
"Error: Your account wasn't registered at"
" an email gateway. Sending registration"
- " now as %1, please wait for the registration"
+ " now as {0}, please wait for the registration"
" to be processed before retrying sending."
- ).arg(email)
+ ).format(email)
)
return
- status, addressVersionNumber, streamNumber, ripe = decodeAddress(
- toAddress)
+ status, addressVersionNumber, streamNumber, ripe = \
+ decodeAddress(toAddress)
if status != 'success':
try:
toAddress = unicode(toAddress, 'utf-8', 'ignore')
except:
- pass
- logger.error('Error: Could not decode recipient address ' + toAddress + ':' + status)
+ logger.warning(
+ "Failed unicode(toAddress ):",
+ exc_info=True)
+ logger.error(
+ 'Error: Could not decode recipient address %s: %s',
+ toAddress, status)
if status == 'missingbm':
self.updateStatusBar(_translate(
"MainWindow",
"Error: Bitmessage addresses start with"
- " BM- Please check the recipient address %1"
- ).arg(toAddress))
+ " BM- Please check the recipient address {0}"
+ ).format(toAddress))
elif status == 'checksumfailed':
self.updateStatusBar(_translate(
"MainWindow",
- "Error: The recipient address %1 is not"
+ "Error: The recipient address {0} is not"
" typed or copied correctly. Please check it."
- ).arg(toAddress))
+ ).format(toAddress))
elif status == 'invalidcharacters':
self.updateStatusBar(_translate(
"MainWindow",
- "Error: The recipient address %1 contains"
+ "Error: The recipient address {0} contains"
" invalid characters. Please check it."
- ).arg(toAddress))
+ ).format(toAddress))
elif status == 'versiontoohigh':
self.updateStatusBar(_translate(
"MainWindow",
"Error: The version of the recipient address"
- " %1 is too high. Either you need to upgrade"
+ " {0} is too high. Either you need to upgrade"
" your Bitmessage software or your"
" acquaintance is being clever."
- ).arg(toAddress))
+ ).format(toAddress))
elif status == 'ripetooshort':
self.updateStatusBar(_translate(
"MainWindow",
"Error: Some data encoded in the recipient"
- " address %1 is too short. There might be"
+ " address {0} is too short. There might be"
" something wrong with the software of"
" your acquaintance."
- ).arg(toAddress))
+ ).format(toAddress))
elif status == 'ripetoolong':
self.updateStatusBar(_translate(
"MainWindow",
"Error: Some data encoded in the recipient"
- " address %1 is too long. There might be"
+ " address {0} is too long. There might be"
" something wrong with the software of"
" your acquaintance."
- ).arg(toAddress))
+ ).format(toAddress))
elif status == 'varintmalformed':
self.updateStatusBar(_translate(
"MainWindow",
"Error: Some data encoded in the recipient"
- " address %1 is malformed. There might be"
+ " address {0} is malformed. There might be"
" something wrong with the software of"
" your acquaintance."
- ).arg(toAddress))
+ ).format(toAddress))
else:
self.updateStatusBar(_translate(
"MainWindow",
"Error: Something is wrong with the"
- " recipient address %1."
- ).arg(toAddress))
+ " recipient address {0}."
+ ).format(toAddress))
elif fromAddress == '':
self.updateStatusBar(_translate(
"MainWindow",
@@ -2111,12 +2204,31 @@ class MyForm(settingsmixin.SMainWindow):
toAddress = addBMIfNotPresent(toAddress)
if addressVersionNumber > 4 or addressVersionNumber <= 1:
- QtGui.QMessageBox.about(self, _translate("MainWindow", "Address version number"), _translate(
- "MainWindow", "Concerning the address %1, Bitmessage cannot understand address version numbers of %2. Perhaps upgrade Bitmessage to the latest version.").arg(toAddress).arg(str(addressVersionNumber)))
+ QtWidgets.QMessageBox.about(
+ self,
+ _translate(
+ "MainWindow", "Address version number"),
+ _translate(
+ "MainWindow",
+ "Concerning the address {0}, Bitmessage"
+ " cannot understand address version"
+ " numbers of {1}. Perhaps upgrade"
+ " Bitmessage to the latest version."
+ ).format(toAddress, addressVersionNumber)
+ )
continue
if streamNumber > 1 or streamNumber == 0:
- QtGui.QMessageBox.about(self, _translate("MainWindow", "Stream number"), _translate(
- "MainWindow", "Concerning the address %1, Bitmessage cannot handle stream numbers of %2. Perhaps upgrade Bitmessage to the latest version.").arg(toAddress).arg(str(streamNumber)))
+ QtWidgets.QMessageBox.about(
+ self,
+ _translate("MainWindow", "Stream number"),
+ _translate(
+ "MainWindow",
+ "Concerning the address {0}, Bitmessage"
+ " cannot handle stream numbers of {1}."
+ " Perhaps upgrade Bitmessage to the"
+ " latest version."
+ ).format(toAddress, streamNumber)
+ )
continue
self.statusbar.clearMessage()
if shared.statusIconColor == 'red':
@@ -2236,11 +2348,11 @@ class MyForm(settingsmixin.SMainWindow):
))
def click_pushButtonFetchNamecoinID(self):
- identities = str(self.ui.lineEditTo.text().toUtf8()).split(";")
+ identities = self.ui.lineEditTo.text().split(";")
err, addr = self.namecoin.query(identities[-1].strip())
if err is not None:
self.updateStatusBar(
- _translate("MainWindow", "Error: %1").arg(err))
+ _translate("MainWindow", "Error: {0}").format(err))
else:
identities[-1] = addr
self.ui.lineEditTo.setText("; ".join(identities))
@@ -2270,8 +2382,8 @@ class MyForm(settingsmixin.SMainWindow):
self.ui.comboBoxSendFrom.addItem(avatarize(addressInKeysFile), label, addressInKeysFile)
# self.ui.comboBoxSendFrom.model().sort(1, Qt.AscendingOrder)
for i in range(self.ui.comboBoxSendFrom.count()):
- address = str(self.ui.comboBoxSendFrom.itemData(
- i, QtCore.Qt.UserRole).toString())
+ address = self.ui.comboBoxSendFrom.itemData(
+ i, QtCore.Qt.UserRole)
self.ui.comboBoxSendFrom.setItemData(
i, AccountColor(address).accountColor(),
QtCore.Qt.ForegroundRole)
@@ -2293,13 +2405,13 @@ class MyForm(settingsmixin.SMainWindow):
label = addressInKeysFile
self.ui.comboBoxSendFromBroadcast.addItem(avatarize(addressInKeysFile), label, addressInKeysFile)
for i in range(self.ui.comboBoxSendFromBroadcast.count()):
- address = str(self.ui.comboBoxSendFromBroadcast.itemData(
- i, QtCore.Qt.UserRole).toString())
+ address = self.ui.comboBoxSendFromBroadcast.itemData(
+ i, QtCore.Qt.UserRole)
self.ui.comboBoxSendFromBroadcast.setItemData(
i, AccountColor(address).accountColor(),
QtCore.Qt.ForegroundRole)
self.ui.comboBoxSendFromBroadcast.insertItem(0, '', '')
- if(self.ui.comboBoxSendFromBroadcast.count() == 2):
+ if self.ui.comboBoxSendFromBroadcast.count() == 2:
self.ui.comboBoxSendFromBroadcast.setCurrentIndex(1)
else:
self.ui.comboBoxSendFromBroadcast.setCurrentIndex(0)
@@ -2325,12 +2437,13 @@ class MyForm(settingsmixin.SMainWindow):
continue
elif not helper_search.check_match(toAddress, fromAddress, subject, message, self.getCurrentSearchOption(tab), self.getCurrentSearchLine(tab)):
continue
-
+
self.addMessageListItemSent(sent, toAddress, fromAddress, subject, "msgqueued", ackdata, time.time())
- self.getAccountTextedit(acct).setPlainText(unicode(message, 'utf-8', 'replace'))
+ self.getAccountTextedit(acct).setPlainText(message)
sent.setCurrentCell(0, 0)
- def displayNewInboxMessage(self, inventoryHash, toAddress, fromAddress, subject, message):
+ def displayNewInboxMessage(
+ self, inventoryHash, toAddress, fromAddress, subject, message):
if toAddress == str_broadcast_subscribers:
acct = accountClass(fromAddress)
else:
@@ -2338,17 +2451,39 @@ class MyForm(settingsmixin.SMainWindow):
inbox = self.getAccountMessagelist(acct)
ret = None
tab = -1
- for treeWidget in [self.ui.treeWidgetYourIdentities, self.ui.treeWidgetSubscriptions, self.ui.treeWidgetChans]:
+ for treeWidget in [
+ self.ui.treeWidgetYourIdentities,
+ self.ui.treeWidgetSubscriptions,
+ self.ui.treeWidgetChans
+ ]:
tab += 1
if tab == 1:
tab = 2
tableWidget = self.widgetConvert(treeWidget)
- if not helper_search.check_match(toAddress, fromAddress, subject, message, self.getCurrentSearchOption(tab), self.getCurrentSearchLine(tab)):
+ if not helper_search.check_match(
+ toAddress, fromAddress, subject, message,
+ self.getCurrentSearchOption(tab),
+ self.getCurrentSearchLine(tab)
+ ):
continue
- if tableWidget == inbox and self.getCurrentAccount(treeWidget) == acct.address and self.getCurrentFolder(treeWidget) in ["inbox", None]:
- ret = self.addMessageListItemInbox(inbox, "inbox", inventoryHash, toAddress, fromAddress, subject, time.time(), 0)
- elif treeWidget == self.ui.treeWidgetYourIdentities and self.getCurrentAccount(treeWidget) is None and self.getCurrentFolder(treeWidget) in ["inbox", "new", None]:
- ret = self.addMessageListItemInbox(tableWidget, "inbox", inventoryHash, toAddress, fromAddress, subject, time.time(), 0)
+ # inventoryHash surprisingly is of type unicode
+ inventoryHash = inventoryHash.encode('utf-8')
+ if tableWidget == inbox \
+ and self.getCurrentAccount(treeWidget) == acct.address \
+ and self.getCurrentFolder(treeWidget) \
+ in ["inbox", None]:
+ ret = self.addMessageListItemInbox(
+ inbox, "inbox", inventoryHash, toAddress, fromAddress,
+ subject, time.time(), 0
+ )
+ elif treeWidget == self.ui.treeWidgetYourIdentities \
+ and self.getCurrentAccount(treeWidget) is None \
+ and self.getCurrentFolder(treeWidget) \
+ in ["inbox", "new", None]:
+ ret = self.addMessageListItemInbox(
+ tableWidget, "inbox", inventoryHash, toAddress,
+ fromAddress, subject, time.time(), 0
+ )
if ret is None:
acct.parseMessage(toAddress, fromAddress, subject, "")
else:
@@ -2359,11 +2494,13 @@ class MyForm(settingsmixin.SMainWindow):
'bitmessagesettings', 'showtraynotifications'):
self.notifierShow(
_translate("MainWindow", "New Message"),
- _translate("MainWindow", "From %1").arg(
- unicode(acct.fromLabel, 'utf-8')),
+ _translate("MainWindow", "From {0}").format(acct.fromLabel),
sound.SOUND_UNKNOWN
)
- if self.getCurrentAccount() is not None and ((self.getCurrentFolder(treeWidget) != "inbox" and self.getCurrentFolder(treeWidget) is not None) or self.getCurrentAccount(treeWidget) != acct.address):
+ if self.getCurrentAccount() is not None and (
+ (self.getCurrentFolder(treeWidget) != "inbox"
+ and self.getCurrentFolder(treeWidget) is not None)
+ or self.getCurrentAccount(treeWidget) != acct.address):
# Ubuntu should notify of new message irespective of
# whether it's in current message list or not
self.indicatorUpdate(True, to_label=acct.toLabel)
@@ -2492,7 +2629,7 @@ class MyForm(settingsmixin.SMainWindow):
# Only settings remain here
acct.settings()
for i in range(self.ui.comboBoxSendFrom.count()):
- if str(self.ui.comboBoxSendFrom.itemData(i).toPyObject()) \
+ if str(self.ui.comboBoxSendFrom.itemData(i)) \
== acct.fromAddress:
self.ui.comboBoxSendFrom.setCurrentIndex(i)
break
@@ -2511,13 +2648,13 @@ class MyForm(settingsmixin.SMainWindow):
self.ui.textEditMessage.setFocus()
def on_action_MarkAllRead(self):
- if QtGui.QMessageBox.question(
+ if QtWidgets.QMessageBox.question(
self, "Marking all messages as read?",
_translate(
"MainWindow",
"Are you sure you would like to mark all messages read?"
- ), QtGui.QMessageBox.Yes | QtGui.QMessageBox.No
- ) != QtGui.QMessageBox.Yes:
+ ), QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.No
+ ) != QtWidgets.QMessageBox.Yes:
return
tableWidget = self.getCurrentMessagelist()
@@ -2531,7 +2668,7 @@ class MyForm(settingsmixin.SMainWindow):
msgids = []
for i in range(0, idCount):
msgids.append(str(tableWidget.item(
- i, 3).data(QtCore.Qt.UserRole).toPyObject()))
+ i, 3).data(QtCore.Qt.UserRole)))
tableWidget.item(i, 0).setUnread(False)
tableWidget.item(i, 1).setUnread(False)
tableWidget.item(i, 2).setUnread(False)
@@ -2551,7 +2688,7 @@ class MyForm(settingsmixin.SMainWindow):
def network_switch(self):
dontconnect_option = not BMConfigParser().safeGetBoolean(
'bitmessagesettings', 'dontconnect')
- reply = QtGui.QMessageBox.question(
+ reply = QtWidgets.QMessageBox.question(
self, _translate("MainWindow", "Disconnecting")
if dontconnect_option else _translate("MainWindow", "Connecting"),
_translate(
@@ -2560,9 +2697,9 @@ class MyForm(settingsmixin.SMainWindow):
) if dontconnect_option else _translate(
"MainWindow",
"Bitmessage will now start connecting to network. Are you sure?"
- ), QtGui.QMessageBox.Yes | QtGui.QMessageBox.Cancel,
- QtGui.QMessageBox.Cancel)
- if reply != QtGui.QMessageBox.Yes:
+ ), QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.Cancel,
+ QtWidgets.QMessageBox.Cancel)
+ if reply != QtWidgets.QMessageBox.Yes:
return
BMConfigParser().set(
'bitmessagesettings', 'dontconnect', str(dontconnect_option))
@@ -2588,74 +2725,68 @@ class MyForm(settingsmixin.SMainWindow):
waitForSync = False
# C PoW currently doesn't support interrupting and OpenCL is untested
- if getPowType() == "python" and (powQueueSize() > 0 or pendingUpload() > 0):
- reply = QtGui.QMessageBox.question(
+ if getPowType() == "python" and (
+ powQueueSize() > 0 or pendingUpload() > 0):
+ reply = QtWidgets.QMessageBox.question(
self, _translate("MainWindow", "Proof of work pending"),
_translate(
"MainWindow",
- "%n object(s) pending proof of work", None,
- QtCore.QCoreApplication.CodecForTr, powQueueSize()
+ "%n object(s) pending proof of work", None, powQueueSize()
) + ", " +
_translate(
"MainWindow",
- "%n object(s) waiting to be distributed", None,
- QtCore.QCoreApplication.CodecForTr, pendingUpload()
+ "%n object(s) waiting to be distributed",
+ None, pendingUpload()
) + "\n\n" +
- _translate(
- "MainWindow", "Wait until these tasks finish?"),
- QtGui.QMessageBox.Yes | QtGui.QMessageBox.No |
- QtGui.QMessageBox.Cancel,
- QtGui.QMessageBox.Cancel
+ _translate("MainWindow", "Wait until these tasks finish?"),
+ QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.No |
+ QtWidgets.QMessageBox.Cancel,
+ QtWidgets.QMessageBox.Cancel
)
- if reply == QtGui.QMessageBox.No:
+ if reply == QtWidgets.QMessageBox.No:
waitForPow = False
- elif reply == QtGui.QMessageBox.Cancel:
+ elif reply == QtWidgets.QMessageBox.Cancel:
return
if pendingDownload() > 0:
- reply = QtGui.QMessageBox.question(
+ reply = QtWidgets.QMessageBox.question(
self, _translate("MainWindow", "Synchronisation pending"),
_translate(
"MainWindow",
"Bitmessage hasn't synchronised with the network,"
" %n object(s) to be downloaded. If you quit now,"
" it may cause delivery delays. Wait until the"
- " synchronisation finishes?", None,
- QtCore.QCoreApplication.CodecForTr, pendingDownload()
- ),
- QtGui.QMessageBox.Yes | QtGui.QMessageBox.No |
- QtGui.QMessageBox.Cancel,
- QtGui.QMessageBox.Cancel
- )
- if reply == QtGui.QMessageBox.Yes:
+ " synchronisation finishes?",
+ None, pendingDownload()
+ ), QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.No |
+ QtWidgets.QMessageBox.Cancel, QtWidgets.QMessageBox.Cancel)
+ if reply == QtWidgets.QMessageBox.Yes:
self.wait = waitForSync = True
- elif reply == QtGui.QMessageBox.Cancel:
+ elif reply == QtWidgets.QMessageBox.Cancel:
return
- if shared.statusIconColor == 'red' and not BMConfigParser().safeGetBoolean(
+ if shared.statusIconColor == 'red' \
+ and not BMConfigParser().safeGetBoolean(
'bitmessagesettings', 'dontconnect'):
- reply = QtGui.QMessageBox.question(
+ reply = QtWidgets.QMessageBox.question(
self, _translate("MainWindow", "Not connected"),
_translate(
"MainWindow",
- "Bitmessage isn't connected to the network. If you"
+ "Bitmessage isn't connected to the network. If you"
" quit now, it may cause delivery delays. Wait until"
" connected and the synchronisation finishes?"
- ),
- QtGui.QMessageBox.Yes | QtGui.QMessageBox.No |
- QtGui.QMessageBox.Cancel,
- QtGui.QMessageBox.Cancel
- )
- if reply == QtGui.QMessageBox.Yes:
+ ), QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.No |
+ QtWidgets.QMessageBox.Cancel, QtWidgets.QMessageBox.Cancel)
+ if reply == QtWidgets.QMessageBox.Yes:
waitForConnection = True
self.wait = waitForSync = True
- elif reply == QtGui.QMessageBox.Cancel:
+ elif reply == QtWidgets.QMessageBox.Cancel:
return
self.quitAccepted = True
self.updateStatusBar(_translate(
- "MainWindow", "Shutting down PyBitmessage... %1%").arg(0))
+ "MainWindow", "Shutting down PyBitmessage... {0}%").format(0))
if waitForConnection:
self.updateStatusBar(_translate(
@@ -2689,16 +2820,18 @@ class MyForm(settingsmixin.SMainWindow):
maxWorkerQueue = curWorkerQueue
if curWorkerQueue > 0:
self.updateStatusBar(_translate(
- "MainWindow", "Waiting for PoW to finish... %1%"
- ).arg(50 * (maxWorkerQueue - curWorkerQueue) /
- maxWorkerQueue))
+ "MainWindow", "Waiting for PoW to finish... {0}%"
+ ).format(
+ 50 * (maxWorkerQueue - curWorkerQueue) / maxWorkerQueue
+ ))
time.sleep(0.5)
QtCore.QCoreApplication.processEvents(
QtCore.QEventLoop.AllEvents, 1000
)
self.updateStatusBar(_translate(
- "MainWindow", "Shutting down Pybitmessage... %1%").arg(50))
+ "MainWindow", "Shutting down Pybitmessage... {0}%"
+ ).format(50))
QtCore.QCoreApplication.processEvents(
QtCore.QEventLoop.AllEvents, 1000
@@ -2712,29 +2845,27 @@ class MyForm(settingsmixin.SMainWindow):
# check if upload (of objects created locally) pending
self.updateStatusBar(_translate(
- "MainWindow", "Waiting for objects to be sent... %1%").arg(50))
+ "MainWindow", "Waiting for objects to be sent... {0}%"
+ ).format(50))
maxPendingUpload = max(1, pendingUpload())
while pendingUpload() > 1:
self.updateStatusBar(_translate(
"MainWindow",
- "Waiting for objects to be sent... %1%"
- ).arg(int(50 + 20 * (pendingUpload() / maxPendingUpload))))
+ "Waiting for objects to be sent... {0}%"
+ ).format(int(50 + 20 * pendingUpload() / maxPendingUpload)))
time.sleep(0.5)
QtCore.QCoreApplication.processEvents(
QtCore.QEventLoop.AllEvents, 1000
)
- QtCore.QCoreApplication.processEvents(
- QtCore.QEventLoop.AllEvents, 1000
- )
QtCore.QCoreApplication.processEvents(
QtCore.QEventLoop.AllEvents, 1000
)
# save state and geometry self and all widgets
self.updateStatusBar(_translate(
- "MainWindow", "Saving settings... %1%").arg(70))
+ "MainWindow", "Saving settings... {0}%").format(70))
QtCore.QCoreApplication.processEvents(
QtCore.QEventLoop.AllEvents, 1000
)
@@ -2747,17 +2878,17 @@ class MyForm(settingsmixin.SMainWindow):
obj.saveSettings()
self.updateStatusBar(_translate(
- "MainWindow", "Shutting down core... %1%").arg(80))
+ "MainWindow", "Shutting down core... {0}%").format(80))
QtCore.QCoreApplication.processEvents(
QtCore.QEventLoop.AllEvents, 1000
)
shutdown.doCleanShutdown()
self.updateStatusBar(_translate(
- "MainWindow", "Stopping notifications... %1%").arg(90))
+ "MainWindow", "Stopping notifications... {0}%").format(90))
self.tray.hide()
self.updateStatusBar(_translate(
- "MainWindow", "Shutdown imminent... %1%").arg(100))
+ "MainWindow", "Shutdown imminent... {0}%").format(100))
logger.info("Shutdown complete")
super(MyForm, myapp).close()
@@ -2791,17 +2922,25 @@ class MyForm(settingsmixin.SMainWindow):
totalLines = len(lines)
for i in xrange(totalLines):
if 'Message ostensibly from ' in lines[i]:
- lines[i] = '
%s
' % (
- lines[i])
- elif lines[i] == '------------------------------------------------------':
+ lines[i] = (
+ '%s
' %
+ lines[i]
+ )
+ elif (
+ lines[i] ==
+ '------------------------------------------------------'
+ ):
lines[i] = '
'
- elif lines[i] == '' and (i+1) < totalLines and \
- lines[i+1] != '------------------------------------------------------':
+ elif (
+ lines[i] == '' and (i + 1) < totalLines and
+ lines[i + 1] !=
+ '------------------------------------------------------'
+ ):
lines[i] = '
'
- content = ' '.join(lines) # To keep the whitespace between lines
+ content = ' '.join(lines) # To keep the whitespace between lines
content = shared.fixPotentiallyInvalidUTF8Data(content)
- content = unicode(content, 'utf-8)')
- textEdit.setHtml(QtCore.QString(content))
+ content = unicode(content, 'utf-8')
+ textEdit.setHtml(content)
def on_action_InboxMarkUnread(self):
tableWidget = self.getCurrentMessagelist()
@@ -2813,7 +2952,7 @@ class MyForm(settingsmixin.SMainWindow):
for row in tableWidget.selectedIndexes():
currentRow = row.row()
msgid = str(tableWidget.item(
- currentRow, 3).data(QtCore.Qt.UserRole).toPyObject())
+ currentRow, 3).data(QtCore.Qt.UserRole))
msgids.add(msgid)
# if not tableWidget.item(currentRow, 0).unread:
# modified += 1
@@ -2828,24 +2967,22 @@ class MyForm(settingsmixin.SMainWindow):
)
self.propagateUnreadCount()
- # tableWidget.selectRow(currentRow + 1)
- # This doesn't de-select the last message if you try to mark it
- # unread, but that doesn't interfere. Might not be necessary.
- # We could also select upwards, but then our problem would be
- # with the topmost message.
- # tableWidget.clearSelection() manages to mark the message
- # as read again.
# Format predefined text on message reply.
def quoted_text(self, message):
- if not BMConfigParser().safeGetBoolean('bitmessagesettings', 'replybelow'):
- return '\n\n------------------------------------------------------\n' + message
+ if not BMConfigParser().safeGetBoolean(
+ 'bitmessagesettings', 'replybelow'):
+ return (
+ '\n\n------------------------------------------------------\n' +
+ message
+ )
+
+ quoteWrapper = textwrap.TextWrapper(
+ replace_whitespace=False, initial_indent='> ',
+ subsequent_indent='> ', break_long_words=False,
+ break_on_hyphens=False
+ )
- quoteWrapper = textwrap.TextWrapper(replace_whitespace = False,
- initial_indent = '> ',
- subsequent_indent = '> ',
- break_long_words = False,
- break_on_hyphens = False)
def quote_line(line):
# Do quote empty lines.
if line == '' or line.isspace():
@@ -2858,7 +2995,7 @@ class MyForm(settingsmixin.SMainWindow):
return quoteWrapper.fill(line)
return '\n'.join([quote_line(l) for l in message.splitlines()]) + '\n\n'
- def setSendFromComboBox(self, address = None):
+ def setSendFromComboBox(self, address=None):
if address is None:
messagelist = self.getCurrentMessagelist()
if messagelist:
@@ -2866,7 +3003,7 @@ class MyForm(settingsmixin.SMainWindow):
address = messagelist.item(
currentInboxRow, 0).address
for box in [self.ui.comboBoxSendFrom, self.ui.comboBoxSendFromBroadcast]:
- listOfAddressesInComboBoxSendFrom = [str(box.itemData(i).toPyObject()) for i in range(box.count())]
+ listOfAddressesInComboBoxSendFrom = [str(box.itemData(i)) for i in range(box.count())]
if address in listOfAddressesInComboBoxSendFrom:
currentIndex = listOfAddressesInComboBoxSendFrom.index(address)
box.setCurrentIndex(currentIndex)
@@ -2902,7 +3039,7 @@ class MyForm(settingsmixin.SMainWindow):
fromAddressAtCurrentInboxRow = tableWidget.item(
currentInboxRow, column_from).address
msgid = str(tableWidget.item(
- currentInboxRow, 3).data(QtCore.Qt.UserRole).toPyObject())
+ currentInboxRow, 3).data(QtCore.Qt.UserRole))
queryreturn = sqlQuery(
"SELECT message FROM inbox WHERE msgid=?", msgid
) or sqlQuery("SELECT message FROM sent WHERE ackdata=?", msgid)
@@ -2912,7 +3049,8 @@ class MyForm(settingsmixin.SMainWindow):
acct.parseMessage(
toAddressAtCurrentInboxRow, fromAddressAtCurrentInboxRow,
tableWidget.item(currentInboxRow, 2).subject,
- messageAtCurrentInboxRow)
+ messageAtCurrentInboxRow
+ )
widget = {
'subject': self.ui.lineEditSubject,
'from': self.ui.comboBoxSendFrom,
@@ -2925,23 +3063,26 @@ class MyForm(settingsmixin.SMainWindow):
)
# toAddressAtCurrentInboxRow = fromAddressAtCurrentInboxRow
elif not BMConfigParser().has_section(toAddressAtCurrentInboxRow):
- QtGui.QMessageBox.information(
- self, _translate("MainWindow", "Address is gone"),
+ QtWidgets.QMessageBox.information(
+ self,
+ _translate("MainWindow", "Address is gone"),
_translate(
"MainWindow",
- "Bitmessage cannot find your address %1. Perhaps you"
+ "Bitmessage cannot find your address {0}. Perhaps you"
" removed it?"
- ).arg(toAddressAtCurrentInboxRow), QtGui.QMessageBox.Ok)
+ ).format(toAddressAtCurrentInboxRow),
+ QtWidgets.QMessageBox.Ok)
elif not BMConfigParser().getboolean(
toAddressAtCurrentInboxRow, 'enabled'):
- QtGui.QMessageBox.information(
- self, _translate("MainWindow", "Address disabled"),
+ QtWidgets.QMessageBox.information(
+ self,
+ _translate("MainWindow", "Address disabled"),
_translate(
"MainWindow",
"Error: The address from which you are trying to send"
- " is disabled. You\'ll have to enable it on the"
- " \'Your Identities\' tab before using it."
- ), QtGui.QMessageBox.Ok)
+ " is disabled. You\'ll have to enable it on the \'Your"
+ " Identities\' tab before using it."
+ ), QtWidgets.QMessageBox.Ok)
else:
self.setBroadcastEnablementDependingOnWhetherThisIsAMailingListAddress(toAddressAtCurrentInboxRow)
broadcast_tab_index = self.ui.tabWidgetSend.indexOf(
@@ -3001,7 +3142,7 @@ class MyForm(settingsmixin.SMainWindow):
if not tableWidget:
return
currentInboxRow = tableWidget.currentRow()
- # tableWidget.item(currentRow,1).data(Qt.UserRole).toPyObject()
+ # tableWidget.item(currentRow,1).data(Qt.UserRole)
addressAtCurrentInboxRow = tableWidget.item(
currentInboxRow, 1).data(QtCore.Qt.UserRole)
self.ui.tabWidget.setCurrentIndex(
@@ -3015,7 +3156,7 @@ class MyForm(settingsmixin.SMainWindow):
if not tableWidget:
return
currentInboxRow = tableWidget.currentRow()
- # tableWidget.item(currentRow,1).data(Qt.UserRole).toPyObject()
+ # tableWidget.item(currentRow,1).data(Qt.UserRole)
addressAtCurrentInboxRow = tableWidget.item(
currentInboxRow, 1).data(QtCore.Qt.UserRole)
recipientAddress = tableWidget.item(
@@ -3039,23 +3180,28 @@ class MyForm(settingsmixin.SMainWindow):
"Error: You cannot add the same address to your blacklist"
" twice. Try renaming the existing one if you want."))
- def deleteRowFromMessagelist(self, row = None, inventoryHash = None, ackData = None, messageLists = None):
+ def deleteRowFromMessagelist(
+ self, row=None, inventoryHash=None, ackData=None, messageLists=None
+ ):
if messageLists is None:
- messageLists = (self.ui.tableWidgetInbox, self.ui.tableWidgetInboxChans, self.ui.tableWidgetInboxSubscriptions)
+ messageLists = (
+ self.ui.tableWidgetInbox, self.ui.tableWidgetInboxChans,
+ self.ui.tableWidgetInboxSubscriptions
+ )
elif type(messageLists) not in (list, tuple):
messageLists = (messageLists)
for messageList in messageLists:
if row is not None:
- inventoryHash = str(messageList.item(row, 3).data(
- QtCore.Qt.UserRole).toPyObject())
+ inventoryHash = messageList.item(row, 3).data(
+ QtCore.Qt.UserRole)
messageList.removeRow(row)
elif inventoryHash is not None:
for i in range(messageList.rowCount() - 1, -1, -1):
- if messageList.item(i, 3).data(QtCore.Qt.UserRole).toPyObject() == inventoryHash:
+ if messageList.item(i, 3).data(QtCore.Qt.UserRole) == inventoryHash:
messageList.removeRow(i)
elif ackData is not None:
for i in range(messageList.rowCount() - 1, -1, -1):
- if messageList.item(i, 3).data(QtCore.Qt.UserRole).toPyObject() == ackData:
+ if messageList.item(i, 3).data(QtCore.Qt.UserRole) == ackData:
messageList.removeRow(i)
# Send item on the Inbox tab to trash
@@ -3065,20 +3211,24 @@ class MyForm(settingsmixin.SMainWindow):
return
currentRow = 0
folder = self.getCurrentFolder()
- shifted = QtGui.QApplication.queryKeyboardModifiers() & QtCore.Qt.ShiftModifier
- tableWidget.setUpdatesEnabled(False);
+ shifted = (QtWidgets.QApplication.queryKeyboardModifiers() &
+ QtCore.Qt.ShiftModifier)
+ tableWidget.setUpdatesEnabled(False)
inventoryHashesToTrash = []
# ranges in reversed order
- for r in sorted(tableWidget.selectedRanges(), key=lambda r: r.topRow())[::-1]:
- for i in range(r.bottomRow()-r.topRow()+1):
+ for r in sorted(
+ tableWidget.selectedRanges(), key=lambda r: r.topRow()
+ )[::-1]:
+ for i in range(r.bottomRow() - r.topRow() + 1):
inventoryHashToTrash = str(tableWidget.item(
- r.topRow()+i, 3).data(QtCore.Qt.UserRole).toPyObject())
+ r.topRow() + i, 3).data(QtCore.Qt.UserRole))
if inventoryHashToTrash in inventoryHashesToTrash:
continue
inventoryHashesToTrash.append(inventoryHashToTrash)
currentRow = r.topRow()
self.getCurrentMessageTextedit().setText("")
- tableWidget.model().removeRows(r.topRow(), r.bottomRow()-r.topRow()+1)
+ tableWidget.model().removeRows(
+ r.topRow(), r.bottomRow() - r.topRow() + 1)
idCount = len(inventoryHashesToTrash)
sqlExecuteChunked(
("DELETE FROM inbox" if folder == "trash" or shifted else
@@ -3097,20 +3247,24 @@ class MyForm(settingsmixin.SMainWindow):
tableWidget.setUpdatesEnabled(False)
inventoryHashesToTrash = []
# ranges in reversed order
- for r in sorted(tableWidget.selectedRanges(), key=lambda r: r.topRow())[::-1]:
- for i in range(r.bottomRow()-r.topRow()+1):
+ for r in sorted(
+ tableWidget.selectedRanges(),
+ key=lambda r: r.topRow())[::-1]:
+ for i in range(r.bottomRow() - r.topRow() + 1):
inventoryHashToTrash = str(tableWidget.item(
- r.topRow()+i, 3).data(QtCore.Qt.UserRole).toPyObject())
+ r.topRow() + i, 3).data(QtCore.Qt.UserRole))
if inventoryHashToTrash in inventoryHashesToTrash:
continue
inventoryHashesToTrash.append(inventoryHashToTrash)
currentRow = r.topRow()
self.getCurrentMessageTextedit().setText("")
- tableWidget.model().removeRows(r.topRow(), r.bottomRow()-r.topRow()+1)
+ tableWidget.model().removeRows(
+ r.topRow(), r.bottomRow() - r.topRow() + 1)
tableWidget.selectRow(0 if currentRow == 0 else currentRow - 1)
idCount = len(inventoryHashesToTrash)
- sqlExecuteChunked('''UPDATE inbox SET folder='inbox' WHERE msgid IN({0})''',
- idCount, *inventoryHashesToTrash)
+ sqlExecuteChunked(
+ "UPDATE inbox SET folder='inbox' WHERE msgid IN({0})",
+ idCount, *inventoryHashesToTrash)
tableWidget.selectRow(0 if currentRow == 0 else currentRow - 1)
tableWidget.setUpdatesEnabled(True)
self.propagateUnreadCount()
@@ -3129,16 +3283,20 @@ class MyForm(settingsmixin.SMainWindow):
# Retrieve the message data out of the SQL database
msgid = str(tableWidget.item(
- currentInboxRow, 3).data(QtCore.Qt.UserRole).toPyObject())
+ currentInboxRow, 3).data(QtCore.Qt.UserRole))
queryreturn = sqlQuery(
'''select message from inbox where msgid=?''', msgid)
if queryreturn != []:
for row in queryreturn:
message, = row
- defaultFilename = "".join(x for x in subjectAtCurrentInboxRow if x.isalnum()) + '.txt'
- filename = QtGui.QFileDialog.getSaveFileName(self, _translate("MainWindow","Save As..."), defaultFilename, "Text files (*.txt);;All files (*.*)")
- if filename == '':
+ defaultFilename = "".join(
+ x for x in subjectAtCurrentInboxRow if x.isalnum()) + '.txt'
+ filename, filetype = QtWidgets.QFileDialog.getSaveFileName(
+ self, _translate("MainWindow", "Save As..."), defaultFilename,
+ "Text files (*.txt);;All files (*.*)"
+ )
+ if not filename:
return
try:
f = open(filename, 'w')
@@ -3150,15 +3308,17 @@ class MyForm(settingsmixin.SMainWindow):
# Send item on the Sent tab to trash
def on_action_SentTrash(self):
+ currentRow = 0
tableWidget = self.getCurrentMessagelist()
if not tableWidget:
return
folder = self.getCurrentFolder()
- shifted = QtGui.QApplication.queryKeyboardModifiers() & QtCore.Qt.ShiftModifier
+ shifted = (QtWidgets.QApplication.queryKeyboardModifiers() &
+ QtCore.Qt.ShiftModifier)
while tableWidget.selectedIndexes() != []:
currentRow = tableWidget.selectedIndexes()[0].row()
ackdataToTrash = str(tableWidget.item(
- currentRow, 3).data(QtCore.Qt.UserRole).toPyObject())
+ currentRow, 3).data(QtCore.Qt.UserRole))
sqlExecute(
"DELETE FROM sent" if folder == "trash" or shifted else
"UPDATE sent SET folder='trash'"
@@ -3183,15 +3343,18 @@ class MyForm(settingsmixin.SMainWindow):
queryreturn = sqlQuery('''select ackdata FROM sent WHERE status='forcepow' ''')
for row in queryreturn:
ackdata, = row
- queues.UISignalQueue.put(('updateSentItemStatusByAckdata', (
- ackdata, 'Overriding maximum-difficulty setting. Work queued.')))
+ queues.UISignalQueue.put((
+ 'updateSentItemStatusByAckdata',
+ (ackdata, 'Overriding maximum-difficulty setting.'
+ ' Work queued.')
+ ))
queues.workerQueue.put(('sendmessage', ''))
def on_action_SentClipboard(self):
currentRow = self.ui.tableWidgetInbox.currentRow()
addressAtCurrentRow = self.ui.tableWidgetInbox.item(
currentRow, 0).data(QtCore.Qt.UserRole)
- clipboard = QtGui.QApplication.clipboard()
+ clipboard = QtWidgets.QApplication.clipboard()
clipboard.setText(str(addressAtCurrentRow))
# Group of functions for the Address Book dialog box
@@ -3216,7 +3379,7 @@ class MyForm(settingsmixin.SMainWindow):
addresses_string = item.address
else:
addresses_string += ', ' + item.address
- clipboard = QtGui.QApplication.clipboard()
+ clipboard = QtWidgets.QApplication.clipboard()
clipboard.setText(addresses_string)
def on_action_AddressBookSend(self):
@@ -3226,8 +3389,7 @@ class MyForm(settingsmixin.SMainWindow):
return self.updateStatusBar(_translate(
"MainWindow", "No addresses selected."))
- addresses_string = unicode(
- self.ui.lineEditTo.text().toUtf8(), 'utf-8')
+ addresses_string = self.ui.lineEditTo.text()
for item in selected_items:
address_string = item.accountString()
if not addresses_string:
@@ -3258,7 +3420,7 @@ class MyForm(settingsmixin.SMainWindow):
)
def on_context_menuAddressBook(self, point):
- self.popMenuAddressBook = QtGui.QMenu(self)
+ self.popMenuAddressBook = QtWidgets.QMenu(self)
self.popMenuAddressBook.addAction(self.actionAddressBookSend)
self.popMenuAddressBook.addAction(self.actionAddressBookClipboard)
self.popMenuAddressBook.addAction(self.actionAddressBookSubscribe)
@@ -3288,7 +3450,7 @@ class MyForm(settingsmixin.SMainWindow):
self.click_pushButtonAddSubscription()
def on_action_SubscriptionsDelete(self):
- if QtGui.QMessageBox.question(
+ if QtWidgets.QMessageBox.question(
self, "Delete subscription?",
_translate(
"MainWindow",
@@ -3299,8 +3461,8 @@ class MyForm(settingsmixin.SMainWindow):
" messages, but you can still view messages you"
" already received.\n\nAre you sure you want to"
" delete the subscription?"
- ), QtGui.QMessageBox.Yes | QtGui.QMessageBox.No
- ) != QtGui.QMessageBox.Yes:
+ ), QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.No
+ ) != QtWidgets.QMessageBox.Yes:
return
address = self.getCurrentAccount()
sqlExecute('''DELETE FROM subscriptions WHERE address=?''',
@@ -3312,7 +3474,7 @@ class MyForm(settingsmixin.SMainWindow):
def on_action_SubscriptionsClipboard(self):
address = self.getCurrentAccount()
- clipboard = QtGui.QApplication.clipboard()
+ clipboard = QtWidgets.QApplication.clipboard()
clipboard.setText(str(address))
def on_action_SubscriptionsEnable(self):
@@ -3337,7 +3499,7 @@ class MyForm(settingsmixin.SMainWindow):
def on_context_menuSubscriptions(self, point):
currentItem = self.getCurrentItem()
- self.popMenuSubscriptions = QtGui.QMenu(self)
+ self.popMenuSubscriptions = QtWidgets.QMenu(self)
if isinstance(currentItem, Ui_AddressWidget):
self.popMenuSubscriptions.addAction(self.actionsubscriptionsNew)
self.popMenuSubscriptions.addAction(self.actionsubscriptionsDelete)
@@ -3377,17 +3539,15 @@ class MyForm(settingsmixin.SMainWindow):
return self.ui.tableWidgetInboxSubscriptions
elif widget == self.ui.treeWidgetChans:
return self.ui.tableWidgetInboxChans
- else:
- return None
def getCurrentTreeWidget(self):
- currentIndex = self.ui.tabWidget.currentIndex();
- treeWidgetList = [
+ currentIndex = self.ui.tabWidget.currentIndex()
+ treeWidgetList = (
self.ui.treeWidgetYourIdentities,
False,
self.ui.treeWidgetSubscriptions,
self.ui.treeWidgetChans
- ]
+ )
if currentIndex >= 0 and currentIndex < len(treeWidgetList):
return treeWidgetList[currentIndex]
else:
@@ -3405,18 +3565,18 @@ class MyForm(settingsmixin.SMainWindow):
return self.ui.treeWidgetYourIdentities
def getCurrentMessagelist(self):
- currentIndex = self.ui.tabWidget.currentIndex();
- messagelistList = [
+ currentIndex = self.ui.tabWidget.currentIndex()
+ messagelistList = (
self.ui.tableWidgetInbox,
False,
self.ui.tableWidgetInboxSubscriptions,
self.ui.tableWidgetInboxChans,
- ]
+ )
if currentIndex >= 0 and currentIndex < len(messagelistList):
return messagelistList[currentIndex]
else:
return False
-
+
def getAccountMessagelist(self, account):
try:
if account.type == AccountMixin.CHAN:
@@ -3433,20 +3593,20 @@ class MyForm(settingsmixin.SMainWindow):
if messagelist:
currentRow = messagelist.currentRow()
if currentRow >= 0:
- msgid = str(messagelist.item(
- currentRow, 3).data(QtCore.Qt.UserRole).toPyObject())
+ msgid = messagelist.item(
+ currentRow, 3).data(QtCore.Qt.UserRole)
# data is saved at the 4. column of the table...
return msgid
return False
def getCurrentMessageTextedit(self):
currentIndex = self.ui.tabWidget.currentIndex()
- messagelistList = [
+ messagelistList = (
self.ui.textEditInboxMessage,
False,
self.ui.textEditInboxMessageSubscriptions,
self.ui.textEditInboxMessageChans,
- ]
+ )
if currentIndex >= 0 and currentIndex < len(messagelistList):
return messagelistList[currentIndex]
else:
@@ -3466,33 +3626,29 @@ class MyForm(settingsmixin.SMainWindow):
def getCurrentSearchLine(self, currentIndex=None, retObj=False):
if currentIndex is None:
currentIndex = self.ui.tabWidget.currentIndex()
- messagelistList = [
+ messagelistList = (
self.ui.inboxSearchLineEdit,
False,
self.ui.inboxSearchLineEditSubscriptions,
self.ui.inboxSearchLineEditChans,
- ]
+ )
if currentIndex >= 0 and currentIndex < len(messagelistList):
if retObj:
return messagelistList[currentIndex]
else:
- return messagelistList[currentIndex].text().toUtf8().data()
- else:
- return None
+ return messagelistList[currentIndex].text()
def getCurrentSearchOption(self, currentIndex=None):
if currentIndex is None:
currentIndex = self.ui.tabWidget.currentIndex()
- messagelistList = [
+ messagelistList = (
self.ui.inboxSearchOption,
False,
self.ui.inboxSearchOptionSubscriptions,
self.ui.inboxSearchOptionChans,
- ]
+ )
if currentIndex >= 0 and currentIndex < len(messagelistList):
- return messagelistList[currentIndex].currentText().toUtf8().data()
- else:
- return None
+ return messagelistList[currentIndex].currentText()
# Group of functions for the Your Identities dialog box
def getCurrentItem(self, treeWidget=None):
@@ -3536,7 +3692,7 @@ class MyForm(settingsmixin.SMainWindow):
if account.type == AccountMixin.NORMAL:
return # maybe in the future
elif account.type == AccountMixin.CHAN:
- if QtGui.QMessageBox.question(
+ if QtWidgets.QMessageBox.question(
self, "Delete channel?",
_translate(
"MainWindow",
@@ -3547,8 +3703,8 @@ class MyForm(settingsmixin.SMainWindow):
" messages, but you can still view messages you"
" already received.\n\nAre you sure you want to"
" delete the channel?"
- ), QtGui.QMessageBox.Yes | QtGui.QMessageBox.No
- ) == QtGui.QMessageBox.Yes:
+ ), QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.No
+ ) == QtWidgets.QMessageBox.Yes:
BMConfigParser().remove_section(str(account.address))
else:
return
@@ -3589,43 +3745,45 @@ class MyForm(settingsmixin.SMainWindow):
def on_action_Clipboard(self):
address = self.getCurrentAccount()
- clipboard = QtGui.QApplication.clipboard()
+ clipboard = QtWidgets.QApplication.clipboard()
clipboard.setText(str(address))
def on_action_ClipboardMessagelist(self):
tableWidget = self.getCurrentMessagelist()
currentColumn = tableWidget.currentColumn()
currentRow = tableWidget.currentRow()
- if currentColumn not in [0, 1, 2]: # to, from, subject
- if self.getCurrentFolder() == "sent":
+ currentFolder = self.getCurrentFolder()
+ if currentColumn not in (0, 1, 2): # to, from, subject
+ if currentFolder == "sent":
currentColumn = 0
else:
currentColumn = 1
- if self.getCurrentFolder() == "sent":
+ if currentFolder == "sent":
myAddress = tableWidget.item(currentRow, 1).data(QtCore.Qt.UserRole)
otherAddress = tableWidget.item(currentRow, 0).data(QtCore.Qt.UserRole)
else:
myAddress = tableWidget.item(currentRow, 0).data(QtCore.Qt.UserRole)
otherAddress = tableWidget.item(currentRow, 1).data(QtCore.Qt.UserRole)
account = accountClass(myAddress)
- if isinstance(account, GatewayAccount) and otherAddress == account.relayAddress and (
- (currentColumn in [0, 2] and self.getCurrentFolder() == "sent") or
- (currentColumn in [1, 2] and self.getCurrentFolder() != "sent")):
- text = str(tableWidget.item(currentRow, currentColumn).label)
+ if isinstance(account, GatewayAccount) \
+ and otherAddress == account.relayAddress and (
+ (currentColumn in (0, 2) and currentFolder == "sent")
+ or (currentColumn in (1, 2) and currentFolder != "sent")):
+ text = tableWidget.item(currentRow, currentColumn).label
else:
text = tableWidget.item(currentRow, currentColumn).data(QtCore.Qt.UserRole)
- text = unicode(str(text), 'utf-8', 'ignore')
- clipboard = QtGui.QApplication.clipboard()
+ # text = unicode(str(text), 'utf-8', 'ignore')
+ clipboard = QtWidgets.QApplication.clipboard()
clipboard.setText(text)
- #set avatar functions
+ # set avatar functions
def on_action_TreeWidgetSetAvatar(self):
address = self.getCurrentAccount()
self.setAvatar(address)
def on_action_AddressBookSetAvatar(self):
self.on_action_SetAvatar(self.ui.tableWidgetAddressBook)
-
+
def on_action_SetAvatar(self, thisTableWidget):
currentRow = thisTableWidget.currentRow()
addressAtCurrentRow = thisTableWidget.item(
@@ -3639,15 +3797,29 @@ class MyForm(settingsmixin.SMainWindow):
if not os.path.exists(state.appdata + 'avatars/'):
os.makedirs(state.appdata + 'avatars/')
hash = hashlib.md5(addBMIfNotPresent(addressAtCurrentRow)).hexdigest()
- extensions = ['PNG', 'GIF', 'JPG', 'JPEG', 'SVG', 'BMP', 'MNG', 'PBM', 'PGM', 'PPM', 'TIFF', 'XBM', 'XPM', 'TGA']
# http://pyqt.sourceforge.net/Docs/PyQt4/qimagereader.html#supportedImageFormats
- names = {'BMP':'Windows Bitmap', 'GIF':'Graphic Interchange Format', 'JPG':'Joint Photographic Experts Group', 'JPEG':'Joint Photographic Experts Group', 'MNG':'Multiple-image Network Graphics', 'PNG':'Portable Network Graphics', 'PBM':'Portable Bitmap', 'PGM':'Portable Graymap', 'PPM':'Portable Pixmap', 'TIFF':'Tagged Image File Format', 'XBM':'X11 Bitmap', 'XPM':'X11 Pixmap', 'SVG':'Scalable Vector Graphics', 'TGA':'Targa Image Format'}
+ names = {
+ 'BMP': 'Windows Bitmap',
+ 'GIF': 'Graphic Interchange Format',
+ 'JPG': 'Joint Photographic Experts Group',
+ 'JPEG': 'Joint Photographic Experts Group',
+ 'MNG': 'Multiple-image Network Graphics',
+ 'PNG': 'Portable Network Graphics',
+ 'PBM': 'Portable Bitmap',
+ 'PGM': 'Portable Graymap',
+ 'PPM': 'Portable Pixmap',
+ 'TIFF': 'Tagged Image File Format',
+ 'XBM': 'X11 Bitmap',
+ 'XPM': 'X11 Pixmap',
+ 'SVG': 'Scalable Vector Graphics',
+ 'TGA': 'Targa Image Format'
+ }
filters = []
all_images_filter = []
current_files = []
- for ext in extensions:
- filters += [ names[ext] + ' (*.' + ext.lower() + ')' ]
- all_images_filter += [ '*.' + ext.lower() ]
+ for ext in names:
+ filters += [names[ext] + ' (*.' + ext.lower() + ')']
+ all_images_filter += ['*.' + ext.lower()]
upper = state.appdata + 'avatars/' + hash + '.' + ext.upper()
lower = state.appdata + 'avatars/' + hash + '.' + ext.lower()
if os.path.isfile(lower):
@@ -3656,33 +3828,43 @@ class MyForm(settingsmixin.SMainWindow):
current_files += [upper]
filters[0:0] = ['Image files (' + ' '.join(all_images_filter) + ')']
filters[1:1] = ['All files (*.*)']
- sourcefile = QtGui.QFileDialog.getOpenFileName(
+ sourcefile, filetype = QtWidgets.QFileDialog.getOpenFileName(
self, _translate("MainWindow", "Set avatar..."),
- filter = ';;'.join(filters)
+ filter=';;'.join(filters)
)
# determine the correct filename (note that avatars don't use the suffix)
destination = state.appdata + 'avatars/' + hash + '.' + sourcefile.split('.')[-1]
exists = QtCore.QFile.exists(destination)
if sourcefile == '':
# ask for removal of avatar
- if exists | (len(current_files)>0):
- displayMsg = _translate("MainWindow", "Do you really want to remove this avatar?")
- overwrite = QtGui.QMessageBox.question(
- self, 'Message', displayMsg, QtGui.QMessageBox.Yes, QtGui.QMessageBox.No)
+ if exists | (len(current_files) > 0):
+ displayMsg = _translate(
+ "MainWindow", "Do you really want to remove this avatar?"
+ )
+ overwrite = QtWidgets.QMessageBox.question(
+ self, 'Message', displayMsg,
+ QtWidgets.QMessageBox.Yes, QtWidgets.QMessageBox.No
+ )
else:
- overwrite = QtGui.QMessageBox.No
+ overwrite = QtWidgets.QMessageBox.No
else:
# ask whether to overwrite old avatar
- if exists | (len(current_files)>0):
- displayMsg = _translate("MainWindow", "You have already set an avatar for this address. Do you really want to overwrite it?")
- overwrite = QtGui.QMessageBox.question(
- self, 'Message', displayMsg, QtGui.QMessageBox.Yes, QtGui.QMessageBox.No)
+ if exists | (len(current_files) > 0):
+ displayMsg = _translate(
+ "MainWindow",
+ "You have already set an avatar for this address."
+ " Do you really want to overwrite it?"
+ )
+ overwrite = QtWidgets.QMessageBox.question(
+ self, 'Message', displayMsg,
+ QtWidgets.QMessageBox.Yes, QtWidgets.QMessageBox.No
+ )
else:
- overwrite = QtGui.QMessageBox.No
-
+ overwrite = QtWidgets.QMessageBox.No
+
# copy the image file to the appdata folder
- if (not exists) | (overwrite == QtGui.QMessageBox.Yes):
- if overwrite == QtGui.QMessageBox.Yes:
+ if (not exists) | (overwrite == QtWidgets.QMessageBox.Yes):
+ if overwrite == QtWidgets.QMessageBox.Yes:
for file in current_files:
QtCore.QFile.remove(file)
QtCore.QFile.remove(destination)
@@ -3714,10 +3896,10 @@ class MyForm(settingsmixin.SMainWindow):
"MainWindow", "Sound files (%s)" %
' '.join(['*%s%s' % (os.extsep, ext) for ext in sound.extensions])
))]
- sourcefile = unicode(QtGui.QFileDialog.getOpenFileName(
+ sourcefile, filetype = QtWidgets.QFileDialog.getOpenFileName(
self, _translate("MainWindow", "Set notification sound..."),
filter=';;'.join(filters)
- ))
+ )
if not sourcefile:
return
@@ -3732,15 +3914,15 @@ class MyForm(settingsmixin.SMainWindow):
pattern = destfile.lower()
for item in os.listdir(destdir):
if item.lower() == pattern:
- overwrite = QtGui.QMessageBox.question(
+ overwrite = QtWidgets.QMessageBox.question(
self, _translate("MainWindow", "Message"),
_translate(
"MainWindow",
"You have already set a notification sound"
" for this address book entry."
" Do you really want to overwrite it?"),
- QtGui.QMessageBox.Yes, QtGui.QMessageBox.No
- ) == QtGui.QMessageBox.Yes
+ QtWidgets.QMessageBox.Yes, QtWidgets.QMessageBox.No
+ ) == QtWidgets.QMessageBox.Yes
if overwrite:
QtCore.QFile.remove(os.path.join(destdir, item))
break
@@ -3751,18 +3933,23 @@ class MyForm(settingsmixin.SMainWindow):
def on_context_menuYourIdentities(self, point):
currentItem = self.getCurrentItem()
- self.popMenuYourIdentities = QtGui.QMenu(self)
+ self.popMenuYourIdentities = QtWidgets.QMenu(self)
if isinstance(currentItem, Ui_AddressWidget):
self.popMenuYourIdentities.addAction(self.actionNewYourIdentities)
self.popMenuYourIdentities.addSeparator()
- self.popMenuYourIdentities.addAction(self.actionClipboardYourIdentities)
+ self.popMenuYourIdentities.addAction(
+ self.actionClipboardYourIdentities)
self.popMenuYourIdentities.addSeparator()
if currentItem.isEnabled:
- self.popMenuYourIdentities.addAction(self.actionDisableYourIdentities)
+ self.popMenuYourIdentities.addAction(
+ self.actionDisableYourIdentities)
else:
- self.popMenuYourIdentities.addAction(self.actionEnableYourIdentities)
- self.popMenuYourIdentities.addAction(self.actionSetAvatarYourIdentities)
- self.popMenuYourIdentities.addAction(self.actionSpecialAddressBehaviorYourIdentities)
+ self.popMenuYourIdentities.addAction(
+ self.actionEnableYourIdentities)
+ self.popMenuYourIdentities.addAction(
+ self.actionSetAvatarYourIdentities)
+ self.popMenuYourIdentities.addAction(
+ self.actionSpecialAddressBehaviorYourIdentities)
self.popMenuYourIdentities.addAction(self.actionEmailGateway)
self.popMenuYourIdentities.addSeparator()
if currentItem.type != AccountMixin.ALL:
@@ -3781,7 +3968,7 @@ class MyForm(settingsmixin.SMainWindow):
# TODO make one popMenu
def on_context_menuChan(self, point):
currentItem = self.getCurrentItem()
- self.popMenu = QtGui.QMenu(self)
+ self.popMenu = QtWidgets.QMenu(self)
if isinstance(currentItem, Ui_AddressWidget):
self.popMenu.addAction(self.actionNew)
self.popMenu.addAction(self.actionDelete)
@@ -3817,7 +4004,7 @@ class MyForm(settingsmixin.SMainWindow):
self.on_context_menuSent(point)
return
- self.popMenuInbox = QtGui.QMenu(self)
+ self.popMenuInbox = QtWidgets.QMenu(self)
self.popMenuInbox.addAction(self.actionForceHtml)
self.popMenuInbox.addAction(self.actionMarkUnread)
self.popMenuInbox.addSeparator()
@@ -3852,7 +4039,7 @@ class MyForm(settingsmixin.SMainWindow):
def on_context_menuSent(self, point):
currentRow = self.ui.tableWidgetInbox.currentRow()
- self.popMenuSent = QtGui.QMenu(self)
+ self.popMenuSent = QtWidgets.QMenu(self)
self.popMenuSent.addAction(self.actionSentClipboard)
self._contact_selected = self.ui.tableWidgetInbox.item(currentRow, 0)
# preloaded gui.menu plugins with prefix 'address'
@@ -3866,7 +4053,7 @@ class MyForm(settingsmixin.SMainWindow):
# menu option (Force Send) if it is.
if currentRow >= 0:
ackData = str(self.ui.tableWidgetInbox.item(
- currentRow, 3).data(QtCore.Qt.UserRole).toPyObject())
+ currentRow, 3).data(QtCore.Qt.UserRole))
queryreturn = sqlQuery('''SELECT status FROM sent where ackdata=?''', ackData)
for row in queryreturn:
status, = row
@@ -3877,24 +4064,26 @@ class MyForm(settingsmixin.SMainWindow):
def inboxSearchLineEditUpdated(self, text):
# dynamic search for too short text is slow
- if len(str(text)) < 3:
+ if len(text) < 3:
return
messagelist = self.getCurrentMessagelist()
searchOption = self.getCurrentSearchOption()
if messagelist:
account = self.getCurrentAccount()
folder = self.getCurrentFolder()
- self.loadMessagelist(messagelist, account, folder, searchOption, str(text))
+ self.loadMessagelist(
+ messagelist, account, folder, searchOption, text)
def inboxSearchLineEditReturnPressed(self):
logger.debug("Search return pressed")
searchLine = self.getCurrentSearchLine()
messagelist = self.getCurrentMessagelist()
- if len(str(searchLine)) < 3:
+ if len(searchLine) < 3:
searchOption = self.getCurrentSearchOption()
account = self.getCurrentAccount()
folder = self.getCurrentFolder()
- self.loadMessagelist(messagelist, account, folder, searchOption, searchLine)
+ self.loadMessagelist(
+ messagelist, account, folder, searchOption, searchLine)
if messagelist:
messagelist.setFocus()
@@ -3929,8 +4118,8 @@ class MyForm(settingsmixin.SMainWindow):
# "All accounts" can't be renamed
if item.type == AccountMixin.ALL:
return
-
- newLabel = unicode(item.text(0), 'utf-8', 'ignore')
+
+ newLabel = item.text(0)
oldLabel = item.defaultLabel()
# unchanged, do not do anything either
@@ -3949,7 +4138,9 @@ class MyForm(settingsmixin.SMainWindow):
self.rerenderMessagelistFromLabels()
if item.type != AccountMixin.SUBSCRIPTION:
self.rerenderMessagelistToLabels()
- if item.type in (AccountMixin.NORMAL, AccountMixin.CHAN, AccountMixin.SUBSCRIPTION):
+ if item.type in (
+ AccountMixin.NORMAL, AccountMixin.CHAN, AccountMixin.SUBSCRIPTION
+ ):
self.rerenderAddressBook()
self.recurDepth -= 1
@@ -3969,9 +4160,9 @@ class MyForm(settingsmixin.SMainWindow):
)
try:
- message = queryreturn[-1][0]
+ message = unicode(queryreturn[-1][0], 'utf-8')
except NameError:
- message = ""
+ message = u""
except IndexError:
message = _translate(
"MainWindow",
@@ -4066,17 +4257,27 @@ class MyForm(settingsmixin.SMainWindow):
# In order for the time columns on the Inbox and Sent tabs to be sorted
# correctly (rather than alphabetically), we need to overload the <
# operator and use this class instead of QTableWidgetItem.
-class myTableWidgetItem(QtGui.QTableWidgetItem):
+class myTableWidgetItem(QtWidgets.QTableWidgetItem):
def __lt__(self, other):
- return int(self.data(33).toPyObject()) < int(other.data(33).toPyObject())
+ return self.data(33) < other.data(33)
+
+ def setData(self, role, value):
+ if role == QtCore.Qt.UserRole:
+ self._data = value
+ return super(myTableWidgetItem, self).setData(role, value)
+
+ def data(self, role):
+ if role == QtCore.Qt.UserRole:
+ return self._data
+ return super(myTableWidgetItem, self).data(role)
app = None
myapp = None
-class MySingleApplication(QtGui.QApplication):
+class MySingleApplication(QtWidgets.QApplication):
"""
Listener to allow our Qt form to get focus when another instance of the
application is open.
@@ -4095,15 +4296,15 @@ class MySingleApplication(QtGui.QApplication):
self.server = None
self.is_running = False
- socket = QLocalSocket()
+ socket = QtNetwork.QLocalSocket()
socket.connectToServer(id)
self.is_running = socket.waitForConnected()
# Cleanup past crashed servers
if not self.is_running:
- if socket.error() == QLocalSocket.ConnectionRefusedError:
+ if socket.error() == QtNetwork.QLocalSocket.ConnectionRefusedError:
socket.disconnectFromServer()
- QLocalServer.removeServer(id)
+ QtNetwork.QLocalServer.removeServer(id)
socket.abort()
@@ -4114,7 +4315,7 @@ class MySingleApplication(QtGui.QApplication):
else:
# Nope, create a local server with this id and assign on_new_connection
# for whenever a second instance tries to run focus the application.
- self.server = QLocalServer()
+ self.server = QtNetwork.QLocalServer()
self.server.listen(id)
self.server.newConnection.connect(self.on_new_connection)
diff --git a/src/bitmessageqt/account.py b/src/bitmessageqt/account.py
index 50ea3548..31780e20 100644
--- a/src/bitmessageqt/account.py
+++ b/src/bitmessageqt/account.py
@@ -1,46 +1,31 @@
-# pylint: disable=too-many-instance-attributes,attribute-defined-outside-init
"""
-account.py
-==========
-
Account related functions.
"""
-from __future__ import absolute_import
-
import inspect
import re
import sys
import time
-from PyQt4 import QtGui
-
import queues
from addresses import decodeAddress
from bmconfigparser import BMConfigParser
from helper_ackPayload import genAckPayload
from helper_sql import sqlQuery, sqlExecute
-from .foldertree import AccountMixin
-from .utils import str_broadcast_subscribers
+from foldertree import AccountMixin
+from utils import str_broadcast_subscribers
+from tr import _translate
def getSortedAccounts():
- """Get a sorted list of configSections"""
-
+ """Get a sorted list of address config sections"""
configSections = BMConfigParser().addresses()
configSections.sort(
cmp=lambda x, y: cmp(
- unicode(
- BMConfigParser().get(
- x,
- 'label'),
- 'utf-8').lower(),
- unicode(
- BMConfigParser().get(
- y,
- 'label'),
- 'utf-8').lower()))
+ unicode(BMConfigParser().get(x, 'label'), 'utf-8').lower(),
+ unicode(BMConfigParser().get(y, 'label'), 'utf-8').lower())
+ )
return configSections
@@ -94,7 +79,8 @@ def accountClass(address):
return subscription
try:
gateway = BMConfigParser().get(address, "gateway")
- for _, cls in inspect.getmembers(sys.modules[__name__], inspect.isclass):
+ for _, cls in inspect.getmembers(
+ sys.modules[__name__], inspect.isclass):
if issubclass(cls, GatewayAccount) and cls.gatewayName == gateway:
return cls(address)
# general gateway
@@ -105,7 +91,7 @@ def accountClass(address):
return BMAccount(address)
-class AccountColor(AccountMixin): # pylint: disable=too-few-public-methods
+class AccountColor(AccountMixin):
"""Set the type of account"""
def __init__(self, address, address_type=None):
@@ -127,12 +113,35 @@ class AccountColor(AccountMixin): # pylint: disable=too-few-public-methods
self.type = address_type
-class BMAccount(object):
- """Encapsulate a Bitmessage account"""
-
+class NoAccount(object):
+ """Minimal account like object (All accounts)"""
+ # pylint: disable=too-many-instance-attributes
def __init__(self, address=None):
self.address = address
self.type = AccountMixin.NORMAL
+ self.toAddress = self.fromAddress = ''
+ self.subject = self.message = ''
+ self.fromLabel = self.toLabel = ''
+
+ def getLabel(self, address=None):
+ """Get a label for this bitmessage account"""
+ return address or self.address
+
+ def parseMessage(self, toAddress, fromAddress, subject, message):
+ """Set metadata and address labels on self"""
+ self.toAddress = toAddress
+ self.fromAddress = fromAddress
+ self.subject = subject
+ self.message = message
+ self.fromLabel = self.getLabel(fromAddress)
+ self.toLabel = self.getLabel(toAddress)
+
+
+class BMAccount(NoAccount):
+ """Encapsulate a Bitmessage account"""
+
+ def __init__(self, address=None):
+ super(BMAccount, self).__init__(address)
if BMConfigParser().has_section(address):
if BMConfigParser().safeGetBoolean(self.address, 'chan'):
self.type = AccountMixin.CHAN
@@ -148,8 +157,7 @@ class BMAccount(object):
def getLabel(self, address=None):
"""Get a label for this bitmessage account"""
- if address is None:
- address = self.address
+ address = super(BMAccount, self).getLabel(address)
label = BMConfigParser().safeGet(address, 'label', address)
queryreturn = sqlQuery(
'''select label from addressbook where address=?''', address)
@@ -162,33 +170,7 @@ class BMAccount(object):
if queryreturn != []:
for row in queryreturn:
label, = row
- return label
-
- def parseMessage(self, toAddress, fromAddress, subject, message):
- """Set metadata and address labels on self"""
-
- self.toAddress = toAddress
- self.fromAddress = fromAddress
- if isinstance(subject, unicode):
- self.subject = str(subject)
- else:
- self.subject = subject
- self.message = message
- self.fromLabel = self.getLabel(fromAddress)
- self.toLabel = self.getLabel(toAddress)
-
-
-class NoAccount(BMAccount):
- """Override the __init__ method on a BMAccount"""
-
- def __init__(self, address=None): # pylint: disable=super-init-not-called
- self.address = address
- self.type = AccountMixin.NORMAL
-
- def getLabel(self, address=None):
- if address is None:
- address = self.address
- return address
+ return unicode(label, 'utf-8')
class SubscriptionAccount(BMAccount):
@@ -208,15 +190,11 @@ class GatewayAccount(BMAccount):
ALL_OK = 0
REGISTRATION_DENIED = 1
- def __init__(self, address):
- super(GatewayAccount, self).__init__(address)
-
def send(self):
- """Override the send method for gateway accounts"""
-
- # pylint: disable=unused-variable
- status, addressVersionNumber, streamNumber, ripe = decodeAddress(self.toAddress)
- stealthLevel = BMConfigParser().safeGetInt('bitmessagesettings', 'ackstealthlevel')
+ """The send method for gateway accounts"""
+ streamNumber, ripe = decodeAddress(self.toAddress)[2:]
+ stealthLevel = BMConfigParser().safeGetInt(
+ 'bitmessagesettings', 'ackstealthlevel')
ackdata = genAckPayload(streamNumber, stealthLevel)
sqlExecute(
'''INSERT INTO sent VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)''',
@@ -289,10 +267,9 @@ class MailchuckAccount(GatewayAccount):
def settings(self):
"""settings specific to a MailchuckAccount"""
-
self.toAddress = self.registrationAddress
self.subject = "config"
- self.message = QtGui.QApplication.translate(
+ self.message = _translate(
"Mailchuck",
"""# You can use this to configure your email gateway account
# Uncomment the setting you want to use
@@ -338,8 +315,9 @@ class MailchuckAccount(GatewayAccount):
def parseMessage(self, toAddress, fromAddress, subject, message):
"""parseMessage specific to a MailchuckAccount"""
-
- super(MailchuckAccount, self).parseMessage(toAddress, fromAddress, subject, message)
+ super(MailchuckAccount, self).parseMessage(
+ toAddress, fromAddress, subject, message
+ )
if fromAddress == self.relayAddress:
matches = self.regExpIncoming.search(subject)
if matches is not None:
@@ -360,6 +338,7 @@ class MailchuckAccount(GatewayAccount):
self.toLabel = matches.group(1)
self.toAddress = matches.group(1)
self.feedback = self.ALL_OK
- if fromAddress == self.registrationAddress and self.subject == "Registration Request Denied":
+ if fromAddress == self.registrationAddress \
+ and self.subject == "Registration Request Denied":
self.feedback = self.REGISTRATION_DENIED
return self.feedback
diff --git a/src/bitmessageqt/address_dialogs.py b/src/bitmessageqt/address_dialogs.py
index 60c10369..274dfbec 100644
--- a/src/bitmessageqt/address_dialogs.py
+++ b/src/bitmessageqt/address_dialogs.py
@@ -3,16 +3,20 @@ src/bitmessageqt/address_dialogs.py
===================================
"""
-# pylint: disable=attribute-defined-outside-init
+# pylint: disable=too-few-public-methods
+# https://github.com/PyCQA/pylint/issues/471
import hashlib
-from PyQt4 import QtCore, QtGui
+from qtpy import QtGui, QtWidgets
import queues
import widgets
-from account import AccountMixin, GatewayAccount, MailchuckAccount, accountClass, getSortedAccounts
-from addresses import addBMIfNotPresent, decodeAddress, encodeVarint
+from account import (
+ GatewayAccount, MailchuckAccount, AccountMixin, accountClass,
+ getSortedAccounts
+)
+from addresses import decodeAddress, encodeVarint, addBMIfNotPresent
from inventory import Inventory
from retranslateui import RetranslateMixin
from tr import _translate
@@ -20,22 +24,19 @@ from tr import _translate
class AddressCheckMixin(object):
"""Base address validation class for QT UI"""
- # pylint: disable=too-few-public-methods
- def __init__(self):
+ def _setup(self):
self.valid = False
- QtCore.QObject.connect( # pylint: disable=no-member
- self.lineEditAddress,
- QtCore.SIGNAL("textChanged(QString)"),
- self.addressChanged)
+ self.lineEditAddress.textChanged.connect(self.addressChanged)
def _onSuccess(self, addressVersion, streamNumber, ripe):
pass
- def addressChanged(self, QString):
- """Address validation callback, performs validation and gives feedback"""
- status, addressVersion, streamNumber, ripe = decodeAddress(
- str(QString))
+ def addressChanged(self, address):
+ """
+ Address validation callback, performs validation and gives feedback
+ """
+ status, addressVersion, streamNumber, ripe = decodeAddress(address)
self.valid = status == 'success'
if self.valid:
self.labelAddressCheck.setText(
@@ -80,19 +81,27 @@ class AddressCheckMixin(object):
))
-class AddressDataDialog(QtGui.QDialog, AddressCheckMixin):
- """QDialog with Bitmessage address validation"""
+class AddressDataDialog(QtWidgets.QDialog, AddressCheckMixin):
+ """
+ Base class for a dialog getting BM-address data.
+ Corresponding ui-file should define two fields:
+ lineEditAddress - for the address
+ lineEditLabel - for it's label
+ After address validation the values of that fields are put into
+ the data field of the dialog.
+ """
def __init__(self, parent):
super(AddressDataDialog, self).__init__(parent)
self.parent = parent
+ self.data = ("", "")
def accept(self):
- """Callback for QDIalog accepting value"""
+ """Callback for QDialog accepting value"""
if self.valid:
self.data = (
addBMIfNotPresent(str(self.lineEditAddress.text())),
- str(self.lineEditLabel.text().toUtf8())
+ self.lineEditLabel.text().encode('utf-8')
)
else:
queues.UISignalQueue.put(('updateStatusBar', _translate(
@@ -103,18 +112,18 @@ class AddressDataDialog(QtGui.QDialog, AddressCheckMixin):
class AddAddressDialog(AddressDataDialog, RetranslateMixin):
- """QDialog for adding a new address, with validation and translation"""
+ """QDialog for adding a new address"""
def __init__(self, parent=None, address=None):
super(AddAddressDialog, self).__init__(parent)
widgets.load('addaddressdialog.ui', self)
- AddressCheckMixin.__init__(self)
+ self._setup()
if address:
self.lineEditAddress.setText(address)
-class NewAddressDialog(QtGui.QDialog, RetranslateMixin):
- """QDialog for generating a new address, with translation"""
+class NewAddressDialog(QtWidgets.QDialog, RetranslateMixin):
+ """QDialog for generating a new address"""
def __init__(self, parent=None):
super(NewAddressDialog, self).__init__(parent)
@@ -126,7 +135,7 @@ class NewAddressDialog(QtGui.QDialog, RetranslateMixin):
self.radioButtonExisting.click()
self.comboBoxExisting.addItem(address)
self.groupBoxDeterministic.setHidden(True)
- QtGui.QWidget.resize(self, QtGui.QWidget.sizeHint(self))
+ QtWidgets.QWidget.resize(self, QtWidgets.QWidget.sizeHint(self))
self.show()
def accept(self):
@@ -143,13 +152,13 @@ class NewAddressDialog(QtGui.QDialog, RetranslateMixin):
self.comboBoxExisting.currentText())[2]
queues.addressGeneratorQueue.put((
'createRandomAddress', 4, streamNumberForAddress,
- str(self.newaddresslabel.text().toUtf8()), 1, "",
+ self.newaddresslabel.text().encode('utf-8'), 1, "",
self.checkBoxEighteenByteRipe.isChecked()
))
else:
if self.lineEditPassphrase.text() != \
self.lineEditPassphraseAgain.text():
- QtGui.QMessageBox.about(
+ QtWidgets.QMessageBox.about(
self, _translate("MainWindow", "Passphrase mismatch"),
_translate(
"MainWindow",
@@ -157,7 +166,7 @@ class NewAddressDialog(QtGui.QDialog, RetranslateMixin):
" match. Try again.")
)
elif self.lineEditPassphrase.text() == "":
- QtGui.QMessageBox.about(
+ QtWidgets.QMessageBox.about(
self, _translate("MainWindow", "Choose a passphrase"),
_translate(
"MainWindow", "You really do need a passphrase.")
@@ -170,18 +179,18 @@ class NewAddressDialog(QtGui.QDialog, RetranslateMixin):
'createDeterministicAddresses', 4, streamNumberForAddress,
"unused deterministic address",
self.spinBoxNumberOfAddressesToMake.value(),
- self.lineEditPassphrase.text().toUtf8(),
+ self.lineEditPassphrase.text().encode('utf-8'),
self.checkBoxEighteenByteRipe.isChecked()
))
class NewSubscriptionDialog(AddressDataDialog, RetranslateMixin):
- """QDialog for subscribing to an address, with validation and translation"""
+ """QDialog for subscribing to an address"""
def __init__(self, parent=None):
super(NewSubscriptionDialog, self).__init__(parent)
widgets.load('newsubscriptiondialog.ui', self)
- AddressCheckMixin.__init__(self)
+ self._setup()
def _onSuccess(self, addressVersion, streamNumber, ripe):
if addressVersion <= 3:
@@ -212,23 +221,24 @@ class NewSubscriptionDialog(AddressDataDialog, RetranslateMixin):
_translate(
"MainWindow",
"Display the %n recent broadcast(s) from this address.",
- None,
- QtCore.QCoreApplication.CodecForTr,
- count
+ None, count
))
-class RegenerateAddressesDialog(QtGui.QDialog, RetranslateMixin):
- """QDialog for regenerating deterministic addresses, with translation"""
+class RegenerateAddressesDialog(QtWidgets.QDialog, RetranslateMixin):
+ """QDialog for regenerating deterministic addresses"""
+
def __init__(self, parent=None):
super(RegenerateAddressesDialog, self).__init__(parent)
widgets.load('regenerateaddresses.ui', self)
self.groupBox.setTitle('')
- QtGui.QWidget.resize(self, QtGui.QWidget.sizeHint(self))
+ QtWidgets.QWidget.resize(self, QtWidgets.QWidget.sizeHint(self))
-class SpecialAddressBehaviorDialog(QtGui.QDialog, RetranslateMixin):
- """QDialog for special address behaviour (e.g. mailing list functionality), with translation"""
+class SpecialAddressBehaviorDialog(QtWidgets.QDialog, RetranslateMixin):
+ """
+ QDialog for special address behaviour (e.g. mailing list functionality)
+ """
def __init__(self, parent=None, config=None):
super(SpecialAddressBehaviorDialog, self).__init__(parent)
@@ -265,7 +275,7 @@ class SpecialAddressBehaviorDialog(QtGui.QDialog, RetranslateMixin):
unicode(mailingListName, 'utf-8')
)
- QtGui.QWidget.resize(self, QtGui.QWidget.sizeHint(self))
+ QtWidgets.QWidget.resize(self, QtWidgets.QWidget.sizeHint(self))
self.show()
def accept(self):
@@ -278,14 +288,15 @@ class SpecialAddressBehaviorDialog(QtGui.QDialog, RetranslateMixin):
# Set the color to either black or grey
if self.config.getboolean(self.address, 'enabled'):
self.parent.setCurrentItemColor(
- QtGui.QApplication.palette().text().color()
+ QtWidgets.QApplication.palette().text().color()
)
else:
self.parent.setCurrentItemColor(QtGui.QColor(128, 128, 128))
else:
self.config.set(str(self.address), 'mailinglist', 'true')
- self.config.set(str(self.address), 'mailinglistname', str(
- self.lineEditMailingListName.text().toUtf8()))
+ self.config.set(
+ str(self.address), 'mailinglistname',
+ self.lineEditMailingListName.text().encode('utf-8'))
self.parent.setCurrentItemColor(
QtGui.QColor(137, 4, 177)) # magenta
self.parent.rerenderComboBoxSendFrom()
@@ -294,8 +305,9 @@ class SpecialAddressBehaviorDialog(QtGui.QDialog, RetranslateMixin):
self.parent.rerenderMessagelistToLabels()
-class EmailGatewayDialog(QtGui.QDialog, RetranslateMixin):
- """QDialog for email gateway control, with translation"""
+class EmailGatewayDialog(QtWidgets.QDialog, RetranslateMixin):
+ """QDialog for email gateway control"""
+
def __init__(self, parent, config=None, account=None):
super(EmailGatewayDialog, self).__init__(parent)
widgets.load('emailgateway.ui', self)
@@ -333,7 +345,7 @@ class EmailGatewayDialog(QtGui.QDialog, RetranslateMixin):
else:
self.acct = MailchuckAccount(address)
self.lineEditEmail.setFocus()
- QtGui.QWidget.resize(self, QtGui.QWidget.sizeHint(self))
+ QtWidgets.QWidget.resize(self, QtWidgets.QWidget.sizeHint(self))
def accept(self):
"""Accept callback"""
@@ -347,7 +359,7 @@ class EmailGatewayDialog(QtGui.QDialog, RetranslateMixin):
if self.radioButtonRegister.isChecked() \
or self.radioButtonRegister.isHidden():
- email = str(self.lineEditEmail.text().toUtf8())
+ email = self.lineEditEmail.text().encode('utf-8')
self.acct.register(email)
self.config.set(self.acct.fromAddress, 'label', email)
self.config.set(self.acct.fromAddress, 'gateway', 'mailchuck')
diff --git a/src/bitmessageqt/addressvalidator.py b/src/bitmessageqt/addressvalidator.py
index f9de70a2..00bf5b13 100644
--- a/src/bitmessageqt/addressvalidator.py
+++ b/src/bitmessageqt/addressvalidator.py
@@ -1,4 +1,4 @@
-from PyQt4 import QtGui
+from qtpy import QtGui, QtWidgets
from Queue import Empty
from addresses import decodeAddress, addBMIfNotPresent
@@ -7,8 +7,14 @@ from queues import apiAddressGeneratorReturnQueue, addressGeneratorQueue
from tr import _translate
from utils import str_chan
+from debug import logger
+
+
class AddressPassPhraseValidatorMixin():
- def setParams(self, passPhraseObject=None, addressObject=None, feedBackObject=None, buttonBox=None, addressMandatory=True):
+ def setParams(
+ self, passPhraseObject=None, addressObject=None,
+ feedBackObject=None, buttonBox=None, addressMandatory=True
+ ):
self.addressObject = addressObject
self.passPhraseObject = passPhraseObject
self.feedBackObject = feedBackObject
@@ -16,7 +22,8 @@ class AddressPassPhraseValidatorMixin():
self.addressMandatory = addressMandatory
self.isValid = False
# save default text
- self.okButtonLabel = self.buttonBox.button(QtGui.QDialogButtonBox.Ok).text()
+ self.okButton = self.buttonBox.button(QtWidgets.QDialogButtonBox.Ok)
+ self.okButtonLabel = self.okButton.text()
def setError(self, string):
if string is not None and self.feedBackObject is not None:
@@ -27,11 +34,13 @@ class AddressPassPhraseValidatorMixin():
self.feedBackObject.setText(string)
self.isValid = False
if self.buttonBox:
- self.buttonBox.button(QtGui.QDialogButtonBox.Ok).setEnabled(False)
+ self.okButton.setEnabled(False)
if string is not None and self.feedBackObject is not None:
- self.buttonBox.button(QtGui.QDialogButtonBox.Ok).setText(_translate("AddressValidator", "Invalid"))
+ self.okButton.setText(
+ _translate("AddressValidator", "Invalid"))
else:
- self.buttonBox.button(QtGui.QDialogButtonBox.Ok).setText(_translate("AddressValidator", "Validating..."))
+ self.okButton.setText(
+ _translate("AddressValidator", "Validating..."))
def setOK(self, string):
if string is not None and self.feedBackObject is not None:
@@ -42,8 +51,8 @@ class AddressPassPhraseValidatorMixin():
self.feedBackObject.setText(string)
self.isValid = True
if self.buttonBox:
- self.buttonBox.button(QtGui.QDialogButtonBox.Ok).setEnabled(True)
- self.buttonBox.button(QtGui.QDialogButtonBox.Ok).setText(self.okButtonLabel)
+ self.okButton.setEnabled(True)
+ self.okButton.setText(self.okButtonLabel)
def checkQueue(self):
gotOne = False
@@ -55,7 +64,8 @@ class AddressPassPhraseValidatorMixin():
while True:
try:
- addressGeneratorReturnValue = apiAddressGeneratorReturnQueue.get(False)
+ addressGeneratorReturnValue = \
+ apiAddressGeneratorReturnQueue.get(False)
except Empty:
if gotOne:
break
@@ -65,80 +75,132 @@ class AddressPassPhraseValidatorMixin():
gotOne = True
if len(addressGeneratorReturnValue) == 0:
- self.setError(_translate("AddressValidator", "Address already present as one of your identities."))
+ 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."))
+ 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."))
+ self.setOK(
+ _translate(
+ "MainWindow", "Passphrase and address appear to be valid."))
def returnValid(self):
- if self.isValid:
- return QtGui.QValidator.Acceptable
- else:
- return QtGui.QValidator.Intermediate
+ return QtGui.QValidator.Acceptable if self.isValid \
+ else QtGui.QValidator.Intermediate
def validate(self, s, pos):
if self.addressObject is None:
address = None
else:
- address = str(self.addressObject.text().toUtf8())
+ address = self.addressObject.text().encode('utf-8')
if address == "":
address = None
if self.passPhraseObject is None:
passPhrase = ""
else:
- passPhrase = str(self.passPhraseObject.text().toUtf8())
+ passPhrase = self.passPhraseObject.text().encode('utf-8')
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."))
+ 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."))
+ 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."))
+ 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."))
+ 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():
+ if not self.okButton.hasFocus():
self.setError(None)
# check through generator
if address is None:
- addressGeneratorQueue.put(('createChan', 4, 1, str_chan + ' ' + str(passPhrase), passPhrase, False))
+ addressGeneratorQueue.put((
+ 'createChan', 4, 1, ' '.join([str_chan, passPhrase]),
+ passPhrase, False
+ ))
else:
- addressGeneratorQueue.put(('joinChan', addBMIfNotPresent(address), str_chan + ' ' + str(passPhrase), passPhrase, False))
+ addressGeneratorQueue.put((
+ 'joinChan', addBMIfNotPresent(address),
+ ' '.join([str_chan, passPhrase]), passPhrase, False
+ ))
- if self.buttonBox.button(QtGui.QDialogButtonBox.Ok).hasFocus():
+ if self.okButton.hasFocus():
return (self.returnValid(), pos)
else:
return (QtGui.QValidator.Intermediate, pos)
def checkData(self):
- return self.validate("", 0)
+ try:
+ return self.validate("", 0)
+ except Exception:
+ logger.warning("Exception in validate():", exc_info=True)
+
class AddressValidator(QtGui.QValidator, AddressPassPhraseValidatorMixin):
- def __init__(self, parent=None, passPhraseObject=None, feedBackObject=None, buttonBox=None, addressMandatory=True):
+ def __init__(
+ self, parent=None, passPhraseObject=None, feedBackObject=None,
+ buttonBox=None, addressMandatory=True
+ ):
super(AddressValidator, self).__init__(parent)
- self.setParams(passPhraseObject, parent, feedBackObject, buttonBox, addressMandatory)
+ self.setParams(
+ passPhraseObject, parent, feedBackObject, buttonBox,
+ addressMandatory
+ )
class PassPhraseValidator(QtGui.QValidator, AddressPassPhraseValidatorMixin):
- def __init__(self, parent=None, addressObject=None, feedBackObject=None, buttonBox=None, addressMandatory=False):
+ def __init__(
+ self, parent=None, addressObject=None, feedBackObject=None,
+ buttonBox=None, addressMandatory=False
+ ):
super(PassPhraseValidator, self).__init__(parent)
- self.setParams(parent, addressObject, feedBackObject, buttonBox, addressMandatory)
+ self.setParams(
+ parent, addressObject, feedBackObject, buttonBox,
+ addressMandatory
+ )
diff --git a/src/bitmessageqt/bitmessage_icons_rc.py b/src/bitmessageqt/bitmessage_icons_rc.py
index bb0a02c0..68404748 100644
--- a/src/bitmessageqt/bitmessage_icons_rc.py
+++ b/src/bitmessageqt/bitmessage_icons_rc.py
@@ -7,7 +7,7 @@
#
# WARNING! All changes made in this file will be lost!
-from PyQt4 import QtCore
+from qtpy import QtCore
qt_resource_data = "\
\x00\x00\x03\x66\
@@ -1666,10 +1666,15 @@ qt_resource_struct = "\
\x00\x00\x01\xe6\x00\x00\x00\x00\x00\x01\x00\x00\x34\xdf\
"
+
def qInitResources():
- QtCore.qRegisterResourceData(0x01, qt_resource_struct, qt_resource_name, qt_resource_data)
+ QtCore.qRegisterResourceData(
+ 0x01, qt_resource_struct, qt_resource_name, qt_resource_data)
+
def qCleanupResources():
- QtCore.qUnregisterResourceData(0x01, qt_resource_struct, qt_resource_name, qt_resource_data)
+ QtCore.qUnregisterResourceData(
+ 0x01, qt_resource_struct, qt_resource_name, qt_resource_data)
+
qInitResources()
diff --git a/src/bitmessageqt/bitmessageui.py b/src/bitmessageqt/bitmessageui.py
index 30d054d0..bb8b5fe3 100644
--- a/src/bitmessageqt/bitmessageui.py
+++ b/src/bitmessageqt/bitmessageui.py
@@ -1,13 +1,5 @@
-# -*- coding: utf-8 -*-
-
-# Form implementation generated from reading ui file 'bitmessageui.ui'
-#
-# Created: Mon Mar 23 22:18:07 2015
-# by: PyQt4 UI code generator 4.10.4
-#
-# WARNING! All changes made in this file will be lost!
-
-from PyQt4 import QtCore, QtGui
+from qtpy import QtCore, QtGui, QtWidgets
+from tr import _translate
from bmconfigparser import BMConfigParser
from foldertree import AddressBookCompleter
from messageview import MessageView
@@ -16,40 +8,23 @@ import settingsmixin
from networkstatus import NetworkStatus
from blacklist import Blacklist
-try:
- _fromUtf8 = QtCore.QString.fromUtf8
-except AttributeError:
- def _fromUtf8(s):
- return s
+import bitmessage_icons_rc
-try:
- _encoding = QtGui.QApplication.UnicodeUTF8
- def _translate(context, text, disambig, encoding = QtCore.QCoreApplication.CodecForTr, n = None):
- if n is None:
- return QtGui.QApplication.translate(context, text, disambig, _encoding)
- else:
- return QtGui.QApplication.translate(context, text, disambig, _encoding, n)
-except AttributeError:
- def _translate(context, text, disambig, encoding = QtCore.QCoreApplication.CodecForTr, n = None):
- if n is None:
- return QtGui.QApplication.translate(context, text, disambig)
- else:
- return QtGui.QApplication.translate(context, text, disambig, QtCore.QCoreApplication.CodecForTr, n)
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
- MainWindow.setObjectName(_fromUtf8("MainWindow"))
+ MainWindow.setObjectName("MainWindow")
MainWindow.resize(885, 580)
icon = QtGui.QIcon()
- icon.addPixmap(QtGui.QPixmap(_fromUtf8(":/newPrefix/images/can-icon-24px.png")), QtGui.QIcon.Normal, QtGui.QIcon.Off)
+ icon.addPixmap(QtGui.QPixmap(":/newPrefix/images/can-icon-24px.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off)
MainWindow.setWindowIcon(icon)
- MainWindow.setTabShape(QtGui.QTabWidget.Rounded)
- self.centralwidget = QtGui.QWidget(MainWindow)
- self.centralwidget.setObjectName(_fromUtf8("centralwidget"))
- self.gridLayout_10 = QtGui.QGridLayout(self.centralwidget)
- self.gridLayout_10.setObjectName(_fromUtf8("gridLayout_10"))
- self.tabWidget = QtGui.QTabWidget(self.centralwidget)
- sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Expanding)
+ MainWindow.setTabShape(QtWidgets.QTabWidget.Rounded)
+ self.centralwidget = QtWidgets.QWidget(MainWindow)
+ self.centralwidget.setObjectName("centralwidget")
+ self.gridLayout_10 = QtWidgets.QGridLayout(self.centralwidget)
+ self.gridLayout_10.setObjectName("gridLayout_10")
+ self.tabWidget = QtWidgets.QTabWidget(self.centralwidget)
+ sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.tabWidget.sizePolicy().hasHeightForWidth())
@@ -59,27 +34,27 @@ class Ui_MainWindow(object):
font = QtGui.QFont()
font.setPointSize(9)
self.tabWidget.setFont(font)
- self.tabWidget.setTabPosition(QtGui.QTabWidget.North)
- self.tabWidget.setTabShape(QtGui.QTabWidget.Rounded)
- self.tabWidget.setObjectName(_fromUtf8("tabWidget"))
- self.inbox = QtGui.QWidget()
- self.inbox.setObjectName(_fromUtf8("inbox"))
- self.gridLayout = QtGui.QGridLayout(self.inbox)
- self.gridLayout.setObjectName(_fromUtf8("gridLayout"))
+ self.tabWidget.setTabPosition(QtWidgets.QTabWidget.North)
+ self.tabWidget.setTabShape(QtWidgets.QTabWidget.Rounded)
+ self.tabWidget.setObjectName("tabWidget")
+ self.inbox = QtWidgets.QWidget()
+ self.inbox.setObjectName("inbox")
+ self.gridLayout = QtWidgets.QGridLayout(self.inbox)
+ self.gridLayout.setObjectName("gridLayout")
self.horizontalSplitter_3 = settingsmixin.SSplitter()
- self.horizontalSplitter_3.setObjectName(_fromUtf8("horizontalSplitter_3"))
+ self.horizontalSplitter_3.setObjectName("horizontalSplitter_3")
self.verticalSplitter_12 = settingsmixin.SSplitter()
- self.verticalSplitter_12.setObjectName(_fromUtf8("verticalSplitter_12"))
+ self.verticalSplitter_12.setObjectName("verticalSplitter_12")
self.verticalSplitter_12.setOrientation(QtCore.Qt.Vertical)
self.treeWidgetYourIdentities = settingsmixin.STreeWidget(self.inbox)
- self.treeWidgetYourIdentities.setObjectName(_fromUtf8("treeWidgetYourIdentities"))
+ self.treeWidgetYourIdentities.setObjectName("treeWidgetYourIdentities")
self.treeWidgetYourIdentities.resize(200, self.treeWidgetYourIdentities.height())
icon1 = QtGui.QIcon()
- icon1.addPixmap(QtGui.QPixmap(_fromUtf8(":/newPrefix/images/identities.png")), QtGui.QIcon.Selected, QtGui.QIcon.Off)
+ icon1.addPixmap(QtGui.QPixmap(":/newPrefix/images/identities.png"), QtGui.QIcon.Selected, QtGui.QIcon.Off)
self.treeWidgetYourIdentities.headerItem().setIcon(0, icon1)
self.verticalSplitter_12.addWidget(self.treeWidgetYourIdentities)
- self.pushButtonNewAddress = QtGui.QPushButton(self.inbox)
- self.pushButtonNewAddress.setObjectName(_fromUtf8("pushButtonNewAddress"))
+ self.pushButtonNewAddress = QtWidgets.QPushButton(self.inbox)
+ self.pushButtonNewAddress.setObjectName("pushButtonNewAddress")
self.pushButtonNewAddress.resize(200, self.pushButtonNewAddress.height())
self.verticalSplitter_12.addWidget(self.pushButtonNewAddress)
self.verticalSplitter_12.setStretchFactor(0, 1)
@@ -89,42 +64,42 @@ class Ui_MainWindow(object):
self.verticalSplitter_12.handle(1).setEnabled(False)
self.horizontalSplitter_3.addWidget(self.verticalSplitter_12)
self.verticalSplitter_7 = settingsmixin.SSplitter()
- self.verticalSplitter_7.setObjectName(_fromUtf8("verticalSplitter_7"))
+ self.verticalSplitter_7.setObjectName("verticalSplitter_7")
self.verticalSplitter_7.setOrientation(QtCore.Qt.Vertical)
- self.horizontalSplitterSearch = QtGui.QSplitter()
- self.horizontalSplitterSearch.setObjectName(_fromUtf8("horizontalSplitterSearch"))
- self.inboxSearchLineEdit = QtGui.QLineEdit(self.inbox)
- self.inboxSearchLineEdit.setObjectName(_fromUtf8("inboxSearchLineEdit"))
+ self.horizontalSplitterSearch = QtWidgets.QSplitter()
+ self.horizontalSplitterSearch.setObjectName("horizontalSplitterSearch")
+ self.inboxSearchLineEdit = QtWidgets.QLineEdit(self.inbox)
+ self.inboxSearchLineEdit.setObjectName("inboxSearchLineEdit")
self.horizontalSplitterSearch.addWidget(self.inboxSearchLineEdit)
- self.inboxSearchOption = QtGui.QComboBox(self.inbox)
- self.inboxSearchOption.setObjectName(_fromUtf8("inboxSearchOption"))
- self.inboxSearchOption.addItem(_fromUtf8(""))
- self.inboxSearchOption.addItem(_fromUtf8(""))
- self.inboxSearchOption.addItem(_fromUtf8(""))
- self.inboxSearchOption.addItem(_fromUtf8(""))
- self.inboxSearchOption.addItem(_fromUtf8(""))
- self.inboxSearchOption.setSizeAdjustPolicy(QtGui.QComboBox.AdjustToContents)
+ self.inboxSearchOption = QtWidgets.QComboBox(self.inbox)
+ self.inboxSearchOption.setObjectName("inboxSearchOption")
+ self.inboxSearchOption.addItem("")
+ self.inboxSearchOption.addItem("")
+ self.inboxSearchOption.addItem("")
+ self.inboxSearchOption.addItem("")
+ self.inboxSearchOption.addItem("")
+ self.inboxSearchOption.setSizeAdjustPolicy(QtWidgets.QComboBox.AdjustToContents)
self.horizontalSplitterSearch.addWidget(self.inboxSearchOption)
self.horizontalSplitterSearch.handle(1).setEnabled(False)
self.horizontalSplitterSearch.setStretchFactor(0, 1)
self.horizontalSplitterSearch.setStretchFactor(1, 0)
self.verticalSplitter_7.addWidget(self.horizontalSplitterSearch)
self.tableWidgetInbox = settingsmixin.STableWidget(self.inbox)
- self.tableWidgetInbox.setEditTriggers(QtGui.QAbstractItemView.NoEditTriggers)
+ self.tableWidgetInbox.setEditTriggers(QtWidgets.QAbstractItemView.NoEditTriggers)
self.tableWidgetInbox.setAlternatingRowColors(True)
- self.tableWidgetInbox.setSelectionMode(QtGui.QAbstractItemView.ExtendedSelection)
- self.tableWidgetInbox.setSelectionBehavior(QtGui.QAbstractItemView.SelectRows)
+ self.tableWidgetInbox.setSelectionMode(QtWidgets.QAbstractItemView.ExtendedSelection)
+ self.tableWidgetInbox.setSelectionBehavior(QtWidgets.QAbstractItemView.SelectRows)
self.tableWidgetInbox.setWordWrap(False)
- self.tableWidgetInbox.setObjectName(_fromUtf8("tableWidgetInbox"))
+ self.tableWidgetInbox.setObjectName("tableWidgetInbox")
self.tableWidgetInbox.setColumnCount(4)
self.tableWidgetInbox.setRowCount(0)
- item = QtGui.QTableWidgetItem()
+ item = QtWidgets.QTableWidgetItem()
self.tableWidgetInbox.setHorizontalHeaderItem(0, item)
- item = QtGui.QTableWidgetItem()
+ item = QtWidgets.QTableWidgetItem()
self.tableWidgetInbox.setHorizontalHeaderItem(1, item)
- item = QtGui.QTableWidgetItem()
+ item = QtWidgets.QTableWidgetItem()
self.tableWidgetInbox.setHorizontalHeaderItem(2, item)
- item = QtGui.QTableWidgetItem()
+ item = QtWidgets.QTableWidgetItem()
self.tableWidgetInbox.setHorizontalHeaderItem(3, item)
self.tableWidgetInbox.horizontalHeader().setCascadingSectionResizes(True)
self.tableWidgetInbox.horizontalHeader().setDefaultSectionSize(200)
@@ -138,7 +113,7 @@ class Ui_MainWindow(object):
self.textEditInboxMessage = MessageView(self.inbox)
self.textEditInboxMessage.setBaseSize(QtCore.QSize(0, 500))
self.textEditInboxMessage.setReadOnly(True)
- self.textEditInboxMessage.setObjectName(_fromUtf8("textEditInboxMessage"))
+ self.textEditInboxMessage.setObjectName("textEditInboxMessage")
self.verticalSplitter_7.addWidget(self.textEditInboxMessage)
self.verticalSplitter_7.setStretchFactor(0, 0)
self.verticalSplitter_7.setStretchFactor(1, 1)
@@ -154,31 +129,31 @@ class Ui_MainWindow(object):
self.horizontalSplitter_3.setCollapsible(1, False)
self.gridLayout.addWidget(self.horizontalSplitter_3)
icon2 = QtGui.QIcon()
- icon2.addPixmap(QtGui.QPixmap(_fromUtf8(":/newPrefix/images/inbox.png")), QtGui.QIcon.Normal, QtGui.QIcon.Off)
- self.tabWidget.addTab(self.inbox, icon2, _fromUtf8(""))
- self.send = QtGui.QWidget()
- self.send.setObjectName(_fromUtf8("send"))
- self.gridLayout_7 = QtGui.QGridLayout(self.send)
- self.gridLayout_7.setObjectName(_fromUtf8("gridLayout_7"))
+ icon2.addPixmap(QtGui.QPixmap(":/newPrefix/images/inbox.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off)
+ self.tabWidget.addTab(self.inbox, icon2, "")
+ self.send = QtWidgets.QWidget()
+ self.send.setObjectName("send")
+ self.gridLayout_7 = QtWidgets.QGridLayout(self.send)
+ self.gridLayout_7.setObjectName("gridLayout_7")
self.horizontalSplitter = settingsmixin.SSplitter()
- self.horizontalSplitter.setObjectName(_fromUtf8("horizontalSplitter"))
+ self.horizontalSplitter.setObjectName("horizontalSplitter")
self.verticalSplitter_2 = settingsmixin.SSplitter()
- self.verticalSplitter_2.setObjectName(_fromUtf8("verticalSplitter_2"))
+ self.verticalSplitter_2.setObjectName("verticalSplitter_2")
self.verticalSplitter_2.setOrientation(QtCore.Qt.Vertical)
self.tableWidgetAddressBook = settingsmixin.STableWidget(self.send)
self.tableWidgetAddressBook.setAlternatingRowColors(True)
- self.tableWidgetAddressBook.setSelectionMode(QtGui.QAbstractItemView.ExtendedSelection)
- self.tableWidgetAddressBook.setSelectionBehavior(QtGui.QAbstractItemView.SelectRows)
- self.tableWidgetAddressBook.setObjectName(_fromUtf8("tableWidgetAddressBook"))
+ self.tableWidgetAddressBook.setSelectionMode(QtWidgets.QAbstractItemView.ExtendedSelection)
+ self.tableWidgetAddressBook.setSelectionBehavior(QtWidgets.QAbstractItemView.SelectRows)
+ self.tableWidgetAddressBook.setObjectName("tableWidgetAddressBook")
self.tableWidgetAddressBook.setColumnCount(2)
self.tableWidgetAddressBook.setRowCount(0)
self.tableWidgetAddressBook.resize(200, self.tableWidgetAddressBook.height())
- item = QtGui.QTableWidgetItem()
+ item = QtWidgets.QTableWidgetItem()
icon3 = QtGui.QIcon()
- icon3.addPixmap(QtGui.QPixmap(_fromUtf8(":/newPrefix/images/addressbook.png")), QtGui.QIcon.Selected, QtGui.QIcon.Off)
+ icon3.addPixmap(QtGui.QPixmap(":/newPrefix/images/addressbook.png"), QtGui.QIcon.Selected, QtGui.QIcon.Off)
item.setIcon(icon3)
self.tableWidgetAddressBook.setHorizontalHeaderItem(0, item)
- item = QtGui.QTableWidgetItem()
+ item = QtWidgets.QTableWidgetItem()
self.tableWidgetAddressBook.setHorizontalHeaderItem(1, item)
self.tableWidgetAddressBook.horizontalHeader().setCascadingSectionResizes(True)
self.tableWidgetAddressBook.horizontalHeader().setDefaultSectionSize(200)
@@ -187,17 +162,17 @@ class Ui_MainWindow(object):
self.tableWidgetAddressBook.verticalHeader().setVisible(False)
self.verticalSplitter_2.addWidget(self.tableWidgetAddressBook)
self.addressBookCompleter = AddressBookCompleter()
- self.addressBookCompleter.setCompletionMode(QtGui.QCompleter.PopupCompletion)
+ self.addressBookCompleter.setCompletionMode(QtWidgets.QCompleter.PopupCompletion)
self.addressBookCompleter.setCaseSensitivity(QtCore.Qt.CaseInsensitive)
- self.addressBookCompleterModel = QtGui.QStringListModel()
+ self.addressBookCompleterModel = QtCore.QStringListModel()
self.addressBookCompleter.setModel(self.addressBookCompleterModel)
- self.pushButtonAddAddressBook = QtGui.QPushButton(self.send)
- self.pushButtonAddAddressBook.setObjectName(_fromUtf8("pushButtonAddAddressBook"))
+ self.pushButtonAddAddressBook = QtWidgets.QPushButton(self.send)
+ self.pushButtonAddAddressBook.setObjectName("pushButtonAddAddressBook")
self.pushButtonAddAddressBook.resize(200, self.pushButtonAddAddressBook.height())
self.verticalSplitter_2.addWidget(self.pushButtonAddAddressBook)
- self.pushButtonFetchNamecoinID = QtGui.QPushButton(self.send)
+ self.pushButtonFetchNamecoinID = QtWidgets.QPushButton(self.send)
self.pushButtonFetchNamecoinID.resize(200, self.pushButtonFetchNamecoinID.height())
- self.pushButtonFetchNamecoinID.setObjectName(_fromUtf8("pushButtonFetchNamecoinID"))
+ self.pushButtonFetchNamecoinID.setObjectName("pushButtonFetchNamecoinID")
self.verticalSplitter_2.addWidget(self.pushButtonFetchNamecoinID)
self.verticalSplitter_2.setStretchFactor(0, 1)
self.verticalSplitter_2.setStretchFactor(1, 0)
@@ -209,45 +184,45 @@ class Ui_MainWindow(object):
self.verticalSplitter_2.handle(2).setEnabled(False)
self.horizontalSplitter.addWidget(self.verticalSplitter_2)
self.verticalSplitter = settingsmixin.SSplitter()
- self.verticalSplitter.setObjectName(_fromUtf8("verticalSplitter"))
+ self.verticalSplitter.setObjectName("verticalSplitter")
self.verticalSplitter.setOrientation(QtCore.Qt.Vertical)
- self.tabWidgetSend = QtGui.QTabWidget(self.send)
- self.tabWidgetSend.setObjectName(_fromUtf8("tabWidgetSend"))
- self.sendDirect = QtGui.QWidget()
- self.sendDirect.setObjectName(_fromUtf8("sendDirect"))
- self.gridLayout_8 = QtGui.QGridLayout(self.sendDirect)
- self.gridLayout_8.setObjectName(_fromUtf8("gridLayout_8"))
+ self.tabWidgetSend = QtWidgets.QTabWidget(self.send)
+ self.tabWidgetSend.setObjectName("tabWidgetSend")
+ self.sendDirect = QtWidgets.QWidget()
+ self.sendDirect.setObjectName("sendDirect")
+ self.gridLayout_8 = QtWidgets.QGridLayout(self.sendDirect)
+ self.gridLayout_8.setObjectName("gridLayout_8")
self.verticalSplitter_5 = settingsmixin.SSplitter()
- self.verticalSplitter_5.setObjectName(_fromUtf8("verticalSplitter_5"))
+ self.verticalSplitter_5.setObjectName("verticalSplitter_5")
self.verticalSplitter_5.setOrientation(QtCore.Qt.Vertical)
- self.gridLayout_2 = QtGui.QGridLayout()
- self.gridLayout_2.setObjectName(_fromUtf8("gridLayout_2"))
- self.label_3 = QtGui.QLabel(self.sendDirect)
- self.label_3.setObjectName(_fromUtf8("label_3"))
+ self.gridLayout_2 = QtWidgets.QGridLayout()
+ self.gridLayout_2.setObjectName("gridLayout_2")
+ self.label_3 = QtWidgets.QLabel(self.sendDirect)
+ self.label_3.setObjectName("label_3")
self.gridLayout_2.addWidget(self.label_3, 2, 0, 1, 1)
- self.label_2 = QtGui.QLabel(self.sendDirect)
- self.label_2.setObjectName(_fromUtf8("label_2"))
+ self.label_2 = QtWidgets.QLabel(self.sendDirect)
+ self.label_2.setObjectName("label_2")
self.gridLayout_2.addWidget(self.label_2, 0, 0, 1, 1)
- self.lineEditSubject = QtGui.QLineEdit(self.sendDirect)
- self.lineEditSubject.setText(_fromUtf8(""))
- self.lineEditSubject.setObjectName(_fromUtf8("lineEditSubject"))
+ self.lineEditSubject = QtWidgets.QLineEdit(self.sendDirect)
+ self.lineEditSubject.setText("")
+ self.lineEditSubject.setObjectName("lineEditSubject")
self.gridLayout_2.addWidget(self.lineEditSubject, 2, 1, 1, 1)
- self.label = QtGui.QLabel(self.sendDirect)
- self.label.setObjectName(_fromUtf8("label"))
+ self.label = QtWidgets.QLabel(self.sendDirect)
+ self.label.setObjectName("label")
self.gridLayout_2.addWidget(self.label, 1, 0, 1, 1)
- self.comboBoxSendFrom = QtGui.QComboBox(self.sendDirect)
+ self.comboBoxSendFrom = QtWidgets.QComboBox(self.sendDirect)
self.comboBoxSendFrom.setMinimumSize(QtCore.QSize(300, 0))
- self.comboBoxSendFrom.setObjectName(_fromUtf8("comboBoxSendFrom"))
+ self.comboBoxSendFrom.setObjectName("comboBoxSendFrom")
self.gridLayout_2.addWidget(self.comboBoxSendFrom, 0, 1, 1, 1)
- self.lineEditTo = QtGui.QLineEdit(self.sendDirect)
- self.lineEditTo.setObjectName(_fromUtf8("lineEditTo"))
+ self.lineEditTo = QtWidgets.QLineEdit(self.sendDirect)
+ self.lineEditTo.setObjectName("lineEditTo")
self.gridLayout_2.addWidget(self.lineEditTo, 1, 1, 1, 1)
self.lineEditTo.setCompleter(self.addressBookCompleter)
- self.gridLayout_2_Widget = QtGui.QWidget()
+ self.gridLayout_2_Widget = QtWidgets.QWidget()
self.gridLayout_2_Widget.setLayout(self.gridLayout_2)
self.verticalSplitter_5.addWidget(self.gridLayout_2_Widget)
self.textEditMessage = MessageCompose(self.sendDirect)
- self.textEditMessage.setObjectName(_fromUtf8("textEditMessage"))
+ self.textEditMessage.setObjectName("textEditMessage")
self.verticalSplitter_5.addWidget(self.textEditMessage)
self.verticalSplitter_5.setStretchFactor(0, 0)
self.verticalSplitter_5.setStretchFactor(1, 1)
@@ -255,35 +230,35 @@ class Ui_MainWindow(object):
self.verticalSplitter_5.setCollapsible(1, False)
self.verticalSplitter_5.handle(1).setEnabled(False)
self.gridLayout_8.addWidget(self.verticalSplitter_5, 0, 0, 1, 1)
- self.tabWidgetSend.addTab(self.sendDirect, _fromUtf8(""))
- self.sendBroadcast = QtGui.QWidget()
- self.sendBroadcast.setObjectName(_fromUtf8("sendBroadcast"))
- self.gridLayout_9 = QtGui.QGridLayout(self.sendBroadcast)
- self.gridLayout_9.setObjectName(_fromUtf8("gridLayout_9"))
+ self.tabWidgetSend.addTab(self.sendDirect, "")
+ self.sendBroadcast = QtWidgets.QWidget()
+ self.sendBroadcast.setObjectName("sendBroadcast")
+ self.gridLayout_9 = QtWidgets.QGridLayout(self.sendBroadcast)
+ self.gridLayout_9.setObjectName("gridLayout_9")
self.verticalSplitter_6 = settingsmixin.SSplitter()
- self.verticalSplitter_6.setObjectName(_fromUtf8("verticalSplitter_6"))
+ self.verticalSplitter_6.setObjectName("verticalSplitter_6")
self.verticalSplitter_6.setOrientation(QtCore.Qt.Vertical)
- self.gridLayout_5 = QtGui.QGridLayout()
- self.gridLayout_5.setObjectName(_fromUtf8("gridLayout_5"))
- self.label_8 = QtGui.QLabel(self.sendBroadcast)
- self.label_8.setObjectName(_fromUtf8("label_8"))
+ self.gridLayout_5 = QtWidgets.QGridLayout()
+ self.gridLayout_5.setObjectName("gridLayout_5")
+ self.label_8 = QtWidgets.QLabel(self.sendBroadcast)
+ self.label_8.setObjectName("label_8")
self.gridLayout_5.addWidget(self.label_8, 0, 0, 1, 1)
- self.lineEditSubjectBroadcast = QtGui.QLineEdit(self.sendBroadcast)
- self.lineEditSubjectBroadcast.setText(_fromUtf8(""))
- self.lineEditSubjectBroadcast.setObjectName(_fromUtf8("lineEditSubjectBroadcast"))
+ self.lineEditSubjectBroadcast = QtWidgets.QLineEdit(self.sendBroadcast)
+ self.lineEditSubjectBroadcast.setText("")
+ self.lineEditSubjectBroadcast.setObjectName("lineEditSubjectBroadcast")
self.gridLayout_5.addWidget(self.lineEditSubjectBroadcast, 1, 1, 1, 1)
- self.label_7 = QtGui.QLabel(self.sendBroadcast)
- self.label_7.setObjectName(_fromUtf8("label_7"))
+ self.label_7 = QtWidgets.QLabel(self.sendBroadcast)
+ self.label_7.setObjectName("label_7")
self.gridLayout_5.addWidget(self.label_7, 1, 0, 1, 1)
- self.comboBoxSendFromBroadcast = QtGui.QComboBox(self.sendBroadcast)
+ self.comboBoxSendFromBroadcast = QtWidgets.QComboBox(self.sendBroadcast)
self.comboBoxSendFromBroadcast.setMinimumSize(QtCore.QSize(300, 0))
- self.comboBoxSendFromBroadcast.setObjectName(_fromUtf8("comboBoxSendFromBroadcast"))
+ self.comboBoxSendFromBroadcast.setObjectName("comboBoxSendFromBroadcast")
self.gridLayout_5.addWidget(self.comboBoxSendFromBroadcast, 0, 1, 1, 1)
- self.gridLayout_5_Widget = QtGui.QWidget()
+ self.gridLayout_5_Widget = QtWidgets.QWidget()
self.gridLayout_5_Widget.setLayout(self.gridLayout_5)
self.verticalSplitter_6.addWidget(self.gridLayout_5_Widget)
self.textEditMessageBroadcast = MessageCompose(self.sendBroadcast)
- self.textEditMessageBroadcast.setObjectName(_fromUtf8("textEditMessageBroadcast"))
+ self.textEditMessageBroadcast.setObjectName("textEditMessageBroadcast")
self.verticalSplitter_6.addWidget(self.textEditMessageBroadcast)
self.verticalSplitter_6.setStretchFactor(0, 0)
self.verticalSplitter_6.setStretchFactor(1, 1)
@@ -291,15 +266,15 @@ class Ui_MainWindow(object):
self.verticalSplitter_6.setCollapsible(1, False)
self.verticalSplitter_6.handle(1).setEnabled(False)
self.gridLayout_9.addWidget(self.verticalSplitter_6, 0, 0, 1, 1)
- self.tabWidgetSend.addTab(self.sendBroadcast, _fromUtf8(""))
+ self.tabWidgetSend.addTab(self.sendBroadcast, "")
self.verticalSplitter.addWidget(self.tabWidgetSend)
- self.tTLContainer = QtGui.QWidget()
- self.tTLContainer.setSizePolicy(QtGui.QSizePolicy.MinimumExpanding, QtGui.QSizePolicy.Fixed)
- self.horizontalLayout_5 = QtGui.QHBoxLayout()
+ self.tTLContainer = QtWidgets.QWidget()
+ self.tTLContainer.setSizePolicy(QtWidgets.QSizePolicy.MinimumExpanding, QtWidgets.QSizePolicy.Fixed)
+ self.horizontalLayout_5 = QtWidgets.QHBoxLayout()
self.tTLContainer.setLayout(self.horizontalLayout_5)
- self.horizontalLayout_5.setObjectName(_fromUtf8("horizontalLayout_5"))
- self.pushButtonTTL = QtGui.QPushButton(self.send)
- sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.MinimumExpanding, QtGui.QSizePolicy.Fixed)
+ self.horizontalLayout_5.setObjectName("horizontalLayout_5")
+ self.pushButtonTTL = QtWidgets.QPushButton(self.send)
+ sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.MinimumExpanding, QtWidgets.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.pushButtonTTL.sizePolicy().hasHeightForWidth())
@@ -319,29 +294,29 @@ class Ui_MainWindow(object):
font.setUnderline(True)
self.pushButtonTTL.setFont(font)
self.pushButtonTTL.setFlat(True)
- self.pushButtonTTL.setObjectName(_fromUtf8("pushButtonTTL"))
+ self.pushButtonTTL.setObjectName("pushButtonTTL")
self.horizontalLayout_5.addWidget(self.pushButtonTTL, 0, QtCore.Qt.AlignRight)
- self.horizontalSliderTTL = QtGui.QSlider(self.send)
+ self.horizontalSliderTTL = QtWidgets.QSlider(self.send)
self.horizontalSliderTTL.setMinimumSize(QtCore.QSize(70, 0))
self.horizontalSliderTTL.setOrientation(QtCore.Qt.Horizontal)
self.horizontalSliderTTL.setInvertedAppearance(False)
self.horizontalSliderTTL.setInvertedControls(False)
- self.horizontalSliderTTL.setObjectName(_fromUtf8("horizontalSliderTTL"))
+ self.horizontalSliderTTL.setObjectName("horizontalSliderTTL")
self.horizontalLayout_5.addWidget(self.horizontalSliderTTL, 0, QtCore.Qt.AlignLeft)
- self.labelHumanFriendlyTTLDescription = QtGui.QLabel(self.send)
- sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.MinimumExpanding, QtGui.QSizePolicy.Fixed)
+ self.labelHumanFriendlyTTLDescription = QtWidgets.QLabel(self.send)
+ sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.MinimumExpanding, QtWidgets.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.labelHumanFriendlyTTLDescription.sizePolicy().hasHeightForWidth())
self.labelHumanFriendlyTTLDescription.setSizePolicy(sizePolicy)
self.labelHumanFriendlyTTLDescription.setMinimumSize(QtCore.QSize(45, 0))
- self.labelHumanFriendlyTTLDescription.setObjectName(_fromUtf8("labelHumanFriendlyTTLDescription"))
+ self.labelHumanFriendlyTTLDescription.setObjectName("labelHumanFriendlyTTLDescription")
self.horizontalLayout_5.addWidget(self.labelHumanFriendlyTTLDescription, 1, QtCore.Qt.AlignLeft)
- self.pushButtonClear = QtGui.QPushButton(self.send)
- self.pushButtonClear.setObjectName(_fromUtf8("pushButtonClear"))
+ self.pushButtonClear = QtWidgets.QPushButton(self.send)
+ self.pushButtonClear.setObjectName("pushButtonClear")
self.horizontalLayout_5.addWidget(self.pushButtonClear, 0, QtCore.Qt.AlignRight)
- self.pushButtonSend = QtGui.QPushButton(self.send)
- self.pushButtonSend.setObjectName(_fromUtf8("pushButtonSend"))
+ self.pushButtonSend = QtWidgets.QPushButton(self.send)
+ self.pushButtonSend.setObjectName("pushButtonSend")
self.horizontalLayout_5.addWidget(self.pushButtonSend, 0, QtCore.Qt.AlignRight)
self.horizontalSliderTTL.setMaximumSize(QtCore.QSize(105, self.pushButtonSend.height()))
self.verticalSplitter.addWidget(self.tTLContainer)
@@ -358,29 +333,29 @@ class Ui_MainWindow(object):
self.horizontalSplitter.setCollapsible(1, False)
self.gridLayout_7.addWidget(self.horizontalSplitter, 0, 0, 1, 1)
icon4 = QtGui.QIcon()
- icon4.addPixmap(QtGui.QPixmap(_fromUtf8(":/newPrefix/images/send.png")), QtGui.QIcon.Normal, QtGui.QIcon.Off)
- self.tabWidget.addTab(self.send, icon4, _fromUtf8(""))
- self.subscriptions = QtGui.QWidget()
- self.subscriptions.setObjectName(_fromUtf8("subscriptions"))
- self.gridLayout_3 = QtGui.QGridLayout(self.subscriptions)
- self.gridLayout_3.setObjectName(_fromUtf8("gridLayout_3"))
+ icon4.addPixmap(QtGui.QPixmap(":/newPrefix/images/send.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off)
+ self.tabWidget.addTab(self.send, icon4, "")
+ self.subscriptions = QtWidgets.QWidget()
+ self.subscriptions.setObjectName("subscriptions")
+ self.gridLayout_3 = QtWidgets.QGridLayout(self.subscriptions)
+ self.gridLayout_3.setObjectName("gridLayout_3")
self.horizontalSplitter_4 = settingsmixin.SSplitter()
- self.horizontalSplitter_4.setObjectName(_fromUtf8("horizontalSplitter_4"))
+ self.horizontalSplitter_4.setObjectName("horizontalSplitter_4")
self.verticalSplitter_3 = settingsmixin.SSplitter()
- self.verticalSplitter_3.setObjectName(_fromUtf8("verticalSplitter_3"))
+ self.verticalSplitter_3.setObjectName("verticalSplitter_3")
self.verticalSplitter_3.setOrientation(QtCore.Qt.Vertical)
self.treeWidgetSubscriptions = settingsmixin.STreeWidget(self.subscriptions)
self.treeWidgetSubscriptions.setAlternatingRowColors(True)
- self.treeWidgetSubscriptions.setSelectionMode(QtGui.QAbstractItemView.SingleSelection)
- self.treeWidgetSubscriptions.setSelectionBehavior(QtGui.QAbstractItemView.SelectRows)
- self.treeWidgetSubscriptions.setObjectName(_fromUtf8("treeWidgetSubscriptions"))
+ self.treeWidgetSubscriptions.setSelectionMode(QtWidgets.QAbstractItemView.SingleSelection)
+ self.treeWidgetSubscriptions.setSelectionBehavior(QtWidgets.QAbstractItemView.SelectRows)
+ self.treeWidgetSubscriptions.setObjectName("treeWidgetSubscriptions")
self.treeWidgetSubscriptions.resize(200, self.treeWidgetSubscriptions.height())
icon5 = QtGui.QIcon()
- icon5.addPixmap(QtGui.QPixmap(_fromUtf8(":/newPrefix/images/subscriptions.png")), QtGui.QIcon.Selected, QtGui.QIcon.Off)
+ icon5.addPixmap(QtGui.QPixmap(":/newPrefix/images/subscriptions.png"), QtGui.QIcon.Selected, QtGui.QIcon.Off)
self.treeWidgetSubscriptions.headerItem().setIcon(0, icon5)
self.verticalSplitter_3.addWidget(self.treeWidgetSubscriptions)
- self.pushButtonAddSubscription = QtGui.QPushButton(self.subscriptions)
- self.pushButtonAddSubscription.setObjectName(_fromUtf8("pushButtonAddSubscription"))
+ self.pushButtonAddSubscription = QtWidgets.QPushButton(self.subscriptions)
+ self.pushButtonAddSubscription.setObjectName("pushButtonAddSubscription")
self.pushButtonAddSubscription.resize(200, self.pushButtonAddSubscription.height())
self.verticalSplitter_3.addWidget(self.pushButtonAddSubscription)
self.verticalSplitter_3.setStretchFactor(0, 1)
@@ -390,42 +365,42 @@ class Ui_MainWindow(object):
self.verticalSplitter_3.handle(1).setEnabled(False)
self.horizontalSplitter_4.addWidget(self.verticalSplitter_3)
self.verticalSplitter_4 = settingsmixin.SSplitter()
- self.verticalSplitter_4.setObjectName(_fromUtf8("verticalSplitter_4"))
+ self.verticalSplitter_4.setObjectName("verticalSplitter_4")
self.verticalSplitter_4.setOrientation(QtCore.Qt.Vertical)
- self.horizontalSplitter_2 = QtGui.QSplitter()
- self.horizontalSplitter_2.setObjectName(_fromUtf8("horizontalSplitter_2"))
- self.inboxSearchLineEditSubscriptions = QtGui.QLineEdit(self.subscriptions)
- self.inboxSearchLineEditSubscriptions.setObjectName(_fromUtf8("inboxSearchLineEditSubscriptions"))
+ self.horizontalSplitter_2 = QtWidgets.QSplitter()
+ self.horizontalSplitter_2.setObjectName("horizontalSplitter_2")
+ self.inboxSearchLineEditSubscriptions = QtWidgets.QLineEdit(self.subscriptions)
+ self.inboxSearchLineEditSubscriptions.setObjectName("inboxSearchLineEditSubscriptions")
self.horizontalSplitter_2.addWidget(self.inboxSearchLineEditSubscriptions)
- self.inboxSearchOptionSubscriptions = QtGui.QComboBox(self.subscriptions)
- self.inboxSearchOptionSubscriptions.setObjectName(_fromUtf8("inboxSearchOptionSubscriptions"))
- self.inboxSearchOptionSubscriptions.addItem(_fromUtf8(""))
- self.inboxSearchOptionSubscriptions.addItem(_fromUtf8(""))
- self.inboxSearchOptionSubscriptions.addItem(_fromUtf8(""))
- self.inboxSearchOptionSubscriptions.addItem(_fromUtf8(""))
- self.inboxSearchOptionSubscriptions.addItem(_fromUtf8(""))
- self.inboxSearchOptionSubscriptions.setSizeAdjustPolicy(QtGui.QComboBox.AdjustToContents)
+ self.inboxSearchOptionSubscriptions = QtWidgets.QComboBox(self.subscriptions)
+ self.inboxSearchOptionSubscriptions.setObjectName("inboxSearchOptionSubscriptions")
+ self.inboxSearchOptionSubscriptions.addItem("")
+ self.inboxSearchOptionSubscriptions.addItem("")
+ self.inboxSearchOptionSubscriptions.addItem("")
+ self.inboxSearchOptionSubscriptions.addItem("")
+ self.inboxSearchOptionSubscriptions.addItem("")
+ self.inboxSearchOptionSubscriptions.setSizeAdjustPolicy(QtWidgets.QComboBox.AdjustToContents)
self.horizontalSplitter_2.addWidget(self.inboxSearchOptionSubscriptions)
self.horizontalSplitter_2.handle(1).setEnabled(False)
self.horizontalSplitter_2.setStretchFactor(0, 1)
self.horizontalSplitter_2.setStretchFactor(1, 0)
self.verticalSplitter_4.addWidget(self.horizontalSplitter_2)
self.tableWidgetInboxSubscriptions = settingsmixin.STableWidget(self.subscriptions)
- self.tableWidgetInboxSubscriptions.setEditTriggers(QtGui.QAbstractItemView.NoEditTriggers)
+ self.tableWidgetInboxSubscriptions.setEditTriggers(QtWidgets.QAbstractItemView.NoEditTriggers)
self.tableWidgetInboxSubscriptions.setAlternatingRowColors(True)
- self.tableWidgetInboxSubscriptions.setSelectionMode(QtGui.QAbstractItemView.ExtendedSelection)
- self.tableWidgetInboxSubscriptions.setSelectionBehavior(QtGui.QAbstractItemView.SelectRows)
+ self.tableWidgetInboxSubscriptions.setSelectionMode(QtWidgets.QAbstractItemView.ExtendedSelection)
+ self.tableWidgetInboxSubscriptions.setSelectionBehavior(QtWidgets.QAbstractItemView.SelectRows)
self.tableWidgetInboxSubscriptions.setWordWrap(False)
- self.tableWidgetInboxSubscriptions.setObjectName(_fromUtf8("tableWidgetInboxSubscriptions"))
+ self.tableWidgetInboxSubscriptions.setObjectName("tableWidgetInboxSubscriptions")
self.tableWidgetInboxSubscriptions.setColumnCount(4)
self.tableWidgetInboxSubscriptions.setRowCount(0)
- item = QtGui.QTableWidgetItem()
+ item = QtWidgets.QTableWidgetItem()
self.tableWidgetInboxSubscriptions.setHorizontalHeaderItem(0, item)
- item = QtGui.QTableWidgetItem()
+ item = QtWidgets.QTableWidgetItem()
self.tableWidgetInboxSubscriptions.setHorizontalHeaderItem(1, item)
- item = QtGui.QTableWidgetItem()
+ item = QtWidgets.QTableWidgetItem()
self.tableWidgetInboxSubscriptions.setHorizontalHeaderItem(2, item)
- item = QtGui.QTableWidgetItem()
+ item = QtWidgets.QTableWidgetItem()
self.tableWidgetInboxSubscriptions.setHorizontalHeaderItem(3, item)
self.tableWidgetInboxSubscriptions.horizontalHeader().setCascadingSectionResizes(True)
self.tableWidgetInboxSubscriptions.horizontalHeader().setDefaultSectionSize(200)
@@ -439,7 +414,7 @@ class Ui_MainWindow(object):
self.textEditInboxMessageSubscriptions = MessageView(self.subscriptions)
self.textEditInboxMessageSubscriptions.setBaseSize(QtCore.QSize(0, 500))
self.textEditInboxMessageSubscriptions.setReadOnly(True)
- self.textEditInboxMessageSubscriptions.setObjectName(_fromUtf8("textEditInboxMessageSubscriptions"))
+ self.textEditInboxMessageSubscriptions.setObjectName("textEditInboxMessageSubscriptions")
self.verticalSplitter_4.addWidget(self.textEditInboxMessageSubscriptions)
self.verticalSplitter_4.setStretchFactor(0, 0)
self.verticalSplitter_4.setStretchFactor(1, 1)
@@ -455,31 +430,31 @@ class Ui_MainWindow(object):
self.horizontalSplitter_4.setCollapsible(1, False)
self.gridLayout_3.addWidget(self.horizontalSplitter_4, 0, 0, 1, 1)
icon6 = QtGui.QIcon()
- icon6.addPixmap(QtGui.QPixmap(_fromUtf8(":/newPrefix/images/subscriptions.png")), QtGui.QIcon.Normal, QtGui.QIcon.Off)
- self.tabWidget.addTab(self.subscriptions, icon6, _fromUtf8(""))
- self.chans = QtGui.QWidget()
- self.chans.setObjectName(_fromUtf8("chans"))
- self.gridLayout_4 = QtGui.QGridLayout(self.chans)
- self.gridLayout_4.setObjectName(_fromUtf8("gridLayout_4"))
+ icon6.addPixmap(QtGui.QPixmap(":/newPrefix/images/subscriptions.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off)
+ self.tabWidget.addTab(self.subscriptions, icon6, "")
+ self.chans = QtWidgets.QWidget()
+ self.chans.setObjectName("chans")
+ self.gridLayout_4 = QtWidgets.QGridLayout(self.chans)
+ self.gridLayout_4.setObjectName("gridLayout_4")
self.horizontalSplitter_7 = settingsmixin.SSplitter()
- self.horizontalSplitter_7.setObjectName(_fromUtf8("horizontalSplitter_7"))
+ self.horizontalSplitter_7.setObjectName("horizontalSplitter_7")
self.verticalSplitter_17 = settingsmixin.SSplitter()
- self.verticalSplitter_17.setObjectName(_fromUtf8("verticalSplitter_17"))
+ self.verticalSplitter_17.setObjectName("verticalSplitter_17")
self.verticalSplitter_17.setOrientation(QtCore.Qt.Vertical)
self.treeWidgetChans = settingsmixin.STreeWidget(self.chans)
- self.treeWidgetChans.setFrameShadow(QtGui.QFrame.Sunken)
+ self.treeWidgetChans.setFrameShadow(QtWidgets.QFrame.Sunken)
self.treeWidgetChans.setLineWidth(1)
self.treeWidgetChans.setAlternatingRowColors(True)
- self.treeWidgetChans.setSelectionMode(QtGui.QAbstractItemView.SingleSelection)
- self.treeWidgetChans.setSelectionBehavior(QtGui.QAbstractItemView.SelectRows)
- self.treeWidgetChans.setObjectName(_fromUtf8("treeWidgetChans"))
+ self.treeWidgetChans.setSelectionMode(QtWidgets.QAbstractItemView.SingleSelection)
+ self.treeWidgetChans.setSelectionBehavior(QtWidgets.QAbstractItemView.SelectRows)
+ self.treeWidgetChans.setObjectName("treeWidgetChans")
self.treeWidgetChans.resize(200, self.treeWidgetChans.height())
icon7 = QtGui.QIcon()
- icon7.addPixmap(QtGui.QPixmap(_fromUtf8(":/newPrefix/images/can-icon-16px.png")), QtGui.QIcon.Selected, QtGui.QIcon.Off)
+ icon7.addPixmap(QtGui.QPixmap(":/newPrefix/images/can-icon-16px.png"), QtGui.QIcon.Selected, QtGui.QIcon.Off)
self.treeWidgetChans.headerItem().setIcon(0, icon7)
self.verticalSplitter_17.addWidget(self.treeWidgetChans)
- self.pushButtonAddChan = QtGui.QPushButton(self.chans)
- self.pushButtonAddChan.setObjectName(_fromUtf8("pushButtonAddChan"))
+ self.pushButtonAddChan = QtWidgets.QPushButton(self.chans)
+ self.pushButtonAddChan.setObjectName("pushButtonAddChan")
self.pushButtonAddChan.resize(200, self.pushButtonAddChan.height())
self.verticalSplitter_17.addWidget(self.pushButtonAddChan)
self.verticalSplitter_17.setStretchFactor(0, 1)
@@ -489,42 +464,42 @@ class Ui_MainWindow(object):
self.verticalSplitter_17.handle(1).setEnabled(False)
self.horizontalSplitter_7.addWidget(self.verticalSplitter_17)
self.verticalSplitter_8 = settingsmixin.SSplitter()
- self.verticalSplitter_8.setObjectName(_fromUtf8("verticalSplitter_8"))
+ self.verticalSplitter_8.setObjectName("verticalSplitter_8")
self.verticalSplitter_8.setOrientation(QtCore.Qt.Vertical)
- self.horizontalSplitter_6 = QtGui.QSplitter()
- self.horizontalSplitter_6.setObjectName(_fromUtf8("horizontalSplitter_6"))
- self.inboxSearchLineEditChans = QtGui.QLineEdit(self.chans)
- self.inboxSearchLineEditChans.setObjectName(_fromUtf8("inboxSearchLineEditChans"))
+ self.horizontalSplitter_6 = QtWidgets.QSplitter()
+ self.horizontalSplitter_6.setObjectName("horizontalSplitter_6")
+ self.inboxSearchLineEditChans = QtWidgets.QLineEdit(self.chans)
+ self.inboxSearchLineEditChans.setObjectName("inboxSearchLineEditChans")
self.horizontalSplitter_6.addWidget(self.inboxSearchLineEditChans)
- self.inboxSearchOptionChans = QtGui.QComboBox(self.chans)
- self.inboxSearchOptionChans.setObjectName(_fromUtf8("inboxSearchOptionChans"))
- self.inboxSearchOptionChans.addItem(_fromUtf8(""))
- self.inboxSearchOptionChans.addItem(_fromUtf8(""))
- self.inboxSearchOptionChans.addItem(_fromUtf8(""))
- self.inboxSearchOptionChans.addItem(_fromUtf8(""))
- self.inboxSearchOptionChans.addItem(_fromUtf8(""))
- self.inboxSearchOptionChans.setSizeAdjustPolicy(QtGui.QComboBox.AdjustToContents)
+ self.inboxSearchOptionChans = QtWidgets.QComboBox(self.chans)
+ self.inboxSearchOptionChans.setObjectName("inboxSearchOptionChans")
+ self.inboxSearchOptionChans.addItem("")
+ self.inboxSearchOptionChans.addItem("")
+ self.inboxSearchOptionChans.addItem("")
+ self.inboxSearchOptionChans.addItem("")
+ self.inboxSearchOptionChans.addItem("")
+ self.inboxSearchOptionChans.setSizeAdjustPolicy(QtWidgets.QComboBox.AdjustToContents)
self.horizontalSplitter_6.addWidget(self.inboxSearchOptionChans)
self.horizontalSplitter_6.handle(1).setEnabled(False)
self.horizontalSplitter_6.setStretchFactor(0, 1)
self.horizontalSplitter_6.setStretchFactor(1, 0)
self.verticalSplitter_8.addWidget(self.horizontalSplitter_6)
self.tableWidgetInboxChans = settingsmixin.STableWidget(self.chans)
- self.tableWidgetInboxChans.setEditTriggers(QtGui.QAbstractItemView.NoEditTriggers)
+ self.tableWidgetInboxChans.setEditTriggers(QtWidgets.QAbstractItemView.NoEditTriggers)
self.tableWidgetInboxChans.setAlternatingRowColors(True)
- self.tableWidgetInboxChans.setSelectionMode(QtGui.QAbstractItemView.ExtendedSelection)
- self.tableWidgetInboxChans.setSelectionBehavior(QtGui.QAbstractItemView.SelectRows)
+ self.tableWidgetInboxChans.setSelectionMode(QtWidgets.QAbstractItemView.ExtendedSelection)
+ self.tableWidgetInboxChans.setSelectionBehavior(QtWidgets.QAbstractItemView.SelectRows)
self.tableWidgetInboxChans.setWordWrap(False)
- self.tableWidgetInboxChans.setObjectName(_fromUtf8("tableWidgetInboxChans"))
+ self.tableWidgetInboxChans.setObjectName("tableWidgetInboxChans")
self.tableWidgetInboxChans.setColumnCount(4)
self.tableWidgetInboxChans.setRowCount(0)
- item = QtGui.QTableWidgetItem()
+ item = QtWidgets.QTableWidgetItem()
self.tableWidgetInboxChans.setHorizontalHeaderItem(0, item)
- item = QtGui.QTableWidgetItem()
+ item = QtWidgets.QTableWidgetItem()
self.tableWidgetInboxChans.setHorizontalHeaderItem(1, item)
- item = QtGui.QTableWidgetItem()
+ item = QtWidgets.QTableWidgetItem()
self.tableWidgetInboxChans.setHorizontalHeaderItem(2, item)
- item = QtGui.QTableWidgetItem()
+ item = QtWidgets.QTableWidgetItem()
self.tableWidgetInboxChans.setHorizontalHeaderItem(3, item)
self.tableWidgetInboxChans.horizontalHeader().setCascadingSectionResizes(True)
self.tableWidgetInboxChans.horizontalHeader().setDefaultSectionSize(200)
@@ -538,7 +513,7 @@ class Ui_MainWindow(object):
self.textEditInboxMessageChans = MessageView(self.chans)
self.textEditInboxMessageChans.setBaseSize(QtCore.QSize(0, 500))
self.textEditInboxMessageChans.setReadOnly(True)
- self.textEditInboxMessageChans.setObjectName(_fromUtf8("textEditInboxMessageChans"))
+ self.textEditInboxMessageChans.setObjectName("textEditInboxMessageChans")
self.verticalSplitter_8.addWidget(self.textEditInboxMessageChans)
self.verticalSplitter_8.setStretchFactor(0, 0)
self.verticalSplitter_8.setStretchFactor(1, 1)
@@ -554,8 +529,8 @@ class Ui_MainWindow(object):
self.horizontalSplitter_7.setCollapsible(1, False)
self.gridLayout_4.addWidget(self.horizontalSplitter_7, 0, 0, 1, 1)
icon8 = QtGui.QIcon()
- icon8.addPixmap(QtGui.QPixmap(_fromUtf8(":/newPrefix/images/can-icon-16px.png")), QtGui.QIcon.Normal, QtGui.QIcon.Off)
- self.tabWidget.addTab(self.chans, icon8, _fromUtf8(""))
+ icon8.addPixmap(QtGui.QPixmap(":/newPrefix/images/can-icon-16px.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off)
+ self.tabWidget.addTab(self.chans, icon8, "")
self.blackwhitelist = Blacklist()
self.tabWidget.addTab(self.blackwhitelist, QtGui.QIcon(":/newPrefix/images/blacklist.png"), "")
# Initialize the Blacklist or Whitelist
@@ -567,62 +542,62 @@ class Ui_MainWindow(object):
self.tabWidget.addTab(self.networkstatus, QtGui.QIcon(":/newPrefix/images/networkstatus.png"), "")
self.gridLayout_10.addWidget(self.tabWidget, 0, 0, 1, 1)
MainWindow.setCentralWidget(self.centralwidget)
- self.menubar = QtGui.QMenuBar(MainWindow)
+ self.menubar = QtWidgets.QMenuBar(MainWindow)
self.menubar.setGeometry(QtCore.QRect(0, 0, 885, 27))
- self.menubar.setObjectName(_fromUtf8("menubar"))
- self.menuFile = QtGui.QMenu(self.menubar)
- self.menuFile.setObjectName(_fromUtf8("menuFile"))
- self.menuSettings = QtGui.QMenu(self.menubar)
- self.menuSettings.setObjectName(_fromUtf8("menuSettings"))
- self.menuHelp = QtGui.QMenu(self.menubar)
- self.menuHelp.setObjectName(_fromUtf8("menuHelp"))
+ self.menubar.setObjectName("menubar")
+ self.menuFile = QtWidgets.QMenu(self.menubar)
+ self.menuFile.setObjectName("menuFile")
+ self.menuSettings = QtWidgets.QMenu(self.menubar)
+ self.menuSettings.setObjectName("menuSettings")
+ self.menuHelp = QtWidgets.QMenu(self.menubar)
+ self.menuHelp.setObjectName("menuHelp")
MainWindow.setMenuBar(self.menubar)
- self.statusbar = QtGui.QStatusBar(MainWindow)
+ self.statusbar = QtWidgets.QStatusBar(MainWindow)
self.statusbar.setMaximumSize(QtCore.QSize(16777215, 22))
- self.statusbar.setObjectName(_fromUtf8("statusbar"))
+ self.statusbar.setObjectName("statusbar")
MainWindow.setStatusBar(self.statusbar)
- self.actionImport_keys = QtGui.QAction(MainWindow)
- self.actionImport_keys.setObjectName(_fromUtf8("actionImport_keys"))
- self.actionManageKeys = QtGui.QAction(MainWindow)
+ self.actionImport_keys = QtWidgets.QAction(MainWindow)
+ self.actionImport_keys.setObjectName("actionImport_keys")
+ self.actionManageKeys = QtWidgets.QAction(MainWindow)
self.actionManageKeys.setCheckable(False)
self.actionManageKeys.setEnabled(True)
- icon = QtGui.QIcon.fromTheme(_fromUtf8("dialog-password"))
+ icon = QtGui.QIcon.fromTheme("dialog-password")
self.actionManageKeys.setIcon(icon)
- self.actionManageKeys.setObjectName(_fromUtf8("actionManageKeys"))
- self.actionNetworkSwitch = QtGui.QAction(MainWindow)
- self.actionNetworkSwitch.setObjectName(_fromUtf8("actionNetworkSwitch"))
- self.actionExit = QtGui.QAction(MainWindow)
- icon = QtGui.QIcon.fromTheme(_fromUtf8("application-exit"))
+ self.actionManageKeys.setObjectName("actionManageKeys")
+ self.actionNetworkSwitch = QtWidgets.QAction(MainWindow)
+ self.actionNetworkSwitch.setObjectName("actionNetworkSwitch")
+ self.actionExit = QtWidgets.QAction(MainWindow)
+ icon = QtGui.QIcon.fromTheme("application-exit")
self.actionExit.setIcon(icon)
- self.actionExit.setObjectName(_fromUtf8("actionExit"))
- self.actionHelp = QtGui.QAction(MainWindow)
- icon = QtGui.QIcon.fromTheme(_fromUtf8("help-contents"))
+ self.actionExit.setObjectName("actionExit")
+ self.actionHelp = QtWidgets.QAction(MainWindow)
+ icon = QtGui.QIcon.fromTheme("help-contents")
self.actionHelp.setIcon(icon)
- self.actionHelp.setObjectName(_fromUtf8("actionHelp"))
- self.actionSupport = QtGui.QAction(MainWindow)
- icon = QtGui.QIcon.fromTheme(_fromUtf8("help-support"))
+ self.actionHelp.setObjectName("actionHelp")
+ self.actionSupport = QtWidgets.QAction(MainWindow)
+ icon = QtGui.QIcon.fromTheme("help-support")
self.actionSupport.setIcon(icon)
- self.actionSupport.setObjectName(_fromUtf8("actionSupport"))
- self.actionAbout = QtGui.QAction(MainWindow)
- icon = QtGui.QIcon.fromTheme(_fromUtf8("help-about"))
+ self.actionSupport.setObjectName("actionSupport")
+ self.actionAbout = QtWidgets.QAction(MainWindow)
+ icon = QtGui.QIcon.fromTheme("help-about")
self.actionAbout.setIcon(icon)
- self.actionAbout.setObjectName(_fromUtf8("actionAbout"))
- self.actionSettings = QtGui.QAction(MainWindow)
- icon = QtGui.QIcon.fromTheme(_fromUtf8("document-properties"))
+ self.actionAbout.setObjectName("actionAbout")
+ self.actionSettings = QtWidgets.QAction(MainWindow)
+ icon = QtGui.QIcon.fromTheme("document-properties")
self.actionSettings.setIcon(icon)
- self.actionSettings.setObjectName(_fromUtf8("actionSettings"))
- self.actionRegenerateDeterministicAddresses = QtGui.QAction(MainWindow)
- icon = QtGui.QIcon.fromTheme(_fromUtf8("view-refresh"))
+ self.actionSettings.setObjectName("actionSettings")
+ self.actionRegenerateDeterministicAddresses = QtWidgets.QAction(MainWindow)
+ icon = QtGui.QIcon.fromTheme("view-refresh")
self.actionRegenerateDeterministicAddresses.setIcon(icon)
- self.actionRegenerateDeterministicAddresses.setObjectName(_fromUtf8("actionRegenerateDeterministicAddresses"))
- self.actionDeleteAllTrashedMessages = QtGui.QAction(MainWindow)
- icon = QtGui.QIcon.fromTheme(_fromUtf8("user-trash"))
+ self.actionRegenerateDeterministicAddresses.setObjectName("actionRegenerateDeterministicAddresses")
+ self.actionDeleteAllTrashedMessages = QtWidgets.QAction(MainWindow)
+ icon = QtGui.QIcon.fromTheme("user-trash")
self.actionDeleteAllTrashedMessages.setIcon(icon)
- self.actionDeleteAllTrashedMessages.setObjectName(_fromUtf8("actionDeleteAllTrashedMessages"))
- self.actionJoinChan = QtGui.QAction(MainWindow)
- icon = QtGui.QIcon.fromTheme(_fromUtf8("contact-new"))
+ self.actionDeleteAllTrashedMessages.setObjectName("actionDeleteAllTrashedMessages")
+ self.actionJoinChan = QtWidgets.QAction(MainWindow)
+ icon = QtGui.QIcon.fromTheme("contact-new")
self.actionJoinChan.setIcon(icon)
- self.actionJoinChan.setObjectName(_fromUtf8("actionJoinChan"))
+ self.actionJoinChan.setObjectName("actionJoinChan")
self.menuFile.addAction(self.actionManageKeys)
self.menuFile.addAction(self.actionDeleteAllTrashedMessages)
self.menuFile.addAction(self.actionRegenerateDeterministicAddresses)
@@ -653,11 +628,11 @@ class Ui_MainWindow(object):
# Popup menu actions container for the Sent page
# pylint: disable=attribute-defined-outside-init
- self.sentContextMenuToolbar = QtGui.QToolBar()
+ self.sentContextMenuToolbar = QtWidgets.QToolBar()
# Popup menu actions container for chans tree
- self.addressContextMenuToolbar = QtGui.QToolBar()
+ self.addressContextMenuToolbar = QtWidgets.QToolBar()
# Popup menu actions container for subscriptions tree
- self.subscriptionsContextMenuToolbar = QtGui.QToolBar()
+ self.subscriptionsContextMenuToolbar = QtWidgets.QToolBar()
def updateNetworkSwitchMenuLabel(self, dontconnect=None):
if dontconnect is None:
@@ -711,7 +686,7 @@ class Ui_MainWindow(object):
hours = int(BMConfigParser().getint('bitmessagesettings', 'ttl')/60/60)
except:
pass
- self.labelHumanFriendlyTTLDescription.setText(_translate("MainWindow", "%n hour(s)", None, QtCore.QCoreApplication.CodecForTr, hours))
+ self.labelHumanFriendlyTTLDescription.setText(_translate("MainWindow", "%n hour(s)", None, hours))
self.pushButtonClear.setText(_translate("MainWindow", "Clear", None))
self.pushButtonSend.setText(_translate("MainWindow", "Send", None))
self.tabWidget.setTabText(self.tabWidget.indexOf(self.send), _translate("MainWindow", "Send", None))
@@ -771,15 +746,13 @@ class Ui_MainWindow(object):
self.actionDeleteAllTrashedMessages.setText(_translate("MainWindow", "Delete all trashed messages", None))
self.actionJoinChan.setText(_translate("MainWindow", "Join / Create chan", None))
-import bitmessage_icons_rc
if __name__ == "__main__":
import sys
-
- app = QtGui.QApplication(sys.argv)
+
+ app = QtWidgets.QApplication(sys.argv)
MainWindow = settingsmixin.SMainWindow()
ui = Ui_MainWindow()
ui.setupUi(MainWindow)
MainWindow.show()
sys.exit(app.exec_())
-
diff --git a/src/bitmessageqt/blacklist.py b/src/bitmessageqt/blacklist.py
index 3897bddc..6db303db 100644
--- a/src/bitmessageqt/blacklist.py
+++ b/src/bitmessageqt/blacklist.py
@@ -1,4 +1,4 @@
-from PyQt4 import QtCore, QtGui
+from qtpy import QtCore, QtGui, QtWidgets
import widgets
from addresses import addBMIfNotPresent
@@ -12,31 +12,31 @@ from uisignaler import UISignaler
from utils import avatarize
-class Blacklist(QtGui.QWidget, RetranslateMixin):
+class Blacklist(QtWidgets.QWidget, RetranslateMixin):
def __init__(self, parent=None):
super(Blacklist, self).__init__(parent)
widgets.load('blacklist.ui', self)
- QtCore.QObject.connect(self.radioButtonBlacklist, QtCore.SIGNAL(
- "clicked()"), self.click_radioButtonBlacklist)
- QtCore.QObject.connect(self.radioButtonWhitelist, QtCore.SIGNAL(
- "clicked()"), self.click_radioButtonWhitelist)
- QtCore.QObject.connect(self.pushButtonAddBlacklist, QtCore.SIGNAL(
- "clicked()"), self.click_pushButtonAddBlacklist)
+ self.radioButtonBlacklist.clicked.connect(
+ self.click_radioButtonBlacklist)
+ self.radioButtonWhitelist.clicked.connect(
+ self.click_radioButtonWhitelist)
+ self.pushButtonAddBlacklist.clicked.connect(
+ self.click_pushButtonAddBlacklist)
self.init_blacklist_popup_menu()
- # Initialize blacklist
- QtCore.QObject.connect(self.tableWidgetBlacklist, QtCore.SIGNAL(
- "itemChanged(QTableWidgetItem *)"), self.tableWidgetBlacklistItemChanged)
+ self.tableWidgetBlacklist.itemChanged.connect(
+ self.tableWidgetBlacklistItemChanged)
# Set the icon sizes for the identicons
- identicon_size = 3*7
- self.tableWidgetBlacklist.setIconSize(QtCore.QSize(identicon_size, identicon_size))
+ identicon_size = 3 * 7
+ self.tableWidgetBlacklist.setIconSize(
+ QtCore.QSize(identicon_size, identicon_size))
self.UISignalThread = UISignaler.get()
- QtCore.QObject.connect(self.UISignalThread, QtCore.SIGNAL(
- "rerenderBlackWhiteList()"), self.rerenderBlackWhiteList)
+ self.UISignalThread.rerenderBlackWhiteList.connect(
+ self.rerenderBlackWhiteList)
def click_radioButtonBlacklist(self):
if BMConfigParser().get('bitmessagesettings', 'blackwhitelist') == 'white':
@@ -69,20 +69,20 @@ class Blacklist(QtGui.QWidget, RetranslateMixin):
sql = '''select * from blacklist where address=?'''
else:
sql = '''select * from whitelist where address=?'''
- queryreturn = sqlQuery(sql,*t)
+ 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 = QtGui.QTableWidgetItem(
+ self.NewBlacklistDialogInstance.lineEditLabel.text())
newItem.setIcon(avatarize(address))
self.tableWidgetBlacklist.setItem(0, 0, newItem)
- newItem = QtGui.QTableWidgetItem(address)
+ newItem = QtWidgets.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)
+ t = (self.NewBlacklistDialogInstance.lineEditLabel.text(), address, True)
if BMConfigParser().get('bitmessagesettings', 'blackwhitelist') == 'black':
sql = '''INSERT INTO blacklist VALUES (?,?,?)'''
else:
@@ -108,17 +108,17 @@ class Blacklist(QtGui.QWidget, RetranslateMixin):
def tableWidgetBlacklistItemChanged(self, item):
if item.column() == 0:
addressitem = self.tableWidgetBlacklist.item(item.row(), 1)
- if isinstance(addressitem, QtGui.QTableWidgetItem):
+ if isinstance(addressitem, QtWidgets.QTableWidgetItem):
if self.radioButtonBlacklist.isChecked():
sqlExecute('''UPDATE blacklist SET label=? WHERE address=?''',
- str(item.text()), str(addressitem.text()))
+ item.text(), str(addressitem.text()))
else:
sqlExecute('''UPDATE whitelist SET label=? WHERE address=?''',
- str(item.text()), str(addressitem.text()))
+ item.text(), str(addressitem.text()))
def init_blacklist_popup_menu(self, connectSignal=True):
# Popup menu for the Blacklist page
- self.blacklistContextMenuToolbar = QtGui.QToolBar()
+ self.blacklistContextMenuToolbar = QtWidgets.QToolBar()
# Actions
self.actionBlacklistNew = self.blacklistContextMenuToolbar.addAction(
_translate(
@@ -143,10 +143,9 @@ class Blacklist(QtGui.QWidget, RetranslateMixin):
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.tableWidgetBlacklist.customContextMenuRequested.connect(
+ self.on_context_menuBlacklist)
+ self.popMenuBlacklist = QtWidgets.QMenu(self)
# self.popMenuBlacklist.addAction( self.actionBlacklistNew )
self.popMenuBlacklist.addAction(self.actionBlacklistDelete)
self.popMenuBlacklist.addSeparator()
@@ -172,16 +171,16 @@ class Blacklist(QtGui.QWidget, RetranslateMixin):
for row in queryreturn:
label, address, enabled = row
self.tableWidgetBlacklist.insertRow(0)
- newItem = QtGui.QTableWidgetItem(unicode(label, 'utf-8'))
+ newItem = QtWidgets.QTableWidgetItem(label)
if not enabled:
- newItem.setTextColor(QtGui.QColor(128, 128, 128))
+ newItem.setForeground(QtGui.QColor(128, 128, 128))
newItem.setIcon(avatarize(address))
self.tableWidgetBlacklist.setItem(0, 0, newItem)
- newItem = QtGui.QTableWidgetItem(address)
+ newItem = QtWidgets.QTableWidgetItem(address)
newItem.setFlags(
QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
if not enabled:
- newItem.setTextColor(QtGui.QColor(128, 128, 128))
+ newItem.setForeground(QtGui.QColor(128, 128, 128))
self.tableWidgetBlacklist.setItem(0, 1, newItem)
self.tableWidgetBlacklist.setSortingEnabled(True)
@@ -192,7 +191,7 @@ class Blacklist(QtGui.QWidget, RetranslateMixin):
def on_action_BlacklistDelete(self):
currentRow = self.tableWidgetBlacklist.currentRow()
labelAtCurrentRow = self.tableWidgetBlacklist.item(
- currentRow, 0).text().toUtf8()
+ currentRow, 0).text()
addressAtCurrentRow = self.tableWidgetBlacklist.item(
currentRow, 1).text()
if BMConfigParser().get('bitmessagesettings', 'blackwhitelist') == 'black':
@@ -209,7 +208,7 @@ class Blacklist(QtGui.QWidget, RetranslateMixin):
currentRow = self.tableWidgetBlacklist.currentRow()
addressAtCurrentRow = self.tableWidgetBlacklist.item(
currentRow, 1).text()
- clipboard = QtGui.QApplication.clipboard()
+ clipboard = QtWidgets.QApplication.clipboard()
clipboard.setText(str(addressAtCurrentRow))
def on_context_menuBlacklist(self, point):
@@ -220,11 +219,12 @@ class Blacklist(QtGui.QWidget, RetranslateMixin):
currentRow = self.tableWidgetBlacklist.currentRow()
addressAtCurrentRow = self.tableWidgetBlacklist.item(
currentRow, 1).text()
- self.tableWidgetBlacklist.item(
- currentRow, 0).setTextColor(QtGui.QApplication.palette().text().color())
- self.tableWidgetBlacklist.item(
- currentRow, 1).setTextColor(QtGui.QApplication.palette().text().color())
- if BMConfigParser().get('bitmessagesettings', 'blackwhitelist') == 'black':
+ self.tableWidgetBlacklist.item(currentRow, 0).setForeground(
+ QtWidgets.QApplication.palette().text().color())
+ self.tableWidgetBlacklist.item(currentRow, 1).setForeground(
+ QtWidgets.QApplication.palette().text().color())
+ if BMConfigParser().get(
+ 'bitmessagesettings', 'blackwhitelist') == 'black':
sqlExecute(
'''UPDATE blacklist SET enabled=1 WHERE address=?''',
str(addressAtCurrentRow))
@@ -237,11 +237,12 @@ class Blacklist(QtGui.QWidget, RetranslateMixin):
currentRow = self.tableWidgetBlacklist.currentRow()
addressAtCurrentRow = self.tableWidgetBlacklist.item(
currentRow, 1).text()
- self.tableWidgetBlacklist.item(
- currentRow, 0).setTextColor(QtGui.QColor(128, 128, 128))
- self.tableWidgetBlacklist.item(
- currentRow, 1).setTextColor(QtGui.QColor(128, 128, 128))
- if BMConfigParser().get('bitmessagesettings', 'blackwhitelist') == 'black':
+ self.tableWidgetBlacklist.item(currentRow, 0).setForeground(
+ QtGui.QColor(128, 128, 128))
+ self.tableWidgetBlacklist.item(currentRow, 1).setForeground(
+ QtGui.QColor(128, 128, 128))
+ if BMConfigParser().get(
+ 'bitmessagesettings', 'blackwhitelist') == 'black':
sqlExecute(
'''UPDATE blacklist SET enabled=0 WHERE address=?''', str(addressAtCurrentRow))
else:
diff --git a/src/bitmessageqt/dialogs.py b/src/bitmessageqt/dialogs.py
index b4bcd2fd..4774ea8e 100644
--- a/src/bitmessageqt/dialogs.py
+++ b/src/bitmessageqt/dialogs.py
@@ -3,7 +3,7 @@ src/bitmessageqt/dialogs.py
===========================
"""
-from PyQt4 import QtGui
+from qtpy import QtWidgets
import paths
import widgets
@@ -18,7 +18,6 @@ from settings import SettingsDialog
from tr import _translate
from version import softwareVersion
-
__all__ = [
"NewChanDialog", "AddAddressDialog", "NewAddressDialog",
"NewSubscriptionDialog", "RegenerateAddressesDialog",
@@ -27,7 +26,7 @@ __all__ = [
]
-class AboutDialog(QtGui.QDialog, RetranslateMixin):
+class AboutDialog(QtWidgets.QDialog, RetranslateMixin):
"""The `About` dialog"""
def __init__(self, parent=None):
super(AboutDialog, self).__init__(parent)
@@ -52,10 +51,10 @@ class AboutDialog(QtGui.QDialog, RetranslateMixin):
except AttributeError:
pass
- self.setFixedSize(QtGui.QWidget.sizeHint(self))
+ self.setFixedSize(QtWidgets.QWidget.sizeHint(self))
-class IconGlossaryDialog(QtGui.QDialog, RetranslateMixin):
+class IconGlossaryDialog(QtWidgets.QDialog, RetranslateMixin):
"""The `Icon Glossary` dialog, explaining the status icon colors"""
def __init__(self, parent=None, config=None):
super(IconGlossaryDialog, self).__init__(parent)
@@ -66,22 +65,23 @@ class IconGlossaryDialog(QtGui.QDialog, RetranslateMixin):
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))
+ "You are using TCP port {0}."
+ " (This can be changed in the settings)."
+ ).format(config.getint('bitmessagesettings', 'port')))
+ self.setFixedSize(QtWidgets.QWidget.sizeHint(self))
-class HelpDialog(QtGui.QDialog, RetranslateMixin):
+class HelpDialog(QtWidgets.QDialog, RetranslateMixin):
"""The `Help` dialog"""
def __init__(self, parent=None):
super(HelpDialog, self).__init__(parent)
widgets.load('help.ui', self)
- self.setFixedSize(QtGui.QWidget.sizeHint(self))
+ self.setFixedSize(QtWidgets.QWidget.sizeHint(self))
-class ConnectDialog(QtGui.QDialog, RetranslateMixin):
+class ConnectDialog(QtWidgets.QDialog, RetranslateMixin):
"""The `Connect` dialog"""
def __init__(self, parent=None):
super(ConnectDialog, self).__init__(parent)
widgets.load('connect.ui', self)
- self.setFixedSize(QtGui.QWidget.sizeHint(self))
+ self.setFixedSize(QtWidgets.QWidget.sizeHint(self))
diff --git a/src/bitmessageqt/foldertree.py b/src/bitmessageqt/foldertree.py
index 2e7e735f..e2676169 100644
--- a/src/bitmessageqt/foldertree.py
+++ b/src/bitmessageqt/foldertree.py
@@ -6,7 +6,7 @@ src/bitmessageqt/foldertree.py
from cgi import escape
-from PyQt4 import QtCore, QtGui
+from qtpy import QtCore, QtGui, QtWidgets
from bmconfigparser import BMConfigParser
from helper_sql import sqlExecute, sqlQuery
@@ -36,15 +36,16 @@ class AccountMixin(object):
return QtGui.QColor(128, 128, 128)
elif self.type == self.CHAN:
return QtGui.QColor(216, 119, 0)
- elif self.type in [self.MAILINGLIST, self.SUBSCRIPTION]:
+ elif self.type in (self.MAILINGLIST, self.SUBSCRIPTION):
return QtGui.QColor(137, 4, 177)
- return QtGui.QApplication.palette().text().color()
+
+ return QtWidgets.QApplication.palette().text().color()
def folderColor(self):
"""QT UI color for a folder"""
if not self.parent().isEnabled:
return QtGui.QColor(128, 128, 128)
- return QtGui.QApplication.palette().text().color()
+ return QtWidgets.QApplication.palette().text().color()
def accountBrush(self):
"""Account brush (for QT UI)"""
@@ -81,7 +82,7 @@ class AccountMixin(object):
except AttributeError:
pass
self.unreadCount = int(cnt)
- if isinstance(self, QtGui.QTreeWidgetItem):
+ if isinstance(self, QtWidgets.QTreeWidgetItem):
self.emitDataChanged()
def setEnabled(self, enabled):
@@ -95,7 +96,7 @@ class AccountMixin(object):
for i in range(self.childCount()):
if isinstance(self.child(i), Ui_FolderWidget):
self.child(i).setEnabled(enabled)
- if isinstance(self, QtGui.QTreeWidgetItem):
+ if isinstance(self, QtWidgets.QTreeWidgetItem):
self.emitDataChanged()
def setType(self):
@@ -109,7 +110,9 @@ class AccountMixin(object):
elif BMConfigParser().safeGetBoolean(self.address, 'mailinglist'):
self.type = self.MAILINGLIST
elif sqlQuery(
- '''select label from subscriptions where address=?''', self.address):
+ '''select label from subscriptions where address=?''',
+ self.address
+ ):
self.type = AccountMixin.SUBSCRIPTION
else:
self.type = self.NORMAL
@@ -126,27 +129,30 @@ class AccountMixin(object):
BMConfigParser().get(self.address, 'label'), 'utf-8')
except Exception:
queryreturn = sqlQuery(
- '''select label from addressbook where address=?''', self.address)
+ '''select label from addressbook where address=?''',
+ self.address
+ )
elif self.type == AccountMixin.SUBSCRIPTION:
queryreturn = sqlQuery(
- '''select label from subscriptions where address=?''', self.address)
+ '''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 _translate("MainWindow", "All accounts")
return retval or unicode(self.address, 'utf-8')
-class BMTreeWidgetItem(QtGui.QTreeWidgetItem, AccountMixin):
+class BMTreeWidgetItem(QtWidgets.QTreeWidgetItem, AccountMixin):
"""A common abstract class for Tree widget item"""
def __init__(self, parent, pos, address, unreadCount):
- super(QtGui.QTreeWidgetItem, self).__init__()
+ super(QtWidgets.QTreeWidgetItem, self).__init__()
self.setAddress(address)
self.setUnreadCount(unreadCount)
self._setup(parent, pos)
@@ -214,7 +220,7 @@ class Ui_FolderWidget(BMTreeWidgetItem):
return self.folderName < other.folderName
return x >= y if reverse else x < y
- return super(QtGui.QTreeWidgetItem, self).__lt__(other)
+ return super(QtWidgets.QTreeWidgetItem, self).__lt__(other)
class Ui_AddressWidget(BMTreeWidgetItem, SettingsMixin):
@@ -230,8 +236,7 @@ class Ui_AddressWidget(BMTreeWidgetItem, SettingsMixin):
def _getLabel(self):
if self.address is None:
- return unicode(_translate(
- "MainWindow", "All accounts").toUtf8(), 'utf-8', 'ignore')
+ return _translate("MainWindow", "All accounts")
else:
try:
return unicode(
@@ -262,11 +267,7 @@ class Ui_AddressWidget(BMTreeWidgetItem, SettingsMixin):
if role == QtCore.Qt.EditRole \
and self.type != AccountMixin.SUBSCRIPTION:
BMConfigParser().set(
- str(self.address), 'label',
- str(value.toString().toUtf8())
- if isinstance(value, QtCore.QVariant)
- else value.encode('utf-8')
- )
+ str(self.address), 'label', value.encode('utf-8'))
BMConfigParser().save()
return super(Ui_AddressWidget, self).setData(column, role, value)
@@ -293,7 +294,7 @@ class Ui_AddressWidget(BMTreeWidgetItem, SettingsMixin):
if self._getSortRank() < other._getSortRank() else reverse
)
- return super(QtGui.QTreeWidgetItem, self).__lt__(other)
+ return super(Ui_AddressWidget, self).__lt__(other)
class Ui_SubscriptionWidget(Ui_AddressWidget):
@@ -305,7 +306,8 @@ class Ui_SubscriptionWidget(Ui_AddressWidget):
def _getLabel(self):
queryreturn = sqlQuery(
- '''select label from subscriptions where address=?''', self.address)
+ '''select label from subscriptions where address=?''',
+ self.address)
if queryreturn != []:
for row in queryreturn:
retval, = row
@@ -320,22 +322,17 @@ class Ui_SubscriptionWidget(Ui_AddressWidget):
def setData(self, column, role, value):
"""Save subscription label to database"""
if role == QtCore.Qt.EditRole:
- if isinstance(value, QtCore.QVariant):
- label = str(
- value.toString().toUtf8()).decode('utf-8', 'ignore')
- else:
- label = unicode(value, 'utf-8', 'ignore')
sqlExecute(
'''UPDATE subscriptions SET label=? WHERE address=?''',
- label, self.address)
+ value, self.address)
return super(Ui_SubscriptionWidget, self).setData(column, role, value)
-class BMTableWidgetItem(QtGui.QTableWidgetItem, SettingsMixin):
+class BMTableWidgetItem(QtWidgets.QTableWidgetItem, SettingsMixin):
"""A common abstract class for Table widget item"""
def __init__(self, parent=None, label=None, unread=False):
- super(QtGui.QTableWidgetItem, self).__init__()
+ super(QtWidgets.QTableWidgetItem, self).__init__()
self.setLabel(label)
self.setUnread(unread)
self._setup()
@@ -438,7 +435,7 @@ class MessageList_AddressWidget(BMAddressWidget):
def __lt__(self, other):
if isinstance(other, MessageList_AddressWidget):
return self.label.lower() < other.label.lower()
- return super(QtGui.QTableWidgetItem, self).__lt__(other)
+ return super(MessageList_AddressWidget, self).__lt__(other)
class MessageList_SubjectWidget(BMTableWidgetItem):
@@ -459,19 +456,18 @@ class MessageList_SubjectWidget(BMTableWidgetItem):
if role == QtCore.Qt.UserRole:
return self.subject
if role == QtCore.Qt.ToolTipRole:
- return escape(unicode(self.subject, 'utf-8'))
+ return escape(self.subject)
return super(MessageList_SubjectWidget, self).data(role)
# label (or address) alphabetically, disabled at the end
def __lt__(self, other):
if isinstance(other, MessageList_SubjectWidget):
return self.label.lower() < other.label.lower()
- return super(QtGui.QTableWidgetItem, self).__lt__(other)
+ return super(MessageList_SubjectWidget, self).__lt__(other)
class Ui_AddressBookWidgetItem(BMAddressWidget):
"""Addressbook item"""
- # pylint: disable=unused-argument
def __init__(self, label=None, acc_type=AccountMixin.NORMAL):
self.type = acc_type
super(Ui_AddressBookWidgetItem, self).__init__(label=label)
@@ -485,10 +481,7 @@ class Ui_AddressBookWidgetItem(BMAddressWidget):
def setData(self, role, value):
"""Set data"""
if role == QtCore.Qt.EditRole:
- self.label = str(
- value.toString().toUtf8()
- if isinstance(value, QtCore.QVariant) else value
- )
+ self.label = value.encode('utf-8')
if self.type in (
AccountMixin.NORMAL,
AccountMixin.MAILINGLIST, AccountMixin.CHAN):
@@ -497,22 +490,29 @@ class Ui_AddressBookWidgetItem(BMAddressWidget):
BMConfigParser().set(self.address, 'label', self.label)
BMConfigParser().save()
except:
- sqlExecute('''UPDATE addressbook set label=? WHERE address=?''', self.label, self.address)
+ sqlExecute(
+ '''UPDATE addressbook set label=? WHERE address=?''',
+ self.label, self.address
+ )
elif self.type == AccountMixin.SUBSCRIPTION:
- sqlExecute('''UPDATE subscriptions set label=? WHERE address=?''', self.label, self.address)
+ sqlExecute(
+ '''UPDATE subscriptions set label=? WHERE address=?''',
+ self.label, self.address)
else:
pass
return super(Ui_AddressBookWidgetItem, self).setData(role, value)
def __lt__(self, other):
- if isinstance(other, Ui_AddressBookWidgetItem):
- reverse = QtCore.Qt.DescendingOrder == \
- self.tableWidget().horizontalHeader().sortIndicatorOrder()
+ if not isinstance(other, Ui_AddressBookWidgetItem):
+ return super(Ui_AddressBookWidgetItem, self).__lt__(other)
- if self.type == other.type:
- return self.label.lower() < other.label.lower()
- return not reverse if self.type < other.type else reverse
- return super(QtGui.QTableWidgetItem, self).__lt__(other)
+ reverse = QtCore.Qt.DescendingOrder == \
+ self.tableWidget().horizontalHeader().sortIndicatorOrder()
+
+ if self.type == other.type:
+ return self.label.lower() < other.label.lower()
+
+ return not reverse if self.type < other.type else reverse
class Ui_AddressBookWidgetItemLabel(Ui_AddressBookWidgetItem):
@@ -543,9 +543,8 @@ class Ui_AddressBookWidgetItemAddress(Ui_AddressBookWidgetItem):
return super(Ui_AddressBookWidgetItemAddress, self).data(role)
-class AddressBookCompleter(QtGui.QCompleter):
+class AddressBookCompleter(QtWidgets.QCompleter):
"""Addressbook completer"""
-
def __init__(self):
super(AddressBookCompleter, self).__init__()
self.cursorPos = -1
@@ -557,14 +556,12 @@ class AddressBookCompleter(QtGui.QCompleter):
def splitPath(self, path):
"""Split on semicolon"""
- text = unicode(path.toUtf8(), 'utf-8')
- return [text[:self.widget().cursorPosition()].split(';')[-1].strip()]
+ return [path[:self.widget().cursorPosition()].split(';')[-1].strip()]
def pathFromIndex(self, index):
"""Perform autocompletion (reimplemented QCompleter method)"""
- autoString = unicode(
- index.data(QtCore.Qt.EditRole).toString().toUtf8(), 'utf-8')
- text = unicode(self.widget().text().toUtf8(), 'utf-8')
+ autoString = index.data(QtCore.Qt.EditRole).toString()
+ text = self.widget().text()
# If cursor position was saved, restore it, else save it
if self.cursorPos != -1:
@@ -593,7 +590,6 @@ class AddressBookCompleter(QtGui.QCompleter):
# Get string value from before auto finished string is selected
# pre = text[prevDelimiterIndex + 1:curIndex - 1]
-
# Get part of string that occurs AFTER cursor
part2 = text[nextDelimiterIndex:]
diff --git a/src/bitmessageqt/languagebox.py b/src/bitmessageqt/languagebox.py
index 9032cc42..7b0bb002 100644
--- a/src/bitmessageqt/languagebox.py
+++ b/src/bitmessageqt/languagebox.py
@@ -1,35 +1,49 @@
import glob
import os
-from PyQt4 import QtCore, QtGui
-from bmconfigparser import BMConfigParser
+from qtpy import QtCore, QtWidgets
+
import paths
+from bmconfigparser import BMConfigParser
+from tr import _translate
-class LanguageBox(QtGui.QComboBox):
- languageName = {"system": "System Settings", "eo": "Esperanto", "en_pirate": "Pirate English"}
- def __init__(self, parent = None):
- super(QtGui.QComboBox, self).__init__(parent)
+
+class LanguageBox(QtWidgets.QComboBox):
+ languageName = {
+ "system": "System Settings",
+ "eo": "Esperanto",
+ "en_pirate": "Pirate English"
+ }
+
+ def __init__(self, parent=None):
+ super(LanguageBox, self).__init__(parent)
self.populate()
def populate(self):
self.clear()
- localesPath = os.path.join (paths.codePath(), 'translations')
- self.addItem(QtGui.QApplication.translate("settingsDialog", "System Settings", "system"), "system")
+ localesPath = os.path.join(paths.codePath(), 'translations')
+ self.addItem(
+ _translate("settingsDialog", "System Settings", "system"),
+ "system"
+ )
self.setCurrentIndex(0)
- self.setInsertPolicy(QtGui.QComboBox.InsertAlphabetically)
- for translationFile in sorted(glob.glob(os.path.join(localesPath, "bitmessage_*.qm"))):
- localeShort = os.path.split(translationFile)[1].split("_", 1)[1][:-3]
- locale = QtCore.QLocale(QtCore.QString(localeShort))
-
+ self.setInsertPolicy(QtWidgets.QComboBox.InsertAlphabetically)
+ for translationFile in sorted(
+ glob.glob(os.path.join(localesPath, "bitmessage_*.qm"))
+ ):
+ localeShort = \
+ os.path.split(translationFile)[1].split("_", 1)[1][:-3]
+ locale = QtCore.QLocale(localeShort)
if localeShort in LanguageBox.languageName:
- self.addItem(LanguageBox.languageName[localeShort], localeShort)
+ self.addItem(
+ LanguageBox.languageName[localeShort], localeShort)
elif locale.nativeLanguageName() == "":
self.addItem(localeShort, localeShort)
else:
self.addItem(locale.nativeLanguageName(), localeShort)
configuredLocale = BMConfigParser().safeGet(
- 'bitmessagesettings', 'userlocale', "system")
+ 'bitmessagesettings', 'userlocale', 'system')
for i in range(self.count()):
if self.itemData(i) == configuredLocale:
self.setCurrentIndex(i)
diff --git a/src/bitmessageqt/messagecompose.py b/src/bitmessageqt/messagecompose.py
index f7d5dac3..f48d0bee 100644
--- a/src/bitmessageqt/messagecompose.py
+++ b/src/bitmessageqt/messagecompose.py
@@ -1,20 +1,28 @@
-from PyQt4 import QtCore, QtGui
+from qtpy import QtCore, QtWidgets
+from tr import _translate
-class MessageCompose(QtGui.QTextEdit):
-
- def __init__(self, parent = 0):
+
+class MessageCompose(QtWidgets.QTextEdit):
+
+ def __init__(self, parent=None):
super(MessageCompose, self).__init__(parent)
- self.setAcceptRichText(False) # we'll deal with this later when we have a new message format
+ # we'll deal with this later when we have a new message format
+ self.setAcceptRichText(False)
self.defaultFontPointSize = self.currentFont().pointSize()
-
+
def wheelEvent(self, event):
- if (QtGui.QApplication.queryKeyboardModifiers() & QtCore.Qt.ControlModifier) == QtCore.Qt.ControlModifier and event.orientation() == QtCore.Qt.Vertical:
+ if (
+ (QtWidgets.QApplication.queryKeyboardModifiers() &
+ QtCore.Qt.ControlModifier) == QtCore.Qt.ControlModifier and
+ event.orientation() == QtCore.Qt.Vertical
+ ):
if event.delta() > 0:
self.zoomIn(1)
else:
self.zoomOut(1)
zoom = self.currentFont().pointSize() * 100 / self.defaultFontPointSize
- QtGui.QApplication.activeWindow().statusBar().showMessage(QtGui.QApplication.translate("MainWindow", "Zoom level %1%").arg(str(zoom)))
+ QtWidgets.QApplication.activeWindow().statusbar.showMessage(
+ _translate("MainWindow", "Zoom level {0}%").format(zoom))
else:
# in QTextEdit, super does not zoom, only scroll
super(MessageCompose, self).wheelEvent(event)
diff --git a/src/bitmessageqt/messageview.py b/src/bitmessageqt/messageview.py
index 45f3a79a..98a401d4 100644
--- a/src/bitmessageqt/messageview.py
+++ b/src/bitmessageqt/messageview.py
@@ -4,17 +4,18 @@ src/bitmessageqt/messageview.py
"""
-from PyQt4 import QtCore, QtGui
+from qtpy import QtCore, QtGui, QtWidgets
from safehtmlparser import SafeHTMLParser
+from tr import _translate
-class MessageView(QtGui.QTextBrowser):
+class MessageView(QtWidgets.QTextBrowser):
"""Message content viewer class, can switch between plaintext and HTML"""
MODE_PLAIN = 0
MODE_HTML = 1
- def __init__(self, parent=0):
+ def __init__(self, parent=None):
super(MessageView, self).__init__(parent)
self.mode = MessageView.MODE_PLAIN
self.html = None
@@ -36,8 +37,11 @@ class MessageView(QtGui.QTextBrowser):
def mousePressEvent(self, event):
"""Mouse press button event handler"""
- if event.button() == QtCore.Qt.LeftButton and self.html and self.html.has_html and self.cursorForPosition(
- event.pos()).block().blockNumber() == 0:
+ if (
+ event.button() == QtCore.Qt.LeftButton and
+ self.html and self.html.has_html and
+ self.cursorForPosition(event.pos()).block().blockNumber() == 0
+ ):
if self.mode == MessageView.MODE_PLAIN:
self.showHTML()
else:
@@ -49,23 +53,24 @@ class MessageView(QtGui.QTextBrowser):
"""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:
+ if (
+ (QtWidgets.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(
- QtGui.QApplication.translate("MainWindow", "Zoom level %1%").arg(str(zoom)))
+ QtWidgets.QApplication.activeWindow().statusbar.showMessage(
+ _translate("MainWindow", "Zoom level {0}%").format(zoom))
def setWrappingWidth(self, width=None):
"""Set word-wrapping width"""
- self.setLineWrapMode(QtGui.QTextEdit.FixedPixelWidth)
- if width is None:
- width = self.width()
- self.setLineWrapColumnOrWidth(width)
+ self.setLineWrapMode(QtWidgets.QTextEdit.FixedPixelWidth)
+ self.setLineWrapColumnOrWidth(width or self.width())
def confirmURL(self, link):
"""Show a dialog requesting URL opening confirmation"""
if link.scheme() == "mailto":
- window = QtGui.QApplication.activeWindow()
+ window = QtWidgets.QApplication.activeWindow()
window.ui.lineEditTo.setText(link.path())
if link.hasQueryItem("subject"):
window.ui.lineEditSubject.setText(
@@ -80,39 +85,40 @@ class MessageView(QtGui.QTextBrowser):
)
window.ui.textEditMessage.setFocus()
return
- reply = QtGui.QMessageBox.warning(
- self,
- QtGui.QApplication.translate(
+ reply = QtWidgets.QMessageBox.warning(
+ self, _translate("MessageView", "Follow external link"),
+ _translate(
"MessageView",
- "Follow external link"),
- QtGui.QApplication.translate(
- "MessageView",
- "The link \"%1\" will open in a browser. It may be a security risk, it could de-anonymise you"
- " or download malicious data. Are you sure?").arg(unicode(link.toString())),
- QtGui.QMessageBox.Yes,
- QtGui.QMessageBox.No)
- if reply == QtGui.QMessageBox.Yes:
+ "The link \"{0}\" will open in a browser. It may be"
+ " a security risk, it could de-anonymise you or download"
+ " malicious data. Are you sure?"
+ ).format(link.toString()),
+ QtWidgets.QMessageBox.Yes, QtWidgets.QMessageBox.No)
+ if reply == QtWidgets.QMessageBox.Yes:
QtGui.QDesktopServices.openUrl(link)
def loadResource(self, restype, name):
"""
- Callback for loading referenced objects, such as an image. For security reasons at the moment doesn't do
- anything)
+ Callback for loading referenced objects, such as an image.
+ For security reasons at the moment doesn't do anything
"""
pass
def lazyRender(self):
"""
- Partially render a message. This is to avoid UI freezing when loading huge messages. It continues loading as
- you scroll down.
+ Partially render a message. This is to avoid UI freezing when
+ loading huge messages. It continues loading as you scroll down.
"""
if self.rendering:
return
self.rendering = True
position = self.verticalScrollBar().value()
cursor = QtGui.QTextCursor(self.document())
- while self.outpos < len(self.out) and self.verticalScrollBar().value(
- ) >= self.document().size().height() - 2 * self.size().height():
+ while (
+ self.outpos < len(self.out) and
+ self.verticalScrollBar().value() >=
+ self.document().size().height() - 2 * self.size().height()
+ ):
startpos = self.outpos
self.outpos += 10240
# find next end of tag
@@ -120,8 +126,9 @@ class MessageView(QtGui.QTextBrowser):
pos = self.out.find(">", self.outpos)
if pos > self.outpos:
self.outpos = pos + 1
- cursor.movePosition(QtGui.QTextCursor.End, QtGui.QTextCursor.MoveAnchor)
- cursor.insertHtml(QtCore.QString(self.out[startpos:self.outpos]))
+ cursor.movePosition(
+ QtGui.QTextCursor.End, QtGui.QTextCursor.MoveAnchor)
+ cursor.insertHtml(self.out[startpos:self.outpos])
self.verticalScrollBar().setValue(position)
self.rendering = False
@@ -130,9 +137,11 @@ class MessageView(QtGui.QTextBrowser):
self.mode = MessageView.MODE_PLAIN
out = self.html.raw
if self.html.has_html:
- out = "" + unicode(
- QtGui.QApplication.translate(
- "MessageView", "HTML detected, click here to display")) + "
" + out
+ out = (
+ '' +
+ _translate(
+ "MessageView", "HTML detected, click here to display"
+ ) + '
' + out)
self.out = out
self.outpos = 0
self.setHtml("")
@@ -141,10 +150,10 @@ class MessageView(QtGui.QTextBrowser):
def showHTML(self):
"""Render message as HTML"""
self.mode = MessageView.MODE_HTML
- out = self.html.sanitised
- out = "" + unicode(
- QtGui.QApplication.translate("MessageView", "Click here to disable HTML")) + "
" + out
- self.out = out
+ self.out = (
+ '' +
+ _translate("MessageView", "Click here to disable HTML") +
+ '
' + self.html.sanitised)
self.outpos = 0
self.setHtml("")
self.lazyRender()
@@ -152,8 +161,6 @@ class MessageView(QtGui.QTextBrowser):
def setContent(self, data):
"""Set message content from argument"""
self.html = SafeHTMLParser()
- self.html.reset()
- self.html.reset_safe()
self.html.allow_picture = True
self.html.feed(data)
self.html.close()
diff --git a/src/bitmessageqt/migrationwizard.py b/src/bitmessageqt/migrationwizard.py
index 6e80f1dc..ec7899a3 100644
--- a/src/bitmessageqt/migrationwizard.py
+++ b/src/bitmessageqt/migrationwizard.py
@@ -1,42 +1,45 @@
-#!/usr/bin/env python2.7
-from PyQt4 import QtCore, QtGui
+from qtpy import QtGui, QtWidgets
-class MigrationWizardIntroPage(QtGui.QWizardPage):
+
+class MigrationWizardIntroPage(QtWidgets.QWizardPage):
def __init__(self):
- super(QtGui.QWizardPage, self).__init__()
+ super(MigrationWizardIntroPage, self).__init__()
self.setTitle("Migrating configuration")
- label = QtGui.QLabel("This wizard will help you to migrate your configuration. "
+ label = QtWidgets.QLabel("This wizard will help you to migrate your configuration. "
"You can still keep using PyBitMessage once you migrate, the changes are backwards compatible.")
label.setWordWrap(True)
- layout = QtGui.QVBoxLayout()
+ layout = QtWidgets.QVBoxLayout()
layout.addWidget(label)
self.setLayout(layout)
-
+
def nextId(self):
return 1
-
-class MigrationWizardAddressesPage(QtGui.QWizardPage):
+
+class MigrationWizardAddressesPage(QtWidgets.QWizardPage):
def __init__(self, addresses):
- super(QtGui.QWizardPage, self).__init__()
+ super(MigrationWizardAddressesPage, self).__init__()
self.setTitle("Addresses")
- label = QtGui.QLabel("Please select addresses that you are already using with mailchuck. ")
+ label = QtWidgets.QLabel(
+ "Please select addresses that you are already using"
+ " with mailchuck. "
+ )
label.setWordWrap(True)
layout = QtGui.QVBoxLayout()
layout.addWidget(label)
self.setLayout(layout)
-
+
def nextId(self):
return 10
-
-class MigrationWizardGPUPage(QtGui.QWizardPage):
+
+class MigrationWizardGPUPage(QtWidgets.QWizardPage):
def __init__(self):
- super(QtGui.QWizardPage, self).__init__()
+ super(MigrationWizardGPUPage, self).__init__()
self.setTitle("GPU")
label = QtGui.QLabel("Are you using a GPU? ")
@@ -45,30 +48,30 @@ class MigrationWizardGPUPage(QtGui.QWizardPage):
layout = QtGui.QVBoxLayout()
layout.addWidget(label)
self.setLayout(layout)
-
+
def nextId(self):
return 10
-
-class MigrationWizardConclusionPage(QtGui.QWizardPage):
+
+class MigrationWizardConclusionPage(QtWidgets.QWizardPage):
def __init__(self):
- super(QtGui.QWizardPage, self).__init__()
+ super(MigrationWizardConclusionPage, self).__init__()
self.setTitle("All done!")
- label = QtGui.QLabel("You successfully migrated.")
+ label = QtWidgets.QLabel("You successfully migrated.")
label.setWordWrap(True)
- layout = QtGui.QVBoxLayout()
+ layout = QtWidgets.QVBoxLayout()
layout.addWidget(label)
self.setLayout(layout)
-class Ui_MigrationWizard(QtGui.QWizard):
+class Ui_MigrationWizard(QtWidgets.QWizard):
def __init__(self, addresses):
- super(QtGui.QWizard, self).__init__()
+ super(Ui_MigrationWizard, self).__init__()
self.pages = {}
-
+
page = MigrationWizardIntroPage()
self.setPage(0, page)
self.setStartId(0)
@@ -81,4 +84,4 @@ class Ui_MigrationWizard(QtGui.QWizard):
self.setWindowTitle("Migration from PyBitMessage wizard")
self.adjustSize()
- self.show()
\ No newline at end of file
+ self.show()
diff --git a/src/bitmessageqt/networkstatus.py b/src/bitmessageqt/networkstatus.py
index 6fbf5df6..e74d5db8 100644
--- a/src/bitmessageqt/networkstatus.py
+++ b/src/bitmessageqt/networkstatus.py
@@ -6,7 +6,7 @@ src/bitmessageqt/networkstatus.py
import time
-from PyQt4 import QtCore, QtGui
+from qtpy import QtCore, QtGui, QtWidgets
import knownnodes
import l10n
@@ -20,38 +20,40 @@ from tr import _translate
from uisignaler import UISignaler
-class NetworkStatus(QtGui.QWidget, RetranslateMixin):
+class NetworkStatus(QtWidgets.QWidget, RetranslateMixin):
"""Network status tab"""
def __init__(self, parent=None):
super(NetworkStatus, self).__init__(parent)
widgets.load('networkstatus.ui', self)
header = self.tableWidgetConnectionCount.horizontalHeader()
- header.setResizeMode(QtGui.QHeaderView.ResizeToContents)
+ # header.setSectionResizeMode(0, QtWidgets.QHeaderView.Stretch)
+ for column in range(0, 4):
+ header.setSectionResizeMode(
+ column, QtWidgets.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.labelStartupTime.setText(_translate(
+ "networkstatus", "Since startup on {0}").format(
+ 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.UISignalThread.updateNumberOfMessagesProcessed.connect(
+ self.updateNumberOfMessagesProcessed)
+ self.UISignalThread.updateNumberOfPubkeysProcessed.connect(
+ self.updateNumberOfPubkeysProcessed)
+ self.UISignalThread.updateNumberOfBroadcastsProcessed.connect(
+ self.updateNumberOfBroadcastsProcessed)
+ self.UISignalThread.updateNetworkStatusTab.connect(
+ self.updateNetworkStatusTab)
self.timer = QtCore.QTimer()
-
- QtCore.QObject.connect(self.timer, QtCore.SIGNAL("timeout()"), self.runEveryTwoSeconds)
- # pylint: enable=no-member
+ self.timer.timeout.connect(self.runEveryTwoSeconds)
def startUpdate(self):
"""Start a timer to update counters every 2 seconds"""
@@ -63,91 +65,66 @@ class NetworkStatus(QtGui.QWidget, RetranslateMixin):
"""Stop counter update timer"""
self.timer.stop()
- def formatBytes(self, num):
+ @staticmethod
+ def formatBytes(num):
"""Format bytes nicely (SI prefixes)"""
- # pylint: disable=no-self-use
- for x in [
- _translate(
- "networkstatus",
- "byte(s)",
- None,
- QtCore.QCoreApplication.CodecForTr,
- num),
- "kB",
- "MB",
- "GB",
- ]:
+ for x in (
+ _translate("networkstatus", "byte(s)", None, num),
+ "kB", "MB", "GB"
+ ):
if num < 1000.0:
return "%3.0f %s" % (num, x)
num /= 1000.0
- return "%3.0f %s" % (num, 'TB')
+ return "%3.0f %s" % (num, "TB")
- def formatByteRate(self, num):
+ @staticmethod
+ def formatByteRate(num):
"""Format transfer speed in kB/s"""
- # pylint: disable=no-self-use
num /= 1000
return "%4.0f kB" % num
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()))
+ self.labelSyncStatus.setText(_translate(
+ "networkstatus", "Object(s) to be synced: %n", None,
+ network.stats.pendingDownload() + network.stats.pendingUpload()))
def updateNumberOfMessagesProcessed(self):
"""Update the counter for number of processed messages"""
self.updateNumberOfObjectsToBeSynced()
- self.labelMessageCount.setText(
- _translate(
- "networkstatus",
- "Processed %n person-to-person message(s).",
- None,
- QtCore.QCoreApplication.CodecForTr,
- shared.numberOfMessagesProcessed))
+ self.labelMessageCount.setText(_translate(
+ "networkstatus", "Processed %n person-to-person message(s).",
+ None, shared.numberOfMessagesProcessed))
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,
- shared.numberOfBroadcastsProcessed))
+ self.labelBroadcastCount.setText(_translate(
+ "networkstatus", "Processed %n broadcast message(s).", None,
+ shared.numberOfBroadcastsProcessed))
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,
- shared.numberOfPubkeysProcessed))
+ self.labelPubkeyCount.setText(_translate(
+ "networkstatus", "Processed %n public key(s).", None,
+ shared.numberOfPubkeysProcessed))
def updateNumberOfBytes(self):
"""
- This function is run every two seconds, so we divide the rate of bytes
- sent and received by 2.
+ 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())))
+ self.labelBytesRecvCount.setText(_translate(
+ "networkstatus", "Down: {0}/s Total: {1}").format(
+ self.formatByteRate(network.stats.downloadSpeed()),
+ self.formatBytes(network.stats.receivedBytes())
+ ))
+ self.labelBytesSentCount.setText(_translate(
+ "networkstatus", "Up: {0}/s Total: {1}").format(
+ self.formatByteRate(network.stats.uploadSpeed()),
+ self.formatBytes(network.stats.sentBytes())
+ ))
def updateNetworkStatusTab(self, outbound, add, destination):
"""Add or remove an entry to the list of connected peers"""
@@ -174,72 +151,75 @@ class NetworkStatus(QtGui.QWidget, RetranslateMixin):
if add:
self.tableWidgetConnectionCount.insertRow(0)
self.tableWidgetConnectionCount.setItem(
- 0, 0,
- QtGui.QTableWidgetItem("%s:%i" % (destination.host, destination.port))
- )
+ 0, 0, QtWidgets.QTableWidgetItem(
+ "%s:%i" % (destination.host, destination.port)))
self.tableWidgetConnectionCount.setItem(
- 0, 2,
- QtGui.QTableWidgetItem("%s" % (c.userAgent))
- )
+ 0, 2, QtWidgets.QTableWidgetItem("%s" % (c.userAgent)))
self.tableWidgetConnectionCount.setItem(
- 0, 3,
- QtGui.QTableWidgetItem("%s" % (c.tlsVersion))
- )
+ 0, 3, QtWidgets.QTableWidgetItem("%s" % (c.tlsVersion)))
self.tableWidgetConnectionCount.setItem(
- 0, 4,
- QtGui.QTableWidgetItem("%s" % (",".join(map(str, c.streams))))
- )
+ 0, 4, QtWidgets.QTableWidgetItem(
+ "%s" % ",".join(map(str, c.streams))))
try:
# .. todo:: FIXME: hard coded stream no
- rating = "%.1f" % (knownnodes.knownNodes[1][destination]['rating'])
+ rating = "%.1f" % knownnodes.knownNodes[1][destination]['rating']
except KeyError:
rating = "-"
self.tableWidgetConnectionCount.setItem(
- 0, 1,
- QtGui.QTableWidgetItem("%s" % (rating))
- )
+ 0, 1, QtWidgets.QTableWidgetItem("%s" % (rating)))
if outbound:
- brush = QtGui.QBrush(QtGui.QColor("yellow"), QtCore.Qt.SolidPattern)
+ brush = QtGui.QBrush(
+ QtGui.QColor("yellow"), QtCore.Qt.SolidPattern)
else:
- brush = QtGui.QBrush(QtGui.QColor("green"), QtCore.Qt.SolidPattern)
+ brush = QtGui.QBrush(
+ QtGui.QColor("green"), QtCore.Qt.SolidPattern)
for j in range(1):
self.tableWidgetConnectionCount.item(0, j).setBackground(brush)
- self.tableWidgetConnectionCount.item(0, 0).setData(QtCore.Qt.UserRole, destination)
- self.tableWidgetConnectionCount.item(0, 1).setData(QtCore.Qt.UserRole, outbound)
+ self.tableWidgetConnectionCount.item(0, 0).setData(
+ QtCore.Qt.UserRole, destination)
+ self.tableWidgetConnectionCount.item(0, 1).setData(
+ QtCore.Qt.UserRole, outbound)
else:
if len(BMConnectionPool().inboundConnections) == 0:
self.window().setStatusIcon('yellow')
for i in range(self.tableWidgetConnectionCount.rowCount()):
- if self.tableWidgetConnectionCount.item(i, 0).data(QtCore.Qt.UserRole).toPyObject() != destination:
+ if self.tableWidgetConnectionCount.item(i, 0).data(
+ QtCore.Qt.UserRole) != destination:
continue
- if self.tableWidgetConnectionCount.item(i, 1).data(QtCore.Qt.UserRole).toPyObject() == outbound:
+ if self.tableWidgetConnectionCount.item(i, 1).data(
+ QtCore.Qt.UserRole) == outbound:
self.tableWidgetConnectionCount.removeRow(i)
break
self.tableWidgetConnectionCount.setUpdatesEnabled(True)
self.tableWidgetConnectionCount.setSortingEnabled(True)
- self.labelTotalConnections.setText(
- _translate(
- "networkstatus", "Total Connections: %1").arg(
- str(self.tableWidgetConnectionCount.rowCount())))
- # 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.
- if self.tableWidgetConnectionCount.rowCount() and shared.statusIconColor == 'red':
- self.window().setStatusIcon('yellow')
- elif self.tableWidgetConnectionCount.rowCount() == 0 and shared.statusIconColor != "red":
+ self.labelTotalConnections.setText(_translate(
+ "networkstatus", "Total Connections: {0}").format(
+ self.tableWidgetConnectionCount.rowCount()
+ ))
+ # 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.
+ if self.tableWidgetConnectionCount.rowCount():
+ if shared.statusIconColor == 'red':
+ self.window().setStatusIcon('yellow')
+ elif shared.statusIconColor != 'red':
self.window().setStatusIcon('red')
# timer driven
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)))
+ self.labelLookupsPerSecond.setText(_translate(
+ "networkstatus", "Inventory lookups per second: {0}").format(
+ Inventory().numberOfInventoryLookupsPerformed / 2
+ ))
Inventory().numberOfInventoryLookupsPerformed = 0
self.updateNumberOfBytes()
self.updateNumberOfObjectsToBeSynced()
def retranslateUi(self):
super(NetworkStatus, self).retranslateUi()
- self.labelStartupTime.setText(_translate("networkstatus", "Since startup on %1").arg(
- l10n.formatTimestamp(self.startup)))
+ self.labelStartupTime.setText(_translate(
+ "networkstatus", "Since startup on {0}").format(
+ l10n.formatTimestamp(self.startup)
+ ))
diff --git a/src/bitmessageqt/newaddressdialog.ui b/src/bitmessageqt/newaddressdialog.ui
index a9eda5c3..0f8c33d7 100644
--- a/src/bitmessageqt/newaddressdialog.ui
+++ b/src/bitmessageqt/newaddressdialog.ui
@@ -375,7 +375,7 @@ The 'Random Number' option is selected by default but deterministic addresses ha
radioButtonDeterministicAddress
toggled(bool)
groupBoxDeterministic
- setShown(bool)
+ setVisible(bool)
92
@@ -391,7 +391,7 @@ The 'Random Number' option is selected by default but deterministic addresses ha
radioButtonRandomAddress
toggled(bool)
groupBox
- setShown(bool)
+ setVisible(bool)
72
diff --git a/src/bitmessageqt/newchandialog.py b/src/bitmessageqt/newchandialog.py
index 8db486c1..a1cb0f56 100644
--- a/src/bitmessageqt/newchandialog.py
+++ b/src/bitmessageqt/newchandialog.py
@@ -4,41 +4,43 @@ src/bitmessageqt/newchandialog.py
"""
-from PyQt4 import QtCore, QtGui
+from qtpy import QtCore, QtWidgets
import widgets
from addresses import addBMIfNotPresent
from addressvalidator import AddressValidator, PassPhraseValidator
-from queues import UISignalQueue, addressGeneratorQueue, apiAddressGeneratorReturnQueue
+from queues import (
+ addressGeneratorQueue, apiAddressGeneratorReturnQueue, UISignalQueue)
from retranslateui import RetranslateMixin
from tr import _translate
from utils import str_chan
-class NewChanDialog(QtGui.QDialog, RetranslateMixin):
+from debug import logger
+
+
+class NewChanDialog(QtWidgets.QDialog, RetranslateMixin):
"""The `New Chan` dialog"""
def __init__(self, parent=None):
super(NewChanDialog, self).__init__(parent)
widgets.load('newchandialog.ui', self)
self.parent = parent
- self.chanAddress.setValidator(
- AddressValidator(
- self.chanAddress,
- self.chanPassPhrase,
- self.validatorFeedback,
- self.buttonBox,
- False))
- self.chanPassPhrase.setValidator(
- PassPhraseValidator(
- self.chanPassPhrase,
- self.chanAddress,
- self.validatorFeedback,
- self.buttonBox,
- False))
+ validator = AddressValidator(
+ self.chanAddress, self.chanPassPhrase,
+ self.validatorFeedback, self.buttonBox, False)
+ try:
+ validator.checkData()
+ except:
+ logger.warning("NewChanDialog.__init__", exc_info=True)
+ # logger.warning("NewChanDialog.__init__, validator.checkData()")
+
+ self.chanAddress.setValidator(validator)
+ self.chanPassPhrase.setValidator(PassPhraseValidator(
+ self.chanPassPhrase, self.chanAddress, self.validatorFeedback,
+ self.buttonBox, False))
self.timer = QtCore.QTimer()
- QtCore.QObject.connect( # pylint: disable=no-member
- self.timer, QtCore.SIGNAL("timeout()"), self.delayedUpdateStatus)
+ self.timer.timeout.connect(self.delayedUpdateStatus)
self.timer.start(500) # milliseconds
self.setAttribute(QtCore.Qt.WA_DeleteOnClose)
self.show()
@@ -52,32 +54,48 @@ class NewChanDialog(QtGui.QDialog, RetranslateMixin):
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))
+ if self.chanAddress.text() == "":
+ addressGeneratorQueue.put((
+ 'createChan', 4, 1,
+ str_chan + ' ' + str(self.chanPassPhrase.text()),
+ self.chanPassPhrase.text(), True
+ ))
else:
- addressGeneratorQueue.put(
- ('joinChan', addBMIfNotPresent(self.chanAddress.text().toUtf8()),
- str_chan + ' ' + str(self.chanPassPhrase.text().toUtf8()),
- self.chanPassPhrase.text().toUtf8(),
- True))
+ addressGeneratorQueue.put((
+ 'joinChan', addBMIfNotPresent(self.chanAddress.text()),
+ str_chan + ' ' + str(self.chanPassPhrase.text()),
+ self.chanPassPhrase.text(), True
+ ))
addressGeneratorReturnValue = apiAddressGeneratorReturnQueue.get(True)
- if addressGeneratorReturnValue and addressGeneratorReturnValue[0] != 'chan name does not match address':
- UISignalQueue.put(('updateStatusBar', _translate(
- "newchandialog", "Successfully created / joined chan %1").arg(unicode(self.chanPassPhrase.text()))))
+ if (len(addressGeneratorReturnValue) > 0 and
+ addressGeneratorReturnValue[0] !=
+ 'chan name does not match address'):
+ UISignalQueue.put((
+ 'updateStatusBar',
+ _translate(
+ "newchandialog",
+ "Successfully created / joined chan {0}"
+ ).format(self.chanPassPhrase.text())
+ ))
self.parent.ui.tabWidget.setCurrentIndex(
self.parent.ui.tabWidget.indexOf(self.parent.ui.chans)
)
- self.done(QtGui.QDialog.Accepted)
+ self.done(QtWidgets.QDialog.Accepted)
else:
- UISignalQueue.put(('updateStatusBar', _translate("newchandialog", "Chan creation / joining failed")))
- self.done(QtGui.QDialog.Rejected)
+ UISignalQueue.put((
+ 'updateStatusBar',
+ _translate(
+ "newchandialog", "Chan creation / joining failed")
+ ))
+ self.done(QtWidgets.QDialog.Rejected)
def reject(self):
"""Cancel joining the chan"""
self.timer.stop()
self.hide()
- UISignalQueue.put(('updateStatusBar', _translate("newchandialog", "Chan creation / joining cancelled")))
- self.done(QtGui.QDialog.Rejected)
+ UISignalQueue.put((
+ 'updateStatusBar',
+ _translate(
+ "newchandialog", "Chan creation / joining cancelled")
+ ))
+ self.done(QtWidgets.QDialog.Rejected)
diff --git a/src/bitmessageqt/retranslateui.py b/src/bitmessageqt/retranslateui.py
index e9d5bb3a..706c3e81 100644
--- a/src/bitmessageqt/retranslateui.py
+++ b/src/bitmessageqt/retranslateui.py
@@ -1,18 +1,20 @@
-from os import path
-from PyQt4 import QtGui
-from debug import logger
+from qtpy import QtWidgets
+
import widgets
+
class RetranslateMixin(object):
def retranslateUi(self):
- defaults = QtGui.QWidget()
+ defaults = QtWidgets.QWidget()
widgets.load(self.__class__.__name__.lower() + '.ui', defaults)
for attr, value in defaults.__dict__.iteritems():
setTextMethod = getattr(value, "setText", None)
if callable(setTextMethod):
getattr(self, attr).setText(getattr(defaults, attr).text())
- elif isinstance(value, QtGui.QTableWidget):
- for i in range (value.columnCount()):
- getattr(self, attr).horizontalHeaderItem(i).setText(getattr(defaults, attr).horizontalHeaderItem(i).text())
- for i in range (value.rowCount()):
- getattr(self, attr).verticalHeaderItem(i).setText(getattr(defaults, attr).verticalHeaderItem(i).text())
+ elif isinstance(value, QtWidgets.QTableWidget):
+ for i in range(value.columnCount()):
+ getattr(self, attr).horizontalHeaderItem(i).setText(
+ getattr(defaults, attr).horizontalHeaderItem(i).text())
+ for i in range(value.rowCount()):
+ getattr(self, attr).verticalHeaderItem(i).setText(
+ getattr(defaults, attr).verticalHeaderItem(i).text())
diff --git a/src/bitmessageqt/settings.py b/src/bitmessageqt/settings.py
index 982328cc..bc5a8e61 100644
--- a/src/bitmessageqt/settings.py
+++ b/src/bitmessageqt/settings.py
@@ -1,7 +1,7 @@
import os
import sys
-from PyQt4 import QtCore, QtGui
+from qtpy import QtCore, QtGui, QtWidgets
import debug
import defaults
@@ -20,7 +20,7 @@ from network.asyncore_pollchoose import set_rates
from tr import _translate
-class SettingsDialog(QtGui.QDialog):
+class SettingsDialog(QtWidgets.QDialog):
"""The "Settings" dialog"""
def __init__(self, parent=None, firstrun=False):
super(SettingsDialog, self).__init__(parent)
@@ -42,7 +42,7 @@ class SettingsDialog(QtGui.QDialog):
self.tabWidgetSettings.setCurrentIndex(
self.tabWidgetSettings.indexOf(self.tabNetworkSettings)
)
- QtGui.QWidget.resize(self, QtGui.QWidget.sizeHint(self))
+ QtWidgets.QWidget.resize(self, QtWidgets.QWidget.sizeHint(self))
def adjust_from_config(self, config):
"""Adjust all widgets state according to config settings"""
@@ -351,7 +351,7 @@ class SettingsDialog(QtGui.QDialog):
self.config.set('bitmessagesettings', 'maxuploadrate', str(
int(float(self.lineEditMaxUploadRate.text()))))
except ValueError:
- QtGui.QMessageBox.about(
+ QtWidgets.QMessageBox.about(
self, _translate("MainWindow", "Number needed"),
_translate(
"MainWindow",
@@ -474,7 +474,7 @@ class SettingsDialog(QtGui.QDialog):
if shared.maximumLengthOfTimeToBotherResendingMessages < 432000:
# If the time period is less than 5 hours, we give
# zero values to all fields. No message will be sent again.
- QtGui.QMessageBox.about(
+ QtWidgets.QMessageBox.about(
self,
_translate("MainWindow", "Will not resend ever"),
_translate(
diff --git a/src/bitmessageqt/settingsmixin.py b/src/bitmessageqt/settingsmixin.py
index 3d5999e2..9e53c6fb 100644
--- a/src/bitmessageqt/settingsmixin.py
+++ b/src/bitmessageqt/settingsmixin.py
@@ -1,15 +1,15 @@
-#!/usr/bin/python2.7
"""
src/settingsmixin.py
====================
"""
-from PyQt4 import QtCore, QtGui
+from qtpy import QtCore, QtWidgets
class SettingsMixin(object):
- """Mixin for adding geometry and state saving between restarts."""
+ """Mixin for adding geometry and state saving between restarts"""
+
def warnIfNoObjectName(self):
"""
Handle objects which don't have a name. Currently it ignores them. Objects without a name can't have their
@@ -40,8 +40,9 @@ class SettingsMixin(object):
self.warnIfNoObjectName()
settings = QtCore.QSettings()
try:
- geom = settings.value("/".join([str(self.objectName()), "geometry"]))
- target.restoreGeometry(geom.toByteArray() if hasattr(geom, 'toByteArray') else geom)
+ geom = settings.value(
+ "/".join([str(self.objectName()), "geometry"]))
+ target.restoreGeometry(geom)
except Exception:
pass
@@ -51,13 +52,14 @@ class SettingsMixin(object):
settings = QtCore.QSettings()
try:
state = settings.value("/".join([str(self.objectName()), "state"]))
- target.restoreState(state.toByteArray() if hasattr(state, 'toByteArray') else state)
+ target.restoreState(state)
except Exception:
pass
-class SMainWindow(QtGui.QMainWindow, SettingsMixin):
- """Main window with Settings functionality."""
+class SMainWindow(QtWidgets.QMainWindow, SettingsMixin):
+ """Main window with Settings functionality"""
+
def loadSettings(self):
"""Load main window settings."""
self.readGeometry(self)
@@ -69,9 +71,9 @@ class SMainWindow(QtGui.QMainWindow, SettingsMixin):
self.writeGeometry(self)
-class STableWidget(QtGui.QTableWidget, SettingsMixin):
+class STableWidget(QtWidgets.QTableWidget, SettingsMixin):
"""Table widget with Settings functionality"""
- # pylint: disable=too-many-ancestors
+
def loadSettings(self):
"""Load table settings."""
self.readState(self.horizontalHeader())
@@ -81,8 +83,9 @@ class STableWidget(QtGui.QTableWidget, SettingsMixin):
self.writeState(self.horizontalHeader())
-class SSplitter(QtGui.QSplitter, SettingsMixin):
- """Splitter with Settings functionality."""
+class SSplitter(QtWidgets.QSplitter, SettingsMixin):
+ """Splitter with Settings functionality"""
+
def loadSettings(self):
"""Load splitter settings"""
self.readState(self)
@@ -92,17 +95,17 @@ class SSplitter(QtGui.QSplitter, SettingsMixin):
self.writeState(self)
-class STreeWidget(QtGui.QTreeWidget, SettingsMixin):
- """Tree widget with settings functionality."""
- # pylint: disable=too-many-ancestors
+class STreeWidget(QtWidgets.QTreeWidget, SettingsMixin):
+ """Tree widget with settings functionality"""
+
def loadSettings(self):
- """Load tree settings."""
+ """Load tree settings. Unimplemented."""
# recurse children
# self.readState(self)
pass
def saveSettings(self):
- """Save tree settings"""
+ """Save tree settings. Unimplemented."""
# recurse children
# self.writeState(self)
pass
diff --git a/src/bitmessageqt/statusbar.py b/src/bitmessageqt/statusbar.py
index 65a5acfb..477b0d68 100644
--- a/src/bitmessageqt/statusbar.py
+++ b/src/bitmessageqt/statusbar.py
@@ -1,8 +1,8 @@
-from PyQt4 import QtCore, QtGui
-from Queue import Queue
+from qtpy import QtWidgets
from time import time
-class BMStatusBar(QtGui.QStatusBar):
+
+class BMStatusBar(QtWidgets.QStatusBar):
duration = 10000
deleteAfter = 60
diff --git a/src/bitmessageqt/support.py b/src/bitmessageqt/support.py
index 2a1ddb18..effe3554 100644
--- a/src/bitmessageqt/support.py
+++ b/src/bitmessageqt/support.py
@@ -1,23 +1,24 @@
import ctypes
-from PyQt4 import QtCore, QtGui
import ssl
import sys
import time
+from qtpy import QtCore
+
import account
-from bmconfigparser import BMConfigParser
-from debug import logger
import defaults
-from foldertree import AccountMixin
-from helper_sql import *
-from l10n import getTranslationLanguage
-from openclpow import openclAvailable, openclEnabled
+import network.stats
import paths
import proofofwork
-from pyelliptic.openssl import OpenSSL
import queues
-import network.stats
import state
+from bmconfigparser import BMConfigParser
+from foldertree import AccountMixin
+from helper_sql import sqlQuery, sqlExecute
+from l10n import getTranslationLanguage
+from openclpow import openclEnabled
+from pyelliptic.openssl import OpenSSL
+from tr import _translate
from version import softwareVersion
# this is BM support address going to Peter Surda
@@ -53,37 +54,56 @@ UPnP: {}
Connected hosts: {}
'''
+
def checkAddressBook(myapp):
- sqlExecute('''DELETE from addressbook WHERE address=?''', OLD_SUPPORT_ADDRESS)
- queryreturn = sqlQuery('''SELECT * FROM addressbook WHERE address=?''', SUPPORT_ADDRESS)
+ sqlExecute(
+ '''DELETE from addressbook WHERE address=?''', OLD_SUPPORT_ADDRESS)
+ queryreturn = sqlQuery(
+ '''SELECT * FROM addressbook WHERE address=?''', SUPPORT_ADDRESS)
if queryreturn == []:
- sqlExecute('''INSERT INTO addressbook VALUES (?,?)''', str(QtGui.QApplication.translate("Support", SUPPORT_LABEL)), SUPPORT_ADDRESS)
+ sqlExecute(
+ '''INSERT INTO addressbook VALUES (?,?)''',
+ str(_translate("Support", SUPPORT_LABEL)), SUPPORT_ADDRESS
+ )
myapp.rerenderAddressBook()
+
def checkHasNormalAddress():
for address in account.getSortedAccounts():
acct = account.accountClass(address)
- if acct.type == AccountMixin.NORMAL and BMConfigParser().safeGetBoolean(address, 'enabled'):
+ if acct.type == AccountMixin.NORMAL \
+ and BMConfigParser().safeGetBoolean(address, 'enabled'):
return address
return False
+
def createAddressIfNeeded(myapp):
if not checkHasNormalAddress():
- queues.addressGeneratorQueue.put(('createRandomAddress', 4, 1, str(QtGui.QApplication.translate("Support", SUPPORT_MY_LABEL)), 1, "", False, defaults.networkDefaultProofOfWorkNonceTrialsPerByte, defaults.networkDefaultPayloadLengthExtraBytes))
+ queues.addressGeneratorQueue.put((
+ 'createRandomAddress', 4, 1,
+ str(_translate("Support", SUPPORT_MY_LABEL)), 1, "", False,
+ defaults.networkDefaultProofOfWorkNonceTrialsPerByte,
+ defaults.networkDefaultPayloadLengthExtraBytes
+ ))
while state.shutdown == 0 and not checkHasNormalAddress():
time.sleep(.2)
myapp.rerenderComboBoxSendFrom()
return checkHasNormalAddress()
+
def createSupportMessage(myapp):
checkAddressBook(myapp)
address = createAddressIfNeeded(myapp)
if state.shutdown:
return
- myapp.ui.lineEditSubject.setText(str(QtGui.QApplication.translate("Support", SUPPORT_SUBJECT)))
- addrIndex = myapp.ui.comboBoxSendFrom.findData(address, QtCore.Qt.UserRole, QtCore.Qt.MatchFixedString | QtCore.Qt.MatchCaseSensitive)
- if addrIndex == -1: # something is very wrong
+ myapp.ui.lineEditSubject.setText(
+ str(_translate("Support", SUPPORT_SUBJECT)))
+ addrIndex = myapp.ui.comboBoxSendFrom.findData(
+ address, QtCore.Qt.UserRole,
+ QtCore.Qt.MatchFixedString | QtCore.Qt.MatchCaseSensitive
+ )
+ if addrIndex == -1: # something is very wrong
return
myapp.ui.comboBoxSendFrom.setCurrentIndex(addrIndex)
myapp.ui.lineEditTo.setText(SUPPORT_ADDRESS)
@@ -93,10 +113,8 @@ def createSupportMessage(myapp):
if commit:
version += " GIT " + commit
- os = sys.platform
- if os == "win32":
- windowsversion = sys.getwindowsversion()
- os = "Windows " + str(windowsversion[0]) + "." + str(windowsversion[1])
+ if sys.platform == "win32":
+ os = "Windows %s.%s" % sys.getwindowsversion()
else:
try:
from os import uname
@@ -106,13 +124,13 @@ def createSupportMessage(myapp):
pass
architecture = "32" if ctypes.sizeof(ctypes.c_voidp) == 4 else "64"
pythonversion = sys.version
-
+
opensslversion = "%s (Python internal), %s (external for PyElliptic)" % (ssl.OPENSSL_VERSION, OpenSSL._version)
frozen = "N/A"
if paths.frozen:
frozen = paths.frozen
- portablemode = "True" if state.appdata == paths.lookupExeFolder() else "False"
+ portablemode = str(state.appdata == paths.lookupExeFolder())
cpow = "True" if proofofwork.bmpow else "False"
openclpow = str(
BMConfigParser().safeGet('bitmessagesettings', 'opencl')
@@ -123,7 +141,12 @@ def createSupportMessage(myapp):
upnp = BMConfigParser().safeGet('bitmessagesettings', 'upnp', "N/A")
connectedhosts = len(network.stats.connectedHostsList())
- myapp.ui.textEditMessage.setText(str(QtGui.QApplication.translate("Support", SUPPORT_MESSAGE)).format(version, os, architecture, pythonversion, opensslversion, frozen, portablemode, cpow, openclpow, locale, socks, upnp, connectedhosts))
+ myapp.ui.textEditMessage.setText(
+ str(_translate("Support", SUPPORT_MESSAGE)).format(
+ version, os, architecture, pythonversion, opensslversion,
+ frozen, portablemode, cpow, openclpow, locale, socks, upnp,
+ connectedhosts
+ ))
# single msg tab
myapp.ui.tabWidgetSend.setCurrentIndex(
diff --git a/src/bitmessageqt/uisignaler.py b/src/bitmessageqt/uisignaler.py
index 055f9097..060f538e 100644
--- a/src/bitmessageqt/uisignaler.py
+++ b/src/bitmessageqt/uisignaler.py
@@ -1,15 +1,33 @@
-
-from PyQt4.QtCore import QThread, SIGNAL
+from qtpy import QtCore
import sys
import queues
+from network.node import Peer
-class UISignaler(QThread):
+class UISignaler(QtCore.QThread):
_instance = None
- def __init__(self, parent=None):
- QThread.__init__(self, parent)
+ writeNewAddressToTable = QtCore.Signal(str, str, str)
+ updateStatusBar = QtCore.Signal(str)
+ updateSentItemStatusByToAddress = QtCore.Signal(object, str)
+ updateSentItemStatusByAckdata = QtCore.Signal(object, str)
+ displayNewInboxMessage = QtCore.Signal(object, str, str, object, str)
+ displayNewSentMessage = QtCore.Signal(object, str, str, str, object, str)
+ updateNetworkStatusTab = QtCore.Signal(bool, bool, Peer)
+ updateNumberOfMessagesProcessed = QtCore.Signal()
+ updateNumberOfPubkeysProcessed = QtCore.Signal()
+ updateNumberOfBroadcastsProcessed = QtCore.Signal()
+ setStatusIcon = QtCore.Signal(str)
+ changedInboxUnread = QtCore.Signal(str)
+ rerenderMessagelistFromLabels = QtCore.Signal()
+ rerenderMessagelistToLabels = QtCore.Signal()
+ rerenderAddressBook = QtCore.Signal()
+ rerenderSubscriptions = QtCore.Signal()
+ rerenderBlackWhiteList = QtCore.Signal()
+ removeInboxRowByMsgid = QtCore.Signal(str)
+ newVersionAvailable = QtCore.Signal(str)
+ displayAlert = QtCore.Signal(str, str, bool)
@classmethod
def get(cls):
@@ -22,58 +40,58 @@ class UISignaler(QThread):
command, data = queues.UISignalQueue.get()
if command == 'writeNewAddressToTable':
label, address, streamNumber = data
- self.emit(SIGNAL(
- "writeNewAddressToTable(PyQt_PyObject,PyQt_PyObject,PyQt_PyObject)"), label, address, str(streamNumber))
+ self.writeNewAddressToTable.emit(
+ label, address, str(streamNumber))
elif command == 'updateStatusBar':
- self.emit(SIGNAL("updateStatusBar(PyQt_PyObject)"), data)
+ self.updateStatusBar.emit(data)
elif command == 'updateSentItemStatusByToAddress':
toAddress, message = data
- self.emit(SIGNAL(
- "updateSentItemStatusByToAddress(PyQt_PyObject,PyQt_PyObject)"), toAddress, message)
+ self.updateSentItemStatusByToAddress.emit(toAddress, message)
elif command == 'updateSentItemStatusByAckdata':
ackData, message = data
- self.emit(SIGNAL(
- "updateSentItemStatusByAckdata(PyQt_PyObject,PyQt_PyObject)"), ackData, message)
+ self.updateSentItemStatusByAckdata.emit(ackData, message)
elif command == 'displayNewInboxMessage':
inventoryHash, toAddress, fromAddress, subject, body = data
- self.emit(SIGNAL(
- "displayNewInboxMessage(PyQt_PyObject,PyQt_PyObject,PyQt_PyObject,PyQt_PyObject,PyQt_PyObject)"),
- inventoryHash, toAddress, fromAddress, subject, body)
+ self.displayNewInboxMessage.emit(
+ inventoryHash, toAddress, fromAddress,
+ unicode(subject, 'utf-8'), body)
elif command == 'displayNewSentMessage':
toAddress, fromLabel, fromAddress, subject, message, ackdata = data
- self.emit(SIGNAL(
- "displayNewSentMessage(PyQt_PyObject,PyQt_PyObject,PyQt_PyObject,PyQt_PyObject,PyQt_PyObject,PyQt_PyObject)"),
- toAddress, fromLabel, fromAddress, subject, message, ackdata)
+ self.displayNewSentMessage.emit(
+ toAddress, fromLabel, fromAddress,
+ unicode(subject, 'utf-8'), message, ackdata)
elif command == 'updateNetworkStatusTab':
outbound, add, destination = data
- self.emit(SIGNAL("updateNetworkStatusTab(PyQt_PyObject,PyQt_PyObject,PyQt_PyObject)"), outbound, add, destination)
+ self.updateNetworkStatusTab.emit(outbound, add, destination)
elif command == 'updateNumberOfMessagesProcessed':
- self.emit(SIGNAL("updateNumberOfMessagesProcessed()"))
+ self.updateNumberOfMessagesProcessed.emit()
elif command == 'updateNumberOfPubkeysProcessed':
- self.emit(SIGNAL("updateNumberOfPubkeysProcessed()"))
+ self.updateNumberOfPubkeysProcessed.emit()
elif command == 'updateNumberOfBroadcastsProcessed':
- self.emit(SIGNAL("updateNumberOfBroadcastsProcessed()"))
+ self.updateNumberOfBroadcastsProcessed.emit()
elif command == 'setStatusIcon':
- self.emit(SIGNAL("setStatusIcon(PyQt_PyObject)"), data)
+ self.setStatusIcon.emit(data)
elif command == 'changedInboxUnread':
- self.emit(SIGNAL("changedInboxUnread(PyQt_PyObject)"), data)
+ self.changedInboxUnread.emit(data)
elif command == 'rerenderMessagelistFromLabels':
- self.emit(SIGNAL("rerenderMessagelistFromLabels()"))
+ self.rerenderMessagelistFromLabels.emit()
elif command == 'rerenderMessagelistToLabels':
- self.emit(SIGNAL("rerenderMessagelistToLabels()"))
+ self.rerenderMessagelistToLabels.emit()
elif command == 'rerenderAddressBook':
- self.emit(SIGNAL("rerenderAddressBook()"))
+ self.rerenderAddressBook.emit()
elif command == 'rerenderSubscriptions':
- self.emit(SIGNAL("rerenderSubscriptions()"))
+ self.rerenderSubscriptions.emit()
elif command == 'rerenderBlackWhiteList':
- self.emit(SIGNAL("rerenderBlackWhiteList()"))
+ self.rerenderBlackWhiteList.emit()
elif command == 'removeInboxRowByMsgid':
- self.emit(SIGNAL("removeInboxRowByMsgid(PyQt_PyObject)"), data)
+ self.removeInboxRowByMsgid.emit(data)
elif command == 'newVersionAvailable':
- self.emit(SIGNAL("newVersionAvailable(PyQt_PyObject)"), data)
+ self.newVersionAvailable.emit(data)
elif command == 'alert':
title, text, exitAfterUserClicksOk = data
- self.emit(SIGNAL("displayAlert(PyQt_PyObject, PyQt_PyObject, PyQt_PyObject)"), title, text, exitAfterUserClicksOk)
+ self.displayAlert.emit(title, text, exitAfterUserClicksOk)
else:
sys.stderr.write(
- 'Command sent to UISignaler not recognized: %s\n' % command)
+ 'Command sent to UISignaler not recognized: %s\n'
+ % command
+ )
diff --git a/src/bitmessageqt/utils.py b/src/bitmessageqt/utils.py
index 564dbc8b..08ed2924 100644
--- a/src/bitmessageqt/utils.py
+++ b/src/bitmessageqt/utils.py
@@ -1,13 +1,17 @@
-from PyQt4 import QtGui
import hashlib
import os
+
+from qtpy import QtGui
+
+import state
from addresses import addBMIfNotPresent
from bmconfigparser import BMConfigParser
-import state
+
str_broadcast_subscribers = '[Broadcast subscribers]'
str_chan = '[chan]'
+
def identiconize(address):
size = 48
@@ -28,18 +32,26 @@ def identiconize(address):
# the identicons to decrease the risk of attacks where someone creates
# an address to mimic someone else's identicon.
identiconsuffix = BMConfigParser().get('bitmessagesettings', 'identiconsuffix')
- if (identicon_lib[:len('qidenticon')] == 'qidenticon'):
+ data = addBMIfNotPresent(address) + identiconsuffix
+ if identicon_lib[:len('qidenticon')] == 'qidenticon':
# print identicon_lib
# originally by:
# :Author:Shin Adachi
# Licesensed under FreeBSD License.
# stripped from PIL and uses QT instead (by sendiulo, same license)
import qidenticon
- hash = hashlib.md5(addBMIfNotPresent(address)+identiconsuffix).hexdigest()
- use_two_colors = (identicon_lib[:len('qidenticon_two')] == 'qidenticon_two')
- opacity = int(not((identicon_lib == 'qidenticon_x') | (identicon_lib == 'qidenticon_two_x') | (identicon_lib == 'qidenticon_b') | (identicon_lib == 'qidenticon_two_b')))*255
+ icon_hash = hashlib.md5(data).hexdigest()
+ use_two_colors = (
+ identicon_lib[:len('qidenticon_two')] == 'qidenticon_two')
+ opacity = int(not(
+ (identicon_lib == 'qidenticon_x') |
+ (identicon_lib == 'qidenticon_two_x') |
+ (identicon_lib == 'qidenticon_b') |
+ (identicon_lib == 'qidenticon_two_b')
+ )) * 255
penwidth = 0
- image = qidenticon.render_identicon(int(hash, 16), size, use_two_colors, opacity, penwidth)
+ image = qidenticon.render_identicon(
+ int(icon_hash, 16), size, use_two_colors, opacity, penwidth)
# filename = './images/identicons/'+hash+'.png'
# image.save(filename)
idcon = QtGui.QIcon()
@@ -53,7 +65,7 @@ def identiconize(address):
# GPLv3 is a copyleft license that would influence our licensing
# Find the source here: http://boottunes.googlecode.com/svn-history/r302/trunk/src/pydenticon.py
# note that it requires PIL to be installed: http://www.pythonware.com/products/pil/
- idcon_render = Pydenticon(addBMIfNotPresent(address)+identiconsuffix, size*3)
+ idcon_render = Pydenticon(data, size * 3)
rendering = idcon_render._render()
data = rendering.convert("RGBA").tostring("raw", "RGBA")
qim = QtGui.QImage(data, size, size, QtGui.QImage.Format_ARGB32)
@@ -62,6 +74,7 @@ def identiconize(address):
idcon.addPixmap(pix, QtGui.QIcon.Normal, QtGui.QIcon.Off)
return idcon
+
def avatarize(address):
"""
loads a supported image for the given address' hash form 'avatars' folder
@@ -69,19 +82,19 @@ def avatarize(address):
falls back to identiconize(address)
"""
idcon = QtGui.QIcon()
- hash = hashlib.md5(addBMIfNotPresent(address)).hexdigest()
+ icon_hash = hashlib.md5(addBMIfNotPresent(address)).hexdigest()
str_broadcast_subscribers = '[Broadcast subscribers]'
if address == str_broadcast_subscribers:
# don't hash [Broadcast subscribers]
- hash = address
+ icon_hash = address
# http://pyqt.sourceforge.net/Docs/PyQt4/qimagereader.html#supportedImageFormats
# print QImageReader.supportedImageFormats ()
# QImageReader.supportedImageFormats ()
extensions = ['PNG', 'GIF', 'JPG', 'JPEG', 'SVG', 'BMP', 'MNG', 'PBM', 'PGM', 'PPM', 'TIFF', 'XBM', 'XPM', 'TGA']
# try to find a specific avatar
for ext in extensions:
- lower_hash = state.appdata + 'avatars/' + hash + '.' + ext.lower()
- upper_hash = state.appdata + 'avatars/' + hash + '.' + ext.upper()
+ lower_hash = state.appdata + 'avatars/' + icon_hash + '.' + ext.lower()
+ upper_hash = state.appdata + 'avatars/' + icon_hash + '.' + ext.upper()
if os.path.isfile(lower_hash):
# print 'found avatar of ', address
idcon.addFile(lower_hash)
@@ -95,11 +108,9 @@ def avatarize(address):
lower_default = state.appdata + 'avatars/' + 'default.' + ext.lower()
upper_default = state.appdata + 'avatars/' + 'default.' + ext.upper()
if os.path.isfile(lower_default):
- default = lower_default
idcon.addFile(lower_default)
return idcon
elif os.path.isfile(upper_default):
- default = upper_default
idcon.addFile(upper_default)
return idcon
# If no avatar is found
diff --git a/src/bitmessageqt/widgets.py b/src/bitmessageqt/widgets.py
index 8ef807f2..e3232fe6 100644
--- a/src/bitmessageqt/widgets.py
+++ b/src/bitmessageqt/widgets.py
@@ -1,13 +1,15 @@
-from PyQt4 import uic
+from qtpy import uic
import os.path
import paths
-import sys
+
def resource_path(resFile):
baseDir = paths.codePath()
- for subDir in ["ui", "bitmessageqt"]:
- if os.path.isdir(os.path.join(baseDir, subDir)) and os.path.isfile(os.path.join(baseDir, subDir, resFile)):
- return os.path.join(baseDir, subDir, resFile)
+ for subDir in ("ui", "bitmessageqt"):
+ path = os.path.join(baseDir, subDir, resFile)
+ if os.path.isfile(path):
+ return path
+
def load(resFile, widget):
uic.loadUi(resource_path(resFile), widget)
diff --git a/src/class_addressGenerator.py b/src/class_addressGenerator.py
index c7c7e261..27765f18 100644
--- a/src/class_addressGenerator.py
+++ b/src/class_addressGenerator.py
@@ -209,9 +209,10 @@ class addressGenerator(StoppableThread):
queues.workerQueue.put((
'sendOutOrStoreMyV4Pubkey', address))
- elif command == 'createDeterministicAddresses' \
- or command == 'getDeterministicAddress' \
- or command == 'createChan' or command == 'joinChan':
+ elif command in (
+ 'createDeterministicAddresses',
+ 'getDeterministicAddress', 'createChan', 'joinChan'
+ ):
if len(deterministicPassphrase) == 0:
self.logger.warning(
'You are creating deterministic'
@@ -221,9 +222,8 @@ class addressGenerator(StoppableThread):
queues.UISignalQueue.put((
'updateStatusBar',
tr._translate(
- "MainWindow",
- "Generating %1 new addresses."
- ).arg(str(numberOfAddressesToMake))
+ "MainWindow", "Generating {0} new addresses."
+ ).format(str(numberOfAddressesToMake))
))
signingKeyNonce = 0
encryptionKeyNonce = 1
@@ -327,9 +327,9 @@ class addressGenerator(StoppableThread):
'updateStatusBar',
tr._translate(
"MainWindow",
- "%1 is already in 'Your Identities'."
+ "{0} is already in 'Your Identities'."
" Not adding it again."
- ).arg(address)
+ ).format(address)
))
else:
self.logger.debug('label: %s', label)
diff --git a/src/depends.py b/src/depends.py
index 0114ec94..fa626fed 100755
--- a/src/depends.py
+++ b/src/depends.py
@@ -362,7 +362,7 @@ def check_pyqt():
PyQt 4.8 or later.
"""
QtCore = try_import(
- 'PyQt4.QtCore', 'PyBitmessage requires PyQt 4.8 or later and Qt 4.7 or later.')
+ 'qtpy.QtCore', 'PyBitmessage requires PyQt 4.8 or later and Qt 4.7 or later.')
if not QtCore:
return False
diff --git a/src/helper_search.py b/src/helper_search.py
index d6704731..7de9f1e5 100644
--- a/src/helper_search.py
+++ b/src/helper_search.py
@@ -1,29 +1,19 @@
-#!/usr/bin/python2.7
+from helper_sql import sqlQuery
+from tr import _translate
-from helper_sql import *
-try:
- from PyQt4 import QtGui
- haveQt = True
-except ImportError:
- haveQt = False
-
-def search_translate (context, text):
- if haveQt:
- return QtGui.QApplication.translate(context, text)
- else:
- return text.lower()
-
-def search_sql(xAddress = "toaddress", account = None, folder = "inbox", where = None, what = None, unreadOnly = False):
+def search_sql(
+ xAddress="toaddress", account=None, folder="inbox", where=None,
+ what=None, unreadOnly=False):
if what is not None and what != "":
what = "%" + what + "%"
- if where == search_translate("MainWindow", "To"):
+ if where == _translate("MainWindow", "To"):
where = "toaddress"
- elif where == search_translate("MainWindow", "From"):
+ elif where == _translate("MainWindow", "From"):
where = "fromaddress"
- elif where == search_translate("MainWindow", "Subject"):
+ elif where == _translate("MainWindow", "Subject"):
where = "subject"
- elif where == search_translate("MainWindow", "Message"):
+ elif where == _translate("MainWindow", "Message"):
where = "message"
else:
where = "toaddress || fromaddress || subject || message"
@@ -68,18 +58,30 @@ def search_sql(xAddress = "toaddress", account = None, folder = "inbox", where =
sqlStatementBase += " ORDER BY lastactiontime"
return sqlQuery(sqlStatementBase, sqlArguments)
-def check_match(toAddress, fromAddress, subject, message, where = None, what = None):
+
+def check_match(
+ toAddress, fromAddress, subject, message, where=None, what=None):
if what is not None and what != "":
- if where in (search_translate("MainWindow", "To"), search_translate("MainWindow", "All")):
+ if where in (
+ _translate("MainWindow", "To"), _translate("MainWindow", "All")
+ ):
if what.lower() not in toAddress.lower():
return False
- elif where in (search_translate("MainWindow", "From"), search_translate("MainWindow", "All")):
+ elif where in (
+ _translate("MainWindow", "From"), _translate("MainWindow", "All")
+ ):
if what.lower() not in fromAddress.lower():
return False
- elif where in (search_translate("MainWindow", "Subject"), search_translate("MainWindow", "All")):
+ elif where in (
+ _translate("MainWindow", "Subject"),
+ _translate("MainWindow", "All")
+ ):
if what.lower() not in subject.lower():
return False
- elif where in (search_translate("MainWindow", "Message"), search_translate("MainWindow", "All")):
+ elif where in (
+ _translate("MainWindow", "Message"),
+ _translate("MainWindow", "All")
+ ):
if what.lower() not in message.lower():
return False
return True
diff --git a/src/plugins/menu_qrcode.py b/src/plugins/menu_qrcode.py
index 2e65bd88..304567fd 100644
--- a/src/plugins/menu_qrcode.py
+++ b/src/plugins/menu_qrcode.py
@@ -9,7 +9,7 @@ A menu plugin showing QR-Code for bitmessage address in modal dialog.
import urllib
import qrcode
-from PyQt4 import QtGui, QtCore
+from qtpy import QtGui, QtCore, QtWidgets
from pybitmessage.tr import _translate
@@ -41,23 +41,23 @@ class Image(qrcode.image.base.BaseImage): # pylint: disable=abstract-m
QtCore.Qt.black)
-class QRCodeDialog(QtGui.QDialog):
+class QRCodeDialog(QtWidgets.QDialog):
"""The dialog"""
def __init__(self, parent):
super(QRCodeDialog, self).__init__(parent)
- self.image = QtGui.QLabel(self)
- self.label = QtGui.QLabel(self)
+ self.image = QtWidgets.QLabel(self)
+ self.label = QtWidgets.QLabel(self)
font = QtGui.QFont()
font.setBold(True)
font.setWeight(75)
self.label.setFont(font)
self.label.setAlignment(
QtCore.Qt.AlignLeft | QtCore.Qt.AlignVCenter)
- buttonBox = QtGui.QDialogButtonBox(self)
+ buttonBox = QtWidgets.QDialogButtonBox(self)
buttonBox.setOrientation(QtCore.Qt.Horizontal)
- buttonBox.setStandardButtons(QtGui.QDialogButtonBox.Ok)
+ buttonBox.setStandardButtons(QtWidgets.QDialogButtonBox.Ok)
buttonBox.accepted.connect(self.accept)
- layout = QtGui.QVBoxLayout(self)
+ layout = QtWidgets.QVBoxLayout(self)
layout.addWidget(self.image)
layout.addWidget(self.label)
layout.addWidget(buttonBox)
@@ -74,7 +74,7 @@ class QRCodeDialog(QtGui.QDialog):
self.label.setText(text)
self.label.setToolTip(text)
self.label.setFixedWidth(pixmap.width())
- self.setFixedSize(QtGui.QWidget.sizeHint(self))
+ self.setFixedSize(QtWidgets.QWidget.sizeHint(self))
def connect_plugin(form):
diff --git a/src/plugins/plugin.py b/src/plugins/plugin.py
index e671a73f..3a966f75 100644
--- a/src/plugins/plugin.py
+++ b/src/plugins/plugin.py
@@ -23,6 +23,7 @@ def get_plugins(group, point='', name=None, fallback=None):
except (AttributeError,
ImportError,
ValueError,
+ RuntimeError, # PyQt for example
pkg_resources.DistributionNotFound,
pkg_resources.UnknownExtra):
continue
diff --git a/src/qidenticon.py b/src/qidenticon.py
index deafc570..158199a3 100644
--- a/src/qidenticon.py
+++ b/src/qidenticon.py
@@ -10,9 +10,7 @@ Return a PIL Image class instance which have generated identicon image.
``size`` specifies `patch size`. Generated image size is 3 * ``size``.
"""
-from PyQt4 import QtGui
-from PyQt4.QtCore import QSize, QPointF, Qt
-from PyQt4.QtGui import QPixmap, QPainter, QPolygonF
+from qtpy import QtCore, QtGui
class IdenticonRendererBase(object):
@@ -37,10 +35,12 @@ class IdenticonRendererBase(object):
"""
# decode the code
- middle, corner, side, foreColor, secondColor, swap_cross = self.decode(self.code, twoColor)
+ middle, corner, side, foreColor, secondColor, swap_cross = \
+ self.decode(self.code, twoColor)
# make image
- image = QPixmap(QSize(size * 3 + penwidth, size * 3 + penwidth))
+ image = QtGui.QPixmap(
+ QtCore.QSize(size * 3 + penwidth, size * 3 + penwidth))
# fill background
backColor = QtGui.QColor(255, 255, 255, opacity)
@@ -54,7 +54,8 @@ class IdenticonRendererBase(object):
'backColor': backColor}
# middle patch
- image = self.drawPatchQt((1, 1), middle[2], middle[1], middle[0], **kwds)
+ image = self.drawPatchQt(
+ (1, 1), middle[2], middle[1], middle[0], **kwds)
# side patch
kwds['foreColor'] = foreColor
@@ -72,8 +73,9 @@ class IdenticonRendererBase(object):
return image
- def drawPatchQt(self, pos, turn, invert, patch_type, image, size, foreColor,
- backColor, penwidth): # pylint: disable=unused-argument
+ def drawPatchQt(
+ self, pos, turn, invert, patch_type, image, size, foreColor,
+ backColor, penwidth): # pylint: disable=unused-argument
"""
:param size: patch size
"""
@@ -83,47 +85,50 @@ class IdenticonRendererBase(object):
invert = not invert
path = [(0., 0.), (1., 0.), (1., 1.), (0., 1.), (0., 0.)]
- polygon = QPolygonF([QPointF(x * size, y * size) for x, y in path])
+ polygon = QtGui.QPolygonF([
+ QtCore.QPointF(x * size, y * size) for x, y in path])
rot = turn % 4
- rect = [QPointF(0., 0.), QPointF(size, 0.), QPointF(size, size), QPointF(0., size)]
+ rect = [
+ QtCore.QPointF(0., 0.), QtCore.QPointF(size, 0.),
+ QtCore.QPointF(size, size), QtCore.QPointF(0., size)]
rotation = [0, 90, 180, 270]
- nopen = QtGui.QPen(foreColor, Qt.NoPen)
- foreBrush = QtGui.QBrush(foreColor, Qt.SolidPattern)
+ nopen = QtGui.QPen(foreColor, QtCore.Qt.NoPen)
+ foreBrush = QtGui.QBrush(foreColor, QtCore.Qt.SolidPattern)
if penwidth > 0:
pen_color = QtGui.QColor(255, 255, 255)
- pen = QtGui.QPen(pen_color, Qt.SolidPattern)
+ pen = QtGui.QPen(pen_color, QtCore.Qt.SolidPattern)
pen.setWidth(penwidth)
- painter = QPainter()
+ painter = QtGui.QPainter()
painter.begin(image)
painter.setPen(nopen)
- painter.translate(pos[0] * size + penwidth / 2, pos[1] * size + penwidth / 2)
+ painter.translate(
+ pos[0] * size + penwidth / 2, pos[1] * size + penwidth / 2)
painter.translate(rect[rot])
painter.rotate(rotation[rot])
if invert:
# subtract the actual polygon from a rectangle to invert it
- poly_rect = QPolygonF(rect)
+ poly_rect = QtGui.QPolygonF(rect)
polygon = poly_rect.subtracted(polygon)
painter.setBrush(foreBrush)
if penwidth > 0:
# draw the borders
painter.setPen(pen)
- painter.drawPolygon(polygon, Qt.WindingFill)
+ painter.drawPolygon(polygon, QtCore.Qt.WindingFill)
# draw the fill
painter.setPen(nopen)
- painter.drawPolygon(polygon, Qt.WindingFill)
+ painter.drawPolygon(polygon, QtCore.Qt.WindingFill)
painter.end()
return image
- def decode(self, code, twoColor):
+ def decode(self, code):
"""virtual functions"""
-
raise NotImplementedError
@@ -166,7 +171,8 @@ class DonRenderer(IdenticonRendererBase):
[(0, 0), (2, 0), (0, 2)],
# [15] empty:
[]]
- # get the [0] full square, [4] square standing on diagonale, [8] small centered square, or [15] empty tile:
+ # get the [0] full square, [4] square standing on diagonale,
+ # [8] small centered square, or [15] empty tile:
MIDDLE_PATCH_SET = [0, 4, 8, 15]
# modify path set
@@ -215,7 +221,8 @@ class DonRenderer(IdenticonRendererBase):
foreColor = QtGui.QColor(*foreColor)
if twoColor:
- secondColor = (second_blue << 3, second_green << 3, second_red << 3)
+ secondColor = (
+ second_blue << 3, second_green << 3, second_red << 3)
secondColor = QtGui.QColor(*secondColor)
else:
secondColor = foreColor
@@ -226,9 +233,9 @@ class DonRenderer(IdenticonRendererBase):
foreColor, secondColor, swap_cross
-def render_identicon(code, size, twoColor=False, opacity=255, penwidth=0, renderer=None):
+def render_identicon(
+ code, size, twoColor=False, opacity=255, penwidth=0, renderer=None):
"""Render an image"""
-
if not renderer:
renderer = DonRenderer
return renderer(code).render(size, twoColor, opacity, penwidth)
diff --git a/src/tr.py b/src/tr.py
index 87e67219..b66dc033 100644
--- a/src/tr.py
+++ b/src/tr.py
@@ -1,31 +1,7 @@
-"""
-Translating text
-"""
-import os
-
import state
-class translateClass:
- """
- This is used so that the translateText function can be used
- when we are in daemon mode and not using any QT functions.
- """
- # pylint: disable=old-style-class,too-few-public-methods
- def __init__(self, context, text):
- self.context = context
- self.text = text
-
- def arg(self, _):
- """Replace argument placeholders"""
- if '%' in self.text:
- # This doesn't actually do anything with the arguments
- # because we don't have a UI in which to display this information anyway.
- return translateClass(self.context, self.text.replace('%', '', 1))
- return self.text
-
-
-def _translate(context, text, disambiguation=None, encoding=None, n=None): # pylint: disable=unused-argument
+def _translate(context, text, disambiguation=None, n=None):
return translateText(context, text, n)
@@ -36,20 +12,11 @@ def translateText(context, text, n=None):
except AttributeError: # inside the plugin
enableGUI = True
if enableGUI:
- try:
- from PyQt4 import QtCore, QtGui
- except Exception as err:
- print 'PyBitmessage requires PyQt unless you want to run it as a daemon'\
- ' and interact with it using the API.'\
- ' You can download PyQt from http://www.riverbankcomputing.com/software/pyqt/download'\
- ' or by searching Google for \'PyQt Download\'.'\
- ' If you want to run in daemon mode, see https://bitmessage.org/wiki/Daemon'
- print 'Error message:', err
- os._exit(0) # pylint: disable=protected-access
+ from qtpy import QtWidgets, QtCore
if n is None:
- return QtGui.QApplication.translate(context, text)
- return QtGui.QApplication.translate(context, text, None, QtCore.QCoreApplication.CodecForTr, n)
+ return QtWidgets.QApplication.translate(context, text)
+ else:
+ return QtWidgets.QApplication.translate(
+ context, text, None, QtCore.QCoreApplication.CodecForTr, n)
else:
- if '%' in text:
- return translateClass(context, text.replace('%', '', 1))
return text