commit 2c0814f0d38aa97f84623267fba9860d79c453ed
parent 404c1f84d2d0d84e30e0be00784da5585fdab6a8
Author: ThomasV <thomasv@gitorious>
Date: Tue, 24 Sep 2013 10:06:03 +0200
simplify gui names
Diffstat:
29 files changed, 3324 insertions(+), 4334 deletions(-)
diff --git a/electrum b/electrum
@@ -149,9 +149,9 @@ if __name__ == '__main__':
if cmd == 'gui':
gui_name = config.get('gui','classic')
- if gui_name in ['lite', 'qt']: gui_name = 'classic'
+ if gui_name in ['lite', 'classic']: gui_name = 'qt'
try:
- gui = __import__('electrum_gui.gui_' + gui_name, fromlist=['electrum_gui'])
+ gui = __import__('electrum_gui.' + gui_name, fromlist=['electrum_gui'])
except ImportError:
traceback.print_exc(file=sys.stdout)
sys.exit()
diff --git a/gui/gui_android.py b/gui/android.py
diff --git a/gui/gui_gtk.py b/gui/gtk.py
diff --git a/gui/gui_classic/__init__.py b/gui/gui_classic/__init__.py
@@ -1,172 +0,0 @@
-#!/usr/bin/env python
-#
-# Electrum - lightweight Bitcoin client
-# Copyright (C) 2012 thomasv@gitorious
-#
-# This program is free software: you can redistribute it and/or modify
-# it under the terms of the GNU General Public License as published by
-# the Free Software Foundation, either version 3 of the License, or
-# (at your option) any later version.
-#
-# This program is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-# GNU General Public License for more details.
-#
-# You should have received a copy of the GNU General Public License
-# along with this program. If not, see <http://www.gnu.org/licenses/>.
-
-import sys, time, datetime, re, threading
-from electrum.i18n import _, set_language
-from electrum.util import print_error, print_msg, parse_url
-from electrum.plugins import run_hook
-import os.path, json, ast, traceback
-import shutil
-
-
-try:
- import PyQt4
-except:
- sys.exit("Error: Could not import PyQt4 on Linux systems, you may try 'sudo apt-get install python-qt4'")
-
-from PyQt4.QtGui import *
-from PyQt4.QtCore import *
-import PyQt4.QtCore as QtCore
-
-from electrum import WalletStorage, Wallet
-from electrum.i18n import _
-from electrum.bitcoin import MIN_RELAY_TX_FEE
-
-try:
- import icons_rc
-except:
- sys.exit("Error: Could not import icons_rc.py, please generate it with: 'pyrcc4 icons.qrc -o gui/gui_classic/icons_rc.py'")
-
-from qt_util import *
-from main_window import ElectrumWindow
-from electrum.plugins import init_plugins
-
-class Timer(QtCore.QThread):
- def run(self):
- while True:
- self.emit(QtCore.SIGNAL('timersignal'))
- time.sleep(0.5)
-
-class OpenFileEventFilter(QObject):
- def __init__(self, windows):
- self.windows = windows
- super(OpenFileEventFilter, self).__init__()
-
- def eventFilter(self, obj, event):
- if event.type() == QtCore.QEvent.FileOpen:
- if len(self.windows) >= 1:
- self.windows[0].set_url(event.url().toString())
- return True
- return False
-
-
-class ElectrumGui:
-
- def __init__(self, config, network, app=None):
- self.network = network
- self.config = config
- self.windows = []
- self.efilter = OpenFileEventFilter(self.windows)
- if app is None:
- self.app = QApplication(sys.argv)
- self.app.installEventFilter(self.efilter)
-
- init_plugins(self)
-
-
-
- def expand(self):
- """Hide the lite mode window and show pro-mode."""
- self.config.set_key('lite_mode', False, True)
- self.mini.hide()
- self.expert.show()
-
- def minimize(self):
- self.config.set_key('lite_mode', True, True)
- self.expert.hide()
- self.mini.show()
-
- def init_lite(self, wallet, expert, url):
- import lite_window
- if not self.check_qt_version():
- return
-
- actuator = lite_window.MiniActuator(self.config, wallet)
- # Should probably not modify the current path but instead
- # change the behaviour of rsrc(...)
- old_path = QDir.currentPath()
- actuator.load_theme()
-
- mini = lite_window.MiniWindow(actuator, self.expand, self.config)
- driver = lite_window.MiniDriver(wallet, mini)
-
- # Reset path back to original value now that loading the GUI
- # is completed.
- QDir.setCurrent(old_path)
- if url:
- payto, amount, label, message, signature, identity, url = parse_url(url)
- mini.set_payment_fields(payto, amount)
-
- return mini
-
- def check_qt_version(self):
- qtVersion = qVersion()
- return int(qtVersion[0]) >= 4 and int(qtVersion[2]) >= 7
-
-
- def main(self, url):
-
- storage = WalletStorage(self.config)
- if not storage.file_exists:
- import installwizard
- wizard = installwizard.InstallWizard(self.config, self.network, storage)
- wallet = wizard.run()
- if not wallet:
- exit()
- else:
- wallet = Wallet(storage)
-
- wallet.start_threads(self.network)
-
-
- self.main_window = w = ElectrumWindow(self.config, self.network, self.minimize)
-
- # plugins that need to change the GUI do it here
- run_hook('init')
-
- w.load_wallet(wallet)
-
- s = Timer()
- s.start()
-
- self.windows.append(w)
- if url: w.set_url(url)
- w.app = self.app
- w.connect_slots(s)
- w.update_wallet()
-
- self.expert = w
- self.mini = self.init_lite(wallet, w, url)
-
- if self.config.get('lite_mode'):
- if not self.mini:
- QMessageBox.warning(None,"Could not start Lite GUI.", "Electrum was unable to load the 'Lite GUI' because it needs Qt version >= 4.7.\nChanging your config to use the 'Classic' GUI")
- self.config.set_key('lite_mode', False, True)
- sys.exit(0)
- else:
- self.minimize()
- else:
- w.show()
- if self.mini:
- self.mini.hide()
-
- self.app.exec_()
-
- wallet.stop_threads()
-
-
diff --git a/gui/gui_classic/lite_window.py b/gui/gui_classic/lite_window.py
@@ -1,915 +0,0 @@
-import sys
-
-# Let's do some dep checking and handle missing ones gracefully
-try:
- from PyQt4.QtCore import *
- from PyQt4.QtGui import *
- from PyQt4.Qt import Qt
- import PyQt4.QtCore as QtCore
-
-except ImportError:
- print "You need to have PyQT installed to run Electrum in graphical mode."
- print "If you have pip installed try 'sudo pip install pyqt' if you are on Debian/Ubuntu try 'sudo apt-get install python-qt4'."
- sys.exit(0)
-
-from decimal import Decimal as D
-from electrum.util import get_resource_path as rsrc
-from electrum.bitcoin import is_valid
-from electrum.i18n import _
-import decimal
-import json
-import os.path
-import random
-import re
-import time
-from electrum.wallet import Wallet, WalletStorage
-import webbrowser
-import history_widget
-import receiving_widget
-from electrum import util
-import csv
-import datetime
-
-from electrum.version import ELECTRUM_VERSION as electrum_version
-from electrum.util import format_satoshis, age
-
-from main_window import ElectrumWindow
-import shutil
-
-from qt_util import *
-
-bitcoin = lambda v: v * 100000000
-
-def IconButton(filename, parent=None):
- pixmap = QPixmap(filename)
- icon = QIcon(pixmap)
- return QPushButton(icon, "", parent)
-
-class Timer(QThread):
- def run(self):
- while True:
- self.emit(SIGNAL('timersignal'))
- time.sleep(0.5)
-
-def resize_line_edit_width(line_edit, text_input):
- metrics = QFontMetrics(qApp.font())
- # Create an extra character to add some space on the end
- text_input += "A"
- line_edit.setMinimumWidth(metrics.width(text_input))
-
-def load_theme_name(theme_path):
- try:
- with open(os.path.join(theme_path, "name.cfg")) as name_cfg_file:
- return name_cfg_file.read().rstrip("\n").strip()
- except IOError:
- return None
-
-
-def theme_dirs_from_prefix(prefix):
- if not os.path.exists(prefix):
- return []
- theme_paths = {}
- for potential_theme in os.listdir(prefix):
- theme_full_path = os.path.join(prefix, potential_theme)
- theme_css = os.path.join(theme_full_path, "style.css")
- if not os.path.exists(theme_css):
- continue
- theme_name = load_theme_name(theme_full_path)
- if theme_name is None:
- continue
- theme_paths[theme_name] = prefix, potential_theme
- return theme_paths
-
-def load_theme_paths():
- theme_paths = {}
- prefixes = (util.local_data_dir(), util.appdata_dir())
- for prefix in prefixes:
- theme_paths.update(theme_dirs_from_prefix(prefix))
- return theme_paths
-
-
-def csv_transaction(wallet):
- try:
- select_export = _('Select file to export your wallet transactions to')
- fileName = QFileDialog.getSaveFileName(QWidget(), select_export, os.path.expanduser('~/electrum-history.csv'), "*.csv")
- if fileName:
- with open(fileName, "w+") as csvfile:
- transaction = csv.writer(csvfile)
- transaction.writerow(["transaction_hash","label", "confirmations", "value", "fee", "balance", "timestamp"])
- for item in wallet.get_tx_history():
- tx_hash, confirmations, is_mine, value, fee, balance, timestamp = item
- if confirmations:
- if timestamp is not None:
- try:
- time_string = datetime.datetime.fromtimestamp(timestamp).isoformat(' ')[:-3]
- except [RuntimeError, TypeError, NameError] as reason:
- time_string = "unknown"
- pass
- else:
- time_string = "unknown"
- else:
- time_string = "pending"
-
- if value is not None:
- value_string = format_satoshis(value, True, wallet.num_zeros)
- else:
- value_string = '--'
-
- if fee is not None:
- fee_string = format_satoshis(fee, True, wallet.num_zeros)
- else:
- fee_string = '0'
-
- if tx_hash:
- label, is_default_label = wallet.get_label(tx_hash)
- else:
- label = ""
-
- balance_string = format_satoshis(balance, False, wallet.num_zeros)
- transaction.writerow([tx_hash, label, confirmations, value_string, fee_string, balance_string, time_string])
- QMessageBox.information(None,"CSV Export created", "Your CSV export has been successfully created.")
- except (IOError, os.error), reason:
- export_error_label = _("Electrum was unable to produce a transaction export.")
- QMessageBox.critical(None,_("Unable to create csv"), export_error_label + "\n" + str(reason))
-
-
-
-class TransactionWindow(QDialog):
-
- def set_label(self):
- label = unicode(self.label_edit.text())
- self.parent.wallet.labels[self.tx_id] = label
-
- super(TransactionWindow, self).accept()
-
- def __init__(self, transaction_id, parent):
- super(TransactionWindow, self).__init__()
-
- self.tx_id = str(transaction_id)
- self.parent = parent
-
- self.setModal(True)
- self.resize(200,100)
- self.setWindowTitle(_("Transaction successfully sent"))
-
- self.layout = QGridLayout(self)
- history_label = "%s\n%s" % (_("Your transaction has been sent."), _("Please enter a label for this transaction for future reference."))
- self.layout.addWidget(QLabel(history_label))
-
- self.label_edit = QLineEdit()
- self.label_edit.setPlaceholderText(_("Transaction label"))
- self.label_edit.setObjectName("label_input")
- self.label_edit.setAttribute(Qt.WA_MacShowFocusRect, 0)
- self.label_edit.setFocusPolicy(Qt.ClickFocus)
- self.layout.addWidget(self.label_edit)
-
- self.save_button = QPushButton(_("Save"))
- self.layout.addWidget(self.save_button)
- self.save_button.clicked.connect(self.set_label)
-
- self.exec_()
-
-class MiniWindow(QDialog):
-
- def __init__(self, actuator, expand_callback, config):
- super(MiniWindow, self).__init__()
- tx = "e08115d0f7819aee65b9d24f81ef9d46eb62bb67ddef5318156cbc3ceb7b703e"
-
- self.actuator = actuator
- self.config = config
- self.btc_balance = None
- self.quote_currencies = ["BRL", "CNY", "EUR", "GBP", "RUB", "USD"]
- self.actuator.set_configured_currency(self.set_quote_currency)
- #self.exchanger = exchange_rate.Exchanger(self)
- # Needed because price discovery is done in a different thread
- # which needs to be sent back to this main one to update the GUI
- self.connect(self, SIGNAL("refresh_balance()"), self.refresh_balance)
-
- self.balance_label = BalanceLabel(self.change_quote_currency, self)
- self.balance_label.setObjectName("balance_label")
-
-
- # Bitcoin address code
- self.address_input = QLineEdit()
- self.address_input.setPlaceholderText(_("Enter a Bitcoin address or contact"))
- self.address_input.setObjectName("address_input")
-
- self.address_input.setFocusPolicy(Qt.ClickFocus)
-
- self.address_input.textChanged.connect(self.address_field_changed)
- resize_line_edit_width(self.address_input,
- "1BtaFUr3qVvAmwrsuDuu5zk6e4s2rxd2Gy")
-
- self.address_completions = QStringListModel()
- address_completer = QCompleter(self.address_input)
- address_completer.setCaseSensitivity(False)
- address_completer.setModel(self.address_completions)
- self.address_input.setCompleter(address_completer)
-
- address_layout = QHBoxLayout()
- address_layout.addWidget(self.address_input)
-
- self.amount_input = QLineEdit()
- self.amount_input.setPlaceholderText(_("... and amount"))
- self.amount_input.setObjectName("amount_input")
-
- self.amount_input.setFocusPolicy(Qt.ClickFocus)
- # This is changed according to the user's displayed balance
- self.amount_validator = QDoubleValidator(self.amount_input)
- self.amount_validator.setNotation(QDoubleValidator.StandardNotation)
- self.amount_validator.setDecimals(8)
- self.amount_input.setValidator(self.amount_validator)
-
- # This removes the very ugly OSX highlighting, please leave this in :D
- self.address_input.setAttribute(Qt.WA_MacShowFocusRect, 0)
- self.amount_input.setAttribute(Qt.WA_MacShowFocusRect, 0)
- self.amount_input.textChanged.connect(self.amount_input_changed)
-
- if self.actuator.wallet.seed:
- self.send_button = QPushButton(_("&Send"))
- else:
- self.send_button = QPushButton(_("&Create"))
-
- self.send_button.setObjectName("send_button")
- self.send_button.setDisabled(True);
- self.send_button.clicked.connect(self.send)
-
- # Creating the receive button
- self.switch_button = QPushButton( QIcon(":icons/switchgui.png"),'' )
- self.switch_button.setMaximumWidth(25)
- self.switch_button.setFlat(True)
- self.switch_button.clicked.connect(expand_callback)
-
- main_layout = QGridLayout(self)
-
- main_layout.addWidget(self.balance_label, 0, 0, 1, 3)
- main_layout.addWidget(self.switch_button, 0, 3)
-
- main_layout.addWidget(self.address_input, 1, 0, 1, 4)
- main_layout.addWidget(self.amount_input, 2, 0, 1, 2)
- main_layout.addWidget(self.send_button, 2, 2, 1, 2)
-
- self.send_button.setMaximumWidth(125)
-
- self.history_list = history_widget.HistoryWidget()
- self.history_list.setObjectName("history")
- self.history_list.hide()
- self.history_list.setAlternatingRowColors(True)
-
- main_layout.addWidget(self.history_list, 3, 0, 1, 4)
-
- self.receiving = receiving_widget.ReceivingWidget(self)
- self.receiving.setObjectName("receiving")
-
- # Add to the right side
- self.receiving_box = QGroupBox(_("Select a receiving address"))
- extra_layout = QGridLayout()
-
- # Checkbox to filter used addresses
- hide_used = QCheckBox(_('Hide used addresses'))
- hide_used.setChecked(True)
- hide_used.stateChanged.connect(self.receiving.toggle_used)
-
- # Events for receiving addresses
- self.receiving.clicked.connect(self.receiving.copy_address)
- self.receiving.itemDoubleClicked.connect(self.receiving.edit_label)
- self.receiving.itemChanged.connect(self.receiving.update_label)
-
-
- # Label
- extra_layout.addWidget( QLabel(_('Selecting an address will copy it to the clipboard.') + '\n' + _('Double clicking the label will allow you to edit it.') ),0,0)
-
- extra_layout.addWidget(self.receiving, 1,0)
- extra_layout.addWidget(hide_used, 2,0)
- extra_layout.setColumnMinimumWidth(0,200)
-
- self.receiving_box.setLayout(extra_layout)
- main_layout.addWidget(self.receiving_box,0,4,-1,3)
- self.receiving_box.hide()
-
- self.main_layout = main_layout
-
- quit_shortcut = QShortcut(QKeySequence("Ctrl+Q"), self)
- quit_shortcut.activated.connect(self.close)
- close_shortcut = QShortcut(QKeySequence("Ctrl+W"), self)
- close_shortcut.activated.connect(self.close)
-
- g = self.config.get("winpos-lite",[4, 25, 351, 149])
- self.setGeometry(g[0], g[1], g[2], g[3])
-
- show_hist = self.config.get("gui_show_history",False)
- self.show_history(show_hist)
- show_hist = self.config.get("gui_show_receiving",False)
- self.toggle_receiving_layout(show_hist)
-
- self.setWindowIcon(QIcon(":icons/electrum.png"))
- self.setWindowTitle("Electrum")
- self.setWindowFlags(Qt.Window|Qt.MSWindowsFixedSizeDialogHint)
- self.layout().setSizeConstraint(QLayout.SetFixedSize)
- self.setObjectName("main_window")
-
- self.show()
-
- def context_menu(self):
- view_menu = QMenu()
- themes_menu = view_menu.addMenu(_("&Themes"))
- selected_theme = self.actuator.selected_theme()
- theme_group = QActionGroup(self)
- for theme_name in self.actuator.theme_names():
- theme_action = themes_menu.addAction(theme_name)
- theme_action.setCheckable(True)
- if selected_theme == theme_name:
- theme_action.setChecked(True)
- class SelectThemeFunctor:
- def __init__(self, theme_name, toggle_theme):
- self.theme_name = theme_name
- self.toggle_theme = toggle_theme
- def __call__(self, checked):
- if checked:
- self.toggle_theme(self.theme_name)
- delegate = SelectThemeFunctor(theme_name, self.toggle_theme)
- theme_action.toggled.connect(delegate)
- theme_group.addAction(theme_action)
- view_menu.addSeparator()
-
- show_receiving = view_menu.addAction(_("Show Receiving addresses"))
- show_receiving.setCheckable(True)
- show_receiving.toggled.connect(self.toggle_receiving_layout)
- show_receiving.setChecked(self.config.get("gui_show_receiving",False))
-
- show_history = view_menu.addAction(_("Show History"))
- show_history.setCheckable(True)
- show_history.toggled.connect(self.show_history)
- show_history.setChecked(self.config.get("gui_show_history",False))
-
- return view_menu
-
-
-
- def toggle_theme(self, theme_name):
- old_path = QDir.currentPath()
- self.actuator.change_theme(theme_name)
- # Recompute style globally
- qApp.style().unpolish(self)
- qApp.style().polish(self)
- QDir.setCurrent(old_path)
-
- def closeEvent(self, event):
- g = self.geometry()
- self.config.set_key("winpos-lite", [g.left(),g.top(),g.width(),g.height()],True)
-
- super(MiniWindow, self).closeEvent(event)
- qApp.quit()
-
- def set_payment_fields(self, dest_address, amount):
- self.address_input.setText(dest_address)
- self.address_field_changed(dest_address)
- self.amount_input.setText(amount)
-
- def activate(self):
- pass
-
- def deactivate(self):
- pass
-
- def set_quote_currency(self, currency):
- """Set and display the fiat currency country."""
- if currency not in self.quote_currencies:
- return
- self.quote_currencies.remove(currency)
- self.quote_currencies.insert(0, currency)
- self.refresh_balance()
-
- def change_quote_currency(self, forward=True):
- if forward:
- self.quote_currencies = \
- self.quote_currencies[1:] + self.quote_currencies[0:1]
- else:
- self.quote_currencies = \
- self.quote_currencies[-1:] + self.quote_currencies[0:-1]
- self.actuator.set_config_currency(self.quote_currencies[0])
- self.refresh_balance()
-
- def refresh_balance(self):
- if self.btc_balance is None:
- # Price has been discovered before wallet has been loaded
- # and server connect... so bail.
- return
- self.set_balances(self.btc_balance)
- self.amount_input_changed(self.amount_input.text())
-
- def set_balances(self, btc_balance):
- """Set the bitcoin balance and update the amount label accordingly."""
- self.btc_balance = btc_balance
- quote_text = self.create_quote_text(btc_balance)
- if quote_text:
- quote_text = "(%s)" % quote_text
- btc_balance = "%.4f" % (btc_balance / bitcoin(1))
- self.balance_label.set_balance_text(btc_balance, quote_text)
- self.setWindowTitle("Electrum %s - %s BTC" % (electrum_version, btc_balance))
-
- def amount_input_changed(self, amount_text):
- """Update the number of bitcoins displayed."""
- self.check_button_status()
-
- try:
- amount = D(str(amount_text))
- except decimal.InvalidOperation:
- self.balance_label.show_balance()
- else:
- quote_text = self.create_quote_text(amount * bitcoin(1))
- if quote_text:
- self.balance_label.set_amount_text(quote_text)
- self.balance_label.show_amount()
- else:
- self.balance_label.show_balance()
-
- def create_quote_text(self, btc_balance):
- """Return a string copy of the amount fiat currency the
- user has in bitcoins."""
- quote_currency = self.quote_currencies[0]
- quote_balance = None #self.exchanger.exchange(btc_balance, quote_currency)
- if quote_balance is None:
- quote_text = ""
- else:
- quote_text = "%.2f %s" % ((quote_balance / bitcoin(1)),
- quote_currency)
- return quote_text
-
- def send(self):
- if self.actuator.send(self.address_input.text(),
- self.amount_input.text(), self):
- self.address_input.setText("")
- self.amount_input.setText("")
-
- def check_button_status(self):
- """Check that the bitcoin address is valid and that something
- is entered in the amount before making the send button clickable."""
- try:
- value = D(str(self.amount_input.text())) * 10**8
- except decimal.InvalidOperation:
- value = None
- # self.address_input.property(...) returns a qVariant, not a bool.
- # The == is needed to properly invoke a comparison.
- if (self.address_input.property("isValid") == True and
- value is not None and 0 < value <= self.btc_balance):
- self.send_button.setDisabled(False)
- else:
- self.send_button.setDisabled(True)
-
- def address_field_changed(self, address):
- # label or alias, with address in brackets
- match2 = re.match("(.*?)\s*\<([1-9A-HJ-NP-Za-km-z]{26,})\>",
- address)
- if match2:
- address = match2.group(2)
- self.address_input.setText(address)
-
- if is_valid(address):
- self.check_button_status()
- self.address_input.setProperty("isValid", True)
- self.recompute_style(self.address_input)
- else:
- self.send_button.setDisabled(True)
- self.address_input.setProperty("isValid", False)
- self.recompute_style(self.address_input)
-
- if len(address) == 0:
- self.address_input.setProperty("isValid", None)
- self.recompute_style(self.address_input)
-
- def recompute_style(self, element):
- self.style().unpolish(element)
- self.style().polish(element)
-
- def copy_address(self):
- receive_popup = ReceivePopup(self.receive_button)
- self.actuator.copy_address(receive_popup)
-
- def update_completions(self, completions):
- self.address_completions.setStringList(completions)
-
-
- def update_history(self, tx_history):
-
- self.history_list.empty()
-
- for item in tx_history[-10:]:
- tx_hash, conf, is_mine, value, fee, balance, timestamp = item
- label = self.actuator.wallet.get_label(tx_hash)[0]
- #amount = D(value) / 10**8
- v_str = format_satoshis(value, True)
- self.history_list.append(label, v_str, age(timestamp))
-
- def acceptbit(self):
- self.actuator.acceptbit(self.quote_currencies[0])
-
- def the_website(self):
- webbrowser.open("http://electrum.org")
-
-
- def toggle_receiving_layout(self, toggle_state):
- if toggle_state:
- self.receiving_box.show()
- else:
- self.receiving_box.hide()
- self.config.set_key("gui_show_receiving", toggle_state)
-
- def show_history(self, toggle_state):
- if toggle_state:
- self.main_layout.setRowMinimumHeight(3,200)
- self.history_list.show()
- else:
- self.main_layout.setRowMinimumHeight(3,0)
- self.history_list.hide()
- self.config.set_key("gui_show_history", toggle_state)
-
-class BalanceLabel(QLabel):
-
- SHOW_CONNECTING = 1
- SHOW_BALANCE = 2
- SHOW_AMOUNT = 3
-
- def __init__(self, change_quote_currency, parent=None):
- super(QLabel, self).__init__(_("Connecting..."), parent)
- self.change_quote_currency = change_quote_currency
- self.state = self.SHOW_CONNECTING
- self.balance_text = ""
- self.amount_text = ""
- self.parent = parent
-
- def mousePressEvent(self, event):
- """Change the fiat currency selection if window background is clicked."""
- if self.state != self.SHOW_CONNECTING:
- if event.button() == Qt.LeftButton:
- self.change_quote_currency()
- else:
- position = event.globalPos()
- menu = self.parent.context_menu()
- menu.exec_(position)
-
-
- def set_balance_text(self, btc_balance, quote_text):
- """Set the amount of bitcoins in the gui."""
- if self.state == self.SHOW_CONNECTING:
- self.state = self.SHOW_BALANCE
- self.balance_text = "<span style='font-size: 18pt'>%s</span> <span style='font-size: 10pt'>BTC</span> <span style='font-size: 10pt'>%s</span>" % (btc_balance, quote_text)
- if self.state == self.SHOW_BALANCE:
- self.setText(self.balance_text)
-
- def set_amount_text(self, quote_text):
- self.amount_text = "<span style='font-size: 10pt'>%s</span>" % quote_text
- if self.state == self.SHOW_AMOUNT:
- self.setText(self.amount_text)
-
- def show_balance(self):
- if self.state == self.SHOW_AMOUNT:
- self.state = self.SHOW_BALANCE
- self.setText(self.balance_text)
-
- def show_amount(self):
- if self.state == self.SHOW_BALANCE:
- self.state = self.SHOW_AMOUNT
- self.setText(self.amount_text)
-
-def ok_cancel_buttons(dialog):
- row_layout = QHBoxLayout()
- row_layout.addStretch(1)
- ok_button = QPushButton(_("OK"))
- row_layout.addWidget(ok_button)
- ok_button.clicked.connect(dialog.accept)
- cancel_button = QPushButton(_("Cancel"))
- row_layout.addWidget(cancel_button)
- cancel_button.clicked.connect(dialog.reject)
- return row_layout
-
-class PasswordDialog(QDialog):
-
- def __init__(self, parent):
- super(QDialog, self).__init__(parent)
-
- self.setModal(True)
-
- self.password_input = QLineEdit()
- self.password_input.setEchoMode(QLineEdit.Password)
-
- main_layout = QVBoxLayout(self)
- message = _('Please enter your password')
- main_layout.addWidget(QLabel(message))
-
- grid = QGridLayout()
- grid.setSpacing(8)
- grid.addWidget(QLabel(_('Password')), 1, 0)
- grid.addWidget(self.password_input, 1, 1)
- main_layout.addLayout(grid)
-
- main_layout.addLayout(ok_cancel_buttons(self))
- self.setLayout(main_layout)
-
- def run(self):
- if not self.exec_():
- return
- return unicode(self.password_input.text())
-
-class ReceivePopup(QDialog):
-
- def leaveEvent(self, event):
- self.close()
-
- def setup(self, address):
- label = QLabel(_("Copied your Bitcoin address to the clipboard!"))
- address_display = QLineEdit(address)
- address_display.setReadOnly(True)
- resize_line_edit_width(address_display, address)
-
- main_layout = QVBoxLayout(self)
- main_layout.addWidget(label)
- main_layout.addWidget(address_display)
-
- self.setMouseTracking(True)
- self.setWindowTitle("Electrum - " + _("Receive Bitcoin payment"))
- self.setWindowFlags(Qt.Window|Qt.FramelessWindowHint|
- Qt.MSWindowsFixedSizeDialogHint)
- self.layout().setSizeConstraint(QLayout.SetFixedSize)
- #self.setFrameStyle(QFrame.WinPanel|QFrame.Raised)
- #self.setAlignment(Qt.AlignCenter)
-
- def popup(self):
- parent = self.parent()
- top_left_pos = parent.mapToGlobal(parent.rect().bottomLeft())
- self.move(top_left_pos)
- center_mouse_pos = self.mapToGlobal(self.rect().center())
- QCursor.setPos(center_mouse_pos)
- self.show()
-
-class MiniActuator:
- """Initialize the definitions relating to themes and
- sending/receiving bitcoins."""
-
-
- def __init__(self, config, wallet):
- """Retrieve the gui theme used in previous session."""
- self.config = config
- self.wallet = wallet
- self.theme_name = self.config.get('litegui_theme','Cleanlook')
- self.themes = load_theme_paths()
-
- def load_theme(self):
- """Load theme retrieved from wallet file."""
- try:
- theme_prefix, theme_path = self.themes[self.theme_name]
- except KeyError:
- util.print_error("Theme not found!", self.theme_name)
- return
- QDir.setCurrent(os.path.join(theme_prefix, theme_path))
- with open(rsrc("style.css")) as style_file:
- qApp.setStyleSheet(style_file.read())
-
- def theme_names(self):
- """Sort themes."""
- return sorted(self.themes.keys())
-
- def selected_theme(self):
- """Select theme."""
- return self.theme_name
-
- def change_theme(self, theme_name):
- """Change theme."""
- self.theme_name = theme_name
- self.config.set_key('litegui_theme',theme_name)
- self.load_theme()
-
- def set_configured_currency(self, set_quote_currency):
- """Set the inital fiat currency conversion country (USD/EUR/GBP) in
- the GUI to what it was set to in the wallet."""
- currency = self.config.get('currency')
- # currency can be none when Electrum is used for the first
- # time and no setting has been created yet.
- if currency is not None:
- set_quote_currency(currency)
-
- def set_config_currency(self, conversion_currency):
- """Change the wallet fiat currency country."""
- self.config.set_key('conversion_currency',conversion_currency,True)
-
- def copy_address(self, receive_popup):
- """Copy the wallet addresses into the client."""
- addrs = [addr for addr in self.wallet.addresses(True)
- if not self.wallet.is_change(addr)]
- # Select most recent addresses from gap limit
- addrs = addrs[-self.wallet.gap_limit:]
- copied_address = random.choice(addrs)
- qApp.clipboard().setText(copied_address)
- receive_popup.setup(copied_address)
- receive_popup.popup()
-
- def waiting_dialog(self, f):
- s = Timer()
- s.start()
- w = QDialog()
- w.resize(200, 70)
- w.setWindowTitle('Electrum')
- l = QLabel(_('Sending transaction, please wait.'))
- vbox = QVBoxLayout()
- vbox.addWidget(l)
- w.setLayout(vbox)
- w.show()
- def ff():
- s = f()
- if s: l.setText(s)
- else: w.close()
- w.connect(s, QtCore.SIGNAL('timersignal'), ff)
- w.exec_()
- w.destroy()
-
-
- def send(self, address, amount, parent_window):
- """Send bitcoins to the target address."""
- dest_address = self.fetch_destination(address)
-
- if dest_address is None or not is_valid(dest_address):
- QMessageBox.warning(parent_window, _('Error'),
- _('Invalid Bitcoin Address') + ':\n' + address, _('OK'))
- return False
-
- convert_amount = lambda amount: \
- int(D(unicode(amount)) * bitcoin(1))
- amount = convert_amount(amount)
-
- if self.wallet.use_encryption:
- password_dialog = PasswordDialog(parent_window)
- password = password_dialog.run()
- if not password:
- return
- else:
- password = None
-
- fee = 0
- # 0.1 BTC = 10000000
- if amount < bitcoin(1) / 10:
- # 0.001 BTC
- fee = bitcoin(1) / 1000
-
- try:
- tx = self.wallet.mktx([(dest_address, amount)], password, fee)
- except BaseException as error:
- QMessageBox.warning(parent_window, _('Error'), str(error), _('OK'))
- return False
-
- if tx.is_complete:
- h = self.wallet.send_tx(tx)
-
- self.waiting_dialog(lambda: False if self.wallet.tx_event.isSet() else _("Sending transaction, please wait..."))
-
- status, message = self.wallet.receive_tx(h)
-
- if not status:
- import tempfile
- dumpf = tempfile.NamedTemporaryFile(delete=False)
- dumpf.write(tx)
- dumpf.close()
- print "Dumped error tx to", dumpf.name
- QMessageBox.warning(parent_window, _('Error'), message, _('OK'))
- return False
-
- TransactionWindow(message, self)
- else:
- filename = 'unsigned_tx_%s' % (time.mktime(time.gmtime()))
- try:
- fileName = QFileDialog.getSaveFileName(QWidget(), _("Select a transaction filename"), os.path.expanduser('~/%s' % (filename)))
- with open(fileName,'w') as f:
- f.write(json.dumps(tx.as_dict(),indent=4) + '\n')
- QMessageBox.information(QWidget(), _('Unsigned transaction created'), _("Unsigned transaction was saved to file:") + " " +fileName, _('OK'))
- except BaseException as e:
- QMessageBox.warning(QWidget(), _('Error'), _('Could not write transaction to file: %s' % e), _('OK'))
- return True
-
- def fetch_destination(self, address):
- recipient = unicode(address).strip()
-
- # alias
- match1 = re.match("^(|([\w\-\.]+)@)((\w[\w\-]+\.)+[\w\-]+)$",
- recipient)
-
- # label or alias, with address in brackets
- match2 = re.match("(.*?)\s*\<([1-9A-HJ-NP-Za-km-z]{26,})\>",
- recipient)
-
- if match1:
- dest_address = \
- self.wallet.get_alias(recipient, True,
- self.show_message, self.question)
- return dest_address
- elif match2:
- return match2.group(2)
- else:
- return recipient
-
-
- def copy_master_public_key(self):
- master_pubkey = self.wallet.get_master_public_key()
- qApp.clipboard().setText(master_pubkey)
- QMessageBox.information(None, _("Copy successful"), _("Your master public key has been copied to your clipboard."))
-
-
- def acceptbit(self, currency):
- master_pubkey = self.wallet.master_public_key
- url = "http://acceptbit.com/mpk/%s/%s" % (master_pubkey, currency)
- webbrowser.open(url)
-
- def show_seed_dialog(self):
- ElectrumWindow.show_seed_dialog(self.wallet)
-
-class MiniDriver(QObject):
-
- INITIALIZING = 0
- CONNECTING = 1
- SYNCHRONIZING = 2
- READY = 3
-
- def __init__(self, wallet, window):
- super(QObject, self).__init__()
-
- self.wallet = wallet
- self.network = wallet.network
- self.window = window
-
- self.wallet.network.register_callback('updated',self.update_callback)
- self.wallet.network.register_callback('connected', self.update_callback)
- self.wallet.network.register_callback('disconnected', self.update_callback)
-
- self.state = None
-
- self.initializing()
- self.connect(self, SIGNAL("updatesignal()"), self.update)
- self.update_callback()
-
- # This is a hack to workaround that Qt does not like changing the
- # window properties from this other thread before the runloop has
- # been called from.
- def update_callback(self):
- self.emit(SIGNAL("updatesignal()"))
-
- def update(self):
- if not self.network.interface:
- self.initializing()
- elif not self.network.interface.is_connected:
- self.connecting()
- elif not self.wallet.up_to_date:
- self.synchronizing()
- else:
- self.ready()
-
- if self.wallet.up_to_date:
- self.update_balance()
- self.update_completions()
- self.update_history()
-
- def initializing(self):
- if self.state == self.INITIALIZING:
- return
- self.state = self.INITIALIZING
- self.window.deactivate()
-
- def connecting(self):
- if self.state == self.CONNECTING:
- return
- self.state = self.CONNECTING
- self.window.deactivate()
-
- def synchronizing(self):
- if self.state == self.SYNCHRONIZING:
- return
- self.state = self.SYNCHRONIZING
- self.window.deactivate()
-
- def ready(self):
- if self.state == self.READY:
- return
- self.state = self.READY
- self.window.activate()
-
- def update_balance(self):
- conf_balance, unconf_balance = self.wallet.get_balance()
- balance = D(conf_balance + unconf_balance)
- self.window.set_balances(balance)
-
- def update_completions(self):
- completions = []
- for addr, label in self.wallet.labels.items():
- if addr in self.wallet.addressbook:
- completions.append("%s <%s>" % (label, addr))
- self.window.update_completions(completions)
-
- def update_history(self):
- tx_history = self.wallet.get_tx_history()
- self.window.update_history(tx_history)
-
-
-if __name__ == "__main__":
- app = QApplication(sys.argv)
- with open(rsrc("style.css")) as style_file:
- app.setStyleSheet(style_file.read())
- mini = MiniWindow()
- sys.exit(app.exec_())
-
diff --git a/gui/gui_classic/main_window.py b/gui/gui_classic/main_window.py
@@ -1,1967 +0,0 @@
-#!/usr/bin/env python
-#
-# Electrum - lightweight Bitcoin client
-# Copyright (C) 2012 thomasv@gitorious
-#
-# This program is free software: you can redistribute it and/or modify
-# it under the terms of the GNU General Public License as published by
-# the Free Software Foundation, either version 3 of the License, or
-# (at your option) any later version.
-#
-# This program is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-# GNU General Public License for more details.
-#
-# You should have received a copy of the GNU General Public License
-# along with this program. If not, see <http://www.gnu.org/licenses/>.
-
-import sys, time, datetime, re, threading
-from electrum.i18n import _, set_language
-from electrum.util import print_error, print_msg
-import os.path, json, ast, traceback
-import shutil
-import StringIO
-
-
-try:
- import PyQt4
-except:
- sys.exit("Error: Could not import PyQt4 on Linux systems, you may try 'sudo apt-get install python-qt4'")
-
-from PyQt4.QtGui import *
-from PyQt4.QtCore import *
-import PyQt4.QtCore as QtCore
-
-from electrum.bitcoin import MIN_RELAY_TX_FEE, is_valid
-from electrum.plugins import run_hook
-
-try:
- import icons_rc
-except:
- sys.exit("Error: Could not import icons_rc.py, please generate it with: 'pyrcc4 icons.qrc -o gui/icons_rc.py'")
-
-from electrum.wallet import format_satoshis
-from electrum import Transaction
-from electrum import mnemonic
-from electrum import util, bitcoin, commands, Interface, Wallet
-from electrum import SimpleConfig, Wallet, WalletStorage
-
-
-from electrum import bmp, pyqrnative
-
-from amountedit import AmountEdit
-from network_dialog import NetworkDialog
-from qrcodewidget import QRCodeWidget
-
-from decimal import Decimal
-
-import platform
-import httplib
-import socket
-import webbrowser
-import csv
-
-if platform.system() == 'Windows':
- MONOSPACE_FONT = 'Lucida Console'
-elif platform.system() == 'Darwin':
- MONOSPACE_FONT = 'Monaco'
-else:
- MONOSPACE_FONT = 'monospace'
-
-from electrum import ELECTRUM_VERSION
-import re
-
-from qt_util import *
-
-
-
-
-
-
-class StatusBarButton(QPushButton):
- def __init__(self, icon, tooltip, func):
- QPushButton.__init__(self, icon, '')
- self.setToolTip(tooltip)
- self.setFlat(True)
- self.setMaximumWidth(25)
- self.clicked.connect(func)
- self.func = func
- self.setIconSize(QSize(25,25))
-
- def keyPressEvent(self, e):
- if e.key() == QtCore.Qt.Key_Return:
- apply(self.func,())
-
-
-
-
-
-
-
-
-
-
-default_column_widths = { "history":[40,140,350,140], "contacts":[350,330], "receive":[[370], [370,200,130]] }
-
-class ElectrumWindow(QMainWindow):
- def changeEvent(self, event):
- flags = self.windowFlags();
- if event and event.type() == QtCore.QEvent.WindowStateChange:
- if self.windowState() & QtCore.Qt.WindowMinimized:
- self.build_menu(True)
- # The only way to toggle the icon in the window managers taskbar is to use the Qt.Tooltip flag
- # The problem is that it somehow creates an (in)visible window that will stay active and prevent
- # Electrum from closing.
- # As for now I have no clue how to implement a proper 'hide to tray' functionality.
- # self.setWindowFlags(flags & ~Qt.ToolTip)
- elif event.oldState() & QtCore.Qt.WindowMinimized:
- self.build_menu(False)
- #self.setWindowFlags(flags | Qt.ToolTip)
-
- def build_menu(self, is_hidden = False):
- m = QMenu()
- if self.isMinimized():
- m.addAction(_("Show"), self.showNormal)
- else:
- m.addAction(_("Hide"), self.showMinimized)
-
- m.addSeparator()
- m.addAction(_("Exit Electrum"), self.close)
- self.tray.setContextMenu(m)
-
- def tray_activated(self, reason):
- if reason == QSystemTrayIcon.DoubleClick:
- self.showNormal()
-
-
- def __init__(self, config, network, go_lite):
- QMainWindow.__init__(self)
-
- self.config = config
- self.network = network
- self.go_lite = go_lite
-
- self._close_electrum = False
- self.lite = None
- self.current_account = self.config.get("current_account", None)
-
- self.icon = QIcon(':icons/electrum.png')
- self.tray = QSystemTrayIcon(self.icon, self)
- self.tray.setToolTip('Electrum')
- self.tray.activated.connect(self.tray_activated)
-
- self.build_menu()
- self.tray.show()
- self.create_status_bar()
-
- self.need_update = threading.Event()
-
- self.expert_mode = config.get('classic_expert_mode', False)
- self.decimal_point = config.get('decimal_point', 8)
- self.num_zeros = int(config.get('num_zeros',0))
-
- set_language(config.get('language'))
-
- self.funds_error = False
- self.completions = QStringListModel()
-
- self.tabs = tabs = QTabWidget(self)
- self.column_widths = self.config.get("column_widths", default_column_widths )
- tabs.addTab(self.create_history_tab(), _('History') )
- tabs.addTab(self.create_send_tab(), _('Send') )
- tabs.addTab(self.create_receive_tab(), _('Receive') )
- tabs.addTab(self.create_contacts_tab(), _('Contacts') )
- tabs.addTab(self.create_console_tab(), _('Console') )
- tabs.setMinimumSize(600, 400)
- tabs.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
- self.setCentralWidget(tabs)
-
- g = self.config.get("winpos-qt",[100, 100, 840, 400])
- self.setGeometry(g[0], g[1], g[2], g[3])
-
- self.init_menubar()
-
- QShortcut(QKeySequence("Ctrl+W"), self, self.close)
- QShortcut(QKeySequence("Ctrl+R"), self, self.update_wallet)
- QShortcut(QKeySequence("Ctrl+Q"), self, self.close)
- QShortcut(QKeySequence("Ctrl+PgUp"), self, lambda: tabs.setCurrentIndex( (tabs.currentIndex() - 1 )%tabs.count() ))
- QShortcut(QKeySequence("Ctrl+PgDown"), self, lambda: tabs.setCurrentIndex( (tabs.currentIndex() + 1 )%tabs.count() ))
-
- self.connect(self, QtCore.SIGNAL('update_status'), self.update_status)
- self.connect(self, QtCore.SIGNAL('banner_signal'), lambda: self.console.showMessage(self.network.banner) )
- self.connect(self, QtCore.SIGNAL('transaction_signal'), lambda: self.notify_transactions() )
-
- self.history_list.setFocus(True)
-
- # dark magic fix by flatfly; https://bitcointalk.org/index.php?topic=73651.msg959913#msg959913
- if platform.system() == 'Windows':
- n = 3 if self.wallet.seed else 2
- tabs.setCurrentIndex (n)
- tabs.setCurrentIndex (0)
-
-
-
-
-
- def load_wallet(self, wallet):
- import electrum
- self.wallet = wallet
-
- self.network.register_callback('updated', lambda: self.need_update.set())
- self.network.register_callback('banner', lambda: self.emit(QtCore.SIGNAL('banner_signal')))
- self.network.register_callback('disconnected', lambda: self.emit(QtCore.SIGNAL('update_status')))
- self.network.register_callback('disconnecting', lambda: self.emit(QtCore.SIGNAL('update_status')))
- self.network.register_callback('new_transaction', lambda: self.emit(QtCore.SIGNAL('transaction_signal')))
- title = 'Electrum ' + self.wallet.electrum_version + ' - ' + self.wallet.storage.path
- if not self.wallet.seed: title += ' [%s]' % (_('seedless'))
- self.setWindowTitle( title )
- self.update_wallet()
- # set initial message
- self.console.showMessage(self.network.banner)
- # Once GUI has been initialized check if we want to announce something since the callback has been called before the GUI was initialized
- self.notify_transactions()
-
- # account selector
- accounts = self.wallet.get_account_names()
- self.account_selector.clear()
- if len(accounts) > 1:
- self.account_selector.addItems([_("All accounts")] + accounts.values())
- self.account_selector.setCurrentIndex(0)
- self.account_selector.show()
- else:
- self.account_selector.hide()
-
- self.new_account.setEnabled(self.wallet.seed_version>4)
-
- self.update_lock_icon()
- self.update_buttons_on_seed()
- self.update_console()
-
- run_hook('load_wallet')
-
-
- def select_wallet_file(self):
- wallet_folder = self.wallet.storage.path
- re.sub("(\/\w*.dat)$", "", wallet_folder)
- file_name = unicode( QFileDialog.getOpenFileName(self, "Select your wallet file", wallet_folder) )
- return file_name
-
-
- def open_wallet(self):
-
- filename = self.select_wallet_file()
- if not filename:
- return
-
- storage = WalletStorage({'wallet_path': filename})
- if not storage.file_exists:
- self.show_message("file not found "+ filename)
- return
-
- self.wallet.stop_threads()
-
- # create new wallet
- wallet = Wallet(storage)
- wallet.start_threads(self.network)
-
- self.load_wallet(wallet)
-
-
-
- def backup_wallet(self):
- import shutil
- path = self.wallet.storage.path
- wallet_folder = os.path.dirname(path)
- new_filename, ok = QInputDialog.getText(self, _('Filename'), _('Current directory') + ': ' + wallet_folder + '\n' + _('Enter a filename for the copy of your wallet') + ':')
- new_filename = unicode(new_filename)
- if not ok or not new_filename:
- return
-
- new_path = os.path.join(wallet_folder, new_filename)
- if new_path != path:
- try:
- shutil.copy2(path, new_path)
- QMessageBox.information(None,"Wallet backup created", _("A copy of your wallet file was created in")+" '%s'" % str(new_path))
- except (IOError, os.error), reason:
- QMessageBox.critical(None,"Unable to create backup", _("Electrum was unable to copy your wallet file to the specified location.")+"\n" + str(reason))
-
-
- def new_wallet(self):
- import installwizard
-
- wallet_folder = os.path.dirname(self.wallet.storage.path)
- filename, ok = QInputDialog.getText(self, _('Filename'), _('Current directory') + ': ' + wallet_folder + '\n'+_('Enter a new file name') + ':')
- filename = unicode(filename)
- if not ok or not filename:
- return
- filename = os.path.join(wallet_folder, filename)
-
- storage = WalletStorage({'wallet_path': filename})
- assert not storage.file_exists
-
- wizard = installwizard.InstallWizard(self.config, self.network, storage)
- wallet = wizard.run()
- if wallet:
- self.load_wallet(wallet)
-
-
-
- def init_menubar(self):
- menubar = QMenuBar()
-
- file_menu = menubar.addMenu(_("&File"))
- open_wallet_action = file_menu.addAction(_("&Open"))
- open_wallet_action.triggered.connect(self.open_wallet)
-
- new_wallet_action = file_menu.addAction(_("&Create/Restore"))
- new_wallet_action.triggered.connect(self.new_wallet)
-
- wallet_backup = file_menu.addAction(_("&Copy"))
- wallet_backup.triggered.connect(self.backup_wallet)
-
- quit_item = file_menu.addAction(_("&Close"))
- quit_item.triggered.connect(self.close)
-
- wallet_menu = menubar.addMenu(_("&Wallet"))
-
- new_contact = wallet_menu.addAction(_("&New contact"))
- new_contact.triggered.connect(self.new_contact_dialog)
-
- self.new_account = wallet_menu.addAction(_("&New account"))
- self.new_account.triggered.connect(self.new_account_dialog)
-
- wallet_menu.addSeparator()
-
- #if self.wallet.seed:
- show_seed = wallet_menu.addAction(_("&Seed"))
- show_seed.triggered.connect(self.show_seed_dialog)
-
- show_mpk = wallet_menu.addAction(_("&Master Public Key"))
- show_mpk.triggered.connect(self.show_master_public_key)
-
- wallet_menu.addSeparator()
-
- csv_transaction_menu = wallet_menu.addMenu(_("&Create transaction"))
-
- csv_transaction_file = csv_transaction_menu.addAction(_("&From CSV file"))
- csv_transaction_file.triggered.connect(self.do_process_from_csv_file)
-
- csv_transaction_text = csv_transaction_menu.addAction(_("&From CSV text"))
- csv_transaction_text.triggered.connect(self.do_process_from_csv_text)
-
- raw_transaction_menu = wallet_menu.addMenu(_("&Load transaction"))
-
- raw_transaction_file = raw_transaction_menu.addAction(_("&From file"))
- raw_transaction_file.triggered.connect(self.do_process_from_file)
-
- raw_transaction_text = raw_transaction_menu.addAction(_("&From text"))
- raw_transaction_text.triggered.connect(self.do_process_from_text)
-
-
- tools_menu = menubar.addMenu(_("&Tools"))
-
- # Settings / Preferences are all reserved keywords in OSX using this as work around
- preferences_name = _("Electrum preferences") if sys.platform == 'darwin' else _("Preferences")
- preferences_menu = tools_menu.addAction(preferences_name)
- preferences_menu.triggered.connect(self.settings_dialog)
-
- plugins_labels = tools_menu.addAction(_("&Plugins"))
- plugins_labels.triggered.connect(self.plugins_dialog)
-
- wallet_menu.addSeparator()
-
- labels_menu = tools_menu.addMenu(_("&Labels"))
- import_labels = labels_menu.addAction(_("&Import"))
- import_labels.triggered.connect(self.do_import_labels)
- export_labels = labels_menu.addAction(_("&Export"))
- export_labels.triggered.connect(self.do_export_labels)
-
- keys_menu = tools_menu.addMenu(_("&Private keys"))
- import_keys = keys_menu.addAction(_("&Import"))
- import_keys.triggered.connect(self.do_import_privkey)
- export_keys = keys_menu.addAction(_("&Export"))
- export_keys.triggered.connect(self.do_export_privkeys)
-
- ex_history = tools_menu.addAction(_("&Export History"))
- ex_history.triggered.connect(self.do_export_history)
-
-
- help_menu = menubar.addMenu(_("&Help"))
- show_about = help_menu.addAction(_("&About"))
- show_about.triggered.connect(self.show_about)
- web_open = help_menu.addAction(_("&Official website"))
- web_open.triggered.connect(lambda: webbrowser.open("http://electrum.org"))
-
- help_menu.addSeparator()
- doc_open = help_menu.addAction(_("&Documentation"))
- doc_open.triggered.connect(lambda: webbrowser.open("http://electrum.org/documentation.html"))
- report_bug = help_menu.addAction(_("&Report Bug"))
- report_bug.triggered.connect(self.show_report_bug)
-
- self.setMenuBar(menubar)
-
- def show_about(self):
- QMessageBox.about(self, "Electrum",
- _("Version")+" %s" % (self.wallet.electrum_version) + "\n\n" + _("Electrum's focus is speed, with low resource usage and simplifying Bitcoin. You do not need to perform regular backups, because your wallet can be recovered from a secret phrase that you can memorize or write on paper. Startup times are instant because it operates in conjunction with high-performance servers that handle the most complicated parts of the Bitcoin system."))
-
- def show_report_bug(self):
- QMessageBox.information(self, "Electrum - " + _("Reporting Bugs"),
- _("Please report any bugs as issues on github:")+" <a href=\"https://github.com/spesmilo/electrum/issues\">https://github.com/spesmilo/electrum/issues</a>")
-
-
- def notify_transactions(self):
- print_error("Notifying GUI")
- if len(self.network.interface.pending_transactions_for_notifications) > 0:
- # Combine the transactions if there are more then three
- tx_amount = len(self.network.interface.pending_transactions_for_notifications)
- if(tx_amount >= 3):
- total_amount = 0
- for tx in self.network.interface.pending_transactions_for_notifications:
- is_relevant, is_mine, v, fee = self.wallet.get_tx_value(tx)
- if(v > 0):
- total_amount += v
-
- self.notify(_("%(txs)s new transactions received. Total amount received in the new transactions %(amount)s %(unit)s") \
- % { 'txs' : tx_amount, 'amount' : self.format_amount(total_amount), 'unit' : self.base_unit()})
-
- self.network.interface.pending_transactions_for_notifications = []
- else:
- for tx in self.network.interface.pending_transactions_for_notifications:
- if tx:
- self.network.interface.pending_transactions_for_notifications.remove(tx)
- is_relevant, is_mine, v, fee = self.wallet.get_tx_value(tx)
- if(v > 0):
- self.notify(_("New transaction received. %(amount)s %(unit)s") % { 'amount' : self.format_amount(v), 'unit' : self.base_unit()})
-
- def notify(self, message):
- self.tray.showMessage("Electrum", message, QSystemTrayIcon.Information, 20000)
-
-
-
- def set_label(self, name, text = None):
- changed = False
- old_text = self.wallet.labels.get(name)
- if text:
- if old_text != text:
- self.wallet.labels[name] = text
- self.wallet.storage.put('labels', self.wallet.labels)
- changed = True
- else:
- if old_text:
- self.wallet.labels.pop(name)
- changed = True
- run_hook('set_label', name, text, changed)
- return changed
-
-
- # custom wrappers for getOpenFileName and getSaveFileName, that remember the path selected by the user
- def getOpenFileName(self, title, filter = ""):
- directory = self.config.get('io_dir', os.path.expanduser('~'))
- fileName = unicode( QFileDialog.getOpenFileName(self, title, directory, filter) )
- if fileName and directory != os.path.dirname(fileName):
- self.config.set_key('io_dir', os.path.dirname(fileName), True)
- return fileName
-
- def getSaveFileName(self, title, filename, filter = ""):
- directory = self.config.get('io_dir', os.path.expanduser('~'))
- path = os.path.join( directory, filename )
- fileName = unicode( QFileDialog.getSaveFileName(self, title, path, filter) )
- if fileName and directory != os.path.dirname(fileName):
- self.config.set_key('io_dir', os.path.dirname(fileName), True)
- return fileName
-
- def close(self):
- QMainWindow.close(self)
- run_hook('close_main_window')
-
- def connect_slots(self, sender):
- self.connect(sender, QtCore.SIGNAL('timersignal'), self.timer_actions)
- self.previous_payto_e=''
-
- def timer_actions(self):
- if self.need_update.is_set():
- self.update_wallet()
- self.need_update.clear()
- run_hook('timer_actions')
-
- def format_amount(self, x, is_diff=False, whitespaces=False):
- return format_satoshis(x, is_diff, self.num_zeros, self.decimal_point, whitespaces)
-
- def read_amount(self, x):
- if x in['.', '']: return None
- p = pow(10, self.decimal_point)
- return int( p * Decimal(x) )
-
- def base_unit(self):
- assert self.decimal_point in [5,8]
- return "BTC" if self.decimal_point == 8 else "mBTC"
-
- def set_status_text(self, text):
- self.balance_label.setText(text)
- run_hook('set_status_text', text)
-
-
- def update_status(self):
- if self.network.interface and self.network.interface.is_connected:
- if not self.wallet.up_to_date:
- text = _("Synchronizing...")
- icon = QIcon(":icons/status_waiting.png")
- else:
- c, u = self.wallet.get_account_balance(self.current_account)
- text = _( "Balance" ) + ": %s "%( self.format_amount(c) ) + self.base_unit()
- if u: text += " [%s unconfirmed]"%( self.format_amount(u,True).strip() )
- self.tray.setToolTip(text)
- icon = QIcon(":icons/status_connected.png")
- else:
- text = _("Not connected")
- icon = QIcon(":icons/status_disconnected.png")
-
- self.set_status_text(text)
- self.status_button.setIcon( icon )
-
- def update_wallet(self):
- self.update_status()
- if self.wallet.up_to_date or not self.network.interface.is_connected:
- self.update_history_tab()
- self.update_receive_tab()
- self.update_contacts_tab()
- self.update_completions()
-
-
-
- def create_history_tab(self):
- self.history_list = l = MyTreeWidget(self)
- l.setColumnCount(5)
- for i,width in enumerate(self.column_widths['history']):
- l.setColumnWidth(i, width)
- l.setHeaderLabels( [ '', _('Date'), _('Description') , _('Amount'), _('Balance')] )
- self.connect(l, SIGNAL('itemDoubleClicked(QTreeWidgetItem*, int)'), self.tx_label_clicked)
- self.connect(l, SIGNAL('itemChanged(QTreeWidgetItem*, int)'), self.tx_label_changed)
-
- l.customContextMenuRequested.connect(self.create_history_menu)
- return l
-
-
- def create_history_menu(self, position):
- self.history_list.selectedIndexes()
- item = self.history_list.currentItem()
- if not item: return
- tx_hash = str(item.data(0, Qt.UserRole).toString())
- if not tx_hash: return
- menu = QMenu()
- menu.addAction(_("Copy ID to Clipboard"), lambda: self.app.clipboard().setText(tx_hash))
- menu.addAction(_("Details"), lambda: self.show_transaction(self.wallet.transactions.get(tx_hash)))
- menu.addAction(_("Edit description"), lambda: self.tx_label_clicked(item,2))
- menu.exec_(self.contacts_list.viewport().mapToGlobal(position))
-
-
- def show_transaction(self, tx):
- import transaction_dialog
- d = transaction_dialog.TxDialog(tx, self)
- d.exec_()
-
- def tx_label_clicked(self, item, column):
- if column==2 and item.isSelected():
- self.is_edit=True
- item.setFlags(Qt.ItemIsEditable|Qt.ItemIsSelectable | Qt.ItemIsUserCheckable | Qt.ItemIsEnabled | Qt.ItemIsDragEnabled)
- self.history_list.editItem( item, column )
- item.setFlags(Qt.ItemIsSelectable | Qt.ItemIsUserCheckable | Qt.ItemIsEnabled | Qt.ItemIsDragEnabled)
- self.is_edit=False
-
- def tx_label_changed(self, item, column):
- if self.is_edit:
- return
- self.is_edit=True
- tx_hash = str(item.data(0, Qt.UserRole).toString())
- tx = self.wallet.transactions.get(tx_hash)
- text = unicode( item.text(2) )
- self.set_label(tx_hash, text)
- if text:
- item.setForeground(2, QBrush(QColor('black')))
- else:
- text = self.wallet.get_default_label(tx_hash)
- item.setText(2, text)
- item.setForeground(2, QBrush(QColor('gray')))
- self.is_edit=False
-
-
- def edit_label(self, is_recv):
- l = self.receive_list if is_recv else self.contacts_list
- item = l.currentItem()
- item.setFlags(Qt.ItemIsEditable|Qt.ItemIsSelectable | Qt.ItemIsUserCheckable | Qt.ItemIsEnabled | Qt.ItemIsDragEnabled)
- l.editItem( item, 1 )
- item.setFlags(Qt.ItemIsSelectable | Qt.ItemIsUserCheckable | Qt.ItemIsEnabled | Qt.ItemIsDragEnabled)
-
-
-
- def address_label_clicked(self, item, column, l, column_addr, column_label):
- if column == column_label and item.isSelected():
- is_editable = item.data(0, 32).toBool()
- if not is_editable:
- return
- addr = unicode( item.text(column_addr) )
- label = unicode( item.text(column_label) )
- item.setFlags(Qt.ItemIsEditable|Qt.ItemIsSelectable | Qt.ItemIsUserCheckable | Qt.ItemIsEnabled | Qt.ItemIsDragEnabled)
- l.editItem( item, column )
- item.setFlags(Qt.ItemIsSelectable | Qt.ItemIsUserCheckable | Qt.ItemIsEnabled | Qt.ItemIsDragEnabled)
-
-
- def address_label_changed(self, item, column, l, column_addr, column_label):
- if column == column_label:
- addr = unicode( item.text(column_addr) )
- text = unicode( item.text(column_label) )
- is_editable = item.data(0, 32).toBool()
- if not is_editable:
- return
-
- changed = self.set_label(addr, text)
- if changed:
- self.update_history_tab()
- self.update_completions()
-
- self.current_item_changed(item)
-
- run_hook('item_changed', item, column)
-
-
- def current_item_changed(self, a):
- run_hook('current_item_changed', a)
-
-
-
- def update_history_tab(self):
-
- self.history_list.clear()
- for item in self.wallet.get_tx_history(self.current_account):
- tx_hash, conf, is_mine, value, fee, balance, timestamp = item
- if conf > 0:
- try:
- time_str = datetime.datetime.fromtimestamp( timestamp).isoformat(' ')[:-3]
- except:
- time_str = _("unknown")
-
- if conf == -1:
- time_str = 'unverified'
- icon = QIcon(":icons/unconfirmed.png")
- elif conf == 0:
- time_str = 'pending'
- icon = QIcon(":icons/unconfirmed.png")
- elif conf < 6:
- icon = QIcon(":icons/clock%d.png"%conf)
- else:
- icon = QIcon(":icons/confirmed.png")
-
- if value is not None:
- v_str = self.format_amount(value, True, whitespaces=True)
- else:
- v_str = '--'
-
- balance_str = self.format_amount(balance, whitespaces=True)
-
- if tx_hash:
- label, is_default_label = self.wallet.get_label(tx_hash)
- else:
- label = _('Pruned transaction outputs')
- is_default_label = False
-
- item = QTreeWidgetItem( [ '', time_str, label, v_str, balance_str] )
- item.setFont(2, QFont(MONOSPACE_FONT))
- item.setFont(3, QFont(MONOSPACE_FONT))
- item.setFont(4, QFont(MONOSPACE_FONT))
- if value < 0:
- item.setForeground(3, QBrush(QColor("#BC1E1E")))
- if tx_hash:
- item.setData(0, Qt.UserRole, tx_hash)
- item.setToolTip(0, "%d %s\nTxId:%s" % (conf, _('Confirmations'), tx_hash) )
- if is_default_label:
- item.setForeground(2, QBrush(QColor('grey')))
-
- item.setIcon(0, icon)
- self.history_list.insertTopLevelItem(0,item)
-
-
- self.history_list.setCurrentItem(self.history_list.topLevelItem(0))
-
-
- def create_send_tab(self):
- w = QWidget()
-
- grid = QGridLayout()
- grid.setSpacing(8)
- grid.setColumnMinimumWidth(3,300)
- grid.setColumnStretch(5,1)
-
-
- self.payto_e = QLineEdit()
- grid.addWidget(QLabel(_('Pay to')), 1, 0)
- grid.addWidget(self.payto_e, 1, 1, 1, 3)
-
- grid.addWidget(HelpButton(_('Recipient of the funds.') + '\n\n' + _('You may enter a Bitcoin address, a label from your list of contacts (a list of completions will be proposed), or an alias (email-like address that forwards to a Bitcoin address)')), 1, 4)
-
- completer = QCompleter()
- completer.setCaseSensitivity(False)
- self.payto_e.setCompleter(completer)
- completer.setModel(self.completions)
-
- self.message_e = QLineEdit()
- grid.addWidget(QLabel(_('Description')), 2, 0)
- grid.addWidget(self.message_e, 2, 1, 1, 3)
- grid.addWidget(HelpButton(_('Description of the transaction (not mandatory).') + '\n\n' + _('The description is not sent to the recipient of the funds. It is stored in your wallet file, and displayed in the \'History\' tab.')), 2, 4)
-
- self.amount_e = AmountEdit(self.base_unit)
- grid.addWidget(QLabel(_('Amount')), 3, 0)
- grid.addWidget(self.amount_e, 3, 1, 1, 2)
- grid.addWidget(HelpButton(
- _('Amount to be sent.') + '\n\n' \
- + _('The amount will be displayed in red if you do not have enough funds in your wallet. Note that if you have frozen some of your addresses, the available funds will be lower than your total balance.') \
- + '\n\n' + _('Keyboard shortcut: type "!" to send all your coins.')), 3, 3)
-
- self.fee_e = AmountEdit(self.base_unit)
- grid.addWidget(QLabel(_('Fee')), 4, 0)
- grid.addWidget(self.fee_e, 4, 1, 1, 2)
- grid.addWidget(HelpButton(
- _('Bitcoin transactions are in general not free. A transaction fee is paid by the sender of the funds.') + '\n\n'\
- + _('The amount of fee can be decided freely by the sender. However, transactions with low fees take more time to be processed.') + '\n\n'\
- + _('A suggested fee is automatically added to this field. You may override it. The suggested fee increases with the size of the transaction.')), 4, 3)
-
-
- self.send_button = EnterButton(_("Send"), self.do_send)
- grid.addWidget(self.send_button, 6, 1)
-
- b = EnterButton(_("Clear"),self.do_clear)
- grid.addWidget(b, 6, 2)
-
- self.payto_sig = QLabel('')
- grid.addWidget(self.payto_sig, 7, 0, 1, 4)
-
- QShortcut(QKeySequence("Up"), w, w.focusPreviousChild)
- QShortcut(QKeySequence("Down"), w, w.focusNextChild)
- w.setLayout(grid)
-
- w2 = QWidget()
- vbox = QVBoxLayout()
- vbox.addWidget(w)
- vbox.addStretch(1)
- w2.setLayout(vbox)
-
- def entry_changed( is_fee ):
- self.funds_error = False
-
- if self.amount_e.is_shortcut:
- self.amount_e.is_shortcut = False
- c, u = self.wallet.get_account_balance(self.current_account)
- inputs, total, fee = self.wallet.choose_tx_inputs( c + u, 0, self.current_account)
- fee = self.wallet.estimated_fee(inputs)
- amount = c + u - fee
- self.amount_e.setText( self.format_amount(amount) )
- self.fee_e.setText( self.format_amount( fee ) )
- return
-
- amount = self.read_amount(str(self.amount_e.text()))
- fee = self.read_amount(str(self.fee_e.text()))
-
- if not is_fee: fee = None
- if amount is None:
- return
- inputs, total, fee = self.wallet.choose_tx_inputs( amount, fee, self.current_account )
- if not is_fee:
- self.fee_e.setText( self.format_amount( fee ) )
- if inputs:
- palette = QPalette()
- palette.setColor(self.amount_e.foregroundRole(), QColor('black'))
- text = ""
- else:
- palette = QPalette()
- palette.setColor(self.amount_e.foregroundRole(), QColor('red'))
- self.funds_error = True
- text = _( "Not enough funds" )
- c, u = self.wallet.get_frozen_balance()
- if c+u: text += ' (' + self.format_amount(c+u).strip() + self.base_unit() + ' ' +_("are frozen") + ')'
-
- self.statusBar().showMessage(text)
- self.amount_e.setPalette(palette)
- self.fee_e.setPalette(palette)
-
- self.amount_e.textChanged.connect(lambda: entry_changed(False) )
- self.fee_e.textChanged.connect(lambda: entry_changed(True) )
-
- run_hook('create_send_tab', grid)
- return w2
-
-
- def update_completions(self):
- l = []
- for addr,label in self.wallet.labels.items():
- if addr in self.wallet.addressbook:
- l.append( label + ' <' + addr + '>')
-
- run_hook('update_completions', l)
- self.completions.setStringList(l)
-
-
- def protected(func):
- return lambda s, *args: s.do_protect(func, args)
-
-
- def do_send(self):
-
- label = unicode( self.message_e.text() )
- r = unicode( self.payto_e.text() )
- r = r.strip()
-
- # label or alias, with address in brackets
- m = re.match('(.*?)\s*\<([1-9A-HJ-NP-Za-km-z]{26,})\>', r)
- to_address = m.group(2) if m else r
-
- if not is_valid(to_address):
- QMessageBox.warning(self, _('Error'), _('Invalid Bitcoin Address') + ':\n' + to_address, _('OK'))
- return
-
- try:
- amount = self.read_amount(unicode( self.amount_e.text()))
- except:
- QMessageBox.warning(self, _('Error'), _('Invalid Amount'), _('OK'))
- return
- try:
- fee = self.read_amount(unicode( self.fee_e.text()))
- except:
- QMessageBox.warning(self, _('Error'), _('Invalid Fee'), _('OK'))
- return
-
- confirm_amount = self.config.get('confirm_amount', 100000000)
- if amount >= confirm_amount:
- if not self.question(_("send %(amount)s to %(address)s?")%{ 'amount' : self.format_amount(amount) + ' '+ self.base_unit(), 'address' : to_address}):
- return
-
- self.send_tx(to_address, amount, fee, label)
-
-
- @protected
- def send_tx(self, to_address, amount, fee, label, password):
-
- try:
- tx = self.wallet.mktx_from_account( [(to_address, amount)], password, fee, self.current_account)
- except BaseException, e:
- traceback.print_exc(file=sys.stdout)
- self.show_message(str(e))
- return
-
- if tx.requires_fee(self.wallet.verifier) and fee < MIN_RELAY_TX_FEE:
- QMessageBox.warning(self, _('Error'), _("This transaction requires a higher fee, or it will not be propagated by the network."), _('OK'))
- return
-
- run_hook('send_tx', tx)
-
- if label:
- self.set_label(tx.hash(), label)
-
- if tx.is_complete:
- h = self.wallet.send_tx(tx)
- waiting_dialog(lambda: False if self.wallet.tx_event.isSet() else _("Please wait..."))
- status, msg = self.wallet.receive_tx( h )
- if status:
- QMessageBox.information(self, '', _('Payment sent.')+'\n'+msg, _('OK'))
- self.do_clear()
- self.update_contacts_tab()
- else:
- QMessageBox.warning(self, _('Error'), msg, _('OK'))
- else:
- filename = label + '.txn' if label else 'unsigned_%s.txn' % (time.mktime(time.gmtime()))
- try:
- fileName = self.getSaveFileName(_("Select a transaction filename"), filename, "*.txn")
- with open(fileName,'w') as f:
- f.write(json.dumps(tx.as_dict(),indent=4) + '\n')
- QMessageBox.information(self, _('Unsigned transaction created'), _("Unsigned transaction was saved to file:") + " " +fileName, _('OK'))
- except:
- QMessageBox.warning(self, _('Error'), _('Could not write transaction to file'), _('OK'))
-
- # add recipient to addressbook
- if to_address not in self.wallet.addressbook and not self.wallet.is_mine(to_address):
- self.wallet.addressbook.append(to_address)
-
-
-
-
- def set_url(self, url):
- address, amount, label, message, signature, identity, url = util.parse_url(url)
- if self.base_unit() == 'mBTC': amount = str( 1000* Decimal(amount))
-
- if label and self.wallet.labels.get(address) != label:
- if self.question('Give label "%s" to address %s ?'%(label,address)):
- if address not in self.wallet.addressbook and not self.wallet.is_mine(address):
- self.wallet.addressbook.append(address)
- self.set_label(address, label)
-
- run_hook('set_url', url, self.show_message, self.question)
-
- self.tabs.setCurrentIndex(1)
- label = self.wallet.labels.get(address)
- m_addr = label + ' <'+ address +'>' if label else address
- self.payto_e.setText(m_addr)
-
- self.message_e.setText(message)
- self.amount_e.setText(amount)
- if identity:
- self.set_frozen(self.payto_e,True)
- self.set_frozen(self.amount_e,True)
- self.set_frozen(self.message_e,True)
- self.payto_sig.setText( ' '+_('The bitcoin URI was signed by')+' ' + identity )
- else:
- self.payto_sig.setVisible(False)
-
- def do_clear(self):
- self.payto_sig.setVisible(False)
- for e in [self.payto_e, self.message_e, self.amount_e, self.fee_e]:
- e.setText('')
- self.set_frozen(e,False)
- self.update_status()
-
- def set_frozen(self,entry,frozen):
- if frozen:
- entry.setReadOnly(True)
- entry.setFrame(False)
- palette = QPalette()
- palette.setColor(entry.backgroundRole(), QColor('lightgray'))
- entry.setPalette(palette)
- else:
- entry.setReadOnly(False)
- entry.setFrame(True)
- palette = QPalette()
- palette.setColor(entry.backgroundRole(), QColor('white'))
- entry.setPalette(palette)
-
-
- def toggle_freeze(self,addr):
- if not addr: return
- if addr in self.wallet.frozen_addresses:
- self.wallet.unfreeze(addr)
- else:
- self.wallet.freeze(addr)
- self.update_receive_tab()
-
- def toggle_priority(self,addr):
- if not addr: return
- if addr in self.wallet.prioritized_addresses:
- self.wallet.unprioritize(addr)
- else:
- self.wallet.prioritize(addr)
- self.update_receive_tab()
-
-
- def create_list_tab(self, headers):
- "generic tab creation method"
- l = MyTreeWidget(self)
- l.setColumnCount( len(headers) )
- l.setHeaderLabels( headers )
-
- w = QWidget()
- vbox = QVBoxLayout()
- w.setLayout(vbox)
-
- vbox.setMargin(0)
- vbox.setSpacing(0)
- vbox.addWidget(l)
- buttons = QWidget()
- vbox.addWidget(buttons)
-
- hbox = QHBoxLayout()
- hbox.setMargin(0)
- hbox.setSpacing(0)
- buttons.setLayout(hbox)
-
- return l,w,hbox
-
-
- def create_receive_tab(self):
- l,w,hbox = self.create_list_tab([ _('Address'), _('Label'), _('Balance'), _('Tx')])
- l.setContextMenuPolicy(Qt.CustomContextMenu)
- l.customContextMenuRequested.connect(self.create_receive_menu)
- self.connect(l, SIGNAL('itemDoubleClicked(QTreeWidgetItem*, int)'), lambda a, b: self.address_label_clicked(a,b,l,0,1))
- self.connect(l, SIGNAL('itemChanged(QTreeWidgetItem*, int)'), lambda a,b: self.address_label_changed(a,b,l,0,1))
- self.connect(l, SIGNAL('currentItemChanged(QTreeWidgetItem*, QTreeWidgetItem*)'), lambda a,b: self.current_item_changed(a))
- self.receive_list = l
- self.receive_buttons_hbox = hbox
- hbox.addStretch(1)
- return w
-
-
- def receive_tab_set_mode(self, i):
- self.save_column_widths()
- self.expert_mode = (i == 1)
- self.config.set_key('classic_expert_mode', self.expert_mode, True)
- self.update_receive_tab()
-
-
- def save_column_widths(self):
- if not self.expert_mode:
- widths = [ self.receive_list.columnWidth(0) ]
- else:
- widths = []
- for i in range(self.receive_list.columnCount() -1):
- widths.append(self.receive_list.columnWidth(i))
- self.column_widths["receive"][self.expert_mode] = widths
-
- self.column_widths["history"] = []
- for i in range(self.history_list.columnCount() - 1):
- self.column_widths["history"].append(self.history_list.columnWidth(i))
-
- self.column_widths["contacts"] = []
- for i in range(self.contacts_list.columnCount() - 1):
- self.column_widths["contacts"].append(self.contacts_list.columnWidth(i))
-
- self.config.set_key("column_widths", self.column_widths, True)
-
-
- def create_contacts_tab(self):
- l,w,hbox = self.create_list_tab([_('Address'), _('Label'), _('Tx')])
- l.setContextMenuPolicy(Qt.CustomContextMenu)
- l.customContextMenuRequested.connect(self.create_contact_menu)
- for i,width in enumerate(self.column_widths['contacts']):
- l.setColumnWidth(i, width)
-
- self.connect(l, SIGNAL('itemDoubleClicked(QTreeWidgetItem*, int)'), lambda a, b: self.address_label_clicked(a,b,l,0,1))
- self.connect(l, SIGNAL('itemChanged(QTreeWidgetItem*, int)'), lambda a,b: self.address_label_changed(a,b,l,0,1))
- self.contacts_list = l
- self.contacts_buttons_hbox = hbox
- hbox.addStretch(1)
- return w
-
-
- def delete_imported_key(self, addr):
- if self.question(_("Do you want to remove")+" %s "%addr +_("from your wallet?")):
- self.wallet.delete_imported_key(addr)
- self.update_receive_tab()
- self.update_history_tab()
-
-
- def create_receive_menu(self, position):
- # fixme: this function apparently has a side effect.
- # if it is not called the menu pops up several times
- #self.receive_list.selectedIndexes()
-
- item = self.receive_list.itemAt(position)
- if not item: return
- addr = unicode(item.text(0))
- if not is_valid(addr):
- item.setExpanded(not item.isExpanded())
- return
- menu = QMenu()
- menu.addAction(_("Copy to clipboard"), lambda: self.app.clipboard().setText(addr))
- menu.addAction(_("QR code"), lambda: self.show_qrcode("bitcoin:" + addr, _("Address")) )
- menu.addAction(_("Edit label"), lambda: self.edit_label(True))
- menu.addAction(_("Private key"), lambda: self.show_private_key(addr))
- menu.addAction(_("Sign message"), lambda: self.sign_message(addr))
- if addr in self.wallet.imported_keys:
- menu.addAction(_("Remove from wallet"), lambda: self.delete_imported_key(addr))
-
- if self.expert_mode:
- t = _("Unfreeze") if addr in self.wallet.frozen_addresses else _("Freeze")
- menu.addAction(t, lambda: self.toggle_freeze(addr))
- t = _("Unprioritize") if addr in self.wallet.prioritized_addresses else _("Prioritize")
- menu.addAction(t, lambda: self.toggle_priority(addr))
-
- run_hook('receive_menu', menu)
- menu.exec_(self.receive_list.viewport().mapToGlobal(position))
-
-
- def payto(self, addr):
- if not addr: return
- label = self.wallet.labels.get(addr)
- m_addr = label + ' <' + addr + '>' if label else addr
- self.tabs.setCurrentIndex(1)
- self.payto_e.setText(m_addr)
- self.amount_e.setFocus()
-
-
- def delete_contact(self, x):
- if self.question(_("Do you want to remove")+" %s "%x +_("from your list of contacts?")):
- self.wallet.delete_contact(x)
- self.set_label(x, None)
- self.update_history_tab()
- self.update_contacts_tab()
- self.update_completions()
-
-
- def create_contact_menu(self, position):
- item = self.contacts_list.itemAt(position)
- if not item: return
- addr = unicode(item.text(0))
- label = unicode(item.text(1))
- is_editable = item.data(0,32).toBool()
- payto_addr = item.data(0,33).toString()
- menu = QMenu()
- menu.addAction(_("Copy to Clipboard"), lambda: self.app.clipboard().setText(addr))
- menu.addAction(_("Pay to"), lambda: self.payto(payto_addr))
- menu.addAction(_("QR code"), lambda: self.show_qrcode("bitcoin:" + addr, _("Address")))
- if is_editable:
- menu.addAction(_("Edit label"), lambda: self.edit_label(False))
- menu.addAction(_("Delete"), lambda: self.delete_contact(addr))
-
- run_hook('create_contact_menu', menu, item)
- menu.exec_(self.contacts_list.viewport().mapToGlobal(position))
-
-
- def update_receive_item(self, item):
- item.setFont(0, QFont(MONOSPACE_FONT))
- address = str(item.data(0,0).toString())
- label = self.wallet.labels.get(address,'')
- item.setData(1,0,label)
- item.setData(0,32, True) # is editable
-
- run_hook('update_receive_item', address, item)
-
- c, u = self.wallet.get_addr_balance(address)
- balance = self.format_amount(c + u)
- item.setData(2,0,balance)
-
- if self.expert_mode:
- if address in self.wallet.frozen_addresses:
- item.setBackgroundColor(0, QColor('lightblue'))
- elif address in self.wallet.prioritized_addresses:
- item.setBackgroundColor(0, QColor('lightgreen'))
-
-
- def update_receive_tab(self):
- l = self.receive_list
-
- l.clear()
- l.setColumnHidden(2, not self.expert_mode)
- l.setColumnHidden(3, not self.expert_mode)
- for i,width in enumerate(self.column_widths['receive'][self.expert_mode]):
- l.setColumnWidth(i, width)
-
- if self.current_account is None:
- account_items = self.wallet.accounts.items()
- elif self.current_account != -1:
- account_items = [(self.current_account, self.wallet.accounts.get(self.current_account))]
- else:
- account_items = []
-
- for k, account in account_items:
- name = self.wallet.get_account_name(k)
- c,u = self.wallet.get_account_balance(k)
- account_item = QTreeWidgetItem( [ name, '', self.format_amount(c+u), ''] )
- l.addTopLevelItem(account_item)
- account_item.setExpanded(True)
-
- for is_change in ([0,1] if self.expert_mode else [0]):
- if self.expert_mode:
- name = _("Receiving") if not is_change else _("Change")
- seq_item = QTreeWidgetItem( [ name, '', '', '', ''] )
- account_item.addChild(seq_item)
- if not is_change: seq_item.setExpanded(True)
- else:
- seq_item = account_item
- is_red = False
- gap = 0
-
- for address in account.get_addresses(is_change):
- h = self.wallet.history.get(address,[])
-
- if h == []:
- gap += 1
- if gap > self.wallet.gap_limit:
- is_red = True
- else:
- gap = 0
-
- num_tx = '*' if h == ['*'] else "%d"%len(h)
- item = QTreeWidgetItem( [ address, '', '', num_tx] )
- self.update_receive_item(item)
- if is_red:
- item.setBackgroundColor(1, QColor('red'))
- seq_item.addChild(item)
-
-
- if self.wallet.imported_keys and (self.current_account is None or self.current_account == -1):
- c,u = self.wallet.get_imported_balance()
- account_item = QTreeWidgetItem( [ _('Imported'), '', self.format_amount(c+u), ''] )
- l.addTopLevelItem(account_item)
- account_item.setExpanded(True)
- for address in self.wallet.imported_keys.keys():
- item = QTreeWidgetItem( [ address, '', '', ''] )
- self.update_receive_item(item)
- account_item.addChild(item)
-
-
- # we use column 1 because column 0 may be hidden
- l.setCurrentItem(l.topLevelItem(0),1)
-
-
- def update_contacts_tab(self):
- l = self.contacts_list
- l.clear()
-
- for address in self.wallet.addressbook:
- label = self.wallet.labels.get(address,'')
- n = self.wallet.get_num_tx(address)
- item = QTreeWidgetItem( [ address, label, "%d"%n] )
- item.setFont(0, QFont(MONOSPACE_FONT))
- # 32 = label can be edited (bool)
- item.setData(0,32, True)
- # 33 = payto string
- item.setData(0,33, address)
- l.addTopLevelItem(item)
-
- run_hook('update_contacts_tab', l)
- l.setCurrentItem(l.topLevelItem(0))
-
-
-
- def create_console_tab(self):
- from qt_console import Console
- self.console = console = Console()
- return console
-
-
- def update_console(self):
- console = self.console
- console.history = self.config.get("console-history",[])
- console.history_index = len(console.history)
-
- console.updateNamespace({'wallet' : self.wallet, 'network' : self.network, 'gui':self})
- console.updateNamespace({'util' : util, 'bitcoin':bitcoin})
-
- c = commands.Commands(self.wallet, self.network, lambda: self.console.set_json(True))
- methods = {}
- def mkfunc(f, method):
- return lambda *args: apply( f, (method, args, self.password_dialog ))
- for m in dir(c):
- if m[0]=='_' or m=='wallet' or m == 'interface': continue
- methods[m] = mkfunc(c._run, m)
-
- console.updateNamespace(methods)
-
-
- def change_account(self,s):
- if s == _("All accounts"):
- self.current_account = None
- else:
- accounts = self.wallet.get_account_names()
- for k, v in accounts.items():
- if v == s:
- self.current_account = k
- self.update_history_tab()
- self.update_status()
- self.update_receive_tab()
-
- def create_status_bar(self):
-
- sb = QStatusBar()
- sb.setFixedHeight(35)
- qtVersion = qVersion()
-
- self.balance_label = QLabel("")
- sb.addWidget(self.balance_label)
-
- from version_getter import UpdateLabel
- self.updatelabel = UpdateLabel(self.config, sb)
-
- self.account_selector = QComboBox()
- self.connect(self.account_selector,SIGNAL("activated(QString)"),self.change_account)
- sb.addPermanentWidget(self.account_selector)
-
- if (int(qtVersion[0]) >= 4 and int(qtVersion[2]) >= 7):
- sb.addPermanentWidget( StatusBarButton( QIcon(":icons/switchgui.png"), _("Switch to Lite Mode"), self.go_lite ) )
-
- self.lock_icon = QIcon()
- self.password_button = StatusBarButton( self.lock_icon, _("Password"), self.change_password_dialog )
- sb.addPermanentWidget( self.password_button )
-
- sb.addPermanentWidget( StatusBarButton( QIcon(":icons/preferences.png"), _("Preferences"), self.settings_dialog ) )
- self.seed_button = StatusBarButton( QIcon(":icons/seed.png"), _("Seed"), self.show_seed_dialog )
- sb.addPermanentWidget( self.seed_button )
- self.status_button = StatusBarButton( QIcon(":icons/status_disconnected.png"), _("Network"), self.run_network_dialog )
- sb.addPermanentWidget( self.status_button )
-
- run_hook('create_status_bar', (sb,))
-
- self.setStatusBar(sb)
-
-
- def update_lock_icon(self):
- icon = QIcon(":icons/lock.png") if self.wallet.use_encryption else QIcon(":icons/unlock.png")
- self.password_button.setIcon( icon )
-
-
- def update_buttons_on_seed(self):
- if self.wallet.seed:
- self.seed_button.show()
- self.password_button.show()
- self.send_button.setText(_("Send"))
- else:
- self.password_button.hide()
- self.seed_button.hide()
- self.send_button.setText(_("Create unsigned transaction"))
-
-
- def change_password_dialog(self):
- from password_dialog import PasswordDialog
- d = PasswordDialog(self.wallet, self)
- d.run()
- self.update_lock_icon()
-
-
- def new_contact_dialog(self):
- text, ok = QInputDialog.getText(self, _('New Contact'), _('Address') + ':')
- address = unicode(text)
- if ok:
- if is_valid(address):
- self.wallet.add_contact(address)
- self.update_contacts_tab()
- self.update_history_tab()
- self.update_completions()
- else:
- QMessageBox.warning(self, _('Error'), _('Invalid Address'), _('OK'))
-
-
- def new_account_dialog(self):
-
- dialog = QDialog(self)
- dialog.setModal(1)
- dialog.setWindowTitle(_("New Account"))
-
- addr = self.wallet.new_account_address()
- vbox = QVBoxLayout()
- msg = _("Electrum considers that an account exists only if it contains bitcoins.") + '\n' \
- + _("To create a new account, please send coins to the first address of that account.") + '\n' \
- + _("Note: you will need to wait for 2 confirmations before the account is created.")
- vbox.addWidget(QLabel(msg))
- vbox.addWidget(QLabel(_('Address')+':'))
- e = QLineEdit(addr)
- e.setReadOnly(True)
- vbox.addWidget(e)
-
- vbox.addLayout(ok_cancel_buttons(dialog))
- dialog.setLayout(vbox)
- r = dialog.exec_()
- if r:
- self.payto(addr)
-
-
-
- def show_master_public_key(self):
- dialog = QDialog(self)
- dialog.setModal(1)
- dialog.setWindowTitle(_("Master Public Key"))
-
- main_text = QTextEdit()
- main_text.setText(self.wallet.get_master_public_key())
- main_text.setReadOnly(True)
- main_text.setMaximumHeight(170)
- qrw = QRCodeWidget(self.wallet.get_master_public_key())
-
- ok_button = QPushButton(_("OK"))
- ok_button.setDefault(True)
- ok_button.clicked.connect(dialog.accept)
-
- main_layout = QGridLayout()
- main_layout.addWidget(QLabel(_('Your Master Public Key is:')), 0, 0, 1, 2)
-
- main_layout.addWidget(main_text, 1, 0)
- main_layout.addWidget(qrw, 1, 1 )
-
- vbox = QVBoxLayout()
- vbox.addLayout(main_layout)
- hbox = QHBoxLayout()
- hbox.addStretch(1)
- hbox.addWidget(ok_button)
- vbox.addLayout(hbox)
-
- dialog.setLayout(vbox)
- dialog.exec_()
-
-
- @protected
- def show_seed_dialog(self, password):
- if not self.wallet.seed:
- QMessageBox.information(parent, _('Message'), _('No seed'), _('OK'))
- return
- try:
- seed = self.wallet.decode_seed(password)
- except:
- QMessageBox.warning(self, _('Error'), _('Incorrect Password'), _('OK'))
- return
-
- from seed_dialog import SeedDialog
- d = SeedDialog(self)
- d.show_seed(seed, self.wallet.imported_keys)
-
-
-
- def show_qrcode(self, data, title = _("QR code")):
- if not data: return
- d = QDialog(self)
- d.setModal(1)
- d.setWindowTitle(title)
- d.setMinimumSize(270, 300)
- vbox = QVBoxLayout()
- qrw = QRCodeWidget(data)
- vbox.addWidget(qrw, 1)
- vbox.addWidget(QLabel(data), 0, Qt.AlignHCenter)
- hbox = QHBoxLayout()
- hbox.addStretch(1)
-
- def print_qr(self):
- filename = "qrcode.bmp"
- bmp.save_qrcode(qrw.qr, filename)
- QMessageBox.information(None, _('Message'), _("QR code saved to file") + " " + filename, _('OK'))
-
- b = QPushButton(_("Save"))
- hbox.addWidget(b)
- b.clicked.connect(print_qr)
-
- b = QPushButton(_("Close"))
- hbox.addWidget(b)
- b.clicked.connect(d.accept)
- b.setDefault(True)
-
- vbox.addLayout(hbox)
- d.setLayout(vbox)
- d.exec_()
-
-
- def do_protect(self, func, args):
- if self.wallet.use_encryption:
- password = self.password_dialog()
- if not password:
- return
- else:
- password = None
-
- if args != (False,):
- args = (self,) + args + (password,)
- else:
- args = (self,password)
- apply( func, args)
-
-
- @protected
- def show_private_key(self, address, password):
- if not address: return
- try:
- pk_list = self.wallet.get_private_key(address, password)
- except BaseException, e:
- self.show_message(str(e))
- return
- QMessageBox.information(self, _('Private key'), _('Address')+ ': ' + address + '\n\n' + _('Private key') + ': ' + '\n'.join(pk_list), _('OK'))
-
-
- @protected
- def do_sign(self, address, message, signature, password):
- message = unicode(message.toPlainText())
- message = message.encode('utf-8')
- try:
- sig = self.wallet.sign_message(str(address.text()), message, password)
- signature.setText(sig)
- except BaseException, e:
- self.show_message(str(e))
-
- def sign_message(self, address):
- if not address: return
- d = QDialog(self)
- d.setModal(1)
- d.setWindowTitle(_('Sign Message'))
- d.setMinimumSize(410, 290)
-
- tab_widget = QTabWidget()
- tab = QWidget()
- layout = QGridLayout(tab)
-
- sign_address = QLineEdit()
-
- sign_address.setText(address)
- layout.addWidget(QLabel(_('Address')), 1, 0)
- layout.addWidget(sign_address, 1, 1)
-
- sign_message = QTextEdit()
- layout.addWidget(QLabel(_('Message')), 2, 0)
- layout.addWidget(sign_message, 2, 1)
- layout.setRowStretch(2,3)
-
- sign_signature = QTextEdit()
- layout.addWidget(QLabel(_('Signature')), 3, 0)
- layout.addWidget(sign_signature, 3, 1)
- layout.setRowStretch(3,1)
-
-
- hbox = QHBoxLayout()
- b = QPushButton(_("Sign"))
- hbox.addWidget(b)
- b.clicked.connect(lambda: self.do_sign(sign_address, sign_message, sign_signature))
- b = QPushButton(_("Close"))
- b.clicked.connect(d.accept)
- hbox.addWidget(b)
- layout.addLayout(hbox, 4, 1)
- tab_widget.addTab(tab, _("Sign"))
-
-
- tab = QWidget()
- layout = QGridLayout(tab)
-
- verify_address = QLineEdit()
- layout.addWidget(QLabel(_('Address')), 1, 0)
- layout.addWidget(verify_address, 1, 1)
-
- verify_message = QTextEdit()
- layout.addWidget(QLabel(_('Message')), 2, 0)
- layout.addWidget(verify_message, 2, 1)
- layout.setRowStretch(2,3)
-
- verify_signature = QTextEdit()
- layout.addWidget(QLabel(_('Signature')), 3, 0)
- layout.addWidget(verify_signature, 3, 1)
- layout.setRowStretch(3,1)
-
- def do_verify():
- message = unicode(verify_message.toPlainText())
- message = message.encode('utf-8')
- if self.wallet.verify_message(verify_address.text(), str(verify_signature.toPlainText()), message):
- self.show_message(_("Signature verified"))
- else:
- self.show_message(_("Error: wrong signature"))
-
- hbox = QHBoxLayout()
- b = QPushButton(_("Verify"))
- b.clicked.connect(do_verify)
- hbox.addWidget(b)
- b = QPushButton(_("Close"))
- b.clicked.connect(d.accept)
- hbox.addWidget(b)
- layout.addLayout(hbox, 4, 1)
- tab_widget.addTab(tab, _("Verify"))
-
- vbox = QVBoxLayout()
- vbox.addWidget(tab_widget)
- d.setLayout(vbox)
- d.exec_()
-
-
-
-
- def question(self, msg):
- return QMessageBox.question(self, _('Message'), msg, QMessageBox.Yes | QMessageBox.No, QMessageBox.No) == QMessageBox.Yes
-
- def show_message(self, msg):
- QMessageBox.information(self, _('Message'), msg, _('OK'))
-
- def password_dialog(self ):
- d = QDialog(self)
- d.setModal(1)
-
- pw = QLineEdit()
- pw.setEchoMode(2)
-
- vbox = QVBoxLayout()
- msg = _('Please enter your password')
- vbox.addWidget(QLabel(msg))
-
- grid = QGridLayout()
- grid.setSpacing(8)
- grid.addWidget(QLabel(_('Password')), 1, 0)
- grid.addWidget(pw, 1, 1)
- vbox.addLayout(grid)
-
- vbox.addLayout(ok_cancel_buttons(d))
- d.setLayout(vbox)
-
- run_hook('password_dialog', pw, grid, 1)
- if not d.exec_(): return
- return unicode(pw.text())
-
-
-
-
-
-
-
-
- def tx_from_text(self, txt):
- "json or raw hexadecimal"
- try:
- txt.decode('hex')
- tx = Transaction(txt)
- return tx
- except:
- pass
-
- try:
- tx_dict = json.loads(str(txt))
- assert "hex" in tx_dict.keys()
- assert "complete" in tx_dict.keys()
- if not tx_dict["complete"]:
- assert "input_info" in tx_dict.keys()
- tx = Transaction(tx_dict["hex"])
- return tx
- except:
- pass
-
- QMessageBox.critical(None, _("Unable to parse transaction"), _("Electrum was unable to parse your transaction"))
-
-
-
- def read_tx_from_file(self):
- fileName = self.getOpenFileName(_("Select your transaction file"), "*.txn")
- if not fileName:
- return
- try:
- with open(fileName, "r") as f:
- file_content = f.read()
- except (ValueError, IOError, os.error), reason:
- QMessageBox.critical(None, _("Unable to read file or no transaction found"), _("Electrum was unable to open your transaction file") + "\n" + str(reason))
-
- return self.tx_from_text(file_content)
-
-
- @protected
- def sign_raw_transaction(self, tx, input_info, password):
- self.wallet.signrawtransaction(tx, input_info, [], password)
-
- def do_process_from_text(self):
- text = text_dialog(self, _('Input raw transaction'), _("Transaction:"), _("Load transaction"))
- if not text:
- return
- tx = self.tx_from_text(text)
- if tx:
- self.show_transaction(tx)
-
- def do_process_from_file(self):
- tx = self.read_tx_from_file()
- if tx:
- self.show_transaction(tx)
-
- def do_process_from_csvReader(self, csvReader):
- outputs = []
- try:
- for row in csvReader:
- address = row[0]
- amount = float(row[1])
- amount = int(100000000*amount)
- outputs.append((address, amount))
- except (ValueError, IOError, os.error), reason:
- QMessageBox.critical(None, _("Unable to read file or no transaction found"), _("Electrum was unable to open your transaction file") + "\n" + str(reason))
- return
-
- try:
- tx = self.wallet.make_unsigned_transaction(outputs, None, None)
- except BaseException, e:
- self.show_message(str(e))
- return
-
- self.show_transaction(tx)
-
- def do_process_from_csv_file(self):
- fileName = self.getOpenFileName(_("Select your transaction CSV"), "*.csv")
- if not fileName:
- return
- try:
- with open(fileName, "r") as f:
- csvReader = csv.reader(f)
- self.do_process_from_csvReader(csvReader)
- except (ValueError, IOError, os.error), reason:
- QMessageBox.critical(None, _("Unable to read file or no transaction found"), _("Electrum was unable to open your transaction file") + "\n" + str(reason))
- return
-
- def do_process_from_csv_text(self):
- text = text_dialog(self, _('Input CSV'), _("CSV:"), _("Load CSV"))
- if not text:
- return
- f = StringIO.StringIO(text)
- csvReader = csv.reader(f)
- self.do_process_from_csvReader(csvReader)
-
-
-
- @protected
- def do_export_privkeys(self, password):
- self.show_message("%s\n%s\n%s" % (_("WARNING: ALL your private keys are secret."), _("Exposing a single private key can compromise your entire wallet!"), _("In particular, DO NOT use 'redeem private key' services proposed by third parties.")))
-
- try:
- select_export = _('Select file to export your private keys to')
- fileName = self.getSaveFileName(select_export, 'electrum-private-keys.csv', "*.csv")
- if fileName:
- with open(fileName, "w+") as csvfile:
- transaction = csv.writer(csvfile)
- transaction.writerow(["address", "private_key"])
-
- addresses = self.wallet.addresses(True)
-
- for addr in addresses:
- pk = "".join(self.wallet.get_private_key(addr, password))
- transaction.writerow(["%34s"%addr,pk])
-
- self.show_message(_("Private keys exported."))
-
- except (IOError, os.error), reason:
- export_error_label = _("Electrum was unable to produce a private key-export.")
- QMessageBox.critical(None, _("Unable to create csv"), export_error_label + "\n" + str(reason))
-
- except BaseException, e:
- self.show_message(str(e))
- return
-
-
- def do_import_labels(self):
- labelsFile = self.getOpenFileName(_("Open labels file"), "*.dat")
- if not labelsFile: return
- try:
- f = open(labelsFile, 'r')
- data = f.read()
- f.close()
- for key, value in json.loads(data).items():
- self.wallet.set_label(key, value)
- QMessageBox.information(None, _("Labels imported"), _("Your labels were imported from")+" '%s'" % str(labelsFile))
- except (IOError, os.error), reason:
- QMessageBox.critical(None, _("Unable to import labels"), _("Electrum was unable to import your labels.")+"\n" + str(reason))
-
-
- def do_export_labels(self):
- labels = self.wallet.labels
- try:
- fileName = self.getSaveFileName(_("Select file to save your labels"), 'electrum_labels.dat', "*.dat")
- if fileName:
- with open(fileName, 'w+') as f:
- json.dump(labels, f)
- QMessageBox.information(None, _("Labels exported"), _("Your labels where exported to")+" '%s'" % str(fileName))
- except (IOError, os.error), reason:
- QMessageBox.critical(None, _("Unable to export labels"), _("Electrum was unable to export your labels.")+"\n" + str(reason))
-
-
- def do_export_history(self):
- from lite_window import csv_transaction
- csv_transaction(self.wallet)
-
-
- @protected
- def do_import_privkey(self, password):
- if not self.wallet.imported_keys:
- r = QMessageBox.question(None, _('Warning'), '<b>'+_('Warning') +':\n</b><br/>'+ _('Imported keys are not recoverable from seed.') + ' ' \
- + _('If you ever need to restore your wallet from its seed, these keys will be lost.') + '<p>' \
- + _('Are you sure you understand what you are doing?'), 3, 4)
- if r == 4: return
-
- text = text_dialog(self, _('Import private keys'), _("Enter private keys")+':', _("Import"))
- if not text: return
-
- text = str(text).split()
- badkeys = []
- addrlist = []
- for key in text:
- try:
- addr = self.wallet.import_key(key, password)
- except BaseException as e:
- badkeys.append(key)
- continue
- if not addr:
- badkeys.append(key)
- else:
- addrlist.append(addr)
- if addrlist:
- QMessageBox.information(self, _('Information'), _("The following addresses were added") + ':\n' + '\n'.join(addrlist))
- if badkeys:
- QMessageBox.critical(self, _('Error'), _("The following inputs could not be imported") + ':\n'+ '\n'.join(badkeys))
- self.update_receive_tab()
- self.update_history_tab()
-
-
- def settings_dialog(self):
- d = QDialog(self)
- d.setWindowTitle(_('Electrum Settings'))
- d.setModal(1)
- vbox = QVBoxLayout()
-
- tabs = QTabWidget(self)
- self.settings_tab = tabs
- vbox.addWidget(tabs)
-
- tab1 = QWidget()
- grid_ui = QGridLayout(tab1)
- grid_ui.setColumnStretch(0,1)
- tabs.addTab(tab1, _('Display') )
-
- nz_label = QLabel(_('Display zeros'))
- grid_ui.addWidget(nz_label, 0, 0)
- nz_e = AmountEdit(None,True)
- nz_e.setText("%d"% self.num_zeros)
- grid_ui.addWidget(nz_e, 0, 1)
- msg = _('Number of zeros displayed after the decimal point. For example, if this is set to 2, "1." will be displayed as "1.00"')
- grid_ui.addWidget(HelpButton(msg), 0, 2)
- if not self.config.is_modifiable('num_zeros'):
- for w in [nz_e, nz_label]: w.setEnabled(False)
-
- lang_label=QLabel(_('Language') + ':')
- grid_ui.addWidget(lang_label, 1, 0)
- lang_combo = QComboBox()
- from electrum.i18n import languages
- lang_combo.addItems(languages.values())
- try:
- index = languages.keys().index(self.config.get("language",''))
- except:
- index = 0
- lang_combo.setCurrentIndex(index)
- grid_ui.addWidget(lang_combo, 1, 1)
- grid_ui.addWidget(HelpButton(_('Select which language is used in the GUI (after restart).')+' '), 1, 2)
- if not self.config.is_modifiable('language'):
- for w in [lang_combo, lang_label]: w.setEnabled(False)
-
- expert_cb = QCheckBox(_('Expert mode'))
- expert_cb.setChecked(self.expert_mode)
- grid_ui.addWidget(expert_cb, 3, 0)
- hh = _('In expert mode, your client will:') + '\n' \
- + _(' - Show change addresses in the Receive tab') + '\n' \
- + _(' - Display the balance of each address') + '\n' \
- + _(' - Add freeze/prioritize actions to addresses.')
- grid_ui.addWidget(HelpButton(hh), 3, 2)
- grid_ui.setRowStretch(4,1)
-
- # wallet tab
- tab2 = QWidget()
- grid_wallet = QGridLayout(tab2)
- grid_wallet.setColumnStretch(0,1)
- tabs.addTab(tab2, _('Wallet') )
-
- fee_label = QLabel(_('Transaction fee'))
- grid_wallet.addWidget(fee_label, 0, 0)
- fee_e = AmountEdit(self.base_unit)
- fee_e.setText(self.format_amount(self.wallet.fee).strip())
- grid_wallet.addWidget(fee_e, 0, 2)
- msg = _('Fee per kilobyte of transaction.') + ' ' \
- + _('Recommended value') + ': ' + self.format_amount(50000)
- grid_wallet.addWidget(HelpButton(msg), 0, 3)
- if not self.config.is_modifiable('fee_per_kb'):
- for w in [fee_e, fee_label]: w.setEnabled(False)
-
- usechange_cb = QCheckBox(_('Use change addresses'))
- usechange_cb.setChecked(self.wallet.use_change)
- grid_wallet.addWidget(usechange_cb, 1, 0)
- grid_wallet.addWidget(HelpButton(_('Using change addresses makes it more difficult for other people to track your transactions.')+' '), 1, 3)
- if not self.config.is_modifiable('use_change'): usechange_cb.setEnabled(False)
-
- units = ['BTC', 'mBTC']
- unit_label = QLabel(_('Base unit'))
- grid_wallet.addWidget(unit_label, 3, 0)
- unit_combo = QComboBox()
- unit_combo.addItems(units)
- unit_combo.setCurrentIndex(units.index(self.base_unit()))
- grid_wallet.addWidget(unit_combo, 3, 2)
- grid_wallet.addWidget(HelpButton(_('Base unit of your wallet.')\
- + '\n1BTC=1000mBTC.\n' \
- + _(' This settings affects the fields in the Send tab')+' '), 3, 3)
- grid_wallet.setRowStretch(4,1)
-
-
- run_hook('create_settings_tab', tabs)
-
- vbox.addLayout(ok_cancel_buttons(d))
- d.setLayout(vbox)
-
- # run the dialog
- if not d.exec_(): return
-
- fee = unicode(fee_e.text())
- try:
- fee = self.read_amount(fee)
- except:
- QMessageBox.warning(self, _('Error'), _('Invalid value') +': %s'%fee, _('OK'))
- return
-
- self.wallet.set_fee(fee)
-
- nz = unicode(nz_e.text())
- try:
- nz = int( nz )
- if nz>8: nz=8
- except:
- QMessageBox.warning(self, _('Error'), _('Invalid value')+':%s'%nz, _('OK'))
- return
-
- if self.num_zeros != nz:
- self.num_zeros = nz
- self.config.set_key('num_zeros', nz, True)
- self.update_history_tab()
- self.update_receive_tab()
-
- usechange_result = usechange_cb.isChecked()
- if self.wallet.use_change != usechange_result:
- self.wallet.use_change = usechange_result
- self.config.set_key('use_change', self.wallet.use_change, True)
-
- unit_result = units[unit_combo.currentIndex()]
- if self.base_unit() != unit_result:
- self.decimal_point = 8 if unit_result == 'BTC' else 5
- self.config.set_key('decimal_point', self.decimal_point, True)
- self.update_history_tab()
- self.update_status()
-
- need_restart = False
-
- lang_request = languages.keys()[lang_combo.currentIndex()]
- if lang_request != self.config.get('language'):
- self.config.set_key("language", lang_request, True)
- need_restart = True
-
-
- run_hook('close_settings_dialog')
-
- if need_restart:
- QMessageBox.warning(self, _('Success'), _('Please restart Electrum to activate the new GUI settings'), _('OK'))
-
- self.receive_tab_set_mode(expert_cb.isChecked())
-
- def run_network_dialog(self):
- NetworkDialog(self.wallet.network, self.config, self).do_exec()
-
- def closeEvent(self, event):
- g = self.geometry()
- self.config.set_key("winpos-qt", [g.left(),g.top(),g.width(),g.height()], True)
- self.save_column_widths()
- self.config.set_key("console-history", self.console.history[-50:], True)
- event.accept()
-
-
-
- def plugins_dialog(self):
- from electrum.plugins import plugins
-
- d = QDialog(self)
- d.setWindowTitle(_('Electrum Plugins'))
- d.setModal(1)
-
- vbox = QVBoxLayout(d)
-
- # plugins
- scroll = QScrollArea()
- scroll.setEnabled(True)
- scroll.setWidgetResizable(True)
- scroll.setMinimumSize(400,250)
- vbox.addWidget(scroll)
-
- w = QWidget()
- scroll.setWidget(w)
- w.setMinimumHeight(len(plugins)*35)
-
- grid = QGridLayout()
- grid.setColumnStretch(0,1)
- w.setLayout(grid)
-
- def mk_toggle(cb, p):
- return lambda: cb.setChecked(p.toggle())
- for i, p in enumerate(plugins):
- try:
- cb = QCheckBox(p.fullname())
- cb.setDisabled(not p.is_available())
- cb.setChecked(p.is_enabled())
- cb.clicked.connect(mk_toggle(cb,p))
- grid.addWidget(cb, i, 0)
- if p.requires_settings():
- grid.addWidget(EnterButton(_('Settings'), p.settings_dialog), i, 1)
- grid.addWidget(HelpButton(p.description()), i, 2)
- except:
- print_msg(_("Error: cannot display plugin"), p)
- traceback.print_exc(file=sys.stdout)
- grid.setRowStretch(i+1,1)
-
- vbox.addLayout(close_button(d))
-
- d.exec_()
diff --git a/gui/gui_classic/network_dialog.py b/gui/gui_classic/network_dialog.py
@@ -1,244 +0,0 @@
-#!/usr/bin/env python
-#
-# Electrum - lightweight Bitcoin client
-# Copyright (C) 2012 thomasv@gitorious
-#
-# This program is free software: you can redistribute it and/or modify
-# it under the terms of the GNU General Public License as published by
-# the Free Software Foundation, either version 3 of the License, or
-# (at your option) any later version.
-#
-# This program is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-# GNU General Public License for more details.
-#
-# You should have received a copy of the GNU General Public License
-# along with this program. If not, see <http://www.gnu.org/licenses/>.
-
-import sys, time, datetime, re, threading
-from electrum.i18n import _
-from electrum.util import print_error, print_msg
-import os.path, json, ast, traceback
-
-from PyQt4.QtGui import *
-from PyQt4.QtCore import *
-from electrum import DEFAULT_SERVERS, DEFAULT_PORTS
-
-from qt_util import *
-
-protocol_names = ['TCP', 'HTTP', 'SSL', 'HTTPS']
-protocol_letters = 'thsg'
-
-class NetworkDialog(QDialog):
- def __init__(self, network, config, parent):
-
- QDialog.__init__(self,parent)
- self.setModal(1)
- self.setWindowTitle(_('Server'))
- self.setMinimumSize(375, 20)
-
- self.network = network
- self.interface = interface = network.interface
- self.config = config
- self.protocol = None
-
- if parent:
- n = len(network.interfaces)
- if n:
- status = _("Connected to %d servers")%n + ", %d "%(network.blockchain.height) + _("blocks")
- else:
- status = _("Not connected")
-
- if interface.is_connected:
- status += "\n" + _("Main server:") + " %s"%(interface.host)
- else:
- status += "\n" + _("Disconnected from main server")
-
-
- server = interface.server
- else:
- import random
- status = _("Please choose a server.") + "\n" + _("Select 'Cancel' if you are offline.")
- server = interface.server
-
- self.servers = network.get_servers()
-
-
- vbox = QVBoxLayout()
- vbox.setSpacing(30)
-
- hbox = QHBoxLayout()
- l = QLabel()
- l.setPixmap(QPixmap(":icons/network.png"))
- hbox.addStretch(10)
- hbox.addWidget(l)
- hbox.addWidget(QLabel(status))
- hbox.addStretch(50)
- hbox.addWidget(HelpButton(_("As of version 1.9, Electrum connects to several servers in order to download block headers and find out the longest blockchain. However, your wallet addresses are sent to a single server, in order to receive your transaction history.")))
- vbox.addLayout(hbox)
-
- # grid layout
- grid = QGridLayout()
- grid.setSpacing(8)
- vbox.addLayout(grid)
-
- # server
- self.server_protocol = QComboBox()
- self.server_host = QLineEdit()
- self.server_host.setFixedWidth(200)
- self.server_port = QLineEdit()
- self.server_port.setFixedWidth(60)
-
- self.server_protocol.addItems(protocol_names)
-
- grid.addWidget(QLabel(_('Server') + ':'), 0, 0)
- grid.addWidget(self.server_protocol, 0, 1)
- grid.addWidget(self.server_host, 0, 2)
- grid.addWidget(self.server_port, 0, 3)
-
- self.server_protocol.connect(self.server_protocol, SIGNAL('currentIndexChanged(int)'), self.change_protocol)
-
- label = _('Active Servers') if interface.servers else _('Default Servers')
- self.servers_list_widget = QTreeWidget(parent)
- self.servers_list_widget.setHeaderLabels( [ label, _('Limit') ] )
- self.servers_list_widget.setMaximumHeight(150)
- self.servers_list_widget.setColumnWidth(0, 240)
-
- if server:
- host, port, protocol = server.split(':')
- self.set_protocol(protocol)
- self.change_server(host, protocol)
- else:
- self.set_protocol('s')
-
- self.servers_list_widget.connect(self.servers_list_widget,
- SIGNAL('currentItemChanged(QTreeWidgetItem*,QTreeWidgetItem*)'),
- lambda x,y: self.server_changed(x))
- grid.addWidget(self.servers_list_widget, 1, 1, 1, 3)
-
- if not config.is_modifiable('server'):
- for w in [self.server_host, self.server_port, self.server_protocol, self.servers_list_widget]: w.setEnabled(False)
-
- # auto cycle
- self.autocycle_cb = QCheckBox(_('Try random servers if disconnected'))
- self.autocycle_cb.setChecked(self.config.get('auto_cycle', True))
- grid.addWidget(self.autocycle_cb, 3, 1, 3, 2)
- if not self.config.is_modifiable('auto_cycle'): self.autocycle_cb.setEnabled(False)
-
- # proxy setting
- self.proxy_mode = QComboBox()
- self.proxy_host = QLineEdit()
- self.proxy_host.setFixedWidth(200)
- self.proxy_port = QLineEdit()
- self.proxy_port.setFixedWidth(60)
- self.proxy_mode.addItems(['NONE', 'SOCKS4', 'SOCKS5', 'HTTP'])
-
- def check_for_disable(index = False):
- if self.proxy_mode.currentText() != 'NONE':
- self.proxy_host.setEnabled(True)
- self.proxy_port.setEnabled(True)
- else:
- self.proxy_host.setEnabled(False)
- self.proxy_port.setEnabled(False)
-
- check_for_disable()
- self.proxy_mode.connect(self.proxy_mode, SIGNAL('currentIndexChanged(int)'), check_for_disable)
-
- if not self.config.is_modifiable('proxy'):
- for w in [self.proxy_host, self.proxy_port, self.proxy_mode]: w.setEnabled(False)
-
- proxy_config = interface.proxy if interface.proxy else { "mode":"none", "host":"localhost", "port":"8080"}
- self.proxy_mode.setCurrentIndex(self.proxy_mode.findText(str(proxy_config.get("mode").upper())))
- self.proxy_host.setText(proxy_config.get("host"))
- self.proxy_port.setText(proxy_config.get("port"))
-
- grid.addWidget(QLabel(_('Proxy') + ':'), 2, 0)
- grid.addWidget(self.proxy_mode, 2, 1)
- grid.addWidget(self.proxy_host, 2, 2)
- grid.addWidget(self.proxy_port, 2, 3)
-
- # buttons
- vbox.addLayout(ok_cancel_buttons(self))
- self.setLayout(vbox)
-
-
- def init_servers_list(self):
- self.servers_list_widget.clear()
- for _host, d in self.servers.items():
- if d.get(self.protocol):
- pruning_level = d.get('pruning','')
- self.servers_list_widget.addTopLevelItem(QTreeWidgetItem( [ _host, pruning_level ] ))
-
-
- def set_protocol(self, protocol):
- if protocol != self.protocol:
- self.protocol = protocol
- self.init_servers_list()
-
- def change_protocol(self, index):
- p = protocol_letters[index]
- host = unicode(self.server_host.text())
- pp = self.servers.get(host)
- if p not in pp.keys():
- p = pp.keys()[0]
- port = pp[p]
- self.server_host.setText( host )
- self.server_port.setText( port )
- self.set_protocol(p)
-
- def server_changed(self, x):
- if x:
- self.change_server(str(x.text(0)), self.protocol)
-
- def change_server(self, host, protocol):
-
- pp = self.servers.get(host, DEFAULT_PORTS)
- if protocol:
- port = pp.get(protocol)
- if not port: protocol = None
-
- if not protocol:
- if 's' in pp.keys():
- protocol = 's'
- port = pp.get(protocol)
- else:
- protocol = pp.keys()[0]
- port = pp.get(protocol)
-
- self.server_host.setText( host )
- self.server_port.setText( port )
- self.server_protocol.setCurrentIndex(protocol_letters.index(protocol))
-
- if not self.servers: return
- for p in protocol_letters:
- i = protocol_letters.index(p)
- j = self.server_protocol.model().index(i,0)
- #if p not in pp.keys(): # and self.interface.is_connected:
- # self.server_protocol.model().setData(j, QVariant(0), Qt.UserRole-1)
- #else:
- # self.server_protocol.model().setData(j, QVariant(33), Qt.UserRole-1)
-
-
- def do_exec(self):
-
- if not self.exec_():
- return
-
- server = ':'.join([str( self.server_host.text() ),
- str( self.server_port.text() ),
- (protocol_letters[self.server_protocol.currentIndex()]) ])
-
- if self.proxy_mode.currentText() != 'NONE':
- proxy = { 'mode':str(self.proxy_mode.currentText()).lower(),
- 'host':str(self.proxy_host.text()),
- 'port':str(self.proxy_port.text()) }
- else:
- proxy = None
-
- self.config.set_key("proxy", proxy, True)
- self.config.set_key("server", server, True)
- self.network.set_server(server, proxy)
-
- self.config.set_key('auto_cycle', self.autocycle_cb.isChecked(), True)
- return True
diff --git a/gui/gui_classic/qt_console.py b/gui/gui_classic/qt_console.py
@@ -1,315 +0,0 @@
-# source: http://stackoverflow.com/questions/2758159/how-to-embed-a-python-interpreter-in-a-pyqt-widget
-
-import sys, os, re
-import traceback, platform
-from PyQt4 import QtCore
-from PyQt4 import QtGui
-from electrum import util
-
-
-if platform.system() == 'Windows':
- MONOSPACE_FONT = 'Lucida Console'
-elif platform.system() == 'Darwin':
- MONOSPACE_FONT = 'Monaco'
-else:
- MONOSPACE_FONT = 'monospace'
-
-
-class Console(QtGui.QPlainTextEdit):
- def __init__(self, prompt='>> ', startup_message='', parent=None):
- QtGui.QPlainTextEdit.__init__(self, parent)
-
- self.prompt = prompt
- self.history = []
- self.namespace = {}
- self.construct = []
-
- self.setGeometry(50, 75, 600, 400)
- self.setWordWrapMode(QtGui.QTextOption.WrapAnywhere)
- self.setUndoRedoEnabled(False)
- self.document().setDefaultFont(QtGui.QFont(MONOSPACE_FONT, 10, QtGui.QFont.Normal))
- self.showMessage(startup_message)
-
- self.updateNamespace({'run':self.run_script})
- self.set_json(False)
-
- def set_json(self, b):
- self.is_json = b
-
- def run_script(self, filename):
- with open(filename) as f:
- script = f.read()
- result = eval(script, self.namespace, self.namespace)
-
-
-
- def updateNamespace(self, namespace):
- self.namespace.update(namespace)
-
- def showMessage(self, message):
- self.appendPlainText(message)
- self.newPrompt()
-
- def clear(self):
- self.setPlainText('')
- self.newPrompt()
-
- def newPrompt(self):
- if self.construct:
- prompt = '.' * len(self.prompt)
- else:
- prompt = self.prompt
-
- self.completions_pos = self.textCursor().position()
- self.completions_visible = False
-
- self.appendPlainText(prompt)
- self.moveCursor(QtGui.QTextCursor.End)
-
- def getCommand(self):
- doc = self.document()
- curr_line = unicode(doc.findBlockByLineNumber(doc.lineCount() - 1).text())
- curr_line = curr_line.rstrip()
- curr_line = curr_line[len(self.prompt):]
- return curr_line
-
- def setCommand(self, command):
- if self.getCommand() == command:
- return
-
- doc = self.document()
- curr_line = unicode(doc.findBlockByLineNumber(doc.lineCount() - 1).text())
- self.moveCursor(QtGui.QTextCursor.End)
- for i in range(len(curr_line) - len(self.prompt)):
- self.moveCursor(QtGui.QTextCursor.Left, QtGui.QTextCursor.KeepAnchor)
-
- self.textCursor().removeSelectedText()
- self.textCursor().insertText(command)
- self.moveCursor(QtGui.QTextCursor.End)
-
-
- def show_completions(self, completions):
- if self.completions_visible:
- self.hide_completions()
-
- c = self.textCursor()
- c.setPosition(self.completions_pos)
-
- completions = map(lambda x: x.split('.')[-1], completions)
- t = '\n' + ' '.join(completions)
- if len(t) > 500:
- t = t[:500] + '...'
- c.insertText(t)
- self.completions_end = c.position()
-
- self.moveCursor(QtGui.QTextCursor.End)
- self.completions_visible = True
-
-
- def hide_completions(self):
- if not self.completions_visible:
- return
- c = self.textCursor()
- c.setPosition(self.completions_pos)
- l = self.completions_end - self.completions_pos
- for x in range(l): c.deleteChar()
-
- self.moveCursor(QtGui.QTextCursor.End)
- self.completions_visible = False
-
-
- def getConstruct(self, command):
- if self.construct:
- prev_command = self.construct[-1]
- self.construct.append(command)
- if not prev_command and not command:
- ret_val = '\n'.join(self.construct)
- self.construct = []
- return ret_val
- else:
- return ''
- else:
- if command and command[-1] == (':'):
- self.construct.append(command)
- return ''
- else:
- return command
-
- def getHistory(self):
- return self.history
-
- def setHisory(self, history):
- self.history = history
-
- def addToHistory(self, command):
- if command.find("importprivkey") > -1:
- return
-
- if command and (not self.history or self.history[-1] != command):
- self.history.append(command)
- self.history_index = len(self.history)
-
- def getPrevHistoryEntry(self):
- if self.history:
- self.history_index = max(0, self.history_index - 1)
- return self.history[self.history_index]
- return ''
-
- def getNextHistoryEntry(self):
- if self.history:
- hist_len = len(self.history)
- self.history_index = min(hist_len, self.history_index + 1)
- if self.history_index < hist_len:
- return self.history[self.history_index]
- return ''
-
- def getCursorPosition(self):
- c = self.textCursor()
- return c.position() - c.block().position() - len(self.prompt)
-
- def setCursorPosition(self, position):
- self.moveCursor(QtGui.QTextCursor.StartOfLine)
- for i in range(len(self.prompt) + position):
- self.moveCursor(QtGui.QTextCursor.Right)
-
- def register_command(self, c, func):
- methods = { c: func}
- self.updateNamespace(methods)
-
-
- def runCommand(self):
- command = self.getCommand()
- self.addToHistory(command)
-
- command = self.getConstruct(command)
-
- if command:
- tmp_stdout = sys.stdout
-
- class stdoutProxy():
- def __init__(self, write_func):
- self.write_func = write_func
- self.skip = False
-
- def flush(self):
- pass
-
- def write(self, text):
- if not self.skip:
- stripped_text = text.rstrip('\n')
- self.write_func(stripped_text)
- QtCore.QCoreApplication.processEvents()
- self.skip = not self.skip
-
- if type(self.namespace.get(command)) == type(lambda:None):
- self.appendPlainText("'%s' is a function. Type '%s()' to use it in the Python console."%(command, command))
- self.newPrompt()
- return
-
- sys.stdout = stdoutProxy(self.appendPlainText)
- try:
- try:
- result = eval(command, self.namespace, self.namespace)
- if result != None:
- if self.is_json:
- util.print_json(result)
- else:
- self.appendPlainText(repr(result))
- except SyntaxError:
- exec command in self.namespace
- except SystemExit:
- self.close()
- except:
- traceback_lines = traceback.format_exc().split('\n')
- # Remove traceback mentioning this file, and a linebreak
- for i in (3,2,1,-1):
- traceback_lines.pop(i)
- self.appendPlainText('\n'.join(traceback_lines))
- sys.stdout = tmp_stdout
- self.newPrompt()
- self.set_json(False)
-
-
- def keyPressEvent(self, event):
- if event.key() == QtCore.Qt.Key_Tab:
- self.completions()
- return
-
- self.hide_completions()
-
- if event.key() in (QtCore.Qt.Key_Enter, QtCore.Qt.Key_Return):
- self.runCommand()
- return
- if event.key() == QtCore.Qt.Key_Home:
- self.setCursorPosition(0)
- return
- if event.key() == QtCore.Qt.Key_PageUp:
- return
- elif event.key() in (QtCore.Qt.Key_Left, QtCore.Qt.Key_Backspace):
- if self.getCursorPosition() == 0:
- return
- elif event.key() == QtCore.Qt.Key_Up:
- self.setCommand(self.getPrevHistoryEntry())
- return
- elif event.key() == QtCore.Qt.Key_Down:
- self.setCommand(self.getNextHistoryEntry())
- return
- elif event.key() == QtCore.Qt.Key_L and event.modifiers() == QtCore.Qt.ControlModifier:
- self.clear()
-
- super(Console, self).keyPressEvent(event)
-
-
-
- def completions(self):
- cmd = self.getCommand()
- lastword = re.split(' |\(|\)',cmd)[-1]
- beginning = cmd[0:-len(lastword)]
-
- path = lastword.split('.')
- ns = self.namespace.keys()
-
- if len(path) == 1:
- ns = ns
- prefix = ''
- else:
- obj = self.namespace.get(path[0])
- prefix = path[0] + '.'
- ns = dir(obj)
-
-
- completions = []
- for x in ns:
- if x[0] == '_':continue
- xx = prefix + x
- if xx.startswith(lastword):
- completions.append(xx)
- completions.sort()
-
- if not completions:
- self.hide_completions()
- elif len(completions) == 1:
- self.hide_completions()
- self.setCommand(beginning + completions[0])
- else:
- # find common prefix
- p = os.path.commonprefix(completions)
- if len(p)>len(lastword):
- self.hide_completions()
- self.setCommand(beginning + p)
- else:
- self.show_completions(completions)
-
-
-welcome_message = '''
- ---------------------------------------------------------------
- Welcome to a primitive Python interpreter.
- ---------------------------------------------------------------
-'''
-
-if __name__ == '__main__':
- app = QtGui.QApplication(sys.argv)
- console = Console(startup_message=welcome_message)
- console.updateNamespace({'myVar1' : app, 'myVar2' : 1234})
- console.show();
- sys.exit(app.exec_())
diff --git a/gui/gui_stdio.py b/gui/gui_stdio.py
@@ -1,252 +0,0 @@
-from decimal import Decimal
-_ = lambda x:x
-#from i18n import _
-from electrum import mnemonic_encode, WalletStorage, Wallet
-from electrum.util import format_satoshis, set_verbosity
-from electrum.bitcoin import is_valid
-from electrum.network import filter_protocol
-import sys, getpass, datetime
-
-# minimal fdisk like gui for console usage
-# written by rofl0r, with some bits stolen from the text gui (ncurses)
-
-class ElectrumGui:
-
- def __init__(self, config, network):
- self.network = network
- self.config = config
- storage = WalletStorage(config)
- if not storage.file_exists:
- print "Wallet not found. try 'electrum create'"
- exit()
-
- self.done = 0
- self.last_balance = ""
-
- set_verbosity(False)
-
- self.str_recipient = ""
- self.str_description = ""
- self.str_amount = ""
- self.str_fee = ""
-
- self.wallet = Wallet(storage)
- self.wallet.start_threads(network)
-
- self.wallet.network.register_callback('updated', self.updated)
- self.wallet.network.register_callback('connected', self.connected)
- self.wallet.network.register_callback('disconnected', self.disconnected)
- self.wallet.network.register_callback('disconnecting', self.disconnecting)
- self.wallet.network.register_callback('peers', self.peers)
- self.wallet.network.register_callback('banner', self.print_banner)
- self.commands = [_("[h] - displays this help text"), \
- _("[i] - display transaction history"), \
- _("[o] - enter payment order"), \
- _("[p] - print stored payment order"), \
- _("[s] - send stored payment order"), \
- _("[r] - show own receipt addresses"), \
- _("[c] - display contacts"), \
- _("[b] - print server banner"), \
- _("[q] - quit") ]
- self.num_commands = len(self.commands)
-
- def main_command(self):
- self.print_balance()
- c = raw_input("enter command: ")
- if c == "h" : self.print_commands()
- elif c == "i" : self.print_history()
- elif c == "o" : self.enter_order()
- elif c == "p" : self.print_order()
- elif c == "s" : self.send_order()
- elif c == "r" : self.print_addresses()
- elif c == "c" : self.print_contacts()
- elif c == "b" : self.print_banner()
- elif c == "n" : self.network_dialog()
- elif c == "e" : self.settings_dialog()
- elif c == "q" : self.done = 1
- else: self.print_commands()
-
- def peers(self):
- print("got peers list:")
- l = filter_protocol(self.wallet.network.get_servers(), 's')
- for s in l:
- print (s)
-
- def connected(self):
- print ("connected")
-
- def disconnected(self):
- print ("disconnected")
-
- def disconnecting(self):
- print ("disconnecting")
-
- def updated(self):
- s = self.get_balance()
- if s != self.last_balance:
- print(s)
- self.last_balance = s
- return True
-
- def print_commands(self):
- self.print_list(self.commands, "Available commands")
-
- def print_history(self):
- width = [20, 40, 14, 14]
- delta = (80 - sum(width) - 4)/3
- format_str = "%"+"%d"%width[0]+"s"+"%"+"%d"%(width[1]+delta)+"s"+"%" \
- + "%d"%(width[2]+delta)+"s"+"%"+"%d"%(width[3]+delta)+"s"
- b = 0
- messages = []
-
- for item in self.wallet.get_tx_history():
- tx_hash, confirmations, is_mine, value, fee, balance, timestamp = item
- if confirmations:
- try:
- time_str = datetime.datetime.fromtimestamp( timestamp).isoformat(' ')[:-3]
- except:
- time_str = "unknown"
- else:
- time_str = 'pending'
-
- label, is_default_label = self.wallet.get_label(tx_hash)
- messages.append( format_str%( time_str, label, format_satoshis(value, whitespaces=True), format_satoshis(balance, whitespaces=True) ) )
-
- self.print_list(messages[::-1], format_str%( _("Date"), _("Description"), _("Amount"), _("Balance")))
-
-
- def print_balance(self):
- print(self.get_balance())
-
- def get_balance(self):
- if self.wallet.network.interface and self.wallet.network.interface.is_connected:
- if not self.wallet.up_to_date:
- msg = _( "Synchronizing..." )
- else:
- c, u = self.wallet.get_balance()
- msg = _("Balance")+": %f "%(Decimal( c ) / 100000000)
- if u: msg += " [%f unconfirmed]"%(Decimal( u ) / 100000000)
- else:
- msg = _( "Not connected" )
-
- return(msg)
-
-
- def print_contacts(self):
- messages = map(lambda addr: "%30s %30s "%(addr, self.wallet.labels.get(addr,"")), self.wallet.addressbook)
- self.print_list(messages, "%19s %25s "%("Address", "Label"))
-
- def print_addresses(self):
- messages = map(lambda addr: "%30s %30s "%(addr, self.wallet.labels.get(addr,"")), self.wallet.addresses())
- self.print_list(messages, "%19s %25s "%("Address", "Label"))
-
- def print_order(self):
- print("send order to " + self.str_recipient + ", amount: " + self.str_amount \
- + "\nfee: " + self.str_fee + ", desc: " + self.str_description)
-
- def enter_order(self):
- self.str_recipient = raw_input("Pay to: ")
- self.str_description = raw_input("Description : ")
- self.str_amount = raw_input("Amount: ")
- self.str_fee = raw_input("Fee: ")
-
- def send_order(self):
- self.do_send()
-
- def print_banner(self):
- for i, x in enumerate( self.wallet.network.banner.split('\n') ):
- print( x )
-
- def print_list(self, list, firstline):
- self.maxpos = len(list)
- if not self.maxpos: return
- print(firstline)
- for i in range(self.maxpos):
- msg = list[i] if i < len(list) else ""
- print(msg)
-
-
- def main(self,url):
- while self.done == 0: self.main_command()
-
- def do_send(self):
- if not is_valid(self.str_recipient):
- print(_('Invalid Bitcoin address'))
- return
- try:
- amount = int( Decimal( self.str_amount) * 100000000 )
- except:
- print(_('Invalid Amount'))
- return
- try:
- fee = int( Decimal( self.str_fee) * 100000000 )
- except:
- print(_('Invalid Fee'))
- return
-
- if self.wallet.use_encryption:
- password = self.password_dialog()
- if not password:
- return
- else:
- password = None
-
- c = ""
- while c != "y":
- c = raw_input("ok to send (y/n)?")
- if c == "n": return
-
- try:
- tx = self.wallet.mktx( [(self.str_recipient, amount)], password, fee)
- except BaseException, e:
- print(str(e))
- return
-
- if self.str_description:
- self.wallet.labels[tx.hash()] = self.str_description
-
- h = self.wallet.send_tx(tx)
- print(_("Please wait..."))
- self.wallet.tx_event.wait()
- status, msg = self.wallet.receive_tx( h )
-
- if status:
- print(_('Payment sent.'))
- #self.do_clear()
- #self.update_contacts_tab()
- else:
- print(_('Error'))
-
- def network_dialog(self):
- print("use 'electrum setconfig server/proxy' to change your network settings")
- return True
-
-
- def settings_dialog(self):
- print("use 'electrum setconfig' to change your settings")
- return True
-
- def password_dialog(self):
- return getpass.getpass()
-
-
-# XXX unused
-
- def run_receive_tab(self, c):
- #if c == 10:
- # out = self.run_popup('Address', ["Edit label", "Freeze", "Prioritize"])
- return
-
- def run_contacts_tab(self, c):
- pass
-# if c == 10 and self.wallet.addressbook:
-# out = self.run_popup('Adress', ["Copy", "Pay to", "Edit label", "Delete"]).get('button')
-# address = self.wallet.addressbook[self.pos%len(self.wallet.addressbook)]
-# if out == "Pay to":
-# self.tab = 1
-# self.str_recipient = address
-# self.pos = 2
-# elif out == "Edit label":
-# s = self.get_string(6 + self.pos, 18)
-# if s:
-# self.wallet.labels[address] = s
diff --git a/gui/gui_text.py b/gui/gui_text.py
@@ -1,444 +0,0 @@
-import curses, datetime
-from decimal import Decimal
-_ = lambda x:x
-#from i18n import _
-from electrum.util import format_satoshis, set_verbosity
-from electrum.bitcoin import is_valid
-
-from electrum import Wallet, WalletStorage
-
-import tty, sys
-
-
-class ElectrumGui:
-
- def __init__(self, config, network):
-
- self.config = config
- self.network = network
- storage = WalletStorage(config)
- if not storage.file_exists:
- print "Wallet not found. try 'electrum create'"
- exit()
-
- self.wallet = Wallet(storage)
- self.wallet.start_threads(network)
-
- self.stdscr = curses.initscr()
- curses.noecho()
- curses.cbreak()
- curses.start_color()
- curses.use_default_colors()
- curses.init_pair(1, curses.COLOR_WHITE, curses.COLOR_BLUE)
- curses.init_pair(2, curses.COLOR_WHITE, curses.COLOR_CYAN)
- self.stdscr.keypad(1)
- self.stdscr.border(0)
- self.maxy, self.maxx = self.stdscr.getmaxyx()
- self.set_cursor(0)
- self.w = curses.newwin(10, 50, 5, 5)
-
- set_verbosity(False)
- self.tab = 0
- self.pos = 0
- self.popup_pos = 0
-
- self.str_recipient = ""
- self.str_description = ""
- self.str_amount = ""
- self.str_fee = ""
-
- self.network.register_callback('updated', self.refresh)
- self.network.register_callback('connected', self.refresh)
- self.network.register_callback('disconnected', self.refresh)
- self.network.register_callback('disconnecting', self.refresh)
- self.tab_names = [_("History"), _("Send"), _("Receive"), _("Contacts"), _("Wall")]
- self.num_tabs = len(self.tab_names)
-
-
- def set_cursor(self, x):
- try:
- curses.curs_set(x)
- except:
- pass
-
- def restore_or_create(self):
- pass
-
- def verify_seed(self):
- pass
-
- def get_string(self, y, x):
- self.set_cursor(1)
- curses.echo()
- self.stdscr.addstr( y, x, " "*20, curses.A_REVERSE)
- s = self.stdscr.getstr(y,x)
- curses.noecho()
- self.set_cursor(0)
- return s
-
-
- def print_history(self):
- width = [20, 40, 14, 14]
- delta = (self.maxx - sum(width) - 4)/3
- format_str = "%"+"%d"%width[0]+"s"+"%"+"%d"%(width[1]+delta)+"s"+"%"+"%d"%(width[2]+delta)+"s"+"%"+"%d"%(width[3]+delta)+"s"
-
- b = 0
- messages = []
-
- for item in self.wallet.get_tx_history():
- tx_hash, conf, is_mine, value, fee, balance, timestamp = item
- if conf:
- try:
- time_str = datetime.datetime.fromtimestamp( timestamp).isoformat(' ')[:-3]
- except:
- time_str = "------"
- else:
- time_str = 'pending'
-
- label, is_default_label = self.wallet.get_label(tx_hash)
- messages.append( format_str%( time_str, label, format_satoshis(value, whitespaces=True), format_satoshis(balance, whitespaces=True) ) )
-
- self.print_list(messages[::-1], format_str%( _("Date"), _("Description"), _("Amount"), _("Balance")))
-
-
- def print_balance(self):
- if self.network.interface and self.network.interface.is_connected:
- if not self.wallet.up_to_date:
- msg = _( "Synchronizing..." )
- else:
- c, u = self.wallet.get_balance()
- msg = _("Balance")+": %f "%(Decimal( c ) / 100000000)
- if u: msg += " [%f unconfirmed]"%(Decimal( u ) / 100000000)
- else:
- msg = _( "Not connected" )
-
- self.stdscr.addstr( self.maxy -1, 3, msg)
-
- for i in range(self.num_tabs):
- self.stdscr.addstr( 0, 2 + 2*i + len(''.join(self.tab_names[0:i])), ' '+self.tab_names[i]+' ', curses.A_BOLD if self.tab == i else 0)
-
- self.stdscr.addstr( self.maxy -1, self.maxx-30, ' '.join([_("Settings"), _("Network"), _("Quit")]))
-
-
- def print_contacts(self):
- messages = map(lambda addr: "%30s %30s "%(addr, self.wallet.labels.get(addr,"")), self.wallet.addressbook)
- self.print_list(messages, "%19s %25s "%("Address", "Label"))
-
- def print_receive(self):
- messages = map(lambda addr: "%30s %30s "%(addr, self.wallet.labels.get(addr,"")), self.wallet.addresses())
- self.print_list(messages, "%19s %25s "%("Address", "Label"))
-
- def print_edit_line(self, y, label, text, index, size):
- text += " "*(size - len(text) )
- self.stdscr.addstr( y, 2, label)
- self.stdscr.addstr( y, 15, text, curses.A_REVERSE if self.pos%6==index else curses.color_pair(1))
-
- def print_send_tab(self):
- self.stdscr.clear()
- self.print_edit_line(3, _("Pay to"), self.str_recipient, 0, 40)
- self.print_edit_line(5, _("Description"), self.str_description, 1, 40)
- self.print_edit_line(7, _("Amount"), self.str_amount, 2, 15)
- self.print_edit_line(9, _("Fee"), self.str_fee, 3, 15)
- self.stdscr.addstr( 12, 15, _("[Send]"), curses.A_REVERSE if self.pos%6==4 else curses.color_pair(2))
- self.stdscr.addstr( 12, 25, _("[Clear]"), curses.A_REVERSE if self.pos%6==5 else curses.color_pair(2))
-
- def print_banner(self):
- for i, x in enumerate( self.network.banner.split('\n') ):
- self.stdscr.addstr( 1+i, 1, x )
-
- def print_list(self, list, firstline):
- self.maxpos = len(list)
- if not self.maxpos: return
- firstline += " "*(self.maxx -2 - len(firstline))
- self.stdscr.addstr( 1, 1, firstline )
- for i in range(self.maxy-4):
- msg = list[i] if i < len(list) else ""
- msg += " "*(self.maxx - 2 - len(msg))
- self.stdscr.addstr( i+2, 1, msg[0:self.maxx - 2], curses.A_REVERSE if i == (self.pos % self.maxpos) else 0)
-
- def refresh(self):
- if self.tab == -1: return
- self.stdscr.border(0)
- self.print_balance()
- self.stdscr.refresh()
-
- def main_command(self):
- c = self.stdscr.getch()
- print c
- if c == curses.KEY_RIGHT: self.tab = (self.tab + 1)%self.num_tabs
- elif c == curses.KEY_LEFT: self.tab = (self.tab - 1)%self.num_tabs
- elif c == curses.KEY_DOWN: self.pos +=1
- elif c == curses.KEY_UP: self.pos -= 1
- elif c == 9: self.pos +=1 # tab
- elif curses.unctrl(c) in ['^W', '^C', '^X', '^Q']: self.tab = -1
- elif curses.unctrl(c) in ['^N']: self.network_dialog()
- elif curses.unctrl(c) == '^S': self.settings_dialog()
- else: return c
- if self.pos<0: self.pos=0
- if self.pos>=self.maxpos: self.pos=self.maxpos - 1
-
- def run_tab(self, i, print_func, exec_func):
- while self.tab == i:
- self.stdscr.clear()
- print_func()
- self.refresh()
- c = self.main_command()
- if c: exec_func(c)
-
-
- def run_history_tab(self, c):
- if c == 10:
- out = self.run_popup('',["blah","foo"])
-
-
- def edit_str(self, target, c, is_num=False):
- # detect backspace
- if c in [8, 127, 263] and target:
- target = target[:-1]
- elif not is_num or curses.unctrl(c) in '0123456789.':
- target += curses.unctrl(c)
- return target
-
-
- def run_send_tab(self, c):
- if self.pos%6 == 0:
- self.str_recipient = self.edit_str(self.str_recipient, c)
- if self.pos%6 == 1:
- self.str_description = self.edit_str(self.str_description, c)
- if self.pos%6 == 2:
- self.str_amount = self.edit_str(self.str_amount, c, True)
- elif self.pos%6 == 3:
- self.str_fee = self.edit_str(self.str_fee, c, True)
- elif self.pos%6==4:
- if c == 10: self.do_send()
- elif self.pos%6==5:
- if c == 10: self.do_clear()
-
-
- def run_receive_tab(self, c):
- if c == 10:
- out = self.run_popup('Address', ["Edit label", "Freeze", "Prioritize"])
-
- def run_contacts_tab(self, c):
- if c == 10 and self.wallet.addressbook:
- out = self.run_popup('Adress', ["Copy", "Pay to", "Edit label", "Delete"]).get('button')
- address = self.wallet.addressbook[self.pos%len(self.wallet.addressbook)]
- if out == "Pay to":
- self.tab = 1
- self.str_recipient = address
- self.pos = 2
- elif out == "Edit label":
- s = self.get_string(6 + self.pos, 18)
- if s:
- self.wallet.labels[address] = s
-
- def run_banner_tab(self, c):
- self.show_message(repr(c))
- pass
-
- def main(self,url):
-
- tty.setraw(sys.stdin)
- while self.tab != -1:
- self.run_tab(0, self.print_history, self.run_history_tab)
- self.run_tab(1, self.print_send_tab, self.run_send_tab)
- self.run_tab(2, self.print_receive, self.run_receive_tab)
- self.run_tab(3, self.print_contacts, self.run_contacts_tab)
- self.run_tab(4, self.print_banner, self.run_banner_tab)
-
- tty.setcbreak(sys.stdin)
- curses.nocbreak()
- self.stdscr.keypad(0)
- curses.echo()
- curses.endwin()
-
-
- def do_clear(self):
- self.str_amount = ''
- self.str_recipient = ''
- self.str_fee = ''
- self.str_description = ''
-
- def do_send(self):
- if not is_valid(self.str_recipient):
- self.show_message(_('Invalid Bitcoin address'))
- return
- try:
- amount = int( Decimal( self.str_amount) * 100000000 )
- except:
- self.show_message(_('Invalid Amount'))
- return
- try:
- fee = int( Decimal( self.str_fee) * 100000000 )
- except:
- self.show_message(_('Invalid Fee'))
- return
-
- if self.wallet.use_encryption:
- password = self.password_dialog()
- if not password:
- return
- else:
- password = None
-
- try:
- tx = self.wallet.mktx( [(self.str_recipient, amount)], password, fee)
- except BaseException, e:
- self.show_message(str(e))
- return
-
- if self.str_description:
- self.wallet.labels[tx.hash()] = self.str_description
-
- h = self.wallet.send_tx(tx)
- self.show_message(_("Please wait..."), getchar=False)
- self.wallet.tx_event.wait()
- status, msg = self.wallet.receive_tx( h )
-
- if status:
- self.show_message(_('Payment sent.'))
- self.do_clear()
- #self.update_contacts_tab()
- else:
- self.show_message(_('Error'))
-
-
- def show_message(self, message, getchar = True):
- w = self.w
- w.clear()
- w.border(0)
- w.addstr(2,2,message)
- w.refresh()
- if getchar: c = self.stdscr.getch()
-
-
- def run_popup(self, title, items):
- return self.run_dialog(title, map(lambda x: {'type':'button','label':x}, items), interval=1, y_pos = self.pos+3)
-
-
- def network_dialog(self):
- out = self.run_dialog('Network', [
- {'label':'server', 'type':'str', 'value':self.network.interface.server},
- {'label':'proxy', 'type':'str', 'value':self.config.get('proxy', '')},
- ], buttons = 1)
- if out:
- if out.get('server'):
- server = out.get('server')
- if out.get('proxy'):
- proxy = self.parse_proxy_options(out.get('proxy'))
- else:
- proxy = None
-
- self.wallet.config.set_key("proxy", proxy, True)
- self.wallet.config.set_key("server", server, True)
- self.network.interface.set_server(server, proxy)
-
-
-
- def settings_dialog(self):
- out = self.run_dialog('Settings', [
- {'label':'Default GUI', 'type':'list', 'choices':['classic','lite','gtk','text'], 'value':self.config.get('gui')},
- {'label':'Default fee', 'type':'satoshis', 'value': format_satoshis(self.wallet.fee).strip() }
- ], buttons = 1)
- if out:
- if out.get('Default GUI'):
- self.config.set_key('gui', out['Default GUI'], True)
- if out.get('Default fee'):
- fee = int ( Decimal( out['Default fee']) *10000000 )
- self.config.set_key('fee_per_kb', fee, True)
-
-
- def password_dialog(self):
- out = self.run_dialog('Password', [
- {'label':'Password', 'type':'password', 'value':''}
- ], buttons = 1)
- return out.get('Password')
-
-
- def run_dialog(self, title, items, interval=2, buttons=None, y_pos=3):
- self.popup_pos = 0
-
- self.w = curses.newwin( 5 + len(items)*interval + (2 if buttons else 0), 50, y_pos, 5)
- w = self.w
- out = {}
- while True:
- w.clear()
- w.border(0)
- w.addstr( 0, 2, title)
-
- num = len(items)
-
- numpos = num
- if buttons: numpos += 2
-
- for i in range(num):
- item = items[i]
- label = item.get('label')
- if item.get('type') == 'list':
- value = item.get('value','')
- elif item.get('type') == 'satoshis':
- value = item.get('value','')
- elif item.get('type') == 'str':
- value = item.get('value','')
- elif item.get('type') == 'password':
- value = '*'*len(item.get('value',''))
- else:
- value = ''
-
- if len(value)<20: value += ' '*(20-len(value))
-
- if item.has_key('value'):
- w.addstr( 2+interval*i, 2, label)
- w.addstr( 2+interval*i, 15, value, curses.A_REVERSE if self.popup_pos%numpos==i else curses.color_pair(1) )
- else:
- w.addstr( 2+interval*i, 2, label, curses.A_REVERSE if self.popup_pos%numpos==i else 0)
-
- if buttons:
- w.addstr( 5+interval*i, 10, "[ ok ]", curses.A_REVERSE if self.popup_pos%numpos==(numpos-2) else curses.color_pair(2))
- w.addstr( 5+interval*i, 25, "[cancel]", curses.A_REVERSE if self.popup_pos%numpos==(numpos-1) else curses.color_pair(2))
-
- w.refresh()
-
- c = self.stdscr.getch()
- if c in [ord('q'), 27]: break
- elif c in [curses.KEY_LEFT, curses.KEY_UP]: self.popup_pos -= 1
- elif c in [curses.KEY_RIGHT, curses.KEY_DOWN]: self.popup_pos +=1
- else:
- i = self.popup_pos%numpos
- if buttons and c==10:
- if i == numpos-2:
- return out
- elif i == numpos -1:
- return {}
-
- item = items[i]
- _type = item.get('type')
-
- if _type == 'str':
- item['value'] = self.edit_str(item['value'], c)
- out[item.get('label')] = item.get('value')
-
- elif _type == 'password':
- item['value'] = self.edit_str(item['value'], c)
- out[item.get('label')] = item ['value']
-
- elif _type == 'satoshis':
- item['value'] = self.edit_str(item['value'], c, True)
- out[item.get('label')] = item.get('value')
-
- elif _type == 'list':
- choices = item.get('choices')
- try:
- j = choices.index(item.get('value'))
- except:
- j = 0
- new_choice = choices[(j + 1)% len(choices)]
- item['value'] = new_choice
- out[item.get('label')] = item.get('value')
-
- elif _type == 'button':
- out['button'] = item.get('label')
- break
-
- return out
-
diff --git a/gui/qt/__init__.py b/gui/qt/__init__.py
@@ -0,0 +1,172 @@
+#!/usr/bin/env python
+#
+# Electrum - lightweight Bitcoin client
+# Copyright (C) 2012 thomasv@gitorious
+#
+# This program is free software: you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation, either version 3 of the License, or
+# (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program. If not, see <http://www.gnu.org/licenses/>.
+
+import sys, time, datetime, re, threading
+from electrum.i18n import _, set_language
+from electrum.util import print_error, print_msg, parse_url
+from electrum.plugins import run_hook
+import os.path, json, ast, traceback
+import shutil
+
+
+try:
+ import PyQt4
+except:
+ sys.exit("Error: Could not import PyQt4 on Linux systems, you may try 'sudo apt-get install python-qt4'")
+
+from PyQt4.QtGui import *
+from PyQt4.QtCore import *
+import PyQt4.QtCore as QtCore
+
+from electrum import WalletStorage, Wallet
+from electrum.i18n import _
+from electrum.bitcoin import MIN_RELAY_TX_FEE
+
+try:
+ import icons_rc
+except:
+ sys.exit("Error: Could not import icons_rc.py, please generate it with: 'pyrcc4 icons.qrc -o gui/gui_classic/icons_rc.py'")
+
+from util import *
+from main_window import ElectrumWindow
+from electrum.plugins import init_plugins
+
+class Timer(QtCore.QThread):
+ def run(self):
+ while True:
+ self.emit(QtCore.SIGNAL('timersignal'))
+ time.sleep(0.5)
+
+class OpenFileEventFilter(QObject):
+ def __init__(self, windows):
+ self.windows = windows
+ super(OpenFileEventFilter, self).__init__()
+
+ def eventFilter(self, obj, event):
+ if event.type() == QtCore.QEvent.FileOpen:
+ if len(self.windows) >= 1:
+ self.windows[0].set_url(event.url().toString())
+ return True
+ return False
+
+
+class ElectrumGui:
+
+ def __init__(self, config, network, app=None):
+ self.network = network
+ self.config = config
+ self.windows = []
+ self.efilter = OpenFileEventFilter(self.windows)
+ if app is None:
+ self.app = QApplication(sys.argv)
+ self.app.installEventFilter(self.efilter)
+
+ init_plugins(self)
+
+
+
+ def expand(self):
+ """Hide the lite mode window and show pro-mode."""
+ self.config.set_key('lite_mode', False, True)
+ self.mini.hide()
+ self.expert.show()
+
+ def minimize(self):
+ self.config.set_key('lite_mode', True, True)
+ self.expert.hide()
+ self.mini.show()
+
+ def init_lite(self, wallet, expert, url):
+ import lite_window
+ if not self.check_qt_version():
+ return
+
+ actuator = lite_window.MiniActuator(self.config, wallet)
+ # Should probably not modify the current path but instead
+ # change the behaviour of rsrc(...)
+ old_path = QDir.currentPath()
+ actuator.load_theme()
+
+ mini = lite_window.MiniWindow(actuator, self.expand, self.config)
+ driver = lite_window.MiniDriver(wallet, mini)
+
+ # Reset path back to original value now that loading the GUI
+ # is completed.
+ QDir.setCurrent(old_path)
+ if url:
+ payto, amount, label, message, signature, identity, url = parse_url(url)
+ mini.set_payment_fields(payto, amount)
+
+ return mini
+
+ def check_qt_version(self):
+ qtVersion = qVersion()
+ return int(qtVersion[0]) >= 4 and int(qtVersion[2]) >= 7
+
+
+ def main(self, url):
+
+ storage = WalletStorage(self.config)
+ if not storage.file_exists:
+ import installwizard
+ wizard = installwizard.InstallWizard(self.config, self.network, storage)
+ wallet = wizard.run()
+ if not wallet:
+ exit()
+ else:
+ wallet = Wallet(storage)
+
+ wallet.start_threads(self.network)
+
+
+ self.main_window = w = ElectrumWindow(self.config, self.network, self.minimize)
+
+ # plugins that need to change the GUI do it here
+ run_hook('init')
+
+ w.load_wallet(wallet)
+
+ s = Timer()
+ s.start()
+
+ self.windows.append(w)
+ if url: w.set_url(url)
+ w.app = self.app
+ w.connect_slots(s)
+ w.update_wallet()
+
+ self.expert = w
+ self.mini = self.init_lite(wallet, w, url)
+
+ if self.config.get('lite_mode'):
+ if not self.mini:
+ QMessageBox.warning(None,"Could not start Lite GUI.", "Electrum was unable to load the 'Lite GUI' because it needs Qt version >= 4.7.\nChanging your config to use the 'Classic' GUI")
+ self.config.set_key('lite_mode', False, True)
+ sys.exit(0)
+ else:
+ self.minimize()
+ else:
+ w.show()
+ if self.mini:
+ self.mini.hide()
+
+ self.app.exec_()
+
+ wallet.stop_threads()
+
+
diff --git a/gui/gui_classic/amountedit.py b/gui/qt/amountedit.py
diff --git a/gui/gui_classic/history_widget.py b/gui/qt/history_widget.py
diff --git a/gui/gui_classic/installwizard.py b/gui/qt/installwizard.py
diff --git a/gui/qt/lite_window.py b/gui/qt/lite_window.py
@@ -0,0 +1,915 @@
+import sys
+
+# Let's do some dep checking and handle missing ones gracefully
+try:
+ from PyQt4.QtCore import *
+ from PyQt4.QtGui import *
+ from PyQt4.Qt import Qt
+ import PyQt4.QtCore as QtCore
+
+except ImportError:
+ print "You need to have PyQT installed to run Electrum in graphical mode."
+ print "If you have pip installed try 'sudo pip install pyqt' if you are on Debian/Ubuntu try 'sudo apt-get install python-qt4'."
+ sys.exit(0)
+
+from decimal import Decimal as D
+from electrum.util import get_resource_path as rsrc
+from electrum.bitcoin import is_valid
+from electrum.i18n import _
+import decimal
+import json
+import os.path
+import random
+import re
+import time
+from electrum.wallet import Wallet, WalletStorage
+import webbrowser
+import history_widget
+import receiving_widget
+from electrum import util
+import csv
+import datetime
+
+from electrum.version import ELECTRUM_VERSION as electrum_version
+from electrum.util import format_satoshis, age
+
+from main_window import ElectrumWindow
+import shutil
+
+from util import *
+
+bitcoin = lambda v: v * 100000000
+
+def IconButton(filename, parent=None):
+ pixmap = QPixmap(filename)
+ icon = QIcon(pixmap)
+ return QPushButton(icon, "", parent)
+
+class Timer(QThread):
+ def run(self):
+ while True:
+ self.emit(SIGNAL('timersignal'))
+ time.sleep(0.5)
+
+def resize_line_edit_width(line_edit, text_input):
+ metrics = QFontMetrics(qApp.font())
+ # Create an extra character to add some space on the end
+ text_input += "A"
+ line_edit.setMinimumWidth(metrics.width(text_input))
+
+def load_theme_name(theme_path):
+ try:
+ with open(os.path.join(theme_path, "name.cfg")) as name_cfg_file:
+ return name_cfg_file.read().rstrip("\n").strip()
+ except IOError:
+ return None
+
+
+def theme_dirs_from_prefix(prefix):
+ if not os.path.exists(prefix):
+ return []
+ theme_paths = {}
+ for potential_theme in os.listdir(prefix):
+ theme_full_path = os.path.join(prefix, potential_theme)
+ theme_css = os.path.join(theme_full_path, "style.css")
+ if not os.path.exists(theme_css):
+ continue
+ theme_name = load_theme_name(theme_full_path)
+ if theme_name is None:
+ continue
+ theme_paths[theme_name] = prefix, potential_theme
+ return theme_paths
+
+def load_theme_paths():
+ theme_paths = {}
+ prefixes = (util.local_data_dir(), util.appdata_dir())
+ for prefix in prefixes:
+ theme_paths.update(theme_dirs_from_prefix(prefix))
+ return theme_paths
+
+
+def csv_transaction(wallet):
+ try:
+ select_export = _('Select file to export your wallet transactions to')
+ fileName = QFileDialog.getSaveFileName(QWidget(), select_export, os.path.expanduser('~/electrum-history.csv'), "*.csv")
+ if fileName:
+ with open(fileName, "w+") as csvfile:
+ transaction = csv.writer(csvfile)
+ transaction.writerow(["transaction_hash","label", "confirmations", "value", "fee", "balance", "timestamp"])
+ for item in wallet.get_tx_history():
+ tx_hash, confirmations, is_mine, value, fee, balance, timestamp = item
+ if confirmations:
+ if timestamp is not None:
+ try:
+ time_string = datetime.datetime.fromtimestamp(timestamp).isoformat(' ')[:-3]
+ except [RuntimeError, TypeError, NameError] as reason:
+ time_string = "unknown"
+ pass
+ else:
+ time_string = "unknown"
+ else:
+ time_string = "pending"
+
+ if value is not None:
+ value_string = format_satoshis(value, True, wallet.num_zeros)
+ else:
+ value_string = '--'
+
+ if fee is not None:
+ fee_string = format_satoshis(fee, True, wallet.num_zeros)
+ else:
+ fee_string = '0'
+
+ if tx_hash:
+ label, is_default_label = wallet.get_label(tx_hash)
+ else:
+ label = ""
+
+ balance_string = format_satoshis(balance, False, wallet.num_zeros)
+ transaction.writerow([tx_hash, label, confirmations, value_string, fee_string, balance_string, time_string])
+ QMessageBox.information(None,"CSV Export created", "Your CSV export has been successfully created.")
+ except (IOError, os.error), reason:
+ export_error_label = _("Electrum was unable to produce a transaction export.")
+ QMessageBox.critical(None,_("Unable to create csv"), export_error_label + "\n" + str(reason))
+
+
+
+class TransactionWindow(QDialog):
+
+ def set_label(self):
+ label = unicode(self.label_edit.text())
+ self.parent.wallet.labels[self.tx_id] = label
+
+ super(TransactionWindow, self).accept()
+
+ def __init__(self, transaction_id, parent):
+ super(TransactionWindow, self).__init__()
+
+ self.tx_id = str(transaction_id)
+ self.parent = parent
+
+ self.setModal(True)
+ self.resize(200,100)
+ self.setWindowTitle(_("Transaction successfully sent"))
+
+ self.layout = QGridLayout(self)
+ history_label = "%s\n%s" % (_("Your transaction has been sent."), _("Please enter a label for this transaction for future reference."))
+ self.layout.addWidget(QLabel(history_label))
+
+ self.label_edit = QLineEdit()
+ self.label_edit.setPlaceholderText(_("Transaction label"))
+ self.label_edit.setObjectName("label_input")
+ self.label_edit.setAttribute(Qt.WA_MacShowFocusRect, 0)
+ self.label_edit.setFocusPolicy(Qt.ClickFocus)
+ self.layout.addWidget(self.label_edit)
+
+ self.save_button = QPushButton(_("Save"))
+ self.layout.addWidget(self.save_button)
+ self.save_button.clicked.connect(self.set_label)
+
+ self.exec_()
+
+class MiniWindow(QDialog):
+
+ def __init__(self, actuator, expand_callback, config):
+ super(MiniWindow, self).__init__()
+ tx = "e08115d0f7819aee65b9d24f81ef9d46eb62bb67ddef5318156cbc3ceb7b703e"
+
+ self.actuator = actuator
+ self.config = config
+ self.btc_balance = None
+ self.quote_currencies = ["BRL", "CNY", "EUR", "GBP", "RUB", "USD"]
+ self.actuator.set_configured_currency(self.set_quote_currency)
+ #self.exchanger = exchange_rate.Exchanger(self)
+ # Needed because price discovery is done in a different thread
+ # which needs to be sent back to this main one to update the GUI
+ self.connect(self, SIGNAL("refresh_balance()"), self.refresh_balance)
+
+ self.balance_label = BalanceLabel(self.change_quote_currency, self)
+ self.balance_label.setObjectName("balance_label")
+
+
+ # Bitcoin address code
+ self.address_input = QLineEdit()
+ self.address_input.setPlaceholderText(_("Enter a Bitcoin address or contact"))
+ self.address_input.setObjectName("address_input")
+
+ self.address_input.setFocusPolicy(Qt.ClickFocus)
+
+ self.address_input.textChanged.connect(self.address_field_changed)
+ resize_line_edit_width(self.address_input,
+ "1BtaFUr3qVvAmwrsuDuu5zk6e4s2rxd2Gy")
+
+ self.address_completions = QStringListModel()
+ address_completer = QCompleter(self.address_input)
+ address_completer.setCaseSensitivity(False)
+ address_completer.setModel(self.address_completions)
+ self.address_input.setCompleter(address_completer)
+
+ address_layout = QHBoxLayout()
+ address_layout.addWidget(self.address_input)
+
+ self.amount_input = QLineEdit()
+ self.amount_input.setPlaceholderText(_("... and amount"))
+ self.amount_input.setObjectName("amount_input")
+
+ self.amount_input.setFocusPolicy(Qt.ClickFocus)
+ # This is changed according to the user's displayed balance
+ self.amount_validator = QDoubleValidator(self.amount_input)
+ self.amount_validator.setNotation(QDoubleValidator.StandardNotation)
+ self.amount_validator.setDecimals(8)
+ self.amount_input.setValidator(self.amount_validator)
+
+ # This removes the very ugly OSX highlighting, please leave this in :D
+ self.address_input.setAttribute(Qt.WA_MacShowFocusRect, 0)
+ self.amount_input.setAttribute(Qt.WA_MacShowFocusRect, 0)
+ self.amount_input.textChanged.connect(self.amount_input_changed)
+
+ if self.actuator.wallet.seed:
+ self.send_button = QPushButton(_("&Send"))
+ else:
+ self.send_button = QPushButton(_("&Create"))
+
+ self.send_button.setObjectName("send_button")
+ self.send_button.setDisabled(True);
+ self.send_button.clicked.connect(self.send)
+
+ # Creating the receive button
+ self.switch_button = QPushButton( QIcon(":icons/switchgui.png"),'' )
+ self.switch_button.setMaximumWidth(25)
+ self.switch_button.setFlat(True)
+ self.switch_button.clicked.connect(expand_callback)
+
+ main_layout = QGridLayout(self)
+
+ main_layout.addWidget(self.balance_label, 0, 0, 1, 3)
+ main_layout.addWidget(self.switch_button, 0, 3)
+
+ main_layout.addWidget(self.address_input, 1, 0, 1, 4)
+ main_layout.addWidget(self.amount_input, 2, 0, 1, 2)
+ main_layout.addWidget(self.send_button, 2, 2, 1, 2)
+
+ self.send_button.setMaximumWidth(125)
+
+ self.history_list = history_widget.HistoryWidget()
+ self.history_list.setObjectName("history")
+ self.history_list.hide()
+ self.history_list.setAlternatingRowColors(True)
+
+ main_layout.addWidget(self.history_list, 3, 0, 1, 4)
+
+ self.receiving = receiving_widget.ReceivingWidget(self)
+ self.receiving.setObjectName("receiving")
+
+ # Add to the right side
+ self.receiving_box = QGroupBox(_("Select a receiving address"))
+ extra_layout = QGridLayout()
+
+ # Checkbox to filter used addresses
+ hide_used = QCheckBox(_('Hide used addresses'))
+ hide_used.setChecked(True)
+ hide_used.stateChanged.connect(self.receiving.toggle_used)
+
+ # Events for receiving addresses
+ self.receiving.clicked.connect(self.receiving.copy_address)
+ self.receiving.itemDoubleClicked.connect(self.receiving.edit_label)
+ self.receiving.itemChanged.connect(self.receiving.update_label)
+
+
+ # Label
+ extra_layout.addWidget( QLabel(_('Selecting an address will copy it to the clipboard.') + '\n' + _('Double clicking the label will allow you to edit it.') ),0,0)
+
+ extra_layout.addWidget(self.receiving, 1,0)
+ extra_layout.addWidget(hide_used, 2,0)
+ extra_layout.setColumnMinimumWidth(0,200)
+
+ self.receiving_box.setLayout(extra_layout)
+ main_layout.addWidget(self.receiving_box,0,4,-1,3)
+ self.receiving_box.hide()
+
+ self.main_layout = main_layout
+
+ quit_shortcut = QShortcut(QKeySequence("Ctrl+Q"), self)
+ quit_shortcut.activated.connect(self.close)
+ close_shortcut = QShortcut(QKeySequence("Ctrl+W"), self)
+ close_shortcut.activated.connect(self.close)
+
+ g = self.config.get("winpos-lite",[4, 25, 351, 149])
+ self.setGeometry(g[0], g[1], g[2], g[3])
+
+ show_hist = self.config.get("gui_show_history",False)
+ self.show_history(show_hist)
+ show_hist = self.config.get("gui_show_receiving",False)
+ self.toggle_receiving_layout(show_hist)
+
+ self.setWindowIcon(QIcon(":icons/electrum.png"))
+ self.setWindowTitle("Electrum")
+ self.setWindowFlags(Qt.Window|Qt.MSWindowsFixedSizeDialogHint)
+ self.layout().setSizeConstraint(QLayout.SetFixedSize)
+ self.setObjectName("main_window")
+
+ self.show()
+
+ def context_menu(self):
+ view_menu = QMenu()
+ themes_menu = view_menu.addMenu(_("&Themes"))
+ selected_theme = self.actuator.selected_theme()
+ theme_group = QActionGroup(self)
+ for theme_name in self.actuator.theme_names():
+ theme_action = themes_menu.addAction(theme_name)
+ theme_action.setCheckable(True)
+ if selected_theme == theme_name:
+ theme_action.setChecked(True)
+ class SelectThemeFunctor:
+ def __init__(self, theme_name, toggle_theme):
+ self.theme_name = theme_name
+ self.toggle_theme = toggle_theme
+ def __call__(self, checked):
+ if checked:
+ self.toggle_theme(self.theme_name)
+ delegate = SelectThemeFunctor(theme_name, self.toggle_theme)
+ theme_action.toggled.connect(delegate)
+ theme_group.addAction(theme_action)
+ view_menu.addSeparator()
+
+ show_receiving = view_menu.addAction(_("Show Receiving addresses"))
+ show_receiving.setCheckable(True)
+ show_receiving.toggled.connect(self.toggle_receiving_layout)
+ show_receiving.setChecked(self.config.get("gui_show_receiving",False))
+
+ show_history = view_menu.addAction(_("Show History"))
+ show_history.setCheckable(True)
+ show_history.toggled.connect(self.show_history)
+ show_history.setChecked(self.config.get("gui_show_history",False))
+
+ return view_menu
+
+
+
+ def toggle_theme(self, theme_name):
+ old_path = QDir.currentPath()
+ self.actuator.change_theme(theme_name)
+ # Recompute style globally
+ qApp.style().unpolish(self)
+ qApp.style().polish(self)
+ QDir.setCurrent(old_path)
+
+ def closeEvent(self, event):
+ g = self.geometry()
+ self.config.set_key("winpos-lite", [g.left(),g.top(),g.width(),g.height()],True)
+
+ super(MiniWindow, self).closeEvent(event)
+ qApp.quit()
+
+ def set_payment_fields(self, dest_address, amount):
+ self.address_input.setText(dest_address)
+ self.address_field_changed(dest_address)
+ self.amount_input.setText(amount)
+
+ def activate(self):
+ pass
+
+ def deactivate(self):
+ pass
+
+ def set_quote_currency(self, currency):
+ """Set and display the fiat currency country."""
+ if currency not in self.quote_currencies:
+ return
+ self.quote_currencies.remove(currency)
+ self.quote_currencies.insert(0, currency)
+ self.refresh_balance()
+
+ def change_quote_currency(self, forward=True):
+ if forward:
+ self.quote_currencies = \
+ self.quote_currencies[1:] + self.quote_currencies[0:1]
+ else:
+ self.quote_currencies = \
+ self.quote_currencies[-1:] + self.quote_currencies[0:-1]
+ self.actuator.set_config_currency(self.quote_currencies[0])
+ self.refresh_balance()
+
+ def refresh_balance(self):
+ if self.btc_balance is None:
+ # Price has been discovered before wallet has been loaded
+ # and server connect... so bail.
+ return
+ self.set_balances(self.btc_balance)
+ self.amount_input_changed(self.amount_input.text())
+
+ def set_balances(self, btc_balance):
+ """Set the bitcoin balance and update the amount label accordingly."""
+ self.btc_balance = btc_balance
+ quote_text = self.create_quote_text(btc_balance)
+ if quote_text:
+ quote_text = "(%s)" % quote_text
+ btc_balance = "%.4f" % (btc_balance / bitcoin(1))
+ self.balance_label.set_balance_text(btc_balance, quote_text)
+ self.setWindowTitle("Electrum %s - %s BTC" % (electrum_version, btc_balance))
+
+ def amount_input_changed(self, amount_text):
+ """Update the number of bitcoins displayed."""
+ self.check_button_status()
+
+ try:
+ amount = D(str(amount_text))
+ except decimal.InvalidOperation:
+ self.balance_label.show_balance()
+ else:
+ quote_text = self.create_quote_text(amount * bitcoin(1))
+ if quote_text:
+ self.balance_label.set_amount_text(quote_text)
+ self.balance_label.show_amount()
+ else:
+ self.balance_label.show_balance()
+
+ def create_quote_text(self, btc_balance):
+ """Return a string copy of the amount fiat currency the
+ user has in bitcoins."""
+ quote_currency = self.quote_currencies[0]
+ quote_balance = None #self.exchanger.exchange(btc_balance, quote_currency)
+ if quote_balance is None:
+ quote_text = ""
+ else:
+ quote_text = "%.2f %s" % ((quote_balance / bitcoin(1)),
+ quote_currency)
+ return quote_text
+
+ def send(self):
+ if self.actuator.send(self.address_input.text(),
+ self.amount_input.text(), self):
+ self.address_input.setText("")
+ self.amount_input.setText("")
+
+ def check_button_status(self):
+ """Check that the bitcoin address is valid and that something
+ is entered in the amount before making the send button clickable."""
+ try:
+ value = D(str(self.amount_input.text())) * 10**8
+ except decimal.InvalidOperation:
+ value = None
+ # self.address_input.property(...) returns a qVariant, not a bool.
+ # The == is needed to properly invoke a comparison.
+ if (self.address_input.property("isValid") == True and
+ value is not None and 0 < value <= self.btc_balance):
+ self.send_button.setDisabled(False)
+ else:
+ self.send_button.setDisabled(True)
+
+ def address_field_changed(self, address):
+ # label or alias, with address in brackets
+ match2 = re.match("(.*?)\s*\<([1-9A-HJ-NP-Za-km-z]{26,})\>",
+ address)
+ if match2:
+ address = match2.group(2)
+ self.address_input.setText(address)
+
+ if is_valid(address):
+ self.check_button_status()
+ self.address_input.setProperty("isValid", True)
+ self.recompute_style(self.address_input)
+ else:
+ self.send_button.setDisabled(True)
+ self.address_input.setProperty("isValid", False)
+ self.recompute_style(self.address_input)
+
+ if len(address) == 0:
+ self.address_input.setProperty("isValid", None)
+ self.recompute_style(self.address_input)
+
+ def recompute_style(self, element):
+ self.style().unpolish(element)
+ self.style().polish(element)
+
+ def copy_address(self):
+ receive_popup = ReceivePopup(self.receive_button)
+ self.actuator.copy_address(receive_popup)
+
+ def update_completions(self, completions):
+ self.address_completions.setStringList(completions)
+
+
+ def update_history(self, tx_history):
+
+ self.history_list.empty()
+
+ for item in tx_history[-10:]:
+ tx_hash, conf, is_mine, value, fee, balance, timestamp = item
+ label = self.actuator.wallet.get_label(tx_hash)[0]
+ #amount = D(value) / 10**8
+ v_str = format_satoshis(value, True)
+ self.history_list.append(label, v_str, age(timestamp))
+
+ def acceptbit(self):
+ self.actuator.acceptbit(self.quote_currencies[0])
+
+ def the_website(self):
+ webbrowser.open("http://electrum.org")
+
+
+ def toggle_receiving_layout(self, toggle_state):
+ if toggle_state:
+ self.receiving_box.show()
+ else:
+ self.receiving_box.hide()
+ self.config.set_key("gui_show_receiving", toggle_state)
+
+ def show_history(self, toggle_state):
+ if toggle_state:
+ self.main_layout.setRowMinimumHeight(3,200)
+ self.history_list.show()
+ else:
+ self.main_layout.setRowMinimumHeight(3,0)
+ self.history_list.hide()
+ self.config.set_key("gui_show_history", toggle_state)
+
+class BalanceLabel(QLabel):
+
+ SHOW_CONNECTING = 1
+ SHOW_BALANCE = 2
+ SHOW_AMOUNT = 3
+
+ def __init__(self, change_quote_currency, parent=None):
+ super(QLabel, self).__init__(_("Connecting..."), parent)
+ self.change_quote_currency = change_quote_currency
+ self.state = self.SHOW_CONNECTING
+ self.balance_text = ""
+ self.amount_text = ""
+ self.parent = parent
+
+ def mousePressEvent(self, event):
+ """Change the fiat currency selection if window background is clicked."""
+ if self.state != self.SHOW_CONNECTING:
+ if event.button() == Qt.LeftButton:
+ self.change_quote_currency()
+ else:
+ position = event.globalPos()
+ menu = self.parent.context_menu()
+ menu.exec_(position)
+
+
+ def set_balance_text(self, btc_balance, quote_text):
+ """Set the amount of bitcoins in the gui."""
+ if self.state == self.SHOW_CONNECTING:
+ self.state = self.SHOW_BALANCE
+ self.balance_text = "<span style='font-size: 18pt'>%s</span> <span style='font-size: 10pt'>BTC</span> <span style='font-size: 10pt'>%s</span>" % (btc_balance, quote_text)
+ if self.state == self.SHOW_BALANCE:
+ self.setText(self.balance_text)
+
+ def set_amount_text(self, quote_text):
+ self.amount_text = "<span style='font-size: 10pt'>%s</span>" % quote_text
+ if self.state == self.SHOW_AMOUNT:
+ self.setText(self.amount_text)
+
+ def show_balance(self):
+ if self.state == self.SHOW_AMOUNT:
+ self.state = self.SHOW_BALANCE
+ self.setText(self.balance_text)
+
+ def show_amount(self):
+ if self.state == self.SHOW_BALANCE:
+ self.state = self.SHOW_AMOUNT
+ self.setText(self.amount_text)
+
+def ok_cancel_buttons(dialog):
+ row_layout = QHBoxLayout()
+ row_layout.addStretch(1)
+ ok_button = QPushButton(_("OK"))
+ row_layout.addWidget(ok_button)
+ ok_button.clicked.connect(dialog.accept)
+ cancel_button = QPushButton(_("Cancel"))
+ row_layout.addWidget(cancel_button)
+ cancel_button.clicked.connect(dialog.reject)
+ return row_layout
+
+class PasswordDialog(QDialog):
+
+ def __init__(self, parent):
+ super(QDialog, self).__init__(parent)
+
+ self.setModal(True)
+
+ self.password_input = QLineEdit()
+ self.password_input.setEchoMode(QLineEdit.Password)
+
+ main_layout = QVBoxLayout(self)
+ message = _('Please enter your password')
+ main_layout.addWidget(QLabel(message))
+
+ grid = QGridLayout()
+ grid.setSpacing(8)
+ grid.addWidget(QLabel(_('Password')), 1, 0)
+ grid.addWidget(self.password_input, 1, 1)
+ main_layout.addLayout(grid)
+
+ main_layout.addLayout(ok_cancel_buttons(self))
+ self.setLayout(main_layout)
+
+ def run(self):
+ if not self.exec_():
+ return
+ return unicode(self.password_input.text())
+
+class ReceivePopup(QDialog):
+
+ def leaveEvent(self, event):
+ self.close()
+
+ def setup(self, address):
+ label = QLabel(_("Copied your Bitcoin address to the clipboard!"))
+ address_display = QLineEdit(address)
+ address_display.setReadOnly(True)
+ resize_line_edit_width(address_display, address)
+
+ main_layout = QVBoxLayout(self)
+ main_layout.addWidget(label)
+ main_layout.addWidget(address_display)
+
+ self.setMouseTracking(True)
+ self.setWindowTitle("Electrum - " + _("Receive Bitcoin payment"))
+ self.setWindowFlags(Qt.Window|Qt.FramelessWindowHint|
+ Qt.MSWindowsFixedSizeDialogHint)
+ self.layout().setSizeConstraint(QLayout.SetFixedSize)
+ #self.setFrameStyle(QFrame.WinPanel|QFrame.Raised)
+ #self.setAlignment(Qt.AlignCenter)
+
+ def popup(self):
+ parent = self.parent()
+ top_left_pos = parent.mapToGlobal(parent.rect().bottomLeft())
+ self.move(top_left_pos)
+ center_mouse_pos = self.mapToGlobal(self.rect().center())
+ QCursor.setPos(center_mouse_pos)
+ self.show()
+
+class MiniActuator:
+ """Initialize the definitions relating to themes and
+ sending/receiving bitcoins."""
+
+
+ def __init__(self, config, wallet):
+ """Retrieve the gui theme used in previous session."""
+ self.config = config
+ self.wallet = wallet
+ self.theme_name = self.config.get('litegui_theme','Cleanlook')
+ self.themes = load_theme_paths()
+
+ def load_theme(self):
+ """Load theme retrieved from wallet file."""
+ try:
+ theme_prefix, theme_path = self.themes[self.theme_name]
+ except KeyError:
+ util.print_error("Theme not found!", self.theme_name)
+ return
+ QDir.setCurrent(os.path.join(theme_prefix, theme_path))
+ with open(rsrc("style.css")) as style_file:
+ qApp.setStyleSheet(style_file.read())
+
+ def theme_names(self):
+ """Sort themes."""
+ return sorted(self.themes.keys())
+
+ def selected_theme(self):
+ """Select theme."""
+ return self.theme_name
+
+ def change_theme(self, theme_name):
+ """Change theme."""
+ self.theme_name = theme_name
+ self.config.set_key('litegui_theme',theme_name)
+ self.load_theme()
+
+ def set_configured_currency(self, set_quote_currency):
+ """Set the inital fiat currency conversion country (USD/EUR/GBP) in
+ the GUI to what it was set to in the wallet."""
+ currency = self.config.get('currency')
+ # currency can be none when Electrum is used for the first
+ # time and no setting has been created yet.
+ if currency is not None:
+ set_quote_currency(currency)
+
+ def set_config_currency(self, conversion_currency):
+ """Change the wallet fiat currency country."""
+ self.config.set_key('conversion_currency',conversion_currency,True)
+
+ def copy_address(self, receive_popup):
+ """Copy the wallet addresses into the client."""
+ addrs = [addr for addr in self.wallet.addresses(True)
+ if not self.wallet.is_change(addr)]
+ # Select most recent addresses from gap limit
+ addrs = addrs[-self.wallet.gap_limit:]
+ copied_address = random.choice(addrs)
+ qApp.clipboard().setText(copied_address)
+ receive_popup.setup(copied_address)
+ receive_popup.popup()
+
+ def waiting_dialog(self, f):
+ s = Timer()
+ s.start()
+ w = QDialog()
+ w.resize(200, 70)
+ w.setWindowTitle('Electrum')
+ l = QLabel(_('Sending transaction, please wait.'))
+ vbox = QVBoxLayout()
+ vbox.addWidget(l)
+ w.setLayout(vbox)
+ w.show()
+ def ff():
+ s = f()
+ if s: l.setText(s)
+ else: w.close()
+ w.connect(s, QtCore.SIGNAL('timersignal'), ff)
+ w.exec_()
+ w.destroy()
+
+
+ def send(self, address, amount, parent_window):
+ """Send bitcoins to the target address."""
+ dest_address = self.fetch_destination(address)
+
+ if dest_address is None or not is_valid(dest_address):
+ QMessageBox.warning(parent_window, _('Error'),
+ _('Invalid Bitcoin Address') + ':\n' + address, _('OK'))
+ return False
+
+ convert_amount = lambda amount: \
+ int(D(unicode(amount)) * bitcoin(1))
+ amount = convert_amount(amount)
+
+ if self.wallet.use_encryption:
+ password_dialog = PasswordDialog(parent_window)
+ password = password_dialog.run()
+ if not password:
+ return
+ else:
+ password = None
+
+ fee = 0
+ # 0.1 BTC = 10000000
+ if amount < bitcoin(1) / 10:
+ # 0.001 BTC
+ fee = bitcoin(1) / 1000
+
+ try:
+ tx = self.wallet.mktx([(dest_address, amount)], password, fee)
+ except BaseException as error:
+ QMessageBox.warning(parent_window, _('Error'), str(error), _('OK'))
+ return False
+
+ if tx.is_complete:
+ h = self.wallet.send_tx(tx)
+
+ self.waiting_dialog(lambda: False if self.wallet.tx_event.isSet() else _("Sending transaction, please wait..."))
+
+ status, message = self.wallet.receive_tx(h)
+
+ if not status:
+ import tempfile
+ dumpf = tempfile.NamedTemporaryFile(delete=False)
+ dumpf.write(tx)
+ dumpf.close()
+ print "Dumped error tx to", dumpf.name
+ QMessageBox.warning(parent_window, _('Error'), message, _('OK'))
+ return False
+
+ TransactionWindow(message, self)
+ else:
+ filename = 'unsigned_tx_%s' % (time.mktime(time.gmtime()))
+ try:
+ fileName = QFileDialog.getSaveFileName(QWidget(), _("Select a transaction filename"), os.path.expanduser('~/%s' % (filename)))
+ with open(fileName,'w') as f:
+ f.write(json.dumps(tx.as_dict(),indent=4) + '\n')
+ QMessageBox.information(QWidget(), _('Unsigned transaction created'), _("Unsigned transaction was saved to file:") + " " +fileName, _('OK'))
+ except BaseException as e:
+ QMessageBox.warning(QWidget(), _('Error'), _('Could not write transaction to file: %s' % e), _('OK'))
+ return True
+
+ def fetch_destination(self, address):
+ recipient = unicode(address).strip()
+
+ # alias
+ match1 = re.match("^(|([\w\-\.]+)@)((\w[\w\-]+\.)+[\w\-]+)$",
+ recipient)
+
+ # label or alias, with address in brackets
+ match2 = re.match("(.*?)\s*\<([1-9A-HJ-NP-Za-km-z]{26,})\>",
+ recipient)
+
+ if match1:
+ dest_address = \
+ self.wallet.get_alias(recipient, True,
+ self.show_message, self.question)
+ return dest_address
+ elif match2:
+ return match2.group(2)
+ else:
+ return recipient
+
+
+ def copy_master_public_key(self):
+ master_pubkey = self.wallet.get_master_public_key()
+ qApp.clipboard().setText(master_pubkey)
+ QMessageBox.information(None, _("Copy successful"), _("Your master public key has been copied to your clipboard."))
+
+
+ def acceptbit(self, currency):
+ master_pubkey = self.wallet.master_public_key
+ url = "http://acceptbit.com/mpk/%s/%s" % (master_pubkey, currency)
+ webbrowser.open(url)
+
+ def show_seed_dialog(self):
+ ElectrumWindow.show_seed_dialog(self.wallet)
+
+class MiniDriver(QObject):
+
+ INITIALIZING = 0
+ CONNECTING = 1
+ SYNCHRONIZING = 2
+ READY = 3
+
+ def __init__(self, wallet, window):
+ super(QObject, self).__init__()
+
+ self.wallet = wallet
+ self.network = wallet.network
+ self.window = window
+
+ self.wallet.network.register_callback('updated',self.update_callback)
+ self.wallet.network.register_callback('connected', self.update_callback)
+ self.wallet.network.register_callback('disconnected', self.update_callback)
+
+ self.state = None
+
+ self.initializing()
+ self.connect(self, SIGNAL("updatesignal()"), self.update)
+ self.update_callback()
+
+ # This is a hack to workaround that Qt does not like changing the
+ # window properties from this other thread before the runloop has
+ # been called from.
+ def update_callback(self):
+ self.emit(SIGNAL("updatesignal()"))
+
+ def update(self):
+ if not self.network.interface:
+ self.initializing()
+ elif not self.network.interface.is_connected:
+ self.connecting()
+ elif not self.wallet.up_to_date:
+ self.synchronizing()
+ else:
+ self.ready()
+
+ if self.wallet.up_to_date:
+ self.update_balance()
+ self.update_completions()
+ self.update_history()
+
+ def initializing(self):
+ if self.state == self.INITIALIZING:
+ return
+ self.state = self.INITIALIZING
+ self.window.deactivate()
+
+ def connecting(self):
+ if self.state == self.CONNECTING:
+ return
+ self.state = self.CONNECTING
+ self.window.deactivate()
+
+ def synchronizing(self):
+ if self.state == self.SYNCHRONIZING:
+ return
+ self.state = self.SYNCHRONIZING
+ self.window.deactivate()
+
+ def ready(self):
+ if self.state == self.READY:
+ return
+ self.state = self.READY
+ self.window.activate()
+
+ def update_balance(self):
+ conf_balance, unconf_balance = self.wallet.get_balance()
+ balance = D(conf_balance + unconf_balance)
+ self.window.set_balances(balance)
+
+ def update_completions(self):
+ completions = []
+ for addr, label in self.wallet.labels.items():
+ if addr in self.wallet.addressbook:
+ completions.append("%s <%s>" % (label, addr))
+ self.window.update_completions(completions)
+
+ def update_history(self):
+ tx_history = self.wallet.get_tx_history()
+ self.window.update_history(tx_history)
+
+
+if __name__ == "__main__":
+ app = QApplication(sys.argv)
+ with open(rsrc("style.css")) as style_file:
+ app.setStyleSheet(style_file.read())
+ mini = MiniWindow()
+ sys.exit(app.exec_())
+
diff --git a/gui/qt/main_window.py b/gui/qt/main_window.py
@@ -0,0 +1,1967 @@
+#!/usr/bin/env python
+#
+# Electrum - lightweight Bitcoin client
+# Copyright (C) 2012 thomasv@gitorious
+#
+# This program is free software: you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation, either version 3 of the License, or
+# (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program. If not, see <http://www.gnu.org/licenses/>.
+
+import sys, time, datetime, re, threading
+from electrum.i18n import _, set_language
+from electrum.util import print_error, print_msg
+import os.path, json, ast, traceback
+import shutil
+import StringIO
+
+
+try:
+ import PyQt4
+except:
+ sys.exit("Error: Could not import PyQt4 on Linux systems, you may try 'sudo apt-get install python-qt4'")
+
+from PyQt4.QtGui import *
+from PyQt4.QtCore import *
+import PyQt4.QtCore as QtCore
+
+from electrum.bitcoin import MIN_RELAY_TX_FEE, is_valid
+from electrum.plugins import run_hook
+
+try:
+ import icons_rc
+except:
+ sys.exit("Error: Could not import icons_rc.py, please generate it with: 'pyrcc4 icons.qrc -o gui/icons_rc.py'")
+
+from electrum.wallet import format_satoshis
+from electrum import Transaction
+from electrum import mnemonic
+from electrum import util, bitcoin, commands, Interface, Wallet
+from electrum import SimpleConfig, Wallet, WalletStorage
+
+
+from electrum import bmp, pyqrnative
+
+from amountedit import AmountEdit
+from network_dialog import NetworkDialog
+from qrcodewidget import QRCodeWidget
+
+from decimal import Decimal
+
+import platform
+import httplib
+import socket
+import webbrowser
+import csv
+
+if platform.system() == 'Windows':
+ MONOSPACE_FONT = 'Lucida Console'
+elif platform.system() == 'Darwin':
+ MONOSPACE_FONT = 'Monaco'
+else:
+ MONOSPACE_FONT = 'monospace'
+
+from electrum import ELECTRUM_VERSION
+import re
+
+from util import *
+
+
+
+
+
+
+class StatusBarButton(QPushButton):
+ def __init__(self, icon, tooltip, func):
+ QPushButton.__init__(self, icon, '')
+ self.setToolTip(tooltip)
+ self.setFlat(True)
+ self.setMaximumWidth(25)
+ self.clicked.connect(func)
+ self.func = func
+ self.setIconSize(QSize(25,25))
+
+ def keyPressEvent(self, e):
+ if e.key() == QtCore.Qt.Key_Return:
+ apply(self.func,())
+
+
+
+
+
+
+
+
+
+
+default_column_widths = { "history":[40,140,350,140], "contacts":[350,330], "receive":[[370], [370,200,130]] }
+
+class ElectrumWindow(QMainWindow):
+ def changeEvent(self, event):
+ flags = self.windowFlags();
+ if event and event.type() == QtCore.QEvent.WindowStateChange:
+ if self.windowState() & QtCore.Qt.WindowMinimized:
+ self.build_menu(True)
+ # The only way to toggle the icon in the window managers taskbar is to use the Qt.Tooltip flag
+ # The problem is that it somehow creates an (in)visible window that will stay active and prevent
+ # Electrum from closing.
+ # As for now I have no clue how to implement a proper 'hide to tray' functionality.
+ # self.setWindowFlags(flags & ~Qt.ToolTip)
+ elif event.oldState() & QtCore.Qt.WindowMinimized:
+ self.build_menu(False)
+ #self.setWindowFlags(flags | Qt.ToolTip)
+
+ def build_menu(self, is_hidden = False):
+ m = QMenu()
+ if self.isMinimized():
+ m.addAction(_("Show"), self.showNormal)
+ else:
+ m.addAction(_("Hide"), self.showMinimized)
+
+ m.addSeparator()
+ m.addAction(_("Exit Electrum"), self.close)
+ self.tray.setContextMenu(m)
+
+ def tray_activated(self, reason):
+ if reason == QSystemTrayIcon.DoubleClick:
+ self.showNormal()
+
+
+ def __init__(self, config, network, go_lite):
+ QMainWindow.__init__(self)
+
+ self.config = config
+ self.network = network
+ self.go_lite = go_lite
+
+ self._close_electrum = False
+ self.lite = None
+ self.current_account = self.config.get("current_account", None)
+
+ self.icon = QIcon(':icons/electrum.png')
+ self.tray = QSystemTrayIcon(self.icon, self)
+ self.tray.setToolTip('Electrum')
+ self.tray.activated.connect(self.tray_activated)
+
+ self.build_menu()
+ self.tray.show()
+ self.create_status_bar()
+
+ self.need_update = threading.Event()
+
+ self.expert_mode = config.get('classic_expert_mode', False)
+ self.decimal_point = config.get('decimal_point', 8)
+ self.num_zeros = int(config.get('num_zeros',0))
+
+ set_language(config.get('language'))
+
+ self.funds_error = False
+ self.completions = QStringListModel()
+
+ self.tabs = tabs = QTabWidget(self)
+ self.column_widths = self.config.get("column_widths", default_column_widths )
+ tabs.addTab(self.create_history_tab(), _('History') )
+ tabs.addTab(self.create_send_tab(), _('Send') )
+ tabs.addTab(self.create_receive_tab(), _('Receive') )
+ tabs.addTab(self.create_contacts_tab(), _('Contacts') )
+ tabs.addTab(self.create_console_tab(), _('Console') )
+ tabs.setMinimumSize(600, 400)
+ tabs.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
+ self.setCentralWidget(tabs)
+
+ g = self.config.get("winpos-qt",[100, 100, 840, 400])
+ self.setGeometry(g[0], g[1], g[2], g[3])
+
+ self.init_menubar()
+
+ QShortcut(QKeySequence("Ctrl+W"), self, self.close)
+ QShortcut(QKeySequence("Ctrl+R"), self, self.update_wallet)
+ QShortcut(QKeySequence("Ctrl+Q"), self, self.close)
+ QShortcut(QKeySequence("Ctrl+PgUp"), self, lambda: tabs.setCurrentIndex( (tabs.currentIndex() - 1 )%tabs.count() ))
+ QShortcut(QKeySequence("Ctrl+PgDown"), self, lambda: tabs.setCurrentIndex( (tabs.currentIndex() + 1 )%tabs.count() ))
+
+ self.connect(self, QtCore.SIGNAL('update_status'), self.update_status)
+ self.connect(self, QtCore.SIGNAL('banner_signal'), lambda: self.console.showMessage(self.network.banner) )
+ self.connect(self, QtCore.SIGNAL('transaction_signal'), lambda: self.notify_transactions() )
+
+ self.history_list.setFocus(True)
+
+ # dark magic fix by flatfly; https://bitcointalk.org/index.php?topic=73651.msg959913#msg959913
+ if platform.system() == 'Windows':
+ n = 3 if self.wallet.seed else 2
+ tabs.setCurrentIndex (n)
+ tabs.setCurrentIndex (0)
+
+
+
+
+
+ def load_wallet(self, wallet):
+ import electrum
+ self.wallet = wallet
+
+ self.network.register_callback('updated', lambda: self.need_update.set())
+ self.network.register_callback('banner', lambda: self.emit(QtCore.SIGNAL('banner_signal')))
+ self.network.register_callback('disconnected', lambda: self.emit(QtCore.SIGNAL('update_status')))
+ self.network.register_callback('disconnecting', lambda: self.emit(QtCore.SIGNAL('update_status')))
+ self.network.register_callback('new_transaction', lambda: self.emit(QtCore.SIGNAL('transaction_signal')))
+ title = 'Electrum ' + self.wallet.electrum_version + ' - ' + self.wallet.storage.path
+ if not self.wallet.seed: title += ' [%s]' % (_('seedless'))
+ self.setWindowTitle( title )
+ self.update_wallet()
+ # set initial message
+ self.console.showMessage(self.network.banner)
+ # Once GUI has been initialized check if we want to announce something since the callback has been called before the GUI was initialized
+ self.notify_transactions()
+
+ # account selector
+ accounts = self.wallet.get_account_names()
+ self.account_selector.clear()
+ if len(accounts) > 1:
+ self.account_selector.addItems([_("All accounts")] + accounts.values())
+ self.account_selector.setCurrentIndex(0)
+ self.account_selector.show()
+ else:
+ self.account_selector.hide()
+
+ self.new_account.setEnabled(self.wallet.seed_version>4)
+
+ self.update_lock_icon()
+ self.update_buttons_on_seed()
+ self.update_console()
+
+ run_hook('load_wallet')
+
+
+ def select_wallet_file(self):
+ wallet_folder = self.wallet.storage.path
+ re.sub("(\/\w*.dat)$", "", wallet_folder)
+ file_name = unicode( QFileDialog.getOpenFileName(self, "Select your wallet file", wallet_folder) )
+ return file_name
+
+
+ def open_wallet(self):
+
+ filename = self.select_wallet_file()
+ if not filename:
+ return
+
+ storage = WalletStorage({'wallet_path': filename})
+ if not storage.file_exists:
+ self.show_message("file not found "+ filename)
+ return
+
+ self.wallet.stop_threads()
+
+ # create new wallet
+ wallet = Wallet(storage)
+ wallet.start_threads(self.network)
+
+ self.load_wallet(wallet)
+
+
+
+ def backup_wallet(self):
+ import shutil
+ path = self.wallet.storage.path
+ wallet_folder = os.path.dirname(path)
+ new_filename, ok = QInputDialog.getText(self, _('Filename'), _('Current directory') + ': ' + wallet_folder + '\n' + _('Enter a filename for the copy of your wallet') + ':')
+ new_filename = unicode(new_filename)
+ if not ok or not new_filename:
+ return
+
+ new_path = os.path.join(wallet_folder, new_filename)
+ if new_path != path:
+ try:
+ shutil.copy2(path, new_path)
+ QMessageBox.information(None,"Wallet backup created", _("A copy of your wallet file was created in")+" '%s'" % str(new_path))
+ except (IOError, os.error), reason:
+ QMessageBox.critical(None,"Unable to create backup", _("Electrum was unable to copy your wallet file to the specified location.")+"\n" + str(reason))
+
+
+ def new_wallet(self):
+ import installwizard
+
+ wallet_folder = os.path.dirname(self.wallet.storage.path)
+ filename, ok = QInputDialog.getText(self, _('Filename'), _('Current directory') + ': ' + wallet_folder + '\n'+_('Enter a new file name') + ':')
+ filename = unicode(filename)
+ if not ok or not filename:
+ return
+ filename = os.path.join(wallet_folder, filename)
+
+ storage = WalletStorage({'wallet_path': filename})
+ assert not storage.file_exists
+
+ wizard = installwizard.InstallWizard(self.config, self.network, storage)
+ wallet = wizard.run()
+ if wallet:
+ self.load_wallet(wallet)
+
+
+
+ def init_menubar(self):
+ menubar = QMenuBar()
+
+ file_menu = menubar.addMenu(_("&File"))
+ open_wallet_action = file_menu.addAction(_("&Open"))
+ open_wallet_action.triggered.connect(self.open_wallet)
+
+ new_wallet_action = file_menu.addAction(_("&Create/Restore"))
+ new_wallet_action.triggered.connect(self.new_wallet)
+
+ wallet_backup = file_menu.addAction(_("&Copy"))
+ wallet_backup.triggered.connect(self.backup_wallet)
+
+ quit_item = file_menu.addAction(_("&Close"))
+ quit_item.triggered.connect(self.close)
+
+ wallet_menu = menubar.addMenu(_("&Wallet"))
+
+ new_contact = wallet_menu.addAction(_("&New contact"))
+ new_contact.triggered.connect(self.new_contact_dialog)
+
+ self.new_account = wallet_menu.addAction(_("&New account"))
+ self.new_account.triggered.connect(self.new_account_dialog)
+
+ wallet_menu.addSeparator()
+
+ #if self.wallet.seed:
+ show_seed = wallet_menu.addAction(_("&Seed"))
+ show_seed.triggered.connect(self.show_seed_dialog)
+
+ show_mpk = wallet_menu.addAction(_("&Master Public Key"))
+ show_mpk.triggered.connect(self.show_master_public_key)
+
+ wallet_menu.addSeparator()
+
+ csv_transaction_menu = wallet_menu.addMenu(_("&Create transaction"))
+
+ csv_transaction_file = csv_transaction_menu.addAction(_("&From CSV file"))
+ csv_transaction_file.triggered.connect(self.do_process_from_csv_file)
+
+ csv_transaction_text = csv_transaction_menu.addAction(_("&From CSV text"))
+ csv_transaction_text.triggered.connect(self.do_process_from_csv_text)
+
+ raw_transaction_menu = wallet_menu.addMenu(_("&Load transaction"))
+
+ raw_transaction_file = raw_transaction_menu.addAction(_("&From file"))
+ raw_transaction_file.triggered.connect(self.do_process_from_file)
+
+ raw_transaction_text = raw_transaction_menu.addAction(_("&From text"))
+ raw_transaction_text.triggered.connect(self.do_process_from_text)
+
+
+ tools_menu = menubar.addMenu(_("&Tools"))
+
+ # Settings / Preferences are all reserved keywords in OSX using this as work around
+ preferences_name = _("Electrum preferences") if sys.platform == 'darwin' else _("Preferences")
+ preferences_menu = tools_menu.addAction(preferences_name)
+ preferences_menu.triggered.connect(self.settings_dialog)
+
+ plugins_labels = tools_menu.addAction(_("&Plugins"))
+ plugins_labels.triggered.connect(self.plugins_dialog)
+
+ wallet_menu.addSeparator()
+
+ labels_menu = tools_menu.addMenu(_("&Labels"))
+ import_labels = labels_menu.addAction(_("&Import"))
+ import_labels.triggered.connect(self.do_import_labels)
+ export_labels = labels_menu.addAction(_("&Export"))
+ export_labels.triggered.connect(self.do_export_labels)
+
+ keys_menu = tools_menu.addMenu(_("&Private keys"))
+ import_keys = keys_menu.addAction(_("&Import"))
+ import_keys.triggered.connect(self.do_import_privkey)
+ export_keys = keys_menu.addAction(_("&Export"))
+ export_keys.triggered.connect(self.do_export_privkeys)
+
+ ex_history = tools_menu.addAction(_("&Export History"))
+ ex_history.triggered.connect(self.do_export_history)
+
+
+ help_menu = menubar.addMenu(_("&Help"))
+ show_about = help_menu.addAction(_("&About"))
+ show_about.triggered.connect(self.show_about)
+ web_open = help_menu.addAction(_("&Official website"))
+ web_open.triggered.connect(lambda: webbrowser.open("http://electrum.org"))
+
+ help_menu.addSeparator()
+ doc_open = help_menu.addAction(_("&Documentation"))
+ doc_open.triggered.connect(lambda: webbrowser.open("http://electrum.org/documentation.html"))
+ report_bug = help_menu.addAction(_("&Report Bug"))
+ report_bug.triggered.connect(self.show_report_bug)
+
+ self.setMenuBar(menubar)
+
+ def show_about(self):
+ QMessageBox.about(self, "Electrum",
+ _("Version")+" %s" % (self.wallet.electrum_version) + "\n\n" + _("Electrum's focus is speed, with low resource usage and simplifying Bitcoin. You do not need to perform regular backups, because your wallet can be recovered from a secret phrase that you can memorize or write on paper. Startup times are instant because it operates in conjunction with high-performance servers that handle the most complicated parts of the Bitcoin system."))
+
+ def show_report_bug(self):
+ QMessageBox.information(self, "Electrum - " + _("Reporting Bugs"),
+ _("Please report any bugs as issues on github:")+" <a href=\"https://github.com/spesmilo/electrum/issues\">https://github.com/spesmilo/electrum/issues</a>")
+
+
+ def notify_transactions(self):
+ print_error("Notifying GUI")
+ if len(self.network.interface.pending_transactions_for_notifications) > 0:
+ # Combine the transactions if there are more then three
+ tx_amount = len(self.network.interface.pending_transactions_for_notifications)
+ if(tx_amount >= 3):
+ total_amount = 0
+ for tx in self.network.interface.pending_transactions_for_notifications:
+ is_relevant, is_mine, v, fee = self.wallet.get_tx_value(tx)
+ if(v > 0):
+ total_amount += v
+
+ self.notify(_("%(txs)s new transactions received. Total amount received in the new transactions %(amount)s %(unit)s") \
+ % { 'txs' : tx_amount, 'amount' : self.format_amount(total_amount), 'unit' : self.base_unit()})
+
+ self.network.interface.pending_transactions_for_notifications = []
+ else:
+ for tx in self.network.interface.pending_transactions_for_notifications:
+ if tx:
+ self.network.interface.pending_transactions_for_notifications.remove(tx)
+ is_relevant, is_mine, v, fee = self.wallet.get_tx_value(tx)
+ if(v > 0):
+ self.notify(_("New transaction received. %(amount)s %(unit)s") % { 'amount' : self.format_amount(v), 'unit' : self.base_unit()})
+
+ def notify(self, message):
+ self.tray.showMessage("Electrum", message, QSystemTrayIcon.Information, 20000)
+
+
+
+ def set_label(self, name, text = None):
+ changed = False
+ old_text = self.wallet.labels.get(name)
+ if text:
+ if old_text != text:
+ self.wallet.labels[name] = text
+ self.wallet.storage.put('labels', self.wallet.labels)
+ changed = True
+ else:
+ if old_text:
+ self.wallet.labels.pop(name)
+ changed = True
+ run_hook('set_label', name, text, changed)
+ return changed
+
+
+ # custom wrappers for getOpenFileName and getSaveFileName, that remember the path selected by the user
+ def getOpenFileName(self, title, filter = ""):
+ directory = self.config.get('io_dir', os.path.expanduser('~'))
+ fileName = unicode( QFileDialog.getOpenFileName(self, title, directory, filter) )
+ if fileName and directory != os.path.dirname(fileName):
+ self.config.set_key('io_dir', os.path.dirname(fileName), True)
+ return fileName
+
+ def getSaveFileName(self, title, filename, filter = ""):
+ directory = self.config.get('io_dir', os.path.expanduser('~'))
+ path = os.path.join( directory, filename )
+ fileName = unicode( QFileDialog.getSaveFileName(self, title, path, filter) )
+ if fileName and directory != os.path.dirname(fileName):
+ self.config.set_key('io_dir', os.path.dirname(fileName), True)
+ return fileName
+
+ def close(self):
+ QMainWindow.close(self)
+ run_hook('close_main_window')
+
+ def connect_slots(self, sender):
+ self.connect(sender, QtCore.SIGNAL('timersignal'), self.timer_actions)
+ self.previous_payto_e=''
+
+ def timer_actions(self):
+ if self.need_update.is_set():
+ self.update_wallet()
+ self.need_update.clear()
+ run_hook('timer_actions')
+
+ def format_amount(self, x, is_diff=False, whitespaces=False):
+ return format_satoshis(x, is_diff, self.num_zeros, self.decimal_point, whitespaces)
+
+ def read_amount(self, x):
+ if x in['.', '']: return None
+ p = pow(10, self.decimal_point)
+ return int( p * Decimal(x) )
+
+ def base_unit(self):
+ assert self.decimal_point in [5,8]
+ return "BTC" if self.decimal_point == 8 else "mBTC"
+
+ def set_status_text(self, text):
+ self.balance_label.setText(text)
+ run_hook('set_status_text', text)
+
+
+ def update_status(self):
+ if self.network.interface and self.network.interface.is_connected:
+ if not self.wallet.up_to_date:
+ text = _("Synchronizing...")
+ icon = QIcon(":icons/status_waiting.png")
+ else:
+ c, u = self.wallet.get_account_balance(self.current_account)
+ text = _( "Balance" ) + ": %s "%( self.format_amount(c) ) + self.base_unit()
+ if u: text += " [%s unconfirmed]"%( self.format_amount(u,True).strip() )
+ self.tray.setToolTip(text)
+ icon = QIcon(":icons/status_connected.png")
+ else:
+ text = _("Not connected")
+ icon = QIcon(":icons/status_disconnected.png")
+
+ self.set_status_text(text)
+ self.status_button.setIcon( icon )
+
+ def update_wallet(self):
+ self.update_status()
+ if self.wallet.up_to_date or not self.network.interface.is_connected:
+ self.update_history_tab()
+ self.update_receive_tab()
+ self.update_contacts_tab()
+ self.update_completions()
+
+
+
+ def create_history_tab(self):
+ self.history_list = l = MyTreeWidget(self)
+ l.setColumnCount(5)
+ for i,width in enumerate(self.column_widths['history']):
+ l.setColumnWidth(i, width)
+ l.setHeaderLabels( [ '', _('Date'), _('Description') , _('Amount'), _('Balance')] )
+ self.connect(l, SIGNAL('itemDoubleClicked(QTreeWidgetItem*, int)'), self.tx_label_clicked)
+ self.connect(l, SIGNAL('itemChanged(QTreeWidgetItem*, int)'), self.tx_label_changed)
+
+ l.customContextMenuRequested.connect(self.create_history_menu)
+ return l
+
+
+ def create_history_menu(self, position):
+ self.history_list.selectedIndexes()
+ item = self.history_list.currentItem()
+ if not item: return
+ tx_hash = str(item.data(0, Qt.UserRole).toString())
+ if not tx_hash: return
+ menu = QMenu()
+ menu.addAction(_("Copy ID to Clipboard"), lambda: self.app.clipboard().setText(tx_hash))
+ menu.addAction(_("Details"), lambda: self.show_transaction(self.wallet.transactions.get(tx_hash)))
+ menu.addAction(_("Edit description"), lambda: self.tx_label_clicked(item,2))
+ menu.exec_(self.contacts_list.viewport().mapToGlobal(position))
+
+
+ def show_transaction(self, tx):
+ import transaction_dialog
+ d = transaction_dialog.TxDialog(tx, self)
+ d.exec_()
+
+ def tx_label_clicked(self, item, column):
+ if column==2 and item.isSelected():
+ self.is_edit=True
+ item.setFlags(Qt.ItemIsEditable|Qt.ItemIsSelectable | Qt.ItemIsUserCheckable | Qt.ItemIsEnabled | Qt.ItemIsDragEnabled)
+ self.history_list.editItem( item, column )
+ item.setFlags(Qt.ItemIsSelectable | Qt.ItemIsUserCheckable | Qt.ItemIsEnabled | Qt.ItemIsDragEnabled)
+ self.is_edit=False
+
+ def tx_label_changed(self, item, column):
+ if self.is_edit:
+ return
+ self.is_edit=True
+ tx_hash = str(item.data(0, Qt.UserRole).toString())
+ tx = self.wallet.transactions.get(tx_hash)
+ text = unicode( item.text(2) )
+ self.set_label(tx_hash, text)
+ if text:
+ item.setForeground(2, QBrush(QColor('black')))
+ else:
+ text = self.wallet.get_default_label(tx_hash)
+ item.setText(2, text)
+ item.setForeground(2, QBrush(QColor('gray')))
+ self.is_edit=False
+
+
+ def edit_label(self, is_recv):
+ l = self.receive_list if is_recv else self.contacts_list
+ item = l.currentItem()
+ item.setFlags(Qt.ItemIsEditable|Qt.ItemIsSelectable | Qt.ItemIsUserCheckable | Qt.ItemIsEnabled | Qt.ItemIsDragEnabled)
+ l.editItem( item, 1 )
+ item.setFlags(Qt.ItemIsSelectable | Qt.ItemIsUserCheckable | Qt.ItemIsEnabled | Qt.ItemIsDragEnabled)
+
+
+
+ def address_label_clicked(self, item, column, l, column_addr, column_label):
+ if column == column_label and item.isSelected():
+ is_editable = item.data(0, 32).toBool()
+ if not is_editable:
+ return
+ addr = unicode( item.text(column_addr) )
+ label = unicode( item.text(column_label) )
+ item.setFlags(Qt.ItemIsEditable|Qt.ItemIsSelectable | Qt.ItemIsUserCheckable | Qt.ItemIsEnabled | Qt.ItemIsDragEnabled)
+ l.editItem( item, column )
+ item.setFlags(Qt.ItemIsSelectable | Qt.ItemIsUserCheckable | Qt.ItemIsEnabled | Qt.ItemIsDragEnabled)
+
+
+ def address_label_changed(self, item, column, l, column_addr, column_label):
+ if column == column_label:
+ addr = unicode( item.text(column_addr) )
+ text = unicode( item.text(column_label) )
+ is_editable = item.data(0, 32).toBool()
+ if not is_editable:
+ return
+
+ changed = self.set_label(addr, text)
+ if changed:
+ self.update_history_tab()
+ self.update_completions()
+
+ self.current_item_changed(item)
+
+ run_hook('item_changed', item, column)
+
+
+ def current_item_changed(self, a):
+ run_hook('current_item_changed', a)
+
+
+
+ def update_history_tab(self):
+
+ self.history_list.clear()
+ for item in self.wallet.get_tx_history(self.current_account):
+ tx_hash, conf, is_mine, value, fee, balance, timestamp = item
+ if conf > 0:
+ try:
+ time_str = datetime.datetime.fromtimestamp( timestamp).isoformat(' ')[:-3]
+ except:
+ time_str = _("unknown")
+
+ if conf == -1:
+ time_str = 'unverified'
+ icon = QIcon(":icons/unconfirmed.png")
+ elif conf == 0:
+ time_str = 'pending'
+ icon = QIcon(":icons/unconfirmed.png")
+ elif conf < 6:
+ icon = QIcon(":icons/clock%d.png"%conf)
+ else:
+ icon = QIcon(":icons/confirmed.png")
+
+ if value is not None:
+ v_str = self.format_amount(value, True, whitespaces=True)
+ else:
+ v_str = '--'
+
+ balance_str = self.format_amount(balance, whitespaces=True)
+
+ if tx_hash:
+ label, is_default_label = self.wallet.get_label(tx_hash)
+ else:
+ label = _('Pruned transaction outputs')
+ is_default_label = False
+
+ item = QTreeWidgetItem( [ '', time_str, label, v_str, balance_str] )
+ item.setFont(2, QFont(MONOSPACE_FONT))
+ item.setFont(3, QFont(MONOSPACE_FONT))
+ item.setFont(4, QFont(MONOSPACE_FONT))
+ if value < 0:
+ item.setForeground(3, QBrush(QColor("#BC1E1E")))
+ if tx_hash:
+ item.setData(0, Qt.UserRole, tx_hash)
+ item.setToolTip(0, "%d %s\nTxId:%s" % (conf, _('Confirmations'), tx_hash) )
+ if is_default_label:
+ item.setForeground(2, QBrush(QColor('grey')))
+
+ item.setIcon(0, icon)
+ self.history_list.insertTopLevelItem(0,item)
+
+
+ self.history_list.setCurrentItem(self.history_list.topLevelItem(0))
+
+
+ def create_send_tab(self):
+ w = QWidget()
+
+ grid = QGridLayout()
+ grid.setSpacing(8)
+ grid.setColumnMinimumWidth(3,300)
+ grid.setColumnStretch(5,1)
+
+
+ self.payto_e = QLineEdit()
+ grid.addWidget(QLabel(_('Pay to')), 1, 0)
+ grid.addWidget(self.payto_e, 1, 1, 1, 3)
+
+ grid.addWidget(HelpButton(_('Recipient of the funds.') + '\n\n' + _('You may enter a Bitcoin address, a label from your list of contacts (a list of completions will be proposed), or an alias (email-like address that forwards to a Bitcoin address)')), 1, 4)
+
+ completer = QCompleter()
+ completer.setCaseSensitivity(False)
+ self.payto_e.setCompleter(completer)
+ completer.setModel(self.completions)
+
+ self.message_e = QLineEdit()
+ grid.addWidget(QLabel(_('Description')), 2, 0)
+ grid.addWidget(self.message_e, 2, 1, 1, 3)
+ grid.addWidget(HelpButton(_('Description of the transaction (not mandatory).') + '\n\n' + _('The description is not sent to the recipient of the funds. It is stored in your wallet file, and displayed in the \'History\' tab.')), 2, 4)
+
+ self.amount_e = AmountEdit(self.base_unit)
+ grid.addWidget(QLabel(_('Amount')), 3, 0)
+ grid.addWidget(self.amount_e, 3, 1, 1, 2)
+ grid.addWidget(HelpButton(
+ _('Amount to be sent.') + '\n\n' \
+ + _('The amount will be displayed in red if you do not have enough funds in your wallet. Note that if you have frozen some of your addresses, the available funds will be lower than your total balance.') \
+ + '\n\n' + _('Keyboard shortcut: type "!" to send all your coins.')), 3, 3)
+
+ self.fee_e = AmountEdit(self.base_unit)
+ grid.addWidget(QLabel(_('Fee')), 4, 0)
+ grid.addWidget(self.fee_e, 4, 1, 1, 2)
+ grid.addWidget(HelpButton(
+ _('Bitcoin transactions are in general not free. A transaction fee is paid by the sender of the funds.') + '\n\n'\
+ + _('The amount of fee can be decided freely by the sender. However, transactions with low fees take more time to be processed.') + '\n\n'\
+ + _('A suggested fee is automatically added to this field. You may override it. The suggested fee increases with the size of the transaction.')), 4, 3)
+
+
+ self.send_button = EnterButton(_("Send"), self.do_send)
+ grid.addWidget(self.send_button, 6, 1)
+
+ b = EnterButton(_("Clear"),self.do_clear)
+ grid.addWidget(b, 6, 2)
+
+ self.payto_sig = QLabel('')
+ grid.addWidget(self.payto_sig, 7, 0, 1, 4)
+
+ QShortcut(QKeySequence("Up"), w, w.focusPreviousChild)
+ QShortcut(QKeySequence("Down"), w, w.focusNextChild)
+ w.setLayout(grid)
+
+ w2 = QWidget()
+ vbox = QVBoxLayout()
+ vbox.addWidget(w)
+ vbox.addStretch(1)
+ w2.setLayout(vbox)
+
+ def entry_changed( is_fee ):
+ self.funds_error = False
+
+ if self.amount_e.is_shortcut:
+ self.amount_e.is_shortcut = False
+ c, u = self.wallet.get_account_balance(self.current_account)
+ inputs, total, fee = self.wallet.choose_tx_inputs( c + u, 0, self.current_account)
+ fee = self.wallet.estimated_fee(inputs)
+ amount = c + u - fee
+ self.amount_e.setText( self.format_amount(amount) )
+ self.fee_e.setText( self.format_amount( fee ) )
+ return
+
+ amount = self.read_amount(str(self.amount_e.text()))
+ fee = self.read_amount(str(self.fee_e.text()))
+
+ if not is_fee: fee = None
+ if amount is None:
+ return
+ inputs, total, fee = self.wallet.choose_tx_inputs( amount, fee, self.current_account )
+ if not is_fee:
+ self.fee_e.setText( self.format_amount( fee ) )
+ if inputs:
+ palette = QPalette()
+ palette.setColor(self.amount_e.foregroundRole(), QColor('black'))
+ text = ""
+ else:
+ palette = QPalette()
+ palette.setColor(self.amount_e.foregroundRole(), QColor('red'))
+ self.funds_error = True
+ text = _( "Not enough funds" )
+ c, u = self.wallet.get_frozen_balance()
+ if c+u: text += ' (' + self.format_amount(c+u).strip() + self.base_unit() + ' ' +_("are frozen") + ')'
+
+ self.statusBar().showMessage(text)
+ self.amount_e.setPalette(palette)
+ self.fee_e.setPalette(palette)
+
+ self.amount_e.textChanged.connect(lambda: entry_changed(False) )
+ self.fee_e.textChanged.connect(lambda: entry_changed(True) )
+
+ run_hook('create_send_tab', grid)
+ return w2
+
+
+ def update_completions(self):
+ l = []
+ for addr,label in self.wallet.labels.items():
+ if addr in self.wallet.addressbook:
+ l.append( label + ' <' + addr + '>')
+
+ run_hook('update_completions', l)
+ self.completions.setStringList(l)
+
+
+ def protected(func):
+ return lambda s, *args: s.do_protect(func, args)
+
+
+ def do_send(self):
+
+ label = unicode( self.message_e.text() )
+ r = unicode( self.payto_e.text() )
+ r = r.strip()
+
+ # label or alias, with address in brackets
+ m = re.match('(.*?)\s*\<([1-9A-HJ-NP-Za-km-z]{26,})\>', r)
+ to_address = m.group(2) if m else r
+
+ if not is_valid(to_address):
+ QMessageBox.warning(self, _('Error'), _('Invalid Bitcoin Address') + ':\n' + to_address, _('OK'))
+ return
+
+ try:
+ amount = self.read_amount(unicode( self.amount_e.text()))
+ except:
+ QMessageBox.warning(self, _('Error'), _('Invalid Amount'), _('OK'))
+ return
+ try:
+ fee = self.read_amount(unicode( self.fee_e.text()))
+ except:
+ QMessageBox.warning(self, _('Error'), _('Invalid Fee'), _('OK'))
+ return
+
+ confirm_amount = self.config.get('confirm_amount', 100000000)
+ if amount >= confirm_amount:
+ if not self.question(_("send %(amount)s to %(address)s?")%{ 'amount' : self.format_amount(amount) + ' '+ self.base_unit(), 'address' : to_address}):
+ return
+
+ self.send_tx(to_address, amount, fee, label)
+
+
+ @protected
+ def send_tx(self, to_address, amount, fee, label, password):
+
+ try:
+ tx = self.wallet.mktx_from_account( [(to_address, amount)], password, fee, self.current_account)
+ except BaseException, e:
+ traceback.print_exc(file=sys.stdout)
+ self.show_message(str(e))
+ return
+
+ if tx.requires_fee(self.wallet.verifier) and fee < MIN_RELAY_TX_FEE:
+ QMessageBox.warning(self, _('Error'), _("This transaction requires a higher fee, or it will not be propagated by the network."), _('OK'))
+ return
+
+ run_hook('send_tx', tx)
+
+ if label:
+ self.set_label(tx.hash(), label)
+
+ if tx.is_complete:
+ h = self.wallet.send_tx(tx)
+ waiting_dialog(lambda: False if self.wallet.tx_event.isSet() else _("Please wait..."))
+ status, msg = self.wallet.receive_tx( h )
+ if status:
+ QMessageBox.information(self, '', _('Payment sent.')+'\n'+msg, _('OK'))
+ self.do_clear()
+ self.update_contacts_tab()
+ else:
+ QMessageBox.warning(self, _('Error'), msg, _('OK'))
+ else:
+ filename = label + '.txn' if label else 'unsigned_%s.txn' % (time.mktime(time.gmtime()))
+ try:
+ fileName = self.getSaveFileName(_("Select a transaction filename"), filename, "*.txn")
+ with open(fileName,'w') as f:
+ f.write(json.dumps(tx.as_dict(),indent=4) + '\n')
+ QMessageBox.information(self, _('Unsigned transaction created'), _("Unsigned transaction was saved to file:") + " " +fileName, _('OK'))
+ except:
+ QMessageBox.warning(self, _('Error'), _('Could not write transaction to file'), _('OK'))
+
+ # add recipient to addressbook
+ if to_address not in self.wallet.addressbook and not self.wallet.is_mine(to_address):
+ self.wallet.addressbook.append(to_address)
+
+
+
+
+ def set_url(self, url):
+ address, amount, label, message, signature, identity, url = util.parse_url(url)
+ if self.base_unit() == 'mBTC': amount = str( 1000* Decimal(amount))
+
+ if label and self.wallet.labels.get(address) != label:
+ if self.question('Give label "%s" to address %s ?'%(label,address)):
+ if address not in self.wallet.addressbook and not self.wallet.is_mine(address):
+ self.wallet.addressbook.append(address)
+ self.set_label(address, label)
+
+ run_hook('set_url', url, self.show_message, self.question)
+
+ self.tabs.setCurrentIndex(1)
+ label = self.wallet.labels.get(address)
+ m_addr = label + ' <'+ address +'>' if label else address
+ self.payto_e.setText(m_addr)
+
+ self.message_e.setText(message)
+ self.amount_e.setText(amount)
+ if identity:
+ self.set_frozen(self.payto_e,True)
+ self.set_frozen(self.amount_e,True)
+ self.set_frozen(self.message_e,True)
+ self.payto_sig.setText( ' '+_('The bitcoin URI was signed by')+' ' + identity )
+ else:
+ self.payto_sig.setVisible(False)
+
+ def do_clear(self):
+ self.payto_sig.setVisible(False)
+ for e in [self.payto_e, self.message_e, self.amount_e, self.fee_e]:
+ e.setText('')
+ self.set_frozen(e,False)
+ self.update_status()
+
+ def set_frozen(self,entry,frozen):
+ if frozen:
+ entry.setReadOnly(True)
+ entry.setFrame(False)
+ palette = QPalette()
+ palette.setColor(entry.backgroundRole(), QColor('lightgray'))
+ entry.setPalette(palette)
+ else:
+ entry.setReadOnly(False)
+ entry.setFrame(True)
+ palette = QPalette()
+ palette.setColor(entry.backgroundRole(), QColor('white'))
+ entry.setPalette(palette)
+
+
+ def toggle_freeze(self,addr):
+ if not addr: return
+ if addr in self.wallet.frozen_addresses:
+ self.wallet.unfreeze(addr)
+ else:
+ self.wallet.freeze(addr)
+ self.update_receive_tab()
+
+ def toggle_priority(self,addr):
+ if not addr: return
+ if addr in self.wallet.prioritized_addresses:
+ self.wallet.unprioritize(addr)
+ else:
+ self.wallet.prioritize(addr)
+ self.update_receive_tab()
+
+
+ def create_list_tab(self, headers):
+ "generic tab creation method"
+ l = MyTreeWidget(self)
+ l.setColumnCount( len(headers) )
+ l.setHeaderLabels( headers )
+
+ w = QWidget()
+ vbox = QVBoxLayout()
+ w.setLayout(vbox)
+
+ vbox.setMargin(0)
+ vbox.setSpacing(0)
+ vbox.addWidget(l)
+ buttons = QWidget()
+ vbox.addWidget(buttons)
+
+ hbox = QHBoxLayout()
+ hbox.setMargin(0)
+ hbox.setSpacing(0)
+ buttons.setLayout(hbox)
+
+ return l,w,hbox
+
+
+ def create_receive_tab(self):
+ l,w,hbox = self.create_list_tab([ _('Address'), _('Label'), _('Balance'), _('Tx')])
+ l.setContextMenuPolicy(Qt.CustomContextMenu)
+ l.customContextMenuRequested.connect(self.create_receive_menu)
+ self.connect(l, SIGNAL('itemDoubleClicked(QTreeWidgetItem*, int)'), lambda a, b: self.address_label_clicked(a,b,l,0,1))
+ self.connect(l, SIGNAL('itemChanged(QTreeWidgetItem*, int)'), lambda a,b: self.address_label_changed(a,b,l,0,1))
+ self.connect(l, SIGNAL('currentItemChanged(QTreeWidgetItem*, QTreeWidgetItem*)'), lambda a,b: self.current_item_changed(a))
+ self.receive_list = l
+ self.receive_buttons_hbox = hbox
+ hbox.addStretch(1)
+ return w
+
+
+ def receive_tab_set_mode(self, i):
+ self.save_column_widths()
+ self.expert_mode = (i == 1)
+ self.config.set_key('classic_expert_mode', self.expert_mode, True)
+ self.update_receive_tab()
+
+
+ def save_column_widths(self):
+ if not self.expert_mode:
+ widths = [ self.receive_list.columnWidth(0) ]
+ else:
+ widths = []
+ for i in range(self.receive_list.columnCount() -1):
+ widths.append(self.receive_list.columnWidth(i))
+ self.column_widths["receive"][self.expert_mode] = widths
+
+ self.column_widths["history"] = []
+ for i in range(self.history_list.columnCount() - 1):
+ self.column_widths["history"].append(self.history_list.columnWidth(i))
+
+ self.column_widths["contacts"] = []
+ for i in range(self.contacts_list.columnCount() - 1):
+ self.column_widths["contacts"].append(self.contacts_list.columnWidth(i))
+
+ self.config.set_key("column_widths", self.column_widths, True)
+
+
+ def create_contacts_tab(self):
+ l,w,hbox = self.create_list_tab([_('Address'), _('Label'), _('Tx')])
+ l.setContextMenuPolicy(Qt.CustomContextMenu)
+ l.customContextMenuRequested.connect(self.create_contact_menu)
+ for i,width in enumerate(self.column_widths['contacts']):
+ l.setColumnWidth(i, width)
+
+ self.connect(l, SIGNAL('itemDoubleClicked(QTreeWidgetItem*, int)'), lambda a, b: self.address_label_clicked(a,b,l,0,1))
+ self.connect(l, SIGNAL('itemChanged(QTreeWidgetItem*, int)'), lambda a,b: self.address_label_changed(a,b,l,0,1))
+ self.contacts_list = l
+ self.contacts_buttons_hbox = hbox
+ hbox.addStretch(1)
+ return w
+
+
+ def delete_imported_key(self, addr):
+ if self.question(_("Do you want to remove")+" %s "%addr +_("from your wallet?")):
+ self.wallet.delete_imported_key(addr)
+ self.update_receive_tab()
+ self.update_history_tab()
+
+
+ def create_receive_menu(self, position):
+ # fixme: this function apparently has a side effect.
+ # if it is not called the menu pops up several times
+ #self.receive_list.selectedIndexes()
+
+ item = self.receive_list.itemAt(position)
+ if not item: return
+ addr = unicode(item.text(0))
+ if not is_valid(addr):
+ item.setExpanded(not item.isExpanded())
+ return
+ menu = QMenu()
+ menu.addAction(_("Copy to clipboard"), lambda: self.app.clipboard().setText(addr))
+ menu.addAction(_("QR code"), lambda: self.show_qrcode("bitcoin:" + addr, _("Address")) )
+ menu.addAction(_("Edit label"), lambda: self.edit_label(True))
+ menu.addAction(_("Private key"), lambda: self.show_private_key(addr))
+ menu.addAction(_("Sign message"), lambda: self.sign_message(addr))
+ if addr in self.wallet.imported_keys:
+ menu.addAction(_("Remove from wallet"), lambda: self.delete_imported_key(addr))
+
+ if self.expert_mode:
+ t = _("Unfreeze") if addr in self.wallet.frozen_addresses else _("Freeze")
+ menu.addAction(t, lambda: self.toggle_freeze(addr))
+ t = _("Unprioritize") if addr in self.wallet.prioritized_addresses else _("Prioritize")
+ menu.addAction(t, lambda: self.toggle_priority(addr))
+
+ run_hook('receive_menu', menu)
+ menu.exec_(self.receive_list.viewport().mapToGlobal(position))
+
+
+ def payto(self, addr):
+ if not addr: return
+ label = self.wallet.labels.get(addr)
+ m_addr = label + ' <' + addr + '>' if label else addr
+ self.tabs.setCurrentIndex(1)
+ self.payto_e.setText(m_addr)
+ self.amount_e.setFocus()
+
+
+ def delete_contact(self, x):
+ if self.question(_("Do you want to remove")+" %s "%x +_("from your list of contacts?")):
+ self.wallet.delete_contact(x)
+ self.set_label(x, None)
+ self.update_history_tab()
+ self.update_contacts_tab()
+ self.update_completions()
+
+
+ def create_contact_menu(self, position):
+ item = self.contacts_list.itemAt(position)
+ if not item: return
+ addr = unicode(item.text(0))
+ label = unicode(item.text(1))
+ is_editable = item.data(0,32).toBool()
+ payto_addr = item.data(0,33).toString()
+ menu = QMenu()
+ menu.addAction(_("Copy to Clipboard"), lambda: self.app.clipboard().setText(addr))
+ menu.addAction(_("Pay to"), lambda: self.payto(payto_addr))
+ menu.addAction(_("QR code"), lambda: self.show_qrcode("bitcoin:" + addr, _("Address")))
+ if is_editable:
+ menu.addAction(_("Edit label"), lambda: self.edit_label(False))
+ menu.addAction(_("Delete"), lambda: self.delete_contact(addr))
+
+ run_hook('create_contact_menu', menu, item)
+ menu.exec_(self.contacts_list.viewport().mapToGlobal(position))
+
+
+ def update_receive_item(self, item):
+ item.setFont(0, QFont(MONOSPACE_FONT))
+ address = str(item.data(0,0).toString())
+ label = self.wallet.labels.get(address,'')
+ item.setData(1,0,label)
+ item.setData(0,32, True) # is editable
+
+ run_hook('update_receive_item', address, item)
+
+ c, u = self.wallet.get_addr_balance(address)
+ balance = self.format_amount(c + u)
+ item.setData(2,0,balance)
+
+ if self.expert_mode:
+ if address in self.wallet.frozen_addresses:
+ item.setBackgroundColor(0, QColor('lightblue'))
+ elif address in self.wallet.prioritized_addresses:
+ item.setBackgroundColor(0, QColor('lightgreen'))
+
+
+ def update_receive_tab(self):
+ l = self.receive_list
+
+ l.clear()
+ l.setColumnHidden(2, not self.expert_mode)
+ l.setColumnHidden(3, not self.expert_mode)
+ for i,width in enumerate(self.column_widths['receive'][self.expert_mode]):
+ l.setColumnWidth(i, width)
+
+ if self.current_account is None:
+ account_items = self.wallet.accounts.items()
+ elif self.current_account != -1:
+ account_items = [(self.current_account, self.wallet.accounts.get(self.current_account))]
+ else:
+ account_items = []
+
+ for k, account in account_items:
+ name = self.wallet.get_account_name(k)
+ c,u = self.wallet.get_account_balance(k)
+ account_item = QTreeWidgetItem( [ name, '', self.format_amount(c+u), ''] )
+ l.addTopLevelItem(account_item)
+ account_item.setExpanded(True)
+
+ for is_change in ([0,1] if self.expert_mode else [0]):
+ if self.expert_mode:
+ name = _("Receiving") if not is_change else _("Change")
+ seq_item = QTreeWidgetItem( [ name, '', '', '', ''] )
+ account_item.addChild(seq_item)
+ if not is_change: seq_item.setExpanded(True)
+ else:
+ seq_item = account_item
+ is_red = False
+ gap = 0
+
+ for address in account.get_addresses(is_change):
+ h = self.wallet.history.get(address,[])
+
+ if h == []:
+ gap += 1
+ if gap > self.wallet.gap_limit:
+ is_red = True
+ else:
+ gap = 0
+
+ num_tx = '*' if h == ['*'] else "%d"%len(h)
+ item = QTreeWidgetItem( [ address, '', '', num_tx] )
+ self.update_receive_item(item)
+ if is_red:
+ item.setBackgroundColor(1, QColor('red'))
+ seq_item.addChild(item)
+
+
+ if self.wallet.imported_keys and (self.current_account is None or self.current_account == -1):
+ c,u = self.wallet.get_imported_balance()
+ account_item = QTreeWidgetItem( [ _('Imported'), '', self.format_amount(c+u), ''] )
+ l.addTopLevelItem(account_item)
+ account_item.setExpanded(True)
+ for address in self.wallet.imported_keys.keys():
+ item = QTreeWidgetItem( [ address, '', '', ''] )
+ self.update_receive_item(item)
+ account_item.addChild(item)
+
+
+ # we use column 1 because column 0 may be hidden
+ l.setCurrentItem(l.topLevelItem(0),1)
+
+
+ def update_contacts_tab(self):
+ l = self.contacts_list
+ l.clear()
+
+ for address in self.wallet.addressbook:
+ label = self.wallet.labels.get(address,'')
+ n = self.wallet.get_num_tx(address)
+ item = QTreeWidgetItem( [ address, label, "%d"%n] )
+ item.setFont(0, QFont(MONOSPACE_FONT))
+ # 32 = label can be edited (bool)
+ item.setData(0,32, True)
+ # 33 = payto string
+ item.setData(0,33, address)
+ l.addTopLevelItem(item)
+
+ run_hook('update_contacts_tab', l)
+ l.setCurrentItem(l.topLevelItem(0))
+
+
+
+ def create_console_tab(self):
+ from console import Console
+ self.console = console = Console()
+ return console
+
+
+ def update_console(self):
+ console = self.console
+ console.history = self.config.get("console-history",[])
+ console.history_index = len(console.history)
+
+ console.updateNamespace({'wallet' : self.wallet, 'network' : self.network, 'gui':self})
+ console.updateNamespace({'util' : util, 'bitcoin':bitcoin})
+
+ c = commands.Commands(self.wallet, self.network, lambda: self.console.set_json(True))
+ methods = {}
+ def mkfunc(f, method):
+ return lambda *args: apply( f, (method, args, self.password_dialog ))
+ for m in dir(c):
+ if m[0]=='_' or m=='wallet' or m == 'interface': continue
+ methods[m] = mkfunc(c._run, m)
+
+ console.updateNamespace(methods)
+
+
+ def change_account(self,s):
+ if s == _("All accounts"):
+ self.current_account = None
+ else:
+ accounts = self.wallet.get_account_names()
+ for k, v in accounts.items():
+ if v == s:
+ self.current_account = k
+ self.update_history_tab()
+ self.update_status()
+ self.update_receive_tab()
+
+ def create_status_bar(self):
+
+ sb = QStatusBar()
+ sb.setFixedHeight(35)
+ qtVersion = qVersion()
+
+ self.balance_label = QLabel("")
+ sb.addWidget(self.balance_label)
+
+ from version_getter import UpdateLabel
+ self.updatelabel = UpdateLabel(self.config, sb)
+
+ self.account_selector = QComboBox()
+ self.connect(self.account_selector,SIGNAL("activated(QString)"),self.change_account)
+ sb.addPermanentWidget(self.account_selector)
+
+ if (int(qtVersion[0]) >= 4 and int(qtVersion[2]) >= 7):
+ sb.addPermanentWidget( StatusBarButton( QIcon(":icons/switchgui.png"), _("Switch to Lite Mode"), self.go_lite ) )
+
+ self.lock_icon = QIcon()
+ self.password_button = StatusBarButton( self.lock_icon, _("Password"), self.change_password_dialog )
+ sb.addPermanentWidget( self.password_button )
+
+ sb.addPermanentWidget( StatusBarButton( QIcon(":icons/preferences.png"), _("Preferences"), self.settings_dialog ) )
+ self.seed_button = StatusBarButton( QIcon(":icons/seed.png"), _("Seed"), self.show_seed_dialog )
+ sb.addPermanentWidget( self.seed_button )
+ self.status_button = StatusBarButton( QIcon(":icons/status_disconnected.png"), _("Network"), self.run_network_dialog )
+ sb.addPermanentWidget( self.status_button )
+
+ run_hook('create_status_bar', (sb,))
+
+ self.setStatusBar(sb)
+
+
+ def update_lock_icon(self):
+ icon = QIcon(":icons/lock.png") if self.wallet.use_encryption else QIcon(":icons/unlock.png")
+ self.password_button.setIcon( icon )
+
+
+ def update_buttons_on_seed(self):
+ if self.wallet.seed:
+ self.seed_button.show()
+ self.password_button.show()
+ self.send_button.setText(_("Send"))
+ else:
+ self.password_button.hide()
+ self.seed_button.hide()
+ self.send_button.setText(_("Create unsigned transaction"))
+
+
+ def change_password_dialog(self):
+ from password_dialog import PasswordDialog
+ d = PasswordDialog(self.wallet, self)
+ d.run()
+ self.update_lock_icon()
+
+
+ def new_contact_dialog(self):
+ text, ok = QInputDialog.getText(self, _('New Contact'), _('Address') + ':')
+ address = unicode(text)
+ if ok:
+ if is_valid(address):
+ self.wallet.add_contact(address)
+ self.update_contacts_tab()
+ self.update_history_tab()
+ self.update_completions()
+ else:
+ QMessageBox.warning(self, _('Error'), _('Invalid Address'), _('OK'))
+
+
+ def new_account_dialog(self):
+
+ dialog = QDialog(self)
+ dialog.setModal(1)
+ dialog.setWindowTitle(_("New Account"))
+
+ addr = self.wallet.new_account_address()
+ vbox = QVBoxLayout()
+ msg = _("Electrum considers that an account exists only if it contains bitcoins.") + '\n' \
+ + _("To create a new account, please send coins to the first address of that account.") + '\n' \
+ + _("Note: you will need to wait for 2 confirmations before the account is created.")
+ vbox.addWidget(QLabel(msg))
+ vbox.addWidget(QLabel(_('Address')+':'))
+ e = QLineEdit(addr)
+ e.setReadOnly(True)
+ vbox.addWidget(e)
+
+ vbox.addLayout(ok_cancel_buttons(dialog))
+ dialog.setLayout(vbox)
+ r = dialog.exec_()
+ if r:
+ self.payto(addr)
+
+
+
+ def show_master_public_key(self):
+ dialog = QDialog(self)
+ dialog.setModal(1)
+ dialog.setWindowTitle(_("Master Public Key"))
+
+ main_text = QTextEdit()
+ main_text.setText(self.wallet.get_master_public_key())
+ main_text.setReadOnly(True)
+ main_text.setMaximumHeight(170)
+ qrw = QRCodeWidget(self.wallet.get_master_public_key())
+
+ ok_button = QPushButton(_("OK"))
+ ok_button.setDefault(True)
+ ok_button.clicked.connect(dialog.accept)
+
+ main_layout = QGridLayout()
+ main_layout.addWidget(QLabel(_('Your Master Public Key is:')), 0, 0, 1, 2)
+
+ main_layout.addWidget(main_text, 1, 0)
+ main_layout.addWidget(qrw, 1, 1 )
+
+ vbox = QVBoxLayout()
+ vbox.addLayout(main_layout)
+ hbox = QHBoxLayout()
+ hbox.addStretch(1)
+ hbox.addWidget(ok_button)
+ vbox.addLayout(hbox)
+
+ dialog.setLayout(vbox)
+ dialog.exec_()
+
+
+ @protected
+ def show_seed_dialog(self, password):
+ if not self.wallet.seed:
+ QMessageBox.information(parent, _('Message'), _('No seed'), _('OK'))
+ return
+ try:
+ seed = self.wallet.decode_seed(password)
+ except:
+ QMessageBox.warning(self, _('Error'), _('Incorrect Password'), _('OK'))
+ return
+
+ from seed_dialog import SeedDialog
+ d = SeedDialog(self)
+ d.show_seed(seed, self.wallet.imported_keys)
+
+
+
+ def show_qrcode(self, data, title = _("QR code")):
+ if not data: return
+ d = QDialog(self)
+ d.setModal(1)
+ d.setWindowTitle(title)
+ d.setMinimumSize(270, 300)
+ vbox = QVBoxLayout()
+ qrw = QRCodeWidget(data)
+ vbox.addWidget(qrw, 1)
+ vbox.addWidget(QLabel(data), 0, Qt.AlignHCenter)
+ hbox = QHBoxLayout()
+ hbox.addStretch(1)
+
+ def print_qr(self):
+ filename = "qrcode.bmp"
+ bmp.save_qrcode(qrw.qr, filename)
+ QMessageBox.information(None, _('Message'), _("QR code saved to file") + " " + filename, _('OK'))
+
+ b = QPushButton(_("Save"))
+ hbox.addWidget(b)
+ b.clicked.connect(print_qr)
+
+ b = QPushButton(_("Close"))
+ hbox.addWidget(b)
+ b.clicked.connect(d.accept)
+ b.setDefault(True)
+
+ vbox.addLayout(hbox)
+ d.setLayout(vbox)
+ d.exec_()
+
+
+ def do_protect(self, func, args):
+ if self.wallet.use_encryption:
+ password = self.password_dialog()
+ if not password:
+ return
+ else:
+ password = None
+
+ if args != (False,):
+ args = (self,) + args + (password,)
+ else:
+ args = (self,password)
+ apply( func, args)
+
+
+ @protected
+ def show_private_key(self, address, password):
+ if not address: return
+ try:
+ pk_list = self.wallet.get_private_key(address, password)
+ except BaseException, e:
+ self.show_message(str(e))
+ return
+ QMessageBox.information(self, _('Private key'), _('Address')+ ': ' + address + '\n\n' + _('Private key') + ': ' + '\n'.join(pk_list), _('OK'))
+
+
+ @protected
+ def do_sign(self, address, message, signature, password):
+ message = unicode(message.toPlainText())
+ message = message.encode('utf-8')
+ try:
+ sig = self.wallet.sign_message(str(address.text()), message, password)
+ signature.setText(sig)
+ except BaseException, e:
+ self.show_message(str(e))
+
+ def sign_message(self, address):
+ if not address: return
+ d = QDialog(self)
+ d.setModal(1)
+ d.setWindowTitle(_('Sign Message'))
+ d.setMinimumSize(410, 290)
+
+ tab_widget = QTabWidget()
+ tab = QWidget()
+ layout = QGridLayout(tab)
+
+ sign_address = QLineEdit()
+
+ sign_address.setText(address)
+ layout.addWidget(QLabel(_('Address')), 1, 0)
+ layout.addWidget(sign_address, 1, 1)
+
+ sign_message = QTextEdit()
+ layout.addWidget(QLabel(_('Message')), 2, 0)
+ layout.addWidget(sign_message, 2, 1)
+ layout.setRowStretch(2,3)
+
+ sign_signature = QTextEdit()
+ layout.addWidget(QLabel(_('Signature')), 3, 0)
+ layout.addWidget(sign_signature, 3, 1)
+ layout.setRowStretch(3,1)
+
+
+ hbox = QHBoxLayout()
+ b = QPushButton(_("Sign"))
+ hbox.addWidget(b)
+ b.clicked.connect(lambda: self.do_sign(sign_address, sign_message, sign_signature))
+ b = QPushButton(_("Close"))
+ b.clicked.connect(d.accept)
+ hbox.addWidget(b)
+ layout.addLayout(hbox, 4, 1)
+ tab_widget.addTab(tab, _("Sign"))
+
+
+ tab = QWidget()
+ layout = QGridLayout(tab)
+
+ verify_address = QLineEdit()
+ layout.addWidget(QLabel(_('Address')), 1, 0)
+ layout.addWidget(verify_address, 1, 1)
+
+ verify_message = QTextEdit()
+ layout.addWidget(QLabel(_('Message')), 2, 0)
+ layout.addWidget(verify_message, 2, 1)
+ layout.setRowStretch(2,3)
+
+ verify_signature = QTextEdit()
+ layout.addWidget(QLabel(_('Signature')), 3, 0)
+ layout.addWidget(verify_signature, 3, 1)
+ layout.setRowStretch(3,1)
+
+ def do_verify():
+ message = unicode(verify_message.toPlainText())
+ message = message.encode('utf-8')
+ if self.wallet.verify_message(verify_address.text(), str(verify_signature.toPlainText()), message):
+ self.show_message(_("Signature verified"))
+ else:
+ self.show_message(_("Error: wrong signature"))
+
+ hbox = QHBoxLayout()
+ b = QPushButton(_("Verify"))
+ b.clicked.connect(do_verify)
+ hbox.addWidget(b)
+ b = QPushButton(_("Close"))
+ b.clicked.connect(d.accept)
+ hbox.addWidget(b)
+ layout.addLayout(hbox, 4, 1)
+ tab_widget.addTab(tab, _("Verify"))
+
+ vbox = QVBoxLayout()
+ vbox.addWidget(tab_widget)
+ d.setLayout(vbox)
+ d.exec_()
+
+
+
+
+ def question(self, msg):
+ return QMessageBox.question(self, _('Message'), msg, QMessageBox.Yes | QMessageBox.No, QMessageBox.No) == QMessageBox.Yes
+
+ def show_message(self, msg):
+ QMessageBox.information(self, _('Message'), msg, _('OK'))
+
+ def password_dialog(self ):
+ d = QDialog(self)
+ d.setModal(1)
+
+ pw = QLineEdit()
+ pw.setEchoMode(2)
+
+ vbox = QVBoxLayout()
+ msg = _('Please enter your password')
+ vbox.addWidget(QLabel(msg))
+
+ grid = QGridLayout()
+ grid.setSpacing(8)
+ grid.addWidget(QLabel(_('Password')), 1, 0)
+ grid.addWidget(pw, 1, 1)
+ vbox.addLayout(grid)
+
+ vbox.addLayout(ok_cancel_buttons(d))
+ d.setLayout(vbox)
+
+ run_hook('password_dialog', pw, grid, 1)
+ if not d.exec_(): return
+ return unicode(pw.text())
+
+
+
+
+
+
+
+
+ def tx_from_text(self, txt):
+ "json or raw hexadecimal"
+ try:
+ txt.decode('hex')
+ tx = Transaction(txt)
+ return tx
+ except:
+ pass
+
+ try:
+ tx_dict = json.loads(str(txt))
+ assert "hex" in tx_dict.keys()
+ assert "complete" in tx_dict.keys()
+ if not tx_dict["complete"]:
+ assert "input_info" in tx_dict.keys()
+ tx = Transaction(tx_dict["hex"])
+ return tx
+ except:
+ pass
+
+ QMessageBox.critical(None, _("Unable to parse transaction"), _("Electrum was unable to parse your transaction"))
+
+
+
+ def read_tx_from_file(self):
+ fileName = self.getOpenFileName(_("Select your transaction file"), "*.txn")
+ if not fileName:
+ return
+ try:
+ with open(fileName, "r") as f:
+ file_content = f.read()
+ except (ValueError, IOError, os.error), reason:
+ QMessageBox.critical(None, _("Unable to read file or no transaction found"), _("Electrum was unable to open your transaction file") + "\n" + str(reason))
+
+ return self.tx_from_text(file_content)
+
+
+ @protected
+ def sign_raw_transaction(self, tx, input_info, password):
+ self.wallet.signrawtransaction(tx, input_info, [], password)
+
+ def do_process_from_text(self):
+ text = text_dialog(self, _('Input raw transaction'), _("Transaction:"), _("Load transaction"))
+ if not text:
+ return
+ tx = self.tx_from_text(text)
+ if tx:
+ self.show_transaction(tx)
+
+ def do_process_from_file(self):
+ tx = self.read_tx_from_file()
+ if tx:
+ self.show_transaction(tx)
+
+ def do_process_from_csvReader(self, csvReader):
+ outputs = []
+ try:
+ for row in csvReader:
+ address = row[0]
+ amount = float(row[1])
+ amount = int(100000000*amount)
+ outputs.append((address, amount))
+ except (ValueError, IOError, os.error), reason:
+ QMessageBox.critical(None, _("Unable to read file or no transaction found"), _("Electrum was unable to open your transaction file") + "\n" + str(reason))
+ return
+
+ try:
+ tx = self.wallet.make_unsigned_transaction(outputs, None, None)
+ except BaseException, e:
+ self.show_message(str(e))
+ return
+
+ self.show_transaction(tx)
+
+ def do_process_from_csv_file(self):
+ fileName = self.getOpenFileName(_("Select your transaction CSV"), "*.csv")
+ if not fileName:
+ return
+ try:
+ with open(fileName, "r") as f:
+ csvReader = csv.reader(f)
+ self.do_process_from_csvReader(csvReader)
+ except (ValueError, IOError, os.error), reason:
+ QMessageBox.critical(None, _("Unable to read file or no transaction found"), _("Electrum was unable to open your transaction file") + "\n" + str(reason))
+ return
+
+ def do_process_from_csv_text(self):
+ text = text_dialog(self, _('Input CSV'), _("CSV:"), _("Load CSV"))
+ if not text:
+ return
+ f = StringIO.StringIO(text)
+ csvReader = csv.reader(f)
+ self.do_process_from_csvReader(csvReader)
+
+
+
+ @protected
+ def do_export_privkeys(self, password):
+ self.show_message("%s\n%s\n%s" % (_("WARNING: ALL your private keys are secret."), _("Exposing a single private key can compromise your entire wallet!"), _("In particular, DO NOT use 'redeem private key' services proposed by third parties.")))
+
+ try:
+ select_export = _('Select file to export your private keys to')
+ fileName = self.getSaveFileName(select_export, 'electrum-private-keys.csv', "*.csv")
+ if fileName:
+ with open(fileName, "w+") as csvfile:
+ transaction = csv.writer(csvfile)
+ transaction.writerow(["address", "private_key"])
+
+ addresses = self.wallet.addresses(True)
+
+ for addr in addresses:
+ pk = "".join(self.wallet.get_private_key(addr, password))
+ transaction.writerow(["%34s"%addr,pk])
+
+ self.show_message(_("Private keys exported."))
+
+ except (IOError, os.error), reason:
+ export_error_label = _("Electrum was unable to produce a private key-export.")
+ QMessageBox.critical(None, _("Unable to create csv"), export_error_label + "\n" + str(reason))
+
+ except BaseException, e:
+ self.show_message(str(e))
+ return
+
+
+ def do_import_labels(self):
+ labelsFile = self.getOpenFileName(_("Open labels file"), "*.dat")
+ if not labelsFile: return
+ try:
+ f = open(labelsFile, 'r')
+ data = f.read()
+ f.close()
+ for key, value in json.loads(data).items():
+ self.wallet.set_label(key, value)
+ QMessageBox.information(None, _("Labels imported"), _("Your labels were imported from")+" '%s'" % str(labelsFile))
+ except (IOError, os.error), reason:
+ QMessageBox.critical(None, _("Unable to import labels"), _("Electrum was unable to import your labels.")+"\n" + str(reason))
+
+
+ def do_export_labels(self):
+ labels = self.wallet.labels
+ try:
+ fileName = self.getSaveFileName(_("Select file to save your labels"), 'electrum_labels.dat', "*.dat")
+ if fileName:
+ with open(fileName, 'w+') as f:
+ json.dump(labels, f)
+ QMessageBox.information(None, _("Labels exported"), _("Your labels where exported to")+" '%s'" % str(fileName))
+ except (IOError, os.error), reason:
+ QMessageBox.critical(None, _("Unable to export labels"), _("Electrum was unable to export your labels.")+"\n" + str(reason))
+
+
+ def do_export_history(self):
+ from lite_window import csv_transaction
+ csv_transaction(self.wallet)
+
+
+ @protected
+ def do_import_privkey(self, password):
+ if not self.wallet.imported_keys:
+ r = QMessageBox.question(None, _('Warning'), '<b>'+_('Warning') +':\n</b><br/>'+ _('Imported keys are not recoverable from seed.') + ' ' \
+ + _('If you ever need to restore your wallet from its seed, these keys will be lost.') + '<p>' \
+ + _('Are you sure you understand what you are doing?'), 3, 4)
+ if r == 4: return
+
+ text = text_dialog(self, _('Import private keys'), _("Enter private keys")+':', _("Import"))
+ if not text: return
+
+ text = str(text).split()
+ badkeys = []
+ addrlist = []
+ for key in text:
+ try:
+ addr = self.wallet.import_key(key, password)
+ except BaseException as e:
+ badkeys.append(key)
+ continue
+ if not addr:
+ badkeys.append(key)
+ else:
+ addrlist.append(addr)
+ if addrlist:
+ QMessageBox.information(self, _('Information'), _("The following addresses were added") + ':\n' + '\n'.join(addrlist))
+ if badkeys:
+ QMessageBox.critical(self, _('Error'), _("The following inputs could not be imported") + ':\n'+ '\n'.join(badkeys))
+ self.update_receive_tab()
+ self.update_history_tab()
+
+
+ def settings_dialog(self):
+ d = QDialog(self)
+ d.setWindowTitle(_('Electrum Settings'))
+ d.setModal(1)
+ vbox = QVBoxLayout()
+
+ tabs = QTabWidget(self)
+ self.settings_tab = tabs
+ vbox.addWidget(tabs)
+
+ tab1 = QWidget()
+ grid_ui = QGridLayout(tab1)
+ grid_ui.setColumnStretch(0,1)
+ tabs.addTab(tab1, _('Display') )
+
+ nz_label = QLabel(_('Display zeros'))
+ grid_ui.addWidget(nz_label, 0, 0)
+ nz_e = AmountEdit(None,True)
+ nz_e.setText("%d"% self.num_zeros)
+ grid_ui.addWidget(nz_e, 0, 1)
+ msg = _('Number of zeros displayed after the decimal point. For example, if this is set to 2, "1." will be displayed as "1.00"')
+ grid_ui.addWidget(HelpButton(msg), 0, 2)
+ if not self.config.is_modifiable('num_zeros'):
+ for w in [nz_e, nz_label]: w.setEnabled(False)
+
+ lang_label=QLabel(_('Language') + ':')
+ grid_ui.addWidget(lang_label, 1, 0)
+ lang_combo = QComboBox()
+ from electrum.i18n import languages
+ lang_combo.addItems(languages.values())
+ try:
+ index = languages.keys().index(self.config.get("language",''))
+ except:
+ index = 0
+ lang_combo.setCurrentIndex(index)
+ grid_ui.addWidget(lang_combo, 1, 1)
+ grid_ui.addWidget(HelpButton(_('Select which language is used in the GUI (after restart).')+' '), 1, 2)
+ if not self.config.is_modifiable('language'):
+ for w in [lang_combo, lang_label]: w.setEnabled(False)
+
+ expert_cb = QCheckBox(_('Expert mode'))
+ expert_cb.setChecked(self.expert_mode)
+ grid_ui.addWidget(expert_cb, 3, 0)
+ hh = _('In expert mode, your client will:') + '\n' \
+ + _(' - Show change addresses in the Receive tab') + '\n' \
+ + _(' - Display the balance of each address') + '\n' \
+ + _(' - Add freeze/prioritize actions to addresses.')
+ grid_ui.addWidget(HelpButton(hh), 3, 2)
+ grid_ui.setRowStretch(4,1)
+
+ # wallet tab
+ tab2 = QWidget()
+ grid_wallet = QGridLayout(tab2)
+ grid_wallet.setColumnStretch(0,1)
+ tabs.addTab(tab2, _('Wallet') )
+
+ fee_label = QLabel(_('Transaction fee'))
+ grid_wallet.addWidget(fee_label, 0, 0)
+ fee_e = AmountEdit(self.base_unit)
+ fee_e.setText(self.format_amount(self.wallet.fee).strip())
+ grid_wallet.addWidget(fee_e, 0, 2)
+ msg = _('Fee per kilobyte of transaction.') + ' ' \
+ + _('Recommended value') + ': ' + self.format_amount(50000)
+ grid_wallet.addWidget(HelpButton(msg), 0, 3)
+ if not self.config.is_modifiable('fee_per_kb'):
+ for w in [fee_e, fee_label]: w.setEnabled(False)
+
+ usechange_cb = QCheckBox(_('Use change addresses'))
+ usechange_cb.setChecked(self.wallet.use_change)
+ grid_wallet.addWidget(usechange_cb, 1, 0)
+ grid_wallet.addWidget(HelpButton(_('Using change addresses makes it more difficult for other people to track your transactions.')+' '), 1, 3)
+ if not self.config.is_modifiable('use_change'): usechange_cb.setEnabled(False)
+
+ units = ['BTC', 'mBTC']
+ unit_label = QLabel(_('Base unit'))
+ grid_wallet.addWidget(unit_label, 3, 0)
+ unit_combo = QComboBox()
+ unit_combo.addItems(units)
+ unit_combo.setCurrentIndex(units.index(self.base_unit()))
+ grid_wallet.addWidget(unit_combo, 3, 2)
+ grid_wallet.addWidget(HelpButton(_('Base unit of your wallet.')\
+ + '\n1BTC=1000mBTC.\n' \
+ + _(' This settings affects the fields in the Send tab')+' '), 3, 3)
+ grid_wallet.setRowStretch(4,1)
+
+
+ run_hook('create_settings_tab', tabs)
+
+ vbox.addLayout(ok_cancel_buttons(d))
+ d.setLayout(vbox)
+
+ # run the dialog
+ if not d.exec_(): return
+
+ fee = unicode(fee_e.text())
+ try:
+ fee = self.read_amount(fee)
+ except:
+ QMessageBox.warning(self, _('Error'), _('Invalid value') +': %s'%fee, _('OK'))
+ return
+
+ self.wallet.set_fee(fee)
+
+ nz = unicode(nz_e.text())
+ try:
+ nz = int( nz )
+ if nz>8: nz=8
+ except:
+ QMessageBox.warning(self, _('Error'), _('Invalid value')+':%s'%nz, _('OK'))
+ return
+
+ if self.num_zeros != nz:
+ self.num_zeros = nz
+ self.config.set_key('num_zeros', nz, True)
+ self.update_history_tab()
+ self.update_receive_tab()
+
+ usechange_result = usechange_cb.isChecked()
+ if self.wallet.use_change != usechange_result:
+ self.wallet.use_change = usechange_result
+ self.config.set_key('use_change', self.wallet.use_change, True)
+
+ unit_result = units[unit_combo.currentIndex()]
+ if self.base_unit() != unit_result:
+ self.decimal_point = 8 if unit_result == 'BTC' else 5
+ self.config.set_key('decimal_point', self.decimal_point, True)
+ self.update_history_tab()
+ self.update_status()
+
+ need_restart = False
+
+ lang_request = languages.keys()[lang_combo.currentIndex()]
+ if lang_request != self.config.get('language'):
+ self.config.set_key("language", lang_request, True)
+ need_restart = True
+
+
+ run_hook('close_settings_dialog')
+
+ if need_restart:
+ QMessageBox.warning(self, _('Success'), _('Please restart Electrum to activate the new GUI settings'), _('OK'))
+
+ self.receive_tab_set_mode(expert_cb.isChecked())
+
+ def run_network_dialog(self):
+ NetworkDialog(self.wallet.network, self.config, self).do_exec()
+
+ def closeEvent(self, event):
+ g = self.geometry()
+ self.config.set_key("winpos-qt", [g.left(),g.top(),g.width(),g.height()], True)
+ self.save_column_widths()
+ self.config.set_key("console-history", self.console.history[-50:], True)
+ event.accept()
+
+
+
+ def plugins_dialog(self):
+ from electrum.plugins import plugins
+
+ d = QDialog(self)
+ d.setWindowTitle(_('Electrum Plugins'))
+ d.setModal(1)
+
+ vbox = QVBoxLayout(d)
+
+ # plugins
+ scroll = QScrollArea()
+ scroll.setEnabled(True)
+ scroll.setWidgetResizable(True)
+ scroll.setMinimumSize(400,250)
+ vbox.addWidget(scroll)
+
+ w = QWidget()
+ scroll.setWidget(w)
+ w.setMinimumHeight(len(plugins)*35)
+
+ grid = QGridLayout()
+ grid.setColumnStretch(0,1)
+ w.setLayout(grid)
+
+ def mk_toggle(cb, p):
+ return lambda: cb.setChecked(p.toggle())
+ for i, p in enumerate(plugins):
+ try:
+ cb = QCheckBox(p.fullname())
+ cb.setDisabled(not p.is_available())
+ cb.setChecked(p.is_enabled())
+ cb.clicked.connect(mk_toggle(cb,p))
+ grid.addWidget(cb, i, 0)
+ if p.requires_settings():
+ grid.addWidget(EnterButton(_('Settings'), p.settings_dialog), i, 1)
+ grid.addWidget(HelpButton(p.description()), i, 2)
+ except:
+ print_msg(_("Error: cannot display plugin"), p)
+ traceback.print_exc(file=sys.stdout)
+ grid.setRowStretch(i+1,1)
+
+ vbox.addLayout(close_button(d))
+
+ d.exec_()
diff --git a/gui/qt/network_dialog.py b/gui/qt/network_dialog.py
@@ -0,0 +1,244 @@
+#!/usr/bin/env python
+#
+# Electrum - lightweight Bitcoin client
+# Copyright (C) 2012 thomasv@gitorious
+#
+# This program is free software: you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation, either version 3 of the License, or
+# (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program. If not, see <http://www.gnu.org/licenses/>.
+
+import sys, time, datetime, re, threading
+from electrum.i18n import _
+from electrum.util import print_error, print_msg
+import os.path, json, ast, traceback
+
+from PyQt4.QtGui import *
+from PyQt4.QtCore import *
+from electrum import DEFAULT_SERVERS, DEFAULT_PORTS
+
+from util import *
+
+protocol_names = ['TCP', 'HTTP', 'SSL', 'HTTPS']
+protocol_letters = 'thsg'
+
+class NetworkDialog(QDialog):
+ def __init__(self, network, config, parent):
+
+ QDialog.__init__(self,parent)
+ self.setModal(1)
+ self.setWindowTitle(_('Server'))
+ self.setMinimumSize(375, 20)
+
+ self.network = network
+ self.interface = interface = network.interface
+ self.config = config
+ self.protocol = None
+
+ if parent:
+ n = len(network.interfaces)
+ if n:
+ status = _("Connected to %d servers")%n + ", %d "%(network.blockchain.height) + _("blocks")
+ else:
+ status = _("Not connected")
+
+ if interface.is_connected:
+ status += "\n" + _("Main server:") + " %s"%(interface.host)
+ else:
+ status += "\n" + _("Disconnected from main server")
+
+
+ server = interface.server
+ else:
+ import random
+ status = _("Please choose a server.") + "\n" + _("Select 'Cancel' if you are offline.")
+ server = interface.server
+
+ self.servers = network.get_servers()
+
+
+ vbox = QVBoxLayout()
+ vbox.setSpacing(30)
+
+ hbox = QHBoxLayout()
+ l = QLabel()
+ l.setPixmap(QPixmap(":icons/network.png"))
+ hbox.addStretch(10)
+ hbox.addWidget(l)
+ hbox.addWidget(QLabel(status))
+ hbox.addStretch(50)
+ hbox.addWidget(HelpButton(_("As of version 1.9, Electrum connects to several servers in order to download block headers and find out the longest blockchain. However, your wallet addresses are sent to a single server, in order to receive your transaction history.")))
+ vbox.addLayout(hbox)
+
+ # grid layout
+ grid = QGridLayout()
+ grid.setSpacing(8)
+ vbox.addLayout(grid)
+
+ # server
+ self.server_protocol = QComboBox()
+ self.server_host = QLineEdit()
+ self.server_host.setFixedWidth(200)
+ self.server_port = QLineEdit()
+ self.server_port.setFixedWidth(60)
+
+ self.server_protocol.addItems(protocol_names)
+
+ grid.addWidget(QLabel(_('Server') + ':'), 0, 0)
+ grid.addWidget(self.server_protocol, 0, 1)
+ grid.addWidget(self.server_host, 0, 2)
+ grid.addWidget(self.server_port, 0, 3)
+
+ self.server_protocol.connect(self.server_protocol, SIGNAL('currentIndexChanged(int)'), self.change_protocol)
+
+ label = _('Active Servers') if interface.servers else _('Default Servers')
+ self.servers_list_widget = QTreeWidget(parent)
+ self.servers_list_widget.setHeaderLabels( [ label, _('Limit') ] )
+ self.servers_list_widget.setMaximumHeight(150)
+ self.servers_list_widget.setColumnWidth(0, 240)
+
+ if server:
+ host, port, protocol = server.split(':')
+ self.set_protocol(protocol)
+ self.change_server(host, protocol)
+ else:
+ self.set_protocol('s')
+
+ self.servers_list_widget.connect(self.servers_list_widget,
+ SIGNAL('currentItemChanged(QTreeWidgetItem*,QTreeWidgetItem*)'),
+ lambda x,y: self.server_changed(x))
+ grid.addWidget(self.servers_list_widget, 1, 1, 1, 3)
+
+ if not config.is_modifiable('server'):
+ for w in [self.server_host, self.server_port, self.server_protocol, self.servers_list_widget]: w.setEnabled(False)
+
+ # auto cycle
+ self.autocycle_cb = QCheckBox(_('Try random servers if disconnected'))
+ self.autocycle_cb.setChecked(self.config.get('auto_cycle', True))
+ grid.addWidget(self.autocycle_cb, 3, 1, 3, 2)
+ if not self.config.is_modifiable('auto_cycle'): self.autocycle_cb.setEnabled(False)
+
+ # proxy setting
+ self.proxy_mode = QComboBox()
+ self.proxy_host = QLineEdit()
+ self.proxy_host.setFixedWidth(200)
+ self.proxy_port = QLineEdit()
+ self.proxy_port.setFixedWidth(60)
+ self.proxy_mode.addItems(['NONE', 'SOCKS4', 'SOCKS5', 'HTTP'])
+
+ def check_for_disable(index = False):
+ if self.proxy_mode.currentText() != 'NONE':
+ self.proxy_host.setEnabled(True)
+ self.proxy_port.setEnabled(True)
+ else:
+ self.proxy_host.setEnabled(False)
+ self.proxy_port.setEnabled(False)
+
+ check_for_disable()
+ self.proxy_mode.connect(self.proxy_mode, SIGNAL('currentIndexChanged(int)'), check_for_disable)
+
+ if not self.config.is_modifiable('proxy'):
+ for w in [self.proxy_host, self.proxy_port, self.proxy_mode]: w.setEnabled(False)
+
+ proxy_config = interface.proxy if interface.proxy else { "mode":"none", "host":"localhost", "port":"8080"}
+ self.proxy_mode.setCurrentIndex(self.proxy_mode.findText(str(proxy_config.get("mode").upper())))
+ self.proxy_host.setText(proxy_config.get("host"))
+ self.proxy_port.setText(proxy_config.get("port"))
+
+ grid.addWidget(QLabel(_('Proxy') + ':'), 2, 0)
+ grid.addWidget(self.proxy_mode, 2, 1)
+ grid.addWidget(self.proxy_host, 2, 2)
+ grid.addWidget(self.proxy_port, 2, 3)
+
+ # buttons
+ vbox.addLayout(ok_cancel_buttons(self))
+ self.setLayout(vbox)
+
+
+ def init_servers_list(self):
+ self.servers_list_widget.clear()
+ for _host, d in self.servers.items():
+ if d.get(self.protocol):
+ pruning_level = d.get('pruning','')
+ self.servers_list_widget.addTopLevelItem(QTreeWidgetItem( [ _host, pruning_level ] ))
+
+
+ def set_protocol(self, protocol):
+ if protocol != self.protocol:
+ self.protocol = protocol
+ self.init_servers_list()
+
+ def change_protocol(self, index):
+ p = protocol_letters[index]
+ host = unicode(self.server_host.text())
+ pp = self.servers.get(host)
+ if p not in pp.keys():
+ p = pp.keys()[0]
+ port = pp[p]
+ self.server_host.setText( host )
+ self.server_port.setText( port )
+ self.set_protocol(p)
+
+ def server_changed(self, x):
+ if x:
+ self.change_server(str(x.text(0)), self.protocol)
+
+ def change_server(self, host, protocol):
+
+ pp = self.servers.get(host, DEFAULT_PORTS)
+ if protocol:
+ port = pp.get(protocol)
+ if not port: protocol = None
+
+ if not protocol:
+ if 's' in pp.keys():
+ protocol = 's'
+ port = pp.get(protocol)
+ else:
+ protocol = pp.keys()[0]
+ port = pp.get(protocol)
+
+ self.server_host.setText( host )
+ self.server_port.setText( port )
+ self.server_protocol.setCurrentIndex(protocol_letters.index(protocol))
+
+ if not self.servers: return
+ for p in protocol_letters:
+ i = protocol_letters.index(p)
+ j = self.server_protocol.model().index(i,0)
+ #if p not in pp.keys(): # and self.interface.is_connected:
+ # self.server_protocol.model().setData(j, QVariant(0), Qt.UserRole-1)
+ #else:
+ # self.server_protocol.model().setData(j, QVariant(33), Qt.UserRole-1)
+
+
+ def do_exec(self):
+
+ if not self.exec_():
+ return
+
+ server = ':'.join([str( self.server_host.text() ),
+ str( self.server_port.text() ),
+ (protocol_letters[self.server_protocol.currentIndex()]) ])
+
+ if self.proxy_mode.currentText() != 'NONE':
+ proxy = { 'mode':str(self.proxy_mode.currentText()).lower(),
+ 'host':str(self.proxy_host.text()),
+ 'port':str(self.proxy_port.text()) }
+ else:
+ proxy = None
+
+ self.config.set_key("proxy", proxy, True)
+ self.config.set_key("server", server, True)
+ self.network.set_server(server, proxy)
+
+ self.config.set_key('auto_cycle', self.autocycle_cb.isChecked(), True)
+ return True
diff --git a/gui/gui_classic/password_dialog.py b/gui/qt/password_dialog.py
diff --git a/gui/gui_classic/qrcodewidget.py b/gui/qt/qrcodewidget.py
diff --git a/gui/gui_classic/receiving_widget.py b/gui/qt/receiving_widget.py
diff --git a/gui/gui_classic/seed_dialog.py b/gui/qt/seed_dialog.py
diff --git a/gui/gui_classic/transaction_dialog.py b/gui/qt/transaction_dialog.py
diff --git a/gui/gui_classic/qt_util.py b/gui/qt/util.py
diff --git a/gui/gui_classic/version_getter.py b/gui/qt/version_getter.py
diff --git a/plugins/exchange_rate.py b/plugins/exchange_rate.py
@@ -9,7 +9,7 @@ import re
from decimal import Decimal
from electrum.plugins import BasePlugin
from electrum.i18n import _
-from electrum_gui.gui_classic.qt_util import *
+from electrum_gui.qt.util import *
class Exchanger(threading.Thread):
diff --git a/plugins/labels.py b/plugins/labels.py
@@ -20,7 +20,7 @@ from electrum import bmp, pyqrnative
from electrum.plugins import BasePlugin
from electrum.i18n import _
-from electrum_gui.gui_classic import HelpButton
+from electrum_gui.qt import HelpButton
class Plugin(BasePlugin):
diff --git a/plugins/pointofsale.py b/plugins/pointofsale.py
@@ -7,7 +7,7 @@ from PyQt4.QtCore import *
import PyQt4.QtCore as QtCore
import PyQt4.QtGui as QtGui
-from electrum_gui.gui_classic.qrcodewidget import QRCodeWidget
+from electrum_gui.qt.qrcodewidget import QRCodeWidget
from electrum import bmp, pyqrnative, BasePlugin
from electrum.i18n import _
diff --git a/plugins/qrscanner.py b/plugins/qrscanner.py
@@ -7,7 +7,7 @@ from electrum.i18n import _
import re
from electrum import Transaction
from electrum.bitcoin import MIN_RELAY_TX_FEE, is_valid
-from electrum_gui.gui_classic.qrcodewidget import QRCodeWidget
+from electrum_gui.qt.qrcodewidget import QRCodeWidget
from electrum import bmp
import json
diff --git a/setup.py b/setup.py
@@ -74,25 +74,26 @@ setup(name = "Electrum",
'electrum.i18n',
'electrum.pyqrnative',
'electrum.plugins',
- 'electrum_gui.gui_gtk',
- 'electrum_gui.gui_text',
- 'electrum_gui.gui_classic',
- 'electrum_gui.gui_classic.qt_console',
- 'electrum_gui.gui_classic.lite_window',
- 'electrum_gui.gui_classic.main_window',
- 'electrum_gui.gui_classic.installwizard',
- 'electrum_gui.gui_classic.icons_rc',
- 'electrum_gui.gui_classic.qrcodewidget',
- 'electrum_gui.gui_classic.history_widget',
- 'electrum_gui.gui_classic.receiving_widget',
- 'electrum_gui.gui_classic.qt_util',
- 'electrum_gui.gui_classic.network_dialog',
- 'electrum_gui.gui_classic.password_dialog',
- 'electrum_gui.gui_classic.seed_dialog',
- 'electrum_gui.gui_classic.transaction dialog',
- 'electrum_gui.gui_classic.version_getter',
- 'electrum_gui.gui_classic.amountedit',
- #'electrum_plugins.aliases',
+ 'electrum_gui.gtk',
+ 'electrum_gui.text',
+ 'electrum_gui.qt',
+ 'electrum_gui.qt.amountedit',
+ 'electrum_gui.qt.console',
+ 'electrum_gui.qt.history_widget',
+ 'electrum_gui.qt.installwizard',
+ 'electrum_gui.qt.icons_rc',
+ 'electrum_gui.qt.lite_window',
+ 'electrum_gui.qt.main_window',
+ 'electrum_gui.qt.network_dialog',
+ 'electrum_gui.qt.password_dialog',
+ 'electrum_gui.qt.qrcodewidget',
+ 'electrum_gui.qt.receiving_widget',
+ 'electrum_gui.qt.seed_dialog',
+ 'electrum_gui.qt.transaction dialog',
+ 'electrum_gui.qt.util',
+ 'electrum_gui.qt.version_getter',
+ 'electrum_gui.stdio',
+ 'electrum_plugins.aliases',
'electrum_plugins.exchange_rate',
'electrum_plugins.labels',
'electrum_plugins.pointofsale',