Module foldertree: simplified a bit and did flake8

This commit is contained in:
Dmitri Bogomolov 2018-03-06 13:15:41 +02:00
parent cbb228db8b
commit 90eca36b5d
Signed by untrusted user: g1itch
GPG Key ID: 720A756F18DEED13

View File

@ -1,10 +1,9 @@
from PyQt4 import QtCore, QtGui
from string import find, rfind, rstrip, lstrip
from tr import _translate
from bmconfigparser import BMConfigParser
from helper_sql import *
from utils import *
from utils import avatarize
from settingsmixin import SettingsMixin
# for pylupdate
@ -55,16 +54,21 @@ class AccountMixin(object):
self.address = str(address)
def setUnreadCount(self, cnt):
if hasattr(self, "unreadCount") and self.unreadCount == int(cnt):
try:
if self.unreadCount == int(cnt):
return
except AttributeError:
pass
self.unreadCount = int(cnt)
if isinstance(self, QtGui.QTreeWidgetItem):
self.emitDataChanged()
def setEnabled(self, enabled):
self.isEnabled = enabled
if hasattr(self, "setExpanded"):
try:
self.setExpanded(enabled)
except AttributeError:
pass
if isinstance(self, Ui_AddressWidget):
for i in range(self.childCount()):
if isinstance(self.child(i), Ui_FolderWidget):
@ -90,9 +94,12 @@ class AccountMixin(object):
def defaultLabel(self):
queryreturn = None
retval = None
if self.type in (AccountMixin.NORMAL, AccountMixin.CHAN, AccountMixin.MAILINGLIST):
if self.type in (
AccountMixin.NORMAL,
AccountMixin.CHAN, AccountMixin.MAILINGLIST):
try:
retval = unicode(BMConfigParser().get(self.address, 'label'), 'utf-8')
retval = unicode(
BMConfigParser().get(self.address, 'label'), 'utf-8')
except Exception as e:
queryreturn = sqlQuery(
'''select label from addressbook where address=?''', self.address)
@ -107,15 +114,15 @@ class AccountMixin(object):
elif self.address is None or self.type == AccountMixin.ALL:
return unicode(
str(_translate("MainWindow", "All accounts")), 'utf-8')
if retval is None:
return unicode(self.address, 'utf-8')
else:
return retval
return retval or unicode(self.address, 'utf-8')
class Ui_FolderWidget(QtGui.QTreeWidgetItem, AccountMixin):
folderWeight = {"inbox": 1, "new": 2, "sent": 3, "trash": 4}
def __init__(self, parent, pos = 0, address = "", folderName = "", unreadCount = 0):
def __init__(
self, parent, pos=0, address="", folderName="", unreadCount=0):
super(QtGui.QTreeWidgetItem, self).__init__()
self.setAddress(address)
self.setFolderName(folderName)
@ -144,7 +151,7 @@ class Ui_FolderWidget(QtGui.QTreeWidgetItem, AccountMixin):
# inbox, sent, thrash first, rest alphabetically
def __lt__(self, other):
if (isinstance(other, Ui_FolderWidget)):
if isinstance(other, Ui_FolderWidget):
if self.folderName in self.folderWeight:
x = self.folderWeight[self.folderName]
else:
@ -153,9 +160,8 @@ class Ui_FolderWidget(QtGui.QTreeWidgetItem, AccountMixin):
y = self.folderWeight[other.folderName]
else:
y = 99
reverse = False
if self.treeWidget().header().sortIndicatorOrder() == QtCore.Qt.DescendingOrder:
reverse = True
reverse = QtCore.Qt.DescendingOrder == \
self.treeWidget().header().sortIndicatorOrder()
if x == y:
return self.folderName < other.folderName
else:
@ -165,7 +171,8 @@ class Ui_FolderWidget(QtGui.QTreeWidgetItem, AccountMixin):
class Ui_AddressWidget(QtGui.QTreeWidgetItem, AccountMixin, SettingsMixin):
def __init__(self, parent, pos = 0, address = None, unreadCount = 0, enabled = True):
def __init__(
self, parent, pos=0, address=None, unreadCount=0, enabled=True):
super(QtGui.QTreeWidgetItem, self).__init__()
parent.insertTopLevelItem(pos, self)
# only set default when creating
@ -220,11 +227,13 @@ class Ui_AddressWidget(QtGui.QTreeWidgetItem, AccountMixin, SettingsMixin):
return super(Ui_AddressWidget, self).data(column, role)
def setData(self, column, role, value):
if role == QtCore.Qt.EditRole and self.type != AccountMixin.SUBSCRIPTION:
if isinstance(value, QtCore.QVariant):
BMConfigParser().set(str(self.address), 'label', str(value.toString().toUtf8()))
else:
BMConfigParser().set(str(self.address), 'label', str(value))
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 str(value)
)
BMConfigParser().save()
return super(Ui_AddressWidget, self).setData(column, role, value)
@ -243,21 +252,25 @@ class Ui_AddressWidget(QtGui.QTreeWidgetItem, AccountMixin, SettingsMixin):
# label (or address) alphabetically, disabled at the end
def __lt__(self, other):
if (isinstance(other, Ui_AddressWidget)):
reverse = False
if self.treeWidget().header().sortIndicatorOrder() == QtCore.Qt.DescendingOrder:
reverse = True
if isinstance(other, Ui_AddressWidget):
reverse = QtCore.Qt.DescendingOrder == \
self.treeWidget().header().sortIndicatorOrder()
if self._getSortRank() == other._getSortRank():
x = self._getLabel().lower()
y = other._getLabel().lower()
return x < y
return (not reverse if self._getSortRank() < other._getSortRank() else reverse)
return (
not reverse
if self._getSortRank() < other._getSortRank() else reverse
)
return super(QtGui.QTreeWidgetItem, self).__lt__(other)
class Ui_SubscriptionWidget(Ui_AddressWidget, AccountMixin):
def __init__(self, parent, pos = 0, address = "", unreadCount = 0, label = "", enabled = True):
def __init__(
self, parent, pos=0, address="", unreadCount=0, label="",
enabled=True):
super(QtGui.QTreeWidgetItem, self).__init__()
parent.insertTopLevelItem(pos, self)
# only set default when creating
@ -282,9 +295,9 @@ class Ui_SubscriptionWidget(Ui_AddressWidget, AccountMixin):
def setData(self, column, role, value):
if role == QtCore.Qt.EditRole:
from debug import logger
if isinstance(value, QtCore.QVariant):
label = str(value.toString().toUtf8()).decode('utf-8', 'ignore')
label = str(
value.toString().toUtf8()).decode('utf-8', 'ignore')
else:
label = unicode(value, 'utf-8', 'ignore')
sqlExecute(
@ -293,12 +306,10 @@ class Ui_SubscriptionWidget(Ui_AddressWidget, AccountMixin):
return super(Ui_SubscriptionWidget, self).setData(column, role, value)
class MessageList_AddressWidget(QtGui.QTableWidgetItem, AccountMixin, SettingsMixin):
class MessageList_AddressWidget(
QtGui.QTableWidgetItem, AccountMixin, SettingsMixin):
def __init__(self, parent, address=None, label=None, unread=False):
super(QtGui.QTableWidgetItem, self).__init__()
#parent.insertTopLevelItem(pos, self)
# only set default when creating
#super(QtGui.QTreeWidgetItem, self).setExpanded(BMConfigParser().getboolean(self.address, 'enabled'))
self.isEnabled = True
self.setAddress(address)
self.setLabel(label)
@ -311,9 +322,13 @@ class MessageList_AddressWidget(QtGui.QTableWidgetItem, AccountMixin, SettingsMi
newLabel = self.address
if label is None:
queryreturn = None
if self.type in (AccountMixin.NORMAL, AccountMixin.CHAN, AccountMixin.MAILINGLIST):
if self.type in (
AccountMixin.NORMAL,
AccountMixin.CHAN, AccountMixin.MAILINGLIST):
try:
newLabel = unicode(BMConfigParser().get(self.address, 'label'), 'utf-8', 'ignore')
newLabel = unicode(
BMConfigParser().get(self.address, 'label'),
'utf-8', 'ignore')
except:
queryreturn = sqlQuery(
'''select label from addressbook where address=?''', self.address)
@ -326,8 +341,10 @@ class MessageList_AddressWidget(QtGui.QTableWidgetItem, AccountMixin, SettingsMi
newLabel = unicode(row[0], 'utf-8', 'ignore')
else:
newLabel = label
if hasattr(self, 'label') and newLabel == self.label:
try:
if self.label == newLabel:
return
except AttributeError:
self.label = newLabel
def setUnread(self, unread):
@ -341,7 +358,8 @@ class MessageList_AddressWidget(QtGui.QTableWidgetItem, AccountMixin, SettingsMi
elif role == QtCore.Qt.ToolTipRole:
return self.label + " (" + self.address + ")"
elif role == QtCore.Qt.DecorationRole:
if BMConfigParser().safeGetBoolean('bitmessagesettings', 'useidenticons'):
if BMConfigParser().safeGetBoolean(
'bitmessagesettings', 'useidenticons'):
if self.address is None:
return avatarize(self.label)
else:
@ -363,7 +381,7 @@ class MessageList_AddressWidget(QtGui.QTableWidgetItem, AccountMixin, SettingsMi
# label (or address) alphabetically, disabled at the end
def __lt__(self, other):
if (isinstance(other, MessageList_AddressWidget)):
if isinstance(other, MessageList_AddressWidget):
return self.label.lower() < other.label.lower()
return super(QtGui.QTableWidgetItem, self).__lt__(other)
@ -371,9 +389,6 @@ class MessageList_AddressWidget(QtGui.QTableWidgetItem, AccountMixin, SettingsMi
class MessageList_SubjectWidget(QtGui.QTableWidgetItem, SettingsMixin):
def __init__(self, parent, subject=None, label=None, unread=False):
super(QtGui.QTableWidgetItem, self).__init__()
#parent.insertTopLevelItem(pos, self)
# only set default when creating
#super(QtGui.QTreeWidgetItem, self).setExpanded(BMConfigParser().getboolean(self.address, 'enabled'))
self.setSubject(subject)
self.setLabel(label)
self.setUnread(unread)
@ -404,12 +419,9 @@ class MessageList_SubjectWidget(QtGui.QTableWidgetItem, SettingsMixin):
return self.subject
return super(MessageList_SubjectWidget, self).data(role)
def setData(self, role, value):
return super(MessageList_SubjectWidget, self).setData(role, value)
# label (or address) alphabetically, disabled at the end
def __lt__(self, other):
if (isinstance(other, MessageList_SubjectWidget)):
if isinstance(other, MessageList_SubjectWidget):
return self.label.lower() < other.label.lower()
return super(QtGui.QTableWidgetItem, self).__lt__(other)
@ -429,11 +441,9 @@ class Ui_AddressBookWidgetItem(QtGui.QTableWidgetItem, AccountMixin):
elif role == QtCore.Qt.ToolTipRole:
return self.label + " (" + self.address + ")"
elif role == QtCore.Qt.DecorationRole:
if BMConfigParser().safeGetBoolean('bitmessagesettings', 'useidenticons'):
if self.address is None:
return avatarize(self.label)
else:
return avatarize(self.address)
if BMConfigParser().safeGetBoolean(
'bitmessagesettings', 'useidenticons'):
return avatarize(self.address or self.label)
elif role == QtCore.Qt.FontRole:
font = QtGui.QFont()
return font
@ -449,25 +459,26 @@ class Ui_AddressBookWidgetItem(QtGui.QTableWidgetItem, AccountMixin):
self.label = str(value.toString().toUtf8())
else:
self.label = str(value)
if self.type in (AccountMixin.NORMAL, AccountMixin.MAILINGLIST, AccountMixin.CHAN):
if self.type in (
AccountMixin.NORMAL,
AccountMixin.MAILINGLIST, AccountMixin.CHAN):
try:
a = BMConfigParser().get(self.address, 'label')
BMConfigParser().get(self.address, 'label')
BMConfigParser().set(self.address, 'label', self.label)
BMConfigParser().save()
except:
sqlExecute('''UPDATE addressbook set label=? WHERE address=?''', self.label, self.address)
elif self.type == AccountMixin.SUBSCRIPTION:
from debug import logger
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 = False
if self.tableWidget().horizontalHeader().sortIndicatorOrder() == QtCore.Qt.DescendingOrder:
reverse = True
if isinstance(other, Ui_AddressBookWidgetItem):
reverse = QtCore.Qt.DescendingOrder == \
self.tableWidget().horizontalHeader().sortIndicatorOrder()
if self.type == other.type:
return self.label.lower() < other.label.lower()
else:
@ -477,7 +488,7 @@ class Ui_AddressBookWidgetItem(QtGui.QTableWidgetItem, AccountMixin):
class Ui_AddressBookWidgetItemLabel(Ui_AddressBookWidgetItem):
def __init__(self, address, label, type):
Ui_AddressBookWidgetItem.__init__(self, label, type)
super(Ui_AddressBookWidgetItemLabel, self).__init__(label, type)
self.address = address
self.label = label
@ -488,7 +499,7 @@ class Ui_AddressBookWidgetItemLabel(Ui_AddressBookWidgetItem):
class Ui_AddressBookWidgetItemAddress(Ui_AddressBookWidgetItem):
def __init__(self, address, label, type):
Ui_AddressBookWidgetItem.__init__(self, address, type)
super(Ui_AddressBookWidgetItemAddress, self).__init__(address, type)
self.address = address
self.setFlags(QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
@ -502,7 +513,7 @@ class Ui_AddressBookWidgetItemAddress(Ui_AddressBookWidgetItem):
class AddressBookCompleter(QtGui.QCompleter):
def __init__(self):
super(QtGui.QCompleter, self).__init__()
super(AddressBookCompleter, self).__init__()
self.cursorPos = -1
def onCursorPositionChanged(self, oldPos, newPos):
@ -510,17 +521,13 @@ class AddressBookCompleter(QtGui.QCompleter):
self.cursorPos = -1
def splitPath(self, path):
stringList = []
text = unicode(path.toUtf8(), encoding="UTF-8")
splitIndex = rfind(text[0:self.widget().cursorPosition()], ";") + 1
str = text[splitIndex:self.widget().cursorPosition()]
str = rstrip(lstrip(str))
stringList.append(str)
return stringList
text = unicode(path.toUtf8(), 'utf-8')
return [text[:self.widget().cursorPosition()].split(';')[-1].strip()]
def pathFromIndex(self, index):
autoString = unicode(index.data(QtCore.Qt.EditRole).toString().toUtf8(), encoding="UTF-8")
text = unicode(self.widget().text().toUtf8(), encoding="UTF-8")
autoString = unicode(
index.data(QtCore.Qt.EditRole).toString().toUtf8(), 'utf-8')
text = unicode(self.widget().text().toUtf8(), 'utf-8')
# If cursor position was saved, restore it, else save it
if self.cursorPos != -1:
@ -531,14 +538,16 @@ class AddressBookCompleter(QtGui.QCompleter):
# Get current prosition
curIndex = self.widget().cursorPosition()
# prev_delimiter_index should actually point at final white space AFTER the delimiter
# prev_delimiter_index should actually point at final white space
# AFTER the delimiter
# Get index of last delimiter before current position
prevDelimiterIndex = rfind(text[0:curIndex], ";")
prevDelimiterIndex = text[0:curIndex].rfind(";")
while text[prevDelimiterIndex + 1] == " ":
prevDelimiterIndex += 1
# Get index of first delimiter after current position (or EOL if no delimiter after cursor)
nextDelimiterIndex = find(text, ";", curIndex)
# Get index of first delimiter after current position
# (or EOL if no delimiter after cursor)
nextDelimiterIndex = text.find(";", curIndex)
if nextDelimiterIndex == -1:
nextDelimiterIndex = len(text)
@ -546,9 +555,9 @@ class AddressBookCompleter(QtGui.QCompleter):
part1 = text[0:prevDelimiterIndex + 1]
# Get string value from before auto finished string is selected
pre = text[prevDelimiterIndex + 1:curIndex - 1];
# pre = text[prevDelimiterIndex + 1:curIndex - 1]
# Get part of string that occurs AFTER cursor
part2 = text[nextDelimiterIndex:]
return part1 + autoString + part2;
return part1 + autoString + part2