Minor style changes:

- removed list <-> set conversion in __init__
  - tuples instead of lists if changes aren't needed
  - removed unnecessary variable redefinition in utils
  - rewrote languagebox module a bit
This commit is contained in:
Dmitri Bogomolov 2018-02-26 13:34:10 +02:00
parent d15e614bb1
commit aa333a66a6
Signed by untrusted user: g1itch
GPG Key ID: 720A756F18DEED13
3 changed files with 397 additions and 277 deletions

View File

@ -224,19 +224,19 @@ class MyForm(settingsmixin.SMainWindow):
if connectSignal: if connectSignal:
self.connect(self.ui.tableWidgetInbox, QtCore.SIGNAL( self.connect(self.ui.tableWidgetInbox, QtCore.SIGNAL(
'customContextMenuRequested(const QPoint&)'), 'customContextMenuRequested(const QPoint&)'),
self.on_context_menuInbox) self.on_context_menuInbox)
self.ui.tableWidgetInboxSubscriptions.setContextMenuPolicy( self.ui.tableWidgetInboxSubscriptions.setContextMenuPolicy(
QtCore.Qt.CustomContextMenu) QtCore.Qt.CustomContextMenu)
if connectSignal: if connectSignal:
self.connect(self.ui.tableWidgetInboxSubscriptions, QtCore.SIGNAL( self.connect(self.ui.tableWidgetInboxSubscriptions, QtCore.SIGNAL(
'customContextMenuRequested(const QPoint&)'), 'customContextMenuRequested(const QPoint&)'),
self.on_context_menuInbox) self.on_context_menuInbox)
self.ui.tableWidgetInboxChans.setContextMenuPolicy( self.ui.tableWidgetInboxChans.setContextMenuPolicy(
QtCore.Qt.CustomContextMenu) QtCore.Qt.CustomContextMenu)
if connectSignal: if connectSignal:
self.connect(self.ui.tableWidgetInboxChans, QtCore.SIGNAL( self.connect(self.ui.tableWidgetInboxChans, QtCore.SIGNAL(
'customContextMenuRequested(const QPoint&)'), 'customContextMenuRequested(const QPoint&)'),
self.on_context_menuInbox) self.on_context_menuInbox)
def init_identities_popup_menu(self, connectSignal=True): def init_identities_popup_menu(self, connectSignal=True):
# Popup menu for the Your Identities tab # Popup menu for the Your Identities tab
@ -276,7 +276,7 @@ class MyForm(settingsmixin.SMainWindow):
if connectSignal: if connectSignal:
self.connect(self.ui.treeWidgetYourIdentities, QtCore.SIGNAL( self.connect(self.ui.treeWidgetYourIdentities, QtCore.SIGNAL(
'customContextMenuRequested(const QPoint&)'), 'customContextMenuRequested(const QPoint&)'),
self.on_context_menuYourIdentities) self.on_context_menuYourIdentities)
# load all gui.menu plugins with prefix 'address' # load all gui.menu plugins with prefix 'address'
self.menu_plugins = {'address': []} self.menu_plugins = {'address': []}
@ -326,7 +326,7 @@ class MyForm(settingsmixin.SMainWindow):
if connectSignal: if connectSignal:
self.connect(self.ui.treeWidgetChans, QtCore.SIGNAL( self.connect(self.ui.treeWidgetChans, QtCore.SIGNAL(
'customContextMenuRequested(const QPoint&)'), 'customContextMenuRequested(const QPoint&)'),
self.on_context_menuChan) self.on_context_menuChan)
def init_addressbook_popup_menu(self, connectSignal=True): def init_addressbook_popup_menu(self, connectSignal=True):
# Popup menu for the Address Book page # Popup menu for the Address Book page
@ -363,7 +363,7 @@ class MyForm(settingsmixin.SMainWindow):
if connectSignal: if connectSignal:
self.connect(self.ui.tableWidgetAddressBook, QtCore.SIGNAL( self.connect(self.ui.tableWidgetAddressBook, QtCore.SIGNAL(
'customContextMenuRequested(const QPoint&)'), 'customContextMenuRequested(const QPoint&)'),
self.on_context_menuAddressBook) self.on_context_menuAddressBook)
def init_subscriptions_popup_menu(self, connectSignal=True): def init_subscriptions_popup_menu(self, connectSignal=True):
# Actions # Actions
@ -392,7 +392,7 @@ class MyForm(settingsmixin.SMainWindow):
if connectSignal: if connectSignal:
self.connect(self.ui.treeWidgetSubscriptions, QtCore.SIGNAL( self.connect(self.ui.treeWidgetSubscriptions, QtCore.SIGNAL(
'customContextMenuRequested(const QPoint&)'), 'customContextMenuRequested(const QPoint&)'),
self.on_context_menuSubscriptions) self.on_context_menuSubscriptions)
def init_sent_popup_menu(self, connectSignal=True): def init_sent_popup_menu(self, connectSignal=True):
# Actions # Actions
@ -423,13 +423,13 @@ class MyForm(settingsmixin.SMainWindow):
treeWidget.header().setSortIndicator( treeWidget.header().setSortIndicator(
0, QtCore.Qt.AscendingOrder) 0, QtCore.Qt.AscendingOrder)
# init dictionary # init dictionary
db = getSortedSubscriptions(True) db = getSortedSubscriptions(True)
for address in db: for address in db:
for folder in folders: for folder in folders:
if not folder in db[address]: if folder not in db[address]:
db[address][folder] = {} db[address][folder] = {}
if treeWidget.isSortingEnabled(): if treeWidget.isSortingEnabled():
treeWidget.setSortingEnabled(False) treeWidget.setSortingEnabled(False)
@ -441,8 +441,8 @@ class MyForm(settingsmixin.SMainWindow):
toAddress = widget.address toAddress = widget.address
else: else:
toAddress = None toAddress = None
if not toAddress in db: if toAddress not in db:
treeWidget.takeTopLevelItem(i) treeWidget.takeTopLevelItem(i)
# no increment # no increment
continue continue
@ -472,7 +472,7 @@ class MyForm(settingsmixin.SMainWindow):
widget.setUnreadCount(unread) widget.setUnreadCount(unread)
db.pop(toAddress, None) db.pop(toAddress, None)
i += 1 i += 1
i = 0 i = 0
for toAddress in db: 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'])
@ -487,23 +487,22 @@ class MyForm(settingsmixin.SMainWindow):
j += 1 j += 1
widget.setUnreadCount(unread) widget.setUnreadCount(unread)
i += 1 i += 1
treeWidget.setSortingEnabled(True)
treeWidget.setSortingEnabled(True)
def rerenderTabTreeMessages(self): def rerenderTabTreeMessages(self):
self.rerenderTabTree('messages') self.rerenderTabTree('messages')
def rerenderTabTreeChans(self): def rerenderTabTreeChans(self):
self.rerenderTabTree('chan') self.rerenderTabTree('chan')
def rerenderTabTree(self, tab): def rerenderTabTree(self, tab):
if tab == 'messages': if tab == 'messages':
treeWidget = self.ui.treeWidgetYourIdentities treeWidget = self.ui.treeWidgetYourIdentities
elif tab == 'chan': elif tab == 'chan':
treeWidget = self.ui.treeWidgetChans treeWidget = self.ui.treeWidgetChans
folders = Ui_FolderWidget.folderWeight.keys() folders = Ui_FolderWidget.folderWeight.keys()
# sort ascending when creating # sort ascending when creating
if treeWidget.topLevelItemCount() == 0: if treeWidget.topLevelItemCount() == 0:
treeWidget.header().setSortIndicator( treeWidget.header().setSortIndicator(
@ -511,7 +510,7 @@ class MyForm(settingsmixin.SMainWindow):
# init dictionary # init dictionary
db = {} db = {}
enabled = {} enabled = {}
for toAddress in getSortedAccounts(): for toAddress in getSortedAccounts():
isEnabled = BMConfigParser().getboolean( isEnabled = BMConfigParser().getboolean(
toAddress, 'enabled') toAddress, 'enabled')
@ -530,7 +529,7 @@ class MyForm(settingsmixin.SMainWindow):
db[toAddress] = {} db[toAddress] = {}
for folder in folders: for folder in folders:
db[toAddress][folder] = 0 db[toAddress][folder] = 0
enabled[toAddress] = isEnabled enabled[toAddress] = isEnabled
# get number of (unread) messages # get number of (unread) messages
@ -548,10 +547,10 @@ class MyForm(settingsmixin.SMainWindow):
db[None]["sent"] = 0 db[None]["sent"] = 0
db[None]["trash"] = 0 db[None]["trash"] = 0
enabled[None] = True enabled[None] = True
if treeWidget.isSortingEnabled(): if treeWidget.isSortingEnabled():
treeWidget.setSortingEnabled(False) treeWidget.setSortingEnabled(False)
widgets = {} widgets = {}
i = 0 i = 0
while i < treeWidget.topLevelItemCount(): while i < treeWidget.topLevelItemCount():
@ -560,8 +559,8 @@ class MyForm(settingsmixin.SMainWindow):
toAddress = widget.address toAddress = widget.address
else: else:
toAddress = None toAddress = None
if not toAddress in db: if toAddress not in db:
treeWidget.takeTopLevelItem(i) treeWidget.takeTopLevelItem(i)
# no increment # no increment
continue continue
@ -570,8 +569,9 @@ class MyForm(settingsmixin.SMainWindow):
while j < widget.childCount(): while j < widget.childCount():
subwidget = widget.child(j) subwidget = widget.child(j)
try: try:
subwidget.setUnreadCount(db[toAddress][subwidget.folderName]) subwidget.setUnreadCount(
if subwidget.folderName not in ["new", "trash", "sent"]: db[toAddress][subwidget.folderName])
if subwidget.folderName not in ("new", "trash", "sent"):
unread += db[toAddress][subwidget.folderName] unread += db[toAddress][subwidget.folderName]
db[toAddress].pop(subwidget.folderName, None) db[toAddress].pop(subwidget.folderName, None)
except: except:
@ -587,13 +587,13 @@ class MyForm(settingsmixin.SMainWindow):
if toAddress is not None and tab == 'messages' and folder == "new": if toAddress is not None and tab == 'messages' and folder == "new":
continue continue
subwidget = Ui_FolderWidget(widget, j, toAddress, f, c) subwidget = Ui_FolderWidget(widget, j, toAddress, f, c)
if subwidget.folderName not in ["new", "trash", "sent"]: if subwidget.folderName not in ("new", "trash", "sent"):
unread += c unread += c
j += 1 j += 1
widget.setUnreadCount(unread) widget.setUnreadCount(unread)
db.pop(toAddress, None) db.pop(toAddress, None)
i += 1 i += 1
i = 0 i = 0
for toAddress in db: for toAddress in db:
widget = Ui_AddressWidget(treeWidget, i, toAddress, db[toAddress]["inbox"], enabled[toAddress]) widget = Ui_AddressWidget(treeWidget, i, toAddress, db[toAddress]["inbox"], enabled[toAddress])
@ -603,12 +603,12 @@ class MyForm(settingsmixin.SMainWindow):
if toAddress is not None and tab == 'messages' and folder == "new": if toAddress is not None and tab == 'messages' and folder == "new":
continue continue
subwidget = Ui_FolderWidget(widget, j, toAddress, folder, db[toAddress][folder]) subwidget = Ui_FolderWidget(widget, j, toAddress, folder, db[toAddress][folder])
if subwidget.folderName not in ["new", "trash", "sent"]: if subwidget.folderName not in ("new", "trash", "sent"):
unread += db[toAddress][folder] unread += db[toAddress][folder]
j += 1 j += 1
widget.setUnreadCount(unread) widget.setUnreadCount(unread)
i += 1 i += 1
treeWidget.setSortingEnabled(True) treeWidget.setSortingEnabled(True)
def __init__(self, parent=None): def __init__(self, parent=None):
@ -1088,15 +1088,16 @@ class MyForm(settingsmixin.SMainWindow):
if sortingEnabled: if sortingEnabled:
tableWidget.setSortingEnabled(False) tableWidget.setSortingEnabled(False)
tableWidget.insertRow(0) tableWidget.insertRow(0)
for i in range(len(items)): for i, item in enumerate(items):
tableWidget.setItem(0, i, items[i]) tableWidget.setItem(0, i, item)
if sortingEnabled: if sortingEnabled:
tableWidget.setSortingEnabled(True) tableWidget.setSortingEnabled(True)
def addMessageListItemSent(self, tableWidget, toAddress, fromAddress, subject, status, ackdata, lastactiontime): def addMessageListItemSent(
acct = accountClass(fromAddress) self, tableWidget, toAddress, fromAddress, subject,
if acct is None: status, ackdata, lastactiontime
acct = BMAccount(fromAddress) ):
acct = accountClass(fromAddress) or BMAccount(fromAddress)
acct.parseMessage(toAddress, fromAddress, subject, "") acct.parseMessage(toAddress, fromAddress, subject, "")
items = [] items = []
@ -1106,25 +1107,32 @@ class MyForm(settingsmixin.SMainWindow):
if status == 'awaitingpubkey': if status == 'awaitingpubkey':
statusText = _translate( statusText = _translate(
"MainWindow", "Waiting for their encryption key. Will request it again soon.") "MainWindow",
"Waiting for their encryption key. Will request it again soon."
)
elif status == 'doingpowforpubkey': elif status == 'doingpowforpubkey':
statusText = _translate( statusText = _translate(
"MainWindow", "Doing work necessary to request encryption key.") "MainWindow", "Doing work necessary to request encryption key."
)
elif status == 'msgqueued': elif status == 'msgqueued':
statusText = _translate( statusText = _translate("MainWindow", "Queued.")
"MainWindow", "Queued.")
elif status == 'msgsent': elif status == 'msgsent':
statusText = _translate("MainWindow", "Message sent. Waiting for acknowledgement. Sent at %1").arg( statusText = _translate(
l10n.formatTimestamp(lastactiontime)) "MainWindow",
"Message sent. Waiting for acknowledgement. Sent at %1"
).arg(l10n.formatTimestamp(lastactiontime))
elif status == 'msgsentnoackexpected': elif status == 'msgsentnoackexpected':
statusText = _translate("MainWindow", "Message sent. Sent at %1").arg( statusText = _translate(
l10n.formatTimestamp(lastactiontime)) "MainWindow", "Message sent. Sent at %1"
).arg(l10n.formatTimestamp(lastactiontime))
elif status == 'doingmsgpow': elif status == 'doingmsgpow':
statusText = _translate( statusText = _translate(
"MainWindow", "Doing work necessary to send message.") "MainWindow", "Doing work necessary to send message.")
elif status == 'ackreceived': elif status == 'ackreceived':
statusText = _translate("MainWindow", "Acknowledgement of the message received %1").arg( statusText = _translate(
l10n.formatTimestamp(lastactiontime)) "MainWindow",
"Acknowledgement of the message received %1"
).arg(l10n.formatTimestamp(lastactiontime))
elif status == 'broadcastqueued': elif status == 'broadcastqueued':
statusText = _translate( statusText = _translate(
"MainWindow", "Broadcast queued.") "MainWindow", "Broadcast queued.")
@ -1135,16 +1143,24 @@ class MyForm(settingsmixin.SMainWindow):
statusText = _translate("MainWindow", "Broadcast on %1").arg( statusText = _translate("MainWindow", "Broadcast on %1").arg(
l10n.formatTimestamp(lastactiontime)) l10n.formatTimestamp(lastactiontime))
elif status == 'toodifficult': elif status == 'toodifficult':
statusText = _translate("MainWindow", "Problem: The work demanded by the recipient is more difficult than you are willing to do. %1").arg( statusText = _translate(
l10n.formatTimestamp(lastactiontime)) "MainWindow",
"Problem: The work demanded by the recipient is more"
" difficult than you are willing to do. %1"
).arg(l10n.formatTimestamp(lastactiontime))
elif status == 'badkey': elif status == 'badkey':
statusText = _translate("MainWindow", "Problem: The recipient\'s encryption key is no good. Could not encrypt message. %1").arg( statusText = _translate(
l10n.formatTimestamp(lastactiontime)) "MainWindow",
"Problem: The recipient\'s encryption key is no good."
" Could not encrypt message. %1"
).arg(l10n.formatTimestamp(lastactiontime))
elif status == 'forcepow': elif status == 'forcepow':
statusText = _translate( statusText = _translate(
"MainWindow", "Forced difficulty override. Send should start soon.") "MainWindow",
"Forced difficulty override. Send should start soon.")
else: else:
statusText = _translate("MainWindow", "Unknown status: %1 %2").arg(status).arg( statusText = _translate(
"MainWindow", "Unknown status: %1 %2").arg(status).arg(
l10n.formatTimestamp(lastactiontime)) l10n.formatTimestamp(lastactiontime))
newItem = myTableWidgetItem(statusText) newItem = myTableWidgetItem(statusText)
newItem.setToolTip(statusText) newItem.setToolTip(statusText)
@ -1156,15 +1172,16 @@ class MyForm(settingsmixin.SMainWindow):
self.addMessageListItem(tableWidget, items) self.addMessageListItem(tableWidget, items)
return acct return acct
def addMessageListItemInbox(self, tableWidget, msgfolder, msgid, toAddress, fromAddress, subject, received, read): def addMessageListItemInbox(
self, tableWidget, toAddress, fromAddress, subject,
msgid, received, read
):
font = QtGui.QFont() font = QtGui.QFont()
font.setBold(True) font.setBold(True)
if toAddress == str_broadcast_subscribers: if toAddress == str_broadcast_subscribers:
acct = accountClass(fromAddress) acct = accountClass(fromAddress)
else: else:
acct = accountClass(toAddress) acct = accountClass(toAddress) or accountClass(fromAddress)
if acct is None:
acct = accountClass(fromAddress)
if acct is None: if acct is None:
acct = BMAccount(fromAddress) acct = BMAccount(fromAddress)
acct.parseMessage(toAddress, fromAddress, subject, "") acct.parseMessage(toAddress, fromAddress, subject, "")
@ -1201,16 +1218,11 @@ class MyForm(settingsmixin.SMainWindow):
xAddress = 'both' xAddress = 'both'
else: else:
tableWidget.setColumnHidden(0, False) tableWidget.setColumnHidden(0, False)
if account is None: tableWidget.setColumnHidden(1, bool(account))
tableWidget.setColumnHidden(1, False)
else:
tableWidget.setColumnHidden(1, True)
xAddress = 'fromaddress' xAddress = 'fromaddress'
tableWidget.setUpdatesEnabled(False) queryreturn = helper_search.search_sql(
tableWidget.setSortingEnabled(False) xAddress, account, "sent", where, what, False)
tableWidget.setRowCount(0)
queryreturn = helper_search.search_sql(xAddress, account, "sent", where, what, False)
for row in queryreturn: for row in queryreturn:
self.addMessageListItemSent(tableWidget, *row) self.addMessageListItemSent(tableWidget, *row)
@ -1218,11 +1230,19 @@ class MyForm(settingsmixin.SMainWindow):
tableWidget.horizontalHeader().setSortIndicator( tableWidget.horizontalHeader().setSortIndicator(
3, QtCore.Qt.DescendingOrder) 3, QtCore.Qt.DescendingOrder)
tableWidget.setSortingEnabled(True) tableWidget.setSortingEnabled(True)
tableWidget.horizontalHeaderItem(3).setText(_translate("MainWindow", "Sent", None)) tableWidget.horizontalHeaderItem(3).setText(
_translate("MainWindow", "Sent"))
tableWidget.setUpdatesEnabled(True) tableWidget.setUpdatesEnabled(True)
# Load messages from database file # 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
):
tableWidget.setUpdatesEnabled(False)
tableWidget.setSortingEnabled(False)
tableWidget.setRowCount(0)
if folder == 'sent': if folder == 'sent':
self.loadSent(tableWidget, account, where, what) self.loadSent(tableWidget, account, where, what)
return return
@ -1238,21 +1258,21 @@ class MyForm(settingsmixin.SMainWindow):
tableWidget.setColumnHidden(0, False) tableWidget.setColumnHidden(0, False)
tableWidget.setColumnHidden(1, False) tableWidget.setColumnHidden(1, False)
tableWidget.setUpdatesEnabled(False) queryreturn = helper_search.search_sql(
tableWidget.setSortingEnabled(False) xAddress, account, folder, where, what, unreadOnly)
tableWidget.setRowCount(0)
queryreturn = helper_search.search_sql(xAddress, account, folder, where, what, unreadOnly)
for row in queryreturn: for row in queryreturn:
toAddress, fromAddress, subject, msgfolder, msgid, received, read = row toAddress, fromAddress, subject, _, msgid, received, read = row
self.addMessageListItemInbox(tableWidget, msgfolder, msgid, toAddress, fromAddress, subject, received, read) self.addMessageListItemInbox(
tableWidget, toAddress, fromAddress, subject,
msgid, received, read)
tableWidget.horizontalHeader().setSortIndicator( tableWidget.horizontalHeader().setSortIndicator(
3, QtCore.Qt.DescendingOrder) 3, QtCore.Qt.DescendingOrder)
tableWidget.setSortingEnabled(True) tableWidget.setSortingEnabled(True)
tableWidget.selectRow(0) tableWidget.selectRow(0)
tableWidget.horizontalHeaderItem(3).setText(_translate("MainWindow", "Received", None)) tableWidget.horizontalHeaderItem(3).setText(
_translate("MainWindow", "Received"))
tableWidget.setUpdatesEnabled(True) tableWidget.setUpdatesEnabled(True)
# create application indicator # create application indicator
@ -1479,9 +1499,9 @@ class MyForm(settingsmixin.SMainWindow):
def handleKeyPress(self, event, focus=None): def handleKeyPress(self, event, focus=None):
"""This method handles keypress events for all widgets on MyForm""" """This method handles keypress events for all widgets on MyForm"""
messagelist = self.getCurrentMessagelist() messagelist = self.getCurrentMessagelist()
folder = self.getCurrentFolder()
if event.key() == QtCore.Qt.Key_Delete: if event.key() == QtCore.Qt.Key_Delete:
if isinstance(focus, MessageView) or isinstance(focus, QtGui.QTableWidget): if isinstance(focus, (MessageView, QtGui.QTableWidget)):
folder = self.getCurrentFolder()
if folder == "sent": if folder == "sent":
self.on_action_SentTrash() self.on_action_SentTrash()
else: else:
@ -1517,17 +1537,18 @@ class MyForm(settingsmixin.SMainWindow):
self.ui.lineEditTo.setFocus() self.ui.lineEditTo.setFocus()
event.ignore() event.ignore()
elif event.key() == QtCore.Qt.Key_F: elif event.key() == QtCore.Qt.Key_F:
searchline = self.getCurrentSearchLine(retObj=True) try:
if searchline: self.getCurrentSearchLine(retObj=True).setFocus()
searchline.setFocus() except AttributeError:
pass
event.ignore() event.ignore()
if not event.isAccepted(): if not event.isAccepted():
return return
if isinstance(focus, MessageView): if isinstance(focus, MessageView):
return MessageView.keyPressEvent(focus, event) return MessageView.keyPressEvent(focus, event)
elif isinstance(focus, QtGui.QTableWidget): if isinstance(focus, QtGui.QTableWidget):
return QtGui.QTableWidget.keyPressEvent(focus, event) return QtGui.QTableWidget.keyPressEvent(focus, event)
elif isinstance(focus, QtGui.QTreeWidget): if isinstance(focus, QtGui.QTreeWidget):
return QtGui.QTreeWidget.keyPressEvent(focus, event) return QtGui.QTreeWidget.keyPressEvent(focus, event)
# menu button 'manage keys' # menu button 'manage keys'
@ -1741,7 +1762,7 @@ class MyForm(settingsmixin.SMainWindow):
self.drawTrayIcon(iconFileName, self.findInboxUnreadCount()) self.drawTrayIcon(iconFileName, self.findInboxUnreadCount())
def calcTrayIcon(self, iconFileName, inboxUnreadCount): def calcTrayIcon(self, iconFileName, inboxUnreadCount):
pixmap = QtGui.QPixmap(":/newPrefix/images/"+iconFileName) pixmap = QtGui.QPixmap(":/newPrefix/images/" + iconFileName)
if inboxUnreadCount > 0: if inboxUnreadCount > 0:
# choose font and calculate font parameters # choose font and calculate font parameters
fontName = "Lucida" fontName = "Lucida"
@ -1753,7 +1774,8 @@ class MyForm(settingsmixin.SMainWindow):
rect = fontMetrics.boundingRect(txt) rect = fontMetrics.boundingRect(txt)
# margins that we add in the top-right corner # margins that we add in the top-right corner
marginX = 2 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 it renders too wide we need to change it to a plus symbol
if rect.width() > 20: if rect.width() > 20:
txt = "+" txt = "+"
@ -1793,11 +1815,18 @@ class MyForm(settingsmixin.SMainWindow):
return self.unreadCount return self.unreadCount
def updateSentItemStatusByToAddress(self, toAddress, textToDisplay): 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) treeWidget = self.widgetConvert(sent)
if self.getCurrentFolder(treeWidget) != "sent": if self.getCurrentFolder(treeWidget) != "sent":
continue 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 continue
for i in range(sent.rowCount()): for i in range(sent.rowCount()):
@ -1817,7 +1846,11 @@ class MyForm(settingsmixin.SMainWindow):
def updateSentItemStatusByAckdata(self, ackdata, textToDisplay): def updateSentItemStatusByAckdata(self, ackdata, textToDisplay):
if type(ackdata) is str: if type(ackdata) is str:
ackdata = QtCore.QByteArray(ackdata) 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) treeWidget = self.widgetConvert(sent)
if self.getCurrentFolder(treeWidget) != "sent": if self.getCurrentFolder(treeWidget) != "sent":
continue continue
@ -1925,11 +1958,13 @@ class MyForm(settingsmixin.SMainWindow):
newRows[address] = [label, AccountMixin.NORMAL] newRows[address] = [label, AccountMixin.NORMAL]
completerList = [] completerList = []
for address in sorted(oldRows, key = lambda x: oldRows[x][2], reverse = True): for address in sorted(
if address in newRows: oldRows, key=lambda x: oldRows[x][2], reverse=True
completerList.append(unicode(newRows[address][0], encoding="UTF-8") + " <" + address + ">") ):
newRows.pop(address) try:
else: completerList.append(
newRows.pop(address)[0] + " <" + address + ">")
except KeyError:
self.ui.tableWidgetAddressBook.removeRow(oldRows[address][2]) self.ui.tableWidgetAddressBook.removeRow(oldRows[address][2])
for address in newRows: for address in newRows:
addRow(address, newRows[address][0], newRows[address][1]) addRow(address, newRows[address][0], newRows[address][1])
@ -2002,11 +2037,14 @@ class MyForm(settingsmixin.SMainWindow):
acct = accountClass(fromAddress) acct = accountClass(fromAddress)
if sendMessageToPeople: # To send a message to specific people (rather than broadcast) # To send a message to specific people (rather than broadcast)
toAddressesList = [s.strip() if sendMessageToPeople:
for s in toAddresses.replace(',', ';').split(';')] toAddressesList = set([
toAddressesList = list(set( s.strip() for s in toAddresses.replace(',', ';').split(';')
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. ])
# 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.
for toAddress in toAddressesList: for toAddress in toAddressesList:
if toAddress != '': if toAddress != '':
# label plus address # label plus address
@ -2213,7 +2251,7 @@ class MyForm(settingsmixin.SMainWindow):
'''INSERT INTO sent VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)''', *t) '''INSERT INTO sent VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)''', *t)
toLabel = str_broadcast_subscribers toLabel = str_broadcast_subscribers
self.displayNewSentMessage( self.displayNewSentMessage(
toAddress, toLabel, fromAddress, subject, message, ackdata) toAddress, toLabel, fromAddress, subject, message, ackdata)
@ -2314,54 +2352,88 @@ class MyForm(settingsmixin.SMainWindow):
# receives a message to an address that is acting as a # receives a message to an address that is acting as a
# pseudo-mailing-list. The message will be broadcast out. This function # pseudo-mailing-list. The message will be broadcast out. This function
# puts the message on the 'Sent' tab. # puts the message on the 'Sent' tab.
def displayNewSentMessage(self, toAddress, toLabel, fromAddress, subject, message, ackdata): def displayNewSentMessage(
self, toAddress, toLabel, fromAddress, subject,
message, ackdata):
acct = accountClass(fromAddress) acct = accountClass(fromAddress)
acct.parseMessage(toAddress, fromAddress, subject, message) acct.parseMessage(toAddress, fromAddress, subject, message)
tab = -1 tab = -1
for sent in [self.ui.tableWidgetInbox, self.ui.tableWidgetInboxSubscriptions, self.ui.tableWidgetInboxChans]: for sent in (
self.ui.tableWidgetInbox,
self.ui.tableWidgetInboxSubscriptions,
self.ui.tableWidgetInboxChans
):
tab += 1 tab += 1
if tab == 1: if tab == 1:
tab = 2 tab = 2
treeWidget = self.widgetConvert(sent) treeWidget = self.widgetConvert(sent)
if self.getCurrentFolder(treeWidget) != "sent": if self.getCurrentFolder(treeWidget) != "sent":
continue continue
if treeWidget == self.ui.treeWidgetYourIdentities and self.getCurrentAccount(treeWidget) not in (fromAddress, None, False): if treeWidget == self.ui.treeWidgetYourIdentities \
and self.getCurrentAccount(treeWidget) not in (
fromAddress, None, False):
continue continue
elif treeWidget in [self.ui.treeWidgetSubscriptions, self.ui.treeWidgetChans] and self.getCurrentAccount(treeWidget) != toAddress: elif treeWidget in (
self.ui.treeWidgetSubscriptions,
self.ui.treeWidgetChans
) and self.getCurrentAccount(treeWidget) != toAddress:
continue continue
elif not helper_search.check_match(toAddress, fromAddress, subject, message, self.getCurrentSearchOption(tab), self.getCurrentSearchLine(tab)): elif not helper_search.check_match(
toAddress, fromAddress, subject, message,
self.getCurrentSearchOption(tab),
self.getCurrentSearchLine(tab)
):
continue continue
self.addMessageListItemSent(sent, toAddress, fromAddress, subject, "msgqueued", ackdata, time.time()) self.addMessageListItemSent(
self.getAccountTextedit(acct).setPlainText(unicode(message, 'utf-8', 'replace')) sent, toAddress, fromAddress, subject,
"msgqueued", ackdata, time.time())
self.getAccountTextedit(acct).setPlainText(message)
sent.setCurrentCell(0, 0) sent.setCurrentCell(0, 0)
def displayNewInboxMessage(self, inventoryHash, toAddress, fromAddress, subject, message): def displayNewInboxMessage(
if toAddress == str_broadcast_subscribers: self, inventoryHash, toAddress, fromAddress, subject, message):
acct = accountClass(fromAddress) acct = accountClass(
else: fromAddress if toAddress == str_broadcast_subscribers
acct = accountClass(toAddress) else toAddress
)
inbox = self.getAccountMessagelist(acct) inbox = self.getAccountMessagelist(acct)
ret = None ret = treeWidget = None
tab = -1 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 tab += 1
if tab == 1: if tab == 1:
tab = 2 tab = 2
tableWidget = self.widgetConvert(treeWidget) if not helper_search.check_match(
if not helper_search.check_match(toAddress, fromAddress, subject, message, self.getCurrentSearchOption(tab), self.getCurrentSearchLine(tab)): toAddress, fromAddress, subject, message,
self.getCurrentSearchOption(tab),
self.getCurrentSearchLine(tab)
):
continue continue
if tableWidget == inbox and self.getCurrentAccount(treeWidget) == acct.address and self.getCurrentFolder(treeWidget) in ["inbox", None]: tableWidget = self.widgetConvert(treeWidget)
ret = self.addMessageListItemInbox(inbox, "inbox", inventoryHash, toAddress, fromAddress, subject, time.time(), 0) current_account = self.getCurrentAccount(treeWidget)
elif treeWidget == self.ui.treeWidgetYourIdentities and self.getCurrentAccount(treeWidget) is None and self.getCurrentFolder(treeWidget) in ["inbox", "new", None]: current_folder = self.getCurrentFolder(treeWidget)
ret = self.addMessageListItemInbox(tableWidget, "inbox", inventoryHash, toAddress, fromAddress, subject, time.time(), 0) # pylint: disable=too-many-boolean-expressions
if ((tableWidget == inbox
and current_account == acct.address
and current_folder in ("inbox", None))
or (treeWidget == self.ui.treeWidgetYourIdentities
and current_account is None
and current_folder in ("inbox", "new", None))):
ret = self.addMessageListItemInbox(
tableWidget, toAddress, fromAddress, subject,
inventoryHash, time.time(), False)
if ret is None: if ret is None:
acct.parseMessage(toAddress, fromAddress, subject, "") acct.parseMessage(toAddress, fromAddress, subject, "")
else: else:
acct = ret acct = ret
# pylint:disable=undefined-loop-variable
self.propagateUnreadCount(widget=treeWidget if ret else None) self.propagateUnreadCount(widget=treeWidget if ret else None)
if BMConfigParser().getboolean( if BMConfigParser().safeGetBoolean(
'bitmessagesettings', 'showtraynotifications'): 'bitmessagesettings', 'showtraynotifications'):
self.notifierShow( self.notifierShow(
_translate("MainWindow", "New Message"), _translate("MainWindow", "New Message"),
@ -2369,16 +2441,22 @@ class MyForm(settingsmixin.SMainWindow):
unicode(acct.fromLabel, 'utf-8')), unicode(acct.fromLabel, 'utf-8')),
sound.SOUND_UNKNOWN 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 (
# Ubuntu should notify of new message irespective of (self.getCurrentFolder(treeWidget) != "inbox"
and self.getCurrentFolder(treeWidget) is not None)
or self.getCurrentAccount(treeWidget) != acct.address):
# Ubuntu should notify of new message irrespective of
# whether it's in current message list or not # whether it's in current message list or not
self.indicatorUpdate(True, to_label=acct.toLabel) self.indicatorUpdate(True, to_label=acct.toLabel)
# cannot find item to pass here ):
if hasattr(acct, "feedback") \ try:
and acct.feedback != GatewayAccount.ALL_OK: if acct.feedback != GatewayAccount.ALL_OK:
if acct.feedback == GatewayAccount.REGISTRATION_DENIED: if acct.feedback == GatewayAccount.REGISTRATION_DENIED:
dialogs.EmailGatewayDialog( dialogs.EmailGatewayDialog(
self, BMConfigParser(), acct).exec_() self, BMConfigParser(), acct).exec_()
# possible other branches?
except AttributeError:
pass
def click_pushButtonAddAddressBook(self, dialog=None): def click_pushButtonAddAddressBook(self, dialog=None):
if not dialog: if not dialog:
@ -2609,10 +2687,8 @@ class MyForm(settingsmixin.SMainWindow):
) + "\n\n" + ) + "\n\n" +
_translate( _translate(
"MainWindow", "Wait until these tasks finish?"), "MainWindow", "Wait until these tasks finish?"),
QtGui.QMessageBox.Yes | QtGui.QMessageBox.No | QtGui.QMessageBox.Yes | QtGui.QMessageBox.No
QtGui.QMessageBox.Cancel, | QtGui.QMessageBox.Cancel, QtGui.QMessageBox.Cancel)
QtGui.QMessageBox.Cancel
)
if reply == QtGui.QMessageBox.No: if reply == QtGui.QMessageBox.No:
waitForPow = False waitForPow = False
elif reply == QtGui.QMessageBox.Cancel: elif reply == QtGui.QMessageBox.Cancel:
@ -2629,10 +2705,8 @@ class MyForm(settingsmixin.SMainWindow):
" synchronisation finishes?", None, " synchronisation finishes?", None,
QtCore.QCoreApplication.CodecForTr, pendingDownload() QtCore.QCoreApplication.CodecForTr, pendingDownload()
), ),
QtGui.QMessageBox.Yes | QtGui.QMessageBox.No | QtGui.QMessageBox.Yes | QtGui.QMessageBox.No
QtGui.QMessageBox.Cancel, | QtGui.QMessageBox.Cancel, QtGui.QMessageBox.Cancel)
QtGui.QMessageBox.Cancel
)
if reply == QtGui.QMessageBox.Yes: if reply == QtGui.QMessageBox.Yes:
self.wait = waitForSync = True self.wait = waitForSync = True
elif reply == QtGui.QMessageBox.Cancel: elif reply == QtGui.QMessageBox.Cancel:
@ -2648,10 +2722,8 @@ class MyForm(settingsmixin.SMainWindow):
" quit now, it may cause delivery delays. Wait until" " quit now, it may cause delivery delays. Wait until"
" connected and the synchronisation finishes?" " connected and the synchronisation finishes?"
), ),
QtGui.QMessageBox.Yes | QtGui.QMessageBox.No | QtGui.QMessageBox.Yes | QtGui.QMessageBox.No
QtGui.QMessageBox.Cancel, | QtGui.QMessageBox.Cancel, QtGui.QMessageBox.Cancel)
QtGui.QMessageBox.Cancel
)
if reply == QtGui.QMessageBox.Yes: if reply == QtGui.QMessageBox.Yes:
waitForConnection = True waitForConnection = True
self.wait = waitForSync = True self.wait = waitForSync = True
@ -2845,13 +2917,13 @@ class MyForm(settingsmixin.SMainWindow):
# Format predefined text on message reply. # Format predefined text on message reply.
def quoted_text(self, message): def quoted_text(self, message):
if not BMConfigParser().safeGetBoolean('bitmessagesettings', 'replybelow'): if not BMConfigParser().safeGetBoolean('bitmessagesettings', 'replybelow'):
return '\n\n------------------------------------------------------\n' + message 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): def quote_line(line):
# Do quote empty lines. # Do quote empty lines.
if line == '' or line.isspace(): if line == '' or line.isspace():
@ -2864,18 +2936,20 @@ class MyForm(settingsmixin.SMainWindow):
return quoteWrapper.fill(line) return quoteWrapper.fill(line)
return '\n'.join([quote_line(l) for l in message.splitlines()]) + '\n\n' 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: if address is None:
messagelist = self.getCurrentMessagelist() messagelist = self.getCurrentMessagelist()
if messagelist: if not messagelist:
currentInboxRow = messagelist.currentRow() return
address = messagelist.item( currentInboxRow = messagelist.currentRow()
currentInboxRow, 0).address address = messagelist.item(currentInboxRow, 0).address
for box in [self.ui.comboBoxSendFrom, self.ui.comboBoxSendFromBroadcast]: for box in (
listOfAddressesInComboBoxSendFrom = [str(box.itemData(i).toPyObject()) for i in range(box.count())] self.ui.comboBoxSendFrom, self.ui.comboBoxSendFromBroadcast
if address in listOfAddressesInComboBoxSendFrom: ):
currentIndex = listOfAddressesInComboBoxSendFrom.index(address) for i in range(box.count()):
box.setCurrentIndex(currentIndex) if str(box.itemData(i).toPyObject()) == address:
box.setCurrentIndex(i)
break
else: else:
box.setCurrentIndex(0) box.setCurrentIndex(0)
@ -2991,7 +3065,7 @@ class MyForm(settingsmixin.SMainWindow):
quotedText = self.quoted_text( quotedText = self.quoted_text(
unicode(messageAtCurrentInboxRow, 'utf-8', 'replace')) unicode(messageAtCurrentInboxRow, 'utf-8', 'replace'))
widget['message'].setPlainText(quotedText) widget['message'].setPlainText(quotedText)
if acct.subject[0:3] in ['Re:', 'RE:']: if acct.subject[0:3] in ('Re:', 'RE:'):
widget['subject'].setText( widget['subject'].setText(
tableWidget.item(currentInboxRow, 2).label) tableWidget.item(currentInboxRow, 2).label)
else: else:
@ -3045,11 +3119,17 @@ class MyForm(settingsmixin.SMainWindow):
"Error: You cannot add the same address to your blacklist" "Error: You cannot add the same address to your blacklist"
" twice. Try renaming the existing one if you want.")) " 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: 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): elif type(messageLists) not in (list, tuple):
messageLists = (messageLists) messageLists = (messageLists,)
for messageList in messageLists: for messageList in messageLists:
if row is not None: if row is not None:
inventoryHash = str(messageList.item(row, 3).data( inventoryHash = str(messageList.item(row, 3).data(
@ -3071,17 +3151,18 @@ class MyForm(settingsmixin.SMainWindow):
return return
currentRow = 0 currentRow = 0
folder = self.getCurrentFolder() folder = self.getCurrentFolder()
shifted = QtGui.QApplication.queryKeyboardModifiers() & QtCore.Qt.ShiftModifier shifted = QtGui.QApplication.queryKeyboardModifiers() \
tableWidget.setUpdatesEnabled(False); & QtCore.Qt.ShiftModifier
inventoryHashesToTrash = [] tableWidget.setUpdatesEnabled(False)
inventoryHashesToTrash = set()
# ranges in reversed order # ranges in reversed order
for r in sorted(tableWidget.selectedRanges(), key=lambda r: r.topRow())[::-1]: for r in sorted(
for i in range(r.bottomRow()-r.topRow()+1): tableWidget.selectedRanges(), key=lambda r: r.topRow()
)[::-1]:
for i in range(r.bottomRow() - r.topRow() + 1):
inventoryHashToTrash = str(tableWidget.item( inventoryHashToTrash = str(tableWidget.item(
r.topRow()+i, 3).data(QtCore.Qt.UserRole).toPyObject()) r.topRow() + i, 3).data(QtCore.Qt.UserRole).toPyObject())
if inventoryHashToTrash in inventoryHashesToTrash: inventoryHashesToTrash.add(inventoryHashToTrash)
continue
inventoryHashesToTrash.append(inventoryHashToTrash)
currentRow = r.topRow() currentRow = r.topRow()
self.getCurrentMessageTextedit().setText("") self.getCurrentMessageTextedit().setText("")
tableWidget.model().removeRows(r.topRow(), r.bottomRow()-r.topRow()+1) tableWidget.model().removeRows(r.topRow(), r.bottomRow()-r.topRow()+1)
@ -3101,22 +3182,24 @@ class MyForm(settingsmixin.SMainWindow):
return return
currentRow = 0 currentRow = 0
tableWidget.setUpdatesEnabled(False) tableWidget.setUpdatesEnabled(False)
inventoryHashesToTrash = [] inventoryHashesToTrash = set()
# ranges in reversed order # ranges in reversed order
for r in sorted(tableWidget.selectedRanges(), key=lambda r: r.topRow())[::-1]: for r in sorted(
for i in range(r.bottomRow()-r.topRow()+1): tableWidget.selectedRanges(), key=lambda r: r.topRow()
)[::-1]:
for i in range(r.bottomRow() - r.topRow() + 1):
inventoryHashToTrash = str(tableWidget.item( inventoryHashToTrash = str(tableWidget.item(
r.topRow()+i, 3).data(QtCore.Qt.UserRole).toPyObject()) r.topRow() + i, 3).data(QtCore.Qt.UserRole).toPyObject())
if inventoryHashToTrash in inventoryHashesToTrash: inventoryHashesToTrash.add(inventoryHashToTrash)
continue
inventoryHashesToTrash.append(inventoryHashToTrash)
currentRow = r.topRow() currentRow = r.topRow()
self.getCurrentMessageTextedit().setText("") 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) tableWidget.selectRow(0 if currentRow == 0 else currentRow - 1)
idCount = len(inventoryHashesToTrash) idCount = len(inventoryHashesToTrash)
sqlExecuteChunked('''UPDATE inbox SET folder='inbox' WHERE msgid IN({0})''', sqlExecuteChunked(
idCount, *inventoryHashesToTrash) "UPDATE inbox SET folder='inbox' WHERE msgid IN({0})",
idCount, *inventoryHashesToTrash)
tableWidget.selectRow(0 if currentRow == 0 else currentRow - 1) tableWidget.selectRow(0 if currentRow == 0 else currentRow - 1)
tableWidget.setUpdatesEnabled(True) tableWidget.setUpdatesEnabled(True)
self.propagateUnreadCount() self.propagateUnreadCount()
@ -3387,13 +3470,13 @@ class MyForm(settingsmixin.SMainWindow):
return None return None
def getCurrentTreeWidget(self): def getCurrentTreeWidget(self):
currentIndex = self.ui.tabWidget.currentIndex(); currentIndex = self.ui.tabWidget.currentIndex()
treeWidgetList = [ treeWidgetList = (
self.ui.treeWidgetYourIdentities, self.ui.treeWidgetYourIdentities,
False, False,
self.ui.treeWidgetSubscriptions, self.ui.treeWidgetSubscriptions,
self.ui.treeWidgetChans self.ui.treeWidgetChans
] )
if currentIndex >= 0 and currentIndex < len(treeWidgetList): if currentIndex >= 0 and currentIndex < len(treeWidgetList):
return treeWidgetList[currentIndex] return treeWidgetList[currentIndex]
else: else:
@ -3411,18 +3494,16 @@ class MyForm(settingsmixin.SMainWindow):
return self.ui.treeWidgetYourIdentities return self.ui.treeWidgetYourIdentities
def getCurrentMessagelist(self): def getCurrentMessagelist(self):
currentIndex = self.ui.tabWidget.currentIndex(); currentIndex = self.ui.tabWidget.currentIndex()
messagelistList = [ messagelistList = (
self.ui.tableWidgetInbox, self.ui.tableWidgetInbox,
False, False,
self.ui.tableWidgetInboxSubscriptions, self.ui.tableWidgetInboxSubscriptions,
self.ui.tableWidgetInboxChans, self.ui.tableWidgetInboxChans,
] )
if currentIndex >= 0 and currentIndex < len(messagelistList): if currentIndex >= 0 and currentIndex < len(messagelistList):
return messagelistList[currentIndex] return messagelistList[currentIndex]
else:
return False
def getAccountMessagelist(self, account): def getAccountMessagelist(self, account):
try: try:
if account.type == AccountMixin.CHAN: if account.type == AccountMixin.CHAN:
@ -3447,16 +3528,14 @@ class MyForm(settingsmixin.SMainWindow):
def getCurrentMessageTextedit(self): def getCurrentMessageTextedit(self):
currentIndex = self.ui.tabWidget.currentIndex() currentIndex = self.ui.tabWidget.currentIndex()
messagelistList = [ messagelistList = (
self.ui.textEditInboxMessage, self.ui.textEditInboxMessage,
False, False,
self.ui.textEditInboxMessageSubscriptions, self.ui.textEditInboxMessageSubscriptions,
self.ui.textEditInboxMessageChans, self.ui.textEditInboxMessageChans,
] )
if currentIndex >= 0 and currentIndex < len(messagelistList): if currentIndex >= 0 and currentIndex < len(messagelistList):
return messagelistList[currentIndex] return messagelistList[currentIndex]
else:
return False
def getAccountTextedit(self, account): def getAccountTextedit(self, account):
try: try:
@ -3472,29 +3551,26 @@ class MyForm(settingsmixin.SMainWindow):
def getCurrentSearchLine(self, currentIndex=None, retObj=False): def getCurrentSearchLine(self, currentIndex=None, retObj=False):
if currentIndex is None: if currentIndex is None:
currentIndex = self.ui.tabWidget.currentIndex() currentIndex = self.ui.tabWidget.currentIndex()
messagelistList = [ messagelistList = (
self.ui.inboxSearchLineEdit, self.ui.inboxSearchLineEdit,
False, False,
self.ui.inboxSearchLineEditSubscriptions, self.ui.inboxSearchLineEditSubscriptions,
self.ui.inboxSearchLineEditChans, self.ui.inboxSearchLineEditChans,
] )
if currentIndex >= 0 and currentIndex < len(messagelistList): if currentIndex >= 0 and currentIndex < len(messagelistList):
if retObj: return (
return messagelistList[currentIndex] messagelistList[currentIndex] if retObj
else: else messagelistList[currentIndex].text().toUtf8().data())
return messagelistList[currentIndex].text().toUtf8().data()
else:
return None
def getCurrentSearchOption(self, currentIndex=None): def getCurrentSearchOption(self, currentIndex=None):
if currentIndex is None: if currentIndex is None:
currentIndex = self.ui.tabWidget.currentIndex() currentIndex = self.ui.tabWidget.currentIndex()
messagelistList = [ messagelistList = (
self.ui.inboxSearchOption, self.ui.inboxSearchOption,
False, False,
self.ui.inboxSearchOptionSubscriptions, self.ui.inboxSearchOptionSubscriptions,
self.ui.inboxSearchOptionChans, self.ui.inboxSearchOptionChans,
] )
if currentIndex >= 0 and currentIndex < len(messagelistList): if currentIndex >= 0 and currentIndex < len(messagelistList):
return messagelistList[currentIndex].currentText() return messagelistList[currentIndex].currentText()
@ -3600,12 +3676,11 @@ class MyForm(settingsmixin.SMainWindow):
tableWidget = self.getCurrentMessagelist() tableWidget = self.getCurrentMessagelist()
currentColumn = tableWidget.currentColumn() currentColumn = tableWidget.currentColumn()
currentRow = tableWidget.currentRow() currentRow = tableWidget.currentRow()
if currentColumn not in [0, 1, 2]: # to, from, subject currentFolder = self.getCurrentFolder()
if self.getCurrentFolder() == "sent": if currentColumn not in (0, 1, 2): # to, from, subject
currentColumn = 0 currentColumn = 0 if currentFolder == "sent" else 1
else:
currentColumn = 1 if currentFolder == "sent":
if self.getCurrentFolder() == "sent":
myAddress = tableWidget.item(currentRow, 1).data(QtCore.Qt.UserRole) myAddress = tableWidget.item(currentRow, 1).data(QtCore.Qt.UserRole)
otherAddress = tableWidget.item(currentRow, 0).data(QtCore.Qt.UserRole) otherAddress = tableWidget.item(currentRow, 0).data(QtCore.Qt.UserRole)
else: else:
@ -3618,18 +3693,18 @@ class MyForm(settingsmixin.SMainWindow):
text = str(tableWidget.item(currentRow, currentColumn).label) text = str(tableWidget.item(currentRow, currentColumn).label)
else: else:
text = tableWidget.item(currentRow, currentColumn).data(QtCore.Qt.UserRole) text = tableWidget.item(currentRow, currentColumn).data(QtCore.Qt.UserRole)
text = unicode(str(text), 'utf-8', 'ignore')
clipboard = QtGui.QApplication.clipboard() clipboard = QtGui.QApplication.clipboard()
clipboard.setText(text) clipboard.setText(text)
#set avatar functions # set avatar functions
def on_action_TreeWidgetSetAvatar(self): def on_action_TreeWidgetSetAvatar(self):
address = self.getCurrentAccount() address = self.getCurrentAccount()
self.setAvatar(address) self.setAvatar(address)
def on_action_AddressBookSetAvatar(self): def on_action_AddressBookSetAvatar(self):
self.on_action_SetAvatar(self.ui.tableWidgetAddressBook) self.on_action_SetAvatar(self.ui.tableWidgetAddressBook)
def on_action_SetAvatar(self, thisTableWidget): def on_action_SetAvatar(self, thisTableWidget):
currentRow = thisTableWidget.currentRow() currentRow = thisTableWidget.currentRow()
addressAtCurrentRow = thisTableWidget.item( addressAtCurrentRow = thisTableWidget.item(
@ -3639,19 +3714,36 @@ class MyForm(settingsmixin.SMainWindow):
thisTableWidget.item( thisTableWidget.item(
currentRow, 0).setIcon(avatarize(addressAtCurrentRow)) currentRow, 0).setIcon(avatarize(addressAtCurrentRow))
# TODO: reuse utils
def setAvatar(self, addressAtCurrentRow): def setAvatar(self, addressAtCurrentRow):
if not os.path.exists(state.appdata + 'avatars/'): if not os.path.exists(state.appdata + 'avatars/'):
os.makedirs(state.appdata + 'avatars/') os.makedirs(state.appdata + 'avatars/')
hash = hashlib.md5(addBMIfNotPresent(addressAtCurrentRow)).hexdigest() hash = hashlib.md5(addBMIfNotPresent(addressAtCurrentRow)).hexdigest()
extensions = ['PNG', 'GIF', 'JPG', 'JPEG', 'SVG', 'BMP', 'MNG', 'PBM', 'PGM', 'PPM', 'TIFF', 'XBM', 'XPM', 'TGA'] extensions = [
# http://pyqt.sourceforge.net/Docs/PyQt4/qimagereader.html#supportedImageFormats 'PNG', 'GIF', 'JPG', 'JPEG', 'SVG', 'BMP', 'MNG', 'PBM',
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'} 'PGM', 'PPM', 'TIFF', 'XBM', 'XPM', 'TGA']
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 = [] filters = []
all_images_filter = [] all_images_filter = []
current_files = [] current_files = []
for ext in extensions: for ext in extensions:
filters += [ names[ext] + ' (*.' + ext.lower() + ')' ] filters += [names[ext] + ' (*.' + ext.lower() + ')']
all_images_filter += [ '*.' + ext.lower() ] all_images_filter += ['*.' + ext.lower()]
upper = state.appdata + 'avatars/' + hash + '.' + ext.upper() upper = state.appdata + 'avatars/' + hash + '.' + ext.upper()
lower = state.appdata + 'avatars/' + hash + '.' + ext.lower() lower = state.appdata + 'avatars/' + hash + '.' + ext.lower()
if os.path.isfile(lower): if os.path.isfile(lower):
@ -3662,28 +3754,34 @@ class MyForm(settingsmixin.SMainWindow):
filters[1:1] = ['All files (*.*)'] filters[1:1] = ['All files (*.*)']
sourcefile = QtGui.QFileDialog.getOpenFileName( sourcefile = QtGui.QFileDialog.getOpenFileName(
self, _translate("MainWindow", "Set avatar..."), self, _translate("MainWindow", "Set avatar..."),
filter = ';;'.join(filters) filter=';;'.join(filters)
) )
# determine the correct filename (note that avatars don't use the suffix) # determine the correct filename (note that avatars don't use the suffix)
destination = state.appdata + 'avatars/' + hash + '.' + sourcefile.split('.')[-1] destination = state.appdata + 'avatars/' + hash + '.' + sourcefile.split('.')[-1]
exists = QtCore.QFile.exists(destination) exists = QtCore.QFile.exists(destination)
if sourcefile == '': if sourcefile == '':
# ask for removal of avatar # ask for removal of avatar
if exists | (len(current_files)>0): if exists | (len(current_files) > 0):
displayMsg = _translate("MainWindow", "Do you really want to remove this avatar?") displayMsg = _translate(
"MainWindow", "Do you really want to remove this avatar?")
overwrite = QtGui.QMessageBox.question( overwrite = QtGui.QMessageBox.question(
self, 'Message', displayMsg, QtGui.QMessageBox.Yes, QtGui.QMessageBox.No) self, 'Message', displayMsg,
QtGui.QMessageBox.Yes, QtGui.QMessageBox.No)
else: else:
overwrite = QtGui.QMessageBox.No overwrite = QtGui.QMessageBox.No
else: else:
# ask whether to overwrite old avatar # ask whether to overwrite old avatar
if exists | (len(current_files)>0): 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?") displayMsg = _translate(
"MainWindow",
"You have already set an avatar for this address."
" Do you really want to overwrite it?")
overwrite = QtGui.QMessageBox.question( overwrite = QtGui.QMessageBox.question(
self, 'Message', displayMsg, QtGui.QMessageBox.Yes, QtGui.QMessageBox.No) self, 'Message', displayMsg,
QtGui.QMessageBox.Yes, QtGui.QMessageBox.No)
else: else:
overwrite = QtGui.QMessageBox.No overwrite = QtGui.QMessageBox.No
# copy the image file to the appdata folder # copy the image file to the appdata folder
if (not exists) | (overwrite == QtGui.QMessageBox.Yes): if (not exists) | (overwrite == QtGui.QMessageBox.Yes):
if overwrite == QtGui.QMessageBox.Yes: if overwrite == QtGui.QMessageBox.Yes:
@ -3885,8 +3983,8 @@ class MyForm(settingsmixin.SMainWindow):
if 0 < len(text) < 3: if 0 < len(text) < 3:
return return
messagelist = self.getCurrentMessagelist() messagelist = self.getCurrentMessagelist()
searchOption = self.getCurrentSearchOption()
if messagelist: if messagelist:
searchOption = self.getCurrentSearchOption()
account = self.getCurrentAccount() account = self.getCurrentAccount()
folder = self.getCurrentFolder() folder = self.getCurrentFolder()
self.loadMessagelist( self.loadMessagelist(
@ -3896,12 +3994,12 @@ class MyForm(settingsmixin.SMainWindow):
logger.debug("Search return pressed") logger.debug("Search return pressed")
searchLine = self.getCurrentSearchLine() searchLine = self.getCurrentSearchLine()
messagelist = self.getCurrentMessagelist() messagelist = self.getCurrentMessagelist()
if len(str(searchLine)) < 3: if messagelist and len(str(searchLine)) < 3:
searchOption = self.getCurrentSearchOption() searchOption = self.getCurrentSearchOption()
account = self.getCurrentAccount() account = self.getCurrentAccount()
folder = self.getCurrentFolder() folder = self.getCurrentFolder()
self.loadMessagelist(messagelist, account, folder, searchOption, searchLine) self.loadMessagelist(
if messagelist: messagelist, account, folder, searchOption, searchLine)
messagelist.setFocus() messagelist.setFocus()
def treeWidgetItemClicked(self): def treeWidgetItemClicked(self):
@ -3927,7 +4025,7 @@ class MyForm(settingsmixin.SMainWindow):
if (not isinstance(item, Ui_AddressWidget)) or (not self.getCurrentTreeWidget()) or self.getCurrentTreeWidget().currentItem() is None: if (not isinstance(item, Ui_AddressWidget)) or (not self.getCurrentTreeWidget()) or self.getCurrentTreeWidget().currentItem() is None:
return return
# not visible # not visible
if (not self.getCurrentItem()) or (not isinstance (self.getCurrentItem(), Ui_AddressWidget)): if (not self.getCurrentItem()) or (not isinstance(self.getCurrentItem(), Ui_AddressWidget)):
return return
# only currently selected item # only currently selected item
if item.address != self.getCurrentAccount(): if item.address != self.getCurrentAccount():
@ -3935,7 +4033,7 @@ class MyForm(settingsmixin.SMainWindow):
# "All accounts" can't be renamed # "All accounts" can't be renamed
if item.type == AccountMixin.ALL: if item.type == AccountMixin.ALL:
return return
newLabel = unicode(item.text(0), 'utf-8', 'ignore') newLabel = unicode(item.text(0), 'utf-8', 'ignore')
oldLabel = item.defaultLabel() oldLabel = item.defaultLabel()
@ -3960,12 +4058,12 @@ class MyForm(settingsmixin.SMainWindow):
self.recurDepth -= 1 self.recurDepth -= 1
def tableWidgetInboxItemClicked(self): def tableWidgetInboxItemClicked(self):
folder = self.getCurrentFolder()
messageTextedit = self.getCurrentMessageTextedit() messageTextedit = self.getCurrentMessageTextedit()
if not messageTextedit: if not messageTextedit:
return return
msgid = self.getCurrentMessageId() msgid = self.getCurrentMessageId()
folder = self.getCurrentFolder()
if msgid: if msgid:
queryreturn = sqlQuery( queryreturn = sqlQuery(
'''SELECT message FROM %s WHERE %s=?''' % ( '''SELECT message FROM %s WHERE %s=?''' % (
@ -4026,12 +4124,15 @@ class MyForm(settingsmixin.SMainWindow):
self.rerenderAddressBook() self.rerenderAddressBook()
def updateStatusBar(self, data): def updateStatusBar(self, data):
if type(data) is tuple or type(data) is list: try:
option = data[1] option, message = data
message = data[0] except ValueError:
else:
option = 0 option = 0
message = data message = data
except TypeError:
logger.debug(
'Invalid argument for updateStatusBar!', exc_info=True)
if message != "": if message != "":
logger.info('Status bar: ' + message) logger.info('Status bar: ' + message)
@ -4047,11 +4148,11 @@ class MyForm(settingsmixin.SMainWindow):
# Check to see whether we can connect to namecoin. # Check to see whether we can connect to namecoin.
# Hide the 'Fetch Namecoin ID' button if we can't. # Hide the 'Fetch Namecoin ID' button if we can't.
if BMConfigParser().safeGetBoolean( if BMConfigParser().safeGetBoolean(
'bitmessagesettings', 'dontconnect' 'bitmessagesettings', 'dontconnect'
) or self.namecoin.test()[0] == 'failed': ) or self.namecoin.test()[0] == 'failed':
logger.warning( logger.warning(
'There was a problem testing for a Namecoin daemon. Hiding the' 'There was a problem testing for a Namecoin daemon.'
' Fetch Namecoin ID button') ' Hiding the Fetch Namecoin ID button')
self.ui.pushButtonFetchNamecoinID.hide() self.ui.pushButtonFetchNamecoinID.hide()
else: else:
self.ui.pushButtonFetchNamecoinID.show() self.ui.pushButtonFetchNamecoinID.show()
@ -4161,7 +4262,7 @@ def run():
# myapp.showMigrationWizard(BMConfigParser().get('bitmessagesettings', 'mailchuck')) # myapp.showMigrationWizard(BMConfigParser().get('bitmessagesettings', 'mailchuck'))
# except: # except:
# myapp.showMigrationWizard(0) # myapp.showMigrationWizard(0)
# only show after wizards and connect dialogs have completed # only show after wizards and connect dialogs have completed
if not BMConfigParser().getboolean('bitmessagesettings', 'startintray'): if not BMConfigParser().getboolean('bitmessagesettings', 'startintray'):
myapp.show() myapp.show()

View File

@ -1,32 +1,41 @@
import glob import glob
import os import os
from PyQt4 import QtCore, QtGui from PyQt4 import QtCore, QtGui
from bmconfigparser import BMConfigParser
import paths import paths
from bmconfigparser import BMConfigParser
class LanguageBox(QtGui.QComboBox): class LanguageBox(QtGui.QComboBox):
languageName = {"system": "System Settings", "eo": "Esperanto", "en_pirate": "Pirate English"} languageName = {
def __init__(self, parent = None): "system": "System Settings", "eo": "Esperanto",
"en_pirate": "Pirate English"
}
def __init__(self, parent=None):
super(QtGui.QComboBox, self).__init__(parent) super(QtGui.QComboBox, self).__init__(parent)
self.populate() self.populate()
def populate(self): def populate(self):
self.clear() self.clear()
localesPath = os.path.join (paths.codePath(), 'translations') localesPath = os.path.join(paths.codePath(), 'translations')
self.addItem(QtGui.QApplication.translate("settingsDialog", "System Settings", "system"), "system") self.addItem(QtGui.QApplication.translate(
"settingsDialog", "System Settings", "system"), "system")
self.setCurrentIndex(0) self.setCurrentIndex(0)
self.setInsertPolicy(QtGui.QComboBox.InsertAlphabetically) self.setInsertPolicy(QtGui.QComboBox.InsertAlphabetically)
for translationFile in sorted(glob.glob(os.path.join(localesPath, "bitmessage_*.qm"))): for translationFile in sorted(
localeShort = os.path.split(translationFile)[1].split("_", 1)[1][:-3] glob.glob(os.path.join(localesPath, "bitmessage_*.qm"))
locale = QtCore.QLocale(QtCore.QString(localeShort)) ):
localeShort = \
os.path.split(translationFile)[1].split("_", 1)[1][:-3]
if localeShort in LanguageBox.languageName: if localeShort in LanguageBox.languageName:
self.addItem(LanguageBox.languageName[localeShort], localeShort) self.addItem(
elif locale.nativeLanguageName() == "": LanguageBox.languageName[localeShort], localeShort)
self.addItem(localeShort, localeShort)
else: else:
self.addItem(locale.nativeLanguageName(), localeShort) locale = QtCore.QLocale(localeShort)
self.addItem(
locale.nativeLanguageName() or localeShort, localeShort)
configuredLocale = BMConfigParser().safeGet( configuredLocale = BMConfigParser().safeGet(
'bitmessagesettings', 'userlocale', "system") 'bitmessagesettings', 'userlocale', "system")

View File

@ -1,13 +1,16 @@
from PyQt4 import QtGui
import hashlib import hashlib
import os import os
from PyQt4 import QtGui
import state
from addresses import addBMIfNotPresent from addresses import addBMIfNotPresent
from bmconfigparser import BMConfigParser from bmconfigparser import BMConfigParser
import state
str_broadcast_subscribers = '[Broadcast subscribers]' str_broadcast_subscribers = '[Broadcast subscribers]'
str_chan = '[chan]' str_chan = '[chan]'
def identiconize(address): def identiconize(address):
size = 48 size = 48
@ -28,32 +31,40 @@ def identiconize(address):
# the identicons to decrease the risk of attacks where someone creates # the identicons to decrease the risk of attacks where someone creates
# an address to mimic someone else's identicon. # an address to mimic someone else's identicon.
identiconsuffix = BMConfigParser().get('bitmessagesettings', 'identiconsuffix') identiconsuffix = BMConfigParser().get('bitmessagesettings', 'identiconsuffix')
if (identicon_lib[:len('qidenticon')] == 'qidenticon'): if identicon_lib[:len('qidenticon')] == 'qidenticon':
# print identicon_lib
# originally by: # originally by:
# :Author:Shin Adachi <shn@glucose.jp> # :Author:Shin Adachi <shn@glucose.jp>
# Licesensed under FreeBSD License. # Licesensed under FreeBSD License.
# stripped from PIL and uses QT instead (by sendiulo, same license) # stripped from PIL and uses QT instead (by sendiulo, same license)
import qidenticon import qidenticon
hash = hashlib.md5(addBMIfNotPresent(address)+identiconsuffix).hexdigest() icon_hash = hashlib.md5(
use_two_colors = (identicon_lib[:len('qidenticon_two')] == 'qidenticon_two') addBMIfNotPresent(address) + identiconsuffix).hexdigest()
opacity = int(not((identicon_lib == 'qidenticon_x') | (identicon_lib == 'qidenticon_two_x') | (identicon_lib == 'qidenticon_b') | (identicon_lib == 'qidenticon_two_b')))*255 use_two_colors = identicon_lib[:len('qidenticon_two')] == 'qidenticon_two'
opacity = int(
identicon_lib not in (
'qidenticon_x', 'qidenticon_two_x',
'qidenticon_b', 'qidenticon_two_b'
)) * 255
penwidth = 0 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' # filename = './images/identicons/'+hash+'.png'
# image.save(filename) # image.save(filename)
idcon = QtGui.QIcon() idcon = QtGui.QIcon()
idcon.addPixmap(image, QtGui.QIcon.Normal, QtGui.QIcon.Off) idcon.addPixmap(image, QtGui.QIcon.Normal, QtGui.QIcon.Off)
return idcon return idcon
elif identicon_lib == 'pydenticon': elif identicon_lib == 'pydenticon':
# print identicon_lib # Here you could load pydenticon.py
# Here you could load pydenticon.py (just put it in the "src" folder of your Bitmessage source) # (just put it in the "src" folder of your Bitmessage source)
from pydenticon import Pydenticon from pydenticon import Pydenticon
# It is not included in the source, because it is licensed under GPLv3 # It is not included in the source, because it is licensed under GPLv3
# GPLv3 is a copyleft license that would influence our licensing # 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 # Find the source here:
# note that it requires PIL to be installed: http://www.pythonware.com/products/pil/ # https://github.com/azaghal/pydenticon
idcon_render = Pydenticon(addBMIfNotPresent(address)+identiconsuffix, size*3) # note that it requires pillow (or PIL) to be installed:
# https://python-pillow.org/
idcon_render = Pydenticon(
addBMIfNotPresent(address) + identiconsuffix, size * 3)
rendering = idcon_render._render() rendering = idcon_render._render()
data = rendering.convert("RGBA").tostring("raw", "RGBA") data = rendering.convert("RGBA").tostring("raw", "RGBA")
qim = QtGui.QImage(data, size, size, QtGui.QImage.Format_ARGB32) qim = QtGui.QImage(data, size, size, QtGui.QImage.Format_ARGB32)
@ -62,32 +73,31 @@ def identiconize(address):
idcon.addPixmap(pix, QtGui.QIcon.Normal, QtGui.QIcon.Off) idcon.addPixmap(pix, QtGui.QIcon.Normal, QtGui.QIcon.Off)
return idcon return idcon
def avatarize(address): def avatarize(address):
""" """
loads a supported image for the given address' hash form 'avatars' folder Loads a supported image for the given address' hash form 'avatars' folder
falls back to default avatar if 'default.*' file exists falls back to default avatar if 'default.*' file exists
falls back to identiconize(address) falls back to identiconize(address)
""" """
idcon = QtGui.QIcon() 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: if address == str_broadcast_subscribers:
# don't hash [Broadcast subscribers] # don't hash [Broadcast subscribers]
hash = address icon_hash = address
# http://pyqt.sourceforge.net/Docs/PyQt4/qimagereader.html#supportedImageFormats # https://www.riverbankcomputing.com/static/Docs/PyQt4/qimagereader.html#supportedImageFormats
# print QImageReader.supportedImageFormats ()
# QImageReader.supportedImageFormats () # QImageReader.supportedImageFormats ()
extensions = ['PNG', 'GIF', 'JPG', 'JPEG', 'SVG', 'BMP', 'MNG', 'PBM', 'PGM', 'PPM', 'TIFF', 'XBM', 'XPM', 'TGA'] extensions = [
'PNG', 'GIF', 'JPG', 'JPEG', 'SVG', 'BMP', 'MNG', 'PBM', 'PGM', 'PPM',
'TIFF', 'XBM', 'XPM', 'TGA']
# try to find a specific avatar # try to find a specific avatar
for ext in extensions: for ext in extensions:
lower_hash = state.appdata + 'avatars/' + hash + '.' + ext.lower() lower_hash = state.appdata + 'avatars/' + icon_hash + '.' + ext.lower()
upper_hash = state.appdata + 'avatars/' + hash + '.' + ext.upper() upper_hash = state.appdata + 'avatars/' + icon_hash + '.' + ext.upper()
if os.path.isfile(lower_hash): if os.path.isfile(lower_hash):
# print 'found avatar of ', address
idcon.addFile(lower_hash) idcon.addFile(lower_hash)
return idcon return idcon
elif os.path.isfile(upper_hash): elif os.path.isfile(upper_hash):
# print 'found avatar of ', address
idcon.addFile(upper_hash) idcon.addFile(upper_hash)
return idcon return idcon
# if we haven't found any, try to find a default avatar # if we haven't found any, try to find a default avatar