Compare commits

...

2 Commits

Author SHA1 Message Date
Omkar Pakki
deebf2fdd2 Flake changes done 2019-06-27 22:37:11 +05:30
Omkar Pakki
693891672b Basic code clean up 2019-06-26 23:36:36 +05:30
11 changed files with 559 additions and 422 deletions

View File

@ -1,4 +1,4 @@
#!/usr/bin/env python2 #! /usr/bin/env python2
""" """
Check dependendies and give recommendations about how to satisfy them Check dependendies and give recommendations about how to satisfy them
@ -12,7 +12,9 @@ Limitations:
import os import os
import sys import sys
from distutils.errors import CompileError from distutils.errors import CompileError
try: try:
from setuptools.dist import Distribution from setuptools.dist import Distribution
from setuptools.extension import Extension from setuptools.extension import Extension
@ -25,8 +27,7 @@ except ImportError:
EXTRAS_REQUIRE = {} EXTRAS_REQUIRE = {}
from importlib import import_module from importlib import import_module
from src.depends import detect_os, PACKAGES, PACKAGE_MANAGER
from src.depends import detectOS, PACKAGES, PACKAGE_MANAGER
COMPILING = { COMPILING = {
@ -72,15 +73,15 @@ def prereqToPackages():
if not detectPrereqs(): if not detectPrereqs():
return return
print("%s %s" % ( print("%s %s" % (
PACKAGE_MANAGER[detectOS()], " ".join( PACKAGE_MANAGER[detect_os()], " ".join(
PACKAGES[x][detectOS()] for x in detectPrereqs()))) PACKAGES[x][detect_os()] for x in detectPrereqs())))
def compilerToPackages(): def compilerToPackages():
if not detectOS() in COMPILING: if not detect_os() in COMPILING:
return return
print("%s %s" % ( print("%s %s" % (
PACKAGE_MANAGER[detectOS.result], COMPILING[detectOS.result])) PACKAGE_MANAGER[detect_os.result], COMPILING[detect_os.result]))
def testCompiler(): def testCompiler():
@ -112,11 +113,11 @@ def testCompiler():
prereqs = detectPrereqs() prereqs = detectPrereqs()
compiler = testCompiler() compiler = testCompiler()
if (not compiler or prereqs) and detectOS() in PACKAGE_MANAGER: if (not compiler or prereqs) and detect_os() in PACKAGE_MANAGER:
print( print(
"It looks like you're using %s. " "It looks like you're using %s. "
"It is highly recommended to use the package manager\n" "It is highly recommended to use the package manager\n"
"to install the missing dependencies." % detectOS.result) "to install the missing dependencies." % detect_os.result)
if not compiler: if not compiler:
print( print(
@ -134,7 +135,7 @@ if prereqs:
print(PACKAGES[package].get('description')) print(PACKAGES[package].get('description'))
# Install the system dependencies of optional extras_require components # Install the system dependencies of optional extras_require components
OPSYS = detectOS() OPSYS = detect_os()
CMD = PACKAGE_MANAGER[OPSYS] if OPSYS in PACKAGE_MANAGER else 'UNKNOWN_INSTALLER' CMD = PACKAGE_MANAGER[OPSYS] if OPSYS in PACKAGE_MANAGER else 'UNKNOWN_INSTALLER'
for lhs, rhs in EXTRAS_REQUIRE.items(): for lhs, rhs in EXTRAS_REQUIRE.items():
if OPSYS is None: if OPSYS is None:

View File

@ -95,11 +95,11 @@ if __name__ == "__main__":
long_description=README, long_description=README,
license='MIT', license='MIT',
# TODO: add author info # TODO: add author info
#author='', # author='',
#author_email='', # author_email='',
url='https://bitmessage.org', url='https://bitmessage.org',
# TODO: add keywords # TODO: add keywords
#keywords='', # keywords='',
install_requires=installRequires, install_requires=installRequires,
tests_require=requirements, tests_require=requirements,
extras_require=EXTRAS_REQUIRE, extras_require=EXTRAS_REQUIRE,

View File

@ -8,38 +8,38 @@ def search_sql(xAddress="toaddress", account=None, folder="inbox", where=None, w
what = None what = None
if folder == "sent": if folder == "sent":
sqlStatementBase = ''' sql_statement_base = '''
SELECT toaddress, fromaddress, subject, status, ackdata, lastactiontime SELECT toaddress, fromaddress, subject, status, ackdata, lastactiontime
FROM sent ''' FROM sent '''
else: else:
sqlStatementBase = '''SELECT folder, msgid, toaddress, fromaddress, subject, received, read sql_statement_base = '''SELECT folder, msgid, toaddress, fromaddress, subject, received, read
FROM inbox ''' FROM inbox '''
sqlStatementParts = [] sql_statement_parts = []
sqlArguments = [] sqlArguments = []
if account is not None: if account is not None:
if xAddress == 'both': if xAddress == 'both':
sqlStatementParts.append("(fromaddress = ? OR toaddress = ?)") sql_statement_parts.append("(fromaddress = ? OR toaddress = ?)")
sqlArguments.append(account) sqlArguments.append(account)
sqlArguments.append(account) sqlArguments.append(account)
else: else:
sqlStatementParts.append(xAddress + " = ? ") sql_statement_parts.append(xAddress + " = ? ")
sqlArguments.append(account) sqlArguments.append(account)
if folder is not None: if folder is not None:
if folder == "new": if folder == "new":
folder = "inbox" folder = "inbox"
unreadOnly = True unreadOnly = True
sqlStatementParts.append("folder = ? ") sql_statement_parts.append("folder = ? ")
sqlArguments.append(folder) sqlArguments.append(folder)
else: else:
sqlStatementParts.append("folder != ?") sql_statement_parts.append("folder != ?")
sqlArguments.append("trash") sqlArguments.append("trash")
if what is not None: if what is not None:
sqlStatementParts.append("%s LIKE ?" % (where)) sql_statement_parts.append("%s LIKE ?" % (where))
sqlArguments.append(what) sqlArguments.append(what)
if unreadOnly: if unreadOnly:
sqlStatementParts.append("read = 0") sql_statement_parts.append("read = 0")
if len(sqlStatementParts) > 0: if len(sql_statement_parts) > 0:
sqlStatementBase += "WHERE " + " AND ".join(sqlStatementParts) sql_statement_base += "WHERE " + " AND ".join(sql_statement_parts)
if folder == "sent": if folder == "sent":
sqlStatementBase += " ORDER BY lastactiontime" sql_statement_base += " ORDER BY lastactiontime"
return sqlQuery(sqlStatementBase, sqlArguments) return sqlQuery(sql_statement_base, sqlArguments)

View File

@ -1,9 +1,9 @@
import kivy_helper_search
import os import os
import queues import queues
import shutdown import shutdown
import state import state
import time import time
import kivy_helper_search
from kivy.app import App from kivy.app import App
from kivy.lang import Builder from kivy.lang import Builder
@ -14,7 +14,6 @@ from kivy.properties import ObjectProperty, StringProperty, ListProperty
from kivy.uix.screenmanager import Screen from kivy.uix.screenmanager import Screen
from kivy.uix.textinput import TextInput from kivy.uix.textinput import TextInput
from kivymd.theming import ThemeManager from kivymd.theming import ThemeManager
from kivymd.toolbar import Toolbar
from bmconfigparser import BMConfigParser from bmconfigparser import BMConfigParser
from helper_ackPayload import genAckPayload from helper_ackPayload import genAckPayload
from addresses import decodeAddress, addBMIfNotPresent from addresses import decodeAddress, addBMIfNotPresent

View File

@ -11,51 +11,53 @@ import sys
import textwrap import textwrap
import threading import threading
import time import time
import defaults
import debug
import dialogs
import helper_search
import knownnodes
import l10n
import namecoin
import openclpow
import paths
import settingsmixin
import shared
import shutdown
import sound
import state
import support
import queues
from datetime import datetime, timedelta from datetime import datetime, timedelta
from sqlite3 import register_adapter from sqlite3 import register_adapter
from PyQt4 import QtCore, QtGui from PyQt4 import QtCore, QtGui
from PyQt4.QtNetwork import QLocalSocket, QLocalServer from PyQt4.QtNetwork import QLocalSocket, QLocalServer
from debug import logger
from tr import _translate
from addresses import decodeAddress, addBMIfNotPresent from addresses import decodeAddress, addBMIfNotPresent
import shared
from bitmessageui import Ui_MainWindow
from bmconfigparser import BMConfigParser
import defaults
import namecoin
from messageview import MessageView
from migrationwizard import Ui_MigrationWizard
from foldertree import (
AccountMixin, Ui_FolderWidget, Ui_AddressWidget, Ui_SubscriptionWidget,
MessageList_AddressWidget, MessageList_SubjectWidget,
Ui_AddressBookWidgetItemLabel, Ui_AddressBookWidgetItemAddress)
from settings import Ui_settingsDialog
import settingsmixin
import support
import debug
from helper_ackPayload import genAckPayload
from helper_sql import sqlQuery, sqlExecute, sqlExecuteChunked, sqlStoredProcedure
import helper_search
import l10n
import openclpow
from utils import str_broadcast_subscribers, avatarize
from account import ( from account import (
getSortedAccounts, getSortedSubscriptions, accountClass, BMAccount, getSortedAccounts, getSortedSubscriptions, accountClass, BMAccount,
GatewayAccount, MailchuckAccount, AccountColor) GatewayAccount, MailchuckAccount, AccountColor)
import dialogs from bitmessageui import Ui_MainWindow
from bmconfigparser import BMConfigParser
from debug import logger
from foldertree import (
AccountMixin, UiFolderWidget, UiAddressWidget, UiSubscriptionWidget,
MessageListAddressWidget, MessageListSubjectWidget,
UiAddressBookWidgetItemLabel, UiAddressBookWidgetItemAddress)
from helper_ackPayload import genAckPayload
from helper_sql import sqlQuery, sqlExecute, sqlExecuteChunked, sqlStoredProcedure
from messageview import MessageView
from migrationwizard import Ui_MigrationWizard
from network.stats import pendingDownload, pendingUpload from network.stats import pendingDownload, pendingUpload
from uisignaler import UISignaler
import knownnodes
import paths
from proofofwork import getPowType
import queues
import shutdown
import state
from statusbar import BMStatusBar
from network.asyncore_pollchoose import set_rates from network.asyncore_pollchoose import set_rates
import sound from proofofwork import getPowType
from settings import Ui_settingsDialog
from statusbar import BMStatusBar
from tr import _translate
from uisignaler import UISignaler
from utils import str_broadcast_subscribers, avatarize
try: try:
@ -84,9 +86,10 @@ def change_translation(newlocale):
qsystranslator = QtCore.QTranslator() qsystranslator = QtCore.QTranslator()
if paths.frozen: if paths.frozen:
translationpath = os.path.join (paths.codePath(), 'translations', 'qt_' + newlocale) translationpath = os.path.join(paths.codePath(), 'translations', 'qt_' + newlocale)
else: else:
translationpath = os.path.join (str(QtCore.QLibraryInfo.location(QtCore.QLibraryInfo.TranslationsPath)), 'qt_' + newlocale) translationpath = os.path.join(
str(QtCore.QLibraryInfo.location(QtCore.QLibraryInfo.TranslationsPath)), 'qt_' + newlocale)
qsystranslator.load(translationpath) qsystranslator.load(translationpath)
QtGui.QApplication.installTranslator(qsystranslator) QtGui.QApplication.installTranslator(qsystranslator)
@ -108,7 +111,7 @@ def change_translation(newlocale):
# TODO: rewrite # TODO: rewrite
def powQueueSize(): def pow_queue_size():
"""Returns the size of queues.workerQueue including current unfinished work""" """Returns the size of queues.workerQueue including current unfinished work"""
queue_len = queues.workerQueue.qsize() queue_len = queues.workerQueue.qsize()
for thread in threading.enumerate(): for thread in threading.enumerate():
@ -404,7 +407,7 @@ class MyForm(settingsmixin.SMainWindow):
def rerenderTabTreeSubscriptions(self): def rerenderTabTreeSubscriptions(self):
treeWidget = self.ui.treeWidgetSubscriptions treeWidget = self.ui.treeWidgetSubscriptions
folders = Ui_FolderWidget.folderWeight.keys() folders = UiFolderWidget.folderWeight.keys()
folders.remove("new") folders.remove("new")
# sort ascending when creating # sort ascending when creating
@ -440,7 +443,7 @@ 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]['count']) subwidget.set_unread_count(db[toAddress][subwidget.folderName]['count'])
unread += db[toAddress][subwidget.folderName]['count'] unread += db[toAddress][subwidget.folderName]['count']
db[toAddress].pop(subwidget.folderName, None) db[toAddress].pop(subwidget.folderName, None)
except: except:
@ -454,9 +457,9 @@ class MyForm(settingsmixin.SMainWindow):
j = 0 j = 0
for f, c in db[toAddress].iteritems(): for f, c in db[toAddress].iteritems():
try: try:
subwidget = Ui_FolderWidget(widget, j, toAddress, f, c['count']) subwidget = UiFolderWidget(widget, j, toAddress, f, c['count'])
except KeyError: except KeyError:
subwidget = Ui_FolderWidget(widget, j, toAddress, f, 0) subwidget = UiFolderWidget(widget, j, toAddress, f, 0)
j += 1 j += 1
widget.setUnreadCount(unread) widget.setUnreadCount(unread)
db.pop(toAddress, None) db.pop(toAddress, None)
@ -464,17 +467,19 @@ class MyForm(settingsmixin.SMainWindow):
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 = UiSubscriptionWidget(
treeWidget, i, toAddress, db[toAddress]["inbox"]['count'],
db[toAddress]["inbox"]['label'], db[toAddress]["inbox"]['enabled'])
j = 0 j = 0
unread = 0 unread = 0
for folder in folders: for folder in folders:
try: try:
subwidget = Ui_FolderWidget(widget, j, toAddress, folder, db[toAddress][folder]['count']) subwidget = UiFolderWidget(widget, j, toAddress, folder, db[toAddress][folder]['count'])
unread += db[toAddress][folder]['count'] unread += db[toAddress][folder]['count']
except KeyError: except KeyError:
subwidget = Ui_FolderWidget(widget, j, toAddress, folder, 0) subwidget = UiFolderWidget(widget, j, toAddress, folder, 0)
j += 1 j += 1
widget.setUnreadCount(unread) widget.set_unread_count(unread)
i += 1 i += 1
treeWidget.setSortingEnabled(True) treeWidget.setSortingEnabled(True)
@ -491,7 +496,7 @@ class MyForm(settingsmixin.SMainWindow):
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 = UiFolderWidget.folderWeight.keys()
# sort ascending when creating # sort ascending when creating
if treeWidget.topLevelItemCount() == 0: if treeWidget.topLevelItemCount() == 0:
@ -524,7 +529,9 @@ class MyForm(settingsmixin.SMainWindow):
# get number of (unread) messages # get number of (unread) messages
total = 0 total = 0
queryreturn = sqlQuery('SELECT toaddress, folder, count(msgid) as cnt FROM inbox WHERE read = 0 GROUP BY toaddress, folder') queryreturn = sqlQuery(
'SELECT toaddress, folder, count(msgid) as cnt FROM inbox WHERE read = 0 GROUP BY toaddress, folder'
)
for row in queryreturn: for row in queryreturn:
toaddress, folder, cnt = row toaddress, folder, cnt = row
total += cnt total += cnt
@ -559,7 +566,7 @@ 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.set_unread_count(db[toAddress][subwidget.folderName])
if subwidget.folderName not in ["new", "trash", "sent"]: 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)
@ -575,7 +582,7 @@ class MyForm(settingsmixin.SMainWindow):
for f, c in db[toAddress].iteritems(): for f, c in db[toAddress].iteritems():
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 = UiFolderWidget(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
@ -585,17 +592,17 @@ class MyForm(settingsmixin.SMainWindow):
i = 0 i = 0
for toAddress in db: for toAddress in db:
widget = Ui_AddressWidget(treeWidget, i, toAddress, db[toAddress]["inbox"], enabled[toAddress]) widget = UiAddressWidget(treeWidget, i, toAddress, db[toAddress]["inbox"], enabled[toAddress])
j = 0 j = 0
unread = 0 unread = 0
for folder in folders: for folder in folders:
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 = UiFolderWidget(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.set_unread_count(unread)
i += 1 i += 1
treeWidget.setSortingEnabled(True) treeWidget.setSortingEnabled(True)
@ -612,7 +619,8 @@ class MyForm(settingsmixin.SMainWindow):
addressInKeysFile) addressInKeysFile)
if addressVersionNumber == 1: if addressVersionNumber == 1:
displayMsg = _translate( displayMsg = _translate(
"MainWindow", "One of your addresses, %1, is an old version 1 address. Version 1 addresses are no longer supported. " "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) + "May we delete it now?").arg(addressInKeysFile)
reply = QtGui.QMessageBox.question( reply = QtGui.QMessageBox.question(
self, 'Message', displayMsg, QtGui.QMessageBox.Yes, QtGui.QMessageBox.No) self, 'Message', displayMsg, QtGui.QMessageBox.Yes, QtGui.QMessageBox.No)
@ -626,8 +634,9 @@ class MyForm(settingsmixin.SMainWindow):
# Auto-startup for Windows # Auto-startup for Windows
RUN_PATH = "HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\CurrentVersion\\Run" RUN_PATH = "HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\CurrentVersion\\Run"
self.settings = QtCore.QSettings(RUN_PATH, QtCore.QSettings.NativeFormat) self.settings = QtCore.QSettings(RUN_PATH, QtCore.QSettings.NativeFormat)
self.settings.remove( self.settings.remove("PyBitmessage")
"PyBitmessage") # In case the user moves the program and the registry entry is no longer valid, this will delete the old registry entry. # In case the user moves the program and the registry entry is no longer valid,
# this will delete the old registry entry.
if BMConfigParser().getboolean('bitmessagesettings', 'startonlogon'): if BMConfigParser().getboolean('bitmessagesettings', 'startonlogon'):
self.settings.setValue("PyBitmessage", sys.argv[0]) self.settings.setValue("PyBitmessage", sys.argv[0])
elif 'darwin' in sys.platform: elif 'darwin' in sys.platform:
@ -693,7 +702,7 @@ class MyForm(settingsmixin.SMainWindow):
"itemChanged(QTableWidgetItem *)"), self.tableWidgetAddressBookItemChanged) "itemChanged(QTableWidgetItem *)"), self.tableWidgetAddressBookItemChanged)
# This is necessary for the completer to work if multiple recipients # This is necessary for the completer to work if multiple recipients
QtCore.QObject.connect(self.ui.lineEditTo, QtCore.SIGNAL( QtCore.QObject.connect(self.ui.lineEditTo, QtCore.SIGNAL(
"cursorPositionChanged(int, int)"), self.ui.lineEditTo.completer().onCursorPositionChanged) "cursorPositionChanged(int, int)"), self.ui.lineEditTo.completer().on_cursor_position_changed)
# show messages from message list # show messages from message list
QtCore.QObject.connect(self.ui.tableWidgetInbox, QtCore.SIGNAL( QtCore.QObject.connect(self.ui.tableWidgetInbox, QtCore.SIGNAL(
@ -758,9 +767,11 @@ class MyForm(settingsmixin.SMainWindow):
QtCore.QObject.connect(self.UISignalThread, QtCore.SIGNAL( QtCore.QObject.connect(self.UISignalThread, QtCore.SIGNAL(
"updateSentItemStatusByAckdata(PyQt_PyObject,PyQt_PyObject)"), self.updateSentItemStatusByAckdata) "updateSentItemStatusByAckdata(PyQt_PyObject,PyQt_PyObject)"), self.updateSentItemStatusByAckdata)
QtCore.QObject.connect(self.UISignalThread, QtCore.SIGNAL( QtCore.QObject.connect(self.UISignalThread, QtCore.SIGNAL(
"displayNewInboxMessage(PyQt_PyObject,PyQt_PyObject,PyQt_PyObject,PyQt_PyObject,PyQt_PyObject)"), self.displayNewInboxMessage) "displayNewInboxMessage(PyQt_PyObject,PyQt_PyObject,PyQt_PyObject,PyQt_PyObject,PyQt_PyObject)"),
self.displayNewInboxMessage)
QtCore.QObject.connect(self.UISignalThread, QtCore.SIGNAL( QtCore.QObject.connect(self.UISignalThread, QtCore.SIGNAL(
"displayNewSentMessage(PyQt_PyObject,PyQt_PyObject,PyQt_PyObject,PyQt_PyObject,PyQt_PyObject,PyQt_PyObject)"), self.displayNewSentMessage) "displayNewSentMessage(PyQt_PyObject,PyQt_PyObject,PyQt_PyObject,PyQt_PyObject,PyQt_PyObject,PyQt_PyObject)"
), self.displayNewSentMessage)
QtCore.QObject.connect(self.UISignalThread, QtCore.SIGNAL( QtCore.QObject.connect(self.UISignalThread, QtCore.SIGNAL(
"setStatusIcon(PyQt_PyObject)"), self.setStatusIcon) "setStatusIcon(PyQt_PyObject)"), self.setStatusIcon)
QtCore.QObject.connect(self.UISignalThread, QtCore.SIGNAL( QtCore.QObject.connect(self.UISignalThread, QtCore.SIGNAL(
@ -838,7 +849,8 @@ class MyForm(settingsmixin.SMainWindow):
font.setBold(True) font.setBold(True)
else: else:
numberOfDays = int(round(TTL / (24*60*60))) numberOfDays = int(round(TTL / (24*60*60)))
self.ui.labelHumanFriendlyTTLDescription.setText(_translate("MainWindow", "%n day(s)", None, QtCore.QCoreApplication.CodecForTr, numberOfDays)) self.ui.labelHumanFriendlyTTLDescription.setText(_translate(
"MainWindow", "%n day(s)", None, QtCore.QCoreApplication.CodecForTr, numberOfDays))
font.setBold(False) font.setBold(False)
self.ui.labelHumanFriendlyTTLDescription.setStyleSheet(stylesheet) self.ui.labelHumanFriendlyTTLDescription.setStyleSheet(stylesheet)
self.ui.labelHumanFriendlyTTLDescription.setFont(font) self.ui.labelHumanFriendlyTTLDescription.setFont(font)
@ -957,7 +969,7 @@ class MyForm(settingsmixin.SMainWindow):
font.setBold(not status) font.setBold(not status)
widget.item(row, 3).setFont(font) widget.item(row, 3).setFont(font)
for col in (0, 1, 2): for col in (0, 1, 2):
widget.item(row, col).setUnread(not status) widget.item(row, col).set_unread(not status)
try: try:
related.item(rrow, 3).setFont(font) related.item(rrow, 3).setFont(font)
@ -965,7 +977,7 @@ class MyForm(settingsmixin.SMainWindow):
pass pass
else: else:
for col in (0, 1, 2): for col in (0, 1, 2):
related.item(rrow, col).setUnread(not status) related.item(rrow, col).set_unread(not status)
# Here we need to update unread count for: # Here we need to update unread count for:
# - all widgets if there is no args # - all widgets if there is no args
@ -1023,7 +1035,7 @@ class MyForm(settingsmixin.SMainWindow):
except KeyError: except KeyError:
newCount = 0 newCount = 0
if newCount != addressItem.unreadCount: if newCount != addressItem.unreadCount:
addressItem.setUnreadCount(newCount) addressItem.set_unread_count(newCount)
for j in range(addressItem.childCount()): for j in range(addressItem.childCount()):
folderItem = addressItem.child(j) folderItem = addressItem.child(j)
folderName = folderItem.folderName folderName = folderItem.folderName
@ -1043,7 +1055,7 @@ class MyForm(settingsmixin.SMainWindow):
except KeyError: except KeyError:
newCount = 0 newCount = 0
if newCount != folderItem.unreadCount: if newCount != folderItem.unreadCount:
folderItem.setUnreadCount(newCount) folderItem.set_unread_count(newCount)
def addMessageListItem(self, tableWidget, items): def addMessageListItem(self, tableWidget, items):
sortingEnabled = tableWidget.isSortingEnabled() sortingEnabled = tableWidget.isSortingEnabled()
@ -1062,9 +1074,9 @@ class MyForm(settingsmixin.SMainWindow):
acct.parseMessage(toAddress, fromAddress, subject, "") acct.parseMessage(toAddress, fromAddress, subject, "")
items = [] items = []
MessageList_AddressWidget(items, str(toAddress), unicode(acct.toLabel, 'utf-8')) MessageListAddressWidget(items, str(toAddress), unicode(acct.toLabel, 'utf-8'))
MessageList_AddressWidget(items, str(fromAddress), unicode(acct.fromLabel, 'utf-8')) MessageListAddressWidget(items, str(fromAddress), unicode(acct.fromLabel, 'utf-8'))
MessageList_SubjectWidget(items, str(subject), unicode(acct.subject, 'utf-8', 'replace')) MessageListSubjectWidget(items, str(subject), unicode(acct.subject, 'utf-8', 'replace'))
if status == 'awaitingpubkey': if status == 'awaitingpubkey':
statusText = _translate( statusText = _translate(
@ -1097,10 +1109,14 @@ 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(
"MainWindow",
"Problem: The work demanded by the recipient is more difficult than you are willing to do. %1").arg(
l10n.formatTimestamp(lastactiontime)) 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(
"MainWindow",
"Problem: The recipient\'s encryption key is no good. Could not encrypt message. %1").arg(
l10n.formatTimestamp(lastactiontime)) l10n.formatTimestamp(lastactiontime))
elif status == 'forcepow': elif status == 'forcepow':
statusText = _translate( statusText = _translate(
@ -1133,11 +1149,11 @@ class MyForm(settingsmixin.SMainWindow):
items = [] items = []
#to #to
MessageList_AddressWidget(items, toAddress, unicode(acct.toLabel, 'utf-8'), not read) MessageListAddressWidget(items, toAddress, unicode(acct.toLabel, 'utf-8'), not read)
# from # from
MessageList_AddressWidget(items, fromAddress, unicode(acct.fromLabel, 'utf-8'), not read) MessageListAddressWidget(items, fromAddress, unicode(acct.fromLabel, 'utf-8'), not read)
# subject # subject
MessageList_SubjectWidget(items, str(subject), unicode(acct.subject, 'utf-8', 'replace'), not read) MessageListSubjectWidget(items, str(subject), unicode(acct.subject, 'utf-8', 'replace'), not read)
# time received # time received
time_item = myTableWidgetItem(l10n.formatTimestamp(received)) time_item = myTableWidgetItem(l10n.formatTimestamp(received))
time_item.setToolTip(l10n.formatTimestamp(received)) time_item.setToolTip(l10n.formatTimestamp(received))
@ -1492,35 +1508,53 @@ class MyForm(settingsmixin.SMainWindow):
# the same directory as this program. It is important that you # the same directory as this program. It is important that you
# back up this file.', QMessageBox.Ok) # back up this file.', QMessageBox.Ok)
reply = QtGui.QMessageBox.information(self, 'keys.dat?', _translate( 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) "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)
else: else:
QtGui.QMessageBox.information(self, 'keys.dat?', _translate( 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) "MainWindow",
"You may manage your keys by editing the keys.dat file stored in\n %1 \n"
"It is important that you back up this file.").arg(state.appdata), QtGui.QMessageBox.Ok)
elif sys.platform == 'win32' or sys.platform == 'win64': elif sys.platform == 'win32' or sys.platform == 'win64':
if state.appdata == '': if state.appdata == '':
reply = QtGui.QMessageBox.question(self, _translate("MainWindow", "Open keys.dat?"), _translate( 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) "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)
else: else:
reply = QtGui.QMessageBox.question(self, _translate("MainWindow", "Open keys.dat?"), _translate( 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) "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: if reply == QtGui.QMessageBox.Yes:
shared.openKeysFile() shared.openKeysFile()
# menu button 'delete all treshed messages' # menu button 'delete all treshed messages'
def click_actionDeleteAllTrashedMessages(self): 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 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:
return return
sqlStoredProcedure('deleteandvacuume') sqlStoredProcedure('deleteandvacuume')
self.rerenderTabTreeMessages() self.rerenderTabTreeMessages()
self.rerenderTabTreeSubscriptions() self.rerenderTabTreeSubscriptions()
self.rerenderTabTreeChans() self.rerenderTabTreeChans()
if self.getCurrentFolder(self.ui.treeWidgetYourIdentities) == "trash": if self.getCurrentFolder(self.ui.treeWidgetYourIdentities) == "trash":
self.loadMessagelist(self.ui.tableWidgetInbox, self.getCurrentAccount(self.ui.treeWidgetYourIdentities), "trash") self.loadMessagelist(self.ui.tableWidgetInbox,
self.getCurrentAccount(self.ui.treeWidgetYourIdentities), "trash")
elif self.getCurrentFolder(self.ui.treeWidgetSubscriptions) == "trash": elif self.getCurrentFolder(self.ui.treeWidgetSubscriptions) == "trash":
self.loadMessagelist(self.ui.tableWidgetInboxSubscriptions, self.getCurrentAccount(self.ui.treeWidgetSubscriptions), "trash") self.loadMessagelist(self.ui.tableWidgetInboxSubscriptions,
self.getCurrentAccount(self.ui.treeWidgetSubscriptions), "trash")
elif self.getCurrentFolder(self.ui.treeWidgetChans) == "trash": elif self.getCurrentFolder(self.ui.treeWidgetChans) == "trash":
self.loadMessagelist(self.ui.tableWidgetInboxChans, self.getCurrentAccount(self.ui.treeWidgetChans), "trash") self.loadMessagelist(self.ui.tableWidgetInboxChans,
self.getCurrentAccount(self.ui.treeWidgetChans), "trash")
# menu button 'regenerate deterministic addresses' # menu button 'regenerate deterministic addresses'
def click_actionRegenerateDeterministicAddresses(self): def click_actionRegenerateDeterministicAddresses(self):
@ -1650,7 +1684,9 @@ class MyForm(settingsmixin.SMainWindow):
"MainWindow", "Not Connected")) "MainWindow", "Not Connected"))
self.setTrayIconFile("can-icon-24px-red.png") self.setTrayIconFile("can-icon-24px-red.png")
if color == 'yellow': if color == 'yellow':
if self.statusbar.currentMessage() == 'Warning: You are currently not connected. Bitmessage will do the work necessary to send the message but it won\'t send until you connect.': if self.statusbar.currentMessage() == 'Warning: You are currently not connected. ' \
'Bitmessage will do the work necessary to send the ' \
'message but it won\'t send until you connect.':
self.statusbar.clearMessage() self.statusbar.clearMessage()
self.pushButtonStatusIcon.setIcon( self.pushButtonStatusIcon.setIcon(
QtGui.QIcon(":/newPrefix/images/yellowicon.png")) QtGui.QIcon(":/newPrefix/images/yellowicon.png"))
@ -1668,7 +1704,9 @@ class MyForm(settingsmixin.SMainWindow):
"MainWindow", "Connected")) "MainWindow", "Connected"))
self.setTrayIconFile("can-icon-24px-yellow.png") self.setTrayIconFile("can-icon-24px-yellow.png")
if color == 'green': if color == 'green':
if self.statusbar.currentMessage() == 'Warning: You are currently not connected. Bitmessage will do the work necessary to send the message but it won\'t send until you connect.': if self.statusbar.currentMessage() == 'Warning: You are currently not connected. ' \
'Bitmessage will do the work necessary to send the ' \
'message but it won\'t send until you connect.':
self.statusbar.clearMessage() self.statusbar.clearMessage()
self.pushButtonStatusIcon.setIcon( self.pushButtonStatusIcon.setIcon(
QtGui.QIcon(":/newPrefix/images/greenicon.png")) QtGui.QIcon(":/newPrefix/images/greenicon.png"))
@ -1751,7 +1789,8 @@ class MyForm(settingsmixin.SMainWindow):
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()):
@ -1760,7 +1799,9 @@ class MyForm(settingsmixin.SMainWindow):
sent.item(i, 3).setToolTip(textToDisplay) sent.item(i, 3).setToolTip(textToDisplay)
try: try:
newlinePosition = textToDisplay.indexOf('\n') 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. 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 = 0 newlinePosition = 0
if newlinePosition > 1: if newlinePosition > 1:
sent.item(i, 3).setText( sent.item(i, 3).setText(
@ -1786,7 +1827,9 @@ class MyForm(settingsmixin.SMainWindow):
sent.item(i, 3).setToolTip(textToDisplay) sent.item(i, 3).setToolTip(textToDisplay)
try: try:
newlinePosition = textToDisplay.indexOf('\n') 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. 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 = 0 newlinePosition = 0
if newlinePosition > 1: if newlinePosition > 1:
sent.item(i, 3).setText( sent.item(i, 3).setText(
@ -1833,21 +1876,23 @@ class MyForm(settingsmixin.SMainWindow):
os._exit(0) os._exit(0)
def rerenderMessagelistFromLabels(self): 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()): for i in range(messagelist.rowCount()):
messagelist.item(i, 1).setLabel() messagelist.item(i, 1).set_label()
def rerenderMessagelistToLabels(self): 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()): for i in range(messagelist.rowCount()):
messagelist.item(i, 0).setLabel() messagelist.item(i, 0).set_label()
def rerenderAddressBook(self): def rerenderAddressBook(self):
def addRow (address, label, type): def addRow (address, label, type):
self.ui.tableWidgetAddressBook.insertRow(0) self.ui.tableWidgetAddressBook.insertRow(0)
newItem = Ui_AddressBookWidgetItemLabel(address, unicode(label, 'utf-8'), type) newItem = UiAddressBookWidgetItemLabel(address, unicode(label, 'utf-8'), type)
self.ui.tableWidgetAddressBook.setItem(0, 0, newItem) self.ui.tableWidgetAddressBook.setItem(0, 0, newItem)
newItem = Ui_AddressBookWidgetItemAddress(address, unicode(label, 'utf-8'), type) newItem = UiAddressBookWidgetItemAddress(address, unicode(label, 'utf-8'), type)
self.ui.tableWidgetAddressBook.setItem(0, 1, newItem) self.ui.tableWidgetAddressBook.setItem(0, 1, newItem)
oldRows = {} oldRows = {}
@ -1903,7 +1948,8 @@ class MyForm(settingsmixin.SMainWindow):
"MainWindow", """The TTL, or Time-To-Live is the length of time that the network will hold the message. "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 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 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."""),
QtGui.QMessageBox.Ok)
def click_pushButtonClear(self): def click_pushButtonClear(self):
self.ui.lineEditSubject.setText("") self.ui.lineEditSubject.setText("")
@ -1959,8 +2005,9 @@ class MyForm(settingsmixin.SMainWindow):
if sendMessageToPeople: # To send a message to specific people (rather than broadcast) if sendMessageToPeople: # To send a message to specific people (rather than broadcast)
toAddressesList = [s.strip() toAddressesList = [s.strip()
for s in toAddresses.replace(',', ';').split(';')] for s in toAddresses.replace(',', ';').split(';')]
toAddressesList = list(set( toAddressesList = list(set(toAddressesList))
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
@ -1973,14 +2020,19 @@ class MyForm(settingsmixin.SMainWindow):
subject = acct.subject subject = acct.subject
toAddress = acct.toAddress toAddress = acct.toAddress
else: else:
if QtGui.QMessageBox.question(self, "Sending an email?", _translate("MainWindow", if QtGui.QMessageBox.question(
"You are trying to send an email instead of a bitmessage. This requires registering with a gateway. Attempt to register?"), self, "Sending an email?",
QtGui.QMessageBox.Yes|QtGui.QMessageBox.No) != QtGui.QMessageBox.Yes: _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:
continue continue
email = acct.getLabel() email = acct.getLabel()
if email[-14:] != "@mailchuck.com": #attempt register if email[-14:] != "@mailchuck.com": #attempt register
# 12 character random email address # 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))
email += "@mailchuck.com"
acct = MailchuckAccount(fromAddress) acct = MailchuckAccount(fromAddress)
acct.register(email) acct.register(email)
BMConfigParser().set(fromAddress, 'label', email) BMConfigParser().set(fromAddress, 'label', email)
@ -2071,12 +2123,18 @@ class MyForm(settingsmixin.SMainWindow):
toAddress = addBMIfNotPresent(toAddress) toAddress = addBMIfNotPresent(toAddress)
if addressVersionNumber > 4 or addressVersionNumber <= 1: if addressVersionNumber > 4 or addressVersionNumber <= 1:
QtGui.QMessageBox.about(self, _translate("MainWindow", "Address version number"), _translate( QtGui.QMessageBox.about(self, _translate("MainWindow", "Address version number"),
"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))) _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)))
continue continue
if streamNumber > 1 or streamNumber == 0: if streamNumber > 1 or streamNumber == 0:
QtGui.QMessageBox.about(self, _translate("MainWindow", "Stream number"), _translate( 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))) "MainWindow",
"Concerning the address %1, Bitmessage cannot handle stream numbers of %2."
" Perhaps upgrade Bitmessage to the latest version."
).arg(toAddress).arg(str(streamNumber)))
continue continue
self.statusbar.clearMessage() self.statusbar.clearMessage()
if shared.statusIconColor == 'red': if shared.statusIconColor == 'red':
@ -2220,8 +2278,8 @@ class MyForm(settingsmixin.SMainWindow):
def rerenderComboBoxSendFrom(self): def rerenderComboBoxSendFrom(self):
self.ui.comboBoxSendFrom.clear() self.ui.comboBoxSendFrom.clear()
for addressInKeysFile in getSortedAccounts(): for addressInKeysFile in getSortedAccounts():
isEnabled = BMConfigParser().getboolean( isEnabled = BMConfigParser().getboolean(addressInKeysFile, 'enabled')
addressInKeysFile, 'enabled') # I realize that this is poor programming practice but I don't care. It's easier for others to read. # I realize that this is poor programming practice but I don't care. It's easier for others to read.
isMaillinglist = BMConfigParser().safeGetBoolean(addressInKeysFile, 'mailinglist') isMaillinglist = BMConfigParser().safeGetBoolean(addressInKeysFile, 'mailinglist')
if isEnabled and not isMaillinglist: if isEnabled and not isMaillinglist:
label = unicode(BMConfigParser().get(addressInKeysFile, 'label'), 'utf-8', 'ignore').strip() label = unicode(BMConfigParser().get(addressInKeysFile, 'label'), 'utf-8', 'ignore').strip()
@ -2233,7 +2291,7 @@ class MyForm(settingsmixin.SMainWindow):
address = str(self.ui.comboBoxSendFrom.itemData( address = str(self.ui.comboBoxSendFrom.itemData(
i, QtCore.Qt.UserRole).toString()) i, QtCore.Qt.UserRole).toString())
self.ui.comboBoxSendFrom.setItemData( self.ui.comboBoxSendFrom.setItemData(
i, AccountColor(address).accountColor(), i, AccountColor(address).account_color(),
QtCore.Qt.ForegroundRole) QtCore.Qt.ForegroundRole)
self.ui.comboBoxSendFrom.insertItem(0, '', '') self.ui.comboBoxSendFrom.insertItem(0, '', '')
if(self.ui.comboBoxSendFrom.count() == 2): if(self.ui.comboBoxSendFrom.count() == 2):
@ -2244,8 +2302,8 @@ class MyForm(settingsmixin.SMainWindow):
def rerenderComboBoxSendFromBroadcast(self): def rerenderComboBoxSendFromBroadcast(self):
self.ui.comboBoxSendFromBroadcast.clear() self.ui.comboBoxSendFromBroadcast.clear()
for addressInKeysFile in getSortedAccounts(): for addressInKeysFile in getSortedAccounts():
isEnabled = BMConfigParser().getboolean( isEnabled = BMConfigParser().getboolean(addressInKeysFile, 'enabled')
addressInKeysFile, 'enabled') # I realize that this is poor programming practice but I don't care. It's easier for others to read. # I realize that this is poor programming practice but I don't care. It's easier for others to read.
isChan = BMConfigParser().safeGetBoolean(addressInKeysFile, 'chan') isChan = BMConfigParser().safeGetBoolean(addressInKeysFile, 'chan')
if isEnabled and not isChan: if isEnabled and not isChan:
label = unicode(BMConfigParser().get(addressInKeysFile, 'label'), 'utf-8', 'ignore').strip() label = unicode(BMConfigParser().get(addressInKeysFile, 'label'), 'utf-8', 'ignore').strip()
@ -2256,7 +2314,7 @@ class MyForm(settingsmixin.SMainWindow):
address = str(self.ui.comboBoxSendFromBroadcast.itemData( address = str(self.ui.comboBoxSendFromBroadcast.itemData(
i, QtCore.Qt.UserRole).toString()) i, QtCore.Qt.UserRole).toString())
self.ui.comboBoxSendFromBroadcast.setItemData( self.ui.comboBoxSendFromBroadcast.setItemData(
i, AccountColor(address).accountColor(), i, AccountColor(address).account_color(),
QtCore.Qt.ForegroundRole) QtCore.Qt.ForegroundRole)
self.ui.comboBoxSendFromBroadcast.insertItem(0, '', '') self.ui.comboBoxSendFromBroadcast.insertItem(0, '', '')
if(self.ui.comboBoxSendFromBroadcast.count() == 2): if(self.ui.comboBoxSendFromBroadcast.count() == 2):
@ -2279,11 +2337,15 @@ class MyForm(settingsmixin.SMainWindow):
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(sent, toAddress, fromAddress, subject, "msgqueued", ackdata, time.time())
@ -2303,12 +2365,20 @@ class MyForm(settingsmixin.SMainWindow):
if tab == 1: if tab == 1:
tab = 2 tab = 2
tableWidget = self.widgetConvert(treeWidget) 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 continue
if tableWidget == inbox and self.getCurrentAccount(treeWidget) == acct.address and self.getCurrentFolder(treeWidget) in ["inbox", None]: if tableWidget == inbox and \
ret = self.addMessageListItemInbox(inbox, "inbox", inventoryHash, toAddress, fromAddress, subject, time.time(), 0) self.getCurrentAccount(treeWidget) == acct.address and \
elif treeWidget == self.ui.treeWidgetYourIdentities and self.getCurrentAccount(treeWidget) is None and self.getCurrentFolder(treeWidget) in ["inbox", "new", None]: self.getCurrentFolder(treeWidget) in ["inbox", None]:
ret = self.addMessageListItemInbox(tableWidget, "inbox", inventoryHash, toAddress, fromAddress, subject, time.time(), 0) 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: if ret is None:
acct.parseMessage(toAddress, fromAddress, subject, "") acct.parseMessage(toAddress, fromAddress, subject, "")
else: else:
@ -2323,7 +2393,9 @@ 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 (
(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 # Ubuntu should notify of new message irespective 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)
@ -2449,29 +2521,40 @@ class MyForm(settingsmixin.SMainWindow):
BMConfigParser().set('bitmessagesettings', 'replybelow', str( BMConfigParser().set('bitmessagesettings', 'replybelow', str(
self.settingsDialogInstance.ui.checkBoxReplyBelow.isChecked())) self.settingsDialogInstance.ui.checkBoxReplyBelow.isChecked()))
lang = str(self.settingsDialogInstance.ui.languageComboBox.itemData(self.settingsDialogInstance.ui.languageComboBox.currentIndex()).toString()) lang = str(
self.settingsDialogInstance.ui.languageComboBox.itemData(
self.settingsDialogInstance.ui.languageComboBox.currentIndex()).toString())
BMConfigParser().set('bitmessagesettings', 'userlocale', lang) BMConfigParser().set('bitmessagesettings', 'userlocale', lang)
change_translation(l10n.getTranslationLanguage()) change_translation(l10n.getTranslationLanguage())
if int(BMConfigParser().get('bitmessagesettings', 'port')) != int(self.settingsDialogInstance.ui.lineEditTCPPort.text()): if int(BMConfigParser().get('bitmessagesettings', 'port')) != \
int(self.settingsDialogInstance.ui.lineEditTCPPort.text()):
if not BMConfigParser().safeGetBoolean('bitmessagesettings', 'dontconnect'): if not BMConfigParser().safeGetBoolean('bitmessagesettings', 'dontconnect'):
QtGui.QMessageBox.about(self, _translate("MainWindow", "Restart"), _translate( QtGui.QMessageBox.about(self, _translate("MainWindow", "Restart"), _translate(
"MainWindow", "You must restart Bitmessage for the port number change to take effect.")) "MainWindow", "You must restart Bitmessage for the port number change to take effect."))
BMConfigParser().set('bitmessagesettings', 'port', str( BMConfigParser().set('bitmessagesettings', 'port', str(
self.settingsDialogInstance.ui.lineEditTCPPort.text())) self.settingsDialogInstance.ui.lineEditTCPPort.text()))
if self.settingsDialogInstance.ui.checkBoxUPnP.isChecked() != BMConfigParser().safeGetBoolean('bitmessagesettings', 'upnp'): if self.settingsDialogInstance.ui.checkBoxUPnP.isChecked() != BMConfigParser().safeGetBoolean(
BMConfigParser().set('bitmessagesettings', 'upnp', str(self.settingsDialogInstance.ui.checkBoxUPnP.isChecked())) 'bitmessagesettings', 'upnp'):
BMConfigParser().set('bitmessagesettings', 'upnp',
str(self.settingsDialogInstance.ui.checkBoxUPnP.isChecked()))
if self.settingsDialogInstance.ui.checkBoxUPnP.isChecked(): if self.settingsDialogInstance.ui.checkBoxUPnP.isChecked():
import upnp import upnp
upnpThread = upnp.uPnPThread() upnpThread = upnp.uPnPThread()
upnpThread.start() upnpThread.start()
#print 'self.settingsDialogInstance.ui.comboBoxProxyType.currentText()', self.settingsDialogInstance.ui.comboBoxProxyType.currentText() #print 'self.settingsDialogInstance.ui.comboBoxProxyType.currentText()',
#print 'self.settingsDialogInstance.ui.comboBoxProxyType.currentText())[0:5]', self.settingsDialogInstance.ui.comboBoxProxyType.currentText()[0:5] # self.settingsDialogInstance.ui.comboBoxProxyType.currentText()
if BMConfigParser().get('bitmessagesettings', 'socksproxytype') == 'none' and self.settingsDialogInstance.ui.comboBoxProxyType.currentText()[0:5] == 'SOCKS': #print 'self.settingsDialogInstance.ui.comboBoxProxyType.currentText())[0:5]',
# self.settingsDialogInstance.ui.comboBoxProxyType.currentText()[0:5]
if BMConfigParser().get('bitmessagesettings', 'socksproxytype') == 'none' \
and self.settingsDialogInstance.ui.comboBoxProxyType.currentText()[0:5] == 'SOCKS':
if shared.statusIconColor != 'red': if shared.statusIconColor != 'red':
QtGui.QMessageBox.about(self, _translate("MainWindow", "Restart"), _translate( QtGui.QMessageBox.about(self, _translate("MainWindow", "Restart"), _translate(
"MainWindow", "Bitmessage will use your proxy from now on but you may want to manually restart Bitmessage now to close existing connections (if any).")) "MainWindow",
if BMConfigParser().get('bitmessagesettings', 'socksproxytype')[0:5] == 'SOCKS' and self.settingsDialogInstance.ui.comboBoxProxyType.currentText()[0:5] != 'SOCKS': "Bitmessage will use your proxy from now on but you may want to manually restart "
"Bitmessage now to close existing connections (if any)."))
if BMConfigParser().get('bitmessagesettings', 'socksproxytype')[0:5] == 'SOCKS' and \
self.settingsDialogInstance.ui.comboBoxProxyType.currentText()[0:5] != 'SOCKS':
self.statusbar.clearMessage() self.statusbar.clearMessage()
state.resetNetworkProtocolAvailability() # just in case we changed something in the network connectivity state.resetNetworkProtocolAvailability() # just in case we changed something in the network connectivity
if self.settingsDialogInstance.ui.comboBoxProxyType.currentText()[0:5] == 'SOCKS': if self.settingsDialogInstance.ui.comboBoxProxyType.currentText()[0:5] == 'SOCKS':
@ -2508,7 +2591,7 @@ class MyForm(settingsmixin.SMainWindow):
int(float(self.settingsDialogInstance.ui.lineEditMaxOutboundConnections.text())))) int(float(self.settingsDialogInstance.ui.lineEditMaxOutboundConnections.text()))))
BMConfigParser().set('bitmessagesettings', 'namecoinrpctype', BMConfigParser().set('bitmessagesettings', 'namecoinrpctype',
self.settingsDialogInstance.getNamecoinType()) self.settingsDialogInstance.get_namecoin_type())
BMConfigParser().set('bitmessagesettings', 'namecoinrpchost', str( BMConfigParser().set('bitmessagesettings', 'namecoinrpchost', str(
self.settingsDialogInstance.ui.lineEditNamecoinHost.text())) self.settingsDialogInstance.ui.lineEditNamecoinHost.text()))
BMConfigParser().set('bitmessagesettings', 'namecoinrpcport', str( BMConfigParser().set('bitmessagesettings', 'namecoinrpcport', str(
@ -2522,31 +2605,43 @@ class MyForm(settingsmixin.SMainWindow):
# Demanded difficulty tab # Demanded difficulty tab
if float(self.settingsDialogInstance.ui.lineEditTotalDifficulty.text()) >= 1: if float(self.settingsDialogInstance.ui.lineEditTotalDifficulty.text()) >= 1:
BMConfigParser().set('bitmessagesettings', 'defaultnoncetrialsperbyte', str(int(float( BMConfigParser().set('bitmessagesettings', 'defaultnoncetrialsperbyte', str(int(float(
self.settingsDialogInstance.ui.lineEditTotalDifficulty.text()) * defaults.networkDefaultProofOfWorkNonceTrialsPerByte))) self.settingsDialogInstance.ui.lineEditTotalDifficulty.text()
) * defaults.networkDefaultProofOfWorkNonceTrialsPerByte)))
if float(self.settingsDialogInstance.ui.lineEditSmallMessageDifficulty.text()) >= 1: if float(self.settingsDialogInstance.ui.lineEditSmallMessageDifficulty.text()) >= 1:
BMConfigParser().set('bitmessagesettings', 'defaultpayloadlengthextrabytes', str(int(float( BMConfigParser().set('bitmessagesettings', 'defaultpayloadlengthextrabytes', str(int(float(
self.settingsDialogInstance.ui.lineEditSmallMessageDifficulty.text()) * defaults.networkDefaultPayloadLengthExtraBytes))) self.settingsDialogInstance.ui.lineEditSmallMessageDifficulty.text()
) * defaults.networkDefaultPayloadLengthExtraBytes)))
if self.settingsDialogInstance.ui.comboBoxOpenCL.currentText().toUtf8() != BMConfigParser().safeGet("bitmessagesettings", "opencl"): if self.settingsDialogInstance.ui.comboBoxOpenCL.currentText().toUtf8() != BMConfigParser().safeGet(
BMConfigParser().set('bitmessagesettings', 'opencl', str(self.settingsDialogInstance.ui.comboBoxOpenCL.currentText())) "bitmessagesettings", "opencl"):
BMConfigParser().set('bitmessagesettings', 'opencl',
str(self.settingsDialogInstance.ui.comboBoxOpenCL.currentText()))
queues.workerQueue.put(('resetPoW', '')) queues.workerQueue.put(('resetPoW', ''))
acceptableDifficultyChanged = False acceptableDifficultyChanged = False
if float(self.settingsDialogInstance.ui.lineEditMaxAcceptableTotalDifficulty.text()) >= 1 or float(self.settingsDialogInstance.ui.lineEditMaxAcceptableTotalDifficulty.text()) == 0: if float(self.settingsDialogInstance.ui.lineEditMaxAcceptableTotalDifficulty.text()) >= 1 \
or float(self.settingsDialogInstance.ui.lineEditMaxAcceptableTotalDifficulty.text()) == 0:
if BMConfigParser().get('bitmessagesettings','maxacceptablenoncetrialsperbyte') != str(int(float( if BMConfigParser().get('bitmessagesettings','maxacceptablenoncetrialsperbyte') != str(int(float(
self.settingsDialogInstance.ui.lineEditMaxAcceptableTotalDifficulty.text()) * defaults.networkDefaultProofOfWorkNonceTrialsPerByte)): self.settingsDialogInstance.ui.lineEditMaxAcceptableTotalDifficulty.text()
) * defaults.networkDefaultProofOfWorkNonceTrialsPerByte)):
# the user changed the max acceptable total difficulty # the user changed the max acceptable total difficulty
acceptableDifficultyChanged = True acceptableDifficultyChanged = True
BMConfigParser().set('bitmessagesettings', 'maxacceptablenoncetrialsperbyte', str(int(float( BMConfigParser().set('bitmessagesettings', 'maxacceptablenoncetrialsperbyte', str(int(float(
self.settingsDialogInstance.ui.lineEditMaxAcceptableTotalDifficulty.text()) * defaults.networkDefaultProofOfWorkNonceTrialsPerByte))) self.settingsDialogInstance.ui.lineEditMaxAcceptableTotalDifficulty.text()
if float(self.settingsDialogInstance.ui.lineEditMaxAcceptableSmallMessageDifficulty.text()) >= 1 or float(self.settingsDialogInstance.ui.lineEditMaxAcceptableSmallMessageDifficulty.text()) == 0: ) * defaults.networkDefaultProofOfWorkNonceTrialsPerByte)))
if float(self.settingsDialogInstance.ui.lineEditMaxAcceptableSmallMessageDifficulty.text()) >= 1 \
or float(self.settingsDialogInstance.ui.lineEditMaxAcceptableSmallMessageDifficulty.text()) == 0:
if BMConfigParser().get('bitmessagesettings','maxacceptablepayloadlengthextrabytes') != str(int(float( if BMConfigParser().get('bitmessagesettings','maxacceptablepayloadlengthextrabytes') != str(int(float(
self.settingsDialogInstance.ui.lineEditMaxAcceptableSmallMessageDifficulty.text()) * defaults.networkDefaultPayloadLengthExtraBytes)): self.settingsDialogInstance.ui.lineEditMaxAcceptableSmallMessageDifficulty.text()
) * defaults.networkDefaultPayloadLengthExtraBytes)):
# the user changed the max acceptable small message difficulty # the user changed the max acceptable small message difficulty
acceptableDifficultyChanged = True acceptableDifficultyChanged = True
BMConfigParser().set('bitmessagesettings', 'maxacceptablepayloadlengthextrabytes', str(int(float( BMConfigParser().set('bitmessagesettings', 'maxacceptablepayloadlengthextrabytes', str(int(float(
self.settingsDialogInstance.ui.lineEditMaxAcceptableSmallMessageDifficulty.text()) * defaults.networkDefaultPayloadLengthExtraBytes))) self.settingsDialogInstance.ui.lineEditMaxAcceptableSmallMessageDifficulty.text()
) * defaults.networkDefaultPayloadLengthExtraBytes)))
if acceptableDifficultyChanged: if acceptableDifficultyChanged:
# It might now be possible to send msgs which were previously marked as toodifficult. # It might now be possible to send msgs which were previously marked as toodifficult.
# Let us change them to 'msgqueued'. The singleWorker will try to send them and will again # Let us change them to 'msgqueued'. The singleWorker will try to send them and will again
@ -2557,7 +2652,9 @@ class MyForm(settingsmixin.SMainWindow):
#start:UI setting to stop trying to send messages after X days/months #start:UI setting to stop trying to send messages after X days/months
# I'm open to changing this UI to something else if someone has a better idea. # I'm open to changing this UI to something else if someone has a better idea.
if ((self.settingsDialogInstance.ui.lineEditDays.text()=='') and (self.settingsDialogInstance.ui.lineEditMonths.text()=='')):#We need to handle this special case. Bitmessage has its default behavior. The input is blank/blank if ((self.settingsDialogInstance.ui.lineEditDays.text()=='') and
(self.settingsDialogInstance.ui.lineEditMonths.text()=='')):
# We need to handle this special case. Bitmessage has its default behavior. The input is blank/blank
BMConfigParser().set('bitmessagesettings', 'stopresendingafterxdays', '') BMConfigParser().set('bitmessagesettings', 'stopresendingafterxdays', '')
BMConfigParser().set('bitmessagesettings', 'stopresendingafterxmonths', '') BMConfigParser().set('bitmessagesettings', 'stopresendingafterxmonths', '')
shared.maximumLengthOfTimeToBotherResendingMessages = float('inf') shared.maximumLengthOfTimeToBotherResendingMessages = float('inf')
@ -2576,11 +2673,18 @@ class MyForm(settingsmixin.SMainWindow):
if lineEditMonthsIsValidFloat and not lineEditDaysIsValidFloat: if lineEditMonthsIsValidFloat and not lineEditDaysIsValidFloat:
self.settingsDialogInstance.ui.lineEditDays.setText("0") self.settingsDialogInstance.ui.lineEditDays.setText("0")
if lineEditDaysIsValidFloat or lineEditMonthsIsValidFloat: if lineEditDaysIsValidFloat or lineEditMonthsIsValidFloat:
if (float(self.settingsDialogInstance.ui.lineEditDays.text()) >=0 and float(self.settingsDialogInstance.ui.lineEditMonths.text()) >=0): if (float(self.settingsDialogInstance.ui.lineEditDays.text()) >=0 and
shared.maximumLengthOfTimeToBotherResendingMessages = (float(str(self.settingsDialogInstance.ui.lineEditDays.text())) * 24 * 60 * 60) + (float(str(self.settingsDialogInstance.ui.lineEditMonths.text())) * (60 * 60 * 24 *365)/12) float(self.settingsDialogInstance.ui.lineEditMonths.text()) >=0):
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. shared.maximumLengthOfTimeToBotherResendingMessages = (float(
str(self.settingsDialogInstance.ui.lineEditDays.text())) * 24 * 60 * 60) + (float(
str(self.settingsDialogInstance.ui.lineEditMonths.text())) * (60 * 60 * 24 *365)/12)
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(self, _translate("MainWindow", "Will not resend ever"), _translate( QtGui.QMessageBox.about(self, _translate("MainWindow", "Will not resend ever"), _translate(
"MainWindow", "Note that the time limit you entered is less than the amount of time Bitmessage waits for the first resend attempt therefore your messages will never be resent.")) "MainWindow",
"Note that the time limit you entered is less than the amount of time Bitmessage waits "
"for the first resend attempt therefore your messages will never be resent."))
BMConfigParser().set('bitmessagesettings', 'stopresendingafterxdays', '0') BMConfigParser().set('bitmessagesettings', 'stopresendingafterxdays', '0')
BMConfigParser().set('bitmessagesettings', 'stopresendingafterxmonths', '0') BMConfigParser().set('bitmessagesettings', 'stopresendingafterxmonths', '0')
shared.maximumLengthOfTimeToBotherResendingMessages = 0 shared.maximumLengthOfTimeToBotherResendingMessages = 0
@ -2607,7 +2711,9 @@ class MyForm(settingsmixin.SMainWindow):
# startup for linux # startup for linux
pass pass
if state.appdata != paths.lookupExeFolder() and self.settingsDialogInstance.ui.checkBoxPortableMode.isChecked(): # If we are NOT using portable mode now but the user selected that we should... if state.appdata != paths.lookupExeFolder() and \
self.settingsDialogInstance.ui.checkBoxPortableMode.isChecked():
# If we are NOT using portable mode now but the user selected that we should...
# Write the keys.dat file to disk in the new location # Write the keys.dat file to disk in the new location
sqlStoredProcedure('movemessagstoprog') sqlStoredProcedure('movemessagstoprog')
with open(paths.lookupExeFolder() + 'keys.dat', 'wb') as configfile: with open(paths.lookupExeFolder() + 'keys.dat', 'wb') as configfile:
@ -2625,7 +2731,9 @@ class MyForm(settingsmixin.SMainWindow):
except: except:
pass pass
if state.appdata == paths.lookupExeFolder() and not self.settingsDialogInstance.ui.checkBoxPortableMode.isChecked(): # If we ARE using portable mode now but the user selected that we shouldn't... if state.appdata == paths.lookupExeFolder() and not \
self.settingsDialogInstance.ui.checkBoxPortableMode.isChecked():
# If we ARE using portable mode now but the user selected that we shouldn't...
state.appdata = paths.lookupAppdataFolder() state.appdata = paths.lookupAppdataFolder()
if not os.path.exists(state.appdata): if not os.path.exists(state.appdata):
os.makedirs(state.appdata) os.makedirs(state.appdata)
@ -2649,7 +2757,7 @@ class MyForm(settingsmixin.SMainWindow):
account_item = self.getCurrentItem() account_item = self.getCurrentItem()
if not account_item: if not account_item:
return return
self.ui.lineEditTo.setText(account_item.accountString()) self.ui.lineEditTo.setText(account_item.account_string())
self.ui.tabWidget.setCurrentIndex( self.ui.tabWidget.setCurrentIndex(
self.ui.tabWidget.indexOf(self.ui.send) self.ui.tabWidget.indexOf(self.ui.send)
) )
@ -2710,9 +2818,9 @@ class MyForm(settingsmixin.SMainWindow):
for i in range(0, idCount): for i in range(0, idCount):
msgids.append(str(tableWidget.item( msgids.append(str(tableWidget.item(
i, 3).data(QtCore.Qt.UserRole).toPyObject())) i, 3).data(QtCore.Qt.UserRole).toPyObject()))
tableWidget.item(i, 0).setUnread(False) tableWidget.item(i, 0).set_unread(False)
tableWidget.item(i, 1).setUnread(False) tableWidget.item(i, 1).set_unread(False)
tableWidget.item(i, 2).setUnread(False) tableWidget.item(i, 2).set_unread(False)
tableWidget.item(i, 3).setFont(font) tableWidget.item(i, 3).setFont(font)
markread = sqlExecuteChunked( markread = sqlExecuteChunked(
@ -2766,13 +2874,13 @@ class MyForm(settingsmixin.SMainWindow):
waitForSync = False waitForSync = False
# C PoW currently doesn't support interrupting and OpenCL is untested # C PoW currently doesn't support interrupting and OpenCL is untested
if getPowType() == "python" and (powQueueSize() > 0 or pendingUpload() > 0): if getPowType() == "python" and (pow_queue_size() > 0 or pendingUpload() > 0):
reply = QtGui.QMessageBox.question( reply = QtGui.QMessageBox.question(
self, _translate("MainWindow", "Proof of work pending"), self, _translate("MainWindow", "Proof of work pending"),
_translate( _translate(
"MainWindow", "MainWindow",
"%n object(s) pending proof of work", None, "%n object(s) pending proof of work", None,
QtCore.QCoreApplication.CodecForTr, powQueueSize() QtCore.QCoreApplication.CodecForTr, pow_queue_size()
) + ", " + ) + ", " +
_translate( _translate(
"MainWindow", "MainWindow",
@ -2859,10 +2967,10 @@ class MyForm(settingsmixin.SMainWindow):
if waitForPow: if waitForPow:
# check if PoW queue empty # check if PoW queue empty
maxWorkerQueue = 0 maxWorkerQueue = 0
curWorkerQueue = powQueueSize() curWorkerQueue = pow_queue_size()
while curWorkerQueue > 0: while curWorkerQueue > 0:
# worker queue size # worker queue size
curWorkerQueue = powQueueSize() curWorkerQueue = pow_queue_size()
if curWorkerQueue > maxWorkerQueue: if curWorkerQueue > maxWorkerQueue:
maxWorkerQueue = curWorkerQueue maxWorkerQueue = curWorkerQueue
if curWorkerQueue > 0: if curWorkerQueue > 0:
@ -3140,7 +3248,7 @@ class MyForm(settingsmixin.SMainWindow):
self.ui.lineEditTo.setText(str(acct.fromAddress)) self.ui.lineEditTo.setText(str(acct.fromAddress))
else: else:
self.ui.lineEditTo.setText( self.ui.lineEditTo.setText(
tableWidget.item(currentInboxRow, column_from).accountString() tableWidget.item(currentInboxRow, column_from).account_string()
) )
# If the previous message was to a chan then we should send our # If the previous message was to a chan then we should send our
@ -3155,7 +3263,7 @@ class MyForm(settingsmixin.SMainWindow):
self.ui.lineEditTo.setText(str(toAddressAtCurrentInboxRow)) self.ui.lineEditTo.setText(str(toAddressAtCurrentInboxRow))
else: else:
self.ui.lineEditTo.setText( self.ui.lineEditTo.setText(
tableWidget.item(currentInboxRow, column_to).accountString() tableWidget.item(currentInboxRow, column_to).account_string()
) )
self.setSendFromComboBox(toAddressAtCurrentInboxRow) self.setSendFromComboBox(toAddressAtCurrentInboxRow)
@ -3202,7 +3310,8 @@ class MyForm(settingsmixin.SMainWindow):
queryreturn = sqlQuery('''select * from blacklist where address=?''', queryreturn = sqlQuery('''select * from blacklist where address=?''',
addressAtCurrentInboxRow) addressAtCurrentInboxRow)
if queryreturn == []: if queryreturn == []:
label = "\"" + tableWidget.item(currentInboxRow, 2).subject + "\" in " + BMConfigParser().get(recipientAddress, "label") label = "\"" + tableWidget.item(currentInboxRow, 2).subject + "\" in " + \
BMConfigParser().get(recipientAddress, "label")
sqlExecute('''INSERT INTO blacklist VALUES (?,?, ?)''', sqlExecute('''INSERT INTO blacklist VALUES (?,?, ?)''',
label, label,
addressAtCurrentInboxRow, True) addressAtCurrentInboxRow, True)
@ -3219,7 +3328,8 @@ class MyForm(settingsmixin.SMainWindow):
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:
@ -3315,7 +3425,8 @@ class MyForm(settingsmixin.SMainWindow):
message, = row message, = row
defaultFilename = "".join(x for x in subjectAtCurrentInboxRow if x.isalnum()) + '.txt' 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 (*.*)") filename = QtGui.QFileDialog.getSaveFileName(
self, _translate("MainWindow","Save As..."), defaultFilename, "Text files (*.txt);;All files (*.*)")
if filename == '': if filename == '':
return return
try: try:
@ -3408,7 +3519,7 @@ class MyForm(settingsmixin.SMainWindow):
addresses_string = unicode( addresses_string = unicode(
self.ui.lineEditTo.text().toUtf8(), 'utf-8') self.ui.lineEditTo.text().toUtf8(), 'utf-8')
for item in selected_items: for item in selected_items:
address_string = item.accountString() address_string = item.account_string()
if not addresses_string: if not addresses_string:
addresses_string = address_string addresses_string = address_string
else: else:
@ -3496,7 +3607,7 @@ class MyForm(settingsmixin.SMainWindow):
'''update subscriptions set enabled=1 WHERE address=?''', '''update subscriptions set enabled=1 WHERE address=?''',
address) address)
account = self.getCurrentItem() account = self.getCurrentItem()
account.setEnabled(True) account.set_enabled(True)
self.rerenderAddressBook() self.rerenderAddressBook()
shared.reloadBroadcastSendersForWhichImWatching() shared.reloadBroadcastSendersForWhichImWatching()
@ -3506,14 +3617,14 @@ class MyForm(settingsmixin.SMainWindow):
'''update subscriptions set enabled=0 WHERE address=?''', '''update subscriptions set enabled=0 WHERE address=?''',
address) address)
account = self.getCurrentItem() account = self.getCurrentItem()
account.setEnabled(False) account.set_enabled(False)
self.rerenderAddressBook() self.rerenderAddressBook()
shared.reloadBroadcastSendersForWhichImWatching() shared.reloadBroadcastSendersForWhichImWatching()
def on_context_menuSubscriptions(self, point): def on_context_menuSubscriptions(self, point):
currentItem = self.getCurrentItem() currentItem = self.getCurrentItem()
self.popMenuSubscriptions = QtGui.QMenu(self) self.popMenuSubscriptions = QtGui.QMenu(self)
if isinstance(currentItem, Ui_AddressWidget): if isinstance(currentItem, UiAddressWidget):
self.popMenuSubscriptions.addAction(self.actionsubscriptionsNew) self.popMenuSubscriptions.addAction(self.actionsubscriptionsNew)
self.popMenuSubscriptions.addAction(self.actionsubscriptionsDelete) self.popMenuSubscriptions.addAction(self.actionsubscriptionsDelete)
self.popMenuSubscriptions.addSeparator() self.popMenuSubscriptions.addSeparator()
@ -3740,7 +3851,7 @@ class MyForm(settingsmixin.SMainWindow):
addressAtCurrentRow = self.getCurrentAccount() addressAtCurrentRow = self.getCurrentAccount()
self.enableIdentity(addressAtCurrentRow) self.enableIdentity(addressAtCurrentRow)
account = self.getCurrentItem() account = self.getCurrentItem()
account.setEnabled(True) account.set_enabled(True)
def enableIdentity(self, address): def enableIdentity(self, address):
BMConfigParser().set(address, 'enabled', 'true') BMConfigParser().set(address, 'enabled', 'true')
@ -3752,7 +3863,7 @@ class MyForm(settingsmixin.SMainWindow):
address = self.getCurrentAccount() address = self.getCurrentAccount()
self.disableIdentity(address) self.disableIdentity(address)
account = self.getCurrentItem() account = self.getCurrentItem()
account.setEnabled(False) account.set_enabled(False)
def disableIdentity(self, address): def disableIdentity(self, address):
BMConfigParser().set(str(address), 'enabled', 'false') BMConfigParser().set(str(address), 'enabled', 'false')
@ -3812,9 +3923,24 @@ class MyForm(settingsmixin.SMainWindow):
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 = ['PNG', 'GIF', 'JPG', 'JPEG', 'SVG', 'BMP', 'MNG', 'PBM',
'PGM', 'PPM', 'TIFF', 'XBM', 'XPM', 'TGA']
# http://pyqt.sourceforge.net/Docs/PyQt4/qimagereader.html#supportedImageFormats # 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 = [] filters = []
all_images_filter = [] all_images_filter = []
current_files = [] current_files = []
@ -3847,7 +3973,9 @@ class MyForm(settingsmixin.SMainWindow):
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:
@ -3925,7 +4053,7 @@ class MyForm(settingsmixin.SMainWindow):
def on_context_menuYourIdentities(self, point): def on_context_menuYourIdentities(self, point):
currentItem = self.getCurrentItem() currentItem = self.getCurrentItem()
self.popMenuYourIdentities = QtGui.QMenu(self) self.popMenuYourIdentities = QtGui.QMenu(self)
if isinstance(currentItem, Ui_AddressWidget): if isinstance(currentItem, UiAddressWidget):
self.popMenuYourIdentities.addAction(self.actionNewYourIdentities) self.popMenuYourIdentities.addAction(self.actionNewYourIdentities)
self.popMenuYourIdentities.addSeparator() self.popMenuYourIdentities.addSeparator()
self.popMenuYourIdentities.addAction(self.actionClipboardYourIdentities) self.popMenuYourIdentities.addAction(self.actionClipboardYourIdentities)
@ -3954,7 +4082,7 @@ class MyForm(settingsmixin.SMainWindow):
def on_context_menuChan(self, point): def on_context_menuChan(self, point):
currentItem = self.getCurrentItem() currentItem = self.getCurrentItem()
self.popMenu = QtGui.QMenu(self) self.popMenu = QtGui.QMenu(self)
if isinstance(currentItem, Ui_AddressWidget): if isinstance(currentItem, UiAddressWidget):
self.popMenu.addAction(self.actionNew) self.popMenu.addAction(self.actionNew)
self.popMenu.addAction(self.actionDelete) self.popMenu.addAction(self.actionDelete)
self.popMenu.addSeparator() self.popMenu.addSeparator()
@ -4077,10 +4205,12 @@ class MyForm(settingsmixin.SMainWindow):
if column != 0: if column != 0:
return return
# only account names of normal addresses (no chans/mailinglists) # only account names of normal addresses (no chans/mailinglists)
if (not isinstance(item, Ui_AddressWidget)) or (not self.getCurrentTreeWidget()) or self.getCurrentTreeWidget().currentItem() is None: if (not isinstance(item, UiAddressWidget)) 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(), UiAddressWidget)):
return return
# only currently selected item # only currently selected item
if item.address != self.getCurrentAccount(): if item.address != self.getCurrentAccount():
@ -4090,7 +4220,7 @@ class MyForm(settingsmixin.SMainWindow):
return return
newLabel = unicode(item.text(0), 'utf-8', 'ignore') newLabel = unicode(item.text(0), 'utf-8', 'ignore')
oldLabel = item.defaultLabel() oldLabel = item.default_label()
# unchanged, do not do anything either # unchanged, do not do anything either
if newLabel == oldLabel: if newLabel == oldLabel:
@ -4284,12 +4414,12 @@ class settingsDialog(QtGui.QDialog):
'bitmessagesettings', 'sockslisten')) 'bitmessagesettings', 'sockslisten'))
if str(BMConfigParser().get('bitmessagesettings', 'socksproxytype')) == 'none': if str(BMConfigParser().get('bitmessagesettings', 'socksproxytype')) == 'none':
self.ui.comboBoxProxyType.setCurrentIndex(0) self.ui.comboBoxProxyType.setCurrentIndex(0)
self.ui.lineEditSocksHostname.setEnabled(False) self.ui.lineEditSocksHostname.set_enabled(False)
self.ui.lineEditSocksPort.setEnabled(False) self.ui.lineEditSocksPort.set_enabled(False)
self.ui.lineEditSocksUsername.setEnabled(False) self.ui.lineEditSocksUsername.set_enabled(False)
self.ui.lineEditSocksPassword.setEnabled(False) self.ui.lineEditSocksPassword.set_enabled(False)
self.ui.checkBoxAuthentication.setEnabled(False) self.ui.checkBoxAuthentication.set_enabled(False)
self.ui.checkBoxSocksListen.setEnabled(False) self.ui.checkBoxSocksListen.set_enabled(False)
elif str(BMConfigParser().get('bitmessagesettings', 'socksproxytype')) == 'SOCKS4a': elif str(BMConfigParser().get('bitmessagesettings', 'socksproxytype')) == 'SOCKS4a':
self.ui.comboBoxProxyType.setCurrentIndex(1) self.ui.comboBoxProxyType.setCurrentIndex(1)
elif str(BMConfigParser().get('bitmessagesettings', 'socksproxytype')) == 'SOCKS5': elif str(BMConfigParser().get('bitmessagesettings', 'socksproxytype')) == 'SOCKS5':
@ -4313,22 +4443,30 @@ class settingsDialog(QtGui.QDialog):
BMConfigParser().get('bitmessagesettings', 'maxoutboundconnections'))) BMConfigParser().get('bitmessagesettings', 'maxoutboundconnections')))
# Demanded difficulty tab # Demanded difficulty tab
self.ui.lineEditTotalDifficulty.setText(str((float(BMConfigParser().getint( self.ui.lineEditTotalDifficulty.setText(
'bitmessagesettings', 'defaultnoncetrialsperbyte')) / defaults.networkDefaultProofOfWorkNonceTrialsPerByte))) str((float(BMConfigParser().getint(
self.ui.lineEditSmallMessageDifficulty.setText(str((float(BMConfigParser().getint( 'bitmessagesettings', 'defaultnoncetrialsperbyte')) /
'bitmessagesettings', 'defaultpayloadlengthextrabytes')) / defaults.networkDefaultPayloadLengthExtraBytes))) defaults.networkDefaultProofOfWorkNonceTrialsPerByte)))
self.ui.lineEditSmallMessageDifficulty.setText(
str((float(BMConfigParser().getint(
'bitmessagesettings', 'defaultpayloadlengthextrabytes')) /
defaults.networkDefaultPayloadLengthExtraBytes)))
# Max acceptable difficulty tab # Max acceptable difficulty tab
self.ui.lineEditMaxAcceptableTotalDifficulty.setText(str((float(BMConfigParser().getint( self.ui.lineEditMaxAcceptableTotalDifficulty.setText(str(
'bitmessagesettings', 'maxacceptablenoncetrialsperbyte')) / defaults.networkDefaultProofOfWorkNonceTrialsPerByte))) (float(BMConfigParser().getint(
self.ui.lineEditMaxAcceptableSmallMessageDifficulty.setText(str((float(BMConfigParser().getint( 'bitmessagesettings', 'maxacceptablenoncetrialsperbyte')) /
'bitmessagesettings', 'maxacceptablepayloadlengthextrabytes')) / defaults.networkDefaultPayloadLengthExtraBytes))) defaults.networkDefaultProofOfWorkNonceTrialsPerByte)))
self.ui.lineEditMaxAcceptableSmallMessageDifficulty.setText(
str((float(BMConfigParser().getint(
'bitmessagesettings', 'maxacceptablepayloadlengthextrabytes')) /
defaults.networkDefaultPayloadLengthExtraBytes)))
# OpenCL # OpenCL
if openclpow.openclAvailable(): if openclpow.openclAvailable():
self.ui.comboBoxOpenCL.setEnabled(True) self.ui.comboBoxOpenCL.set_enabled(True)
else: else:
self.ui.comboBoxOpenCL.setEnabled(False) self.ui.comboBoxOpenCL.set_enabled(False)
self.ui.comboBoxOpenCL.clear() self.ui.comboBoxOpenCL.clear()
self.ui.comboBoxOpenCL.addItem("None") self.ui.comboBoxOpenCL.addItem("None")
self.ui.comboBoxOpenCL.addItems(openclpow.vendors) self.ui.comboBoxOpenCL.addItems(openclpow.vendors)
@ -4353,19 +4491,19 @@ class settingsDialog(QtGui.QDialog):
self.ui.radioButtonNamecoinNamecoind.setChecked(True) self.ui.radioButtonNamecoinNamecoind.setChecked(True)
elif nmctype == "nmcontrol": elif nmctype == "nmcontrol":
self.ui.radioButtonNamecoinNmcontrol.setChecked(True) self.ui.radioButtonNamecoinNmcontrol.setChecked(True)
self.ui.lineEditNamecoinUser.setEnabled(False) self.ui.lineEditNamecoinUser.set_enabled(False)
self.ui.labelNamecoinUser.setEnabled(False) self.ui.labelNamecoinUser.set_enabled(False)
self.ui.lineEditNamecoinPassword.setEnabled(False) self.ui.lineEditNamecoinPassword.set_enabled(False)
self.ui.labelNamecoinPassword.setEnabled(False) self.ui.labelNamecoinPassword.set_enabled(False)
else: else:
assert False assert False
QtCore.QObject.connect(self.ui.radioButtonNamecoinNamecoind, QtCore.SIGNAL( QtCore.QObject.connect(self.ui.radioButtonNamecoinNamecoind, QtCore.SIGNAL(
"toggled(bool)"), self.namecoinTypeChanged) "toggled(bool)"), self.namecoin_type_changed)
QtCore.QObject.connect(self.ui.radioButtonNamecoinNmcontrol, QtCore.SIGNAL( QtCore.QObject.connect(self.ui.radioButtonNamecoinNmcontrol, QtCore.SIGNAL(
"toggled(bool)"), self.namecoinTypeChanged) "toggled(bool)"), self.namecoin_type_changed)
QtCore.QObject.connect(self.ui.pushButtonNamecoinTest, QtCore.SIGNAL( QtCore.QObject.connect(self.ui.pushButtonNamecoinTest, QtCore.SIGNAL(
"clicked()"), self.click_pushButtonNamecoinTest) "clicked()"), self.click_push_button_namecoin_test)
#Message Resend tab #Message Resend tab
self.ui.lineEditDays.setText(str( self.ui.lineEditDays.setText(str(
@ -4396,24 +4534,24 @@ class settingsDialog(QtGui.QDialog):
def comboBoxProxyTypeChanged(self, comboBoxIndex): def comboBoxProxyTypeChanged(self, comboBoxIndex):
if comboBoxIndex == 0: if comboBoxIndex == 0:
self.ui.lineEditSocksHostname.setEnabled(False) self.ui.lineEditSocksHostname.set_enabled(False)
self.ui.lineEditSocksPort.setEnabled(False) self.ui.lineEditSocksPort.set_enabled(False)
self.ui.lineEditSocksUsername.setEnabled(False) self.ui.lineEditSocksUsername.set_enabled(False)
self.ui.lineEditSocksPassword.setEnabled(False) self.ui.lineEditSocksPassword.set_enabled(False)
self.ui.checkBoxAuthentication.setEnabled(False) self.ui.checkBoxAuthentication.set_enabled(False)
self.ui.checkBoxSocksListen.setEnabled(False) self.ui.checkBoxSocksListen.set_enabled(False)
elif comboBoxIndex == 1 or comboBoxIndex == 2: elif comboBoxIndex == 1 or comboBoxIndex == 2:
self.ui.lineEditSocksHostname.setEnabled(True) self.ui.lineEditSocksHostname.set_enabled(True)
self.ui.lineEditSocksPort.setEnabled(True) self.ui.lineEditSocksPort.set_enabled(True)
self.ui.checkBoxAuthentication.setEnabled(True) self.ui.checkBoxAuthentication.set_enabled(True)
self.ui.checkBoxSocksListen.setEnabled(True) self.ui.checkBoxSocksListen.set_enabled(True)
if self.ui.checkBoxAuthentication.isChecked(): if self.ui.checkBoxAuthentication.isChecked():
self.ui.lineEditSocksUsername.setEnabled(True) self.ui.lineEditSocksUsername.set_enabled(True)
self.ui.lineEditSocksPassword.setEnabled(True) self.ui.lineEditSocksPassword.set_enabled(True)
# Check status of namecoin integration radio buttons and translate # Check status of namecoin integration radio buttons and translate
# it to a string as in the options. # it to a string as in the options.
def getNamecoinType(self): def get_namecoin_type(self):
if self.ui.radioButtonNamecoinNamecoind.isChecked(): if self.ui.radioButtonNamecoinNamecoind.isChecked():
return "namecoind" return "namecoind"
if self.ui.radioButtonNamecoinNmcontrol.isChecked(): if self.ui.radioButtonNamecoinNmcontrol.isChecked():
@ -4421,31 +4559,32 @@ class settingsDialog(QtGui.QDialog):
assert False assert False
# Namecoin connection type was changed. # Namecoin connection type was changed.
def namecoinTypeChanged(self, checked): def namecoin_type_changed(self, checked):
nmctype = self.getNamecoinType() nmctype = self.get_namecoin_type()
assert nmctype == "namecoind" or nmctype == "nmcontrol" assert nmctype == "namecoind" or nmctype == "nmcontrol"
isNamecoind = (nmctype == "namecoind") isNamecoind = (nmctype == "namecoind")
self.ui.lineEditNamecoinUser.setEnabled(isNamecoind) self.ui.lineEditNamecoinUser.set_enabled(isNamecoind)
self.ui.labelNamecoinUser.setEnabled(isNamecoind) self.ui.labelNamecoinUser.set_enabled(isNamecoind)
self.ui.lineEditNamecoinPassword.setEnabled(isNamecoind) self.ui.lineEditNamecoinPassword.set_enabled(isNamecoind)
self.ui.labelNamecoinPassword.setEnabled(isNamecoind) self.ui.labelNamecoinPassword.set_enabled(isNamecoind)
if isNamecoind: if isNamecoind:
self.ui.lineEditNamecoinPort.setText(defaults.namecoinDefaultRpcPort) self.ui.lineEditNamecoinPort.setText(defaults.namecoinDefaultRpcPort)
else: else:
self.ui.lineEditNamecoinPort.setText("9000") self.ui.lineEditNamecoinPort.setText("9000")
def click_pushButtonNamecoinTest(self): def click_push_button_namecoin_test(self):
"""Test the namecoin settings specified in the settings dialog.""" """Test the namecoin settings specified in the settings dialog."""
self.ui.labelNamecoinTestResult.setText(_translate( self.ui.labelNamecoinTestResult.setText(_translate(
"MainWindow", "Testing...")) "MainWindow", "Testing..."))
options = {} options = {
options["type"] = self.getNamecoinType() "type": self.get_namecoin_type(),
options["host"] = str(self.ui.lineEditNamecoinHost.text().toUtf8()) "host": str(self.ui.lineEditNamecoinHost.text().toUtf8()),
options["port"] = str(self.ui.lineEditNamecoinPort.text().toUtf8()) "port": str(self.ui.lineEditNamecoinPort.text().toUtf8()),
options["user"] = str(self.ui.lineEditNamecoinUser.text().toUtf8()) "user": str(self.ui.lineEditNamecoinUser.text().toUtf8()),
options["password"] = str(self.ui.lineEditNamecoinPassword.text().toUtf8()) "password": str(self.ui.lineEditNamecoinPassword.text().toUtf8())
}
nc = namecoin.namecoinConnection(options) nc = namecoin.namecoinConnection(options)
status, text = nc.test() status, text = nc.test()
self.ui.labelNamecoinTestResult.setText(text) self.ui.labelNamecoinTestResult.setText(text)

View File

@ -13,14 +13,15 @@ import inspect
import re import re
import sys import sys
import time import time
import queues
from PyQt4 import QtGui from PyQt4 import QtGui
import queues
from addresses import decodeAddress from addresses import decodeAddress
from bmconfigparser import BMConfigParser from bmconfigparser import BMConfigParser
from helper_ackPayload import genAckPayload from helper_ackPayload import genAckPayload
from helper_sql import sqlQuery, sqlExecute from helper_sql import sqlQuery, sqlExecute
from .foldertree import AccountMixin from .foldertree import AccountMixin
from .utils import str_broadcast_subscribers from .utils import str_broadcast_subscribers

View File

@ -6,11 +6,11 @@ src/bitmessageqt/address_dialogs.py
# pylint: disable=attribute-defined-outside-init # pylint: disable=attribute-defined-outside-init
import hashlib import hashlib
import queues
import widgets
from PyQt4 import QtCore, QtGui from PyQt4 import QtCore, QtGui
import queues
import widgets
from account import AccountMixin, GatewayAccount, MailchuckAccount, accountClass, getSortedAccounts from account import AccountMixin, GatewayAccount, MailchuckAccount, accountClass, getSortedAccounts
from addresses import addBMIfNotPresent, decodeAddress, encodeVarint from addresses import addBMIfNotPresent, decodeAddress, encodeVarint
from inventory import Inventory from inventory import Inventory
@ -27,20 +27,20 @@ class AddressCheckMixin(object):
QtCore.QObject.connect( # pylint: disable=no-member QtCore.QObject.connect( # pylint: disable=no-member
self.lineEditAddress, self.lineEditAddress,
QtCore.SIGNAL("textChanged(QString)"), QtCore.SIGNAL("textChanged(QString)"),
self.addressChanged) self.address_changed)
def _onSuccess(self, addressVersion, streamNumber, ripe): def _onSuccess(self, addressVersion, streamNumber, ripe):
pass pass
def addressChanged(self, QString): def address_changed(self, q_string):
"""Address validation callback, performs validation and gives feedback""" """Address validation callback, performs validation and gives feedback"""
status, addressVersion, streamNumber, ripe = decodeAddress( status, address_version, stream_number, ripe = decodeAddress(
str(QString)) str(q_string))
self.valid = status == 'success' self.valid = status == 'success'
if self.valid: if self.valid:
self.labelAddressCheck.setText( self.labelAddressCheck.setText(
_translate("MainWindow", "Address is valid.")) _translate("MainWindow", "Address is valid."))
self._onSuccess(addressVersion, streamNumber, ripe) self._onSuccess(address_version, stream_number, ripe)
elif status == 'missingbm': elif status == 'missingbm':
self.labelAddressCheck.setText(_translate( self.labelAddressCheck.setText(_translate(
"MainWindow", # dialog name should be here "MainWindow", # dialog name should be here
@ -135,14 +135,14 @@ class NewAddressDialog(QtGui.QDialog, RetranslateMixin):
# self.buttonBox.enabled = False # self.buttonBox.enabled = False
if self.radioButtonRandomAddress.isChecked(): if self.radioButtonRandomAddress.isChecked():
if self.radioButtonMostAvailable.isChecked(): if self.radioButtonMostAvailable.isChecked():
streamNumberForAddress = 1 stream_number_for_address = 1
else: else:
# User selected 'Use the same stream as an existing # User selected 'Use the same stream as an existing
# address.' # address.'
streamNumberForAddress = decodeAddress( stream_number_for_address = decodeAddress(
self.comboBoxExisting.currentText())[2] self.comboBoxExisting.currentText())[2]
queues.addressGeneratorQueue.put(( queues.addressGeneratorQueue.put((
'createRandomAddress', 4, streamNumberForAddress, 'createRandomAddress', 4, stream_number_for_address,
str(self.newaddresslabel.text().toUtf8()), 1, "", str(self.newaddresslabel.text().toUtf8()), 1, "",
self.checkBoxEighteenByteRipe.isChecked() self.checkBoxEighteenByteRipe.isChecked()
)) ))
@ -165,9 +165,9 @@ class NewAddressDialog(QtGui.QDialog, RetranslateMixin):
else: else:
# this will eventually have to be replaced by logic # this will eventually have to be replaced by logic
# to determine the most available stream number. # to determine the most available stream number.
streamNumberForAddress = 1 stream_number_for_address = 1
queues.addressGeneratorQueue.put(( queues.addressGeneratorQueue.put((
'createDeterministicAddresses', 4, streamNumberForAddress, 'createDeterministicAddresses', 4, stream_number_for_address,
"unused deterministic address", "unused deterministic address",
self.spinBoxNumberOfAddressesToMake.value(), self.spinBoxNumberOfAddressesToMake.value(),
self.lineEditPassphrase.text().toUtf8(), self.lineEditPassphrase.text().toUtf8(),
@ -183,8 +183,8 @@ class NewSubscriptionDialog(AddressDataDialog, RetranslateMixin):
widgets.load('newsubscriptiondialog.ui', self) widgets.load('newsubscriptiondialog.ui', self)
AddressCheckMixin.__init__(self) AddressCheckMixin.__init__(self)
def _onSuccess(self, addressVersion, streamNumber, ripe): def _onSuccess(self, address_version, stream_number, ripe):
if addressVersion <= 3: if address_version <= 3:
self.checkBoxDisplayMessagesAlreadyInInventory.setText(_translate( self.checkBoxDisplayMessagesAlreadyInInventory.setText(_translate(
"MainWindow", "MainWindow",
"Address is an old type. We cannot display its past" "Address is an old type. We cannot display its past"
@ -192,11 +192,11 @@ class NewSubscriptionDialog(AddressDataDialog, RetranslateMixin):
)) ))
else: else:
Inventory().flush() Inventory().flush()
doubleHashOfAddressData = hashlib.sha512(hashlib.sha512( double_hash_of_address_data = hashlib.sha512(hashlib.sha512(
encodeVarint(addressVersion) + encodeVarint(address_version) +
encodeVarint(streamNumber) + ripe encodeVarint(stream_number) + ripe
).digest()).digest() ).digest()).digest()
tag = doubleHashOfAddressData[32:] tag = double_hash_of_address_data[32:]
self.recent = Inventory().by_type_and_tag(3, tag) self.recent = Inventory().by_type_and_tag(3, tag)
count = len(self.recent) count = len(self.recent)
if count == 0: if count == 0:
@ -207,7 +207,7 @@ class NewSubscriptionDialog(AddressDataDialog, RetranslateMixin):
" to display." " to display."
)) ))
else: else:
self.checkBoxDisplayMessagesAlreadyInInventory.setEnabled(True) self.checkBoxDisplayMessagesAlreadyInInventory.set_enabled(True)
self.checkBoxDisplayMessagesAlreadyInInventory.setText( self.checkBoxDisplayMessagesAlreadyInInventory.setText(
_translate( _translate(
"MainWindow", "MainWindow",
@ -257,12 +257,12 @@ class SpecialAddressBehaviorDialog(QtGui.QDialog, RetranslateMixin):
else: else:
self.radioButtonBehaveNormalAddress.click() self.radioButtonBehaveNormalAddress.click()
try: try:
mailingListName = config.get( mailing_list_name = config.get(
self.address, 'mailinglistname') self.address, 'mailinglistname')
except: except:
mailingListName = '' mailing_list_name = ''
self.lineEditMailingListName.setText( self.lineEditMailingListName.setText(
unicode(mailingListName, 'utf-8') unicode(mailing_list_name, 'utf-8')
) )
QtGui.QWidget.resize(self, QtGui.QWidget.sizeHint(self)) QtGui.QWidget.resize(self, QtGui.QWidget.sizeHint(self))
@ -325,11 +325,11 @@ class EmailGatewayDialog(QtGui.QDialog, RetranslateMixin):
if "@" in label: if "@" in label:
self.lineEditEmail.setText(label) self.lineEditEmail.setText(label)
if isinstance(self.acct, GatewayAccount): if isinstance(self.acct, GatewayAccount):
self.radioButtonUnregister.setEnabled(True) self.radioButtonUnregister.set_enabled(True)
self.radioButtonStatus.setEnabled(True) self.radioButtonStatus.set_enabled(True)
self.radioButtonStatus.setChecked(True) self.radioButtonStatus.setChecked(True)
self.radioButtonSettings.setEnabled(True) self.radioButtonSettings.set_enabled(True)
self.lineEditEmail.setEnabled(False) self.lineEditEmail.set_enabled(False)
else: else:
self.acct = MailchuckAccount(address) self.acct = MailchuckAccount(address)
self.lineEditEmail.setFocus() self.lineEditEmail.setFocus()

View File

@ -27,7 +27,7 @@ class AddressPassPhraseValidatorMixin():
self.feedBackObject.setText(string) self.feedBackObject.setText(string)
self.isValid = False self.isValid = False
if self.buttonBox: if self.buttonBox:
self.buttonBox.button(QtGui.QDialogButtonBox.Ok).setEnabled(False) self.buttonBox.button(QtGui.QDialogButtonBox.Ok).set_enabled(False)
if string is not None and self.feedBackObject is not None: if string is not None and self.feedBackObject is not None:
self.buttonBox.button(QtGui.QDialogButtonBox.Ok).setText(_translate("AddressValidator", "Invalid")) self.buttonBox.button(QtGui.QDialogButtonBox.Ok).setText(_translate("AddressValidator", "Invalid"))
else: else:
@ -42,7 +42,7 @@ class AddressPassPhraseValidatorMixin():
self.feedBackObject.setText(string) self.feedBackObject.setText(string)
self.isValid = True self.isValid = True
if self.buttonBox: if self.buttonBox:
self.buttonBox.button(QtGui.QDialogButtonBox.Ok).setEnabled(True) self.buttonBox.button(QtGui.QDialogButtonBox.Ok).set_enabled(True)
self.buttonBox.button(QtGui.QDialogButtonBox.Ok).setText(self.okButtonLabel) self.buttonBox.button(QtGui.QDialogButtonBox.Ok).setText(self.okButtonLabel)
def checkQueue(self): def checkQueue(self):

View File

@ -86,7 +86,7 @@ class Ui_MainWindow(object):
self.verticalSplitter_12.setStretchFactor(1, 0) self.verticalSplitter_12.setStretchFactor(1, 0)
self.verticalSplitter_12.setCollapsible(0, False) self.verticalSplitter_12.setCollapsible(0, False)
self.verticalSplitter_12.setCollapsible(1, False) self.verticalSplitter_12.setCollapsible(1, False)
self.verticalSplitter_12.handle(1).setEnabled(False) self.verticalSplitter_12.handle(1).set_enabled(False)
self.horizontalSplitter_3.addWidget(self.verticalSplitter_12) self.horizontalSplitter_3.addWidget(self.verticalSplitter_12)
self.verticalSplitter_7 = settingsmixin.SSplitter() self.verticalSplitter_7 = settingsmixin.SSplitter()
self.verticalSplitter_7.setObjectName(_fromUtf8("verticalSplitter_7")) self.verticalSplitter_7.setObjectName(_fromUtf8("verticalSplitter_7"))
@ -105,7 +105,7 @@ class Ui_MainWindow(object):
self.inboxSearchOption.addItem(_fromUtf8("")) self.inboxSearchOption.addItem(_fromUtf8(""))
self.inboxSearchOption.setSizeAdjustPolicy(QtGui.QComboBox.AdjustToContents) self.inboxSearchOption.setSizeAdjustPolicy(QtGui.QComboBox.AdjustToContents)
self.horizontalSplitterSearch.addWidget(self.inboxSearchOption) self.horizontalSplitterSearch.addWidget(self.inboxSearchOption)
self.horizontalSplitterSearch.handle(1).setEnabled(False) self.horizontalSplitterSearch.handle(1).set_enabled(False)
self.horizontalSplitterSearch.setStretchFactor(0, 1) self.horizontalSplitterSearch.setStretchFactor(0, 1)
self.horizontalSplitterSearch.setStretchFactor(1, 0) self.horizontalSplitterSearch.setStretchFactor(1, 0)
self.verticalSplitter_7.addWidget(self.horizontalSplitterSearch) self.verticalSplitter_7.addWidget(self.horizontalSplitterSearch)
@ -146,7 +146,7 @@ class Ui_MainWindow(object):
self.verticalSplitter_7.setCollapsible(0, False) self.verticalSplitter_7.setCollapsible(0, False)
self.verticalSplitter_7.setCollapsible(1, False) self.verticalSplitter_7.setCollapsible(1, False)
self.verticalSplitter_7.setCollapsible(2, False) self.verticalSplitter_7.setCollapsible(2, False)
self.verticalSplitter_7.handle(1).setEnabled(False) self.verticalSplitter_7.handle(1).set_enabled(False)
self.horizontalSplitter_3.addWidget(self.verticalSplitter_7) self.horizontalSplitter_3.addWidget(self.verticalSplitter_7)
self.horizontalSplitter_3.setStretchFactor(0, 0) self.horizontalSplitter_3.setStretchFactor(0, 0)
self.horizontalSplitter_3.setStretchFactor(1, 1) self.horizontalSplitter_3.setStretchFactor(1, 1)
@ -205,8 +205,8 @@ class Ui_MainWindow(object):
self.verticalSplitter_2.setCollapsible(0, False) self.verticalSplitter_2.setCollapsible(0, False)
self.verticalSplitter_2.setCollapsible(1, False) self.verticalSplitter_2.setCollapsible(1, False)
self.verticalSplitter_2.setCollapsible(2, False) self.verticalSplitter_2.setCollapsible(2, False)
self.verticalSplitter_2.handle(1).setEnabled(False) self.verticalSplitter_2.handle(1).set_enabled(False)
self.verticalSplitter_2.handle(2).setEnabled(False) self.verticalSplitter_2.handle(2).set_enabled(False)
self.horizontalSplitter.addWidget(self.verticalSplitter_2) self.horizontalSplitter.addWidget(self.verticalSplitter_2)
self.verticalSplitter = settingsmixin.SSplitter() self.verticalSplitter = settingsmixin.SSplitter()
self.verticalSplitter.setObjectName(_fromUtf8("verticalSplitter")) self.verticalSplitter.setObjectName(_fromUtf8("verticalSplitter"))
@ -253,7 +253,7 @@ class Ui_MainWindow(object):
self.verticalSplitter_5.setStretchFactor(1, 1) self.verticalSplitter_5.setStretchFactor(1, 1)
self.verticalSplitter_5.setCollapsible(0, False) self.verticalSplitter_5.setCollapsible(0, False)
self.verticalSplitter_5.setCollapsible(1, False) self.verticalSplitter_5.setCollapsible(1, False)
self.verticalSplitter_5.handle(1).setEnabled(False) self.verticalSplitter_5.handle(1).set_enabled(False)
self.gridLayout_8.addWidget(self.verticalSplitter_5, 0, 0, 1, 1) self.gridLayout_8.addWidget(self.verticalSplitter_5, 0, 0, 1, 1)
self.tabWidgetSend.addTab(self.sendDirect, _fromUtf8("")) self.tabWidgetSend.addTab(self.sendDirect, _fromUtf8(""))
self.sendBroadcast = QtGui.QWidget() self.sendBroadcast = QtGui.QWidget()
@ -289,7 +289,7 @@ class Ui_MainWindow(object):
self.verticalSplitter_6.setStretchFactor(1, 1) self.verticalSplitter_6.setStretchFactor(1, 1)
self.verticalSplitter_6.setCollapsible(0, False) self.verticalSplitter_6.setCollapsible(0, False)
self.verticalSplitter_6.setCollapsible(1, False) self.verticalSplitter_6.setCollapsible(1, False)
self.verticalSplitter_6.handle(1).setEnabled(False) self.verticalSplitter_6.handle(1).set_enabled(False)
self.gridLayout_9.addWidget(self.verticalSplitter_6, 0, 0, 1, 1) self.gridLayout_9.addWidget(self.verticalSplitter_6, 0, 0, 1, 1)
self.tabWidgetSend.addTab(self.sendBroadcast, _fromUtf8("")) self.tabWidgetSend.addTab(self.sendBroadcast, _fromUtf8(""))
self.verticalSplitter.addWidget(self.tabWidgetSend) self.verticalSplitter.addWidget(self.tabWidgetSend)
@ -350,7 +350,7 @@ class Ui_MainWindow(object):
self.verticalSplitter.setStretchFactor(0, 1) self.verticalSplitter.setStretchFactor(0, 1)
self.verticalSplitter.setCollapsible(0, False) self.verticalSplitter.setCollapsible(0, False)
self.verticalSplitter.setCollapsible(1, False) self.verticalSplitter.setCollapsible(1, False)
self.verticalSplitter.handle(1).setEnabled(False) self.verticalSplitter.handle(1).set_enabled(False)
self.horizontalSplitter.addWidget(self.verticalSplitter) self.horizontalSplitter.addWidget(self.verticalSplitter)
self.horizontalSplitter.setStretchFactor(0, 0) self.horizontalSplitter.setStretchFactor(0, 0)
self.horizontalSplitter.setStretchFactor(1, 1) self.horizontalSplitter.setStretchFactor(1, 1)
@ -387,7 +387,7 @@ class Ui_MainWindow(object):
self.verticalSplitter_3.setStretchFactor(1, 0) self.verticalSplitter_3.setStretchFactor(1, 0)
self.verticalSplitter_3.setCollapsible(0, False) self.verticalSplitter_3.setCollapsible(0, False)
self.verticalSplitter_3.setCollapsible(1, False) self.verticalSplitter_3.setCollapsible(1, False)
self.verticalSplitter_3.handle(1).setEnabled(False) self.verticalSplitter_3.handle(1).set_enabled(False)
self.horizontalSplitter_4.addWidget(self.verticalSplitter_3) self.horizontalSplitter_4.addWidget(self.verticalSplitter_3)
self.verticalSplitter_4 = settingsmixin.SSplitter() self.verticalSplitter_4 = settingsmixin.SSplitter()
self.verticalSplitter_4.setObjectName(_fromUtf8("verticalSplitter_4")) self.verticalSplitter_4.setObjectName(_fromUtf8("verticalSplitter_4"))
@ -406,7 +406,7 @@ class Ui_MainWindow(object):
self.inboxSearchOptionSubscriptions.addItem(_fromUtf8("")) self.inboxSearchOptionSubscriptions.addItem(_fromUtf8(""))
self.inboxSearchOptionSubscriptions.setSizeAdjustPolicy(QtGui.QComboBox.AdjustToContents) self.inboxSearchOptionSubscriptions.setSizeAdjustPolicy(QtGui.QComboBox.AdjustToContents)
self.horizontalSplitter_2.addWidget(self.inboxSearchOptionSubscriptions) self.horizontalSplitter_2.addWidget(self.inboxSearchOptionSubscriptions)
self.horizontalSplitter_2.handle(1).setEnabled(False) self.horizontalSplitter_2.handle(1).set_enabled(False)
self.horizontalSplitter_2.setStretchFactor(0, 1) self.horizontalSplitter_2.setStretchFactor(0, 1)
self.horizontalSplitter_2.setStretchFactor(1, 0) self.horizontalSplitter_2.setStretchFactor(1, 0)
self.verticalSplitter_4.addWidget(self.horizontalSplitter_2) self.verticalSplitter_4.addWidget(self.horizontalSplitter_2)
@ -447,7 +447,7 @@ class Ui_MainWindow(object):
self.verticalSplitter_4.setCollapsible(0, False) self.verticalSplitter_4.setCollapsible(0, False)
self.verticalSplitter_4.setCollapsible(1, False) self.verticalSplitter_4.setCollapsible(1, False)
self.verticalSplitter_4.setCollapsible(2, False) self.verticalSplitter_4.setCollapsible(2, False)
self.verticalSplitter_4.handle(1).setEnabled(False) self.verticalSplitter_4.handle(1).set_enabled(False)
self.horizontalSplitter_4.addWidget(self.verticalSplitter_4) self.horizontalSplitter_4.addWidget(self.verticalSplitter_4)
self.horizontalSplitter_4.setStretchFactor(0, 0) self.horizontalSplitter_4.setStretchFactor(0, 0)
self.horizontalSplitter_4.setStretchFactor(1, 1) self.horizontalSplitter_4.setStretchFactor(1, 1)
@ -486,7 +486,7 @@ class Ui_MainWindow(object):
self.verticalSplitter_17.setStretchFactor(1, 0) self.verticalSplitter_17.setStretchFactor(1, 0)
self.verticalSplitter_17.setCollapsible(0, False) self.verticalSplitter_17.setCollapsible(0, False)
self.verticalSplitter_17.setCollapsible(1, False) self.verticalSplitter_17.setCollapsible(1, False)
self.verticalSplitter_17.handle(1).setEnabled(False) self.verticalSplitter_17.handle(1).set_enabled(False)
self.horizontalSplitter_7.addWidget(self.verticalSplitter_17) self.horizontalSplitter_7.addWidget(self.verticalSplitter_17)
self.verticalSplitter_8 = settingsmixin.SSplitter() self.verticalSplitter_8 = settingsmixin.SSplitter()
self.verticalSplitter_8.setObjectName(_fromUtf8("verticalSplitter_8")) self.verticalSplitter_8.setObjectName(_fromUtf8("verticalSplitter_8"))
@ -505,7 +505,7 @@ class Ui_MainWindow(object):
self.inboxSearchOptionChans.addItem(_fromUtf8("")) self.inboxSearchOptionChans.addItem(_fromUtf8(""))
self.inboxSearchOptionChans.setSizeAdjustPolicy(QtGui.QComboBox.AdjustToContents) self.inboxSearchOptionChans.setSizeAdjustPolicy(QtGui.QComboBox.AdjustToContents)
self.horizontalSplitter_6.addWidget(self.inboxSearchOptionChans) self.horizontalSplitter_6.addWidget(self.inboxSearchOptionChans)
self.horizontalSplitter_6.handle(1).setEnabled(False) self.horizontalSplitter_6.handle(1).set_enabled(False)
self.horizontalSplitter_6.setStretchFactor(0, 1) self.horizontalSplitter_6.setStretchFactor(0, 1)
self.horizontalSplitter_6.setStretchFactor(1, 0) self.horizontalSplitter_6.setStretchFactor(1, 0)
self.verticalSplitter_8.addWidget(self.horizontalSplitter_6) self.verticalSplitter_8.addWidget(self.horizontalSplitter_6)
@ -546,7 +546,7 @@ class Ui_MainWindow(object):
self.verticalSplitter_8.setCollapsible(0, False) self.verticalSplitter_8.setCollapsible(0, False)
self.verticalSplitter_8.setCollapsible(1, False) self.verticalSplitter_8.setCollapsible(1, False)
self.verticalSplitter_8.setCollapsible(2, False) self.verticalSplitter_8.setCollapsible(2, False)
self.verticalSplitter_8.handle(1).setEnabled(False) self.verticalSplitter_8.handle(1).set_enabled(False)
self.horizontalSplitter_7.addWidget(self.verticalSplitter_8) self.horizontalSplitter_7.addWidget(self.verticalSplitter_8)
self.horizontalSplitter_7.setStretchFactor(0, 0) self.horizontalSplitter_7.setStretchFactor(0, 0)
self.horizontalSplitter_7.setStretchFactor(1, 1) self.horizontalSplitter_7.setStretchFactor(1, 1)

View File

@ -30,7 +30,7 @@ class AccountMixin(object):
SUBSCRIPTION = 4 SUBSCRIPTION = 4
BROADCAST = 5 BROADCAST = 5
def accountColor(self): def account_color(self):
"""QT UI color for an account""" """QT UI color for an account"""
if not self.isEnabled: if not self.isEnabled:
return QtGui.QColor(128, 128, 128) return QtGui.QColor(128, 128, 128)
@ -40,25 +40,25 @@ class AccountMixin(object):
return QtGui.QColor(137, 4, 177) return QtGui.QColor(137, 4, 177)
return QtGui.QApplication.palette().text().color() return QtGui.QApplication.palette().text().color()
def folderColor(self): def folder_color(self):
"""QT UI color for a folder""" """QT UI color for a folder"""
if not self.parent().isEnabled: if not self.parent().isEnabled:
return QtGui.QColor(128, 128, 128) return QtGui.QColor(128, 128, 128)
return QtGui.QApplication.palette().text().color() return QtGui.QApplication.palette().text().color()
def accountBrush(self): def account_brush(self):
"""Account brush (for QT UI)""" """Account brush (for QT UI)"""
brush = QtGui.QBrush(self.accountColor()) brush = QtGui.QBrush(self.account_color())
brush.setStyle(QtCore.Qt.NoBrush) brush.setStyle(QtCore.Qt.NoBrush)
return brush return brush
def folderBrush(self): def folder_brush(self):
"""Folder brush (for QT UI)""" """Folder brush (for QT UI)"""
brush = QtGui.QBrush(self.folderColor()) brush = QtGui.QBrush(self.folder_color())
brush.setStyle(QtCore.Qt.NoBrush) brush.setStyle(QtCore.Qt.NoBrush)
return brush return brush
def accountString(self): def account_string(self):
"""Account string suitable for use in To: field: label <address>""" """Account string suitable for use in To: field: label <address>"""
label = self._getLabel() label = self._getLabel()
return ( return (
@ -66,14 +66,11 @@ class AccountMixin(object):
else '%s <%s>' % (label, self.address) else '%s <%s>' % (label, self.address)
) )
def setAddress(self, address): def set_address(self, address):
"""Set bitmessage address of the object""" """Set bitmessage address of the object"""
if address is None: self.address = None if address is None else str(address)
self.address = None
else:
self.address = str(address)
def setUnreadCount(self, cnt): def set_unread_count(self, cnt):
"""Set number of unread messages""" """Set number of unread messages"""
try: try:
if self.unreadCount == int(cnt): if self.unreadCount == int(cnt):
@ -84,17 +81,17 @@ class AccountMixin(object):
if isinstance(self, QtGui.QTreeWidgetItem): if isinstance(self, QtGui.QTreeWidgetItem):
self.emitDataChanged() self.emitDataChanged()
def setEnabled(self, enabled): def set_enabled(self, enabled):
"""Set account enabled (QT UI)""" """Set account enabled (QT UI)"""
self.isEnabled = enabled self.isEnabled = enabled
try: try:
self.setExpanded(enabled) self.setExpanded(enabled)
except AttributeError: except AttributeError:
pass pass
if isinstance(self, Ui_AddressWidget): if isinstance(self, UiAddressWidget):
for i in range(self.childCount()): for i in range(self.childCount()):
if isinstance(self.child(i), Ui_FolderWidget): if isinstance(self.child(i), UiFolderWidget):
self.child(i).setEnabled(enabled) self.child(i).set_enabled(enabled)
if isinstance(self, QtGui.QTreeWidgetItem): if isinstance(self, QtGui.QTreeWidgetItem):
self.emitDataChanged() self.emitDataChanged()
@ -114,7 +111,7 @@ class AccountMixin(object):
else: else:
self.type = self.NORMAL self.type = self.NORMAL
def defaultLabel(self): def default_label(self):
"""Default label (in case no label is set manually)""" """Default label (in case no label is set manually)"""
queryreturn = None queryreturn = None
retval = None retval = None
@ -131,7 +128,7 @@ class AccountMixin(object):
queryreturn = sqlQuery( 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 is not None:
if queryreturn != []: if queryreturn:
for row in queryreturn: for row in queryreturn:
retval, = row retval, = row
retval = unicode(retval, 'utf-8') retval = unicode(retval, 'utf-8')
@ -145,25 +142,25 @@ class AccountMixin(object):
class BMTreeWidgetItem(QtGui.QTreeWidgetItem, AccountMixin): class BMTreeWidgetItem(QtGui.QTreeWidgetItem, AccountMixin):
"""A common abstract class for Tree widget item""" """A common abstract class for Tree widget item"""
def __init__(self, parent, pos, address, unreadCount): def __init__(self, parent, pos, address, unread_count):
super(QtGui.QTreeWidgetItem, self).__init__() super(QtGui.QTreeWidgetItem, self).__init__()
self.setAddress(address) self.set_address(address)
self.setUnreadCount(unreadCount) self.set_unread_count(unread_count)
self._setup(parent, pos) self._setup(parent, pos)
def _getAddressBracket(self, unreadCount=False): def _get_address_bracket(self, unreadCount=False):
return " (" + str(self.unreadCount) + ")" if unreadCount else "" return " (" + str(self.unreadCount) + ")" if unreadCount else ""
def data(self, column, role): def data(self, column, role):
"""Override internal QT method for returning object data""" """Override internal QT method for returning object data"""
if column == 0: if column == 0:
if role == QtCore.Qt.DisplayRole: if role == QtCore.Qt.DisplayRole:
return self._getLabel() + self._getAddressBracket( return self._getLabel() + self._get_address_bracket(
self.unreadCount > 0) self.unreadCount > 0)
elif role == QtCore.Qt.EditRole: elif role == QtCore.Qt.EditRole:
return self._getLabel() return self._getLabel()
elif role == QtCore.Qt.ToolTipRole: elif role == QtCore.Qt.ToolTipRole:
return self._getLabel() + self._getAddressBracket(False) return self._getLabel() + self._get_address_bracket(False)
elif role == QtCore.Qt.FontRole: elif role == QtCore.Qt.FontRole:
font = QtGui.QFont() font = QtGui.QFont()
font.setBold(self.unreadCount > 0) font.setBold(self.unreadCount > 0)
@ -171,35 +168,35 @@ class BMTreeWidgetItem(QtGui.QTreeWidgetItem, AccountMixin):
return super(BMTreeWidgetItem, self).data(column, role) return super(BMTreeWidgetItem, self).data(column, role)
class Ui_FolderWidget(BMTreeWidgetItem): class UiFolderWidget(BMTreeWidgetItem):
"""Item in the account/folder tree representing a folder""" """Item in the account/folder tree representing a folder"""
folderWeight = {"inbox": 1, "new": 2, "sent": 3, "trash": 4} folderWeight = {"inbox": 1, "new": 2, "sent": 3, "trash": 4}
def __init__( def __init__(
self, parent, pos=0, address="", folderName="", unreadCount=0): self, parent, pos=0, address="", folder_name="", unread_count=0):
self.setFolderName(folderName) self.set_folder_name(folder_name)
super(Ui_FolderWidget, self).__init__( super(UiFolderWidget, self).__init__(
parent, pos, address, unreadCount) parent, pos, address, unread_count)
def _setup(self, parent, pos): def _setup(self, parent, pos):
parent.insertChild(pos, self) parent.insertChild(pos, self)
def _getLabel(self): def _get_label(self):
return _translate("MainWindow", self.folderName) return _translate("MainWindow", self.folderName)
def setFolderName(self, fname): def set_folder_name(self, fname):
"""Set folder name (for QT UI)""" """Set folder name (for QT UI)"""
self.folderName = str(fname) self.folderName = str(fname)
def data(self, column, role): def data(self, column, role):
"""Override internal QT method for returning object data""" """Override internal QT method for returning object data"""
if column == 0 and role == QtCore.Qt.ForegroundRole: if column == 0 and role == QtCore.Qt.ForegroundRole:
return self.folderBrush() return self.folder_brush()
return super(Ui_FolderWidget, self).data(column, role) return super(UiFolderWidget, self).data(column, role)
# inbox, sent, thrash first, rest alphabetically # inbox, sent, thrash first, rest alphabetically
def __lt__(self, other): def __lt__(self, other):
if isinstance(other, Ui_FolderWidget): if isinstance(other, UiFolderWidget):
if self.folderName in self.folderWeight: if self.folderName in self.folderWeight:
x = self.folderWeight[self.folderName] x = self.folderWeight[self.folderName]
else: else:
@ -217,18 +214,18 @@ class Ui_FolderWidget(BMTreeWidgetItem):
return super(QtGui.QTreeWidgetItem, self).__lt__(other) return super(QtGui.QTreeWidgetItem, self).__lt__(other)
class Ui_AddressWidget(BMTreeWidgetItem, SettingsMixin): class UiAddressWidget(BMTreeWidgetItem, SettingsMixin):
"""Item in the account/folder tree representing an account""" """Item in the account/folder tree representing an account"""
def __init__(self, parent, pos=0, address=None, unreadCount=0, enabled=True): def __init__(self, parent, pos=0, address=None, unread_count=0, enabled=True):
super(Ui_AddressWidget, self).__init__( super(UiAddressWidget, self).__init__(
parent, pos, address, unreadCount) parent, pos, address, unread_count)
self.setEnabled(enabled) self.set_enabled(enabled)
def _setup(self, parent, pos): def _setup(self, parent, pos):
self.setType() self.setType()
parent.insertTopLevelItem(pos, self) parent.insertTopLevelItem(pos, self)
def _getLabel(self): def _get_label(self):
if self.address is None: if self.address is None:
return unicode(_translate( return unicode(_translate(
"MainWindow", "All accounts").toUtf8(), 'utf-8', 'ignore') "MainWindow", "All accounts").toUtf8(), 'utf-8', 'ignore')
@ -240,11 +237,11 @@ class Ui_AddressWidget(BMTreeWidgetItem, SettingsMixin):
except: except:
return unicode(self.address, 'utf-8') return unicode(self.address, 'utf-8')
def _getAddressBracket(self, unreadCount=False): def _get_address_bracket(self, unread_count=False):
ret = "" if self.isExpanded() \ ret = "" if self.isExpanded() \
else super(Ui_AddressWidget, self)._getAddressBracket(unreadCount) else super(UiAddressWidget, self)._get_address_bracket(unread_count)
if self.address is not None: if self.address is not None:
ret += " (" + self.address + ")" ret += " (%s)" % self.address
return ret return ret
def data(self, column, role): def data(self, column, role):
@ -252,10 +249,10 @@ class Ui_AddressWidget(BMTreeWidgetItem, SettingsMixin):
if column == 0: if column == 0:
if role == QtCore.Qt.DecorationRole: if role == QtCore.Qt.DecorationRole:
return avatarize( return avatarize(
self.address or self._getLabel().encode('utf8')) self.address or self._get_label().encode('utf8'))
elif role == QtCore.Qt.ForegroundRole: elif role == QtCore.Qt.ForegroundRole:
return self.accountBrush() return self.account_brush()
return super(Ui_AddressWidget, self).data(column, role) return super(UiAddressWidget, self).data(column, role)
def setData(self, column, role, value): def setData(self, column, role, value):
"""Save account label (if you edit in the the UI, this will be triggered and will save it to keys.dat)""" """Save account label (if you edit in the the UI, this will be triggered and will save it to keys.dat)"""
@ -268,42 +265,42 @@ class Ui_AddressWidget(BMTreeWidgetItem, SettingsMixin):
else value.encode('utf-8') else value.encode('utf-8')
) )
BMConfigParser().save() BMConfigParser().save()
return super(Ui_AddressWidget, self).setData(column, role, value) return super(UiAddressWidget, self).setData(column, role, value)
def setAddress(self, address): def set_address(self, address):
"""Set address to object (for QT UI)""" """Set address to object (for QT UI)"""
super(Ui_AddressWidget, self).setAddress(address) super(UiAddressWidget, self).set_address(address)
self.setData(0, QtCore.Qt.UserRole, self.address) self.setData(0, QtCore.Qt.UserRole, self.address)
def _getSortRank(self): def _get_sort_rank(self):
return self.type if self.isEnabled else (self.type + 100) return self.type if self.isEnabled else (self.type + 100)
# label (or address) alphabetically, disabled at the end # label (or address) alphabetically, disabled at the end
def __lt__(self, other): def __lt__(self, other):
# pylint: disable=protected-access # pylint: disable=protected-access
if isinstance(other, Ui_AddressWidget): if isinstance(other, UiAddressWidget):
reverse = QtCore.Qt.DescendingOrder == \ reverse = QtCore.Qt.DescendingOrder == \
self.treeWidget().header().sortIndicatorOrder() self.treeWidget().header().sortIndicatorOrder()
if self._getSortRank() == other._getSortRank(): if self._get_sort_rank() == other._get_sort_rank():
x = self._getLabel().lower() x = self._get_label().lower()
y = other._getLabel().lower() y = other._get_label().lower()
return x < y return x < y
return ( return (
not reverse not reverse
if self._getSortRank() < other._getSortRank() else reverse if self._get_sort_rank() < other._get_sort_rank() else reverse
) )
return super(QtGui.QTreeWidgetItem, self).__lt__(other) return super(QtGui.QTreeWidgetItem, self).__lt__(other)
class Ui_SubscriptionWidget(Ui_AddressWidget): class UiSubscriptionWidget(UiAddressWidget):
"""Special treating of subscription addresses""" """Special treating of subscription addresses"""
# pylint: disable=unused-argument # pylint: disable=unused-argument
def __init__(self, parent, pos=0, address="", unreadCount=0, label="", enabled=True): def __init__(self, parent, pos=0, address="", unread_count=0, label="", enabled=True):
super(Ui_SubscriptionWidget, self).__init__( super(UiSubscriptionWidget, self).__init__(
parent, pos, address, unreadCount, enabled) parent, pos, address, unread_count, enabled)
def _getLabel(self): def _get_label(self):
queryreturn = sqlQuery( queryreturn = sqlQuery(
'''select label from subscriptions where address=?''', self.address) '''select label from subscriptions where address=?''', self.address)
if queryreturn != []: if queryreturn != []:
@ -314,7 +311,7 @@ class Ui_SubscriptionWidget(Ui_AddressWidget):
def setType(self): def setType(self):
"""Set account type""" """Set account type"""
super(Ui_SubscriptionWidget, self).setType() # sets it editable super(UiSubscriptionWidget, self).setType() # sets it editable
self.type = AccountMixin.SUBSCRIPTION # overrides type self.type = AccountMixin.SUBSCRIPTION # overrides type
def setData(self, column, role, value): def setData(self, column, role, value):
@ -328,7 +325,7 @@ class Ui_SubscriptionWidget(Ui_AddressWidget):
sqlExecute( sqlExecute(
'''UPDATE subscriptions SET label=? WHERE address=?''', '''UPDATE subscriptions SET label=? WHERE address=?''',
label, self.address) label, self.address)
return super(Ui_SubscriptionWidget, self).setData(column, role, value) return super(UiSubscriptionWidget, self).setData(column, role, value)
class BMTableWidgetItem(QtGui.QTableWidgetItem, SettingsMixin): class BMTableWidgetItem(QtGui.QTableWidgetItem, SettingsMixin):
@ -336,17 +333,17 @@ class BMTableWidgetItem(QtGui.QTableWidgetItem, SettingsMixin):
def __init__(self, parent=None, label=None, unread=False): def __init__(self, parent=None, label=None, unread=False):
super(QtGui.QTableWidgetItem, self).__init__() super(QtGui.QTableWidgetItem, self).__init__()
self.setLabel(label) self.set_label(label)
self.setUnread(unread) self.set_unread(unread)
self._setup() self._setup()
if parent is not None: if parent is not None:
parent.append(self) parent.append(self)
def setLabel(self, label): def set_label(self, label):
"""Set object label""" """Set object label"""
self.label = label self.label = label
def setUnread(self, unread): def set_unread(self, unread):
"""Set/unset read state of an item""" """Set/unset read state of an item"""
self.unread = unread self.unread = unread
@ -367,9 +364,9 @@ class BMAddressWidget(BMTableWidgetItem, AccountMixin):
"""A common class for Table widget item with account""" """A common class for Table widget item with account"""
def _setup(self): def _setup(self):
self.setEnabled(True) self.set_enabled(True)
def _getLabel(self): def _get_label(self):
return self.label return self.label
def data(self, role): def data(self, role):
@ -381,33 +378,33 @@ class BMAddressWidget(BMTableWidgetItem, AccountMixin):
'bitmessagesettings', 'useidenticons'): 'bitmessagesettings', 'useidenticons'):
return avatarize(self.address or self.label) return avatarize(self.address or self.label)
elif role == QtCore.Qt.ForegroundRole: elif role == QtCore.Qt.ForegroundRole:
return self.accountBrush() return self.account_brush()
return super(BMAddressWidget, self).data(role) return super(BMAddressWidget, self).data(role)
class MessageList_AddressWidget(BMAddressWidget): class MessageListAddressWidget(BMAddressWidget):
"""Address item in a messagelist""" """Address item in a messagelist"""
def __init__(self, parent, address=None, label=None, unread=False): def __init__(self, parent, address=None, label=None, unread=False):
self.setAddress(address) self.set_address(address)
super(MessageList_AddressWidget, self).__init__(parent, label, unread) super(MessageListAddressWidget, self).__init__(parent, label, unread)
def _setup(self): def _setup(self):
self.isEnabled = True self.isEnabled = True
self.setFlags(QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled) self.setFlags(QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
self.setType() self.setType()
def setLabel(self, label=None): def set_label(self, label=None):
"""Set label""" """Set label"""
super(MessageList_AddressWidget, self).setLabel(label) super(MessageListAddressWidget, self).set_label(label)
if label is not None: if label is not None:
return return
newLabel = self.address new_label = self.address
queryreturn = None queryreturn = None
if self.type in ( if self.type in (
AccountMixin.NORMAL, AccountMixin.NORMAL,
AccountMixin.CHAN, AccountMixin.MAILINGLIST): AccountMixin.CHAN, AccountMixin.MAILINGLIST):
try: try:
newLabel = unicode( new_label = unicode(
BMConfigParser().get(self.address, 'label'), BMConfigParser().get(self.address, 'label'),
'utf-8', 'ignore') 'utf-8', 'ignore')
except: except:
@ -418,39 +415,39 @@ class MessageList_AddressWidget(BMAddressWidget):
'''select label from subscriptions where address=?''', self.address) '''select label from subscriptions where address=?''', self.address)
if queryreturn: if queryreturn:
for row in queryreturn: for row in queryreturn:
newLabel = unicode(row[0], 'utf-8', 'ignore') new_label = unicode(row[0], 'utf-8', 'ignore')
self.label = newLabel self.label = new_label
def data(self, role): def data(self, role):
"""Return object data (QT UI)""" """Return object data (QT UI)"""
if role == QtCore.Qt.UserRole: if role == QtCore.Qt.UserRole:
return self.address return self.address
return super(MessageList_AddressWidget, self).data(role) return super(MessageListAddressWidget, self).data(role)
def setData(self, role, value): def setData(self, role, value):
"""Set object data""" """Set object data"""
if role == QtCore.Qt.EditRole: if role == QtCore.Qt.EditRole:
self.setLabel() self.set_label()
return super(MessageList_AddressWidget, self).setData(role, value) return super(MessageListAddressWidget, self).setData(role, value)
# label (or address) alphabetically, disabled at the end # label (or address) alphabetically, disabled at the end
def __lt__(self, other): def __lt__(self, other):
if isinstance(other, MessageList_AddressWidget): if isinstance(other, MessageListAddressWidget):
return self.label.lower() < other.label.lower() return self.label.lower() < other.label.lower()
return super(QtGui.QTableWidgetItem, self).__lt__(other) return super(QtGui.QTableWidgetItem, self).__lt__(other)
class MessageList_SubjectWidget(BMTableWidgetItem): class MessageListSubjectWidget(BMTableWidgetItem):
"""Message list subject item""" """Message list subject item"""
def __init__(self, parent, subject=None, label=None, unread=False): def __init__(self, parent, subject=None, label=None, unread=False):
self.setSubject(subject) self.set_subject(subject)
super(MessageList_SubjectWidget, self).__init__(parent, label, unread) super(MessageListSubjectWidget, self).__init__(parent, label, unread)
def _setup(self): def _setup(self):
self.setFlags(QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled) self.setFlags(QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
def setSubject(self, subject): def set_subject(self, subject):
"""Set subject""" """Set subject"""
self.subject = subject self.subject = subject
@ -460,27 +457,27 @@ class MessageList_SubjectWidget(BMTableWidgetItem):
return self.subject return self.subject
if role == QtCore.Qt.ToolTipRole: if role == QtCore.Qt.ToolTipRole:
return escape(unicode(self.subject, 'utf-8')) return escape(unicode(self.subject, 'utf-8'))
return super(MessageList_SubjectWidget, self).data(role) return super(MessageListSubjectWidget, self).data(role)
# label (or address) alphabetically, disabled at the end # label (or address) alphabetically, disabled at the end
def __lt__(self, other): def __lt__(self, other):
if isinstance(other, MessageList_SubjectWidget): if isinstance(other, MessageListSubjectWidget):
return self.label.lower() < other.label.lower() return self.label.lower() < other.label.lower()
return super(QtGui.QTableWidgetItem, self).__lt__(other) return super(QtGui.QTableWidgetItem, self).__lt__(other)
class Ui_AddressBookWidgetItem(BMAddressWidget): class UiAddressBookWidgetItem(BMAddressWidget):
"""Addressbook item""" """Addressbook item"""
# pylint: disable=unused-argument # pylint: disable=unused-argument
def __init__(self, label=None, acc_type=AccountMixin.NORMAL): def __init__(self, label=None, acc_type=AccountMixin.NORMAL):
self.type = acc_type self.type = acc_type
super(Ui_AddressBookWidgetItem, self).__init__(label=label) super(UiAddressBookWidgetItem, self).__init__(label=label)
def data(self, role): def data(self, role):
"""Return object data""" """Return object data"""
if role == QtCore.Qt.UserRole: if role == QtCore.Qt.UserRole:
return self.type return self.type
return super(Ui_AddressBookWidgetItem, self).data(role) return super(UiAddressBookWidgetItem, self).data(role)
def setData(self, role, value): def setData(self, role, value):
"""Set data""" """Set data"""
@ -502,10 +499,10 @@ class Ui_AddressBookWidgetItem(BMAddressWidget):
sqlExecute('''UPDATE subscriptions set label=? WHERE address=?''', self.label, self.address) sqlExecute('''UPDATE subscriptions set label=? WHERE address=?''', self.label, self.address)
else: else:
pass pass
return super(Ui_AddressBookWidgetItem, self).setData(role, value) return super(UiAddressBookWidgetItem, self).setData(role, value)
def __lt__(self, other): def __lt__(self, other):
if isinstance(other, Ui_AddressBookWidgetItem): if isinstance(other, UiAddressBookWidgetItem):
reverse = QtCore.Qt.DescendingOrder == \ reverse = QtCore.Qt.DescendingOrder == \
self.tableWidget().horizontalHeader().sortIndicatorOrder() self.tableWidget().horizontalHeader().sortIndicatorOrder()
@ -515,22 +512,22 @@ class Ui_AddressBookWidgetItem(BMAddressWidget):
return super(QtGui.QTableWidgetItem, self).__lt__(other) return super(QtGui.QTableWidgetItem, self).__lt__(other)
class Ui_AddressBookWidgetItemLabel(Ui_AddressBookWidgetItem): class UiAddressBookWidgetItemLabel(UiAddressBookWidgetItem):
"""Addressbook label item""" """Addressbook label item"""
def __init__(self, address, label, acc_type): def __init__(self, address, label, acc_type):
super(Ui_AddressBookWidgetItemLabel, self).__init__(label, acc_type) super(UiAddressBookWidgetItemLabel, self).__init__(label, acc_type)
self.address = address self.address = address
def data(self, role): def data(self, role):
"""Return object data""" """Return object data"""
self.label = self.defaultLabel() self.label = self.default_label()
return super(Ui_AddressBookWidgetItemLabel, self).data(role) return super(UiAddressBookWidgetItemLabel, self).data(role)
class Ui_AddressBookWidgetItemAddress(Ui_AddressBookWidgetItem): class UiAddressBookWidgetItemAddress(UiAddressBookWidgetItem):
"""Addressbook address item""" """Addressbook address item"""
def __init__(self, address, label, acc_type): def __init__(self, address, label, acc_type):
super(Ui_AddressBookWidgetItemAddress, self).__init__(address, acc_type) super(UiAddressBookWidgetItemAddress, self).__init__(address, acc_type)
self.address = address self.address = address
self.setFlags(QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled) self.setFlags(QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
@ -540,7 +537,7 @@ class Ui_AddressBookWidgetItemAddress(Ui_AddressBookWidgetItem):
return self.address return self.address
if role == QtCore.Qt.DecorationRole: if role == QtCore.Qt.DecorationRole:
return None return None
return super(Ui_AddressBookWidgetItemAddress, self).data(role) return super(UiAddressBookWidgetItemAddress, self).data(role)
class AddressBookCompleter(QtGui.QCompleter): class AddressBookCompleter(QtGui.QCompleter):
@ -550,7 +547,7 @@ class AddressBookCompleter(QtGui.QCompleter):
super(AddressBookCompleter, self).__init__() super(AddressBookCompleter, self).__init__()
self.cursorPos = -1 self.cursorPos = -1
def onCursorPositionChanged(self, oldPos, newPos): # pylint: disable=unused-argument def on_cursor_position_changed(self, oldPos, newPos): # pylint: disable=unused-argument
"""Callback for cursor position change""" """Callback for cursor position change"""
if oldPos != self.cursorPos: if oldPos != self.cursorPos:
self.cursorPos = -1 self.cursorPos = -1
@ -562,7 +559,7 @@ class AddressBookCompleter(QtGui.QCompleter):
def pathFromIndex(self, index): def pathFromIndex(self, index):
"""Perform autocompletion (reimplemented QCompleter method)""" """Perform autocompletion (reimplemented QCompleter method)"""
autoString = unicode( auto_string = unicode(
index.data(QtCore.Qt.EditRole).toString().toUtf8(), 'utf-8') index.data(QtCore.Qt.EditRole).toString().toUtf8(), 'utf-8')
text = unicode(self.widget().text().toUtf8(), 'utf-8') text = unicode(self.widget().text().toUtf8(), 'utf-8')
@ -573,28 +570,28 @@ class AddressBookCompleter(QtGui.QCompleter):
self.cursorPos = self.widget().cursorPosition() self.cursorPos = self.widget().cursorPosition()
# Get current prosition # Get current prosition
curIndex = self.widget().cursorPosition() cur_index = self.widget().cursorPosition()
# prev_delimiter_index should actually point at final white space # prev_delimiter_index should actually point at final white space
# AFTER the delimiter # AFTER the delimiter
# Get index of last delimiter before current position # Get index of last delimiter before current position
prevDelimiterIndex = text[0:curIndex].rfind(";") prev_delimiter_index = text[0:cur_index].rfind(";")
while text[prevDelimiterIndex + 1] == " ": while text[prev_delimiter_index + 1] == " ":
prevDelimiterIndex += 1 prev_delimiter_index += 1
# Get index of first delimiter after current position # Get index of first delimiter after current position
# (or EOL if no delimiter after cursor) # (or EOL if no delimiter after cursor)
nextDelimiterIndex = text.find(";", curIndex) next_delimiter_index = text.find(";", cur_index)
if nextDelimiterIndex == -1: if next_delimiter_index == -1:
nextDelimiterIndex = len(text) next_delimiter_index = len(text)
# Get part of string that occurs before cursor # Get part of string that occurs before cursor
part1 = text[0:prevDelimiterIndex + 1] part1 = text[0:prev_delimiter_index + 1]
# Get string value from before auto finished string is selected # Get string value from before auto finished string is selected
# pre = text[prevDelimiterIndex + 1:curIndex - 1] # pre = text[prev_delimiter_index + 1:cur_index - 1]
# Get part of string that occurs AFTER cursor # Get part of string that occurs AFTER cursor
part2 = text[nextDelimiterIndex:] part2 = text[next_delimiter_index:]
return part1 + autoString + part2 return part1 + auto_string + part2

View File

@ -4,6 +4,10 @@ and suggest how it may be installed
""" """
import sys import sys
import logging
import os
from importlib import import_module
# Only really old versions of Python don't have sys.hexversion. We don't # Only really old versions of Python don't have sys.hexversion. We don't
# support them. The logging module was introduced in Python 2.3 # support them. The logging module was introduced in Python 2.3
@ -14,10 +18,6 @@ if not hasattr(sys, 'hexversion') or sys.hexversion < 0x20300F0:
% sys.version % sys.version
) )
import logging
import os
from importlib import import_module
# We can now use logging so set up a simple configuration # We can now use logging so set up a simple configuration
formatter = logging.Formatter('%(levelname)s: %(message)s') formatter = logging.Formatter('%(levelname)s: %(message)s')
handler = logging.StreamHandler(sys.stdout) handler = logging.StreamHandler(sys.stdout)
@ -112,39 +112,39 @@ PACKAGES = {
} }
def detectOS(): def detect_os():
if detectOS.result is not None: if detect_os.result is not None:
return detectOS.result return detect_os.result
if sys.platform.startswith('openbsd'): if sys.platform.startswith('openbsd'):
detectOS.result = "OpenBSD" detect_os.result = "OpenBSD"
elif sys.platform.startswith('freebsd'): elif sys.platform.startswith('freebsd'):
detectOS.result = "FreeBSD" detect_os.result = "FreeBSD"
elif sys.platform.startswith('win'): elif sys.platform.startswith('win'):
detectOS.result = "Windows" detect_os.result = "Windows"
elif os.path.isfile("/etc/os-release"): elif os.path.isfile("/etc/os-release"):
detectOSRelease() detect_os_release()
elif os.path.isfile("/etc/config.scm"): elif os.path.isfile("/etc/config.scm"):
detectOS.result = "Guix" detect_os.result = "Guix"
return detectOS.result return detect_os.result
detectOS.result = None detect_os.result = None
def detectOSRelease(): def detect_os_release():
with open("/etc/os-release", 'r') as osRelease: with open("/etc/os-release", 'r') as osRelease:
version = None version = None
for line in osRelease: for line in osRelease:
if line.startswith("NAME="): if line.startswith("NAME="):
detectOS.result = OS_RELEASE.get( detect_os.result = OS_RELEASE.get(
line.replace('"', '').split("=")[-1].strip().lower()) line.replace('"', '').split("=")[-1].strip().lower())
elif line.startswith("VERSION_ID="): elif line.startswith("VERSION_ID="):
try: try:
version = float(line.split("=")[1].replace("\"", "")) version = float(line.split("=")[1].replace("\"", ""))
except ValueError: except ValueError:
pass pass
if detectOS.result == "Ubuntu" and version < 14: if detect_os.result == "Ubuntu" and version < 14:
detectOS.result = "Ubuntu 12" detect_os.result = "Ubuntu 12"
def try_import(module, log_extra=False): def try_import(module, log_extra=False):
@ -155,7 +155,7 @@ def try_import(module, log_extra=False):
logger.error('The %s module is not available.', module) logger.error('The %s module is not available.', module)
if log_extra: if log_extra:
logger.error(log_extra) logger.error(log_extra)
dist = detectOS() dist = detect_os()
logger.error( logger.error(
'On %s, try running "%s %s" as root.', 'On %s, try running "%s %s" as root.',
dist, PACKAGE_MANAGER[dist], PACKAGES[module][dist]) dist, PACKAGE_MANAGER[dist], PACKAGES[module][dist])