Reduce imports from outer package in bitmessageqt: main idea

This commit is contained in:
Dmitri Bogomolov 2019-11-29 12:29:18 +02:00
parent 448e9e2f36
commit a1c12b7f2f
Signed by untrusted user: g1itch
GPG Key ID: 720A756F18DEED13
4 changed files with 165 additions and 142 deletions

View File

@ -32,6 +32,7 @@ import traceback
from struct import pack from struct import pack
import defaults import defaults
import queues
import shared import shared
import shutdown import shutdown
import state import state
@ -153,7 +154,9 @@ class Main(object):
_fixSocket() _fixSocket()
adjustHalfOpenConnectionsLimit() adjustHalfOpenConnectionsLimit()
config = BMConfigParser() self.config = config = BMConfigParser()
self.queues = queues
self.state = state
daemon = config.safeGetBoolean('bitmessagesettings', 'daemon') daemon = config.safeGetBoolean('bitmessagesettings', 'daemon')
try: try:
@ -357,7 +360,7 @@ class Main(object):
# NavigateApp().run() # NavigateApp().run()
else: else:
import bitmessageqt import bitmessageqt
bitmessageqt.run() bitmessageqt.run(self)
else: else:
config.remove_option('bitmessagesettings', 'dontconnect') config.remove_option('bitmessagesettings', 'dontconnect')

View File

