3 from PyQt4.QtCore import *
4 from PyQt4.QtGui import *
6 from decimal import Decimal as D
7 from interface import DEFAULT_SERVERS
8 from util import get_resource_path as rsrc
22 import lib.gui_qt as gui_qt
24 import electrum.gui_qt as gui_qt
26 bitcoin = lambda v: v * 100000000
28 def IconButton(filename, parent=None):
29 pixmap = QPixmap(filename)
31 return QPushButton(icon, "", parent)
36 self.emit(SIGNAL('timersignal'))
39 def resize_line_edit_width(line_edit, text_input):
40 metrics = QFontMetrics(qApp.font())
41 # Create an extra character to add some space on the end
43 line_edit.setMinimumWidth(metrics.width(text_input))
47 def __init__(self, wallet):
49 self.app = QApplication(sys.argv)
52 actuator = MiniActuator(self.wallet)
53 # Should probably not modify the current path but instead
54 # change the behaviour of rsrc(...)
55 old_path = QDir.currentPath()
58 self.mini = MiniWindow(actuator, self.expand)
59 driver = MiniDriver(self.wallet, self.mini)
61 # Reset path back to original value now that loading the GUI
63 QDir.setCurrent(old_path)
70 self.expert = gui_qt.ElectrumWindow(self.wallet)
71 self.expert.app = self.app
72 self.expert.connect_slots(timer)
73 self.expert.update_wallet()
78 """Hide the lite mode window and show pro-mode."""
82 def set_url(self, url):
83 payto, amount, label, message, signature, identity, url = \
84 self.wallet.parse_url(url, self.show_message, self.show_question)
85 self.mini.set_payment_fields(payto, amount)
87 def show_message(self, message):
88 QMessageBox.information(self.mini, _("Message"), message, _("OK"))
90 def show_question(self, message):
91 choice = QMessageBox.question(self.mini, _("Message"), message,
92 QMessageBox.Yes|QMessageBox.No,
94 return choice == QMessageBox.Yes
96 def restore_or_create(self):
97 qt_gui_object = gui_qt.ElectrumGui(self.wallet, self.app)
98 return qt_gui_object.restore_or_create()
100 class MiniWindow(QDialog):
102 def __init__(self, actuator, expand_callback):
103 super(MiniWindow, self).__init__()
105 self.actuator = actuator
107 self.btc_balance = None
108 self.quote_currencies = ["EUR", "USD", "GBP"]
109 self.actuator.set_configured_currency(self.set_quote_currency)
110 self.exchanger = exchange_rate.Exchanger(self)
111 # Needed because price discovery is done in a different thread
112 # which needs to be sent back to this main one to update the GUI
113 self.connect(self, SIGNAL("refresh_balance()"), self.refresh_balance)
115 self.balance_label = BalanceLabel(self.change_quote_currency)
116 self.balance_label.setObjectName("balance_label")
118 self.receive_button = QPushButton(_("&Receive"))
119 self.receive_button.setObjectName("receive_button")
120 self.receive_button.setDefault(True)
121 self.receive_button.clicked.connect(self.copy_address)
123 # Bitcoin address code
124 self.address_input = QLineEdit()
125 self.address_input.setPlaceholderText(_("Enter a Bitcoin address..."))
126 self.address_input.setObjectName("address_input")
129 self.address_input.textEdited.connect(self.address_field_changed)
130 resize_line_edit_width(self.address_input,
131 "1BtaFUr3qVvAmwrsuDuu5zk6e4s2rxd2Gy")
133 self.address_completions = QStringListModel()
134 address_completer = QCompleter(self.address_input)
135 address_completer.setCaseSensitivity(False)
136 address_completer.setModel(self.address_completions)
137 self.address_input.setCompleter(address_completer)
139 address_layout = QHBoxLayout()
140 address_layout.addWidget(self.address_input)
142 self.amount_input = QLineEdit()
143 self.amount_input.setPlaceholderText(_("... and amount"))
144 self.amount_input.setObjectName("amount_input")
145 # This is changed according to the user's displayed balance
146 self.amount_validator = QDoubleValidator(self.amount_input)
147 self.amount_validator.setNotation(QDoubleValidator.StandardNotation)
148 self.amount_validator.setDecimals(8)
149 self.amount_input.setValidator(self.amount_validator)
151 # This removes the very ugly OSX highlighting, please leave this in :D
152 self.address_input.setAttribute(Qt.WA_MacShowFocusRect, 0)
153 self.amount_input.setAttribute(Qt.WA_MacShowFocusRect, 0)
154 self.amount_input.textChanged.connect(self.amount_input_changed)
156 self.send_button = QPushButton(_("&Send"))
157 self.send_button.setObjectName("send_button")
158 self.send_button.setDisabled(True);
159 self.send_button.clicked.connect(self.send)
161 main_layout = QGridLayout(self)
163 main_layout.addWidget(self.balance_label, 0, 0)
164 main_layout.addWidget(self.receive_button, 0, 1)
166 main_layout.addWidget(self.address_input, 1, 0, 1, -1)
168 main_layout.addWidget(self.amount_input, 2, 0)
169 main_layout.addWidget(self.send_button, 2, 1)
171 self.history_list = history_widget.HistoryWidget()
172 self.history_list.setObjectName("history")
173 self.history_list.hide()
174 self.history_list.setAlternatingRowColors(True)
175 main_layout.addWidget(self.history_list, 3, 0, 1, -1)
178 electrum_menu = menubar.addMenu(_("&Bitcoin"))
179 servers_menu = electrum_menu.addMenu(_("&Servers"))
180 servers_group = QActionGroup(self)
181 self.actuator.set_servers_gui_stuff(servers_menu, servers_group)
182 self.actuator.populate_servers_menu()
183 electrum_menu.addSeparator()
184 brain_seed = electrum_menu.addAction(_("&BrainWallet Info"))
185 brain_seed.triggered.connect(self.actuator.show_seed_dialog)
186 quit_option = electrum_menu.addAction(_("&Quit"))
187 quit_option.triggered.connect(self.close)
189 view_menu = menubar.addMenu(_("&View"))
190 expert_gui = view_menu.addAction(_("&Pro Mode"))
191 expert_gui.triggered.connect(expand_callback)
192 themes_menu = view_menu.addMenu(_("&Themes"))
193 selected_theme = self.actuator.selected_theme()
194 theme_group = QActionGroup(self)
195 for theme_name in self.actuator.theme_names():
196 theme_action = themes_menu.addAction(theme_name)
197 theme_action.setCheckable(True)
198 if selected_theme == theme_name:
199 theme_action.setChecked(True)
200 class SelectThemeFunctor:
201 def __init__(self, theme_name, toggle_theme):
202 self.theme_name = theme_name
203 self.toggle_theme = toggle_theme
204 def __call__(self, checked):
206 self.toggle_theme(self.theme_name)
207 delegate = SelectThemeFunctor(theme_name, self.toggle_theme)
208 theme_action.toggled.connect(delegate)
209 theme_group.addAction(theme_action)
210 view_menu.addSeparator()
211 show_history = view_menu.addAction(_("Show History"))
212 show_history.setCheckable(True)
213 show_history.toggled.connect(self.show_history)
215 help_menu = menubar.addMenu(_("&Help"))
216 the_website = help_menu.addAction(_("&Website"))
217 the_website.triggered.connect(self.the_website)
218 help_menu.addSeparator()
219 report_bug = help_menu.addAction(_("&Report Bug"))
220 report_bug.triggered.connect(self.show_report_bug)
221 show_about = help_menu.addAction(_("&About"))
222 show_about.triggered.connect(self.show_about)
223 main_layout.setMenuBar(menubar)
225 quit_shortcut = QShortcut(QKeySequence("Ctrl+Q"), self)
226 quit_shortcut.activated.connect(self.close)
227 close_shortcut = QShortcut(QKeySequence("Ctrl+W"), self)
228 close_shortcut.activated.connect(self.close)
230 self.setWindowIcon(QIcon(":electrum.png"))
231 self.setWindowTitle("Electrum")
232 self.setWindowFlags(Qt.Window|Qt.MSWindowsFixedSizeDialogHint)
233 self.layout().setSizeConstraint(QLayout.SetFixedSize)
234 self.setObjectName("main_window")
237 def toggle_theme(self, theme_name):
238 old_path = QDir.currentPath()
239 self.actuator.change_theme(theme_name)
240 # Recompute style globally
241 qApp.style().unpolish(self)
242 qApp.style().polish(self)
243 QDir.setCurrent(old_path)
245 def closeEvent(self, event):
246 super(MiniWindow, self).closeEvent(event)
249 def set_payment_fields(self, dest_address, amount):
250 self.address_input.setText(dest_address)
251 self.address_field_changed(dest_address)
252 self.amount_input.setText(amount)
257 def deactivate(self):
260 def set_quote_currency(self, currency):
261 """Set and display the fiat currency country."""
262 assert currency in self.quote_currencies
263 self.quote_currencies.remove(currency)
264 self.quote_currencies.insert(0, currency)
265 self.refresh_balance()
267 def change_quote_currency(self):
268 self.quote_currencies = \
269 self.quote_currencies[1:] + self.quote_currencies[0:1]
270 self.actuator.set_config_currency(self.quote_currencies[0])
271 self.refresh_balance()
273 def refresh_balance(self):
274 if self.btc_balance is None:
275 # Price has been discovered before wallet has been loaded
276 # and server connect... so bail.
278 self.set_balances(self.btc_balance)
279 self.amount_input_changed(self.amount_input.text())
281 def set_balances(self, btc_balance):
282 """Set the bitcoin balance and update the amount label accordingly."""
283 self.btc_balance = btc_balance
284 quote_text = self.create_quote_text(btc_balance)
286 quote_text = "(%s)" % quote_text
287 btc_balance = "%.2f" % (btc_balance / bitcoin(1))
288 self.balance_label.set_balance_text(btc_balance, quote_text)
289 self.setWindowTitle("Electrum - %s BTC" % btc_balance)
291 def amount_input_changed(self, amount_text):
292 """Update the number of bitcoins displayed."""
293 self.check_button_status()
296 amount = D(str(amount_text))
297 except decimal.InvalidOperation:
298 self.balance_label.show_balance()
300 quote_text = self.create_quote_text(amount * bitcoin(1))
302 self.balance_label.set_amount_text(quote_text)
303 self.balance_label.show_amount()
305 self.balance_label.show_balance()
307 def create_quote_text(self, btc_balance):
308 """Return a string copy of the amount fiat currency the
309 user has in bitcoins."""
310 quote_currency = self.quote_currencies[0]
311 quote_balance = self.exchanger.exchange(btc_balance, quote_currency)
312 if quote_balance is None:
315 quote_text = "%.2f %s" % ((quote_balance / bitcoin(1)),
320 if self.actuator.send(self.address_input.text(),
321 self.amount_input.text(), self):
322 self.address_input.setText("")
323 self.amount_input.setText("")
325 def check_button_status(self):
326 """Check that the bitcoin address is valid and that something
327 is entered in the amount before making the send button clickable."""
328 # self.address_input.property(...) returns a qVariant, not a bool.
329 # The == is needed to properly invoke a comparison.
330 if (self.address_input.property("isValid") == True and
331 len(self.amount_input.text()) > 0):
332 self.send_button.setDisabled(False)
334 self.send_button.setDisabled(True)
336 def address_field_changed(self, address):
337 if self.actuator.is_valid(address):
338 self.check_button_status()
339 self.address_input.setProperty("isValid", True)
340 self.recompute_style(self.address_input)
342 self.send_button.setDisabled(True)
343 self.address_input.setProperty("isValid", False)
344 self.recompute_style(self.address_input)
346 if len(address) == 0:
347 self.address_input.setProperty("isValid", None)
348 self.recompute_style(self.address_input)
350 def recompute_style(self, element):
351 self.style().unpolish(element)
352 self.style().polish(element)
354 def copy_address(self):
355 receive_popup = ReceivePopup(self.receive_button)
356 self.actuator.copy_address(receive_popup)
358 def update_completions(self, completions):
359 self.address_completions.setStringList(completions)
361 def update_history(self, tx_history):
362 for tx in tx_history[-10:]:
363 address = tx["default_label"]
364 amount = D(tx["value"]) / 10**8
365 self.history_list.append(address, amount)
368 self.actuator.acceptbit(self.quote_currencies[0])
370 def the_website(self):
371 webbrowser.open("http://electrum-desktop.com")
373 def show_about(self):
374 QMessageBox.about(self, "Electrum",
375 _("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"))
377 def show_report_bug(self):
378 QMessageBox.information(self, "Electrum - " + _("Reporting Bugs"),
379 _("Email bug reports to %s") % "genjix" + "@" + "riseup.net")
381 def show_history(self, toggle_state):
383 self.history_list.show()
385 self.history_list.hide()
387 class BalanceLabel(QLabel):
393 def __init__(self, change_quote_currency, parent=None):
394 super(QLabel, self).__init__(_("Connecting..."), parent)
395 self.change_quote_currency = change_quote_currency
396 self.state = self.SHOW_CONNECTING
397 self.balance_text = ""
398 self.amount_text = ""
400 def mousePressEvent(self, event):
401 """Change the fiat currency selection if window background is clicked."""
402 if self.state != self.SHOW_CONNECTING:
403 self.change_quote_currency()
405 def set_balance_text(self, btc_balance, quote_text):
406 """Set the amount of bitcoins in the gui."""
407 if self.state == self.SHOW_CONNECTING:
408 self.state = self.SHOW_BALANCE
409 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)
410 if self.state == self.SHOW_BALANCE:
411 self.setText(self.balance_text)
413 def set_amount_text(self, quote_text):
414 self.amount_text = "<span style='font-size: 10pt'>%s</span>" % quote_text
415 if self.state == self.SHOW_AMOUNT:
416 self.setText(self.amount_text)
418 def show_balance(self):
419 if self.state == self.SHOW_AMOUNT:
420 self.state = self.SHOW_BALANCE
421 self.setText(self.balance_text)
423 def show_amount(self):
424 if self.state == self.SHOW_BALANCE:
425 self.state = self.SHOW_AMOUNT
426 self.setText(self.amount_text)
428 def ok_cancel_buttons(dialog):
429 row_layout = QHBoxLayout()
430 row_layout.addStretch(1)
431 ok_button = QPushButton(_("OK"))
432 row_layout.addWidget(ok_button)
433 ok_button.clicked.connect(dialog.accept)
434 cancel_button = QPushButton(_("Cancel"))
435 row_layout.addWidget(cancel_button)
436 cancel_button.clicked.connect(dialog.reject)
439 class PasswordDialog(QDialog):
441 def __init__(self, parent):
442 super(QDialog, self).__init__(parent)
446 self.password_input = QLineEdit()
447 self.password_input.setEchoMode(QLineEdit.Password)
449 main_layout = QVBoxLayout(self)
450 message = _('Please enter your password')
451 main_layout.addWidget(QLabel(message))
455 grid.addWidget(QLabel(_('Password')), 1, 0)
456 grid.addWidget(self.password_input, 1, 1)
457 main_layout.addLayout(grid)
459 main_layout.addLayout(ok_cancel_buttons(self))
460 self.setLayout(main_layout)
465 return unicode(self.password_input.text())
467 class ReceivePopup(QDialog):
469 def leaveEvent(self, event):
472 def setup(self, address):
473 label = QLabel(_("Copied your Bitcoin address to the clipboard!"))
474 address_display = QLineEdit(address)
475 address_display.setReadOnly(True)
476 resize_line_edit_width(address_display, address)
478 main_layout = QVBoxLayout(self)
479 main_layout.addWidget(label)
480 main_layout.addWidget(address_display)
482 self.setMouseTracking(True)
483 self.setWindowTitle("Electrum - " + _("Receive Bitcoin payment"))
484 self.setWindowFlags(Qt.Window|Qt.FramelessWindowHint|
485 Qt.MSWindowsFixedSizeDialogHint)
486 self.layout().setSizeConstraint(QLayout.SetFixedSize)
487 #self.setFrameStyle(QFrame.WinPanel|QFrame.Raised)
488 #self.setAlignment(Qt.AlignCenter)
491 parent = self.parent()
492 top_left_pos = parent.mapToGlobal(parent.rect().bottomLeft())
493 self.move(top_left_pos)
494 center_mouse_pos = self.mapToGlobal(self.rect().center())
495 QCursor.setPos(center_mouse_pos)
498 class MiniActuator(QObject):
499 """Initialize the definitions relating to themes and
500 sending/recieving bitcoins.
504 def __init__(self, wallet):
505 """Retrieve the gui theme used in previous session."""
506 super(QObject, self).__init__()
509 self.theme_name = self.wallet.theme
510 self.themes = util.load_theme_paths()
512 def load_theme(self):
513 """Load theme retrieved from wallet file."""
515 theme_prefix, theme_path = self.themes[self.theme_name]
517 util.print_error("Theme not found!", self.theme_name)
519 QDir.setCurrent(os.path.join(theme_prefix, theme_path))
520 with open(rsrc("style.css")) as style_file:
521 qApp.setStyleSheet(style_file.read())
523 def theme_names(self):
525 return sorted(self.themes.keys())
527 def selected_theme(self):
529 return self.theme_name
531 def change_theme(self, theme_name):
533 self.wallet.theme = self.theme_name = theme_name
536 def set_configured_currency(self, set_quote_currency):
537 """Set the inital fiat currency conversion country (USD/EUR/GBP) in
538 the GUI to what it was set to in the wallet."""
539 currency = self.wallet.conversion_currency
540 # currency can be none when Electrum is used for the first
541 # time and no setting has been created yet.
542 if currency is not None:
543 set_quote_currency(currency)
545 def set_config_currency(self, conversion_currency):
546 """Change the wallet fiat currency country."""
547 self.wallet.conversion_currency = conversion_currency
549 def set_servers_gui_stuff(self, servers_menu, servers_group):
550 self.servers_menu = servers_menu
551 self.servers_group = servers_group
552 self.connect(self, SIGNAL("updateservers()"), self.update_servers_list)
554 def populate_servers_menu(self):
555 interface = self.wallet.interface
556 interface.servers_loaded_callback = self.server_list_changed
557 if not interface.servers:
558 print "No servers loaded yet."
559 self.servers_list = []
560 for server_string in DEFAULT_SERVERS:
561 host, port, protocol = server_string.split(':')
562 transports = [(protocol,port)]
563 self.servers_list.append((host, transports))
565 print "Servers loaded."
566 self.servers_list = interface.servers
567 server_names = [details[0] for details in self.servers_list]
568 current_server = self.wallet.server.split(":")[0]
569 for server_name in server_names:
570 server_action = self.servers_menu.addAction(server_name)
571 server_action.setCheckable(True)
572 if server_name == current_server:
573 server_action.setChecked(True)
574 class SelectServerFunctor:
575 def __init__(self, server_name, server_selected):
576 self.server_name = server_name
577 self.server_selected = server_selected
578 def __call__(self, checked):
580 # call server_selected
581 self.server_selected(self.server_name)
582 delegate = SelectServerFunctor(server_name, self.server_selected)
583 server_action.toggled.connect(delegate)
584 self.servers_group.addAction(server_action)
586 def server_list_changed(self):
587 self.emit(SIGNAL("updateservers()"))
589 def update_servers_list(self):
590 # Clear servers_group
591 for action in self.servers_group.actions():
592 self.servers_group.removeAction(action)
593 self.populate_servers_menu()
595 def server_selected(self, server_name):
596 match = [transports for (host, transports) in self.servers_list
597 if host == server_name]
598 assert len(match) == 1
600 # Default to TCP if available else use anything
601 # TODO: protocol should be selectable.
602 tcp_port = [port for (protocol, port) in match if protocol == "t"]
603 if len(tcp_port) == 0:
604 protocol = match[0][0]
609 server_line = "%s:%s:%s" % (server_name, port, protocol)
610 # Should this have exception handling?
611 self.wallet.set_server(server_line)
613 def copy_address(self, receive_popup):
614 """Copy the wallet addresses into the client."""
615 addrs = [addr for addr in self.wallet.all_addresses()
616 if not self.wallet.is_change(addr)]
617 # Select most recent addresses from gap limit
618 addrs = addrs[-self.wallet.gap_limit:]
619 copied_address = random.choice(addrs)
620 qApp.clipboard().setText(copied_address)
621 receive_popup.setup(copied_address)
622 receive_popup.popup()
624 def send(self, address, amount, parent_window):
625 """Send bitcoins to the target address."""
626 dest_address = self.fetch_destination(address)
628 if dest_address is None or not self.wallet.is_valid(dest_address):
629 QMessageBox.warning(parent_window, _('Error'),
630 _('Invalid Bitcoin Address') + ':\n' + address, _('OK'))
633 convert_amount = lambda amount: \
634 int(D(unicode(amount)) * bitcoin(1))
635 amount = convert_amount(amount)
637 if self.wallet.use_encryption:
638 password_dialog = PasswordDialog(parent_window)
639 password = password_dialog.run()
647 if amount < bitcoin(1) / 10:
649 fee = bitcoin(1) / 1000
652 tx = self.wallet.mktx(dest_address, amount, "", password, fee)
653 except BaseException as error:
654 QMessageBox.warning(parent_window, _('Error'), str(error), _('OK'))
657 status, message = self.wallet.sendtx(tx)
659 QMessageBox.warning(parent_window, _('Error'), message, _('OK'))
662 QMessageBox.information(parent_window, '',
663 _('Payment sent.') + '\n' + message, _('OK'))
666 def fetch_destination(self, address):
667 recipient = unicode(address).strip()
670 match1 = re.match("^(|([\w\-\.]+)@)((\w[\w\-]+\.)+[\w\-]+)$",
673 # label or alias, with address in brackets
674 match2 = re.match("(.*?)\s*\<([1-9A-HJ-NP-Za-km-z]{26,})\>",
679 self.wallet.get_alias(recipient, True,
680 self.show_message, self.question)
683 return match2.group(2)
687 def is_valid(self, address):
688 """Check if bitcoin address is valid."""
689 return self.wallet.is_valid(address)
691 def acceptbit(self, currency):
692 master_pubkey = self.wallet.master_public_key.encode("hex")
693 url = "http://acceptbit.com/mpk/%s/%s" % (master_pubkey, currency)
696 def show_seed_dialog(self):
697 gui_qt.ElectrumWindow.show_seed_dialog(self.wallet)
699 class MiniDriver(QObject):
706 def __init__(self, wallet, window):
707 super(QObject, self).__init__()
712 self.wallet.register_callback(self.update_callback)
717 self.connect(self, SIGNAL("updatesignal()"), self.update)
718 self.update_callback()
720 # This is a hack to workaround that Qt does not like changing the
721 # window properties from this other thread before the runloop has
723 def update_callback(self):
724 self.emit(SIGNAL("updatesignal()"))
727 if not self.wallet.interface:
729 elif not self.wallet.interface.is_connected:
731 elif not self.wallet.blocks == -1:
733 elif not self.wallet.is_up_to_date:
738 if self.wallet.up_to_date:
739 self.update_balance()
740 self.update_completions()
741 self.update_history()
743 def initializing(self):
744 if self.state == self.INITIALIZING:
746 self.state = self.INITIALIZING
747 self.window.deactivate()
749 def connecting(self):
750 if self.state == self.CONNECTING:
752 self.state = self.CONNECTING
753 self.window.deactivate()
755 def synchronizing(self):
756 if self.state == self.SYNCHRONIZING:
758 self.state = self.SYNCHRONIZING
759 self.window.deactivate()
762 if self.state == self.READY:
764 self.state = self.READY
765 self.window.activate()
767 def update_balance(self):
768 conf_balance, unconf_balance = self.wallet.get_balance()
769 balance = D(conf_balance + unconf_balance)
770 self.window.set_balances(balance)
772 def update_completions(self):
774 for addr, label in self.wallet.labels.items():
775 if addr in self.wallet.addressbook:
776 completions.append("%s <%s>" % (label, addr))
777 completions = completions + self.wallet.aliases.keys()
778 self.window.update_completions(completions)
780 def update_history(self):
781 tx_history = self.wallet.get_tx_history()
782 self.window.update_history(tx_history)
784 if __name__ == "__main__":
785 app = QApplication(sys.argv)
786 with open(rsrc("style.css")) as style_file:
787 app.setStyleSheet(style_file.read())
789 sys.exit(app.exec_())