Merge branch 'v0.6' into readthedocs

This commit is contained in:
Peter Šurda 2018-06-26 15:25:27 +02:00 committed by GitHub
commit 354bf45d54
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
4 changed files with 1122 additions and 1570 deletions

View File

@ -1,9 +1,5 @@
# pylint: disable=too-many-lines,broad-except,too-many-instance-attributes,global-statement,too-few-public-methods
# pylint: disable=too-many-statements,too-many-branches,attribute-defined-outside-init,too-many-arguments,no-member
# pylint: disable=unused-argument,no-self-use,too-many-locals,unused-variable,too-many-nested-blocks
# pylint: disable=too-many-return-statements,protected-access,super-init-not-called,non-parent-init-called
""" """
Initialise the QT interface PyQt based UI for bitmessage, the main module
""" """
import hashlib import hashlib
@ -15,64 +11,51 @@ import sys
import textwrap import textwrap
import time import time
from datetime import datetime, timedelta from datetime import datetime, timedelta
from sqlite3 import register_adapter
import debug
from debug import logger
try:
from PyQt4 import QtCore, QtGui from PyQt4 import QtCore, QtGui
from PyQt4.QtNetwork import QLocalSocket, QLocalServer from PyQt4.QtNetwork import QLocalSocket, QLocalServer
except ImportError:
logmsg = (
'PyBitmessage requires PyQt unless you want to run it as a daemon and interact with it using the API. You can'
' download it from http://www.riverbankcomputing.com/software/pyqt/download or by searching Google for '
'\'PyQt Download\' (without quotes).'
)
logger.critical(logmsg, exc_info=True)
sys.exit()
from sqlite3 import register_adapter # pylint: disable=wrong-import-order
from debug import logger
from tr import _translate
from addresses import decodeAddress, addBMIfNotPresent
import shared
from bitmessageui import Ui_MainWindow
from bmconfigparser import BMConfigParser
import defaults import defaults
from namecoin import namecoinConnection
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 helper_search
import knownnodes
import l10n import l10n
import openclpow import openclpow
from utils import str_broadcast_subscribers, avatarize
from account import (
getSortedAccounts, getSortedSubscriptions, accountClass, BMAccount,
GatewayAccount, MailchuckAccount, AccountColor)
import dialogs
from helper_generic import powQueueSize
from network.stats import pendingDownload, pendingUpload
from uisignaler import UISignaler
import knownnodes
import paths import paths
from proofofwork import getPowType
import queues import queues
import shared
import shutdown import shutdown
import state import state
import upnp from statusbar import BMStatusBar
from bitmessageqt import sound, support, dialogs
from bitmessageqt.foldertree import (
AccountMixin, Ui_FolderWidget, Ui_AddressWidget, Ui_SubscriptionWidget, MessageList_AddressWidget,
MessageList_SubjectWidget, Ui_AddressBookWidgetItemLabel, Ui_AddressBookWidgetItemAddress,
)
from bitmessageqt.account import (
getSortedAccounts, getSortedSubscriptions, accountClass, BMAccount, GatewayAccount, MailchuckAccount, AccountColor,
)
from bitmessageqt.bitmessageui import Ui_MainWindow, settingsmixin
from bitmessageqt.messageview import MessageView
from bitmessageqt.migrationwizard import Ui_MigrationWizard
from bitmessageqt.settings import Ui_settingsDialog
from bitmessageqt.utils import str_broadcast_subscribers, avatarize
from bitmessageqt.uisignaler import UISignaler
from bitmessageqt.statusbar import BMStatusBar
from addresses import decodeAddress, addBMIfNotPresent
from bmconfigparser import BMConfigParser
from namecoin import namecoinConnection
from helper_ackPayload import genAckPayload
from helper_generic import powQueueSize
from helper_sql import sqlQuery, sqlExecute, sqlExecuteChunked, sqlStoredProcedure
from network.stats import pendingDownload, pendingUpload
from network.asyncore_pollchoose import set_rates from network.asyncore_pollchoose import set_rates
from proofofwork import getPowType import sound
from tr import _translate
try: try:
@ -81,15 +64,8 @@ except ImportError:
get_plugins = False get_plugins = False
qmytranslator = None
qsystranslator = None
def change_translation(newlocale): def change_translation(newlocale):
"""Change a translation to a new locale"""
global qmytranslator, qsystranslator global qmytranslator, qsystranslator
try: try:
if not qmytranslator.isEmpty(): if not qmytranslator.isEmpty():
QtGui.QApplication.removeTranslator(qmytranslator) QtGui.QApplication.removeTranslator(qmytranslator)
@ -110,8 +86,7 @@ def change_translation(newlocale):
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( translationpath = os.path.join (str(QtCore.QLibraryInfo.location(QtCore.QLibraryInfo.TranslationsPath)), 'qt_' + newlocale)
QtCore.QLibraryInfo.TranslationsPath)), 'qt_' + newlocale)
qsystranslator.load(translationpath) qsystranslator.load(translationpath)
QtGui.QApplication.installTranslator(qsystranslator) QtGui.QApplication.installTranslator(qsystranslator)
@ -132,8 +107,7 @@ def change_translation(newlocale):
logger.error("Failed to set locale to %s", lang, exc_info=True) logger.error("Failed to set locale to %s", lang, exc_info=True)
class MyForm(settingsmixin.SMainWindow): # pylint: disable=too-many-public-methods class MyForm(settingsmixin.SMainWindow):
"""TBC"""
# the last time that a message arrival sound was played # the last time that a message arrival sound was played
lastSoundTime = datetime.now() - timedelta(days=1) lastSoundTime = datetime.now() - timedelta(days=1)
@ -145,8 +119,6 @@ class MyForm(settingsmixin.SMainWindow): # pylint: disable=too-many-public-meth
REPLY_TYPE_CHAN = 1 REPLY_TYPE_CHAN = 1
def init_file_menu(self): def init_file_menu(self):
"""Initialise the file menu"""
QtCore.QObject.connect(self.ui.actionExit, QtCore.SIGNAL( QtCore.QObject.connect(self.ui.actionExit, QtCore.SIGNAL(
"triggered()"), self.quit) "triggered()"), self.quit)
QtCore.QObject.connect(self.ui.actionNetworkSwitch, QtCore.SIGNAL( QtCore.QObject.connect(self.ui.actionNetworkSwitch, QtCore.SIGNAL(
@ -161,9 +133,8 @@ class MyForm(settingsmixin.SMainWindow): # pylint: disable=too-many-public-meth
QtCore.SIGNAL( QtCore.SIGNAL(
"triggered()"), "triggered()"),
self.click_actionRegenerateDeterministicAddresses) self.click_actionRegenerateDeterministicAddresses)
QtCore.QObject.connect( QtCore.QObject.connect(self.ui.pushButtonAddChan, QtCore.SIGNAL(
self.ui.pushButtonAddChan, "clicked()"),
QtCore.SIGNAL("clicked()"),
self.click_actionJoinChan) # also used for creating chans. self.click_actionJoinChan) # also used for creating chans.
QtCore.QObject.connect(self.ui.pushButtonNewAddress, QtCore.SIGNAL( QtCore.QObject.connect(self.ui.pushButtonNewAddress, QtCore.SIGNAL(
"clicked()"), self.click_NewAddressDialog) "clicked()"), self.click_NewAddressDialog)
@ -189,8 +160,7 @@ class MyForm(settingsmixin.SMainWindow): # pylint: disable=too-many-public-meth
"triggered()"), self.click_actionHelp) "triggered()"), self.click_actionHelp)
def init_inbox_popup_menu(self, connectSignal=True): def init_inbox_popup_menu(self, connectSignal=True):
"""Popup menu for the Inbox tab""" # Popup menu for the Inbox tab
self.ui.inboxContextMenuToolbar = QtGui.QToolBar() self.ui.inboxContextMenuToolbar = QtGui.QToolBar()
# Actions # Actions
self.actionReply = self.ui.inboxContextMenuToolbar.addAction(_translate( self.actionReply = self.ui.inboxContextMenuToolbar.addAction(_translate(
@ -227,28 +197,24 @@ class MyForm(settingsmixin.SMainWindow): # pylint: disable=too-many-public-meth
self.ui.tableWidgetInbox.setContextMenuPolicy( self.ui.tableWidgetInbox.setContextMenuPolicy(
QtCore.Qt.CustomContextMenu) QtCore.Qt.CustomContextMenu)
if connectSignal: if connectSignal:
self.connect( self.connect(self.ui.tableWidgetInbox, QtCore.SIGNAL(
self.ui.tableWidgetInbox, 'customContextMenuRequested(const QPoint&)'),
QtCore.SIGNAL('customContextMenuRequested(const QPoint&)'),
self.on_context_menuInbox) self.on_context_menuInbox)
self.ui.tableWidgetInboxSubscriptions.setContextMenuPolicy( self.ui.tableWidgetInboxSubscriptions.setContextMenuPolicy(
QtCore.Qt.CustomContextMenu) QtCore.Qt.CustomContextMenu)
if connectSignal: if connectSignal:
self.connect( self.connect(self.ui.tableWidgetInboxSubscriptions, QtCore.SIGNAL(
self.ui.tableWidgetInboxSubscriptions, 'customContextMenuRequested(const QPoint&)'),
QtCore.SIGNAL('customContextMenuRequested(const QPoint&)'),
self.on_context_menuInbox) self.on_context_menuInbox)
self.ui.tableWidgetInboxChans.setContextMenuPolicy( self.ui.tableWidgetInboxChans.setContextMenuPolicy(
QtCore.Qt.CustomContextMenu) QtCore.Qt.CustomContextMenu)
if connectSignal: if connectSignal:
self.connect( self.connect(self.ui.tableWidgetInboxChans, QtCore.SIGNAL(
self.ui.tableWidgetInboxChans, 'customContextMenuRequested(const QPoint&)'),
QtCore.SIGNAL('customContextMenuRequested(const QPoint&)'),
self.on_context_menuInbox) self.on_context_menuInbox)
def init_identities_popup_menu(self, connectSignal=True): def init_identities_popup_menu(self, connectSignal=True):
"""Popup menu for the Your Identities tab""" # Popup menu for the Your Identities tab
self.ui.addressContextMenuToolbarYourIdentities = QtGui.QToolBar() self.ui.addressContextMenuToolbarYourIdentities = QtGui.QToolBar()
# Actions # Actions
self.actionNewYourIdentities = self.ui.addressContextMenuToolbarYourIdentities.addAction(_translate( self.actionNewYourIdentities = self.ui.addressContextMenuToolbarYourIdentities.addAction(_translate(
@ -283,9 +249,8 @@ class MyForm(settingsmixin.SMainWindow): # pylint: disable=too-many-public-meth
self.ui.treeWidgetYourIdentities.setContextMenuPolicy( self.ui.treeWidgetYourIdentities.setContextMenuPolicy(
QtCore.Qt.CustomContextMenu) QtCore.Qt.CustomContextMenu)
if connectSignal: if connectSignal:
self.connect( self.connect(self.ui.treeWidgetYourIdentities, QtCore.SIGNAL(
self.ui.treeWidgetYourIdentities, 'customContextMenuRequested(const QPoint&)'),
QtCore.SIGNAL('customContextMenuRequested(const QPoint&)'),
self.on_context_menuYourIdentities) self.on_context_menuYourIdentities)
# load all gui.menu plugins with prefix 'address' # load all gui.menu plugins with prefix 'address'
@ -301,8 +266,7 @@ class MyForm(settingsmixin.SMainWindow): # pylint: disable=too-many-public-meth
)) ))
def init_chan_popup_menu(self, connectSignal=True): def init_chan_popup_menu(self, connectSignal=True):
"""Popup menu for the Channels tab""" # Popup menu for the Channels tab
self.ui.addressContextMenuToolbar = QtGui.QToolBar() self.ui.addressContextMenuToolbar = QtGui.QToolBar()
# Actions # Actions
self.actionNew = self.ui.addressContextMenuToolbar.addAction(_translate( self.actionNew = self.ui.addressContextMenuToolbar.addAction(_translate(
@ -332,14 +296,12 @@ class MyForm(settingsmixin.SMainWindow): # pylint: disable=too-many-public-meth
self.ui.treeWidgetChans.setContextMenuPolicy( self.ui.treeWidgetChans.setContextMenuPolicy(
QtCore.Qt.CustomContextMenu) QtCore.Qt.CustomContextMenu)
if connectSignal: if connectSignal:
self.connect( self.connect(self.ui.treeWidgetChans, QtCore.SIGNAL(
self.ui.treeWidgetChans, 'customContextMenuRequested(const QPoint&)'),
QtCore.SIGNAL('customContextMenuRequested(const QPoint&)'),
self.on_context_menuChan) self.on_context_menuChan)
def init_addressbook_popup_menu(self, connectSignal=True): def init_addressbook_popup_menu(self, connectSignal=True):
"""Popup menu for the Address Book page""" # Popup menu for the Address Book page
self.ui.addressBookContextMenuToolbar = QtGui.QToolBar() self.ui.addressBookContextMenuToolbar = QtGui.QToolBar()
# Actions # Actions
self.actionAddressBookSend = self.ui.addressBookContextMenuToolbar.addAction( self.actionAddressBookSend = self.ui.addressBookContextMenuToolbar.addAction(
@ -371,14 +333,12 @@ class MyForm(settingsmixin.SMainWindow): # pylint: disable=too-many-public-meth
self.ui.tableWidgetAddressBook.setContextMenuPolicy( self.ui.tableWidgetAddressBook.setContextMenuPolicy(
QtCore.Qt.CustomContextMenu) QtCore.Qt.CustomContextMenu)
if connectSignal: if connectSignal:
self.connect( self.connect(self.ui.tableWidgetAddressBook, QtCore.SIGNAL(
self.ui.tableWidgetAddressBook, 'customContextMenuRequested(const QPoint&)'),
QtCore.SIGNAL('customContextMenuRequested(const QPoint&)'),
self.on_context_menuAddressBook) self.on_context_menuAddressBook)
def init_subscriptions_popup_menu(self, connectSignal=True): def init_subscriptions_popup_menu(self, connectSignal=True):
"""Popup menu for the Subscriptions page""" # Popup menu for the Subscriptions page
self.ui.subscriptionsContextMenuToolbar = QtGui.QToolBar() self.ui.subscriptionsContextMenuToolbar = QtGui.QToolBar()
# Actions # Actions
self.actionsubscriptionsNew = self.ui.subscriptionsContextMenuToolbar.addAction( self.actionsubscriptionsNew = self.ui.subscriptionsContextMenuToolbar.addAction(
@ -401,14 +361,12 @@ class MyForm(settingsmixin.SMainWindow): # pylint: disable=too-many-public-meth
self.ui.treeWidgetSubscriptions.setContextMenuPolicy( self.ui.treeWidgetSubscriptions.setContextMenuPolicy(
QtCore.Qt.CustomContextMenu) QtCore.Qt.CustomContextMenu)
if connectSignal: if connectSignal:
self.connect( self.connect(self.ui.treeWidgetSubscriptions, QtCore.SIGNAL(
self.ui.treeWidgetSubscriptions, 'customContextMenuRequested(const QPoint&)'),
QtCore.SIGNAL('customContextMenuRequested(const QPoint&)'),
self.on_context_menuSubscriptions) self.on_context_menuSubscriptions)
def init_sent_popup_menu(self, connectSignal=True): def init_sent_popup_menu(self, connectSignal=True):
"""Popup menu for the Sent page""" # Popup menu for the Sent page
self.ui.sentContextMenuToolbar = QtGui.QToolBar() self.ui.sentContextMenuToolbar = QtGui.QToolBar()
# Actions # Actions
self.actionTrashSentMessage = self.ui.sentContextMenuToolbar.addAction( self.actionTrashSentMessage = self.ui.sentContextMenuToolbar.addAction(
@ -421,10 +379,11 @@ class MyForm(settingsmixin.SMainWindow): # pylint: disable=too-many-public-meth
self.actionForceSend = self.ui.sentContextMenuToolbar.addAction( self.actionForceSend = self.ui.sentContextMenuToolbar.addAction(
_translate( _translate(
"MainWindow", "Force send"), self.on_action_ForceSend) "MainWindow", "Force send"), self.on_action_ForceSend)
# self.popMenuSent = QtGui.QMenu( self )
# self.popMenuSent.addAction( self.actionSentClipboard )
# self.popMenuSent.addAction( self.actionTrashSentMessage )
def rerenderTabTreeSubscriptions(self): def rerenderTabTreeSubscriptions(self):
"""TBC"""
treeWidget = self.ui.treeWidgetSubscriptions treeWidget = self.ui.treeWidgetSubscriptions
folders = Ui_FolderWidget.folderWeight.keys() folders = Ui_FolderWidget.folderWeight.keys()
folders.remove("new") folders.remove("new")
@ -438,12 +397,13 @@ class MyForm(settingsmixin.SMainWindow): # pylint: disable=too-many-public-meth
db = getSortedSubscriptions(True) db = getSortedSubscriptions(True)
for address in db: for address in db:
for folder in folders: for folder in folders:
if folder not in db[address]: if not folder in db[address]:
db[address][folder] = {} db[address][folder] = {}
if treeWidget.isSortingEnabled(): if treeWidget.isSortingEnabled():
treeWidget.setSortingEnabled(False) treeWidget.setSortingEnabled(False)
widgets = {}
i = 0 i = 0
while i < treeWidget.topLevelItemCount(): while i < treeWidget.topLevelItemCount():
widget = treeWidget.topLevelItem(i) widget = treeWidget.topLevelItem(i)
@ -452,7 +412,7 @@ class MyForm(settingsmixin.SMainWindow): # pylint: disable=too-many-public-meth
else: else:
toAddress = None toAddress = None
if toAddress not in db: if not toAddress in db:
treeWidget.takeTopLevelItem(i) treeWidget.takeTopLevelItem(i)
# no increment # no increment
continue continue
@ -471,7 +431,7 @@ class MyForm(settingsmixin.SMainWindow): # pylint: disable=too-many-public-meth
j += 1 j += 1
# add missing folders # add missing folders
if db[toAddress]: if len(db[toAddress]) > 0:
j = 0 j = 0
for f, c in db[toAddress].iteritems(): for f, c in db[toAddress].iteritems():
try: try:
@ -485,11 +445,7 @@ class MyForm(settingsmixin.SMainWindow): # pylint: disable=too-many-public-meth
i = 0 i = 0
for toAddress in db: for toAddress in db:
widget = Ui_SubscriptionWidget( widget = Ui_SubscriptionWidget(treeWidget, i, toAddress, db[toAddress]["inbox"]['count'], db[toAddress]["inbox"]['label'], db[toAddress]["inbox"]['enabled'])
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:
@ -504,19 +460,14 @@ class MyForm(settingsmixin.SMainWindow): # pylint: disable=too-many-public-meth
treeWidget.setSortingEnabled(True) treeWidget.setSortingEnabled(True)
def rerenderTabTreeMessages(self):
"""TBC"""
def rerenderTabTreeMessages(self):
self.rerenderTabTree('messages') self.rerenderTabTree('messages')
def rerenderTabTreeChans(self): def rerenderTabTreeChans(self):
"""TBC"""
self.rerenderTabTree('chan') self.rerenderTabTree('chan')
def rerenderTabTree(self, tab): def rerenderTabTree(self, tab):
"""TBC"""
if tab == 'messages': if tab == 'messages':
treeWidget = self.ui.treeWidgetYourIdentities treeWidget = self.ui.treeWidgetYourIdentities
elif tab == 'chan': elif tab == 'chan':
@ -536,6 +487,8 @@ class MyForm(settingsmixin.SMainWindow): # pylint: disable=too-many-public-meth
toAddress, 'enabled') toAddress, 'enabled')
isChan = BMConfigParser().safeGetBoolean( isChan = BMConfigParser().safeGetBoolean(
toAddress, 'chan') toAddress, 'chan')
isMaillinglist = BMConfigParser().safeGetBoolean(
toAddress, 'mailinglist')
if treeWidget == self.ui.treeWidgetYourIdentities: if treeWidget == self.ui.treeWidgetYourIdentities:
if isChan: if isChan:
@ -552,8 +505,7 @@ class MyForm(settingsmixin.SMainWindow): # pylint: disable=too-many-public-meth
# get number of (unread) messages # get number of (unread) messages
total = 0 total = 0
queryreturn = sqlQuery( queryreturn = sqlQuery('SELECT toaddress, folder, count(msgid) as cnt FROM inbox WHERE read = 0 GROUP BY toaddress, folder')
'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
@ -570,6 +522,7 @@ class MyForm(settingsmixin.SMainWindow): # pylint: disable=too-many-public-meth
if treeWidget.isSortingEnabled(): if treeWidget.isSortingEnabled():
treeWidget.setSortingEnabled(False) treeWidget.setSortingEnabled(False)
widgets = {}
i = 0 i = 0
while i < treeWidget.topLevelItemCount(): while i < treeWidget.topLevelItemCount():
widget = treeWidget.topLevelItem(i) widget = treeWidget.topLevelItem(i)
@ -578,7 +531,7 @@ class MyForm(settingsmixin.SMainWindow): # pylint: disable=too-many-public-meth
else: else:
toAddress = None toAddress = None
if toAddress not in db: if not toAddress in db:
treeWidget.takeTopLevelItem(i) treeWidget.takeTopLevelItem(i)
# no increment # no increment
continue continue
@ -598,7 +551,7 @@ class MyForm(settingsmixin.SMainWindow): # pylint: disable=too-many-public-meth
j += 1 j += 1
# add missing folders # add missing folders
if db[toAddress]: if len(db[toAddress]) > 0:
j = 0 j = 0
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":
@ -629,8 +582,6 @@ class MyForm(settingsmixin.SMainWindow): # pylint: disable=too-many-public-meth
treeWidget.setSortingEnabled(True) treeWidget.setSortingEnabled(True)
def __init__(self, parent=None): def __init__(self, parent=None):
"""TBC"""
QtGui.QWidget.__init__(self, parent) QtGui.QWidget.__init__(self, parent)
self.ui = Ui_MainWindow() self.ui = Ui_MainWindow()
self.ui.setupUi(self) self.ui.setupUi(self)
@ -638,14 +589,12 @@ class MyForm(settingsmixin.SMainWindow): # pylint: disable=too-many-public-meth
# Ask the user if we may delete their old version 1 addresses if they # Ask the user if we may delete their old version 1 addresses if they
# have any. # have any.
for addressInKeysFile in getSortedAccounts(): for addressInKeysFile in getSortedAccounts():
status, addressVersionNumber, streamNumber, addressHash = decodeAddress( status, addressVersionNumber, streamNumber, hash = decodeAddress(
addressInKeysFile) addressInKeysFile)
if addressVersionNumber == 1: if addressVersionNumber == 1:
displayMsg = _translate( displayMsg = _translate(
"MainWindow", "MainWindow", "One of your addresses, %1, is an old version 1 address. Version 1 addresses are no longer supported. "
'One of your addresses, %1, is an old version 1 address. Version 1 addresses are no longer ' + "May we delete it now?").arg(addressInKeysFile)
'supported. 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)
if reply == QtGui.QMessageBox.Yes: if reply == QtGui.QMessageBox.Yes:
@ -655,13 +604,11 @@ class MyForm(settingsmixin.SMainWindow): # pylint: disable=too-many-public-meth
# Configure Bitmessage to start on startup (or remove the # Configure Bitmessage to start on startup (or remove the
# configuration) based on the setting in the keys.dat file # configuration) based on the setting in the keys.dat file
if 'win32' in sys.platform or 'win64' in sys.platform: if 'win32' in sys.platform or 'win64' in sys.platform:
# 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)
# In case the user moves the program and the registry entry is no longer self.settings.remove(
# valid, this will delete the old registry entry. "PyBitmessage") # In case the user moves the program and the registry entry is no longer valid, this will delete the old registry entry.
self.settings.remove("PyBitmessage")
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:
@ -791,15 +738,10 @@ class MyForm(settingsmixin.SMainWindow): # pylint: disable=too-many-public-meth
"updateSentItemStatusByToAddress(PyQt_PyObject,PyQt_PyObject)"), self.updateSentItemStatusByToAddress) "updateSentItemStatusByToAddress(PyQt_PyObject,PyQt_PyObject)"), self.updateSentItemStatusByToAddress)
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( QtCore.QObject.connect(self.UISignalThread, QtCore.SIGNAL(
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)"), QtCore.QObject.connect(self.UISignalThread, QtCore.SIGNAL(
self.displayNewInboxMessage) "displayNewSentMessage(PyQt_PyObject,PyQt_PyObject,PyQt_PyObject,PyQt_PyObject,PyQt_PyObject,PyQt_PyObject)"), self.displayNewSentMessage)
QtCore.QObject.connect(
self.UISignalThread, QtCore.SIGNAL(
("displayNewSentMessage(PyQt_PyObject,PyQt_PyObject,PyQt_PyObject,"
"PyQt_PyObject,PyQt_PyObject,PyQt_PyObject)")),
self.displayNewSentMessage)
QtCore.QObject.connect(self.UISignalThread, QtCore.SIGNAL( 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(
@ -868,16 +810,12 @@ class MyForm(settingsmixin.SMainWindow): # pylint: disable=too-many-public-meth
self.ui.pushButtonFetchNamecoinID.hide() self.ui.pushButtonFetchNamecoinID.hide()
def updateTTL(self, sliderPosition): def updateTTL(self, sliderPosition):
"""TBC"""
TTL = int(sliderPosition ** 3.199 + 3600) TTL = int(sliderPosition ** 3.199 + 3600)
self.updateHumanFriendlyTTLDescription(TTL) self.updateHumanFriendlyTTLDescription(TTL)
BMConfigParser().set('bitmessagesettings', 'ttl', str(TTL)) BMConfigParser().set('bitmessagesettings', 'ttl', str(TTL))
BMConfigParser().save() BMConfigParser().save()
def updateHumanFriendlyTTLDescription(self, TTL): def updateHumanFriendlyTTLDescription(self, TTL):
"""TBC"""
numberOfHours = int(round(TTL / (60*60))) numberOfHours = int(round(TTL / (60*60)))
font = QtGui.QFont() font = QtGui.QFont()
stylesheet = "" stylesheet = ""
@ -892,23 +830,14 @@ class MyForm(settingsmixin.SMainWindow): # pylint: disable=too-many-public-meth
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( self.ui.labelHumanFriendlyTTLDescription.setText(_translate("MainWindow", "%n day(s)", None, QtCore.QCoreApplication.CodecForTr, numberOfDays))
_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)
# Show or hide the application window after clicking an item within the
# tray icon or, on Windows, the try icon itself.
def appIndicatorShowOrHideWindow(self): def appIndicatorShowOrHideWindow(self):
"""
Show or hide the application window after clicking an item within the tray icon or, on Windows,
the try icon itself.
"""
if not self.actionShow.isChecked(): if not self.actionShow.isChecked():
self.hide() self.hide()
else: else:
@ -918,18 +847,16 @@ class MyForm(settingsmixin.SMainWindow): # pylint: disable=too-many-public-meth
self.raise_() self.raise_()
self.activateWindow() self.activateWindow()
# show the application window
def appIndicatorShow(self): def appIndicatorShow(self):
"""show the application window"""
if self.actionShow is None: if self.actionShow is None:
return return
if not self.actionShow.isChecked(): if not self.actionShow.isChecked():
self.actionShow.setChecked(True) self.actionShow.setChecked(True)
self.appIndicatorShowOrHideWindow() self.appIndicatorShowOrHideWindow()
# unchecks the show item on the application indicator
def appIndicatorHide(self): def appIndicatorHide(self):
"""unchecks the show item on the application indicator"""
if self.actionShow is None: if self.actionShow is None:
return return
if self.actionShow.isChecked(): if self.actionShow.isChecked():
@ -937,16 +864,25 @@ class MyForm(settingsmixin.SMainWindow): # pylint: disable=too-many-public-meth
self.appIndicatorShowOrHideWindow() self.appIndicatorShowOrHideWindow()
def appIndicatorSwitchQuietMode(self): def appIndicatorSwitchQuietMode(self):
"""TBC"""
BMConfigParser().set( BMConfigParser().set(
'bitmessagesettings', 'showtraynotifications', 'bitmessagesettings', 'showtraynotifications',
str(not self.actionQuiet.isChecked()) str(not self.actionQuiet.isChecked())
) )
def appIndicatorInbox(self, item=None): # application indicator show or hide
"""Show the program window and select inbox tab""" """# application indicator show or hide
def appIndicatorShowBitmessage(self):
#if self.actionShow == None:
# return
print self.actionShow.isChecked()
if not self.actionShow.isChecked():
self.hide()
#self.setWindowState(self.windowState() & QtCore.Qt.WindowMinimized)
else:
self.appIndicatorShowOrHideWindow()"""
# Show the program window and select inbox tab
def appIndicatorInbox(self, item=None):
self.appIndicatorShow() self.appIndicatorShow()
# select inbox # select inbox
self.ui.tabWidget.setCurrentIndex( self.ui.tabWidget.setCurrentIndex(
@ -962,24 +898,22 @@ class MyForm(settingsmixin.SMainWindow): # pylint: disable=too-many-public-meth
else: else:
self.ui.tableWidgetInbox.setCurrentCell(0, 0) self.ui.tableWidgetInbox.setCurrentCell(0, 0)
# Show the program window and select send tab
def appIndicatorSend(self): def appIndicatorSend(self):
"""Show the program window and select send tab"""
self.appIndicatorShow() self.appIndicatorShow()
self.ui.tabWidget.setCurrentIndex( self.ui.tabWidget.setCurrentIndex(
self.ui.tabWidget.indexOf(self.ui.send) self.ui.tabWidget.indexOf(self.ui.send)
) )
# Show the program window and select subscriptions tab
def appIndicatorSubscribe(self): def appIndicatorSubscribe(self):
"""Show the program window and select subscriptions tab"""
self.appIndicatorShow() self.appIndicatorShow()
self.ui.tabWidget.setCurrentIndex( self.ui.tabWidget.setCurrentIndex(
self.ui.tabWidget.indexOf(self.ui.subscriptions) self.ui.tabWidget.indexOf(self.ui.subscriptions)
) )
# Show the program window and select channels tab
def appIndicatorChannel(self): def appIndicatorChannel(self):
"""Show the program window and select channels tab"""
self.appIndicatorShow() self.appIndicatorShow()
self.ui.tabWidget.setCurrentIndex( self.ui.tabWidget.setCurrentIndex(
self.ui.tabWidget.indexOf(self.ui.chans) self.ui.tabWidget.indexOf(self.ui.chans)
@ -1025,12 +959,9 @@ class MyForm(settingsmixin.SMainWindow): # pylint: disable=too-many-public-meth
for col in (0, 1, 2): for col in (0, 1, 2):
related.item(rrow, col).setUnread(not status) related.item(rrow, col).setUnread(not status)
def propagateUnreadCount(self, address=None, folder="inbox", widget=None, type_arg=1): def propagateUnreadCount(self, address = None, folder = "inbox", widget = None, type = 1):
"""TBC"""
widgets = [self.ui.treeWidgetYourIdentities, self.ui.treeWidgetSubscriptions, self.ui.treeWidgetChans] widgets = [self.ui.treeWidgetYourIdentities, self.ui.treeWidgetSubscriptions, self.ui.treeWidgetChans]
queryReturn = sqlQuery( queryReturn = sqlQuery("SELECT toaddress, folder, COUNT(msgid) AS cnt FROM inbox WHERE read = 0 GROUP BY toaddress, folder")
"SELECT toaddress, folder, COUNT(msgid) AS cnt FROM inbox WHERE read = 0 GROUP BY toaddress, folder")
totalUnread = {} totalUnread = {}
normalUnread = {} normalUnread = {}
for row in queryReturn: for row in queryReturn:
@ -1042,10 +973,7 @@ class MyForm(settingsmixin.SMainWindow): # pylint: disable=too-many-public-meth
totalUnread[row[1]] += row[2] totalUnread[row[1]] += row[2]
else: else:
totalUnread[row[1]] = row[2] totalUnread[row[1]] = row[2]
queryReturn = sqlQuery( queryReturn = sqlQuery("SELECT fromaddress, folder, COUNT(msgid) AS cnt FROM inbox WHERE read = 0 AND toaddress = ? GROUP BY fromaddress, folder", str_broadcast_subscribers)
"SELECT fromaddress, folder, COUNT(msgid) AS cnt FROM inbox "
"WHERE read = 0 AND toaddress = ? GROUP BY fromaddress, folder",
str_broadcast_subscribers)
broadcastsUnread = {} broadcastsUnread = {}
for row in queryReturn: for row in queryReturn:
broadcastsUnread[row[0]] = {} broadcastsUnread[row[0]] = {}
@ -1077,8 +1005,7 @@ class MyForm(settingsmixin.SMainWindow): # pylint: disable=too-many-public-meth
if addressItem.type == AccountMixin.ALL and folderName in totalUnread: if addressItem.type == AccountMixin.ALL and folderName in totalUnread:
newCount = totalUnread[folderName] newCount = totalUnread[folderName]
elif addressItem.type == AccountMixin.SUBSCRIPTION: elif addressItem.type == AccountMixin.SUBSCRIPTION:
if addressItem.address in broadcastsUnread and folderName in broadcastsUnread[ if addressItem.address in broadcastsUnread and folderName in broadcastsUnread[addressItem.address]:
addressItem.address]:
newCount = broadcastsUnread[addressItem.address][folderName] newCount = broadcastsUnread[addressItem.address][folderName]
elif addressItem.address in normalUnread and folderName in normalUnread[addressItem.address]: elif addressItem.address in normalUnread and folderName in normalUnread[addressItem.address]:
newCount = normalUnread[addressItem.address][folderName] newCount = normalUnread[addressItem.address][folderName]
@ -1086,20 +1013,16 @@ class MyForm(settingsmixin.SMainWindow): # pylint: disable=too-many-public-meth
folderItem.setUnreadCount(newCount) folderItem.setUnreadCount(newCount)
def addMessageListItem(self, tableWidget, items): def addMessageListItem(self, tableWidget, items):
"""TBC"""
sortingEnabled = tableWidget.isSortingEnabled() sortingEnabled = tableWidget.isSortingEnabled()
if sortingEnabled: if sortingEnabled:
tableWidget.setSortingEnabled(False) tableWidget.setSortingEnabled(False)
tableWidget.insertRow(0) tableWidget.insertRow(0)
for i, _ in enumerate(items): for i in range(len(items)):
tableWidget.setItem(0, i, items[i]) tableWidget.setItem(0, i, items[i])
if sortingEnabled: if sortingEnabled:
tableWidget.setSortingEnabled(True) tableWidget.setSortingEnabled(True)
def addMessageListItemSent(self, tableWidget, toAddress, fromAddress, subject, status, ackdata, lastactiontime): def addMessageListItemSent(self, tableWidget, toAddress, fromAddress, subject, status, ackdata, lastactiontime):
"""TBC"""
acct = accountClass(fromAddress) acct = accountClass(fromAddress)
if acct is None: if acct is None:
acct = BMAccount(fromAddress) acct = BMAccount(fromAddress)
@ -1138,18 +1061,13 @@ class MyForm(settingsmixin.SMainWindow): # pylint: disable=too-many-public-meth
statusText = _translate( statusText = _translate(
"MainWindow", "Doing work necessary to send broadcast.") "MainWindow", "Doing work necessary to send broadcast.")
elif status == 'broadcastsent': elif status == 'broadcastsent':
statusText = _translate( statusText = _translate("MainWindow", "Broadcast on %1").arg(
"MainWindow", "Broadcast on %1").arg(
l10n.formatTimestamp(lastactiontime)) l10n.formatTimestamp(lastactiontime))
elif status == 'toodifficult': elif status == 'toodifficult':
statusText = _translate( statusText = _translate("MainWindow", "Problem: The work demanded by the recipient is more difficult than you are willing to do. %1").arg(
"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( statusText = _translate("MainWindow", "Problem: The recipient\'s encryption key is no good. Could not encrypt message. %1").arg(
"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(
@ -1168,8 +1086,6 @@ class MyForm(settingsmixin.SMainWindow): # pylint: disable=too-many-public-meth
return acct return acct
def addMessageListItemInbox(self, tableWidget, msgfolder, msgid, toAddress, fromAddress, subject, received, read): def addMessageListItemInbox(self, tableWidget, msgfolder, msgid, toAddress, fromAddress, subject, received, read):
"""TBC"""
font = QtGui.QFont() font = QtGui.QFont()
font.setBold(True) font.setBold(True)
if toAddress == str_broadcast_subscribers: if toAddress == str_broadcast_subscribers:
@ -1202,9 +1118,8 @@ class MyForm(settingsmixin.SMainWindow): # pylint: disable=too-many-public-meth
self.addMessageListItem(tableWidget, items) self.addMessageListItem(tableWidget, items)
return acct return acct
# Load Sent items from database
def loadSent(self, tableWidget, account, where="", what=""): def loadSent(self, tableWidget, account, where="", what=""):
"""Load Sent items from database"""
if tableWidget == self.ui.tableWidgetInboxSubscriptions: if tableWidget == self.ui.tableWidgetInboxSubscriptions:
tableWidget.setColumnHidden(0, True) tableWidget.setColumnHidden(0, True)
tableWidget.setColumnHidden(1, False) tableWidget.setColumnHidden(1, False)
@ -1236,9 +1151,8 @@ class MyForm(settingsmixin.SMainWindow): # pylint: disable=too-many-public-meth
tableWidget.horizontalHeaderItem(3).setText(_translate("MainWindow", "Sent", None)) tableWidget.horizontalHeaderItem(3).setText(_translate("MainWindow", "Sent", None))
tableWidget.setUpdatesEnabled(True) tableWidget.setUpdatesEnabled(True)
# Load messages from database file
def loadMessagelist(self, tableWidget, account, folder="inbox", where="", what="", unreadOnly = False): def loadMessagelist(self, tableWidget, account, folder="inbox", where="", what="", unreadOnly = False):
"""Load messages from database file"""
if folder == 'sent': if folder == 'sent':
self.loadSent(tableWidget, account, where, what) self.loadSent(tableWidget, account, where, what)
return return
@ -1262,8 +1176,7 @@ class MyForm(settingsmixin.SMainWindow): # pylint: disable=too-many-public-meth
for row in queryreturn: for row in queryreturn:
msgfolder, msgid, toAddress, fromAddress, subject, received, read = row msgfolder, msgid, toAddress, fromAddress, subject, received, read = row
self.addMessageListItemInbox(tableWidget, msgfolder, msgid, toAddress, self.addMessageListItemInbox(tableWidget, msgfolder, msgid, toAddress, fromAddress, subject, received, read)
fromAddress, subject, received, read)
tableWidget.horizontalHeader().setSortIndicator( tableWidget.horizontalHeader().setSortIndicator(
3, QtCore.Qt.DescendingOrder) 3, QtCore.Qt.DescendingOrder)
@ -1272,10 +1185,9 @@ class MyForm(settingsmixin.SMainWindow): # pylint: disable=too-many-public-meth
tableWidget.horizontalHeaderItem(3).setText(_translate("MainWindow", "Received", None)) tableWidget.horizontalHeaderItem(3).setText(_translate("MainWindow", "Received", None))
tableWidget.setUpdatesEnabled(True) tableWidget.setUpdatesEnabled(True)
def appIndicatorInit(self, this_app): # create application indicator
"""create application indicator""" def appIndicatorInit(self, app):
self.initTrayIcon("can-icon-24px-red.png", app)
self.initTrayIcon("can-icon-24px-red.png", this_app)
traySignal = "activated(QSystemTrayIcon::ActivationReason)" traySignal = "activated(QSystemTrayIcon::ActivationReason)"
QtCore.QObject.connect(self.tray, QtCore.SIGNAL( QtCore.QObject.connect(self.tray, QtCore.SIGNAL(
traySignal), self.__icon_activated) traySignal), self.__icon_activated)
@ -1297,7 +1209,7 @@ class MyForm(settingsmixin.SMainWindow): # pylint: disable=too-many-public-meth
self.actionShow.setChecked(not BMConfigParser().getboolean( self.actionShow.setChecked(not BMConfigParser().getboolean(
'bitmessagesettings', 'startintray')) 'bitmessagesettings', 'startintray'))
self.actionShow.triggered.connect(self.appIndicatorShowOrHideWindow) self.actionShow.triggered.connect(self.appIndicatorShowOrHideWindow)
if sys.platform[0:3] != 'win': if not sys.platform[0:3] == 'win':
m.addAction(self.actionShow) m.addAction(self.actionShow)
# quiet mode # quiet mode
@ -1338,9 +1250,8 @@ class MyForm(settingsmixin.SMainWindow): # pylint: disable=too-many-public-meth
self.tray.setContextMenu(m) self.tray.setContextMenu(m)
self.tray.show() self.tray.show()
# returns the number of unread messages and subscriptions
def getUnread(self): def getUnread(self):
"""returns the number of unread messages and subscriptions"""
counters = [0, 0] counters = [0, 0]
queryreturn = sqlQuery(''' queryreturn = sqlQuery('''
@ -1355,15 +1266,12 @@ class MyForm(settingsmixin.SMainWindow): # pylint: disable=too-many-public-meth
return counters return counters
def playSound(self, category, label): # pylint: disable=inconsistent-return-statements # play a sound
"""play a sound""" def playSound(self, category, label):
# filename of the sound to be played # filename of the sound to be played
soundFilename = None soundFilename = None
def _choose_ext(basename): # pylint: disable=inconsistent-return-statements def _choose_ext(basename):
"""TBC"""
for ext in sound.extensions: for ext in sound.extensions:
if os.path.isfile(os.extsep.join([basename, ext])): if os.path.isfile(os.extsep.join([basename, ext])):
return os.extsep + ext return os.extsep + ext
@ -1385,7 +1293,8 @@ class MyForm(settingsmixin.SMainWindow): # pylint: disable=too-many-public-meth
# elapsed time since the last sound was played # elapsed time since the last sound was played
dt = datetime.now() - self.lastSoundTime dt = datetime.now() - self.lastSoundTime
# suppress sounds which are more frequent than the threshold # suppress sounds which are more frequent than the threshold
if not dt.total_seconds() < self.maxSoundFrequencySec: if dt.total_seconds() < self.maxSoundFrequencySec:
return
# the sound is for an address which exists in the address book # the sound is for an address which exists in the address book
if category is sound.SOUND_KNOWN: if category is sound.SOUND_KNOWN:
@ -1425,14 +1334,13 @@ class MyForm(settingsmixin.SMainWindow): # pylint: disable=too-many-public-meth
self._player(soundFilename) self._player(soundFilename)
# Adapters and converters for QT <-> sqlite
def sqlInit(self): def sqlInit(self):
"""Adapters and converters for QT <-> sqlite"""
register_adapter(QtCore.QByteArray, str) register_adapter(QtCore.QByteArray, str)
# Try init the distro specific appindicator,
# for example the Ubuntu MessagingMenu
def indicatorInit(self): def indicatorInit(self):
""" Try init the distro specific appindicator, for example the Ubuntu MessagingMenu"""
def _noop_update(*args, **kwargs): def _noop_update(*args, **kwargs):
pass pass
@ -1442,9 +1350,8 @@ class MyForm(settingsmixin.SMainWindow): # pylint: disable=too-many-public-meth
logger.warning("No indicator plugin found") logger.warning("No indicator plugin found")
self.indicatorUpdate = _noop_update self.indicatorUpdate = _noop_update
# initialise the message notifier
def notifierInit(self): def notifierInit(self):
"""initialise the message notifier"""
def _simple_notify( def _simple_notify(
title, subtitle, category, label=None, icon=None): title, subtitle, category, label=None, icon=None):
self.tray.showMessage(title, subtitle, 1, 2000) self.tray.showMessage(title, subtitle, 1, 2000)
@ -1474,34 +1381,27 @@ class MyForm(settingsmixin.SMainWindow): # pylint: disable=too-many-public-meth
def notifierShow( def notifierShow(
self, title, subtitle, category, label=None, icon=None): self, title, subtitle, category, label=None, icon=None):
"""TBC"""
self.playSound(category, label) self.playSound(category, label)
self._notifier( self._notifier(
unicode(title), unicode(subtitle), category, label, icon) unicode(title), unicode(subtitle), category, label, icon)
# tree
def treeWidgetKeyPressEvent(self, event): def treeWidgetKeyPressEvent(self, event):
"""tree"""
return self.handleKeyPress(event, self.getCurrentTreeWidget()) return self.handleKeyPress(event, self.getCurrentTreeWidget())
# inbox / sent
def tableWidgetKeyPressEvent(self, event): def tableWidgetKeyPressEvent(self, event):
"""inbox / sent"""
return self.handleKeyPress(event, self.getCurrentMessagelist()) return self.handleKeyPress(event, self.getCurrentMessagelist())
# messageview
def textEditKeyPressEvent(self, event): def textEditKeyPressEvent(self, event):
"""messageview"""
return self.handleKeyPress(event, self.getCurrentMessageTextedit()) return self.handleKeyPress(event, self.getCurrentMessageTextedit())
def handleKeyPress(self, event, focus=None): # pylint: disable=inconsistent-return-statements def handleKeyPress(self, event, focus = None):
"""TBC"""
messagelist = self.getCurrentMessagelist() messagelist = self.getCurrentMessagelist()
folder = self.getCurrentFolder() folder = self.getCurrentFolder()
if event.key() == QtCore.Qt.Key_Delete: if event.key() == QtCore.Qt.Key_Delete:
if isinstance(focus, (MessageView, QtGui.QTableWidget)): if isinstance (focus, MessageView) or isinstance(focus, QtGui.QTableWidget):
if folder == "sent": if folder == "sent":
self.on_action_SentTrash() self.on_action_SentTrash()
else: else:
@ -1550,103 +1450,47 @@ class MyForm(settingsmixin.SMainWindow): # pylint: disable=too-many-public-meth
elif isinstance (focus, QtGui.QTreeWidget): elif isinstance (focus, QtGui.QTreeWidget):
return QtGui.QTreeWidget.keyPressEvent(focus, event) return QtGui.QTreeWidget.keyPressEvent(focus, event)
# menu button 'manage keys'
def click_actionManageKeys(self): def click_actionManageKeys(self):
"""menu button 'manage keys'"""
if 'darwin' in sys.platform or 'linux' in sys.platform: if 'darwin' in sys.platform or 'linux' in sys.platform:
if state.appdata == '': if state.appdata == '':
# reply = QtGui.QMessageBox.information(self, 'keys.dat?','You # reply = QtGui.QMessageBox.information(self, 'keys.dat?','You
# may manage your keys by editing the keys.dat file stored in # may manage your keys by editing the keys.dat file stored in
# 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( reply = QtGui.QMessageBox.information(self, 'keys.dat?', _translate(
self, "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)
'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)
else: else:
QtGui.QMessageBox.information( QtGui.QMessageBox.information(self, 'keys.dat?', _translate(
self, "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)
'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)
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( reply = QtGui.QMessageBox.question(self, _translate("MainWindow", "Open keys.dat?"), _translate(
self, "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)
_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)
else: else:
reply = QtGui.QMessageBox.question( reply = QtGui.QMessageBox.question(self, _translate("MainWindow", "Open keys.dat?"), _translate(
self, "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)
_translate(
"MainWindow",
"Open keys.dat?"),
_translate(
"MainWindow",
("You may manage your keys by editing the keys.dat file stored in\n %1 \nIt is important "
"that you back up this file. Would you like to open the file now? (Be sure to close "
"Bitmessage before making any changes.)")).arg(
state.appdata),
QtGui.QMessageBox.Yes,
QtGui.QMessageBox.No)
if reply == QtGui.QMessageBox.Yes: if reply == QtGui.QMessageBox.Yes:
shared.openKeysFile() shared.openKeysFile()
# menu button 'delete all treshed messages'
def click_actionDeleteAllTrashedMessages(self): def click_actionDeleteAllTrashedMessages(self):
"""menu button 'delete all treshed messages'""" 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.loadMessagelist(self.ui.tableWidgetInbox, self.getCurrentAccount(self.ui.treeWidgetYourIdentities), "trash")
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.loadMessagelist(self.ui.tableWidgetInboxSubscriptions, self.getCurrentAccount(self.ui.treeWidgetSubscriptions), "trash")
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.loadMessagelist(self.ui.tableWidgetInboxChans, self.getCurrentAccount(self.ui.treeWidgetChans), "trash")
self.ui.tableWidgetInboxChans,
self.getCurrentAccount(
self.ui.treeWidgetChans),
"trash")
# menu button 'regenerate deterministic addresses'
def click_actionRegenerateDeterministicAddresses(self): def click_actionRegenerateDeterministicAddresses(self):
"""menu button 'regenerate deterministic addresses'"""
dialog = dialogs.RegenerateAddressesDialog(self) dialog = dialogs.RegenerateAddressesDialog(self)
if dialog.exec_(): if dialog.exec_():
if dialog.lineEditPassphrase.text() == "": if dialog.lineEditPassphrase.text() == "":
@ -1693,14 +1537,11 @@ class MyForm(settingsmixin.SMainWindow): # pylint: disable=too-many-public-meth
self.ui.tabWidget.indexOf(self.ui.chans) self.ui.tabWidget.indexOf(self.ui.chans)
) )
# opens 'join chan' dialog
def click_actionJoinChan(self): def click_actionJoinChan(self):
"""opens 'join chan' dialog"""
dialogs.NewChanDialog(self) dialogs.NewChanDialog(self)
def showConnectDialog(self): def showConnectDialog(self):
"""TBC"""
dialog = dialogs.ConnectDialog(self) dialog = dialogs.ConnectDialog(self)
if dialog.exec_(): if dialog.exec_():
if dialog.radioButtonConnectNow.isChecked(): if dialog.radioButtonConnectNow.isChecked():
@ -1713,8 +1554,6 @@ class MyForm(settingsmixin.SMainWindow): # pylint: disable=too-many-public-meth
self._firstrun = False self._firstrun = False
def showMigrationWizard(self, level): def showMigrationWizard(self, level):
"""TBC"""
self.migrationWizardInstance = Ui_MigrationWizard(["a"]) self.migrationWizardInstance = Ui_MigrationWizard(["a"])
if self.migrationWizardInstance.exec_(): if self.migrationWizardInstance.exec_():
pass pass
@ -1722,8 +1561,6 @@ class MyForm(settingsmixin.SMainWindow): # pylint: disable=too-many-public-meth
pass pass
def changeEvent(self, event): def changeEvent(self, event):
"""TBC"""
if event.type() == QtCore.QEvent.LanguageChange: if event.type() == QtCore.QEvent.LanguageChange:
self.ui.retranslateUi(self) self.ui.retranslateUi(self)
self.init_inbox_popup_menu(False) self.init_inbox_popup_menu(False)
@ -1735,17 +1572,15 @@ class MyForm(settingsmixin.SMainWindow): # pylint: disable=too-many-public-meth
self.ui.blackwhitelist.init_blacklist_popup_menu(False) self.ui.blackwhitelist.init_blacklist_popup_menu(False)
if event.type() == QtCore.QEvent.WindowStateChange: if event.type() == QtCore.QEvent.WindowStateChange:
if self.windowState() & QtCore.Qt.WindowMinimized: if self.windowState() & QtCore.Qt.WindowMinimized:
if BMConfigParser().getboolean('bitmessagesettings', 'minimizetotray'): if BMConfigParser().getboolean('bitmessagesettings', 'minimizetotray') and not 'darwin' in sys.platform:
if 'darwin' not in sys.platform:
QtCore.QTimer.singleShot(0, self.appIndicatorHide) QtCore.QTimer.singleShot(0, self.appIndicatorHide)
elif event.oldState() & QtCore.Qt.WindowMinimized: elif event.oldState() & QtCore.Qt.WindowMinimized:
# The window state has just been changed to # The window state has just been changed to
# Normal/Maximised/FullScreen # Normal/Maximised/FullScreen
pass pass
# QtGui.QWidget.changeEvent(self, event)
def __icon_activated(self, reason): def __icon_activated(self, reason):
"""TBC"""
if reason == QtGui.QSystemTrayIcon.Trigger: if reason == QtGui.QSystemTrayIcon.Trigger:
self.actionShow.setChecked(not self.actionShow.isChecked()) self.actionShow.setChecked(not self.actionShow.isChecked())
self.appIndicatorShowOrHideWindow() self.appIndicatorShowOrHideWindow()
@ -1754,8 +1589,7 @@ class MyForm(settingsmixin.SMainWindow): # pylint: disable=too-many-public-meth
connected = False connected = False
def setStatusIcon(self, color): def setStatusIcon(self, color):
"""Set the status icon""" # print 'setting status icon color'
_notifications_enabled = not BMConfigParser().getboolean( _notifications_enabled = not BMConfigParser().getboolean(
'bitmessagesettings', 'hidetrayconnectionnotifications') 'bitmessagesettings', 'hidetrayconnectionnotifications')
if color == 'red': if color == 'red':
@ -1783,9 +1617,7 @@ class MyForm(settingsmixin.SMainWindow): # pylint: disable=too-many-public-meth
"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 ' 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.':
'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"))
@ -1803,9 +1635,7 @@ class MyForm(settingsmixin.SMainWindow): # pylint: disable=too-many-public-meth
"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 ' 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.':
'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"))
@ -1822,22 +1652,16 @@ class MyForm(settingsmixin.SMainWindow): # pylint: disable=too-many-public-meth
"MainWindow", "Connected")) "MainWindow", "Connected"))
self.setTrayIconFile("can-icon-24px-green.png") self.setTrayIconFile("can-icon-24px-green.png")
def initTrayIcon(self, iconFileName, this_app): def initTrayIcon(self, iconFileName, app):
"""TBC"""
self.currentTrayIconFileName = iconFileName self.currentTrayIconFileName = iconFileName
self.tray = QtGui.QSystemTrayIcon( self.tray = QtGui.QSystemTrayIcon(
self.calcTrayIcon(iconFileName, self.findInboxUnreadCount()), this_app) self.calcTrayIcon(iconFileName, self.findInboxUnreadCount()), app)
def setTrayIconFile(self, iconFileName): def setTrayIconFile(self, iconFileName):
"""TBC"""
self.currentTrayIconFileName = iconFileName self.currentTrayIconFileName = iconFileName
self.drawTrayIcon(iconFileName, self.findInboxUnreadCount()) self.drawTrayIcon(iconFileName, self.findInboxUnreadCount())
def calcTrayIcon(self, iconFileName, inboxUnreadCount): def calcTrayIcon(self, iconFileName, inboxUnreadCount):
"""TBC"""
pixmap = QtGui.QPixmap(":/newPrefix/images/"+iconFileName) pixmap = QtGui.QPixmap(":/newPrefix/images/"+iconFileName)
if inboxUnreadCount > 0: if inboxUnreadCount > 0:
# choose font and calculate font parameters # choose font and calculate font parameters
@ -1869,13 +1693,9 @@ class MyForm(settingsmixin.SMainWindow): # pylint: disable=too-many-public-meth
return QtGui.QIcon(pixmap) return QtGui.QIcon(pixmap)
def drawTrayIcon(self, iconFileName, inboxUnreadCount): def drawTrayIcon(self, iconFileName, inboxUnreadCount):
"""TBC"""
self.tray.setIcon(self.calcTrayIcon(iconFileName, inboxUnreadCount)) self.tray.setIcon(self.calcTrayIcon(iconFileName, inboxUnreadCount))
def changedInboxUnread(self, row=None): def changedInboxUnread(self, row=None):
"""TBC"""
self.drawTrayIcon( self.drawTrayIcon(
self.currentTrayIconFileName, self.findInboxUnreadCount()) self.currentTrayIconFileName, self.findInboxUnreadCount())
self.rerenderTabTreeMessages() self.rerenderTabTreeMessages()
@ -1883,8 +1703,6 @@ class MyForm(settingsmixin.SMainWindow): # pylint: disable=too-many-public-meth
self.rerenderTabTreeChans() self.rerenderTabTreeChans()
def findInboxUnreadCount(self, count=None): def findInboxUnreadCount(self, count=None):
"""TBC"""
if count is None: if count is None:
queryreturn = sqlQuery('''SELECT count(*) from inbox WHERE folder='inbox' and read=0''') queryreturn = sqlQuery('''SELECT count(*) from inbox WHERE folder='inbox' and read=0''')
cnt = 0 cnt = 0
@ -1896,14 +1714,11 @@ class MyForm(settingsmixin.SMainWindow): # pylint: disable=too-many-public-meth
return self.unreadCount return self.unreadCount
def updateSentItemStatusByToAddress(self, toAddress, textToDisplay): def updateSentItemStatusByToAddress(self, toAddress, textToDisplay):
"""TBC"""
for sent in [self.ui.tableWidgetInbox, self.ui.tableWidgetInboxSubscriptions, self.ui.tableWidgetInboxChans]: for sent in [self.ui.tableWidgetInbox, self.ui.tableWidgetInboxSubscriptions, self.ui.tableWidgetInboxChans]:
treeWidget = self.widgetConvert(sent) treeWidget = self.widgetConvert(sent)
if self.getCurrentFolder(treeWidget) != "sent": if self.getCurrentFolder(treeWidget) != "sent":
continue continue
if treeWidget in [self.ui.treeWidgetSubscriptions, if treeWidget in [self.ui.treeWidgetSubscriptions, self.ui.treeWidgetChans] and self.getCurrentAccount(treeWidget) != toAddress:
self.ui.treeWidgetChans] and self.getCurrentAccount(treeWidget) != toAddress:
continue continue
for i in range(sent.rowCount()): for i in range(sent.rowCount()):
@ -1912,7 +1727,7 @@ class MyForm(settingsmixin.SMainWindow): # pylint: disable=too-many-public-meth
sent.item(i, 3).setToolTip(textToDisplay) sent.item(i, 3).setToolTip(textToDisplay)
try: try:
newlinePosition = textToDisplay.indexOf('\n') newlinePosition = textToDisplay.indexOf('\n')
except: # If no "_translate" appended to string before passing in, there's no qstring 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(
@ -1921,9 +1736,7 @@ class MyForm(settingsmixin.SMainWindow): # pylint: disable=too-many-public-meth
sent.item(i, 3).setText(textToDisplay) sent.item(i, 3).setText(textToDisplay)
def updateSentItemStatusByAckdata(self, ackdata, textToDisplay): def updateSentItemStatusByAckdata(self, ackdata, textToDisplay):
"""TBC""" if type(ackdata) is str:
if isinstance(ackdata, str):
ackdata = QtCore.QByteArray(ackdata) ackdata = QtCore.QByteArray(ackdata)
for sent in [self.ui.tableWidgetInbox, self.ui.tableWidgetInboxSubscriptions, self.ui.tableWidgetInboxChans]: for sent in [self.ui.tableWidgetInbox, self.ui.tableWidgetInboxSubscriptions, self.ui.tableWidgetInboxChans]:
treeWidget = self.widgetConvert(sent) treeWidget = self.widgetConvert(sent)
@ -1940,7 +1753,7 @@ class MyForm(settingsmixin.SMainWindow): # pylint: disable=too-many-public-meth
sent.item(i, 3).setToolTip(textToDisplay) sent.item(i, 3).setToolTip(textToDisplay)
try: try:
newlinePosition = textToDisplay.indexOf('\n') newlinePosition = textToDisplay.indexOf('\n')
except: # If no "_translate" appended to string before passing in, there's no qstring 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(
@ -1949,8 +1762,6 @@ class MyForm(settingsmixin.SMainWindow): # pylint: disable=too-many-public-meth
sent.item(i, 3).setText(textToDisplay) sent.item(i, 3).setText(textToDisplay)
def removeInboxRowByMsgid(self, msgid): # msgid and inventoryHash are the same thing def removeInboxRowByMsgid(self, msgid): # msgid and inventoryHash are the same thing
"""TBC"""
for inbox in ([ for inbox in ([
self.ui.tableWidgetInbox, self.ui.tableWidgetInbox,
self.ui.tableWidgetInboxSubscriptions, self.ui.tableWidgetInboxSubscriptions,
@ -1960,25 +1771,13 @@ class MyForm(settingsmixin.SMainWindow): # pylint: disable=too-many-public-meth
self.updateStatusBar( self.updateStatusBar(
_translate("MainWindow", "Message trashed")) _translate("MainWindow", "Message trashed"))
treeWidget = self.widgetConvert(inbox) treeWidget = self.widgetConvert(inbox)
self.propagateUnreadCount( self.propagateUnreadCount(inbox.item(i, 1 if inbox.item(i, 1).type == AccountMixin.SUBSCRIPTION else 0).data(QtCore.Qt.UserRole), self.getCurrentFolder(treeWidget), treeWidget, 0)
inbox.item(
i,
1 if inbox.item(
i,
1).type == AccountMixin.SUBSCRIPTION else 0).data(
QtCore.Qt.UserRole),
self.getCurrentFolder(treeWidget),
treeWidget,
0)
inbox.removeRow(i) inbox.removeRow(i)
break break
def newVersionAvailable(self, version): def newVersionAvailable(self, version):
"""TBC"""
self.notifiedNewVersion = ".".join(str(n) for n in version) self.notifiedNewVersion = ".".join(str(n) for n in version)
self.updateStatusBar( self.updateStatusBar(_translate(
_translate(
"MainWindow", "MainWindow",
"New version of PyBitmessage is available: %1. Download it" "New version of PyBitmessage is available: %1. Download it"
" from https://github.com/Bitmessage/PyBitmessage/releases/latest" " from https://github.com/Bitmessage/PyBitmessage/releases/latest"
@ -1986,43 +1785,27 @@ class MyForm(settingsmixin.SMainWindow): # pylint: disable=too-many-public-meth
) )
def displayAlert(self, title, text, exitAfterUserClicksOk): def displayAlert(self, title, text, exitAfterUserClicksOk):
"""TBC"""
self.updateStatusBar(text) self.updateStatusBar(text)
QtGui.QMessageBox.critical(self, title, text, QtGui.QMessageBox.Ok) QtGui.QMessageBox.critical(self, title, text, QtGui.QMessageBox.Ok)
if exitAfterUserClicksOk: if exitAfterUserClicksOk:
sys.exit(0) os._exit(0)
def rerenderMessagelistFromLabels(self): def rerenderMessagelistFromLabels(self):
"""TBC""" 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).setLabel()
def rerenderMessagelistToLabels(self): def rerenderMessagelistToLabels(self):
"""TBC""" 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).setLabel()
def rerenderAddressBook(self): def rerenderAddressBook(self):
"""TBC""" def addRow (address, label, type):
def addRow(address, label, arg_type):
"""TBC"""
self.ui.tableWidgetAddressBook.insertRow(0) self.ui.tableWidgetAddressBook.insertRow(0)
newItem = Ui_AddressBookWidgetItemLabel(address, unicode(label, 'utf-8'), arg_type) newItem = Ui_AddressBookWidgetItemLabel(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'), arg_type) newItem = Ui_AddressBookWidgetItemAddress(address, unicode(label, 'utf-8'), type)
self.ui.tableWidgetAddressBook.setItem(0, 1, newItem) self.ui.tableWidgetAddressBook.setItem(0, 1, newItem)
oldRows = {} oldRows = {}
@ -2071,42 +1854,22 @@ class MyForm(settingsmixin.SMainWindow): # pylint: disable=too-many-public-meth
self.ui.lineEditTo.completer().model().setStringList(completerList) self.ui.lineEditTo.completer().model().setStringList(completerList)
def rerenderSubscriptions(self): def rerenderSubscriptions(self):
"""TBC"""
self.rerenderTabTreeSubscriptions() self.rerenderTabTreeSubscriptions()
def click_pushButtonTTL(self): def click_pushButtonTTL(self):
"""TBC"""
QtGui.QMessageBox.information(self, 'Time To Live', _translate( QtGui.QMessageBox.information(self, 'Time To Live', _translate(
"MainWindow", "MainWindow", """The TTL, or Time-To-Live is the length of time that the network will hold the message.
("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 " will resend the message automatically. The longer the Time-To-Live, the
"acknowledgement, it will resend the message automatically. The longer the Time-To-Live, " 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)
"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)
def click_pushButtonClear(self): def click_pushButtonClear(self):
"""TBC"""
self.ui.lineEditSubject.setText("") self.ui.lineEditSubject.setText("")
self.ui.lineEditTo.setText("") self.ui.lineEditTo.setText("")
self.ui.textEditMessage.setText("") self.ui.textEditMessage.setText("")
self.ui.comboBoxSendFrom.setCurrentIndex(0) self.ui.comboBoxSendFrom.setCurrentIndex(0)
def click_pushButtonSend(self): def click_pushButtonSend(self):
"""
TBC
Regarding the line below `if len(message) > (2 ** 18 - 500):`:
The whole network message must fit in 2^18 bytes.
Let's assume 500 bytes of overhead. If someone wants to get that
too an exact number you are welcome to but I think that it would
be a better use of time to support message continuation so that
users can send messages of any length.
"""
encoding = 3 if QtGui.QApplication.queryKeyboardModifiers() & QtCore.Qt.ShiftModifier else 2 encoding = 3 if QtGui.QApplication.queryKeyboardModifiers() & QtCore.Qt.ShiftModifier else 2
self.statusbar.clearMessage() self.statusbar.clearMessage()
@ -2131,6 +1894,13 @@ class MyForm(settingsmixin.SMainWindow): # pylint: disable=too-many-public-meth
subject = str(self.ui.lineEditSubjectBroadcast.text().toUtf8()) subject = str(self.ui.lineEditSubjectBroadcast.text().toUtf8())
message = str( message = str(
self.ui.textEditMessageBroadcast.document().toPlainText().toUtf8()) self.ui.textEditMessageBroadcast.document().toPlainText().toUtf8())
"""
The whole network message must fit in 2^18 bytes.
Let's assume 500 bytes of overhead. If someone wants to get that
too an exact number you are welcome to but I think that it would
be a better use of time to support message continuation so that
users can send messages of any length.
"""
if len(message) > (2 ** 18 - 500): if len(message) > (2 ** 18 - 500):
QtGui.QMessageBox.about( QtGui.QMessageBox.about(
self, _translate("MainWindow", "Message too long"), self, _translate("MainWindow", "Message too long"),
@ -2147,10 +1917,8 @@ class MyForm(settingsmixin.SMainWindow): # pylint: disable=too-many-public-meth
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(';')]
# remove duplicate addresses. If the user has one address with a BM- and toAddressesList = list(set(
# the same address without the BM-, this will not catch it. They'll send 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.
# the message to the person twice.
toAddressesList = list(set(toAddressesList))
for toAddress in toAddressesList: for toAddress in toAddressesList:
if toAddress != '': if toAddress != '':
# label plus address # label plus address
@ -2163,30 +1931,25 @@ class MyForm(settingsmixin.SMainWindow): # pylint: disable=too-many-public-meth
subject = acct.subject subject = acct.subject
toAddress = acct.toAddress toAddress = acct.toAddress
else: else:
if QtGui.QMessageBox.question( if QtGui.QMessageBox.question(self, "Sending an email?", _translate("MainWindow",
self, "Sending an email?", "You are trying to send an email instead of a bitmessage. This requires registering with a gateway. Attempt to register?"),
_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: 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) email = ''.join(random.SystemRandom().choice(string.ascii_lowercase) for _ in range(12)) + "@mailchuck.com"
for _ in range(12)) + "@mailchuck.com"
acct = MailchuckAccount(fromAddress) acct = MailchuckAccount(fromAddress)
acct.register(email) acct.register(email)
BMConfigParser().set(fromAddress, 'label', email) BMConfigParser().set(fromAddress, 'label', email)
BMConfigParser().set(fromAddress, 'gateway', 'mailchuck') BMConfigParser().set(fromAddress, 'gateway', 'mailchuck')
BMConfigParser().save() BMConfigParser().save()
self.updateStatusBar( self.updateStatusBar(_translate(
_translate(
"MainWindow", "MainWindow",
("Error: Your account wasn't registered at an email gateway. Sending registration" "Error: Your account wasn't registered at"
" now as %1, please wait for the registration to be processed before retrying " " an email gateway. Sending registration"
"sending.") " now as %1, please wait for the registration"
" to be processed before retrying sending."
).arg(email) ).arg(email)
) )
return return
@ -2258,45 +2021,29 @@ class MyForm(settingsmixin.SMainWindow): # pylint: disable=too-many-public-meth
elif fromAddress == '': elif fromAddress == '':
self.updateStatusBar(_translate( self.updateStatusBar(_translate(
"MainWindow", "MainWindow",
("Error: You must specify a From address. If you don\'t have one, go to the" "Error: You must specify a From address. If you"
" \'Your Identities\' tab."))) " don\'t have one, go to the"
" \'Your Identities\' tab.")
)
else: else:
toAddress = addBMIfNotPresent(toAddress) toAddress = addBMIfNotPresent(toAddress)
if addressVersionNumber > 4 or addressVersionNumber <= 1: if addressVersionNumber > 4 or addressVersionNumber <= 1:
QtGui.QMessageBox.about( QtGui.QMessageBox.about(self, _translate("MainWindow", "Address version number"), _translate(
self, "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",
"Address version number"),
_translate(
"MainWindow",
("Concerning the address %1, Bitmessage cannot understand address version "
"numbers of %2. Perhaps upgrade Bitmessage to the latest version.")
).arg(toAddress).arg(
str(addressVersionNumber)))
continue continue
if streamNumber > 1 or streamNumber == 0: if streamNumber > 1 or streamNumber == 0:
QtGui.QMessageBox.about( QtGui.QMessageBox.about(self, _translate("MainWindow", "Stream number"), _translate(
self, "MainWindow", "Concerning the address %1, Bitmessage cannot handle stream numbers of %2. Perhaps upgrade Bitmessage to the latest version.").arg(toAddress).arg(str(streamNumber)))
_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)))
continue continue
self.statusbar.clearMessage() self.statusbar.clearMessage()
if shared.statusIconColor == 'red': if shared.statusIconColor == 'red':
self.updateStatusBar( self.updateStatusBar(_translate(
_translate(
"MainWindow", "MainWindow",
("Warning: You are currently not connected. Bitmessage will do the work necessary" "Warning: You are currently not connected."
" to send the message but it won\'t send until you connect.") " Bitmessage will do the work necessary to"
) " send the message but it won\'t send until"
" you connect.")
) )
stealthLevel = BMConfigParser().safeGetInt( stealthLevel = BMConfigParser().safeGetInt(
'bitmessagesettings', 'ackstealthlevel') 'bitmessagesettings', 'ackstealthlevel')
@ -2361,8 +2108,7 @@ class MyForm(settingsmixin.SMainWindow): # pylint: disable=too-many-public-meth
ackdata = genAckPayload(streamNumber, 0) ackdata = genAckPayload(streamNumber, 0)
toAddress = str_broadcast_subscribers toAddress = str_broadcast_subscribers
ripe = '' ripe = ''
t = ( t = ('', # msgid. We don't know what this will be until the POW is done.
'', # msgid. We don't know what this will be until the POW is done.
toAddress, toAddress,
ripe, ripe,
fromAddress, fromAddress,
@ -2399,8 +2145,6 @@ class MyForm(settingsmixin.SMainWindow): # pylint: disable=too-many-public-meth
"MainWindow", "Broadcast queued.")) "MainWindow", "Broadcast queued."))
def click_pushButtonLoadFromAddressBook(self): def click_pushButtonLoadFromAddressBook(self):
"""TBC"""
self.ui.tabWidget.setCurrentIndex(5) self.ui.tabWidget.setCurrentIndex(5)
for i in range(4): for i in range(4):
time.sleep(0.1) time.sleep(0.1)
@ -2413,8 +2157,6 @@ class MyForm(settingsmixin.SMainWindow): # pylint: disable=too-many-public-meth
)) ))
def click_pushButtonFetchNamecoinID(self): def click_pushButtonFetchNamecoinID(self):
"""TBC"""
nc = namecoinConnection() nc = namecoinConnection()
identities = str(self.ui.lineEditTo.text().toUtf8()).split(";") identities = str(self.ui.lineEditTo.text().toUtf8()).split(";")
err, addr = nc.query(identities[-1].strip()) err, addr = nc.query(identities[-1].strip())
@ -2428,8 +2170,8 @@ class MyForm(settingsmixin.SMainWindow): # pylint: disable=too-many-public-meth
"MainWindow", "Fetched address from namecoin identity.")) "MainWindow", "Fetched address from namecoin identity."))
def setBroadcastEnablementDependingOnWhetherThisIsAMailingListAddress(self, address): def setBroadcastEnablementDependingOnWhetherThisIsAMailingListAddress(self, address):
"""If this is a chan then don't let people broadcast because no one should subscribe to chan addresses.""" # If this is a chan then don't let people broadcast because no one
# should subscribe to chan addresses.
self.ui.tabWidgetSend.setCurrentIndex( self.ui.tabWidgetSend.setCurrentIndex(
self.ui.tabWidgetSend.indexOf( self.ui.tabWidgetSend.indexOf(
self.ui.sendBroadcast self.ui.sendBroadcast
@ -2438,20 +2180,17 @@ class MyForm(settingsmixin.SMainWindow): # pylint: disable=too-many-public-meth
)) ))
def rerenderComboBoxSendFrom(self): def rerenderComboBoxSendFrom(self):
"""TBC"""
self.ui.comboBoxSendFrom.clear() self.ui.comboBoxSendFrom.clear()
for addressInKeysFile in getSortedAccounts(): for addressInKeysFile in getSortedAccounts():
isEnabled = BMConfigParser().getboolean(
# I realize that this is poor programming practice but I don't care. It's easier for others to read. addressInKeysFile, 'enabled') # I realize that this is poor programming practice but I don't care. It's easier for others to read.
isEnabled = BMConfigParser().getboolean(addressInKeysFile, 'enabled')
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()
if label == "": if label == "":
label = addressInKeysFile label = addressInKeysFile
self.ui.comboBoxSendFrom.addItem(avatarize(addressInKeysFile), label, addressInKeysFile) self.ui.comboBoxSendFrom.addItem(avatarize(addressInKeysFile), label, addressInKeysFile)
# self.ui.comboBoxSendFrom.model().sort(1, Qt.AscendingOrder)
for i in range(self.ui.comboBoxSendFrom.count()): for i in range(self.ui.comboBoxSendFrom.count()):
address = str(self.ui.comboBoxSendFrom.itemData( address = str(self.ui.comboBoxSendFrom.itemData(
i, QtCore.Qt.UserRole).toString()) i, QtCore.Qt.UserRole).toString())
@ -2459,26 +2198,22 @@ class MyForm(settingsmixin.SMainWindow): # pylint: disable=too-many-public-meth
i, AccountColor(address).accountColor(), i, AccountColor(address).accountColor(),
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):
self.ui.comboBoxSendFrom.setCurrentIndex(1) self.ui.comboBoxSendFrom.setCurrentIndex(1)
else: else:
self.ui.comboBoxSendFrom.setCurrentIndex(0) self.ui.comboBoxSendFrom.setCurrentIndex(0)
def rerenderComboBoxSendFromBroadcast(self): def rerenderComboBoxSendFromBroadcast(self):
"""TBC"""
self.ui.comboBoxSendFromBroadcast.clear() self.ui.comboBoxSendFromBroadcast.clear()
for addressInKeysFile in getSortedAccounts(): for addressInKeysFile in getSortedAccounts():
isEnabled = BMConfigParser().getboolean(
# I realize that this is poor programming practice but I don't care. It's easier for others to read. addressInKeysFile, 'enabled') # I realize that this is poor programming practice but I don't care. It's easier for others to read.
isEnabled = BMConfigParser().getboolean(addressInKeysFile, 'enabled')
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()
if label == "": if label == "":
label = addressInKeysFile label = addressInKeysFile
self.ui.comboBoxSendFromBroadcast.addItem(avatarize(addressInKeysFile), label, addressInKeysFile) self.ui.comboBoxSendFromBroadcast.addItem(avatarize(addressInKeysFile), label, addressInKeysFile)
for i in range(self.ui.comboBoxSendFromBroadcast.count()): for i in range(self.ui.comboBoxSendFromBroadcast.count()):
address = str(self.ui.comboBoxSendFromBroadcast.itemData( address = str(self.ui.comboBoxSendFromBroadcast.itemData(
i, QtCore.Qt.UserRole).toString()) i, QtCore.Qt.UserRole).toString())
@ -2486,19 +2221,16 @@ class MyForm(settingsmixin.SMainWindow): # pylint: disable=too-many-public-meth
i, AccountColor(address).accountColor(), i, AccountColor(address).accountColor(),
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):
self.ui.comboBoxSendFromBroadcast.setCurrentIndex(1) self.ui.comboBoxSendFromBroadcast.setCurrentIndex(1)
else: else:
self.ui.comboBoxSendFromBroadcast.setCurrentIndex(0) self.ui.comboBoxSendFromBroadcast.setCurrentIndex(0)
# This function is called by the processmsg function when that function
# receives a message to an address that is acting as a
# pseudo-mailing-list. The message will be broadcast out. This function
# puts the message on the 'Sent' tab.
def displayNewSentMessage(self, toAddress, toLabel, fromAddress, subject, message, ackdata): def displayNewSentMessage(self, toAddress, toLabel, fromAddress, subject, message, ackdata):
"""
This function is called by the processmsg function when that function
receives a message to an address that is acting as a
pseudo-mailing-list. The message will be broadcast out. This function
puts the message on the 'Sent' tab.
"""
acct = accountClass(fromAddress) acct = accountClass(fromAddress)
acct.parseMessage(toAddress, fromAddress, subject, message) acct.parseMessage(toAddress, fromAddress, subject, message)
tab = -1 tab = -1
@ -2509,24 +2241,11 @@ class MyForm(settingsmixin.SMainWindow): # pylint: disable=too-many-public-meth
treeWidget = self.widgetConvert(sent) treeWidget = self.widgetConvert(sent)
if self.getCurrentFolder(treeWidget) != "sent": if self.getCurrentFolder(treeWidget) != "sent":
continue continue
if ( if treeWidget == self.ui.treeWidgetYourIdentities and self.getCurrentAccount(treeWidget) not in (fromAddress, None, False):
treeWidget == self.ui.treeWidgetYourIdentities and
self.getCurrentAccount(treeWidget) not in (fromAddress, None, False)
):
continue continue
elif ( elif treeWidget in [self.ui.treeWidgetSubscriptions, self.ui.treeWidgetChans] and self.getCurrentAccount(treeWidget) != toAddress:
treeWidget in [self.ui.treeWidgetSubscriptions, self.ui.treeWidgetChans] and
self.getCurrentAccount(treeWidget) != toAddress
):
continue continue
elif not helper_search.check_match( elif not helper_search.check_match(toAddress, fromAddress, subject, message, self.getCurrentSearchOption(tab), self.getCurrentSearchLine(tab)):
toAddress,
fromAddress,
subject,
message,
self.getCurrentSearchOption(tab),
self.getCurrentSearchLine(tab),
):
continue continue
self.addMessageListItemSent(sent, toAddress, fromAddress, subject, "msgqueued", ackdata, time.time()) self.addMessageListItemSent(sent, toAddress, fromAddress, subject, "msgqueued", ackdata, time.time())
@ -2534,8 +2253,6 @@ class MyForm(settingsmixin.SMainWindow): # pylint: disable=too-many-public-meth
sent.setCurrentCell(0, 0) sent.setCurrentCell(0, 0)
def displayNewInboxMessage(self, inventoryHash, toAddress, fromAddress, subject, message): def displayNewInboxMessage(self, inventoryHash, toAddress, fromAddress, subject, message):
"""TBC"""
if toAddress == str_broadcast_subscribers: if toAddress == str_broadcast_subscribers:
acct = accountClass(fromAddress) acct = accountClass(fromAddress)
else: else:
@ -2543,54 +2260,17 @@ class MyForm(settingsmixin.SMainWindow): # pylint: disable=too-many-public-meth
inbox = self.getAccountMessagelist(acct) inbox = self.getAccountMessagelist(acct)
ret = None ret = None
tab = -1 tab = -1
for treeWidget in [ for treeWidget in [self.ui.treeWidgetYourIdentities, self.ui.treeWidgetSubscriptions, self.ui.treeWidgetChans]:
self.ui.treeWidgetYourIdentities,
self.ui.treeWidgetSubscriptions,
self.ui.treeWidgetChans,
]:
tab += 1 tab += 1
if tab == 1: if tab == 1:
tab = 2 tab = 2
tableWidget = self.widgetConvert(treeWidget) tableWidget = self.widgetConvert(treeWidget)
if not helper_search.check_match( if not helper_search.check_match(toAddress, fromAddress, subject, message, self.getCurrentSearchOption(tab), self.getCurrentSearchLine(tab)):
toAddress,
fromAddress,
subject,
message,
self.getCurrentSearchOption(tab),
self.getCurrentSearchLine(tab),
):
continue continue
if ( if tableWidget == inbox and self.getCurrentAccount(treeWidget) == acct.address and self.getCurrentFolder(treeWidget) in ["inbox", None]:
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:
@ -2604,26 +2284,18 @@ class MyForm(settingsmixin.SMainWindow): # pylint: disable=too-many-public-meth
unicode(acct.fromLabel, 'utf-8')), unicode(acct.fromLabel, 'utf-8')),
sound.SOUND_UNKNOWN sound.SOUND_UNKNOWN
) )
# pylint: disable=undefined-loop-variable 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) not in ("inbox", 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)
# cannot find item to pass here ): # cannot find item to pass here ):
if hasattr(acct, "feedback") and acct.feedback != GatewayAccount.ALL_OK: if hasattr(acct, "feedback") \
and acct.feedback != GatewayAccount.ALL_OK:
if acct.feedback == GatewayAccount.REGISTRATION_DENIED: if acct.feedback == GatewayAccount.REGISTRATION_DENIED:
dialogs.EmailGatewayDialog( dialogs.EmailGatewayDialog(
self, BMConfigParser(), acct).exec_() self, BMConfigParser(), acct).exec_()
# pylint: enable=undefined-loop-variable
def click_pushButtonAddAddressBook(self, dialog=None): def click_pushButtonAddAddressBook(self, dialog=None):
"""TBC"""
if not dialog: if not dialog:
dialog = dialogs.AddAddressDialog(self) dialog = dialogs.AddAddressDialog(self)
dialog.exec_() dialog.exec_()
@ -2647,8 +2319,6 @@ class MyForm(settingsmixin.SMainWindow): # pylint: disable=too-many-public-meth
self.addEntryToAddressBook(address, label) self.addEntryToAddressBook(address, label)
def addEntryToAddressBook(self, address, label): def addEntryToAddressBook(self, address, label):
"""TBC"""
if shared.isAddressInMyAddressBook(address): if shared.isAddressInMyAddressBook(address):
return return
sqlExecute('''INSERT INTO addressbook VALUES (?,?)''', label, address) sqlExecute('''INSERT INTO addressbook VALUES (?,?)''', label, address)
@ -2657,8 +2327,6 @@ class MyForm(settingsmixin.SMainWindow): # pylint: disable=too-many-public-meth
self.rerenderAddressBook() self.rerenderAddressBook()
def addSubscription(self, address, label): def addSubscription(self, address, label):
"""TBC"""
# This should be handled outside of this function, for error displaying # This should be handled outside of this function, for error displaying
# and such, but it must also be checked here. # and such, but it must also be checked here.
if shared.isAddressInMySubscriptionsList(address): if shared.isAddressInMySubscriptionsList(address):
@ -2674,8 +2342,6 @@ class MyForm(settingsmixin.SMainWindow): # pylint: disable=too-many-public-meth
self.rerenderTabTreeSubscriptions() self.rerenderTabTreeSubscriptions()
def click_pushButtonAddSubscription(self): def click_pushButtonAddSubscription(self):
"""TBC"""
dialog = dialogs.NewSubscriptionDialog(self) dialog = dialogs.NewSubscriptionDialog(self)
dialog.exec_() dialog.exec_()
try: try:
@ -2706,28 +2372,18 @@ class MyForm(settingsmixin.SMainWindow): # pylint: disable=too-many-public-meth
)) ))
def click_pushButtonStatusIcon(self): def click_pushButtonStatusIcon(self):
"""TBC"""
dialogs.IconGlossaryDialog(self, config=BMConfigParser()).exec_() dialogs.IconGlossaryDialog(self, config=BMConfigParser()).exec_()
def click_actionHelp(self): def click_actionHelp(self):
"""TBC"""
dialogs.HelpDialog(self).exec_() dialogs.HelpDialog(self).exec_()
def click_actionSupport(self): def click_actionSupport(self):
"""TBC"""
support.createSupportMessage(self) support.createSupportMessage(self)
def click_actionAbout(self): def click_actionAbout(self):
"""TBC"""
dialogs.AboutDialog(self).exec_() dialogs.AboutDialog(self).exec_()
def click_actionSettings(self): def click_actionSettings(self):
"""TBC"""
self.settingsDialogInstance = settingsDialog(self) self.settingsDialogInstance = settingsDialog(self)
if self._firstrun: if self._firstrun:
self.settingsDialogInstance.ui.tabWidgetSettings.setCurrentIndex(1) self.settingsDialogInstance.ui.tabWidgetSettings.setCurrentIndex(1)
@ -2754,48 +2410,29 @@ class MyForm(settingsmixin.SMainWindow): # pylint: disable=too-many-public-meth
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( lang = str(self.settingsDialogInstance.ui.languageComboBox.itemData(self.settingsDialogInstance.ui.languageComboBox.currentIndex()).toString())
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( if int(BMConfigParser().get('bitmessagesettings', 'port')) != int(self.settingsDialogInstance.ui.lineEditTCPPort.text()):
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( if self.settingsDialogInstance.ui.checkBoxUPnP.isChecked() != BMConfigParser().safeGetBoolean('bitmessagesettings', 'upnp'):
'bitmessagesettings', 'upnp' BMConfigParser().set('bitmessagesettings', 'upnp', str(self.settingsDialogInstance.ui.checkBoxUPnP.isChecked()))
):
BMConfigParser().set(
'bitmessagesettings', 'upnp',
str(self.settingsDialogInstance.ui.checkBoxUPnP.isChecked()))
if self.settingsDialogInstance.ui.checkBoxUPnP.isChecked(): if self.settingsDialogInstance.ui.checkBoxUPnP.isChecked():
import upnp
upnpThread = upnp.uPnPThread() upnpThread = upnp.uPnPThread()
upnpThread.start() upnpThread.start()
#print 'self.settingsDialogInstance.ui.comboBoxProxyType.currentText()', self.settingsDialogInstance.ui.comboBoxProxyType.currentText()
if ( #print 'self.settingsDialogInstance.ui.comboBoxProxyType.currentText())[0:5]', self.settingsDialogInstance.ui.comboBoxProxyType.currentText()[0:5]
BMConfigParser().get('bitmessagesettings', 'socksproxytype') == 'none' and if BMConfigParser().get('bitmessagesettings', 'socksproxytype') == 'none' and self.settingsDialogInstance.ui.comboBoxProxyType.currentText()[0:5] == 'SOCKS':
self.settingsDialogInstance.ui.comboBoxProxyType.currentText()[0:5] == 'SOCKS'
):
if shared.statusIconColor != 'red': if shared.statusIconColor != 'red':
QtGui.QMessageBox.about( QtGui.QMessageBox.about(self, _translate("MainWindow", "Restart"), _translate(
self, "MainWindow", "Bitmessage will use your proxy from now on but you may want to manually restart Bitmessage now to close existing connections (if any)."))
_translate( if BMConfigParser().get('bitmessagesettings', 'socksproxytype')[0:5] == 'SOCKS' and self.settingsDialogInstance.ui.comboBoxProxyType.currentText()[0:5] != 'SOCKS':
"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).")))
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':
@ -2845,61 +2482,31 @@ class MyForm(settingsmixin.SMainWindow): # pylint: disable=too-many-public-meth
# 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() self.settingsDialogInstance.ui.lineEditTotalDifficulty.text()) * defaults.networkDefaultProofOfWorkNonceTrialsPerByte)))
) * 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() self.settingsDialogInstance.ui.lineEditSmallMessageDifficulty.text()) * defaults.networkDefaultPayloadLengthExtraBytes)))
) * defaults.networkDefaultPayloadLengthExtraBytes)))
if self.settingsDialogInstance.ui.comboBoxOpenCL.currentText().toUtf8( if self.settingsDialogInstance.ui.comboBoxOpenCL.currentText().toUtf8() != BMConfigParser().safeGet("bitmessagesettings", "opencl"):
) != BMConfigParser().safeGet("bitmessagesettings", "opencl"): BMConfigParser().set('bitmessagesettings', 'opencl', str(self.settingsDialogInstance.ui.comboBoxOpenCL.currentText()))
BMConfigParser().set(
'bitmessagesettings', 'opencl',
str(self.settingsDialogInstance.ui.comboBoxOpenCL.currentText()))
queues.workerQueue.put(('resetPoW', '')) queues.workerQueue.put(('resetPoW', ''))
acceptableDifficultyChanged = False acceptableDifficultyChanged = False
if ( if float(self.settingsDialogInstance.ui.lineEditMaxAcceptableTotalDifficulty.text()) >= 1 or float(self.settingsDialogInstance.ui.lineEditMaxAcceptableTotalDifficulty.text()) == 0:
float(self.settingsDialogInstance.ui.lineEditMaxAcceptableTotalDifficulty.text()) >= 1 or if BMConfigParser().get('bitmessagesettings','maxacceptablenoncetrialsperbyte') != str(int(float(
float(self.settingsDialogInstance.ui.lineEditMaxAcceptableTotalDifficulty.text()) == 0 self.settingsDialogInstance.ui.lineEditMaxAcceptableTotalDifficulty.text()) * defaults.networkDefaultProofOfWorkNonceTrialsPerByte)):
):
if BMConfigParser().get(
'bitmessagesettings',
'maxacceptablenoncetrialsperbyte',
) != str(
int(
float(
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() self.settingsDialogInstance.ui.lineEditMaxAcceptableTotalDifficulty.text()) * defaults.networkDefaultProofOfWorkNonceTrialsPerByte)))
) * 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 ( self.settingsDialogInstance.ui.lineEditMaxAcceptableSmallMessageDifficulty.text()) * defaults.networkDefaultPayloadLengthExtraBytes)):
float(self.settingsDialogInstance.ui.lineEditMaxAcceptableSmallMessageDifficulty.text()) >= 1 or
float(self.settingsDialogInstance.ui.lineEditMaxAcceptableSmallMessageDifficulty.text()) == 0
):
if BMConfigParser().get(
'bitmessagesettings',
'maxacceptablepayloadlengthextrabytes',
) != str(
int(
float(
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() self.settingsDialogInstance.ui.lineEditMaxAcceptableSmallMessageDifficulty.text()) * defaults.networkDefaultPayloadLengthExtraBytes)))
) * 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
@ -2910,10 +2517,7 @@ class MyForm(settingsmixin.SMainWindow): # pylint: disable=too-many-public-meth
#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 ( 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
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')
@ -2932,26 +2536,11 @@ class MyForm(settingsmixin.SMainWindow): # pylint: disable=too-many-public-meth
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 ( if (float(self.settingsDialogInstance.ui.lineEditDays.text()) >=0 and float(self.settingsDialogInstance.ui.lineEditMonths.text()) >=0):
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.
): QtGui.QMessageBox.about(self, _translate("MainWindow", "Will not resend ever"), _translate(
shared.maximumLengthOfTimeToBotherResendingMessages = sum( "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."))
float(str(self.settingsDialogInstance.ui.lineEditDays.text())) * 24 * 60 * 60,
float(str(self.settingsDialogInstance.ui.lineEditMonths.text())) * (60 * 60 * 24 * 365) / 12,
)
# If the time period is less than 5 hours, we give zero values to all
# fields. No message will be sent again.
if shared.maximumLengthOfTimeToBotherResendingMessages < 432000:
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.")))
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
@ -2978,10 +2567,7 @@ class MyForm(settingsmixin.SMainWindow): # pylint: disable=too-many-public-meth
# startup for linux # startup for linux
pass pass
# 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...
if state.appdata != paths.lookupExeFolder():
if self.settingsDialogInstance.ui.checkBoxPortableMode.isChecked():
# 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:
@ -2999,10 +2585,7 @@ class MyForm(settingsmixin.SMainWindow): # pylint: disable=too-many-public-meth
except: except:
pass pass
# 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...
if state.appdata == paths.lookupExeFolder():
if not self.settingsDialogInstance.ui.checkBoxPortableMode.isChecked():
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)
@ -3021,13 +2604,9 @@ class MyForm(settingsmixin.SMainWindow): # pylint: disable=too-many-public-meth
pass pass
def on_action_SpecialAddressBehaviorDialog(self): def on_action_SpecialAddressBehaviorDialog(self):
"""TBC"""
dialogs.SpecialAddressBehaviorDialog(self, BMConfigParser()) dialogs.SpecialAddressBehaviorDialog(self, BMConfigParser())
def on_action_EmailGatewayDialog(self): def on_action_EmailGatewayDialog(self):
"""TBC"""
dialog = dialogs.EmailGatewayDialog(self, config=BMConfigParser()) dialog = dialogs.EmailGatewayDialog(self, config=BMConfigParser())
# For Modal dialogs # For Modal dialogs
dialog.exec_() dialog.exec_()
@ -3058,8 +2637,6 @@ class MyForm(settingsmixin.SMainWindow): # pylint: disable=too-many-public-meth
self.ui.textEditMessage.setFocus() self.ui.textEditMessage.setFocus()
def on_action_MarkAllRead(self): def on_action_MarkAllRead(self):
"""TBC"""
if QtGui.QMessageBox.question( if QtGui.QMessageBox.question(
self, "Marking all messages as read?", self, "Marking all messages as read?",
_translate( _translate(
@ -3099,13 +2676,9 @@ class MyForm(settingsmixin.SMainWindow): # pylint: disable=too-many-public-meth
# addressAtCurrentRow, self.getCurrentFolder(), None, 0) # addressAtCurrentRow, self.getCurrentFolder(), None, 0)
def click_NewAddressDialog(self): def click_NewAddressDialog(self):
"""TBC"""
dialogs.NewAddressDialog(self) dialogs.NewAddressDialog(self)
def network_switch(self): def network_switch(self):
"""TBC"""
dontconnect_option = not BMConfigParser().safeGetBoolean( dontconnect_option = not BMConfigParser().safeGetBoolean(
'bitmessagesettings', 'dontconnect') 'bitmessagesettings', 'dontconnect')
BMConfigParser().set( BMConfigParser().set(
@ -3117,8 +2690,15 @@ class MyForm(settingsmixin.SMainWindow): # pylint: disable=too-many-public-meth
dontconnect_option or self.namecoin.test()[0] == 'failed' dontconnect_option or self.namecoin.test()[0] == 'failed'
) )
# Quit selected from menu or application indicator
def quit(self): def quit(self):
"""Quit selected from menu or application indicator""" '''quit_msg = "Are you sure you want to exit Bitmessage?"
reply = QtGui.QMessageBox.question(self, 'Message',
quit_msg, QtGui.QMessageBox.Yes, QtGui.QMessageBox.No)
if reply is QtGui.QMessageBox.No:
return
'''
if self.quitAccepted: if self.quitAccepted:
return return
@ -3133,50 +2713,20 @@ class MyForm(settingsmixin.SMainWindow): # pylint: disable=too-many-public-meth
# 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 (powQueueSize() > 0 or pendingUpload() > 0):
reply = QtGui.QMessageBox.question( reply = QtGui.QMessageBox.question(self, _translate("MainWindow", "Proof of work pending"),
self, _translate("MainWindow", "%n object(s) pending proof of work", None, QtCore.QCoreApplication.CodecForTr, powQueueSize()) + ", " +
_translate( _translate("MainWindow", "%n object(s) waiting to be distributed", None, QtCore.QCoreApplication.CodecForTr, pendingUpload()) + "\n\n" +
"MainWindow", _translate("MainWindow", "Wait until these tasks finish?"),
"Proof of work pending"), QtGui.QMessageBox.Yes|QtGui.QMessageBox.No|QtGui.QMessageBox.Cancel, QtGui.QMessageBox.Cancel)
_translate(
"MainWindow",
"%n object(s) pending proof of work",
None,
QtCore.QCoreApplication.CodecForTr,
powQueueSize()) +
", " +
_translate(
"MainWindow",
"%n object(s) waiting to be distributed",
None,
QtCore.QCoreApplication.CodecForTr,
pendingUpload()) +
"\n\n" +
_translate(
"MainWindow",
"Wait until these tasks finish?"),
QtGui.QMessageBox.Yes | QtGui.QMessageBox.No | QtGui.QMessageBox.Cancel,
QtGui.QMessageBox.Cancel)
if reply == QtGui.QMessageBox.No: if reply == QtGui.QMessageBox.No:
waitForPow = False waitForPow = False
elif reply == QtGui.QMessageBox.Cancel: elif reply == QtGui.QMessageBox.Cancel:
return return
if pendingDownload() > 0: if pendingDownload() > 0:
reply = QtGui.QMessageBox.question( reply = QtGui.QMessageBox.question(self, _translate("MainWindow", "Synchronisation pending"),
self, _translate("MainWindow", "Bitmessage hasn't synchronised with the network, %n object(s) to be downloaded. If you quit now, it may cause delivery delays. Wait until the synchronisation finishes?", None, QtCore.QCoreApplication.CodecForTr, pendingDownload()),
_translate( QtGui.QMessageBox.Yes|QtGui.QMessageBox.No|QtGui.QMessageBox.Cancel, QtGui.QMessageBox.Cancel)
"MainWindow",
"Synchronisation pending"),
_translate(
"MainWindow",
("Bitmessage hasn't synchronised with the network, %n object(s) to be downloaded. If you quit "
"now, it may cause delivery delays. Wait until the synchronisation finishes?"),
None,
QtCore.QCoreApplication.CodecForTr,
pendingDownload()),
QtGui.QMessageBox.Yes | QtGui.QMessageBox.No | QtGui.QMessageBox.Cancel,
QtGui.QMessageBox.Cancel)
if reply == QtGui.QMessageBox.Yes: if reply == QtGui.QMessageBox.Yes:
waitForSync = True waitForSync = True
elif reply == QtGui.QMessageBox.Cancel: elif reply == QtGui.QMessageBox.Cancel:
@ -3184,17 +2734,9 @@ class MyForm(settingsmixin.SMainWindow): # pylint: disable=too-many-public-meth
if shared.statusIconColor == 'red' and not BMConfigParser().safeGetBoolean( if shared.statusIconColor == 'red' and not BMConfigParser().safeGetBoolean(
'bitmessagesettings', 'dontconnect'): 'bitmessagesettings', 'dontconnect'):
reply = QtGui.QMessageBox.question( reply = QtGui.QMessageBox.question(self, _translate("MainWindow", "Not connected"),
self, _translate("MainWindow", "Bitmessage isn't connected to the network. If you quit now, it may cause delivery delays. Wait until connected and the synchronisation finishes?"),
_translate( QtGui.QMessageBox.Yes|QtGui.QMessageBox.No|QtGui.QMessageBox.Cancel, QtGui.QMessageBox.Cancel)
"MainWindow",
"Not connected"),
_translate(
"MainWindow",
("Bitmessage isn't connected to the network. If you quit now, it may cause delivery delays. "
"Wait until connected and the synchronisation finishes?")),
QtGui.QMessageBox.Yes | QtGui.QMessageBox.No | QtGui.QMessageBox.Cancel,
QtGui.QMessageBox.Cancel)
if reply == QtGui.QMessageBox.Yes: if reply == QtGui.QMessageBox.Yes:
waitForConnection = True waitForConnection = True
waitForSync = True waitForSync = True
@ -3215,9 +2757,7 @@ class MyForm(settingsmixin.SMainWindow): # pylint: disable=too-many-public-meth
QtCore.QEventLoop.AllEvents, 1000 QtCore.QEventLoop.AllEvents, 1000
) )
# this probably will not work correctly, because there is a delay between # this probably will not work correctly, because there is a delay between the status icon turning red and inventory exchange, but it's better than nothing.
# the status icon turning red and inventory exchange, but it's better than
# nothing.
if waitForSync: if waitForSync:
self.updateStatusBar(_translate( self.updateStatusBar(_translate(
"MainWindow", "Waiting for finishing synchronisation...")) "MainWindow", "Waiting for finishing synchronisation..."))
@ -3237,11 +2777,10 @@ class MyForm(settingsmixin.SMainWindow): # pylint: disable=too-many-public-meth
if curWorkerQueue > maxWorkerQueue: if curWorkerQueue > maxWorkerQueue:
maxWorkerQueue = curWorkerQueue maxWorkerQueue = curWorkerQueue
if curWorkerQueue > 0: if curWorkerQueue > 0:
self.updateStatusBar( self.updateStatusBar(_translate(
_translate( "MainWindow", "Waiting for PoW to finish... %1%"
"MainWindow", ).arg(50 * (maxWorkerQueue - curWorkerQueue)
"Waiting for PoW to finish... %1%", / maxWorkerQueue)
).arg(50 * (maxWorkerQueue - curWorkerQueue) / maxWorkerQueue)
) )
time.sleep(0.5) time.sleep(0.5)
QtCore.QCoreApplication.processEvents( QtCore.QCoreApplication.processEvents(
@ -3267,8 +2806,7 @@ class MyForm(settingsmixin.SMainWindow): # pylint: disable=too-many-public-meth
maxPendingUpload = max(1, pendingUpload()) maxPendingUpload = max(1, pendingUpload())
while pendingUpload() > 1: while pendingUpload() > 1:
self.updateStatusBar( self.updateStatusBar(_translate(
_translate(
"MainWindow", "MainWindow",
"Waiting for objects to be sent... %1%" "Waiting for objects to be sent... %1%"
).arg(int(50 + 20 * (pendingUpload()/maxPendingUpload))) ).arg(int(50 + 20 * (pendingUpload()/maxPendingUpload)))
@ -3314,11 +2852,11 @@ class MyForm(settingsmixin.SMainWindow): # pylint: disable=too-many-public-meth
shared.thisapp.cleanup() shared.thisapp.cleanup()
logger.info("Shutdown complete") logger.info("Shutdown complete")
super(MyForm, myapp).close() super(MyForm, myapp).close()
sys.exit(0) # return
os._exit(0)
# window close event
def closeEvent(self, event): def closeEvent(self, event):
"""window close event"""
self.appIndicatorHide() self.appIndicatorHide()
trayonclose = False trayonclose = False
@ -3339,8 +2877,6 @@ class MyForm(settingsmixin.SMainWindow): # pylint: disable=too-many-public-meth
self.quit() self.quit()
def on_action_InboxMessageForceHtml(self): def on_action_InboxMessageForceHtml(self):
"""TBC"""
msgid = self.getCurrentMessageId() msgid = self.getCurrentMessageId()
textEdit = self.getCurrentMessageTextedit() textEdit = self.getCurrentMessageTextedit()
if not msgid: if not msgid:
@ -3368,45 +2904,51 @@ class MyForm(settingsmixin.SMainWindow): # pylint: disable=too-many-public-meth
textEdit.setHtml(QtCore.QString(content)) textEdit.setHtml(QtCore.QString(content))
def on_action_InboxMarkUnread(self): def on_action_InboxMarkUnread(self):
"""TBC"""
tableWidget = self.getCurrentMessagelist() tableWidget = self.getCurrentMessagelist()
if not tableWidget: if not tableWidget:
return return
msgids = set() msgids = set()
# modified = 0
for row in tableWidget.selectedIndexes(): for row in tableWidget.selectedIndexes():
currentRow = row.row() currentRow = row.row()
msgid = str(tableWidget.item( msgid = str(tableWidget.item(
currentRow, 3).data(QtCore.Qt.UserRole).toPyObject()) currentRow, 3).data(QtCore.Qt.UserRole).toPyObject())
msgids.add(msgid) msgids.add(msgid)
# if not tableWidget.item(currentRow, 0).unread:
# modified += 1
self.updateUnreadStatus(tableWidget, currentRow, msgid, False) self.updateUnreadStatus(tableWidget, currentRow, msgid, False)
# for 1081
idCount = len(msgids) idCount = len(msgids)
# rowcount =
sqlExecuteChunked( sqlExecuteChunked(
'''UPDATE inbox SET read=0 WHERE msgid IN ({0}) AND read=1''', '''UPDATE inbox SET read=0 WHERE msgid IN ({0}) AND read=1''',
idCount, *msgids idCount, *msgids
) )
self.propagateUnreadCount() self.propagateUnreadCount()
# if rowcount == 1:
# # performance optimisation
# self.propagateUnreadCount(tableWidget.item(currentRow, 1 if tableWidget.item(currentRow, 1).type == AccountMixin.SUBSCRIPTION else 0).data(QtCore.Qt.UserRole), self.getCurrentFolder())
# else:
# self.propagateUnreadCount(tableWidget.item(currentRow, 1 if tableWidget.item(currentRow, 1).type == AccountMixin.SUBSCRIPTION else 0).data(QtCore.Qt.UserRole), self.getCurrentFolder(), self.getCurrentTreeWidget(), 0)
# tableWidget.selectRow(currentRow + 1)
# This doesn't de-select the last message if you try to mark it unread, but that doesn't interfere. Might not be necessary.
# We could also select upwards, but then our problem would be with the topmost message.
# tableWidget.clearSelection() manages to mark the message as read again.
# Format predefined text on message reply.
def quoted_text(self, message): def quoted_text(self, message):
"""Format predefined text on message reply."""
if not BMConfigParser().safeGetBoolean('bitmessagesettings', 'replybelow'): if not BMConfigParser().safeGetBoolean('bitmessagesettings', 'replybelow'):
return '\n\n------------------------------------------------------\n' + message return '\n\n------------------------------------------------------\n' + message
quoteWrapper = textwrap.TextWrapper( quoteWrapper = textwrap.TextWrapper(replace_whitespace = False,
replace_whitespace=False,
initial_indent = '> ', initial_indent = '> ',
subsequent_indent = '> ', subsequent_indent = '> ',
break_long_words = False, break_long_words = False,
break_on_hyphens=False, break_on_hyphens = False)
)
def quote_line(line): def quote_line(line):
"""TBC"""
# Do quote empty lines. # Do quote empty lines.
if line == '' or line.isspace(): if line == '' or line.isspace():
return '> ' return '> '
@ -3414,13 +2956,11 @@ class MyForm(settingsmixin.SMainWindow): # pylint: disable=too-many-public-meth
elif line[0:2] == '> ': elif line[0:2] == '> ':
return '> ' + line return '> ' + line
# Wrap and quote lines/paragraphs new to this message. # Wrap and quote lines/paragraphs new to this message.
else:
return quoteWrapper.fill(line) return quoteWrapper.fill(line)
return '\n'.join([quote_line(l) for l in message.splitlines()]) + '\n\n' return '\n'.join([quote_line(l) for l in message.splitlines()]) + '\n\n'
def setSendFromComboBox(self, address = None): def setSendFromComboBox(self, address = None):
"""TBC"""
if address is None: if address is None:
messagelist = self.getCurrentMessagelist() messagelist = self.getCurrentMessagelist()
if messagelist: if messagelist:
@ -3436,13 +2976,9 @@ class MyForm(settingsmixin.SMainWindow): # pylint: disable=too-many-public-meth
box.setCurrentIndex(0) box.setCurrentIndex(0)
def on_action_InboxReplyChan(self): def on_action_InboxReplyChan(self):
"""TBC"""
self.on_action_InboxReply(self.REPLY_TYPE_CHAN) self.on_action_InboxReply(self.REPLY_TYPE_CHAN)
def on_action_InboxReply(self, replyType = None): def on_action_InboxReply(self, replyType = None):
"""TBC"""
tableWidget = self.getCurrentMessagelist() tableWidget = self.getCurrentMessagelist()
if not tableWidget: if not tableWidget:
return return
@ -3466,13 +3002,7 @@ class MyForm(settingsmixin.SMainWindow): # pylint: disable=too-many-public-meth
if queryreturn != []: if queryreturn != []:
for row in queryreturn: for row in queryreturn:
messageAtCurrentInboxRow, = row messageAtCurrentInboxRow, = row
acct.parseMessage( acct.parseMessage(toAddressAtCurrentInboxRow, fromAddressAtCurrentInboxRow, tableWidget.item(currentInboxRow, 2).subject, messageAtCurrentInboxRow)
toAddressAtCurrentInboxRow,
fromAddressAtCurrentInboxRow,
tableWidget.item(
currentInboxRow,
2).subject,
messageAtCurrentInboxRow)
widget = { widget = {
'subject': self.ui.lineEditSubject, 'subject': self.ui.lineEditSubject,
'from': self.ui.comboBoxSendFrom, 'from': self.ui.comboBoxSendFrom,
@ -3482,23 +3012,13 @@ class MyForm(settingsmixin.SMainWindow): # pylint: disable=too-many-public-meth
self.ui.tabWidgetSend.setCurrentIndex( self.ui.tabWidgetSend.setCurrentIndex(
self.ui.tabWidgetSend.indexOf(self.ui.sendDirect) self.ui.tabWidgetSend.indexOf(self.ui.sendDirect)
) )
# toAddressAtCurrentInboxRow = fromAddressAtCurrentInboxRow
elif not BMConfigParser().has_section(toAddressAtCurrentInboxRow): elif not BMConfigParser().has_section(toAddressAtCurrentInboxRow):
QtGui.QMessageBox.information( QtGui.QMessageBox.information(self, _translate("MainWindow", "Address is gone"), _translate(
self, _translate("MainWindow", "Address is gone"), "MainWindow", "Bitmessage cannot find your address %1. Perhaps you removed it?").arg(toAddressAtCurrentInboxRow), QtGui.QMessageBox.Ok)
_translate("MainWindow", "Bitmessage cannot find your address %1. Perhaps you removed it?").arg(
toAddressAtCurrentInboxRow),
QtGui.QMessageBox.Ok)
elif not BMConfigParser().getboolean(toAddressAtCurrentInboxRow, 'enabled'): elif not BMConfigParser().getboolean(toAddressAtCurrentInboxRow, 'enabled'):
QtGui.QMessageBox.information( QtGui.QMessageBox.information(self, _translate("MainWindow", "Address disabled"), _translate(
self, "MainWindow", "Error: The address from which you are trying to send is disabled. You\'ll have to enable it on the \'Your Identities\' tab before using it."), QtGui.QMessageBox.Ok)
_translate(
"MainWindow",
"Address disabled"),
_translate(
"MainWindow",
("Error: The address from which you are trying to send is disabled. You\'ll have to enable it on "
"the \'Your Identities\' tab before using it.")),
QtGui.QMessageBox.Ok)
else: else:
self.setBroadcastEnablementDependingOnWhetherThisIsAMailingListAddress(toAddressAtCurrentInboxRow) self.setBroadcastEnablementDependingOnWhetherThisIsAMailingListAddress(toAddressAtCurrentInboxRow)
broadcast_tab_index = self.ui.tabWidgetSend.indexOf( broadcast_tab_index = self.ui.tabWidgetSend.indexOf(
@ -3516,25 +3036,15 @@ class MyForm(settingsmixin.SMainWindow): # pylint: disable=too-many-public-meth
isinstance(acct, GatewayAccount) and fromAddressAtCurrentInboxRow == acct.relayAddress): isinstance(acct, GatewayAccount) and fromAddressAtCurrentInboxRow == acct.relayAddress):
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, 1).label + " <" + str(acct.fromAddress) + ">")
''.join(
[
tableWidget.item(currentInboxRow, 1).label,
" <",
str(acct.fromAddress) + ">",
]
)
)
# If the previous message was to a chan then we should send our reply to # If the previous message was to a chan then we should send our reply to the chan rather than to the particular person who sent the message.
# the chan rather than to the particular person who sent the message.
if acct.type == AccountMixin.CHAN and replyType == self.REPLY_TYPE_CHAN: if acct.type == AccountMixin.CHAN and replyType == self.REPLY_TYPE_CHAN:
logger.debug('original sent to a chan. Setting the to address in the reply to the chan address.') logger.debug('original sent to a chan. Setting the to address in the reply to the chan address.')
if toAddressAtCurrentInboxRow == tableWidget.item(currentInboxRow, 0).label: if toAddressAtCurrentInboxRow == tableWidget.item(currentInboxRow, 0).label:
self.ui.lineEditTo.setText(str(toAddressAtCurrentInboxRow)) self.ui.lineEditTo.setText(str(toAddressAtCurrentInboxRow))
else: else:
self.ui.lineEditTo.setText(tableWidget.item( self.ui.lineEditTo.setText(tableWidget.item(currentInboxRow, 0).label + " <" + str(acct.toAddress) + ">")
currentInboxRow, 0).label + " <" + str(acct.toAddress) + ">")
self.setSendFromComboBox(toAddressAtCurrentInboxRow) self.setSendFromComboBox(toAddressAtCurrentInboxRow)
@ -3550,8 +3060,6 @@ class MyForm(settingsmixin.SMainWindow): # pylint: disable=too-many-public-meth
widget['message'].setFocus() widget['message'].setFocus()
def on_action_InboxAddSenderToAddressBook(self): def on_action_InboxAddSenderToAddressBook(self):
"""TBC"""
tableWidget = self.getCurrentMessagelist() tableWidget = self.getCurrentMessagelist()
if not tableWidget: if not tableWidget:
return return
@ -3566,8 +3074,6 @@ class MyForm(settingsmixin.SMainWindow): # pylint: disable=too-many-public-meth
dialogs.AddAddressDialog(self, addressAtCurrentInboxRow)) dialogs.AddAddressDialog(self, addressAtCurrentInboxRow))
def on_action_InboxAddSenderToBlackList(self): def on_action_InboxAddSenderToBlackList(self):
"""TBC"""
tableWidget = self.getCurrentMessagelist() tableWidget = self.getCurrentMessagelist()
if not tableWidget: if not tableWidget:
return return
@ -3581,37 +3087,25 @@ class MyForm(settingsmixin.SMainWindow): # pylint: disable=too-many-public-meth
queryreturn = sqlQuery('''select * from blacklist where address=?''', queryreturn = sqlQuery('''select * from blacklist where address=?''',
addressAtCurrentInboxRow) addressAtCurrentInboxRow)
if queryreturn == []: if queryreturn == []:
label = "\"" + tableWidget.item(currentInboxRow, label = "\"" + tableWidget.item(currentInboxRow, 2).subject + "\" in " + BMConfigParser().get(recipientAddress, "label")
2).subject + "\" in " + BMConfigParser().get(recipientAddress,
"label")
sqlExecute('''INSERT INTO blacklist VALUES (?,?, ?)''', sqlExecute('''INSERT INTO blacklist VALUES (?,?, ?)''',
label, label,
addressAtCurrentInboxRow, True) addressAtCurrentInboxRow, True)
self.ui.blackwhitelist.rerenderBlackWhiteList() self.ui.blackwhitelist.rerenderBlackWhiteList()
self.updateStatusBar( self.updateStatusBar(_translate(
_translate(
"MainWindow", "MainWindow",
"Entry added to the blacklist. Edit the label to your liking." "Entry added to the blacklist. Edit the label to your liking.")
)
) )
else: else:
self.updateStatusBar( self.updateStatusBar(_translate(
_translate(
"MainWindow", "MainWindow",
("Error: You cannot add the same address to your blacklist" "Error: You cannot add the same address to your blacklist"
" twice. Try renaming the existing one if you want.") " twice. Try renaming the existing one if you want."))
)
)
def deleteRowFromMessagelist(self, row = None, inventoryHash = None, ackData = None, messageLists = None): def deleteRowFromMessagelist(self, row = None, inventoryHash = None, ackData = None, messageLists = None):
"""TBC"""
if messageLists is None: if messageLists is None:
messageLists = ( messageLists = (self.ui.tableWidgetInbox, self.ui.tableWidgetInboxChans, self.ui.tableWidgetInboxSubscriptions)
self.ui.tableWidgetInbox, elif type(messageLists) not in (list, tuple):
self.ui.tableWidgetInboxChans,
self.ui.tableWidgetInboxSubscriptions)
elif not isinstance(messageLists, (list, tuple)):
messageLists = (messageLists) messageLists = (messageLists)
for messageList in messageLists: for messageList in messageLists:
if row is not None: if row is not None:
@ -3627,16 +3121,15 @@ class MyForm(settingsmixin.SMainWindow): # pylint: disable=too-many-public-meth
if messageList.item(i, 3).data(QtCore.Qt.UserRole).toPyObject() == ackData: if messageList.item(i, 3).data(QtCore.Qt.UserRole).toPyObject() == ackData:
messageList.removeRow(i) messageList.removeRow(i)
# Send item on the Inbox tab to trash
def on_action_InboxTrash(self): def on_action_InboxTrash(self):
"""Send item on the Inbox tab to trash"""
tableWidget = self.getCurrentMessagelist() tableWidget = self.getCurrentMessagelist()
if not tableWidget: if not tableWidget:
return return
currentRow = 0 currentRow = 0
folder = self.getCurrentFolder() folder = self.getCurrentFolder()
shifted = QtGui.QApplication.queryKeyboardModifiers() & QtCore.Qt.ShiftModifier shifted = QtGui.QApplication.queryKeyboardModifiers() & QtCore.Qt.ShiftModifier
tableWidget.setUpdatesEnabled(False) tableWidget.setUpdatesEnabled(False);
inventoryHashesToTrash = [] inventoryHashesToTrash = []
# ranges in reversed order # ranges in reversed order
for r in sorted(tableWidget.selectedRanges(), key=lambda r: r.topRow())[::-1]: for r in sorted(tableWidget.selectedRanges(), key=lambda r: r.topRow())[::-1]:
@ -3663,8 +3156,6 @@ class MyForm(settingsmixin.SMainWindow): # pylint: disable=too-many-public-meth
"MainWindow", "Moved items to trash.")) "MainWindow", "Moved items to trash."))
def on_action_TrashUndelete(self): def on_action_TrashUndelete(self):
"""TBC"""
tableWidget = self.getCurrentMessagelist() tableWidget = self.getCurrentMessagelist()
if not tableWidget: if not tableWidget:
return return
@ -3695,8 +3186,6 @@ class MyForm(settingsmixin.SMainWindow): # pylint: disable=too-many-public-meth
self.updateStatusBar(_translate("MainWindow", "Undeleted item.")) self.updateStatusBar(_translate("MainWindow", "Undeleted item."))
def on_action_InboxSaveMessageAs(self): def on_action_InboxSaveMessageAs(self):
"""TBC"""
tableWidget = self.getCurrentMessagelist() tableWidget = self.getCurrentMessagelist()
if not tableWidget: if not tableWidget:
return return
@ -3717,9 +3206,7 @@ class MyForm(settingsmixin.SMainWindow): # pylint: disable=too-many-public-meth
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( filename = QtGui.QFileDialog.getSaveFileName(self, _translate("MainWindow","Save As..."), defaultFilename, "Text files (*.txt);;All files (*.*)")
self, _translate("MainWindow", "Save As..."),
defaultFilename, "Text files (*.txt);;All files (*.*)")
if filename == '': if filename == '':
return return
try: try:
@ -3730,10 +3217,10 @@ class MyForm(settingsmixin.SMainWindow): # pylint: disable=too-many-public-meth
logger.exception('Message not saved', exc_info=True) logger.exception('Message not saved', exc_info=True)
self.updateStatusBar(_translate("MainWindow", "Write error.")) self.updateStatusBar(_translate("MainWindow", "Write error."))
# Send item on the Sent tab to trash
def on_action_SentTrash(self): def on_action_SentTrash(self):
"""Send item on the Sent tab to trash"""
currentRow = 0 currentRow = 0
unread = False
tableWidget = self.getCurrentMessagelist() tableWidget = self.getCurrentMessagelist()
if not tableWidget: if not tableWidget:
return return
@ -3748,15 +3235,7 @@ class MyForm(settingsmixin.SMainWindow): # pylint: disable=too-many-public-meth
else: else:
sqlExecute('''UPDATE sent SET folder='trash' WHERE ackdata=?''', ackdataToTrash) sqlExecute('''UPDATE sent SET folder='trash' WHERE ackdata=?''', ackdataToTrash)
if tableWidget.item(currentRow, 0).unread: if tableWidget.item(currentRow, 0).unread:
self.propagateUnreadCount( self.propagateUnreadCount(tableWidget.item(currentRow, 1 if tableWidget.item(currentRow, 1).type == AccountMixin.SUBSCRIPTION else 0).data(QtCore.Qt.UserRole), folder, self.getCurrentTreeWidget(), -1)
tableWidget.item(
currentRow,
1 if tableWidget.item(currentRow, 1).type == AccountMixin.SUBSCRIPTION else 0
).data(QtCore.Qt.UserRole),
folder,
self.getCurrentTreeWidget(),
-1,
)
self.getCurrentMessageTextedit().setPlainText("") self.getCurrentMessageTextedit().setPlainText("")
tableWidget.removeRow(currentRow) tableWidget.removeRow(currentRow)
self.updateStatusBar(_translate( self.updateStatusBar(_translate(
@ -3766,8 +3245,6 @@ class MyForm(settingsmixin.SMainWindow): # pylint: disable=too-many-public-meth
currentRow if currentRow == 0 else currentRow - 1) currentRow if currentRow == 0 else currentRow - 1)
def on_action_ForceSend(self): def on_action_ForceSend(self):
"""TBC"""
currentRow = self.ui.tableWidgetInbox.currentRow() currentRow = self.ui.tableWidgetInbox.currentRow()
addressAtCurrentRow = self.ui.tableWidgetInbox.item( addressAtCurrentRow = self.ui.tableWidgetInbox.item(
currentRow, 0).data(QtCore.Qt.UserRole) currentRow, 0).data(QtCore.Qt.UserRole)
@ -3783,22 +3260,17 @@ class MyForm(settingsmixin.SMainWindow): # pylint: disable=too-many-public-meth
queues.workerQueue.put(('sendmessage', '')) queues.workerQueue.put(('sendmessage', ''))
def on_action_SentClipboard(self): def on_action_SentClipboard(self):
"""TBC"""
currentRow = self.ui.tableWidgetInbox.currentRow() currentRow = self.ui.tableWidgetInbox.currentRow()
addressAtCurrentRow = self.ui.tableWidgetInbox.item( addressAtCurrentRow = self.ui.tableWidgetInbox.item(
currentRow, 0).data(QtCore.Qt.UserRole) currentRow, 0).data(QtCore.Qt.UserRole)
clipboard = QtGui.QApplication.clipboard() clipboard = QtGui.QApplication.clipboard()
clipboard.setText(str(addressAtCurrentRow)) clipboard.setText(str(addressAtCurrentRow))
# Group of functions for the Address Book dialog box
def on_action_AddressBookNew(self): def on_action_AddressBookNew(self):
"""Group of functions for the Address Book dialog box"""
self.click_pushButtonAddAddressBook() self.click_pushButtonAddAddressBook()
def on_action_AddressBookDelete(self): def on_action_AddressBookDelete(self):
"""TBC"""
while self.ui.tableWidgetAddressBook.selectedIndexes() != []: while self.ui.tableWidgetAddressBook.selectedIndexes() != []:
currentRow = self.ui.tableWidgetAddressBook.selectedIndexes()[ currentRow = self.ui.tableWidgetAddressBook.selectedIndexes()[
0].row() 0].row()
@ -3813,8 +3285,6 @@ class MyForm(settingsmixin.SMainWindow): # pylint: disable=too-many-public-meth
self.rerenderMessagelistToLabels() self.rerenderMessagelistToLabels()
def on_action_AddressBookClipboard(self): def on_action_AddressBookClipboard(self):
"""TBC"""
fullStringOfAddresses = '' fullStringOfAddresses = ''
listOfSelectedRows = {} listOfSelectedRows = {}
for i in range(len(self.ui.tableWidgetAddressBook.selectedIndexes())): for i in range(len(self.ui.tableWidgetAddressBook.selectedIndexes())):
@ -3831,8 +3301,6 @@ class MyForm(settingsmixin.SMainWindow): # pylint: disable=too-many-public-meth
clipboard.setText(fullStringOfAddresses) clipboard.setText(fullStringOfAddresses)
def on_action_AddressBookSend(self): def on_action_AddressBookSend(self):
"""TBC"""
listOfSelectedRows = {} listOfSelectedRows = {}
for i in range(len(self.ui.tableWidgetAddressBook.selectedIndexes())): for i in range(len(self.ui.tableWidgetAddressBook.selectedIndexes())):
listOfSelectedRows[ listOfSelectedRows[
@ -3858,8 +3326,6 @@ class MyForm(settingsmixin.SMainWindow): # pylint: disable=too-many-public-meth
) )
def on_action_AddressBookSubscribe(self): def on_action_AddressBookSubscribe(self):
"""TBC"""
listOfSelectedRows = {} listOfSelectedRows = {}
for i in range(len(self.ui.tableWidgetAddressBook.selectedIndexes())): for i in range(len(self.ui.tableWidgetAddressBook.selectedIndexes())):
listOfSelectedRows[self.ui.tableWidgetAddressBook.selectedIndexes()[i].row()] = 0 listOfSelectedRows[self.ui.tableWidgetAddressBook.selectedIndexes()[i].row()] = 0
@ -3880,8 +3346,6 @@ class MyForm(settingsmixin.SMainWindow): # pylint: disable=too-many-public-meth
) )
def on_context_menuAddressBook(self, point): def on_context_menuAddressBook(self, point):
"""TBC"""
self.popMenuAddressBook = QtGui.QMenu(self) self.popMenuAddressBook = QtGui.QMenu(self)
self.popMenuAddressBook.addAction(self.actionAddressBookSend) self.popMenuAddressBook.addAction(self.actionAddressBookSend)
self.popMenuAddressBook.addAction(self.actionAddressBookClipboard) self.popMenuAddressBook.addAction(self.actionAddressBookClipboard)
@ -3893,9 +3357,9 @@ class MyForm(settingsmixin.SMainWindow): # pylint: disable=too-many-public-meth
normal = True normal = True
for row in self.ui.tableWidgetAddressBook.selectedIndexes(): for row in self.ui.tableWidgetAddressBook.selectedIndexes():
currentRow = row.row() currentRow = row.row()
row_type = self.ui.tableWidgetAddressBook.item( type = self.ui.tableWidgetAddressBook.item(
currentRow, 0).type currentRow, 0).type
if row_type != AccountMixin.NORMAL: if type != AccountMixin.NORMAL:
normal = False normal = False
if normal: if normal:
# only if all selected addressbook items are normal, allow delete # only if all selected addressbook items are normal, allow delete
@ -3903,14 +3367,11 @@ class MyForm(settingsmixin.SMainWindow): # pylint: disable=too-many-public-meth
self.popMenuAddressBook.exec_( self.popMenuAddressBook.exec_(
self.ui.tableWidgetAddressBook.mapToGlobal(point)) self.ui.tableWidgetAddressBook.mapToGlobal(point))
# Group of functions for the Subscriptions dialog box
def on_action_SubscriptionsNew(self): def on_action_SubscriptionsNew(self):
"""Group of functions for the Subscriptions dialog box"""
self.click_pushButtonAddSubscription() self.click_pushButtonAddSubscription()
def on_action_SubscriptionsDelete(self): def on_action_SubscriptionsDelete(self):
"""TBC"""
if QtGui.QMessageBox.question( if QtGui.QMessageBox.question(
self, "Delete subscription?", self, "Delete subscription?",
_translate( _translate(
@ -3934,15 +3395,11 @@ class MyForm(settingsmixin.SMainWindow): # pylint: disable=too-many-public-meth
shared.reloadBroadcastSendersForWhichImWatching() shared.reloadBroadcastSendersForWhichImWatching()
def on_action_SubscriptionsClipboard(self): def on_action_SubscriptionsClipboard(self):
"""TBC"""
address = self.getCurrentAccount() address = self.getCurrentAccount()
clipboard = QtGui.QApplication.clipboard() clipboard = QtGui.QApplication.clipboard()
clipboard.setText(str(address)) clipboard.setText(str(address))
def on_action_SubscriptionsEnable(self): def on_action_SubscriptionsEnable(self):
"""TBC"""
address = self.getCurrentAccount() address = self.getCurrentAccount()
sqlExecute( sqlExecute(
'''update subscriptions set enabled=1 WHERE address=?''', '''update subscriptions set enabled=1 WHERE address=?''',
@ -3953,8 +3410,6 @@ class MyForm(settingsmixin.SMainWindow): # pylint: disable=too-many-public-meth
shared.reloadBroadcastSendersForWhichImWatching() shared.reloadBroadcastSendersForWhichImWatching()
def on_action_SubscriptionsDisable(self): def on_action_SubscriptionsDisable(self):
"""TBC"""
address = self.getCurrentAccount() address = self.getCurrentAccount()
sqlExecute( sqlExecute(
'''update subscriptions set enabled=0 WHERE address=?''', '''update subscriptions set enabled=0 WHERE address=?''',
@ -3965,8 +3420,6 @@ class MyForm(settingsmixin.SMainWindow): # pylint: disable=too-many-public-meth
shared.reloadBroadcastSendersForWhichImWatching() shared.reloadBroadcastSendersForWhichImWatching()
def on_context_menuSubscriptions(self, point): def on_context_menuSubscriptions(self, point):
"""TBC"""
currentItem = self.getCurrentItem() currentItem = self.getCurrentItem()
self.popMenuSubscriptions = QtGui.QMenu(self) self.popMenuSubscriptions = QtGui.QMenu(self)
if isinstance(currentItem, Ui_AddressWidget): if isinstance(currentItem, Ui_AddressWidget):
@ -3989,9 +3442,7 @@ class MyForm(settingsmixin.SMainWindow): # pylint: disable=too-many-public-meth
self.popMenuSubscriptions.exec_( self.popMenuSubscriptions.exec_(
self.ui.treeWidgetSubscriptions.mapToGlobal(point)) self.ui.treeWidgetSubscriptions.mapToGlobal(point))
def widgetConvert(self, widget): # pylint: disable=inconsistent-return-statements def widgetConvert (self, widget):
"""TBC"""
if widget == self.ui.tableWidgetInbox: if widget == self.ui.tableWidgetInbox:
return self.ui.treeWidgetYourIdentities return self.ui.treeWidgetYourIdentities
elif widget == self.ui.tableWidgetInboxSubscriptions: elif widget == self.ui.tableWidgetInboxSubscriptions:
@ -4004,35 +3455,35 @@ class MyForm(settingsmixin.SMainWindow): # pylint: disable=too-many-public-meth
return self.ui.tableWidgetInboxSubscriptions return self.ui.tableWidgetInboxSubscriptions
elif widget == self.ui.treeWidgetChans: elif widget == self.ui.treeWidgetChans:
return self.ui.tableWidgetInboxChans return self.ui.tableWidgetInboxChans
else:
return None
def getCurrentTreeWidget(self): def getCurrentTreeWidget(self):
"""TBC""" currentIndex = self.ui.tabWidget.currentIndex();
currentIndex = self.ui.tabWidget.currentIndex()
treeWidgetList = [ treeWidgetList = [
self.ui.treeWidgetYourIdentities, self.ui.treeWidgetYourIdentities,
False, False,
self.ui.treeWidgetSubscriptions, self.ui.treeWidgetSubscriptions,
self.ui.treeWidgetChans self.ui.treeWidgetChans
] ]
return treeWidgetList[currentIndex] if currentIndex >= 0 and currentIndex < len(treeWidgetList) else False if currentIndex >= 0 and currentIndex < len(treeWidgetList):
return treeWidgetList[currentIndex]
else:
return False
def getAccountTreeWidget(self, account): def getAccountTreeWidget(self, account):
"""TBC"""
try: try:
if account.type == AccountMixin.CHAN: if account.type == AccountMixin.CHAN:
return self.ui.treeWidgetChans return self.ui.treeWidgetChans
elif account.type == AccountMixin.SUBSCRIPTION: elif account.type == AccountMixin.SUBSCRIPTION:
return self.ui.treeWidgetSubscriptions return self.ui.treeWidgetSubscriptions
else:
return self.ui.treeWidgetYourIdentities return self.ui.treeWidgetYourIdentities
except: except:
return self.ui.treeWidgetYourIdentities return self.ui.treeWidgetYourIdentities
def getCurrentMessagelist(self): def getCurrentMessagelist(self):
"""TBC""" currentIndex = self.ui.tabWidget.currentIndex();
currentIndex = self.ui.tabWidget.currentIndex()
messagelistList = [ messagelistList = [
self.ui.tableWidgetInbox, self.ui.tableWidgetInbox,
False, False,
@ -4041,23 +3492,21 @@ class MyForm(settingsmixin.SMainWindow): # pylint: disable=too-many-public-meth
] ]
if currentIndex >= 0 and currentIndex < len(messagelistList): if currentIndex >= 0 and currentIndex < len(messagelistList):
return messagelistList[currentIndex] return messagelistList[currentIndex]
else:
return False return False
def getAccountMessagelist(self, account): def getAccountMessagelist(self, account):
"""TBC"""
try: try:
if account.type == AccountMixin.CHAN: if account.type == AccountMixin.CHAN:
return self.ui.tableWidgetInboxChans return self.ui.tableWidgetInboxChans
elif account.type == AccountMixin.SUBSCRIPTION: elif account.type == AccountMixin.SUBSCRIPTION:
return self.ui.tableWidgetInboxSubscriptions return self.ui.tableWidgetInboxSubscriptions
else:
return self.ui.tableWidgetInbox return self.ui.tableWidgetInbox
except: except:
return self.ui.tableWidgetInbox return self.ui.tableWidgetInbox
def getCurrentMessageId(self): def getCurrentMessageId(self):
"""TBC"""
messagelist = self.getCurrentMessagelist() messagelist = self.getCurrentMessagelist()
if messagelist: if messagelist:
currentRow = messagelist.currentRow() currentRow = messagelist.currentRow()
@ -4069,8 +3518,6 @@ class MyForm(settingsmixin.SMainWindow): # pylint: disable=too-many-public-meth
return False return False
def getCurrentMessageTextedit(self): def getCurrentMessageTextedit(self):
"""TBC"""
currentIndex = self.ui.tabWidget.currentIndex() currentIndex = self.ui.tabWidget.currentIndex()
messagelistList = [ messagelistList = [
self.ui.textEditInboxMessage, self.ui.textEditInboxMessage,
@ -4080,41 +3527,38 @@ class MyForm(settingsmixin.SMainWindow): # pylint: disable=too-many-public-meth
] ]
if currentIndex >= 0 and currentIndex < len(messagelistList): if currentIndex >= 0 and currentIndex < len(messagelistList):
return messagelistList[currentIndex] return messagelistList[currentIndex]
else:
return False return False
def getAccountTextedit(self, account): def getAccountTextedit(self, account):
"""TBC"""
try: try:
if account.type == AccountMixin.CHAN: if account.type == AccountMixin.CHAN:
return self.ui.textEditInboxMessageChans return self.ui.textEditInboxMessageChans
elif account.type == AccountMixin.SUBSCRIPTION: elif account.type == AccountMixin.SUBSCRIPTION:
return self.ui.textEditInboxSubscriptions return self.ui.textEditInboxSubscriptions
else:
return self.ui.textEditInboxMessage return self.ui.textEditInboxMessage
except: except:
return self.ui.textEditInboxMessage return self.ui.textEditInboxMessage
def getCurrentSearchLine(self, currentIndex=None, retObj=False): # pylint: disable=inconsistent-return-statements def getCurrentSearchLine(self, currentIndex=None, retObj=False):
"""TBC"""
if currentIndex is None: if currentIndex is None:
currentIndex = self.ui.tabWidget.currentIndex() currentIndex = self.ui.tabWidget.currentIndex()
messagelistList = [ messagelistList = [
self.ui.inboxSearchLineEdit, self.ui.inboxSearchLineEdit,
False, False,
self.ui.inboxSearchLineEditSubscriptions, self.ui.inboxSearchLineEditSubscriptions,
self.ui.inboxSearchLineEditChans, self.ui.inboxSearchLineEditChans,
] ]
if currentIndex >= 0 and currentIndex < len(messagelistList): if currentIndex >= 0 and currentIndex < len(messagelistList):
if retObj: if retObj:
return messagelistList[currentIndex] return messagelistList[currentIndex]
else:
return messagelistList[currentIndex].text().toUtf8().data() return messagelistList[currentIndex].text().toUtf8().data()
else:
return None
def getCurrentSearchOption(self, currentIndex=None): # pylint: disable=inconsistent-return-statements def getCurrentSearchOption(self, currentIndex=None):
"""TBC"""
if currentIndex is None: if currentIndex is None:
currentIndex = self.ui.tabWidget.currentIndex() currentIndex = self.ui.tabWidget.currentIndex()
messagelistList = [ messagelistList = [
@ -4125,10 +3569,11 @@ class MyForm(settingsmixin.SMainWindow): # pylint: disable=too-many-public-meth
] ]
if currentIndex >= 0 and currentIndex < len(messagelistList): if currentIndex >= 0 and currentIndex < len(messagelistList):
return messagelistList[currentIndex].currentText().toUtf8().data() return messagelistList[currentIndex].currentText().toUtf8().data()
else:
return None
# Group of functions for the Your Identities dialog box
def getCurrentItem(self, treeWidget=None): def getCurrentItem(self, treeWidget=None):
"""Group of functions for the Your Identities dialog box"""
if treeWidget is None: if treeWidget is None:
treeWidget = self.getCurrentTreeWidget() treeWidget = self.getCurrentTreeWidget()
if treeWidget: if treeWidget:
@ -4138,27 +3583,26 @@ class MyForm(settingsmixin.SMainWindow): # pylint: disable=too-many-public-meth
return False return False
def getCurrentAccount(self, treeWidget=None): def getCurrentAccount(self, treeWidget=None):
"""TODO: debug msg in else?"""
currentItem = self.getCurrentItem(treeWidget) currentItem = self.getCurrentItem(treeWidget)
if currentItem: if currentItem:
account = currentItem.address account = currentItem.address
return account return account
else:
# TODO need debug msg?
return False return False
def getCurrentFolder(self, treeWidget=None): # pylint: disable=inconsistent-return-statements def getCurrentFolder(self, treeWidget=None):
"""TBC"""
if treeWidget is None: if treeWidget is None:
treeWidget = self.getCurrentTreeWidget() treeWidget = self.getCurrentTreeWidget()
#treeWidget = self.ui.treeWidgetYourIdentities
if treeWidget: if treeWidget:
currentItem = treeWidget.currentItem() currentItem = treeWidget.currentItem()
if currentItem and hasattr(currentItem, 'folderName'): if currentItem and hasattr(currentItem, 'folderName'):
return currentItem.folderName return currentItem.folderName
else:
return None
def setCurrentItemColor(self, color): def setCurrentItemColor(self, color):
"""TBC"""
treeWidget = self.getCurrentTreeWidget() treeWidget = self.getCurrentTreeWidget()
if treeWidget: if treeWidget:
brush = QtGui.QBrush() brush = QtGui.QBrush()
@ -4168,13 +3612,9 @@ class MyForm(settingsmixin.SMainWindow): # pylint: disable=too-many-public-meth
currentItem.setForeground(0, brush) currentItem.setForeground(0, brush)
def on_action_YourIdentitiesNew(self): def on_action_YourIdentitiesNew(self):
"""TBC"""
self.click_NewAddressDialog() self.click_NewAddressDialog()
def on_action_YourIdentitiesDelete(self): def on_action_YourIdentitiesDelete(self):
"""TBC"""
account = self.getCurrentItem() account = self.getCurrentItem()
if account.type == AccountMixin.NORMAL: if account.type == AccountMixin.NORMAL:
return # maybe in the future return # maybe in the future
@ -4207,48 +3647,35 @@ class MyForm(settingsmixin.SMainWindow): # pylint: disable=too-many-public-meth
self.rerenderTabTreeChans() self.rerenderTabTreeChans()
def on_action_Enable(self): def on_action_Enable(self):
"""TBC"""
addressAtCurrentRow = self.getCurrentAccount() addressAtCurrentRow = self.getCurrentAccount()
self.enableIdentity(addressAtCurrentRow) self.enableIdentity(addressAtCurrentRow)
account = self.getCurrentItem() account = self.getCurrentItem()
account.setEnabled(True) account.setEnabled(True)
def enableIdentity(self, address): def enableIdentity(self, address):
"""TBC"""
BMConfigParser().set(address, 'enabled', 'true') BMConfigParser().set(address, 'enabled', 'true')
BMConfigParser().save() BMConfigParser().save()
shared.reloadMyAddressHashes() shared.reloadMyAddressHashes()
self.rerenderAddressBook() self.rerenderAddressBook()
def on_action_Disable(self): def on_action_Disable(self):
"""TBC"""
address = self.getCurrentAccount() address = self.getCurrentAccount()
self.disableIdentity(address) self.disableIdentity(address)
account = self.getCurrentItem() account = self.getCurrentItem()
account.setEnabled(False) account.setEnabled(False)
def disableIdentity(self, address): def disableIdentity(self, address):
"""TBC"""
BMConfigParser().set(str(address), 'enabled', 'false') BMConfigParser().set(str(address), 'enabled', 'false')
BMConfigParser().save() BMConfigParser().save()
shared.reloadMyAddressHashes() shared.reloadMyAddressHashes()
self.rerenderAddressBook() self.rerenderAddressBook()
def on_action_Clipboard(self): def on_action_Clipboard(self):
"""TBC"""
address = self.getCurrentAccount() address = self.getCurrentAccount()
clipboard = QtGui.QApplication.clipboard() clipboard = QtGui.QApplication.clipboard()
clipboard.setText(str(address)) clipboard.setText(str(address))
def on_action_ClipboardMessagelist(self): def on_action_ClipboardMessagelist(self):
"""TBC"""
# pylint: disable=too-many-boolean-expressions
tableWidget = self.getCurrentMessagelist() tableWidget = self.getCurrentMessagelist()
currentColumn = tableWidget.currentColumn() currentColumn = tableWidget.currentColumn()
currentRow = tableWidget.currentRow() currentRow = tableWidget.currentRow()
@ -4264,14 +3691,9 @@ class MyForm(settingsmixin.SMainWindow): # pylint: disable=too-many-public-meth
myAddress = tableWidget.item(currentRow, 0).data(QtCore.Qt.UserRole) myAddress = tableWidget.item(currentRow, 0).data(QtCore.Qt.UserRole)
otherAddress = tableWidget.item(currentRow, 1).data(QtCore.Qt.UserRole) otherAddress = tableWidget.item(currentRow, 1).data(QtCore.Qt.UserRole)
account = accountClass(myAddress) account = accountClass(myAddress)
if ( if isinstance(account, GatewayAccount) and otherAddress == account.relayAddress and (
isinstance(account, GatewayAccount) and (currentColumn in [0, 2] and self.getCurrentFolder() == "sent") or
otherAddress == account.relayAddress and ( (currentColumn in [1, 2] and self.getCurrentFolder() != "sent")):
currentColumn in [0, 2] and self.getCurrentFolder() == "sent" or
currentColumn in [1, 2] and self.getCurrentFolder() != "sent"
)
):
text = str(tableWidget.item(currentRow, currentColumn).label) text = str(tableWidget.item(currentRow, currentColumn).label)
else: else:
text = tableWidget.item(currentRow, currentColumn).data(QtCore.Qt.UserRole) text = tableWidget.item(currentRow, currentColumn).data(QtCore.Qt.UserRole)
@ -4279,20 +3701,15 @@ class MyForm(settingsmixin.SMainWindow): # pylint: disable=too-many-public-meth
clipboard = QtGui.QApplication.clipboard() clipboard = QtGui.QApplication.clipboard()
clipboard.setText(text) clipboard.setText(text)
#set avatar functions
def on_action_TreeWidgetSetAvatar(self): def on_action_TreeWidgetSetAvatar(self):
"""set avatar functions"""
address = self.getCurrentAccount() address = self.getCurrentAccount()
self.setAvatar(address) self.setAvatar(address)
def on_action_AddressBookSetAvatar(self): def on_action_AddressBookSetAvatar(self):
"""TBC"""
self.on_action_SetAvatar(self.ui.tableWidgetAddressBook) self.on_action_SetAvatar(self.ui.tableWidgetAddressBook)
def on_action_SetAvatar(self, thisTableWidget): def on_action_SetAvatar(self, thisTableWidget):
"""TBC"""
currentRow = thisTableWidget.currentRow() currentRow = thisTableWidget.currentRow()
addressAtCurrentRow = thisTableWidget.item( addressAtCurrentRow = thisTableWidget.item(
currentRow, 1).text() currentRow, 1).text()
@ -4302,50 +3719,20 @@ class MyForm(settingsmixin.SMainWindow): # pylint: disable=too-many-public-meth
currentRow, 0).setIcon(avatarize(addressAtCurrentRow)) currentRow, 0).setIcon(avatarize(addressAtCurrentRow))
def setAvatar(self, addressAtCurrentRow): def setAvatar(self, addressAtCurrentRow):
"""TBC"""
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/')
addressHash = hashlib.md5(addBMIfNotPresent(addressAtCurrentRow)).hexdigest() hash = hashlib.md5(addBMIfNotPresent(addressAtCurrentRow)).hexdigest()
extensions = [ extensions = ['PNG', 'GIF', 'JPG', 'JPEG', 'SVG', 'BMP', 'MNG', 'PBM', 'PGM', 'PPM', 'TIFF', 'XBM', 'XPM', 'TGA']
'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 = { 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'}
'BMP': 'Windows Bitmap',
'GIF': 'Graphic Interchange Format',
'JPG': 'Joint Photographic Experts Group',
'JPEG': 'Joint Photographic Experts Group',
'MNG': 'Multiple-image Network Graphics',
'PNG': 'Portable Network Graphics',
'PBM': 'Portable Bitmap',
'PGM': 'Portable Graymap',
'PPM': 'Portable Pixmap',
'TIFF': 'Tagged Image File Format',
'XBM': 'X11 Bitmap',
'XPM': 'X11 Pixmap',
'SVG': 'Scalable Vector Graphics',
'TGA': 'Targa Image Format'}
filters = [] filters = []
all_images_filter = [] all_images_filter = []
current_files = [] current_files = []
for ext in extensions: for ext in extensions:
filters += [ names[ext] + ' (*.' + ext.lower() + ')' ] filters += [ names[ext] + ' (*.' + ext.lower() + ')' ]
all_images_filter += [ '*.' + ext.lower() ] all_images_filter += [ '*.' + ext.lower() ]
upper = state.appdata + 'avatars/' + addressHash + '.' + ext.upper() upper = state.appdata + 'avatars/' + hash + '.' + ext.upper()
lower = state.appdata + 'avatars/' + addressHash + '.' + ext.lower() lower = state.appdata + 'avatars/' + hash + '.' + ext.lower()
if os.path.isfile(lower): if os.path.isfile(lower):
current_files += [lower] current_files += [lower]
elif os.path.isfile(upper): elif os.path.isfile(upper):
@ -4357,11 +3744,11 @@ class MyForm(settingsmixin.SMainWindow): # pylint: disable=too-many-public-meth
filter = ';;'.join(filters) filter = ';;'.join(filters)
) )
# determine the correct filename (note that avatars don't use the suffix) # determine the correct filename (note that avatars don't use the suffix)
destination = state.appdata + 'avatars/' + addressHash + '.' + sourcefile.split('.')[-1] destination = state.appdata + 'avatars/' + hash + '.' + sourcefile.split('.')[-1]
exists = QtCore.QFile.exists(destination) exists = QtCore.QFile.exists(destination)
if sourcefile == '': if sourcefile == '':
# ask for removal of avatar # ask for removal of avatar
if exists | current_files: if exists | (len(current_files)>0):
displayMsg = _translate("MainWindow", "Do you really want to remove this avatar?") displayMsg = _translate("MainWindow", "Do you really want to remove this avatar?")
overwrite = QtGui.QMessageBox.question( overwrite = QtGui.QMessageBox.question(
self, 'Message', displayMsg, QtGui.QMessageBox.Yes, QtGui.QMessageBox.No) self, 'Message', displayMsg, QtGui.QMessageBox.Yes, QtGui.QMessageBox.No)
@ -4369,20 +3756,18 @@ class MyForm(settingsmixin.SMainWindow): # pylint: disable=too-many-public-meth
overwrite = QtGui.QMessageBox.No overwrite = QtGui.QMessageBox.No
else: else:
# ask whether to overwrite old avatar # ask whether to overwrite old avatar
if exists | current_files: if exists | (len(current_files)>0):
displayMsg = _translate( displayMsg = _translate("MainWindow", "You have already set an avatar for this address. Do you really want to overwrite it?")
"MainWindow",
"You have already set an avatar for this address. Do you really want to overwrite it?")
overwrite = QtGui.QMessageBox.question( overwrite = QtGui.QMessageBox.question(
self, 'Message', displayMsg, QtGui.QMessageBox.Yes, QtGui.QMessageBox.No) self, 'Message', displayMsg, QtGui.QMessageBox.Yes, QtGui.QMessageBox.No)
else: else:
overwrite = QtGui.QMessageBox.No overwrite = QtGui.QMessageBox.No
# copy the image file to the appdata folder # copy the image file to the appdata folder
if not exists | overwrite == QtGui.QMessageBox.Yes: if (not exists) | (overwrite == QtGui.QMessageBox.Yes):
if overwrite == QtGui.QMessageBox.Yes: if overwrite == QtGui.QMessageBox.Yes:
for file_name in current_files: for file in current_files:
QtCore.QFile.remove(file_name) QtCore.QFile.remove(file)
QtCore.QFile.remove(destination) QtCore.QFile.remove(destination)
# copy it # copy it
if sourcefile != '': if sourcefile != '':
@ -4404,14 +3789,10 @@ class MyForm(settingsmixin.SMainWindow): # pylint: disable=too-many-public-meth
return True return True
def on_action_AddressBookSetSound(self): def on_action_AddressBookSetSound(self):
"""TBC"""
widget = self.ui.tableWidgetAddressBook widget = self.ui.tableWidgetAddressBook
self.setAddressSound(widget.item(widget.currentRow(), 0).text()) self.setAddressSound(widget.item(widget.currentRow(), 0).text())
def setAddressSound(self, addr): def setAddressSound(self, addr):
"""TBC"""
filters = [unicode(_translate( filters = [unicode(_translate(
"MainWindow", "Sound files (%s)" % "MainWindow", "Sound files (%s)" %
' '.join(['*%s%s' % (os.extsep, ext) for ext in sound.extensions]) ' '.join(['*%s%s' % (os.extsep, ext) for ext in sound.extensions])
@ -4452,8 +3833,6 @@ class MyForm(settingsmixin.SMainWindow): # pylint: disable=too-many-public-meth
'couldn\'t copy %s to %s', sourcefile, destination) 'couldn\'t copy %s to %s', sourcefile, destination)
def on_context_menuYourIdentities(self, point): def on_context_menuYourIdentities(self, point):
"""TBC"""
currentItem = self.getCurrentItem() currentItem = self.getCurrentItem()
self.popMenuYourIdentities = QtGui.QMenu(self) self.popMenuYourIdentities = QtGui.QMenu(self)
if isinstance(currentItem, Ui_AddressWidget): if isinstance(currentItem, Ui_AddressWidget):
@ -4479,9 +3858,8 @@ class MyForm(settingsmixin.SMainWindow): # pylint: disable=too-many-public-meth
self.popMenuYourIdentities.exec_( self.popMenuYourIdentities.exec_(
self.ui.treeWidgetYourIdentities.mapToGlobal(point)) self.ui.treeWidgetYourIdentities.mapToGlobal(point))
# TODO make one popMenu
def on_context_menuChan(self, point): def on_context_menuChan(self, point):
"""TODO: make one popMenu"""
currentItem = self.getCurrentItem() currentItem = self.getCurrentItem()
self.popMenu = QtGui.QMenu(self) self.popMenu = QtGui.QMenu(self)
if isinstance(currentItem, Ui_AddressWidget): if isinstance(currentItem, Ui_AddressWidget):
@ -4505,8 +3883,6 @@ class MyForm(settingsmixin.SMainWindow): # pylint: disable=too-many-public-meth
self.ui.treeWidgetChans.mapToGlobal(point)) self.ui.treeWidgetChans.mapToGlobal(point))
def on_context_menuInbox(self, point): def on_context_menuInbox(self, point):
"""TBC"""
tableWidget = self.getCurrentMessagelist() tableWidget = self.getCurrentMessagelist()
if tableWidget: if tableWidget:
currentFolder = self.getCurrentFolder() currentFolder = self.getCurrentFolder()
@ -4527,9 +3903,9 @@ class MyForm(settingsmixin.SMainWindow): # pylint: disable=too-many-public-meth
self.popMenuInbox.addAction(self.actionReply) self.popMenuInbox.addAction(self.actionReply)
self.popMenuInbox.addAction(self.actionAddSenderToAddressBook) self.popMenuInbox.addAction(self.actionAddSenderToAddressBook)
self.actionClipboardMessagelist = self.ui.inboxContextMenuToolbar.addAction( self.actionClipboardMessagelist = self.ui.inboxContextMenuToolbar.addAction(
_translate( _translate("MainWindow",
"MainWindow", "Copy subject to clipboard" "Copy subject to clipboard" if tableWidget.currentColumn() == 2 else "Copy address to clipboard"
if tableWidget.currentColumn() == 2 else "Copy address to clipboard"), ),
self.on_action_ClipboardMessagelist) self.on_action_ClipboardMessagelist)
self.popMenuInbox.addAction(self.actionClipboardMessagelist) self.popMenuInbox.addAction(self.actionClipboardMessagelist)
self.popMenuInbox.addSeparator() self.popMenuInbox.addSeparator()
@ -4543,8 +3919,6 @@ class MyForm(settingsmixin.SMainWindow): # pylint: disable=too-many-public-meth
self.popMenuInbox.exec_(tableWidget.mapToGlobal(point)) self.popMenuInbox.exec_(tableWidget.mapToGlobal(point))
def on_context_menuSent(self, point): def on_context_menuSent(self, point):
"""TBC"""
self.popMenuSent = QtGui.QMenu(self) self.popMenuSent = QtGui.QMenu(self)
self.popMenuSent.addAction(self.actionSentClipboard) self.popMenuSent.addAction(self.actionSentClipboard)
self.popMenuSent.addAction(self.actionTrashSentMessage) self.popMenuSent.addAction(self.actionTrashSentMessage)
@ -4564,8 +3938,6 @@ class MyForm(settingsmixin.SMainWindow): # pylint: disable=too-many-public-meth
self.popMenuSent.exec_(self.ui.tableWidgetInbox.mapToGlobal(point)) self.popMenuSent.exec_(self.ui.tableWidgetInbox.mapToGlobal(point))
def inboxSearchLineEditUpdated(self, text): def inboxSearchLineEditUpdated(self, text):
"""TBC"""
# dynamic search for too short text is slow # dynamic search for too short text is slow
if len(str(text)) < 3: if len(str(text)) < 3:
return return
@ -4577,8 +3949,6 @@ class MyForm(settingsmixin.SMainWindow): # pylint: disable=too-many-public-meth
self.loadMessagelist(messagelist, account, folder, searchOption, str(text)) self.loadMessagelist(messagelist, account, folder, searchOption, str(text))
def inboxSearchLineEditReturnPressed(self): def inboxSearchLineEditReturnPressed(self):
"""TBC"""
logger.debug("Search return pressed") logger.debug("Search return pressed")
searchLine = self.getCurrentSearchLine() searchLine = self.getCurrentSearchLine()
messagelist = self.getCurrentMessagelist() messagelist = self.getCurrentMessagelist()
@ -4591,8 +3961,6 @@ class MyForm(settingsmixin.SMainWindow): # pylint: disable=too-many-public-meth
messagelist.setFocus() messagelist.setFocus()
def treeWidgetItemClicked(self): def treeWidgetItemClicked(self):
"""TBC"""
searchLine = self.getCurrentSearchLine() searchLine = self.getCurrentSearchLine()
searchOption = self.getCurrentSearchOption() searchOption = self.getCurrentSearchOption()
messageTextedit = self.getCurrentMessageTextedit() messageTextedit = self.getCurrentMessageTextedit()
@ -4608,19 +3976,12 @@ class MyForm(settingsmixin.SMainWindow): # pylint: disable=too-many-public-meth
self.loadMessagelist(messagelist, account, folder, searchOption, searchLine) self.loadMessagelist(messagelist, account, folder, searchOption, searchLine)
def treeWidgetItemChanged(self, item, column): def treeWidgetItemChanged(self, item, column):
"""TBC"""
# only for manual edits. automatic edits (setText) are ignored # only for manual edits. automatic edits (setText) are ignored
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 ( if (not isinstance(item, Ui_AddressWidget)) or (not self.getCurrentTreeWidget()) or self.getCurrentTreeWidget().currentItem() is None:
not isinstance(item, Ui_AddressWidget) or
not self.getCurrentTreeWidget() or
self.getCurrentTreeWidget().currentItem() is None
):
return return
# not visible # not visible
if (not self.getCurrentItem()) or (not isinstance (self.getCurrentItem(), Ui_AddressWidget)): if (not self.getCurrentItem()) or (not isinstance (self.getCurrentItem(), Ui_AddressWidget)):
return return
@ -4655,8 +4016,6 @@ class MyForm(settingsmixin.SMainWindow): # pylint: disable=too-many-public-meth
self.recurDepth -= 1 self.recurDepth -= 1
def tableWidgetInboxItemClicked(self): def tableWidgetInboxItemClicked(self):
"""TBC"""
folder = self.getCurrentFolder() folder = self.getCurrentFolder()
messageTextedit = self.getCurrentMessageTextedit() messageTextedit = self.getCurrentMessageTextedit()
if not messageTextedit: if not messageTextedit:
@ -4687,10 +4046,10 @@ class MyForm(settingsmixin.SMainWindow): # pylint: disable=too-many-public-meth
if tableWidget.item(currentRow, 0).unread is True: if tableWidget.item(currentRow, 0).unread is True:
self.updateUnreadStatus(tableWidget, currentRow, msgid) self.updateUnreadStatus(tableWidget, currentRow, msgid)
# propagate # propagate
if ( if folder != 'sent' and sqlExecute(
folder != 'sent' and '''UPDATE inbox SET read=1 WHERE msgid=? AND read=0''',
sqlExecute('''UPDATE inbox SET read=1 WHERE msgid=? AND read=0''', msgid) > 0 msgid
): ) > 0:
self.propagateUnreadCount() self.propagateUnreadCount()
messageTextedit.setCurrentFont(QtGui.QFont()) messageTextedit.setCurrentFont(QtGui.QFont())
@ -4698,29 +4057,23 @@ class MyForm(settingsmixin.SMainWindow): # pylint: disable=too-many-public-meth
messageTextedit.setContent(message) messageTextedit.setContent(message)
def tableWidgetAddressBookItemChanged(self, item): def tableWidgetAddressBookItemChanged(self, item):
"""TBC"""
if item.type == AccountMixin.CHAN: if item.type == AccountMixin.CHAN:
self.rerenderComboBoxSendFrom() self.rerenderComboBoxSendFrom()
self.rerenderMessagelistFromLabels() self.rerenderMessagelistFromLabels()
self.rerenderMessagelistToLabels() self.rerenderMessagelistToLabels()
completerList = self.ui.lineEditTo.completer().model().stringList() completerList = self.ui.lineEditTo.completer().model().stringList()
for i, this_item in enumerate(completerList): for i in range(len(completerList)):
if unicode(this_item).endswith(" <" + item.address + ">"): if unicode(completerList[i]).endswith(" <" + item.address + ">"):
this_item = item.label + " <" + item.address + ">" completerList[i] = item.label + " <" + item.address + ">"
self.ui.lineEditTo.completer().model().setStringList(completerList) self.ui.lineEditTo.completer().model().setStringList(completerList)
def tabWidgetCurrentChanged(self, n): def tabWidgetCurrentChanged(self, n):
"""TBC"""
if n == self.ui.tabWidget.indexOf(self.ui.networkstatus): if n == self.ui.tabWidget.indexOf(self.ui.networkstatus):
self.ui.networkstatus.startUpdate() self.ui.networkstatus.startUpdate()
else: else:
self.ui.networkstatus.stopUpdate() self.ui.networkstatus.stopUpdate()
def writeNewAddressToTable(self, label, address, streamNumber): def writeNewAddressToTable(self, label, address, streamNumber):
"""TBC"""
self.rerenderTabTreeMessages() self.rerenderTabTreeMessages()
self.rerenderTabTreeSubscriptions() self.rerenderTabTreeSubscriptions()
self.rerenderTabTreeChans() self.rerenderTabTreeChans()
@ -4729,16 +4082,14 @@ class MyForm(settingsmixin.SMainWindow): # pylint: disable=too-many-public-meth
self.rerenderAddressBook() self.rerenderAddressBook()
def updateStatusBar(self, data): def updateStatusBar(self, data):
"""TBC""" if type(data) is tuple or type(data) is list:
if isinstance(data, (tuple, list)):
option = data[1] option = data[1]
message = data[0] message = data[0]
else: else:
option = 0 option = 0
message = data message = data
if message != "": if message != "":
logger.info('Status bar: %s', message) logger.info('Status bar: ' + message)
if option == 1: if option == 1:
self.statusbar.addImportant(message) self.statusbar.addImportant(message)
@ -4746,8 +4097,6 @@ class MyForm(settingsmixin.SMainWindow): # pylint: disable=too-many-public-meth
self.statusbar.showMessage(message, 10000) self.statusbar.showMessage(message, 10000)
def initSettings(self): def initSettings(self):
"""TBC"""
QtCore.QCoreApplication.setOrganizationName("PyBitmessage") QtCore.QCoreApplication.setOrganizationName("PyBitmessage")
QtCore.QCoreApplication.setOrganizationDomain("bitmessage.org") QtCore.QCoreApplication.setOrganizationDomain("bitmessage.org")
QtCore.QCoreApplication.setApplicationName("pybitmessageqt") QtCore.QCoreApplication.setApplicationName("pybitmessageqt")
@ -4761,11 +4110,8 @@ class MyForm(settingsmixin.SMainWindow): # pylint: disable=too-many-public-meth
class settingsDialog(QtGui.QDialog): class settingsDialog(QtGui.QDialog):
"""TBC"""
def __init__(self, parent): def __init__(self, parent):
"""TBC"""
QtGui.QWidget.__init__(self, parent) QtGui.QWidget.__init__(self, parent)
self.ui = Ui_settingsDialog() self.ui = Ui_settingsDialog()
self.ui.setupUi(self) self.ui.setupUi(self)
@ -4854,36 +4200,16 @@ class settingsDialog(QtGui.QDialog):
BMConfigParser().get('bitmessagesettings', 'maxoutboundconnections'))) BMConfigParser().get('bitmessagesettings', 'maxoutboundconnections')))
# Demanded difficulty tab # Demanded difficulty tab
self.ui.lineEditTotalDifficulty.setText( self.ui.lineEditTotalDifficulty.setText(str((float(BMConfigParser().getint(
str( 'bitmessagesettings', 'defaultnoncetrialsperbyte')) / defaults.networkDefaultProofOfWorkNonceTrialsPerByte)))
float( self.ui.lineEditSmallMessageDifficulty.setText(str((float(BMConfigParser().getint(
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( self.ui.lineEditMaxAcceptableTotalDifficulty.setText(str((float(BMConfigParser().getint(
str( 'bitmessagesettings', 'maxacceptablenoncetrialsperbyte')) / defaults.networkDefaultProofOfWorkNonceTrialsPerByte)))
float( self.ui.lineEditMaxAcceptableSmallMessageDifficulty.setText(str((float(BMConfigParser().getint(
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():
@ -4934,11 +4260,28 @@ class settingsDialog(QtGui.QDialog):
self.ui.lineEditMonths.setText(str( self.ui.lineEditMonths.setText(str(
BMConfigParser().get('bitmessagesettings', 'stopresendingafterxmonths'))) BMConfigParser().get('bitmessagesettings', 'stopresendingafterxmonths')))
#'System' tab removed for now.
"""try:
maxCores = BMConfigParser().getint('bitmessagesettings', 'maxcores')
except:
maxCores = 99999
if maxCores <= 1:
self.ui.comboBoxMaxCores.setCurrentIndex(0)
elif maxCores == 2:
self.ui.comboBoxMaxCores.setCurrentIndex(1)
elif maxCores <= 4:
self.ui.comboBoxMaxCores.setCurrentIndex(2)
elif maxCores <= 8:
self.ui.comboBoxMaxCores.setCurrentIndex(3)
elif maxCores <= 16:
self.ui.comboBoxMaxCores.setCurrentIndex(4)
else:
self.ui.comboBoxMaxCores.setCurrentIndex(5)"""
QtGui.QWidget.resize(self, QtGui.QWidget.sizeHint(self)) QtGui.QWidget.resize(self, QtGui.QWidget.sizeHint(self))
def comboBoxProxyTypeChanged(self, comboBoxIndex): def comboBoxProxyTypeChanged(self, comboBoxIndex):
"""TBC"""
if comboBoxIndex == 0: if comboBoxIndex == 0:
self.ui.lineEditSocksHostname.setEnabled(False) self.ui.lineEditSocksHostname.setEnabled(False)
self.ui.lineEditSocksPort.setEnabled(False) self.ui.lineEditSocksPort.setEnabled(False)
@ -4955,19 +4298,17 @@ class settingsDialog(QtGui.QDialog):
self.ui.lineEditSocksUsername.setEnabled(True) self.ui.lineEditSocksUsername.setEnabled(True)
self.ui.lineEditSocksPassword.setEnabled(True) self.ui.lineEditSocksPassword.setEnabled(True)
# Check status of namecoin integration radio buttons and translate
# it to a string as in the options.
def getNamecoinType(self): def getNamecoinType(self):
"""Check status of namecoin integration radio buttons and translate it to a string as in the options."""
if self.ui.radioButtonNamecoinNamecoind.isChecked(): if self.ui.radioButtonNamecoinNamecoind.isChecked():
return "namecoind" return "namecoind"
elif self.ui.radioButtonNamecoinNmcontrol.isChecked(): if self.ui.radioButtonNamecoinNmcontrol.isChecked():
return "nmcontrol" return "nmcontrol"
logger.info("Neither namecoind nor nmcontrol were checked. This is a fatal error") assert False
sys.exit(1)
# Namecoin connection type was changed.
def namecoinTypeChanged(self, checked): def namecoinTypeChanged(self, checked):
"""Namecoin connection type was changed."""
nmctype = self.getNamecoinType() nmctype = self.getNamecoinType()
assert nmctype == "namecoind" or nmctype == "nmcontrol" assert nmctype == "namecoind" or nmctype == "nmcontrol"
@ -4982,9 +4323,8 @@ class settingsDialog(QtGui.QDialog):
else: else:
self.ui.lineEditNamecoinPort.setText("9000") self.ui.lineEditNamecoinPort.setText("9000")
# Test the namecoin settings specified in the settings dialog.
def click_pushButtonNamecoinTest(self): def click_pushButtonNamecoinTest(self):
"""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 = {}
@ -5002,11 +4342,10 @@ class settingsDialog(QtGui.QDialog):
self.parent.ui.pushButtonFetchNamecoinID.show() self.parent.ui.pushButtonFetchNamecoinID.show()
# In order for the time columns on the Inbox and Sent tabs to be sorted
# correctly (rather than alphabetically), we need to overload the <
# operator and use this class instead of QTableWidgetItem.
class myTableWidgetItem(QtGui.QTableWidgetItem): class myTableWidgetItem(QtGui.QTableWidgetItem):
"""
In order for the time columns on the Inbox and Sent tabs to be sorted correctly (rather than alphabetically),
we need to overload the < operator and use this class instead of QTableWidgetItem.
"""
def __lt__(self, other): def __lt__(self, other):
return int(self.data(33).toPyObject()) < int(other.data(33).toPyObject()) return int(self.data(33).toPyObject()) < int(other.data(33).toPyObject())
@ -5029,23 +4368,21 @@ class MySingleApplication(QtGui.QApplication):
uuid = '6ec0149b-96e1-4be1-93ab-1465fb3ebf7c' uuid = '6ec0149b-96e1-4be1-93ab-1465fb3ebf7c'
def __init__(self, *argv): def __init__(self, *argv):
"""TBC"""
super(MySingleApplication, self).__init__(*argv) super(MySingleApplication, self).__init__(*argv)
_id = MySingleApplication.uuid id = MySingleApplication.uuid
self.server = None self.server = None
self.is_running = False self.is_running = False
socket = QLocalSocket() socket = QLocalSocket()
socket.connectToServer(_id) socket.connectToServer(id)
self.is_running = socket.waitForConnected() self.is_running = socket.waitForConnected()
# Cleanup past crashed servers # Cleanup past crashed servers
if not self.is_running: if not self.is_running:
if socket.error() == QLocalSocket.ConnectionRefusedError: if socket.error() == QLocalSocket.ConnectionRefusedError:
socket.disconnectFromServer() socket.disconnectFromServer()
QLocalServer.removeServer(_id) QLocalServer.removeServer(id)
socket.abort() socket.abort()
@ -5057,44 +4394,34 @@ class MySingleApplication(QtGui.QApplication):
# Nope, create a local server with this id and assign on_new_connection # Nope, create a local server with this id and assign on_new_connection
# for whenever a second instance tries to run focus the application. # for whenever a second instance tries to run focus the application.
self.server = QLocalServer() self.server = QLocalServer()
self.server.listen(_id) self.server.listen(id)
self.server.newConnection.connect(self.on_new_connection) self.server.newConnection.connect(self.on_new_connection)
def __del__(self): def __del__(self):
"""TBC"""
if self.server: if self.server:
self.server.close() self.server.close()
def on_new_connection(self): def on_new_connection(self):
"""TBC"""
if myapp: if myapp:
myapp.appIndicatorShow() myapp.appIndicatorShow()
def init(): def init():
"""TBC"""
global app global app
if not app: if not app:
app = MySingleApplication(sys.argv) app = MySingleApplication(sys.argv)
return app return app
def run(): def run():
"""Run the gui"""
global myapp global myapp
app = init()
running_app = init()
change_translation(l10n.getTranslationLanguage()) change_translation(l10n.getTranslationLanguage())
app.setStyleSheet("QStatusBar::item { border: 0px solid black }") app.setStyleSheet("QStatusBar::item { border: 0px solid black }")
myapp = MyForm() myapp = MyForm()
myapp.sqlInit() myapp.sqlInit()
myapp.appIndicatorInit(running_app) myapp.appIndicatorInit(app)
myapp.indicatorInit() myapp.indicatorInit()
myapp.notifierInit() myapp.notifierInit()
myapp._firstrun = BMConfigParser().safeGetBoolean( myapp._firstrun = BMConfigParser().safeGetBoolean(
@ -5103,6 +4430,12 @@ def run():
myapp.showConnectDialog() # ask the user if we may connect myapp.showConnectDialog() # ask the user if we may connect
myapp.ui.updateNetworkSwitchMenuLabel() myapp.ui.updateNetworkSwitchMenuLabel()
# try:
# if BMConfigParser().get('bitmessagesettings', 'mailchuck') < 1:
# myapp.showMigrationWizard(BMConfigParser().get('bitmessagesettings', 'mailchuck'))
# except:
# myapp.showMigrationWizard(0)
# only show after wizards and connect dialogs have completed # only show after wizards and connect dialogs have completed
if not BMConfigParser().getboolean('bitmessagesettings', 'startintray'): if not BMConfigParser().getboolean('bitmessagesettings', 'startintray'):
myapp.show() myapp.show()

View File

@ -1,26 +1,58 @@
from PyQt4 import QtCore, QtGui # pylint: disable=too-many-instance-attributes,attribute-defined-outside-init
"""
account.py
==========
import queues Account related functions.
"""
from __future__ import absolute_import
import inspect
import re import re
import sys import sys
import inspect
from helper_sql import *
from helper_ackPayload import genAckPayload
from addresses import decodeAddress
from bmconfigparser import BMConfigParser
from foldertree import AccountMixin
from pyelliptic.openssl import OpenSSL
from utils import str_broadcast_subscribers
import time import time
from PyQt4 import QtGui
import queues
from addresses import decodeAddress
from bmconfigparser import BMConfigParser
from helper_ackPayload import genAckPayload
from helper_sql import sqlQuery, sqlExecute
from .foldertree import AccountMixin
from .utils import str_broadcast_subscribers
def getSortedAccounts(): def getSortedAccounts():
"""Get a sorted list of configSections"""
configSections = BMConfigParser().addresses() configSections = BMConfigParser().addresses()
configSections.sort(cmp = configSections.sort(
lambda x,y: cmp(unicode(BMConfigParser().get(x, 'label'), 'utf-8').lower(), unicode(BMConfigParser().get(y, 'label'), 'utf-8').lower()) cmp=lambda x, y: cmp(
) unicode(
BMConfigParser().get(
x,
'label'),
'utf-8').lower(),
unicode(
BMConfigParser().get(
y,
'label'),
'utf-8').lower()))
return configSections return configSections
def getSortedSubscriptions(count=False): def getSortedSubscriptions(count=False):
"""
Actually return a grouped dictionary rather than a sorted list
:param count: Whether to count messages for each fromaddress in the inbox
:type count: bool, default False
:retuns: dict keys are addresses, values are dicts containing settings
:rtype: dict, default {}
"""
queryreturn = sqlQuery('SELECT label, address, enabled FROM subscriptions ORDER BY label COLLATE NOCASE ASC') queryreturn = sqlQuery('SELECT label, address, enabled FROM subscriptions ORDER BY label COLLATE NOCASE ASC')
ret = {} ret = {}
for row in queryreturn: for row in queryreturn:
@ -37,7 +69,7 @@ def getSortedSubscriptions(count = False):
GROUP BY inbox.fromaddress, folder''', str_broadcast_subscribers) GROUP BY inbox.fromaddress, folder''', str_broadcast_subscribers)
for row in queryreturn: for row in queryreturn:
address, folder, cnt = row address, folder, cnt = row
if not folder in ret[address]: if folder not in ret[address]:
ret[address][folder] = { ret[address][folder] = {
'label': ret[address]['inbox']['label'], 'label': ret[address]['inbox']['label'],
'enabled': ret[address]['inbox']['enabled'] 'enabled': ret[address]['inbox']['enabled']
@ -45,9 +77,11 @@ def getSortedSubscriptions(count = False):
ret[address][folder]['count'] = cnt ret[address][folder]['count'] = cnt
return ret return ret
def accountClass(address): def accountClass(address):
"""Return a BMAccount for the address"""
if not BMConfigParser().has_section(address): if not BMConfigParser().has_section(address):
# FIXME: This BROADCAST section makes no sense # .. todo:: This BROADCAST section makes no sense
if address == str_broadcast_subscribers: if address == str_broadcast_subscribers:
subscription = BroadcastAccount(address) subscription = BroadcastAccount(address)
if subscription.type != AccountMixin.BROADCAST: if subscription.type != AccountMixin.BROADCAST:
@ -60,8 +94,7 @@ def accountClass(address):
return subscription return subscription
try: try:
gateway = BMConfigParser().get(address, "gateway") gateway = BMConfigParser().get(address, "gateway")
for name, cls in inspect.getmembers(sys.modules[__name__], inspect.isclass): for _, cls in inspect.getmembers(sys.modules[__name__], inspect.isclass):
# obj = g(address)
if issubclass(cls, GatewayAccount) and cls.gatewayName == gateway: if issubclass(cls, GatewayAccount) and cls.gatewayName == gateway:
return cls(address) return cls(address)
# general gateway # general gateway
@ -71,11 +104,14 @@ def accountClass(address):
# no gateway # no gateway
return BMAccount(address) return BMAccount(address)
class AccountColor(AccountMixin):
def __init__(self, address, type = None): class AccountColor(AccountMixin): # pylint: disable=too-few-public-methods
"""Set the type of account"""
def __init__(self, address, address_type=None):
self.isEnabled = True self.isEnabled = True
self.address = address self.address = address
if type is None: if address_type is None:
if address is None: if address is None:
self.type = AccountMixin.ALL self.type = AccountMixin.ALL
elif BMConfigParser().safeGetBoolean(self.address, 'mailinglist'): elif BMConfigParser().safeGetBoolean(self.address, 'mailinglist'):
@ -88,10 +124,12 @@ class AccountColor(AccountMixin):
else: else:
self.type = AccountMixin.NORMAL self.type = AccountMixin.NORMAL
else: else:
self.type = type self.type = address_type
class BMAccount(object): class BMAccount(object):
"""Encapsulate a Bitmessage account"""
def __init__(self, address=None): def __init__(self, address=None):
self.address = address self.address = address
self.type = AccountMixin.NORMAL self.type = AccountMixin.NORMAL
@ -109,6 +147,7 @@ class BMAccount(object):
self.type = AccountMixin.SUBSCRIPTION self.type = AccountMixin.SUBSCRIPTION
def getLabel(self, address=None): def getLabel(self, address=None):
"""Get a label for this bitmessage account"""
if address is None: if address is None:
address = self.address address = self.address
label = address label = address
@ -128,6 +167,8 @@ class BMAccount(object):
return label return label
def parseMessage(self, toAddress, fromAddress, subject, message): def parseMessage(self, toAddress, fromAddress, subject, message):
"""Set metadata and address labels on self"""
self.toAddress = toAddress self.toAddress = toAddress
self.fromAddress = fromAddress self.fromAddress = fromAddress
if isinstance(subject, unicode): if isinstance(subject, unicode):
@ -140,7 +181,9 @@ class BMAccount(object):
class NoAccount(BMAccount): class NoAccount(BMAccount):
def __init__(self, address = None): """Override the __init__ method on a BMAccount"""
def __init__(self, address=None): # pylint: disable=super-init-not-called
self.address = address self.address = address
self.type = AccountMixin.NORMAL self.type = AccountMixin.NORMAL
@ -151,25 +194,32 @@ class NoAccount(BMAccount):
class SubscriptionAccount(BMAccount): class SubscriptionAccount(BMAccount):
"""Encapsulate a subscription account"""
pass pass
class BroadcastAccount(BMAccount): class BroadcastAccount(BMAccount):
"""Encapsulate a broadcast account"""
pass pass
class GatewayAccount(BMAccount): class GatewayAccount(BMAccount):
"""Encapsulate a gateway account"""
gatewayName = None gatewayName = None
ALL_OK = 0 ALL_OK = 0
REGISTRATION_DENIED = 1 REGISTRATION_DENIED = 1
def __init__(self, address): def __init__(self, address):
super(GatewayAccount, self).__init__(address) super(GatewayAccount, self).__init__(address)
def send(self): def send(self):
"""Override the send method for gateway accounts"""
# pylint: disable=unused-variable
status, addressVersionNumber, streamNumber, ripe = decodeAddress(self.toAddress) status, addressVersionNumber, streamNumber, ripe = decodeAddress(self.toAddress)
stealthLevel = BMConfigParser().safeGetInt('bitmessagesettings', 'ackstealthlevel') stealthLevel = BMConfigParser().safeGetInt('bitmessagesettings', 'ackstealthlevel')
ackdata = genAckPayload(streamNumber, stealthLevel) ackdata = genAckPayload(streamNumber, stealthLevel)
t = ()
sqlExecute( sqlExecute(
'''INSERT INTO sent VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)''', '''INSERT INTO sent VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)''',
'', '',
@ -186,33 +236,37 @@ class GatewayAccount(BMAccount):
0, # retryNumber 0, # retryNumber
'sent', # folder 'sent', # folder
2, # encodingtype 2, # encodingtype
min(BMConfigParser().getint('bitmessagesettings', 'ttl'), 86400 * 2) # not necessary to have a TTL higher than 2 days # not necessary to have a TTL higher than 2 days
min(BMConfigParser().getint('bitmessagesettings', 'ttl'), 86400 * 2)
) )
queues.workerQueue.put(('sendmessage', self.toAddress)) queues.workerQueue.put(('sendmessage', self.toAddress))
def parseMessage(self, toAddress, fromAddress, subject, message):
super(GatewayAccount, self).parseMessage(toAddress, fromAddress, subject, message)
class MailchuckAccount(GatewayAccount): class MailchuckAccount(GatewayAccount):
"""Encapsulate a particular kind of gateway account"""
# set "gateway" in keys.dat to this # set "gateway" in keys.dat to this
gatewayName = "mailchuck" gatewayName = "mailchuck"
registrationAddress = "BM-2cVYYrhaY5Gbi3KqrX9Eae2NRNrkfrhCSA" registrationAddress = "BM-2cVYYrhaY5Gbi3KqrX9Eae2NRNrkfrhCSA"
unregistrationAddress = "BM-2cVMAHTRjZHCTPMue75XBK5Tco175DtJ9J" unregistrationAddress = "BM-2cVMAHTRjZHCTPMue75XBK5Tco175DtJ9J"
relayAddress = "BM-2cWim8aZwUNqxzjMxstnUMtVEUQJeezstf" relayAddress = "BM-2cWim8aZwUNqxzjMxstnUMtVEUQJeezstf"
regExpIncoming = re.compile("(.*)MAILCHUCK-FROM::(\S+) \| (.*)") regExpIncoming = re.compile(r"(.*)MAILCHUCK-FROM::(\S+) \| (.*)")
regExpOutgoing = re.compile("(\S+) (.*)") regExpOutgoing = re.compile(r"(\S+) (.*)")
def __init__(self, address): def __init__(self, address):
super(MailchuckAccount, self).__init__(address) super(MailchuckAccount, self).__init__(address)
self.feedback = self.ALL_OK self.feedback = self.ALL_OK
def createMessage(self, toAddress, fromAddress, subject, message): def createMessage(self, toAddress, fromAddress, subject, message):
"""createMessage specific to a MailchuckAccount"""
self.subject = toAddress + " " + subject self.subject = toAddress + " " + subject
self.toAddress = self.relayAddress self.toAddress = self.relayAddress
self.fromAddress = fromAddress self.fromAddress = fromAddress
self.message = message self.message = message
def register(self, email): def register(self, email):
"""register specific to a MailchuckAccount"""
self.toAddress = self.registrationAddress self.toAddress = self.registrationAddress
self.subject = email self.subject = email
self.message = "" self.message = ""
@ -220,6 +274,7 @@ class MailchuckAccount(GatewayAccount):
self.send() self.send()
def unregister(self): def unregister(self):
"""unregister specific to a MailchuckAccount"""
self.toAddress = self.unregistrationAddress self.toAddress = self.unregistrationAddress
self.subject = "" self.subject = ""
self.message = "" self.message = ""
@ -227,6 +282,7 @@ class MailchuckAccount(GatewayAccount):
self.send() self.send()
def status(self): def status(self):
"""status specific to a MailchuckAccount"""
self.toAddress = self.registrationAddress self.toAddress = self.registrationAddress
self.subject = "status" self.subject = "status"
self.message = "" self.message = ""
@ -234,9 +290,13 @@ class MailchuckAccount(GatewayAccount):
self.send() self.send()
def settings(self): def settings(self):
"""settings specific to a MailchuckAccount"""
self.toAddress = self.registrationAddress self.toAddress = self.registrationAddress
self.subject = "config" self.subject = "config"
self.message = QtGui.QApplication.translate("Mailchuck", """# You can use this to configure your email gateway account self.message = QtGui.QApplication.translate(
"Mailchuck",
"""# You can use this to configure your email gateway account
# Uncomment the setting you want to use # Uncomment the setting you want to use
# Here are the options: # Here are the options:
# #
@ -279,10 +339,12 @@ class MailchuckAccount(GatewayAccount):
self.fromAddress = self.address self.fromAddress = self.address
def parseMessage(self, toAddress, fromAddress, subject, message): def parseMessage(self, toAddress, fromAddress, subject, message):
"""parseMessage specific to a MailchuckAccount"""
super(MailchuckAccount, self).parseMessage(toAddress, fromAddress, subject, message) super(MailchuckAccount, self).parseMessage(toAddress, fromAddress, subject, message)
if fromAddress == self.relayAddress: if fromAddress == self.relayAddress:
matches = self.regExpIncoming.search(subject) matches = self.regExpIncoming.search(subject)
if not matches is None: if matches is not None:
self.subject = "" self.subject = ""
if not matches.group(1) is None: if not matches.group(1) is None:
self.subject += matches.group(1) self.subject += matches.group(1)
@ -293,7 +355,7 @@ class MailchuckAccount(GatewayAccount):
self.fromAddress = matches.group(2) self.fromAddress = matches.group(2)
if toAddress == self.relayAddress: if toAddress == self.relayAddress:
matches = self.regExpOutgoing.search(subject) matches = self.regExpOutgoing.search(subject)
if not matches is None: if matches is not None:
if not matches.group(2) is None: if not matches.group(2) is None:
self.subject = matches.group(2) self.subject = matches.group(2)
if not matches.group(1) is None: if not matches.group(1) is None:

View File

@ -1,15 +1,23 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
# pylint: disable=too-many-instance-attributes,too-many-locals,too-many-statements,attribute-defined-outside-init
"""
Form implementation generated from reading ui file 'settings.ui'
# Form implementation generated from reading ui file 'settings.ui' Created: Thu Dec 25 23:21:20 2014
# by: PyQt4 UI code generator 4.10.3
# Created: Thu Dec 25 23:21:20 2014
# by: PyQt4 UI code generator 4.10.3 WARNING! All changes made in this file will be lost!
# """
# WARNING! All changes made in this file will be lost!
from __future__ import absolute_import
from sys import platform
from PyQt4 import QtCore, QtGui from PyQt4 import QtCore, QtGui
from languagebox import LanguageBox
from sys import platform from . import bitmessage_icons_rc # pylint: disable=unused-import
from .languagebox import LanguageBox
try: try:
_fromUtf8 = QtCore.QString.fromUtf8 _fromUtf8 = QtCore.QString.fromUtf8
@ -19,14 +27,20 @@ except AttributeError:
try: try:
_encoding = QtGui.QApplication.UnicodeUTF8 _encoding = QtGui.QApplication.UnicodeUTF8
def _translate(context, text, disambig): def _translate(context, text, disambig):
return QtGui.QApplication.translate(context, text, disambig, _encoding) return QtGui.QApplication.translate(context, text, disambig, _encoding)
except AttributeError: except AttributeError:
def _translate(context, text, disambig): def _translate(context, text, disambig):
return QtGui.QApplication.translate(context, text, disambig) return QtGui.QApplication.translate(context, text, disambig)
class Ui_settingsDialog(object): class Ui_settingsDialog(object):
"""Encapsulate a UI settings dialog object"""
def setupUi(self, settingsDialog): def setupUi(self, settingsDialog):
"""Set up the UI"""
settingsDialog.setObjectName(_fromUtf8("settingsDialog")) settingsDialog.setObjectName(_fromUtf8("settingsDialog"))
settingsDialog.resize(521, 413) settingsDialog.resize(521, 413)
self.gridLayout = QtGui.QGridLayout(settingsDialog) self.gridLayout = QtGui.QGridLayout(settingsDialog)
@ -64,7 +78,8 @@ class Ui_settingsDialog(object):
self.formLayout.setWidget(1, QtGui.QFormLayout.SpanningRole, self.groupBoxTray) self.formLayout.setWidget(1, QtGui.QFormLayout.SpanningRole, self.groupBoxTray)
self.checkBoxHideTrayConnectionNotifications = QtGui.QCheckBox(self.tabUserInterface) self.checkBoxHideTrayConnectionNotifications = QtGui.QCheckBox(self.tabUserInterface)
self.checkBoxHideTrayConnectionNotifications.setChecked(False) self.checkBoxHideTrayConnectionNotifications.setChecked(False)
self.checkBoxHideTrayConnectionNotifications.setObjectName(_fromUtf8("checkBoxHideTrayConnectionNotifications")) self.checkBoxHideTrayConnectionNotifications.setObjectName(
_fromUtf8("checkBoxHideTrayConnectionNotifications"))
self.formLayout.setWidget(2, QtGui.QFormLayout.LabelRole, self.checkBoxHideTrayConnectionNotifications) self.formLayout.setWidget(2, QtGui.QFormLayout.LabelRole, self.checkBoxHideTrayConnectionNotifications)
self.checkBoxShowTrayNotifications = QtGui.QCheckBox(self.tabUserInterface) self.checkBoxShowTrayNotifications = QtGui.QCheckBox(self.tabUserInterface)
self.checkBoxShowTrayNotifications.setObjectName(_fromUtf8("checkBoxShowTrayNotifications")) self.checkBoxShowTrayNotifications.setObjectName(_fromUtf8("checkBoxShowTrayNotifications"))
@ -96,7 +111,7 @@ class Ui_settingsDialog(object):
self.formLayout_2.setObjectName(_fromUtf8("formLayout_2")) self.formLayout_2.setObjectName(_fromUtf8("formLayout_2"))
self.languageComboBox = LanguageBox(self.groupBox) self.languageComboBox = LanguageBox(self.groupBox)
self.languageComboBox.setMinimumSize(QtCore.QSize(100, 0)) self.languageComboBox.setMinimumSize(QtCore.QSize(100, 0))
self.languageComboBox.setObjectName(_fromUtf8("languageComboBox")) self.languageComboBox.setObjectName(_fromUtf8("languageComboBox")) # pylint: disable=not-callable
self.formLayout_2.setWidget(0, QtGui.QFormLayout.LabelRole, self.languageComboBox) self.formLayout_2.setWidget(0, QtGui.QFormLayout.LabelRole, self.languageComboBox)
self.formLayout.setWidget(9, QtGui.QFormLayout.FieldRole, self.groupBox) self.formLayout.setWidget(9, QtGui.QFormLayout.FieldRole, self.groupBox)
self.tabWidgetSettings.addTab(self.tabUserInterface, _fromUtf8("")) self.tabWidgetSettings.addTab(self.tabUserInterface, _fromUtf8(""))
@ -108,8 +123,6 @@ class Ui_settingsDialog(object):
self.groupBox1.setObjectName(_fromUtf8("groupBox1")) self.groupBox1.setObjectName(_fromUtf8("groupBox1"))
self.gridLayout_3 = QtGui.QGridLayout(self.groupBox1) self.gridLayout_3 = QtGui.QGridLayout(self.groupBox1)
self.gridLayout_3.setObjectName(_fromUtf8("gridLayout_3")) self.gridLayout_3.setObjectName(_fromUtf8("gridLayout_3"))
#spacerItem = QtGui.QSpacerItem(125, 20, QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Minimum)
#self.gridLayout_3.addItem(spacerItem, 0, 0, 1, 1)
self.label = QtGui.QLabel(self.groupBox1) self.label = QtGui.QLabel(self.groupBox1)
self.label.setObjectName(_fromUtf8("label")) self.label.setObjectName(_fromUtf8("label"))
self.gridLayout_3.addWidget(self.label, 0, 0, 1, 1, QtCore.Qt.AlignRight) self.gridLayout_3.addWidget(self.label, 0, 0, 1, 1, QtCore.Qt.AlignRight)
@ -165,7 +178,8 @@ class Ui_settingsDialog(object):
self.lineEditMaxOutboundConnections.setSizePolicy(sizePolicy) self.lineEditMaxOutboundConnections.setSizePolicy(sizePolicy)
self.lineEditMaxOutboundConnections.setMaximumSize(QtCore.QSize(60, 16777215)) self.lineEditMaxOutboundConnections.setMaximumSize(QtCore.QSize(60, 16777215))
self.lineEditMaxOutboundConnections.setObjectName(_fromUtf8("lineEditMaxOutboundConnections")) self.lineEditMaxOutboundConnections.setObjectName(_fromUtf8("lineEditMaxOutboundConnections"))
self.lineEditMaxOutboundConnections.setValidator(QtGui.QIntValidator(0, 8, self.lineEditMaxOutboundConnections)) self.lineEditMaxOutboundConnections.setValidator(
QtGui.QIntValidator(0, 8, self.lineEditMaxOutboundConnections))
self.gridLayout_9.addWidget(self.lineEditMaxOutboundConnections, 2, 2, 1, 1) self.gridLayout_9.addWidget(self.lineEditMaxOutboundConnections, 2, 2, 1, 1)
self.gridLayout_4.addWidget(self.groupBox_3, 2, 0, 1, 1) self.gridLayout_4.addWidget(self.groupBox_3, 2, 0, 1, 1)
self.groupBox_2 = QtGui.QGroupBox(self.tabNetworkSettings) self.groupBox_2 = QtGui.QGroupBox(self.tabNetworkSettings)
@ -207,7 +221,8 @@ class Ui_settingsDialog(object):
self.gridLayout_2.addWidget(self.label_6, 2, 4, 1, 1) self.gridLayout_2.addWidget(self.label_6, 2, 4, 1, 1)
self.lineEditSocksPassword = QtGui.QLineEdit(self.groupBox_2) self.lineEditSocksPassword = QtGui.QLineEdit(self.groupBox_2)
self.lineEditSocksPassword.setEnabled(False) self.lineEditSocksPassword.setEnabled(False)
self.lineEditSocksPassword.setInputMethodHints(QtCore.Qt.ImhHiddenText|QtCore.Qt.ImhNoAutoUppercase|QtCore.Qt.ImhNoPredictiveText) self.lineEditSocksPassword.setInputMethodHints(
QtCore.Qt.ImhHiddenText | QtCore.Qt.ImhNoAutoUppercase | QtCore.Qt.ImhNoPredictiveText)
self.lineEditSocksPassword.setEchoMode(QtGui.QLineEdit.Password) self.lineEditSocksPassword.setEchoMode(QtGui.QLineEdit.Password)
self.lineEditSocksPassword.setObjectName(_fromUtf8("lineEditSocksPassword")) self.lineEditSocksPassword.setObjectName(_fromUtf8("lineEditSocksPassword"))
self.gridLayout_2.addWidget(self.lineEditSocksPassword, 2, 5, 1, 1) self.gridLayout_2.addWidget(self.lineEditSocksPassword, 2, 5, 1, 1)
@ -215,7 +230,7 @@ class Ui_settingsDialog(object):
self.checkBoxSocksListen.setObjectName(_fromUtf8("checkBoxSocksListen")) self.checkBoxSocksListen.setObjectName(_fromUtf8("checkBoxSocksListen"))
self.gridLayout_2.addWidget(self.checkBoxSocksListen, 3, 1, 1, 4) self.gridLayout_2.addWidget(self.checkBoxSocksListen, 3, 1, 1, 4)
self.comboBoxProxyType = QtGui.QComboBox(self.groupBox_2) self.comboBoxProxyType = QtGui.QComboBox(self.groupBox_2)
self.comboBoxProxyType.setObjectName(_fromUtf8("comboBoxProxyType")) self.comboBoxProxyType.setObjectName(_fromUtf8("comboBoxProxyType")) # pylint: disable=not-callable
self.comboBoxProxyType.addItem(_fromUtf8("")) self.comboBoxProxyType.addItem(_fromUtf8(""))
self.comboBoxProxyType.addItem(_fromUtf8("")) self.comboBoxProxyType.addItem(_fromUtf8(""))
self.comboBoxProxyType.addItem(_fromUtf8("")) self.comboBoxProxyType.addItem(_fromUtf8(""))
@ -310,7 +325,8 @@ class Ui_settingsDialog(object):
sizePolicy.setHeightForWidth(self.lineEditMaxAcceptableSmallMessageDifficulty.sizePolicy().hasHeightForWidth()) sizePolicy.setHeightForWidth(self.lineEditMaxAcceptableSmallMessageDifficulty.sizePolicy().hasHeightForWidth())
self.lineEditMaxAcceptableSmallMessageDifficulty.setSizePolicy(sizePolicy) self.lineEditMaxAcceptableSmallMessageDifficulty.setSizePolicy(sizePolicy)
self.lineEditMaxAcceptableSmallMessageDifficulty.setMaximumSize(QtCore.QSize(70, 16777215)) self.lineEditMaxAcceptableSmallMessageDifficulty.setMaximumSize(QtCore.QSize(70, 16777215))
self.lineEditMaxAcceptableSmallMessageDifficulty.setObjectName(_fromUtf8("lineEditMaxAcceptableSmallMessageDifficulty")) self.lineEditMaxAcceptableSmallMessageDifficulty.setObjectName(
_fromUtf8("lineEditMaxAcceptableSmallMessageDifficulty"))
self.gridLayout_7.addWidget(self.lineEditMaxAcceptableSmallMessageDifficulty, 2, 2, 1, 1) self.gridLayout_7.addWidget(self.lineEditMaxAcceptableSmallMessageDifficulty, 2, 2, 1, 1)
spacerItem8 = QtGui.QSpacerItem(20, 147, QtGui.QSizePolicy.Minimum, QtGui.QSizePolicy.Expanding) spacerItem8 = QtGui.QSpacerItem(20, 147, QtGui.QSizePolicy.Minimum, QtGui.QSizePolicy.Expanding)
self.gridLayout_7.addItem(spacerItem8, 3, 1, 1, 1) self.gridLayout_7.addItem(spacerItem8, 3, 1, 1, 1)
@ -362,11 +378,13 @@ class Ui_settingsDialog(object):
spacerItem13 = QtGui.QSpacerItem(40, 20, QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Minimum) spacerItem13 = QtGui.QSpacerItem(40, 20, QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Minimum)
self.gridLayout_8.addItem(spacerItem13, 5, 0, 1, 1) self.gridLayout_8.addItem(spacerItem13, 5, 0, 1, 1)
self.labelNamecoinPassword = QtGui.QLabel(self.tabNamecoin) self.labelNamecoinPassword = QtGui.QLabel(self.tabNamecoin)
self.labelNamecoinPassword.setAlignment(QtCore.Qt.AlignRight|QtCore.Qt.AlignTrailing|QtCore.Qt.AlignVCenter) self.labelNamecoinPassword.setAlignment(
QtCore.Qt.AlignRight | QtCore.Qt.AlignTrailing | QtCore.Qt.AlignVCenter)
self.labelNamecoinPassword.setObjectName(_fromUtf8("labelNamecoinPassword")) self.labelNamecoinPassword.setObjectName(_fromUtf8("labelNamecoinPassword"))
self.gridLayout_8.addWidget(self.labelNamecoinPassword, 5, 1, 1, 1) self.gridLayout_8.addWidget(self.labelNamecoinPassword, 5, 1, 1, 1)
self.lineEditNamecoinPassword = QtGui.QLineEdit(self.tabNamecoin) self.lineEditNamecoinPassword = QtGui.QLineEdit(self.tabNamecoin)
self.lineEditNamecoinPassword.setInputMethodHints(QtCore.Qt.ImhHiddenText|QtCore.Qt.ImhNoAutoUppercase|QtCore.Qt.ImhNoPredictiveText) self.lineEditNamecoinPassword.setInputMethodHints(
QtCore.Qt.ImhHiddenText | QtCore.Qt.ImhNoAutoUppercase | QtCore.Qt.ImhNoPredictiveText)
self.lineEditNamecoinPassword.setEchoMode(QtGui.QLineEdit.Password) self.lineEditNamecoinPassword.setEchoMode(QtGui.QLineEdit.Password)
self.lineEditNamecoinPassword.setObjectName(_fromUtf8("lineEditNamecoinPassword")) self.lineEditNamecoinPassword.setObjectName(_fromUtf8("lineEditNamecoinPassword"))
self.gridLayout_8.addWidget(self.lineEditNamecoinPassword, 5, 2, 1, 1) self.gridLayout_8.addWidget(self.lineEditNamecoinPassword, 5, 2, 1, 1)
@ -431,10 +449,20 @@ class Ui_settingsDialog(object):
self.retranslateUi(settingsDialog) self.retranslateUi(settingsDialog)
self.tabWidgetSettings.setCurrentIndex(0) self.tabWidgetSettings.setCurrentIndex(0)
QtCore.QObject.connect(self.buttonBox, QtCore.SIGNAL(_fromUtf8("accepted()")), settingsDialog.accept) QtCore.QObject.connect( # pylint: disable=no-member
QtCore.QObject.connect(self.buttonBox, QtCore.SIGNAL(_fromUtf8("rejected()")), settingsDialog.reject) self.buttonBox, QtCore.SIGNAL(_fromUtf8("accepted()")), settingsDialog.accept)
QtCore.QObject.connect(self.checkBoxAuthentication, QtCore.SIGNAL(_fromUtf8("toggled(bool)")), self.lineEditSocksUsername.setEnabled) QtCore.QObject.connect( # pylint: disable=no-member
QtCore.QObject.connect(self.checkBoxAuthentication, QtCore.SIGNAL(_fromUtf8("toggled(bool)")), self.lineEditSocksPassword.setEnabled) self.buttonBox, QtCore.SIGNAL(_fromUtf8("rejected()")), settingsDialog.reject)
QtCore.QObject.connect( # pylint: disable=no-member
self.checkBoxAuthentication,
QtCore.SIGNAL(
_fromUtf8("toggled(bool)")),
self.lineEditSocksUsername.setEnabled)
QtCore.QObject.connect( # pylint: disable=no-member
self.checkBoxAuthentication,
QtCore.SIGNAL(
_fromUtf8("toggled(bool)")),
self.lineEditSocksPassword.setEnabled)
QtCore.QMetaObject.connectSlotsByName(settingsDialog) QtCore.QMetaObject.connectSlotsByName(settingsDialog)
settingsDialog.setTabOrder(self.tabWidgetSettings, self.checkBoxStartOnLogon) settingsDialog.setTabOrder(self.tabWidgetSettings, self.checkBoxStartOnLogon)
settingsDialog.setTabOrder(self.checkBoxStartOnLogon, self.checkBoxStartInTray) settingsDialog.setTabOrder(self.checkBoxStartOnLogon, self.checkBoxStartInTray)
@ -450,22 +478,47 @@ class Ui_settingsDialog(object):
settingsDialog.setTabOrder(self.checkBoxSocksListen, self.buttonBox) settingsDialog.setTabOrder(self.checkBoxSocksListen, self.buttonBox)
def retranslateUi(self, settingsDialog): def retranslateUi(self, settingsDialog):
"""Re-translate the UI into the supported languages"""
settingsDialog.setWindowTitle(_translate("settingsDialog", "Settings", None)) settingsDialog.setWindowTitle(_translate("settingsDialog", "Settings", None))
self.checkBoxStartOnLogon.setText(_translate("settingsDialog", "Start Bitmessage on user login", None)) self.checkBoxStartOnLogon.setText(_translate("settingsDialog", "Start Bitmessage on user login", None))
self.groupBoxTray.setTitle(_translate("settingsDialog", "Tray", None)) self.groupBoxTray.setTitle(_translate("settingsDialog", "Tray", None))
self.checkBoxStartInTray.setText(_translate("settingsDialog", "Start Bitmessage in the tray (don\'t show main window)", None)) self.checkBoxStartInTray.setText(
_translate(
"settingsDialog",
"Start Bitmessage in the tray (don\'t show main window)",
None))
self.checkBoxMinimizeToTray.setText(_translate("settingsDialog", "Minimize to tray", None)) self.checkBoxMinimizeToTray.setText(_translate("settingsDialog", "Minimize to tray", None))
self.checkBoxTrayOnClose.setText(_translate("settingsDialog", "Close to tray", None)) self.checkBoxTrayOnClose.setText(_translate("settingsDialog", "Close to tray", None))
self.checkBoxHideTrayConnectionNotifications.setText(_translate("settingsDialog", "Hide connection notifications", None)) self.checkBoxHideTrayConnectionNotifications.setText(
self.checkBoxShowTrayNotifications.setText(_translate("settingsDialog", "Show notification when message received", None)) _translate("settingsDialog", "Hide connection notifications", None))
self.checkBoxShowTrayNotifications.setText(
_translate(
"settingsDialog",
"Show notification when message received",
None))
self.checkBoxPortableMode.setText(_translate("settingsDialog", "Run in Portable Mode", None)) self.checkBoxPortableMode.setText(_translate("settingsDialog", "Run in Portable Mode", None))
self.PortableModeDescription.setText(_translate("settingsDialog", "In Portable Mode, messages and config files are stored in the same directory as the program rather than the normal application-data folder. This makes it convenient to run Bitmessage from a USB thumb drive.", None)) self.PortableModeDescription.setText(
self.checkBoxWillinglySendToMobile.setText(_translate("settingsDialog", "Willingly include unencrypted destination address when sending to a mobile device", None)) _translate(
"settingsDialog",
"In Portable Mode, messages and config files are stored in the same directory as the"
" program rather than the normal application-data folder. This makes it convenient to"
" run Bitmessage from a USB thumb drive.",
None))
self.checkBoxWillinglySendToMobile.setText(
_translate(
"settingsDialog",
"Willingly include unencrypted destination address when sending to a mobile device",
None))
self.checkBoxUseIdenticons.setText(_translate("settingsDialog", "Use Identicons", None)) self.checkBoxUseIdenticons.setText(_translate("settingsDialog", "Use Identicons", None))
self.checkBoxReplyBelow.setText(_translate("settingsDialog", "Reply below Quote", None)) self.checkBoxReplyBelow.setText(_translate("settingsDialog", "Reply below Quote", None))
self.groupBox.setTitle(_translate("settingsDialog", "Interface Language", None)) self.groupBox.setTitle(_translate("settingsDialog", "Interface Language", None))
self.languageComboBox.setItemText(0, _translate("settingsDialog", "System Settings", "system")) self.languageComboBox.setItemText(0, _translate("settingsDialog", "System Settings", "system"))
self.tabWidgetSettings.setTabText(self.tabWidgetSettings.indexOf(self.tabUserInterface), _translate("settingsDialog", "User Interface", None)) self.tabWidgetSettings.setTabText(
self.tabWidgetSettings.indexOf(
self.tabUserInterface),
_translate(
"settingsDialog", "User Interface", None))
self.groupBox1.setTitle(_translate("settingsDialog", "Listening port", None)) self.groupBox1.setTitle(_translate("settingsDialog", "Listening port", None))
self.label.setText(_translate("settingsDialog", "Listen for connections on port:", None)) self.label.setText(_translate("settingsDialog", "Listen for connections on port:", None))
self.labelUPnP.setText(_translate("settingsDialog", "UPnP:", None)) self.labelUPnP.setText(_translate("settingsDialog", "UPnP:", None))
@ -480,23 +533,70 @@ class Ui_settingsDialog(object):
self.checkBoxAuthentication.setText(_translate("settingsDialog", "Authentication", None)) self.checkBoxAuthentication.setText(_translate("settingsDialog", "Authentication", None))
self.label_5.setText(_translate("settingsDialog", "Username:", None)) self.label_5.setText(_translate("settingsDialog", "Username:", None))
self.label_6.setText(_translate("settingsDialog", "Pass:", None)) self.label_6.setText(_translate("settingsDialog", "Pass:", None))
self.checkBoxSocksListen.setText(_translate("settingsDialog", "Listen for incoming connections when using proxy", None)) self.checkBoxSocksListen.setText(
_translate(
"settingsDialog",
"Listen for incoming connections when using proxy",
None))
self.comboBoxProxyType.setItemText(0, _translate("settingsDialog", "none", None)) self.comboBoxProxyType.setItemText(0, _translate("settingsDialog", "none", None))
self.comboBoxProxyType.setItemText(1, _translate("settingsDialog", "SOCKS4a", None)) self.comboBoxProxyType.setItemText(1, _translate("settingsDialog", "SOCKS4a", None))
self.comboBoxProxyType.setItemText(2, _translate("settingsDialog", "SOCKS5", None)) self.comboBoxProxyType.setItemText(2, _translate("settingsDialog", "SOCKS5", None))
self.tabWidgetSettings.setTabText(self.tabWidgetSettings.indexOf(self.tabNetworkSettings), _translate("settingsDialog", "Network Settings", None)) self.tabWidgetSettings.setTabText(
self.tabWidgetSettings.indexOf(
self.tabNetworkSettings),
_translate(
"settingsDialog", "Network Settings", None))
self.label_9.setText(_translate("settingsDialog", "Total difficulty:", None)) self.label_9.setText(_translate("settingsDialog", "Total difficulty:", None))
self.label_10.setText(_translate("settingsDialog", "The \'Total difficulty\' affects the absolute amount of work the sender must complete. Doubling this value doubles the amount of work.", None)) self.label_10.setText(
_translate(
"settingsDialog",
"The \'Total difficulty\' affects the absolute amount of work the sender must complete."
" Doubling this value doubles the amount of work.",
None))
self.label_11.setText(_translate("settingsDialog", "Small message difficulty:", None)) self.label_11.setText(_translate("settingsDialog", "Small message difficulty:", None))
self.label_8.setText(_translate("settingsDialog", "When someone sends you a message, their computer must first complete some work. The difficulty of this work, by default, is 1. You may raise this default for new addresses you create by changing the values here. Any new addresses you create will require senders to meet the higher difficulty. There is one exception: if you add a friend or acquaintance to your address book, Bitmessage will automatically notify them when you next send a message that they need only complete the minimum amount of work: difficulty 1. ", None)) self.label_8.setText(_translate(
self.label_12.setText(_translate("settingsDialog", "The \'Small message difficulty\' mostly only affects the difficulty of sending small messages. Doubling this value makes it almost twice as difficult to send a small message but doesn\'t really affect large messages.", None)) "settingsDialog",
self.tabWidgetSettings.setTabText(self.tabWidgetSettings.indexOf(self.tabDemandedDifficulty), _translate("settingsDialog", "Demanded difficulty", None)) "When someone sends you a message, their computer must first complete some work. The difficulty of this"
self.label_15.setText(_translate("settingsDialog", "Here you may set the maximum amount of work you are willing to do to send a message to another person. Setting these values to 0 means that any value is acceptable.", None)) " work, by default, is 1. You may raise this default for new addresses you create by changing the values"
" here. Any new addresses you create will require senders to meet the higher difficulty. There is one"
" exception: if you add a friend or acquaintance to your address book, Bitmessage will automatically"
" notify them when you next send a message that they need only complete the minimum amount of"
" work: difficulty 1. ",
None))
self.label_12.setText(
_translate(
"settingsDialog",
"The \'Small message difficulty\' mostly only affects the difficulty of sending small messages."
" Doubling this value makes it almost twice as difficult to send a small message but doesn\'t really"
" affect large messages.",
None))
self.tabWidgetSettings.setTabText(
self.tabWidgetSettings.indexOf(
self.tabDemandedDifficulty),
_translate(
"settingsDialog", "Demanded difficulty", None))
self.label_15.setText(
_translate(
"settingsDialog",
"Here you may set the maximum amount of work you are willing to do to send a message to another"
" person. Setting these values to 0 means that any value is acceptable.",
None))
self.label_13.setText(_translate("settingsDialog", "Maximum acceptable total difficulty:", None)) self.label_13.setText(_translate("settingsDialog", "Maximum acceptable total difficulty:", None))
self.label_14.setText(_translate("settingsDialog", "Maximum acceptable small message difficulty:", None)) self.label_14.setText(_translate("settingsDialog", "Maximum acceptable small message difficulty:", None))
self.tabWidgetSettings.setTabText(self.tabWidgetSettings.indexOf(self.tabMaxAcceptableDifficulty), _translate("settingsDialog", "Max acceptable difficulty", None)) self.tabWidgetSettings.setTabText(
self.tabWidgetSettings.indexOf(
self.tabMaxAcceptableDifficulty),
_translate(
"settingsDialog", "Max acceptable difficulty", None))
self.labelOpenCL.setText(_translate("settingsDialog", "Hardware GPU acceleration (OpenCL):", None)) self.labelOpenCL.setText(_translate("settingsDialog", "Hardware GPU acceleration (OpenCL):", None))
self.label_16.setText(_translate("settingsDialog", "<html><head/><body><p>Bitmessage can utilize a different Bitcoin-based program called Namecoin to make addresses human-friendly. For example, instead of having to tell your friend your long Bitmessage address, you can simply tell him to send a message to <span style=\" font-style:italic;\">test. </span></p><p>(Getting your own Bitmessage address into Namecoin is still rather difficult).</p><p>Bitmessage can use either namecoind directly or a running nmcontrol instance.</p></body></html>", None)) self.label_16.setText(_translate(
"settingsDialog",
"<html><head/><body><p>Bitmessage can utilize a different Bitcoin-based program called Namecoin to make"
" addresses human-friendly. For example, instead of having to tell your friend your long Bitmessage"
" address, you can simply tell him to send a message to <span style=\" font-style:italic;\">test."
" </span></p><p>(Getting your own Bitmessage address into Namecoin is still rather difficult).</p>"
"<p>Bitmessage can use either namecoind directly or a running nmcontrol instance.</p></body></html>",
None))
self.label_17.setText(_translate("settingsDialog", "Host:", None)) self.label_17.setText(_translate("settingsDialog", "Host:", None))
self.label_18.setText(_translate("settingsDialog", "Port:", None)) self.label_18.setText(_translate("settingsDialog", "Port:", None))
self.labelNamecoinUser.setText(_translate("settingsDialog", "Username:", None)) self.labelNamecoinUser.setText(_translate("settingsDialog", "Username:", None))
@ -505,12 +605,26 @@ class Ui_settingsDialog(object):
self.label_21.setText(_translate("settingsDialog", "Connect to:", None)) self.label_21.setText(_translate("settingsDialog", "Connect to:", None))
self.radioButtonNamecoinNamecoind.setText(_translate("settingsDialog", "Namecoind", None)) self.radioButtonNamecoinNamecoind.setText(_translate("settingsDialog", "Namecoind", None))
self.radioButtonNamecoinNmcontrol.setText(_translate("settingsDialog", "NMControl", None)) self.radioButtonNamecoinNmcontrol.setText(_translate("settingsDialog", "NMControl", None))
self.tabWidgetSettings.setTabText(self.tabWidgetSettings.indexOf(self.tabNamecoin), _translate("settingsDialog", "Namecoin integration", None)) self.tabWidgetSettings.setTabText(
self.label_7.setText(_translate("settingsDialog", "<html><head/><body><p>By default, if you send a message to someone and he is offline for more than two days, Bitmessage will send the message again after an additional two days. This will be continued with exponential backoff forever; messages will be resent after 5, 10, 20 days ect. until the receiver acknowledges them. Here you may change that behavior by having Bitmessage give up after a certain number of days or months.</p><p>Leave these input fields blank for the default behavior. </p></body></html>", None)) self.tabWidgetSettings.indexOf(
self.tabNamecoin),
_translate(
"settingsDialog", "Namecoin integration", None))
self.label_7.setText(_translate(
"settingsDialog",
"<html><head/><body><p>By default, if you send a message to someone and he is offline for more than two"
" days, Bitmessage will send the message again after an additional two days. This will be continued with"
" exponential backoff forever; messages will be resent after 5, 10, 20 days ect. until the receiver"
" acknowledges them. Here you may change that behavior by having Bitmessage give up after a certain"
" number of days or months.</p><p>Leave these input fields blank for the default behavior."
" </p></body></html>",
None))
self.label_19.setText(_translate("settingsDialog", "Give up after", None)) self.label_19.setText(_translate("settingsDialog", "Give up after", None))
self.label_20.setText(_translate("settingsDialog", "and", None)) self.label_20.setText(_translate("settingsDialog", "and", None))
self.label_22.setText(_translate("settingsDialog", "days", None)) self.label_22.setText(_translate("settingsDialog", "days", None))
self.label_23.setText(_translate("settingsDialog", "months.", None)) self.label_23.setText(_translate("settingsDialog", "months.", None))
self.tabWidgetSettings.setTabText(self.tabWidgetSettings.indexOf(self.tabResendsExpire), _translate("settingsDialog", "Resends Expire", None)) self.tabWidgetSettings.setTabText(
self.tabWidgetSettings.indexOf(
import bitmessage_icons_rc self.tabResendsExpire),
_translate(
"settingsDialog", "Resends Expire", None))

View File

@ -1,54 +1,64 @@
# Copyright (C) 2013 by Daniel Kraft <d@domob.eu> # pylint: disable=too-many-branches,protected-access
# This file is part of the Bitmessage project. """
# Copyright (C) 2013 by Daniel Kraft <d@domob.eu>
# Permission is hereby granted, free of charge, to any person obtaining a copy This file is part of the Bitmessage project.
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights Permission is hereby granted, free of charge, to any person obtaining a copy
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell of this software and associated documentation files (the "Software"), to deal
# copies of the Software, and to permit persons to whom the Software is in the Software without restriction, including without limitation the rights
# furnished to do so, subject to the following conditions: to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# The above copyright notice and this permission notice shall be included in all furnished to do so, subject to the following conditions:
# copies or substantial portions of the Software.
# The above copyright notice and this permission notice shall be included in all
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR copies or substantial portions of the Software.
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# SOFTWARE. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
.. todo:: from debug import logger crashes PyBitmessage due to a circular dependency. The debug module will also
override/disable logging.getLogger() # loggers so module level logging functions are used instead
"""
from __future__ import absolute_import
import base64 import base64
import httplib import httplib
import json import json
import os
import socket import socket
import sys import sys
import os
from bmconfigparser import BMConfigParser import logging as logger
import defaults import defaults
import tr # translate import tr # translate
from bmconfigparser import BMConfigParser
# FIXME: from debug import logger crashes PyBitmessage due to a circular
# dependency. The debug module will also override/disable logging.getLogger()
# loggers so module level logging functions are used instead
import logging as logger
configSection = "bitmessagesettings" configSection = "bitmessagesettings"
# Error thrown when the RPC call returns an error.
class RPCError(Exception): class RPCError(Exception):
"""Error thrown when the RPC call returns an error."""
error = None error = None
def __init__(self, data): def __init__(self, data):
super(RPCError, self).__init__()
self.error = data self.error = data
def __str__(self): def __str__(self):
return '{0}: {1}'.format(type(self).__name__, self.error) return '{0}: {1}'.format(type(self).__name__, self.error)
# This class handles the Namecoin identity integration.
class namecoinConnection(object): class namecoinConnection(object):
"""This class handles the Namecoin identity integration."""
user = None user = None
password = None password = None
host = None host = None
@ -58,11 +68,13 @@ class namecoinConnection (object):
queryid = 1 queryid = 1
con = None con = None
# Initialise. If options are given, take the connection settings from
# them instead of loading from the configs. This can be used to test
# currently entered connection settings in the config dialog without
# actually changing the values (yet).
def __init__(self, options=None): def __init__(self, options=None):
"""
Initialise. If options are given, take the connection settings from
them instead of loading from the configs. This can be used to test
currently entered connection settings in the config dialog without
actually changing the values (yet).
"""
if options is None: if options is None:
self.nmctype = BMConfigParser().get(configSection, "namecoinrpctype") self.nmctype = BMConfigParser().get(configSection, "namecoinrpctype")
self.host = BMConfigParser().get(configSection, "namecoinrpchost") self.host = BMConfigParser().get(configSection, "namecoinrpchost")
@ -81,11 +93,13 @@ class namecoinConnection (object):
if self.nmctype == "namecoind": if self.nmctype == "namecoind":
self.con = httplib.HTTPConnection(self.host, self.port, timeout=3) self.con = httplib.HTTPConnection(self.host, self.port, timeout=3)
# Query for the bitmessage address corresponding to the given identity
# string. If it doesn't contain a slash, id/ is prepended. We return
# the result as (Error, Address) pair, where the Error is an error
# message to display or None in case of success.
def query(self, string): def query(self, string):
"""
Query for the bitmessage address corresponding to the given identity
string. If it doesn't contain a slash, id/ is prepended. We return
the result as (Error, Address) pair, where the Error is an error
message to display or None in case of success.
"""
slashPos = string.find("/") slashPos = string.find("/")
if slashPos < 0: if slashPos < 0:
string = "id/" + string string = "id/" + string
@ -97,7 +111,7 @@ class namecoinConnection (object):
elif self.nmctype == "nmcontrol": elif self.nmctype == "nmcontrol":
res = self.callRPC("data", ["getValue", string]) res = self.callRPC("data", ["getValue", string])
res = res["reply"] res = res["reply"]
if res == False: if not res:
return (tr._translate("MainWindow", 'The name %1 was not found.').arg(unicode(string)), None) return (tr._translate("MainWindow", 'The name %1 was not found.').arg(unicode(string)), None)
else: else:
assert False assert False
@ -108,7 +122,7 @@ class namecoinConnection (object):
else: else:
errmsg = exc.error errmsg = exc.error
return (tr._translate("MainWindow", 'The namecoin query failed (%1)').arg(unicode(errmsg)), None) return (tr._translate("MainWindow", 'The namecoin query failed (%1)').arg(unicode(errmsg)), None)
except Exception as exc: except Exception:
logger.exception("Namecoin query exception") logger.exception("Namecoin query exception")
return (tr._translate("MainWindow", 'The namecoin query failed.'), None) return (tr._translate("MainWindow", 'The namecoin query failed.'), None)
@ -124,12 +138,19 @@ class namecoinConnection (object):
else: else:
ret = val["bitmessage"] ret = val["bitmessage"]
return (None, ret) return (None, ret)
return (tr._translate("MainWindow",'The name %1 has no associated Bitmessage address.').arg(unicode(string)), None) return (
tr._translate(
"MainWindow",
'The name %1 has no associated Bitmessage address.').arg(
unicode(string)),
None)
# Test the connection settings. This routine tries to query a "getinfo"
# command, and builds either an error message or a success message with
# some info from it.
def test(self): def test(self):
"""
Test the connection settings. This routine tries to query a "getinfo"
command, and builds either an error message or a success message with
some info from it.
"""
try: try:
if self.nmctype == "namecoind": if self.nmctype == "namecoind":
try: try:
@ -146,7 +167,12 @@ class namecoinConnection (object):
versStr = "0.%d.%d" % (v1, v2) versStr = "0.%d.%d" % (v1, v2)
else: else:
versStr = "0.%d.%d.%d" % (v1, v2, v3) versStr = "0.%d.%d.%d" % (v1, v2, v3)
return ('success', tr._translate("MainWindow",'Success! Namecoind version %1 running.').arg(unicode(versStr)) ) message = (
'success',
tr._translate(
"MainWindow",
'Success! Namecoind version %1 running.').arg(
unicode(versStr)))
elif self.nmctype == "nmcontrol": elif self.nmctype == "nmcontrol":
res = self.callRPC("data", ["status"]) res = self.callRPC("data", ["status"])
@ -155,10 +181,13 @@ class namecoinConnection (object):
return ('success', tr._translate("MainWindow", 'Success! NMControll is up and running.')) return ('success', tr._translate("MainWindow", 'Success! NMControll is up and running.'))
logger.error("Unexpected nmcontrol reply: %s", res) logger.error("Unexpected nmcontrol reply: %s", res)
return ('failed', tr._translate("MainWindow",'Couldn\'t understand NMControl.')) message = ('failed', tr._translate("MainWindow", 'Couldn\'t understand NMControl.'))
else: else:
assert False print "Unsupported Namecoin type"
sys.exit(1)
return message
except Exception: except Exception:
logger.info("Namecoin connection test failure") logger.info("Namecoin connection test failure")
@ -168,8 +197,9 @@ class namecoinConnection (object):
"MainWindow", "The connection to namecoin failed.") "MainWindow", "The connection to namecoin failed.")
) )
# Helper routine that actually performs an JSON RPC call.
def callRPC(self, method, params): def callRPC(self, method, params):
"""Helper routine that actually performs an JSON RPC call."""
data = {"method": method, "params": params, "id": self.queryid} data = {"method": method, "params": params, "id": self.queryid}
if self.nmctype == "namecoind": if self.nmctype == "namecoind":
resp = self.queryHTTP(json.dumps(data)) resp = self.queryHTTP(json.dumps(data))
@ -193,8 +223,9 @@ class namecoinConnection (object):
raise RPCError(val["result"]) raise RPCError(val["result"])
raise RPCError(error) raise RPCError(error)
# Query the server via HTTP.
def queryHTTP(self, data): def queryHTTP(self, data):
"""Query the server via HTTP."""
result = None result = None
try: try:
@ -213,7 +244,7 @@ class namecoinConnection (object):
resp = self.con.getresponse() resp = self.con.getresponse()
result = resp.read() result = resp.read()
if resp.status != 200: if resp.status != 200:
raise Exception ("Namecoin returned status %i: %s", resp.status, resp.reason) raise Exception("Namecoin returned status %i: %s" % resp.status, resp.reason)
except: except:
logger.info("HTTP receive error") logger.info("HTTP receive error")
except: except:
@ -221,8 +252,9 @@ class namecoinConnection (object):
return result return result
# Helper routine sending data to the RPC server and returning the result.
def queryServer(self, data): def queryServer(self, data):
"""Helper routine sending data to the RPC server and returning the result."""
try: try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
@ -244,9 +276,14 @@ class namecoinConnection (object):
except socket.error as exc: except socket.error as exc:
raise Exception("Socket error in RPC connection: %s" % str(exc)) raise Exception("Socket error in RPC connection: %s" % str(exc))
# Look up the namecoin data folder.
# FIXME: Check whether this works on other platforms as well!
def lookupNamecoinFolder(): def lookupNamecoinFolder():
"""
Look up the namecoin data folder.
.. todo:: Check whether this works on other platforms as well!
"""
app = "namecoin" app = "namecoin"
from os import path, environ from os import path, environ
if sys.platform == "darwin": if sys.platform == "darwin":
@ -254,8 +291,10 @@ def lookupNamecoinFolder ():
dataFolder = path.join(os.environ["HOME"], dataFolder = path.join(os.environ["HOME"],
"Library/Application Support/", app) + '/' "Library/Application Support/", app) + '/'
else: else:
print ("Could not find home folder, please report this message" print(
+ " and your OS X version to the BitMessage Github.") "Could not find home folder, please report this message"
" and your OS X version to the BitMessage Github."
)
sys.exit() sys.exit()
elif "win32" in sys.platform or "win64" in sys.platform: elif "win32" in sys.platform or "win64" in sys.platform:
@ -265,9 +304,13 @@ def lookupNamecoinFolder ():
return dataFolder return dataFolder
# Ensure all namecoin options are set, by setting those to default values
# that aren't there.
def ensureNamecoinOptions(): def ensureNamecoinOptions():
"""
Ensure all namecoin options are set, by setting those to default values
that aren't there.
"""
if not BMConfigParser().has_option(configSection, "namecoinrpctype"): if not BMConfigParser().has_option(configSection, "namecoinrpctype"):
BMConfigParser().set(configSection, "namecoinrpctype", "namecoind") BMConfigParser().set(configSection, "namecoinrpctype", "namecoind")
if not BMConfigParser().has_option(configSection, "namecoinrpchost"): if not BMConfigParser().has_option(configSection, "namecoinrpchost"):
@ -304,16 +347,16 @@ def ensureNamecoinOptions ():
nmc.close() nmc.close()
except IOError: except IOError:
logger.error("%s unreadable or missing, Namecoin support deactivated", nmcConfig) logger.error("%s unreadable or missing, Namecoin support deactivated", nmcConfig)
except Exception as exc: except Exception:
logger.warning("Error processing namecoin.conf", exc_info=True) logger.warning("Error processing namecoin.conf", exc_info=True)
# If still nothing found, set empty at least. # If still nothing found, set empty at least.
if (not hasUser): if not hasUser:
BMConfigParser().set(configSection, "namecoinrpcuser", defaultUser) BMConfigParser().set(configSection, "namecoinrpcuser", defaultUser)
if (not hasPass): if not hasPass:
BMConfigParser().set(configSection, "namecoinrpcpassword", defaultPass) BMConfigParser().set(configSection, "namecoinrpcpassword", defaultPass)
# Set default port now, possibly to found value. # Set default port now, possibly to found value.
if (not hasPort): if not hasPort:
BMConfigParser().set(configSection, "namecoinrpcport", BMConfigParser().set(configSection, "namecoinrpcport",
defaults.namecoinDefaultRpcPort) defaults.namecoinDefaultRpcPort)