@ -4,6 +4,7 @@ PyQt based UI for bitmessage, the main module
import hashlib import hashlib
import locale import locale
import logging
import os import os
import random import random
import string import string
@ -19,12 +20,9 @@ from PyQt4 import QtCore, QtGui
from PyQt4.QtNetwork import QLocalSocket, QLocalServer from PyQt4.QtNetwork import QLocalSocket, QLocalServer
import shared import shared
import state
from debug import logger
from tr import _translate from tr import _translate
from addresses import decodeAddress, addBMIfNotPresent from addresses import decodeAddress, addBMIfNotPresent
from bitmessageui import Ui_MainWindow from bitmessageui import Ui_MainWindow
from bmconfigparser import BMConfigParser
import namecoin import namecoin
from messageview import MessageView from messageview import MessageView
from migrationwizard import Ui_MigrationWizard from migrationwizard import Ui_MigrationWizard
@ -48,8 +46,6 @@ from network.stats import pendingDownload, pendingUpload
from uisignaler import UISignaler from uisignaler import UISignaler
import paths import paths
from proofofwork import getPowType from proofofwork import getPowType
import queues
import shutdown
from statusbar import BMStatusBar from statusbar import BMStatusBar
import sound import sound
# This is needed for tray icon # This is needed for tray icon
@ -61,11 +57,13 @@ try:
except ImportError: except ImportError:
get_plugins = False get_plugins = False
logger = logging.getLogger('default')
# TODO: rewrite # TODO: rewrite
def powQueueSize(): def powQueueSize():
"""Returns the size of queues.workerQueue including current unfinished work""" """Returns the size of queues.workerQueue including current unfinished work"""
queue_len = queues.workerQueue.qsize() queue_len = app.core.queues.workerQueue.qsize()
for thread in threading.enumerate(): for thread in threading.enumerate():
try: try:
if thread.name == "singleWorker": if thread.name == "singleWorker":
@ -75,9 +73,8 @@ def powQueueSize():
return queue_len return queue_len
def openKeysFile(): def openKeysFile(keysfile):
"""Open keys file with an external editor""" """Open keys *keysfile* with an external editor"""
keysfile = os.path.join(state.appdata, 'keys.dat')
if 'linux' in sys.platform: if 'linux' in sys.platform:
subprocess.call(["xdg-open", keysfile]) subprocess.call(["xdg-open", keysfile])
elif sys.platform.startswith('win'): elif sys.platform.startswith('win'):
@ -514,11 +511,11 @@ class MyForm(settingsmixin.SMainWindow):
enabled = {} enabled = {}
for toAddress in getSortedAccounts(): for toAddress in getSortedAccounts():
isEnabled = BMConfigParser().getboolean( isEnabled = app.core.config.getboolean(
toAddress, 'enabled') toAddress, 'enabled')
isChan = BMConfigParser().safeGetBoolean( isChan = app.core.config.safeGetBoolean(
toAddress, 'chan') toAddress, 'chan')
isMaillinglist = BMConfigParser().safeGetBoolean( isMaillinglist = app.core.config.safeGetBoolean(
toAddress, 'mailinglist') toAddress, 'mailinglist')
if treeWidget == self.ui.treeWidgetYourIdentities: if treeWidget == self.ui.treeWidgetYourIdentities:
@ -637,8 +634,8 @@ class MyForm(settingsmixin.SMainWindow):
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:
BMConfigParser().remove_section(addressInKeysFile) app.core.config.remove_section(addressInKeysFile)
BMConfigParser().save() app.core.config.save()
self.updateStartOnLogon() self.updateStartOnLogon()
@ -810,7 +807,7 @@ class MyForm(settingsmixin.SMainWindow):
self.rerenderComboBoxSendFromBroadcast() self.rerenderComboBoxSendFromBroadcast()
# Put the TTL slider in the correct spot # Put the TTL slider in the correct spot
TTL = BMConfigParser().getint('bitmessagesettings', 'ttl') TTL = app.core.config.getint('bitmessagesettings', 'ttl')
if TTL < 3600: # an hour if TTL < 3600: # an hour
TTL = 3600 TTL = 3600
elif TTL > 28*24*60*60: # 28 days elif TTL > 28*24*60*60: # 28 days
@ -829,7 +826,7 @@ class MyForm(settingsmixin.SMainWindow):
self.ui.updateNetworkSwitchMenuLabel() self.ui.updateNetworkSwitchMenuLabel()
self._firstrun = BMConfigParser().safeGetBoolean( self._firstrun = app.core.config.safeGetBoolean(
'bitmessagesettings', 'dontconnect') 'bitmessagesettings', 'dontconnect')
self._contact_selected = None self._contact_selected = None
@ -854,7 +851,7 @@ class MyForm(settingsmixin.SMainWindow):
# In case the user moves the program and the registry entry is # In case the user moves the program and the registry entry is
# no longer valid, this will delete the old registry entry. # no longer valid, this will delete the old registry entry.
self.settings.remove("PyBitmessage") self.settings.remove("PyBitmessage")
if BMConfigParser().getboolean( if app.core.config.getboolean(
'bitmessagesettings', 'startonlogon' 'bitmessagesettings', 'startonlogon'
): ):
self.settings.setValue("PyBitmessage", sys.argv[0]) self.settings.setValue("PyBitmessage", sys.argv[0])
@ -868,8 +865,8 @@ class MyForm(settingsmixin.SMainWindow):
def updateTTL(self, sliderPosition): def updateTTL(self, sliderPosition):
TTL = int(sliderPosition ** 3.199 + 3600) TTL = int(sliderPosition ** 3.199 + 3600)
self.updateHumanFriendlyTTLDescription(TTL) self.updateHumanFriendlyTTLDescription(TTL)
BMConfigParser().set('bitmessagesettings', 'ttl', str(TTL)) app.core.config.set('bitmessagesettings', 'ttl', str(TTL))
BMConfigParser().save() app.core.config.save()
def updateHumanFriendlyTTLDescription(self, TTL): def updateHumanFriendlyTTLDescription(self, TTL):
numberOfHours = int(round(TTL / (60*60))) numberOfHours = int(round(TTL / (60*60)))
@ -920,7 +917,7 @@ class MyForm(settingsmixin.SMainWindow):
self.appIndicatorShowOrHideWindow() self.appIndicatorShowOrHideWindow()
def appIndicatorSwitchQuietMode(self): def appIndicatorSwitchQuietMode(self):
BMConfigParser().set( app.core.config.set(
'bitmessagesettings', 'showtraynotifications', 'bitmessagesettings', 'showtraynotifications',
str(not self.actionQuiet.isChecked()) str(not self.actionQuiet.isChecked())
) )
@ -1291,7 +1288,7 @@ class MyForm(settingsmixin.SMainWindow):
# show bitmessage # show bitmessage
self.actionShow = QtGui.QAction(_translate( self.actionShow = QtGui.QAction(_translate(
"MainWindow", "Show Bitmessage"), m, checkable=True) "MainWindow", "Show Bitmessage"), m, checkable=True)
self.actionShow.setChecked(not BMConfigParser().getboolean( self.actionShow.setChecked(not app.core.config.getboolean(
'bitmessagesettings', 'startintray')) 'bitmessagesettings', 'startintray'))
self.actionShow.triggered.connect(self.appIndicatorShowOrHideWindow) self.actionShow.triggered.connect(self.appIndicatorShowOrHideWindow)
if not sys.platform[0:3] == 'win': if not sys.platform[0:3] == 'win':
@ -1300,7 +1297,7 @@ class MyForm(settingsmixin.SMainWindow):
# quiet mode # quiet mode
self.actionQuiet = QtGui.QAction(_translate( self.actionQuiet = QtGui.QAction(_translate(
"MainWindow", "Quiet Mode"), m, checkable=True) "MainWindow", "Quiet Mode"), m, checkable=True)
self.actionQuiet.setChecked(not BMConfigParser().getboolean( self.actionQuiet.setChecked(not app.core.config.getboolean(
'bitmessagesettings', 'showtraynotifications')) 'bitmessagesettings', 'showtraynotifications'))
self.actionQuiet.triggered.connect(self.appIndicatorSwitchQuietMode) self.actionQuiet.triggered.connect(self.appIndicatorSwitchQuietMode)
m.addAction(self.actionQuiet) m.addAction(self.actionQuiet)
@ -1364,7 +1361,7 @@ class MyForm(settingsmixin.SMainWindow):
# if the address had a known label in the address book # if the address had a known label in the address book
if label: if label:
# Does a sound file exist for this particular contact? # Does a sound file exist for this particular contact?
soundFilename = state.appdata + 'sounds/' + label soundFilename = app.core.state.appdata + 'sounds/' + label
ext = _choose_ext(soundFilename) ext = _choose_ext(soundFilename)
if not ext: if not ext:
category = sound.SOUND_KNOWN category = sound.SOUND_KNOWN
@ -1383,19 +1380,19 @@ class MyForm(settingsmixin.SMainWindow):
# 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:
soundFilename = state.appdata + 'sounds/known' soundFilename = app.core.state.appdata + 'sounds/known'
# the sound is for an unknown address # the sound is for an unknown address
elif category is sound.SOUND_UNKNOWN: elif category is sound.SOUND_UNKNOWN:
soundFilename = state.appdata + 'sounds/unknown' soundFilename = app.core.state.appdata + 'sounds/unknown'
# initial connection sound # initial connection sound
elif category is sound.SOUND_CONNECTED: elif category is sound.SOUND_CONNECTED:
soundFilename = state.appdata + 'sounds/connected' soundFilename = app.core.state.appdata + 'sounds/connected'
# disconnected sound # disconnected sound
elif category is sound.SOUND_DISCONNECTED: elif category is sound.SOUND_DISCONNECTED:
soundFilename = state.appdata + 'sounds/disconnected' soundFilename = app.core.state.appdata + 'sounds/disconnected'
# sound when the connection status becomes green # sound when the connection status becomes green
elif category is sound.SOUND_CONNECTION_GREEN: elif category is sound.SOUND_CONNECTION_GREEN:
soundFilename = state.appdata + 'sounds/green' soundFilename = app.core.state.appdata + 'sounds/green'
if soundFilename is None: if soundFilename is None:
logger.warning("Probably wrong category number in playSound()") logger.warning("Probably wrong category number in playSound()")
@ -1549,7 +1546,7 @@ class MyForm(settingsmixin.SMainWindow):
# menu button 'manage keys' # menu button 'manage keys'
def click_actionManageKeys(self): def click_actionManageKeys(self):
if 'darwin' in sys.platform or 'linux' in sys.platform: if 'darwin' in sys.platform or 'linux' in sys.platform:
if state.appdata == '': if app.core.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
@ -1559,16 +1556,16 @@ class MyForm(settingsmixin.SMainWindow):
else: else:
QtGui.QMessageBox.information(self, 'keys.dat?', _translate( QtGui.QMessageBox.information(self, 'keys.dat?', _translate(
"MainWindow", "You may manage your keys by editing the keys.dat file stored in\n %1 \nIt is important that you back up this file.").arg(state.appdata), QtGui.QMessageBox.Ok) "MainWindow", "You may manage your keys by editing the keys.dat file stored in\n %1 \nIt is important that you back up this file.").arg(app.core.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 app.core.state.appdata == '':
reply = QtGui.QMessageBox.question(self, _translate("MainWindow", "Open keys.dat?"), _translate( reply = QtGui.QMessageBox.question(self, _translate("MainWindow", "Open keys.dat?"), _translate(
"MainWindow", "You may manage your keys by editing the keys.dat file stored in the same directory as this program. It is important that you back up this file. Would you like to open the file now? (Be sure to close Bitmessage before making any changes.)"), QtGui.QMessageBox.Yes, QtGui.QMessageBox.No) "MainWindow", "You may manage your keys by editing the keys.dat file stored in the same directory as this program. It is important that you back up this file. Would you like to open the file now? (Be sure to close Bitmessage before making any changes.)"), QtGui.QMessageBox.Yes, QtGui.QMessageBox.No)
else: else:
reply = QtGui.QMessageBox.question(self, _translate("MainWindow", "Open keys.dat?"), _translate( reply = QtGui.QMessageBox.question(self, _translate("MainWindow", "Open keys.dat?"), _translate(
"MainWindow", "You may manage your keys by editing the keys.dat file stored in\n %1 \nIt is important that you back up this file. Would you like to open the file now? (Be sure to close Bitmessage before making any changes.)").arg(state.appdata), QtGui.QMessageBox.Yes, QtGui.QMessageBox.No) "MainWindow", "You may manage your keys by editing the keys.dat file stored in\n %1 \nIt is important that you back up this file. Would you like to open the file now? (Be sure to close Bitmessage before making any changes.)").arg(app.core.state.appdata), QtGui.QMessageBox.Yes, QtGui.QMessageBox.No)
if reply == QtGui.QMessageBox.Yes: if reply == QtGui.QMessageBox.Yes:
openKeysFile() openKeysFile(os.path.join(app.core.state.appdata, 'keys.dat'))
# menu button 'delete all treshed messages' # menu button 'delete all treshed messages'
def click_actionDeleteAllTrashedMessages(self): def click_actionDeleteAllTrashedMessages(self):
@ -1621,7 +1618,7 @@ class MyForm(settingsmixin.SMainWindow):
"Your address version number must be either 3 or 4." "Your address version number must be either 3 or 4."
)) ))
return return
queues.addressGeneratorQueue.put(( app.core.queues.addressGeneratorQueue.put((
'createDeterministicAddresses', 'createDeterministicAddresses',
addressVersionNumber, streamNumberForAddress, addressVersionNumber, streamNumberForAddress,
"regenerated deterministic address", "regenerated deterministic address",
@ -1642,9 +1639,9 @@ class MyForm(settingsmixin.SMainWindow):
if dialog.exec_(): if dialog.exec_():
if dialog.radioButtonConnectNow.isChecked(): if dialog.radioButtonConnectNow.isChecked():
self.ui.updateNetworkSwitchMenuLabel(False) self.ui.updateNetworkSwitchMenuLabel(False)
BMConfigParser().remove_option( app.core.config.remove_option(
'bitmessagesettings', 'dontconnect') 'bitmessagesettings', 'dontconnect')
BMConfigParser().save() app.core.config.save()
elif dialog.radioButtonConfigureNetwork.isChecked(): elif dialog.radioButtonConfigureNetwork.isChecked():
self.click_actionSettings() self.click_actionSettings()
else: else:
@ -1669,7 +1666,7 @@ class MyForm(settingsmixin.SMainWindow):
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') and not 'darwin' in sys.platform: if app.core.config.getboolean('bitmessagesettings', 'minimizetotray') and not 'darwin' 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
@ -1686,20 +1683,24 @@ class MyForm(settingsmixin.SMainWindow):
def setStatusIcon(self, color): def setStatusIcon(self, color):
# print 'setting status icon color' # print 'setting status icon color'
_notifications_enabled = not BMConfigParser().getboolean( _notifications_enabled = not app.core.config.getboolean(
'bitmessagesettings', 'hidetrayconnectionnotifications') 'bitmessagesettings', 'hidetrayconnectionnotifications')
if color == 'red': if color == 'red':
self.pushButtonStatusIcon.setIcon( self.pushButtonStatusIcon.setIcon(
QtGui.QIcon(":/newPrefix/images/redicon.png")) QtGui.QIcon(":/newPrefix/images/redicon.png"))
state.statusIconColor = 'red' app.core.state.statusIconColor = 'red'
# if the connection is lost then show a notification # if the connection is lost then show a notification
if self.connected and _notifications_enabled: if self.connected and _notifications_enabled:
self.notifierShow( self.notifierShow(
'Bitmessage', 'Bitmessage',
_translate("MainWindow", "Connection lost"), _translate("MainWindow", "Connection lost"),
sound.SOUND_DISCONNECTED) sound.SOUND_DISCONNECTED)
if not BMConfigParser().safeGetBoolean('bitmessagesettings', 'upnp') and \ if (
BMConfigParser().get('bitmessagesettings', 'socksproxytype') == "none": not app.core.config.safeGetBoolean(
'bitmessagesettings', 'upnp')
and app.core.config.get(
'bitmessagesettings', 'socksproxytype') == 'none'
):
self.updateStatusBar( self.updateStatusBar(
_translate( _translate(
"MainWindow", "MainWindow",
@ -1717,7 +1718,7 @@ class MyForm(settingsmixin.SMainWindow):
self.statusbar.clearMessage() self.statusbar.clearMessage()
self.pushButtonStatusIcon.setIcon( self.pushButtonStatusIcon.setIcon(
QtGui.QIcon(":/newPrefix/images/yellowicon.png")) QtGui.QIcon(":/newPrefix/images/yellowicon.png"))
state.statusIconColor = 'yellow' app.core.state.statusIconColor = 'yellow'
# if a new connection has been established then show a notification # if a new connection has been established then show a notification
if not self.connected and _notifications_enabled: if not self.connected and _notifications_enabled:
self.notifierShow( self.notifierShow(
@ -1735,7 +1736,7 @@ class MyForm(settingsmixin.SMainWindow):
self.statusbar.clearMessage() self.statusbar.clearMessage()
self.pushButtonStatusIcon.setIcon( self.pushButtonStatusIcon.setIcon(
QtGui.QIcon(":/newPrefix/images/greenicon.png")) QtGui.QIcon(":/newPrefix/images/greenicon.png"))
state.statusIconColor = 'green' app.core.state.statusIconColor = 'green'
if not self.connected and _notifications_enabled: if not self.connected and _notifications_enabled:
self.notifierShow( self.notifierShow(
'Bitmessage', 'Bitmessage',
@ -1942,7 +1943,7 @@ class MyForm(settingsmixin.SMainWindow):
addresses = getSortedAccounts() addresses = getSortedAccounts()
for address in addresses: for address in addresses:
account = accountClass(address) account = accountClass(address)
if (account.type == AccountMixin.CHAN and BMConfigParser().safeGetBoolean(address, 'enabled')): if (account.type == AccountMixin.CHAN and app.core.config.safeGetBoolean(address, 'enabled')):
newRows[address] = [account.getLabel(), AccountMixin.CHAN] newRows[address] = [account.getLabel(), AccountMixin.CHAN]
# normal accounts # normal accounts
queryreturn = sqlQuery('SELECT * FROM addressbook') queryreturn = sqlQuery('SELECT * FROM addressbook')
@ -2060,9 +2061,9 @@ class MyForm(settingsmixin.SMainWindow):
email = ''.join(random.SystemRandom().choice(string.ascii_lowercase) for _ in range(12)) + "@mailchuck.com" email = ''.join(random.SystemRandom().choice(string.ascii_lowercase) for _ in range(12)) + "@mailchuck.com"
acct = MailchuckAccount(fromAddress) acct = MailchuckAccount(fromAddress)
acct.register(email) acct.register(email)
BMConfigParser().set(fromAddress, 'label', email) app.core.config.set(fromAddress, 'label', email)
BMConfigParser().set(fromAddress, 'gateway', 'mailchuck') app.core.config.set(fromAddress, 'gateway', 'mailchuck')
BMConfigParser().save() app.core.config.save()
self.updateStatusBar(_translate( self.updateStatusBar(_translate(
"MainWindow", "MainWindow",
"Error: Your account wasn't registered at" "Error: Your account wasn't registered at"
@ -2155,7 +2156,7 @@ class MyForm(settingsmixin.SMainWindow):
"MainWindow", "Concerning the address %1, Bitmessage cannot handle stream numbers of %2. Perhaps upgrade Bitmessage to the latest version.").arg(toAddress).arg(str(streamNumber))) "MainWindow", "Concerning the address %1, Bitmessage cannot handle stream numbers of %2. Perhaps upgrade Bitmessage to the latest version.").arg(toAddress).arg(str(streamNumber)))
continue continue
self.statusbar.clearMessage() self.statusbar.clearMessage()
if state.statusIconColor == 'red': if app.core.state.statusIconColor == 'red':
self.updateStatusBar(_translate( self.updateStatusBar(_translate(
"MainWindow", "MainWindow",
"Warning: You are currently not connected." "Warning: You are currently not connected."
@ -2175,7 +2176,7 @@ class MyForm(settingsmixin.SMainWindow):
self.displayNewSentMessage( self.displayNewSentMessage(
toAddress, toLabel, fromAddress, subject, message, ackdata) toAddress, toLabel, fromAddress, subject, message, ackdata)
queues.workerQueue.put(('sendmessage', toAddress)) app.core.queues.workerQueue.put(('sendmessage', toAddress))
self.click_pushButtonClear() self.click_pushButtonClear()
if self.replyFromTab is not None: if self.replyFromTab is not None:
@ -2212,7 +2213,7 @@ class MyForm(settingsmixin.SMainWindow):
self.displayNewSentMessage( self.displayNewSentMessage(
toAddress, toLabel, fromAddress, subject, message, ackdata) toAddress, toLabel, fromAddress, subject, message, ackdata)
queues.workerQueue.put(('sendbroadcast', '')) app.core.queues.workerQueue.put(('sendbroadcast', ''))
self.ui.comboBoxSendFromBroadcast.setCurrentIndex(0) self.ui.comboBoxSendFromBroadcast.setCurrentIndex(0)
self.ui.lineEditSubjectBroadcast.setText('') self.ui.lineEditSubjectBroadcast.setText('')
@ -2254,18 +2255,18 @@ class MyForm(settingsmixin.SMainWindow):
self.ui.tabWidgetSend.setCurrentIndex( self.ui.tabWidgetSend.setCurrentIndex(
self.ui.tabWidgetSend.indexOf( self.ui.tabWidgetSend.indexOf(
self.ui.sendBroadcast self.ui.sendBroadcast
if BMConfigParser().safeGetBoolean(str(address), 'mailinglist') if app.core.config.safeGetBoolean(str(address), 'mailinglist')
else self.ui.sendDirect else self.ui.sendDirect
)) ))
def rerenderComboBoxSendFrom(self): def rerenderComboBoxSendFrom(self):
self.ui.comboBoxSendFrom.clear() self.ui.comboBoxSendFrom.clear()
for addressInKeysFile in getSortedAccounts(): for addressInKeysFile in getSortedAccounts():
isEnabled = BMConfigParser().getboolean( isEnabled = app.core.config.getboolean(
addressInKeysFile, 'enabled') # 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.
isMaillinglist = BMConfigParser().safeGetBoolean(addressInKeysFile, 'mailinglist') isMaillinglist = app.core.config.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(app.core.config.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)
@ -2285,11 +2286,11 @@ class MyForm(settingsmixin.SMainWindow):
def rerenderComboBoxSendFromBroadcast(self): def rerenderComboBoxSendFromBroadcast(self):
self.ui.comboBoxSendFromBroadcast.clear() self.ui.comboBoxSendFromBroadcast.clear()
for addressInKeysFile in getSortedAccounts(): for addressInKeysFile in getSortedAccounts():
isEnabled = BMConfigParser().getboolean( isEnabled = app.core.config.getboolean(
addressInKeysFile, 'enabled') # 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.
isChan = BMConfigParser().safeGetBoolean(addressInKeysFile, 'chan') isChan = app.core.config.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(app.core.config.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)
@ -2390,7 +2391,7 @@ class MyForm(settingsmixin.SMainWindow):
else: else:
acct = ret acct = ret
self.propagateUnreadCount(widget=treeWidget if ret else None) self.propagateUnreadCount(widget=treeWidget if ret else None)
if BMConfigParser().safeGetBoolean( if app.core.config.safeGetBoolean(
'bitmessagesettings', 'showtraynotifications'): 'bitmessagesettings', 'showtraynotifications'):
self.notifierShow( self.notifierShow(
_translate("MainWindow", "New Message"), _translate("MainWindow", "New Message"),
@ -2410,7 +2411,7 @@ class MyForm(settingsmixin.SMainWindow):
if acct.feedback != GatewayAccount.ALL_OK: if acct.feedback != GatewayAccount.ALL_OK:
if acct.feedback == GatewayAccount.REGISTRATION_DENIED: if acct.feedback == GatewayAccount.REGISTRATION_DENIED:
dialogs.EmailGatewayDialog( dialogs.EmailGatewayDialog(
self, BMConfigParser(), acct).exec_() self, app.core.config, acct).exec_()
# possible other branches? # possible other branches?
except AttributeError: except AttributeError:
pass pass
@ -2487,12 +2488,12 @@ class MyForm(settingsmixin.SMainWindow):
# to the objectProcessorQueue to be processed # to the objectProcessorQueue to be processed
if dialog.checkBoxDisplayMessagesAlreadyInInventory.isChecked(): if dialog.checkBoxDisplayMessagesAlreadyInInventory.isChecked():
for value in dialog.recent: for value in dialog.recent:
queues.objectProcessorQueue.put(( app.core.queues.objectProcessorQueue.put((
value.type, value.payload value.type, value.payload
)) ))
def click_pushButtonStatusIcon(self): def click_pushButtonStatusIcon(self):
dialogs.IconGlossaryDialog(self, config=BMConfigParser()).exec_() dialogs.IconGlossaryDialog(self, config=app.core.config).exec_()
def click_actionHelp(self): def click_actionHelp(self):
dialogs.HelpDialog(self).exec_() dialogs.HelpDialog(self).exec_()
@ -2519,10 +2520,10 @@ class MyForm(settingsmixin.SMainWindow):
def on_action_SpecialAddressBehaviorDialog(self): def on_action_SpecialAddressBehaviorDialog(self):
"""Show SpecialAddressBehaviorDialog""" """Show SpecialAddressBehaviorDialog"""
dialogs.SpecialAddressBehaviorDialog(self, BMConfigParser()) dialogs.SpecialAddressBehaviorDialog(self, app.core.config)
def on_action_EmailGatewayDialog(self): def on_action_EmailGatewayDialog(self):
dialog = dialogs.EmailGatewayDialog(self, config=BMConfigParser()) dialog = dialogs.EmailGatewayDialog(self, config=app.core.config)
# For Modal dialogs # For Modal dialogs
dialog.exec_() dialog.exec_()
try: try:
@ -2584,7 +2585,7 @@ class MyForm(settingsmixin.SMainWindow):
dialogs.NewAddressDialog(self) dialogs.NewAddressDialog(self)
def network_switch(self): def network_switch(self):
dontconnect_option = not BMConfigParser().safeGetBoolean( dontconnect_option = not app.core.config.safeGetBoolean(
'bitmessagesettings', 'dontconnect') 'bitmessagesettings', 'dontconnect')
reply = QtGui.QMessageBox.question( reply = QtGui.QMessageBox.question(
self, _translate("MainWindow", "Disconnecting") self, _translate("MainWindow", "Disconnecting")
@ -2599,9 +2600,9 @@ class MyForm(settingsmixin.SMainWindow):
QtGui.QMessageBox.Cancel) QtGui.QMessageBox.Cancel)
if reply != QtGui.QMessageBox.Yes: if reply != QtGui.QMessageBox.Yes:
return return
BMConfigParser().set( app.core.config.set(
'bitmessagesettings', 'dontconnect', str(dontconnect_option)) 'bitmessagesettings', 'dontconnect', str(dontconnect_option))
BMConfigParser().save() app.core.config.save()
self.ui.updateNetworkSwitchMenuLabel(dontconnect_option) self.ui.updateNetworkSwitchMenuLabel(dontconnect_option)
self.ui.pushButtonFetchNamecoinID.setHidden( self.ui.pushButtonFetchNamecoinID.setHidden(
@ -2623,7 +2624,10 @@ class MyForm(settingsmixin.SMainWindow):
waitForSync = False waitForSync = False
# C PoW currently doesn't support interrupting and OpenCL is untested # C PoW currently doesn't support interrupting and OpenCL is untested
if getPowType() == "python" and (powQueueSize() > 0 or pendingUpload() > 0): if (
getPowType() == "python"
and powQueueSize() > 0 or pendingUpload() > 0
):
reply = QtGui.QMessageBox.question( reply = QtGui.QMessageBox.question(
self, _translate("MainWindow", "Proof of work pending"), self, _translate("MainWindow", "Proof of work pending"),
_translate( _translate(
@ -2663,8 +2667,11 @@ class MyForm(settingsmixin.SMainWindow):
elif reply == QtGui.QMessageBox.Cancel: elif reply == QtGui.QMessageBox.Cancel:
return return
if state.statusIconColor == 'red' and not BMConfigParser().safeGetBoolean( if (
'bitmessagesettings', 'dontconnect'): app.core.state.statusIconColor == 'red'
and not app.core.config.safeGetBoolean(
'bitmessagesettings', 'dontconnect')
):
reply = QtGui.QMessageBox.question( reply = QtGui.QMessageBox.question(
self, _translate("MainWindow", "Not connected"), self, _translate("MainWindow", "Not connected"),
_translate( _translate(
@ -2689,7 +2696,7 @@ class MyForm(settingsmixin.SMainWindow):
if waitForConnection: if waitForConnection:
self.updateStatusBar(_translate( self.updateStatusBar(_translate(
"MainWindow", "Waiting for network connection...")) "MainWindow", "Waiting for network connection..."))
while state.statusIconColor == 'red': while app.core.state.statusIconColor == 'red':
time.sleep(0.5) time.sleep(0.5)
QtCore.QCoreApplication.processEvents( QtCore.QCoreApplication.processEvents(
QtCore.QEventLoop.AllEvents, 1000 QtCore.QEventLoop.AllEvents, 1000
@ -2780,7 +2787,7 @@ class MyForm(settingsmixin.SMainWindow):
QtCore.QCoreApplication.processEvents( QtCore.QCoreApplication.processEvents(
QtCore.QEventLoop.AllEvents, 1000 QtCore.QEventLoop.AllEvents, 1000
) )
shutdown.doCleanShutdown() app.core.stop()
self.updateStatusBar(_translate( self.updateStatusBar(_translate(
"MainWindow", "Stopping notifications... %1%").arg(90)) "MainWindow", "Stopping notifications... %1%").arg(90))
@ -2799,7 +2806,7 @@ class MyForm(settingsmixin.SMainWindow):
def closeEvent(self, event): def closeEvent(self, event):
"""window close event""" """window close event"""
event.ignore() event.ignore()
trayonclose = BMConfigParser().safeGetBoolean( trayonclose = app.core.config.safeGetBoolean(
'bitmessagesettings', 'trayonclose') 'bitmessagesettings', 'trayonclose')
if trayonclose: if trayonclose:
self.appIndicatorHide() self.appIndicatorHide()
@ -2868,7 +2875,8 @@ class MyForm(settingsmixin.SMainWindow):
# Format predefined text on message reply. # Format predefined text on message reply.
def quoted_text(self, message): def quoted_text(self, message):
if not BMConfigParser().safeGetBoolean('bitmessagesettings', 'replybelow'): if not app.core.config.safeGetBoolean(
'bitmessagesettings', 'replybelow'):
return '\n\n------------------------------------------------------\n' + message return '\n\n------------------------------------------------------\n' + message
quoteWrapper = textwrap.TextWrapper( quoteWrapper = textwrap.TextWrapper(
@ -2955,7 +2963,7 @@ class MyForm(settingsmixin.SMainWindow):
self.ui.tabWidgetSend.indexOf(self.ui.sendDirect) self.ui.tabWidgetSend.indexOf(self.ui.sendDirect)
) )
# toAddressAtCurrentInboxRow = fromAddressAtCurrentInboxRow # toAddressAtCurrentInboxRow = fromAddressAtCurrentInboxRow
elif not BMConfigParser().has_section(toAddressAtCurrentInboxRow): elif not app.core.config.has_section(toAddressAtCurrentInboxRow):
QtGui.QMessageBox.information( QtGui.QMessageBox.information(
self, _translate("MainWindow", "Address is gone"), self, _translate("MainWindow", "Address is gone"),
_translate( _translate(
@ -2963,7 +2971,7 @@ class MyForm(settingsmixin.SMainWindow):
"Bitmessage cannot find your address %1. Perhaps you" "Bitmessage cannot find your address %1. Perhaps you"
" removed it?" " removed it?"
).arg(toAddressAtCurrentInboxRow), QtGui.QMessageBox.Ok) ).arg(toAddressAtCurrentInboxRow), QtGui.QMessageBox.Ok)
elif not BMConfigParser().getboolean( elif not app.core.config.getboolean(
toAddressAtCurrentInboxRow, 'enabled'): toAddressAtCurrentInboxRow, 'enabled'):
QtGui.QMessageBox.information( QtGui.QMessageBox.information(
self, _translate("MainWindow", "Address disabled"), self, _translate("MainWindow", "Address disabled"),
@ -3053,7 +3061,7 @@ class MyForm(settingsmixin.SMainWindow):
queryreturn = sqlQuery('''select * from blacklist where address=?''', queryreturn = sqlQuery('''select * from blacklist where address=?''',
addressAtCurrentInboxRow) addressAtCurrentInboxRow)
if queryreturn == []: if queryreturn == []:
label = "\"" + tableWidget.item(currentInboxRow, 2).subject + "\" in " + BMConfigParser().get(recipientAddress, "label") label = "\"" + tableWidget.item(currentInboxRow, 2).subject + "\" in " + app.core.config.get(recipientAddress, "label")
sqlExecute('''INSERT INTO blacklist VALUES (?,?, ?)''', sqlExecute('''INSERT INTO blacklist VALUES (?,?, ?)''',
label, label,
addressAtCurrentInboxRow, True) addressAtCurrentInboxRow, True)
@ -3217,9 +3225,12 @@ class MyForm(settingsmixin.SMainWindow):
queryreturn = sqlQuery('''select ackdata FROM sent WHERE status='forcepow' ''') queryreturn = sqlQuery('''select ackdata FROM sent WHERE status='forcepow' ''')
for row in queryreturn: for row in queryreturn:
ackdata, = row ackdata, = row
queues.UISignalQueue.put(('updateSentItemStatusByAckdata', ( app.core.queues.UISignalQueue.put((
ackdata, 'Overriding maximum-difficulty setting. Work queued.'))) 'updateSentItemStatusByAckdata', (
queues.workerQueue.put(('sendmessage', '')) ackdata,
'Overriding maximum-difficulty setting. Work queued.')
))
app.core.queues.workerQueue.put(('sendmessage', ''))
def on_action_SentClipboard(self): def on_action_SentClipboard(self):
currentRow = self.ui.tableWidgetInbox.currentRow() currentRow = self.ui.tableWidgetInbox.currentRow()
@ -3570,12 +3581,12 @@ class MyForm(settingsmixin.SMainWindow):
" delete the channel?" " delete the channel?"
), QtGui.QMessageBox.Yes | QtGui.QMessageBox.No ), QtGui.QMessageBox.Yes | QtGui.QMessageBox.No
) == QtGui.QMessageBox.Yes: ) == QtGui.QMessageBox.Yes:
BMConfigParser().remove_section(str(account.address)) app.core.config.remove_section(str(account.address))
else: else:
return return
else: else:
return return
BMConfigParser().save() app.core.config.save()
shared.reloadMyAddressHashes() shared.reloadMyAddressHashes()
self.rerenderAddressBook() self.rerenderAddressBook()
self.rerenderComboBoxSendFrom() self.rerenderComboBoxSendFrom()
@ -3591,8 +3602,8 @@ class MyForm(settingsmixin.SMainWindow):
account.setEnabled(True) account.setEnabled(True)
def enableIdentity(self, address): def enableIdentity(self, address):
BMConfigParser().set(address, 'enabled', 'true') app.core.config.set(address, 'enabled', 'true')
BMConfigParser().save() app.core.config.save()
shared.reloadMyAddressHashes() shared.reloadMyAddressHashes()
self.rerenderAddressBook() self.rerenderAddressBook()
@ -3603,8 +3614,8 @@ class MyForm(settingsmixin.SMainWindow):
account.setEnabled(False) account.setEnabled(False)
def disableIdentity(self, address): def disableIdentity(self, address):
BMConfigParser().set(str(address), 'enabled', 'false') app.core.config.set(str(address), 'enabled', 'false')
BMConfigParser().save() app.core.config.save()
shared.reloadMyAddressHashes() shared.reloadMyAddressHashes()
self.rerenderAddressBook() self.rerenderAddressBook()
@ -3657,9 +3668,11 @@ class MyForm(settingsmixin.SMainWindow):
# TODO: reuse utils # TODO: reuse utils
def setAvatar(self, addressAtCurrentRow): def setAvatar(self, addressAtCurrentRow):
if not os.path.exists(state.appdata + 'avatars/'): destination = app.core.state.appdata + 'avatars/'
os.makedirs(state.appdata + 'avatars/') if not os.path.exists(destination):
hash = hashlib.md5(addBMIfNotPresent(addressAtCurrentRow)).hexdigest() os.makedirs(destination)
addrhash = hashlib.md5(
addBMIfNotPresent(addressAtCurrentRow)).hexdigest()
extensions = [ extensions = [
'PNG', 'GIF', 'JPG', 'JPEG', 'SVG', 'BMP', 'MNG', 'PBM', 'PNG', 'GIF', 'JPG', 'JPEG', 'SVG', 'BMP', 'MNG', 'PBM',
'PGM', 'PPM', 'TIFF', 'XBM', 'XPM', 'TGA'] 'PGM', 'PPM', 'TIFF', 'XBM', 'XPM', 'TGA']
@ -3685,8 +3698,9 @@ class MyForm(settingsmixin.SMainWindow):
for ext in extensions: for ext in extensions:
filters += [names[ext] + ' (*.' + ext.lower() + ')'] filters += [names[ext] + ' (*.' + ext.lower() + ')']
all_images_filter += ['*.' + ext.lower()] all_images_filter += ['*.' + ext.lower()]
upper = state.appdata + 'avatars/' + hash + '.' + ext.upper() upper = lower = destination + addrhash
lower = state.appdata + 'avatars/' + hash + '.' + ext.lower() upper += ext.upper()
lower += 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):
@ -3697,8 +3711,9 @@ class MyForm(settingsmixin.SMainWindow):
self, _translate("MainWindow", "Set avatar..."), self, _translate("MainWindow", "Set avatar..."),
filter=';;'.join(filters) filter=';;'.join(filters)
) )
# determine the correct filename (note that avatars don't use the suffix) # determine the correct filename
destination = state.appdata + 'avatars/' + hash + '.' + sourcefile.split('.')[-1] # (note that avatars don't use the suffix)
destination += '.' + 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
@ -3765,7 +3780,7 @@ class MyForm(settingsmixin.SMainWindow):
if not sourcefile: if not sourcefile:
return return
destdir = os.path.join(state.appdata, 'sounds') destdir = os.path.join(app.core.state.appdata, 'sounds')
destfile = unicode(addr) + os.path.splitext(sourcefile)[-1] destfile = unicode(addr) + os.path.splitext(sourcefile)[-1]
destination = os.path.join(destdir, destfile) destination = os.path.join(destdir, destfile)
@ -4087,7 +4102,7 @@ class MyForm(settingsmixin.SMainWindow):
# Check to see whether we can connect to namecoin. # Check to see whether we can connect to namecoin.
# Hide the 'Fetch Namecoin ID' button if we can't. # Hide the 'Fetch Namecoin ID' button if we can't.
if BMConfigParser().safeGetBoolean( if app.core.config.safeGetBoolean(
'bitmessagesettings', 'dontconnect' 'bitmessagesettings', 'dontconnect'
) or self.namecoin.test()[0] == 'failed': ) or self.namecoin.test()[0] == 'failed':
logger.warning( logger.warning(
@ -4175,9 +4190,10 @@ def init():
return app return app
def run(): def run(parent):
global myapp global myapp
app = init() app = init()
app.core = parent
myapp = MyForm() myapp = MyForm()
myapp.appIndicatorInit(app) myapp.appIndicatorInit(app)
@ -4186,13 +4202,13 @@ def run():
myapp.showConnectDialog() # ask the user if we may connect myapp.showConnectDialog() # ask the user if we may connect
# try: # try:
# if BMConfigParser().get('bitmessagesettings', 'mailchuck') < 1: # if app.core.config.get('bitmessagesettings', 'mailchuck') < 1:
# myapp.showMigrationWizard(BMConfigParser().get('bitmessagesettings', 'mailchuck')) # myapp.showMigrationWizard(app.core.config.get('bitmessagesettings', 'mailchuck'))
# except: # except:
# myapp.showMigrationWizard(0) # myapp.showMigrationWizard(0)
# only show after wizards and connect dialogs have completed # only show after wizards and connect dialogs have completed
if not BMConfigParser().getboolean('bitmessagesettings', 'startintray'): if not app.core.config.getboolean('bitmessagesettings', 'startintray'):
myapp.show() myapp.show()
app.exec_() app.exec_()

View File

@ -2,10 +2,8 @@ from PyQt4 import QtCore, QtGui
import widgets import widgets
from addresses import addBMIfNotPresent from addresses import addBMIfNotPresent
from bmconfigparser import BMConfigParser
from dialogs import AddAddressDialog from dialogs import AddAddressDialog
from helper_sql import sqlExecute, sqlQuery from helper_sql import sqlExecute, sqlQuery
from queues import UISignalQueue
from retranslateui import RetranslateMixin from retranslateui import RetranslateMixin
from tr import _translate from tr import _translate
from uisignaler import UISignaler from uisignaler import UISignaler
@ -17,6 +15,10 @@ class Blacklist(QtGui.QWidget, RetranslateMixin):
super(Blacklist, self).__init__(parent) super(Blacklist, self).__init__(parent)
widgets.load('blacklist.ui', self) widgets.load('blacklist.ui', self)
core = QtGui.QApplication.instance().core
self.config = core.config
self.queue = core.queues.UISignalQueue
QtCore.QObject.connect(self.radioButtonBlacklist, QtCore.SIGNAL( QtCore.QObject.connect(self.radioButtonBlacklist, QtCore.SIGNAL(
"clicked()"), self.click_radioButtonBlacklist) "clicked()"), self.click_radioButtonBlacklist)
QtCore.QObject.connect(self.radioButtonWhitelist, QtCore.SIGNAL( QtCore.QObject.connect(self.radioButtonWhitelist, QtCore.SIGNAL(
@ -39,17 +41,17 @@ class Blacklist(QtGui.QWidget, RetranslateMixin):
"rerenderBlackWhiteList()"), self.rerenderBlackWhiteList) "rerenderBlackWhiteList()"), self.rerenderBlackWhiteList)
def click_radioButtonBlacklist(self): def click_radioButtonBlacklist(self):
if BMConfigParser().get('bitmessagesettings', 'blackwhitelist') == 'white': if self.config.get('bitmessagesettings', 'blackwhitelist') == 'white':
BMConfigParser().set('bitmessagesettings', 'blackwhitelist', 'black') self.config.set('bitmessagesettings', 'blackwhitelist', 'black')
BMConfigParser().save() self.config.save()
# self.tableWidgetBlacklist.clearContents() # self.tableWidgetBlacklist.clearContents()
self.tableWidgetBlacklist.setRowCount(0) self.tableWidgetBlacklist.setRowCount(0)
self.rerenderBlackWhiteList() self.rerenderBlackWhiteList()
def click_radioButtonWhitelist(self): def click_radioButtonWhitelist(self):
if BMConfigParser().get('bitmessagesettings', 'blackwhitelist') == 'black': if self.config.get('bitmessagesettings', 'blackwhitelist') == 'black':
BMConfigParser().set('bitmessagesettings', 'blackwhitelist', 'white') self.config.set('bitmessagesettings', 'blackwhitelist', 'white')
BMConfigParser().save() self.config.save()
# self.tableWidgetBlacklist.clearContents() # self.tableWidgetBlacklist.clearContents()
self.tableWidgetBlacklist.setRowCount(0) self.tableWidgetBlacklist.setRowCount(0)
self.rerenderBlackWhiteList() self.rerenderBlackWhiteList()
@ -65,7 +67,7 @@ class Blacklist(QtGui.QWidget, RetranslateMixin):
# address book. The user cannot add it again or else it will # address book. The user cannot add it again or else it will
# cause problems when updating and deleting the entry. # cause problems when updating and deleting the entry.
t = (address,) t = (address,)
if BMConfigParser().get('bitmessagesettings', 'blackwhitelist') == 'black': if self.config.get('bitmessagesettings', 'blackwhitelist') == 'black':
sql = '''select * from blacklist where address=?''' sql = '''select * from blacklist where address=?'''
else: else:
sql = '''select * from whitelist where address=?''' sql = '''select * from whitelist where address=?'''
@ -83,13 +85,13 @@ class Blacklist(QtGui.QWidget, RetranslateMixin):
self.tableWidgetBlacklist.setItem(0, 1, newItem) self.tableWidgetBlacklist.setItem(0, 1, newItem)
self.tableWidgetBlacklist.setSortingEnabled(True) self.tableWidgetBlacklist.setSortingEnabled(True)
t = (str(self.NewBlacklistDialogInstance.lineEditLabel.text().toUtf8()), address, True) t = (str(self.NewBlacklistDialogInstance.lineEditLabel.text().toUtf8()), address, True)
if BMConfigParser().get('bitmessagesettings', 'blackwhitelist') == 'black': if self.config.get('bitmessagesettings', 'blackwhitelist') == 'black':
sql = '''INSERT INTO blacklist VALUES (?,?,?)''' sql = '''INSERT INTO blacklist VALUES (?,?,?)'''
else: else:
sql = '''INSERT INTO whitelist VALUES (?,?,?)''' sql = '''INSERT INTO whitelist VALUES (?,?,?)'''
sqlExecute(sql, *t) sqlExecute(sql, *t)
else: else:
UISignalQueue.put(( self.queue.put((
'updateStatusBar', 'updateStatusBar',
_translate( _translate(
"MainWindow", "MainWindow",
@ -98,7 +100,7 @@ class Blacklist(QtGui.QWidget, RetranslateMixin):
" if you want.") " if you want.")
)) ))
else: else:
UISignalQueue.put(( self.queue.put((
'updateStatusBar', 'updateStatusBar',
_translate( _translate(
"MainWindow", "MainWindow",
@ -158,12 +160,12 @@ class Blacklist(QtGui.QWidget, RetranslateMixin):
def rerenderBlackWhiteList(self): def rerenderBlackWhiteList(self):
tabs = self.parent().parent() tabs = self.parent().parent()
if BMConfigParser().get('bitmessagesettings', 'blackwhitelist') == 'black': if self.config.get('bitmessagesettings', 'blackwhitelist') == 'black':
tabs.setTabText(tabs.indexOf(self), _translate('blacklist', 'Blacklist')) tabs.setTabText(tabs.indexOf(self), _translate('blacklist', 'Blacklist'))
else: else:
tabs.setTabText(tabs.indexOf(self), _translate('blacklist', 'Whitelist')) tabs.setTabText(tabs.indexOf(self), _translate('blacklist', 'Whitelist'))
self.tableWidgetBlacklist.setRowCount(0) self.tableWidgetBlacklist.setRowCount(0)
listType = BMConfigParser().get('bitmessagesettings', 'blackwhitelist') listType = self.config.get('bitmessagesettings', 'blackwhitelist')
if listType == 'black': if listType == 'black':
queryreturn = sqlQuery('''SELECT label, address, enabled FROM blacklist''') queryreturn = sqlQuery('''SELECT label, address, enabled FROM blacklist''')
else: else:
@ -195,7 +197,7 @@ class Blacklist(QtGui.QWidget, RetranslateMixin):
currentRow, 0).text().toUtf8() currentRow, 0).text().toUtf8()
addressAtCurrentRow = self.tableWidgetBlacklist.item( addressAtCurrentRow = self.tableWidgetBlacklist.item(
currentRow, 1).text() currentRow, 1).text()
if BMConfigParser().get('bitmessagesettings', 'blackwhitelist') == 'black': if self.config.get('bitmessagesettings', 'blackwhitelist') == 'black':
sqlExecute( sqlExecute(
'''DELETE FROM blacklist WHERE label=? AND address=?''', '''DELETE FROM blacklist WHERE label=? AND address=?''',
str(labelAtCurrentRow), str(addressAtCurrentRow)) str(labelAtCurrentRow), str(addressAtCurrentRow))
@ -224,7 +226,7 @@ class Blacklist(QtGui.QWidget, RetranslateMixin):
currentRow, 0).setTextColor(QtGui.QApplication.palette().text().color()) currentRow, 0).setTextColor(QtGui.QApplication.palette().text().color())
self.tableWidgetBlacklist.item( self.tableWidgetBlacklist.item(
currentRow, 1).setTextColor(QtGui.QApplication.palette().text().color()) currentRow, 1).setTextColor(QtGui.QApplication.palette().text().color())
if BMConfigParser().get('bitmessagesettings', 'blackwhitelist') == 'black': if self.config.get('bitmessagesettings', 'blackwhitelist') == 'black':
sqlExecute( sqlExecute(
'''UPDATE blacklist SET enabled=1 WHERE address=?''', '''UPDATE blacklist SET enabled=1 WHERE address=?''',
str(addressAtCurrentRow)) str(addressAtCurrentRow))
@ -241,7 +243,7 @@ class Blacklist(QtGui.QWidget, RetranslateMixin):
currentRow, 0).setTextColor(QtGui.QColor(128, 128, 128)) currentRow, 0).setTextColor(QtGui.QColor(128, 128, 128))
self.tableWidgetBlacklist.item( self.tableWidgetBlacklist.item(
currentRow, 1).setTextColor(QtGui.QColor(128, 128, 128)) currentRow, 1).setTextColor(QtGui.QColor(128, 128, 128))
if BMConfigParser().get('bitmessagesettings', 'blackwhitelist') == 'black': if self.config.get('bitmessagesettings', 'blackwhitelist') == 'black':
sqlExecute( sqlExecute(
'''UPDATE blacklist SET enabled=0 WHERE address=?''', str(addressAtCurrentRow)) '''UPDATE blacklist SET enabled=0 WHERE address=?''', str(addressAtCurrentRow))
else: else:

View File

@ -13,10 +13,7 @@ import defaults
import namecoin import namecoin
import openclpow import openclpow
import paths import paths
import queues
import state
import widgets import widgets
from bmconfigparser import BMConfigParser
from helper_sql import sqlExecute, sqlStoredProcedure from helper_sql import sqlExecute, sqlStoredProcedure
from helper_startup import start_proxyconfig from helper_startup import start_proxyconfig
from network import knownnodes from network import knownnodes
@ -45,7 +42,12 @@ class SettingsDialog(QtGui.QDialog):
self.parent = parent self.parent = parent
self.firstrun = firstrun self.firstrun = firstrun
self.config = BMConfigParser()
core = QtGui.QApplication.instance().core
self.config = core.config
self.state = core.state
self.workerQueue = core.queues.workerQueue
self.net_restart_needed = False self.net_restart_needed = False
self.timer = QtCore.QTimer() self.timer = QtCore.QTimer()
@ -108,7 +110,7 @@ class SettingsDialog(QtGui.QDialog):
self.checkBoxReplyBelow.setChecked( self.checkBoxReplyBelow.setChecked(
config.safeGetBoolean('bitmessagesettings', 'replybelow')) config.safeGetBoolean('bitmessagesettings', 'replybelow'))
if state.appdata == paths.lookupExeFolder(): if self.state.appdata == paths.lookupExeFolder():
self.checkBoxPortableMode.setChecked(True) self.checkBoxPortableMode.setChecked(True)
else: else:
try: try:
@ -342,7 +344,7 @@ class SettingsDialog(QtGui.QDialog):
proxytype_index = self.comboBoxProxyType.currentIndex() proxytype_index = self.comboBoxProxyType.currentIndex()
if proxytype_index == 0: if proxytype_index == 0:
if self._proxy_type and state.statusIconColor != 'red': if self._proxy_type and self.state.statusIconColor != 'red':
self.net_restart_needed = True self.net_restart_needed = True
elif state.statusIconColor == 'red' and self.config.safeGetBoolean('bitmessagesettings', 'dontconnect'): elif state.statusIconColor == 'red' and self.config.safeGetBoolean('bitmessagesettings', 'dontconnect'):
self.net_restart_needed = False self.net_restart_needed = False
@ -428,7 +430,7 @@ class SettingsDialog(QtGui.QDialog):
self.config.set( self.config.set(
'bitmessagesettings', 'opencl', 'bitmessagesettings', 'opencl',
str(self.comboBoxOpenCL.currentText())) str(self.comboBoxOpenCL.currentText()))
queues.workerQueue.put(('resetPoW', '')) self.workerQueue.put(('resetPoW', ''))
acceptableDifficultyChanged = False acceptableDifficultyChanged = False
@ -475,7 +477,7 @@ class SettingsDialog(QtGui.QDialog):
sqlExecute( sqlExecute(
"UPDATE sent SET status='msgqueued'" "UPDATE sent SET status='msgqueued'"
" WHERE status='toodifficult'") " WHERE status='toodifficult'")
queues.workerQueue.put(('sendmessage', '')) self.workerQueue.put(('sendmessage', ''))
stopResendingDefaults = False stopResendingDefaults = False
@ -486,7 +488,7 @@ class SettingsDialog(QtGui.QDialog):
# default behavior. The input is blank/blank # default behavior. The input is blank/blank
self.config.set('bitmessagesettings', 'stopresendingafterxdays', '') self.config.set('bitmessagesettings', 'stopresendingafterxdays', '')
self.config.set('bitmessagesettings', 'stopresendingafterxmonths', '') self.config.set('bitmessagesettings', 'stopresendingafterxmonths', '')
state.maximumLengthOfTimeToBotherResendingMessages = float('inf') self.state.maximumLengthOfTimeToBotherResendingMessages = float('inf')
stopResendingDefaults = True stopResendingDefaults = True
try: try:
@ -501,9 +503,9 @@ class SettingsDialog(QtGui.QDialog):
months = 0.0 months = 0.0
if days >= 0 and months >= 0 and not stopResendingDefaults: if days >= 0 and months >= 0 and not stopResendingDefaults:
state.maximumLengthOfTimeToBotherResendingMessages = \ self.state.maximumLengthOfTimeToBotherResendingMessages = \
days * 24 * 60 * 60 + months * 60 * 60 * 24 * 365 / 12 days * 24 * 60 * 60 + months * 60 * 60 * 24 * 365 / 12
if state.maximumLengthOfTimeToBotherResendingMessages < 432000: if self.state.maximumLengthOfTimeToBotherResendingMessages < 432000:
# If the time period is less than 5 hours, we give # If the time period is less than 5 hours, we give
# zero values to all fields. No message will be sent again. # zero values to all fields. No message will be sent again.
QtGui.QMessageBox.about( QtGui.QMessageBox.about(
@ -520,7 +522,7 @@ class SettingsDialog(QtGui.QDialog):
'bitmessagesettings', 'stopresendingafterxdays', '0') 'bitmessagesettings', 'stopresendingafterxdays', '0')
self.config.set( self.config.set(
'bitmessagesettings', 'stopresendingafterxmonths', '0') 'bitmessagesettings', 'stopresendingafterxmonths', '0')
state.maximumLengthOfTimeToBotherResendingMessages = 0.0 self.state.maximumLengthOfTimeToBotherResendingMessages = 0.0
else: else:
self.config.set( self.config.set(
'bitmessagesettings', 'stopresendingafterxdays', str(days)) 'bitmessagesettings', 'stopresendingafterxdays', str(days))
@ -542,7 +544,7 @@ class SettingsDialog(QtGui.QDialog):
self.parent.updateStartOnLogon() self.parent.updateStartOnLogon()
if ( if (
state.appdata != paths.lookupExeFolder() self.state.appdata != paths.lookupExeFolder()
and self.checkBoxPortableMode.isChecked() and self.checkBoxPortableMode.isChecked()
): ):
# If we are NOT using portable mode now but the user selected # If we are NOT using portable mode now but the user selected
@ -553,10 +555,10 @@ class SettingsDialog(QtGui.QDialog):
self.config.write(configfile) self.config.write(configfile)
# Write the knownnodes.dat file to disk in the new location # Write the knownnodes.dat file to disk in the new location
knownnodes.saveKnownNodes(paths.lookupExeFolder()) knownnodes.saveKnownNodes(paths.lookupExeFolder())
os.remove(state.appdata + 'keys.dat') os.remove(self.state.appdata + 'keys.dat')
os.remove(state.appdata + 'knownnodes.dat') os.remove(self.state.appdata + 'knownnodes.dat')
previousAppdataLocation = state.appdata previousAppdataLocation = self.state.appdata
state.appdata = paths.lookupExeFolder() self.state.appdata = paths.lookupExeFolder()
debug.resetLogging() debug.resetLogging()
try: try:
os.remove(previousAppdataLocation + 'debug.log') os.remove(previousAppdataLocation + 'debug.log')
@ -565,19 +567,19 @@ class SettingsDialog(QtGui.QDialog):
pass pass
if ( if (
state.appdata == paths.lookupExeFolder() self.state.appdata == paths.lookupExeFolder()
and not self.checkBoxPortableMode.isChecked() and not self.checkBoxPortableMode.isChecked()
): ):
# If we ARE using portable mode now but the user selected # If we ARE using portable mode now but the user selected
# that we shouldn't... # that we shouldn't...
state.appdata = paths.lookupAppdataFolder() self.state.appdata = paths.lookupAppdataFolder()
if not os.path.exists(state.appdata): if not os.path.exists(self.state.appdata):
os.makedirs(state.appdata) os.makedirs(self.state.appdata)
sqlStoredProcedure('movemessagstoappdata') sqlStoredProcedure('movemessagstoappdata')
# Write the keys.dat file to disk in the new location # Write the keys.dat file to disk in the new location
self.config.save() self.config.save()
# Write the knownnodes.dat file to disk in the new location # Write the knownnodes.dat file to disk in the new location
knownnodes.saveKnownNodes(state.appdata) knownnodes.saveKnownNodes(self.state.appdata)
os.remove(paths.lookupExeFolder() + 'keys.dat') os.remove(paths.lookupExeFolder() + 'keys.dat')
os.remove(paths.lookupExeFolder() + 'knownnodes.dat') os.remove(paths.lookupExeFolder() + 'knownnodes.dat')
debug.resetLogging() debug.resetLogging()