3 from PyQt4.QtCore import *
4 from PyQt4.QtGui import *
6 from decimal import Decimal as D
7 from util import get_resource_path as rsrc
21 import lib.gui_qt as gui_qt
23 import electrum.gui_qt as gui_qt
25 bitcoin = lambda v: v * 100000000
27 def IconButton(filename, parent=None):
28 pixmap = QPixmap(filename)
30 return QPushButton(icon, "", parent)
35 self.emit(SIGNAL('timersignal'))
38 def resize_line_edit_width(line_edit, text_input):
39 metrics = QFontMetrics(qApp.font())
40 # Create an extra character to add some space on the end
42 line_edit.setMinimumWidth(metrics.width(text_input))
46 def __init__(self, wallet):
48 self.app = QApplication(sys.argv)
51 actuator = MiniActuator(self.wallet)
52 # Should probably not modify the current path but instead
53 # change the behaviour of rsrc(...)
54 old_path = QDir.currentPath()
57 self.mini = MiniWindow(actuator, self.expand)
58 driver = MiniDriver(self.wallet, self.mini)
60 # Reset path back to original value now that loading the GUI
62 QDir.setCurrent(old_path)
69 self.expert = gui_qt.ElectrumWindow(self.wallet)
70 self.expert.app = self.app
71 self.expert.connect_slots(timer)
72 self.expert.update_wallet()
80 def set_url(self, url):
81 payto, amount, label, message, signature, identity, url = \
82 self.wallet.parse_url(url, self.show_message, self.show_question)
83 self.mini.set_payment_fields(payto, amount)
85 def show_message(self, message):
86 QMessageBox.information(self.mini, _("Message"), message, _("OK"))
88 def show_question(self, message):
89 choice = QMessageBox.question(self.mini, _("Message"), message,
90 QMessageBox.Yes|QMessageBox.No,
92 return choice == QMessageBox.Yes
94 def restore_or_create(self):
95 qt_gui_object = gui_qt.ElectrumGui(self.wallet, self.app)
96 return qt_gui_object.restore_or_create()
98 class MiniWindow(QDialog):
100 def __init__(self, actuator, expand_callback):
101 super(MiniWindow, self).__init__()
103 self.actuator = actuator
105 self.btc_balance = None
106 self.quote_currencies = ["EUR", "USD", "GBP"]
107 self.actuator.set_configured_currency(self.set_quote_currency)
108 self.exchanger = exchange_rate.Exchanger(self)
109 # Needed because price discovery is done in a different thread
110 # which needs to be sent back to this main one to update the GUI
111 self.connect(self, SIGNAL("refresh_balance()"), self.refresh_balance)
113 self.balance_label = BalanceLabel(self.change_quote_currency)
114 self.balance_label.setObjectName("balance_label")
116 self.receive_button = QPushButton(_("&Receive"))
117 self.receive_button.setObjectName("receive_button")
118 self.receive_button.setDefault(True)
119 self.receive_button.clicked.connect(self.copy_address)
121 # Bitcoin address code
122 self.address_input = QLineEdit()
123 self.address_input.setPlaceholderText(_("Enter a Bitcoin address..."))
124 self.address_input.setObjectName("address_input")
127 self.address_input.textEdited.connect(self.address_field_changed)
128 resize_line_edit_width(self.address_input,
129 "1BtaFUr3qVvAmwrsuDuu5zk6e4s2rxd2Gy")
131 self.address_completions = QStringListModel()
132 address_completer = QCompleter(self.address_input)
133 address_completer.setCaseSensitivity(False)
134 address_completer.setModel(self.address_completions)
135 self.address_input.setCompleter(address_completer)
137 address_layout = QHBoxLayout()
138 address_layout.addWidget(self.address_input)
140 self.amount_input = QLineEdit()
141 self.amount_input.setPlaceholderText(_("... and amount"))
142 self.amount_input.setObjectName("amount_input")
143 # This is changed according to the user's displayed balance
144 self.amount_validator = QDoubleValidator(self.amount_input)
145 self.amount_validator.setNotation(QDoubleValidator.StandardNotation)
146 self.amount_validator.setDecimals(8)
147 self.amount_input.setValidator(self.amount_validator)
149 # This removes the very ugly OSX highlighting, please leave this in :D
150 self.address_input.setAttribute(Qt.WA_MacShowFocusRect, 0)
151 self.amount_input.setAttribute(Qt.WA_MacShowFocusRect, 0)
152 self.amount_input.textChanged.connect(self.amount_input_changed)
154 self.send_button = QPushButton(_("&Send"))
155 self.send_button.setObjectName("send_button")
156 self.send_button.setDisabled(True);
157 self.send_button.clicked.connect(self.send)
159 main_layout = QGridLayout(self)
161 main_layout.addWidget(self.balance_label, 0, 0)
162 main_layout.addWidget(self.receive_button, 0, 1)
164 main_layout.addWidget(self.address_input, 1, 0, 1, -1)
166 main_layout.addWidget(self.amount_input, 2, 0)
167 main_layout.addWidget(self.send_button, 2, 1)
169 self.history_list = history_widget.HistoryWidget()
170 self.history_list.setObjectName("history")
171 self.history_list.hide()
172 self.history_list.setAlternatingRowColors(True)
173 main_layout.addWidget(self.history_list, 3, 0, 1, -1)
176 electrum_menu = menubar.addMenu(_("&Bitcoin"))
177 self.servers_menu = electrum_menu.addMenu(_("&Servers"))
178 self.servers_menu.addAction(_("Foo"))
179 electrum_menu.addSeparator()
180 brain_seed = electrum_menu.addAction(_("&BrainWallet Info"))
181 brain_seed.triggered.connect(self.actuator.show_seed_dialog)
183 electrum_menu.addAction(_("&Quit"))
185 view_menu = menubar.addMenu(_("&View"))
186 expert_gui = view_menu.addAction(_("&Pro Mode"))
187 expert_gui.triggered.connect(expand_callback)
188 view_menu.addMenu(_("&Themes"))
189 view_menu.addSeparator()
190 show_history = view_menu.addAction(_("Show History"))
191 show_history.setCheckable(True)
192 show_history.toggled.connect(self.show_history)
194 help_menu = menubar.addMenu(_("&Help"))
195 the_website = help_menu.addAction(_("&Website"))
196 the_website.triggered.connect(self.the_website)
197 help_menu.addSeparator()
198 report_bug = help_menu.addAction(_("&Report Bug"))
199 report_bug.triggered.connect(self.show_report_bug)
200 show_about = help_menu.addAction(_("&About"))
201 show_about.triggered.connect(self.show_about)
202 main_layout.setMenuBar(menubar)
204 quit_shortcut = QShortcut(QKeySequence("Ctrl+Q"), self)
205 quit_shortcut.activated.connect(self.close)
206 close_shortcut = QShortcut(QKeySequence("Ctrl+W"), self)
207 close_shortcut.activated.connect(self.close)
209 self.setWindowIcon(QIcon(":electrum.png"))
210 self.setWindowTitle("Electrum")
211 self.setWindowFlags(Qt.Window|Qt.MSWindowsFixedSizeDialogHint)
212 self.layout().setSizeConstraint(QLayout.SetFixedSize)
213 self.setObjectName("main_window")
216 def recompute_style(self):
217 qApp.style().unpolish(self)
218 qApp.style().polish(self)
220 def closeEvent(self, event):
221 super(MiniWindow, self).closeEvent(event)
224 def set_payment_fields(self, dest_address, amount):
225 self.address_input.setText(dest_address)
226 self.address_field_changed(dest_address)
227 self.amount_input.setText(amount)
232 def deactivate(self):
235 def set_quote_currency(self, currency):
236 assert currency in self.quote_currencies
237 self.quote_currencies.remove(currency)
238 self.quote_currencies = [currency] + self.quote_currencies
239 self.refresh_balance()
241 def change_quote_currency(self):
242 self.quote_currencies = \
243 self.quote_currencies[1:] + self.quote_currencies[0:1]
244 self.actuator.set_config_currency(self.quote_currencies[0])
245 self.refresh_balance()
247 def refresh_balance(self):
248 if self.btc_balance is None:
249 # Price has been discovered before wallet has been loaded
250 # and server connect... so bail.
252 self.set_balances(self.btc_balance)
253 self.amount_input_changed(self.amount_input.text())
255 def set_balances(self, btc_balance):
256 self.btc_balance = btc_balance
257 quote_text = self.create_quote_text(btc_balance)
259 quote_text = "(%s)" % quote_text
260 btc_balance = "%.2f" % (btc_balance / bitcoin(1))
261 self.balance_label.set_balance_text(btc_balance, quote_text)
262 self.setWindowTitle("Electrum - %s BTC" % btc_balance)
264 def amount_input_changed(self, amount_text):
265 self.check_button_status()
268 amount = D(str(amount_text))
269 except decimal.InvalidOperation:
270 self.balance_label.show_balance()
272 quote_text = self.create_quote_text(amount * bitcoin(1))
274 self.balance_label.set_amount_text(quote_text)
275 self.balance_label.show_amount()
277 self.balance_label.show_balance()
279 def create_quote_text(self, btc_balance):
280 quote_currency = self.quote_currencies[0]
281 quote_balance = self.exchanger.exchange(btc_balance, quote_currency)
282 if quote_balance is None:
285 quote_text = "%.2f %s" % ((quote_balance / bitcoin(1)),
290 if self.actuator.send(self.address_input.text(),
291 self.amount_input.text(), self):
292 self.address_input.setText("")
293 self.amount_input.setText("")
295 def check_button_status(self):
296 if (self.address_input.property("isValid") == True and
297 len(self.amount_input.text()) > 0):
298 self.send_button.setDisabled(False)
300 self.send_button.setDisabled(True)
302 def address_field_changed(self, address):
303 if self.actuator.is_valid(address):
304 self.check_button_status()
305 self.address_input.setProperty("isValid", True)
306 self.recompute_style(self.address_input)
308 self.send_button.setDisabled(True)
309 self.address_input.setProperty("isValid", False)
310 self.recompute_style(self.address_input)
312 if len(address) == 0:
313 self.address_input.setProperty("isValid", None)
314 self.recompute_style(self.address_input)
316 def recompute_style(self, element):
317 self.style().unpolish(element)
318 self.style().polish(element)
320 def copy_address(self):
321 receive_popup = ReceivePopup(self.receive_button)
322 self.actuator.copy_address(receive_popup)
324 def update_completions(self, completions):
325 self.address_completions.setStringList(completions)
327 def update_history(self, tx_history):
328 for tx in tx_history[-10:]:
329 address = tx["default_label"]
330 amount = D(tx["value"]) / 10**8
331 self.history_list.append(address, amount)
334 self.actuator.acceptbit(self.quote_currencies[0])
336 def the_website(self):
337 webbrowser.open("http://electrum-desktop.com")
339 def show_about(self):
340 QMessageBox.about(self, "Electrum",
341 _("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 conjuction with high-performance servers that handle the most complicated parts of the Bitcoin system.\n\nSend donations to 1JwTMv4GWaPdf931N6LNPJeZBfZgZJ3zX1"))
343 def show_report_bug(self):
344 QMessageBox.information(self, "Electrum - " + _("Reporting Bugs"),
345 _("Email bug reports to %s") % "genjix" + "@" + "riseup.net")
347 def show_history(self, toggle_state):
349 self.history_list.show()
351 self.history_list.hide()
353 class BalanceLabel(QLabel):
359 def __init__(self, change_quote_currency, parent=None):
360 super(QLabel, self).__init__(_("Connecting..."), parent)
361 self.change_quote_currency = change_quote_currency
362 self.state = self.SHOW_CONNECTING
363 self.balance_text = ""
364 self.amount_text = ""
366 def mousePressEvent(self, event):
367 if self.state != self.SHOW_CONNECTING:
368 self.change_quote_currency()
370 def set_balance_text(self, btc_balance, quote_text):
371 if self.state == self.SHOW_CONNECTING:
372 self.state = self.SHOW_BALANCE
373 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)
374 if self.state == self.SHOW_BALANCE:
375 self.setText(self.balance_text)
377 def set_amount_text(self, quote_text):
378 self.amount_text = "<span style='font-size: 10pt'>%s</span>" % quote_text
379 if self.state == self.SHOW_AMOUNT:
380 self.setText(self.amount_text)
382 def show_balance(self):
383 if self.state == self.SHOW_AMOUNT:
384 self.state = self.SHOW_BALANCE
385 self.setText(self.balance_text)
387 def show_amount(self):
388 if self.state == self.SHOW_BALANCE:
389 self.state = self.SHOW_AMOUNT
390 self.setText(self.amount_text)
392 def ok_cancel_buttons(dialog):
393 row_layout = QHBoxLayout()
394 row_layout.addStretch(1)
395 ok_button = QPushButton(_("OK"))
396 row_layout.addWidget(ok_button)
397 ok_button.clicked.connect(dialog.accept)
398 cancel_button = QPushButton(_("Cancel"))
399 row_layout.addWidget(cancel_button)
400 cancel_button.clicked.connect(dialog.reject)
403 class PasswordDialog(QDialog):
405 def __init__(self, parent):
406 super(QDialog, self).__init__(parent)
410 self.password_input = QLineEdit()
411 self.password_input.setEchoMode(QLineEdit.Password)
413 main_layout = QVBoxLayout(self)
414 message = _('Please enter your password')
415 main_layout.addWidget(QLabel(message))
419 grid.addWidget(QLabel(_('Password')), 1, 0)
420 grid.addWidget(self.password_input, 1, 1)
421 main_layout.addLayout(grid)
423 main_layout.addLayout(ok_cancel_buttons(self))
424 self.setLayout(main_layout)
429 return unicode(self.password_input.text())
431 class ReceivePopup(QDialog):
433 def leaveEvent(self, event):
436 def setup(self, address):
437 label = QLabel(_("Copied your Bitcoin address to the clipboard!"))
438 address_display = QLineEdit(address)
439 address_display.setReadOnly(True)
440 resize_line_edit_width(address_display, address)
442 main_layout = QVBoxLayout(self)
443 main_layout.addWidget(label)
444 main_layout.addWidget(address_display)
446 self.setMouseTracking(True)
447 self.setWindowTitle("Electrum - " + _("Receive Bitcoin payment"))
448 self.setWindowFlags(Qt.Window|Qt.FramelessWindowHint|Qt.MSWindowsFixedSizeDialogHint)
449 self.layout().setSizeConstraint(QLayout.SetFixedSize)
450 #self.setFrameStyle(QFrame.WinPanel|QFrame.Raised)
451 #self.setAlignment(Qt.AlignCenter)
454 parent = self.parent()
455 top_left_pos = parent.mapToGlobal(parent.rect().bottomLeft())
456 self.move(top_left_pos)
457 center_mouse_pos = self.mapToGlobal(self.rect().center())
458 QCursor.setPos(center_mouse_pos)
463 def __init__(self, wallet):
466 self.theme_name = self.wallet.theme
467 self.themes = util.load_theme_paths()
469 def load_theme(self):
471 theme_prefix, theme_path = self.themes[self.theme_name]
473 util.print_error("Theme not found! ", self.theme_name)
475 theme_css = os.path.join(theme_path, "style.css")
476 QDir.setCurrent(theme_prefix)
477 with open(rsrc(theme_css)) as style_file:
478 qApp.setStyleSheet(style_file.read())
480 def theme_names(self):
481 return self.themes.keys()
482 def selected_theme(self):
483 return self.theme_name
485 def set_configured_currency(self, set_quote_currency):
486 currency = self.wallet.conversion_currency
487 # currency can be none when Electrum is used for the first
488 # time and no setting has been created yet.
489 if currency is not None:
490 set_quote_currency(currency)
492 def set_config_currency(self, conversion_currency):
493 self.wallet.conversion_currency = conversion_currency
495 def copy_address(self, receive_popup):
496 addrs = [addr for addr in self.wallet.all_addresses()
497 if not self.wallet.is_change(addr)]
498 # Select most recent addresses from gap limit
499 addrs = addrs[-self.wallet.gap_limit:]
500 copied_address = random.choice(addrs)
501 qApp.clipboard().setText(copied_address)
502 receive_popup.setup(copied_address)
503 receive_popup.popup()
505 def send(self, address, amount, parent_window):
506 dest_address = self.fetch_destination(address)
508 if dest_address is None or not self.wallet.is_valid(dest_address):
509 QMessageBox.warning(parent_window, _('Error'),
510 _('Invalid Bitcoin Address') + ':\n' + address, _('OK'))
513 convert_amount = lambda amount: \
514 int(D(unicode(amount)) * bitcoin(1))
515 amount = convert_amount(amount)
517 if self.wallet.use_encryption:
518 password_dialog = PasswordDialog(parent_window)
519 password = password_dialog.run()
527 if amount < bitcoin(1) / 10:
529 fee = bitcoin(1) / 1000
532 tx = self.wallet.mktx(dest_address, amount, "", password, fee)
533 except BaseException as error:
534 QMessageBox.warning(parent_window, _('Error'), str(error), _('OK'))
537 status, message = self.wallet.sendtx(tx)
539 QMessageBox.warning(parent_window, _('Error'), message, _('OK'))
542 QMessageBox.information(parent_window, '',
543 _('Payment sent.') + '\n' + message, _('OK'))
546 def fetch_destination(self, address):
547 recipient = unicode(address).strip()
550 match1 = re.match("^(|([\w\-\.]+)@)((\w[\w\-]+\.)+[\w\-]+)$",
553 # label or alias, with address in brackets
554 match2 = re.match("(.*?)\s*\<([1-9A-HJ-NP-Za-km-z]{26,})\>",
559 self.wallet.get_alias(recipient, True,
560 self.show_message, self.question)
563 return match2.group(2)
567 def is_valid(self, address):
568 return self.wallet.is_valid(address)
570 def acceptbit(self, currency):
571 master_pubkey = self.wallet.master_public_key.encode("hex")
572 url = "http://acceptbit.com/mpk/%s/%s" % (master_pubkey, currency)
575 def show_seed_dialog(self):
576 gui_qt.ElectrumWindow.show_seed_dialog(self.wallet)
578 class MiniDriver(QObject):
585 def __init__(self, wallet, window):
586 super(QObject, self).__init__()
591 self.wallet.register_callback(self.update_callback)
596 self.connect(self, SIGNAL("updatesignal()"), self.update)
597 self.update_callback()
599 # This is a hack to workaround that Qt does not like changing the
600 # window properties from this other thread before the runloop has
602 def update_callback(self):
603 self.emit(SIGNAL("updatesignal()"))
606 if not self.wallet.interface:
608 elif not self.wallet.interface.is_connected:
610 elif not self.wallet.blocks == -1:
612 elif not self.wallet.is_up_to_date:
617 if self.wallet.up_to_date:
618 self.update_balance()
619 self.update_completions()
620 self.update_history()
622 def initializing(self):
623 if self.state == self.INITIALIZING:
625 self.state = self.INITIALIZING
626 self.window.deactivate()
628 def connecting(self):
629 if self.state == self.CONNECTING:
631 self.state = self.CONNECTING
632 self.window.deactivate()
634 def synchronizing(self):
635 if self.state == self.SYNCHRONIZING:
637 self.state = self.SYNCHRONIZING
638 self.window.deactivate()
641 if self.state == self.READY:
643 self.state = self.READY
644 self.window.activate()
646 def update_balance(self):
647 conf_balance, unconf_balance = self.wallet.get_balance()
648 balance = D(conf_balance + unconf_balance)
649 self.window.set_balances(balance)
651 def update_completions(self):
653 for addr, label in self.wallet.labels.items():
654 if addr in self.wallet.addressbook:
655 completions.append("%s <%s>" % (label, addr))
656 completions = completions + self.wallet.aliases.keys()
657 self.window.update_completions(completions)
659 def update_history(self):
660 tx_history = self.wallet.get_tx_history()
661 self.window.update_history(tx_history)
663 if __name__ == "__main__":
664 app = QApplication(sys.argv)
665 with open(rsrc("style.css")) as style_file:
666 app.setStyleSheet(style_file.read())
668 sys.exit(app.exec_())