4 from PyQt4.QtCore import *
5 from PyQt4.QtGui import *
7 print "You need to have PyQT installed to run Electrum"
8 print "If you have pip installed try 'sudo pip install pyqt' if you are on Debian/Ubuntu try 'sudo apt-get install python-qt4'"
11 from decimal import Decimal as D
12 from util import appdata_dir, get_resource_path as rsrc
25 import lib.gui_qt as gui_qt
27 import electrum.gui_qt as gui_qt
29 bitcoin = lambda v: v * 100000000
31 def IconButton(filename, parent=None):
32 pixmap = QPixmap(filename)
34 return QPushButton(icon, "", parent)
39 self.emit(SIGNAL('timersignal'))
42 def resize_line_edit_width(line_edit, text_input):
43 metrics = QFontMetrics(qApp.font())
44 # Create an extra character to add some space on the end
46 line_edit.setMinimumWidth(metrics.width(text_input))
50 prefix_path = os.path.dirname(sys.argv[0])
51 local_data = os.path.join(prefix_path, "data")
52 if os.path.exists(os.path.join(local_data, "style.css")):
55 data_dir = appdata_dir()
56 QDir.setCurrent(data_dir)
60 def __init__(self, wallet):
61 qtVersion = qVersion()
62 if not(int(qtVersion[0]) >= 4 and int(qtVersion[2]) >= 7):
63 print "Sorry, Electrum requires Qt >= 4.7 to run"
64 print "Check your distributions packages or download it at http://qt.nokia.com/downloads"
68 self.app = QApplication(sys.argv)
69 # Should probably not modify the current path but instead
70 # change the behaviour of rsrc(...)
71 self.old_path = QDir.currentPath()
73 with open(rsrc("style.css")) as style_file:
74 self.app.setStyleSheet(style_file.read())
77 actuator = MiniActuator(self.wallet)
78 self.mini = MiniWindow(actuator, self.expand)
79 driver = MiniDriver(self.wallet, self.mini)
81 # Reset path back to original value now that loading the GUI
83 QDir.setCurrent(self.old_path)
90 self.expert = gui_qt.ElectrumWindow(self.wallet)
91 self.expert.app = self.app
92 self.expert.connect_slots(timer)
93 self.expert.update_wallet()
101 def set_url(self, url):
102 payto, amount, label, message, signature, identity, url = \
103 self.wallet.parse_url(url, self.show_message, self.show_question)
104 self.mini.set_payment_fields(payto, amount)
106 def show_message(self, message):
107 QMessageBox.information(self.mini, _("Message"), message, _("OK"))
109 def show_question(self, message):
110 choice = QMessageBox.question(self.mini, _("Message"), message,
111 QMessageBox.Yes|QMessageBox.No,
113 return choice == QMessageBox.Yes
115 def restore_or_create(self):
116 qt_gui_object = gui_qt.ElectrumGui(self.wallet, self.app)
117 return qt_gui_object.restore_or_create()
119 class MiniWindow(QDialog):
121 def __init__(self, actuator, expand_callback):
122 super(MiniWindow, self).__init__()
124 self.actuator = actuator
126 self.btc_balance = None
127 self.quote_currencies = ["EUR", "USD", "GBP"]
128 self.actuator.set_configured_currency(self.set_quote_currency)
129 self.exchanger = exchange_rate.Exchanger(self)
130 # Needed because price discovery is done in a different thread
131 # which needs to be sent back to this main one to update the GUI
132 self.connect(self, SIGNAL("refresh_balance()"), self.refresh_balance)
134 self.balance_label = BalanceLabel(self.change_quote_currency)
135 self.balance_label.setObjectName("balance_label")
137 self.receive_button = QPushButton(_("&Receive"))
138 self.receive_button.setObjectName("receive_button")
139 self.receive_button.setDefault(True)
140 self.receive_button.clicked.connect(self.copy_address)
142 # Bitcoin address code
143 self.address_input = QLineEdit()
144 self.address_input.setPlaceholderText(_("Enter a Bitcoin address..."))
145 self.address_input.setObjectName("address_input")
148 self.address_input.textEdited.connect(self.address_field_changed)
149 resize_line_edit_width(self.address_input,
150 "1BtaFUr3qVvAmwrsuDuu5zk6e4s2rxd2Gy")
152 self.address_completions = QStringListModel()
153 address_completer = QCompleter(self.address_input)
154 address_completer.setCaseSensitivity(False)
155 address_completer.setModel(self.address_completions)
156 self.address_input.setCompleter(address_completer)
158 address_layout = QHBoxLayout()
159 address_layout.addWidget(self.address_input)
161 self.amount_input = QLineEdit()
162 self.amount_input.setPlaceholderText(_("... and amount"))
163 self.amount_input.setObjectName("amount_input")
164 # This is changed according to the user's displayed balance
165 self.amount_validator = QDoubleValidator(self.amount_input)
166 self.amount_validator.setNotation(QDoubleValidator.StandardNotation)
167 self.amount_validator.setDecimals(8)
168 self.amount_input.setValidator(self.amount_validator)
170 # This removes the very ugly OSX highlighting, please leave this in :D
171 self.address_input.setAttribute(Qt.WA_MacShowFocusRect, 0)
172 self.amount_input.setAttribute(Qt.WA_MacShowFocusRect, 0)
173 self.amount_input.textChanged.connect(self.amount_input_changed)
175 self.send_button = QPushButton(_("&Send"))
176 self.send_button.setObjectName("send_button")
177 self.send_button.setDisabled(True);
178 self.send_button.clicked.connect(self.send)
180 main_layout = QGridLayout(self)
182 main_layout.addWidget(self.balance_label, 0, 0)
183 main_layout.addWidget(self.receive_button, 0, 1)
185 main_layout.addWidget(self.address_input, 1, 0, 1, -1)
187 main_layout.addWidget(self.amount_input, 2, 0)
188 main_layout.addWidget(self.send_button, 2, 1)
190 self.history_list = history_widget.HistoryWidget()
191 self.history_list.setObjectName("history")
192 self.history_list.hide()
193 self.history_list.setAlternatingRowColors(True)
194 main_layout.addWidget(self.history_list, 3, 0, 1, -1)
197 electrum_menu = menubar.addMenu(_("&Bitcoin"))
198 self.servers_menu = electrum_menu.addMenu(_("&Servers"))
199 self.servers_menu.addAction(_("Foo"))
200 electrum_menu.addSeparator()
201 brain_seed = electrum_menu.addAction(_("&BrainWallet Info"))
202 brain_seed.triggered.connect(self.actuator.show_seed_dialog)
203 electrum_menu.addAction(_("&Quit"))
205 view_menu = menubar.addMenu(_("&View"))
206 expert_gui = view_menu.addAction(_("&Pro Mode"))
207 expert_gui.triggered.connect(expand_callback)
208 view_menu.addMenu(_("&Themes"))
209 view_menu.addSeparator()
210 show_history = view_menu.addAction(_("Show History"))
211 show_history.setCheckable(True)
212 show_history.toggled.connect(self.show_history)
214 settings_menu = menubar.addMenu(_("&Settings"))
215 settings_menu.addAction(_("&Configure Electrum"))
217 help_menu = menubar.addMenu(_("&Help"))
218 the_website = help_menu.addAction(_("&Website"))
219 the_website.triggered.connect(self.the_website)
220 help_menu.addSeparator()
221 report_bug = help_menu.addAction(_("&Report Bug"))
222 report_bug.triggered.connect(self.show_report_bug)
223 show_about = help_menu.addAction(_("&About"))
224 show_about.triggered.connect(self.show_about)
225 main_layout.setMenuBar(menubar)
227 quit_shortcut = QShortcut(QKeySequence("Ctrl+Q"), self)
228 quit_shortcut.activated.connect(self.close)
229 close_shortcut = QShortcut(QKeySequence("Ctrl+W"), self)
230 close_shortcut.activated.connect(self.close)
232 self.setWindowIcon(QIcon(":electrum.png"))
233 self.setWindowTitle("Electrum")
234 self.setWindowFlags(Qt.Window|Qt.MSWindowsFixedSizeDialogHint)
235 self.layout().setSizeConstraint(QLayout.SetFixedSize)
236 self.setObjectName("main_window")
239 def recompute_style(self):
240 qApp.style().unpolish(self)
241 qApp.style().polish(self)
243 def closeEvent(self, event):
244 super(MiniWindow, self).closeEvent(event)
247 def set_payment_fields(self, dest_address, amount):
248 self.address_input.setText(dest_address)
249 self.address_field_changed(dest_address)
250 self.amount_input.setText(amount)
255 def deactivate(self):
258 def set_quote_currency(self, currency):
259 assert currency in self.quote_currencies
260 self.quote_currencies.remove(currency)
261 self.quote_currencies = [currency] + self.quote_currencies
262 self.refresh_balance()
264 def change_quote_currency(self):
265 self.quote_currencies = \
266 self.quote_currencies[1:] + self.quote_currencies[0:1]
267 self.actuator.set_config_currency(self.quote_currencies[0])
268 self.refresh_balance()
270 def refresh_balance(self):
271 if self.btc_balance is None:
272 # Price has been discovered before wallet has been loaded
273 # and server connect... so bail.
275 self.set_balances(self.btc_balance)
276 self.amount_input_changed(self.amount_input.text())
278 def set_balances(self, btc_balance):
279 self.btc_balance = btc_balance
280 quote_text = self.create_quote_text(btc_balance)
282 quote_text = "(%s)" % quote_text
283 btc_balance = "%.2f" % (btc_balance / bitcoin(1))
284 self.balance_label.set_balance_text(btc_balance, quote_text)
285 self.setWindowTitle("Electrum - %s BTC" % btc_balance)
287 def amount_input_changed(self, amount_text):
288 self.check_button_status()
291 amount = D(str(amount_text))
292 except decimal.InvalidOperation:
293 self.balance_label.show_balance()
295 quote_text = self.create_quote_text(amount * bitcoin(1))
297 self.balance_label.set_amount_text(quote_text)
298 self.balance_label.show_amount()
300 self.balance_label.show_balance()
302 def create_quote_text(self, btc_balance):
303 quote_currency = self.quote_currencies[0]
304 quote_balance = self.exchanger.exchange(btc_balance, quote_currency)
305 if quote_balance is None:
308 quote_text = "%.2f %s" % ((quote_balance / bitcoin(1)),
313 if self.actuator.send(self.address_input.text(),
314 self.amount_input.text(), self):
315 self.address_input.setText("")
316 self.amount_input.setText("")
318 def check_button_status(self):
319 if (self.address_input.property("isValid") == True and
320 len(self.amount_input.text()) > 0):
321 self.send_button.setDisabled(False)
323 self.send_button.setDisabled(True)
325 def address_field_changed(self, address):
326 if self.actuator.is_valid(address):
327 self.check_button_status()
328 self.address_input.setProperty("isValid", True)
329 self.recompute_style(self.address_input)
331 self.send_button.setDisabled(True)
332 self.address_input.setProperty("isValid", False)
333 self.recompute_style(self.address_input)
335 if len(address) == 0:
336 self.address_input.setProperty("isValid", None)
337 self.recompute_style(self.address_input)
339 def recompute_style(self, element):
340 self.style().unpolish(element)
341 self.style().polish(element)
343 def copy_address(self):
344 receive_popup = ReceivePopup(self.receive_button)
345 self.actuator.copy_address(receive_popup)
347 def update_completions(self, completions):
348 self.address_completions.setStringList(completions)
350 def update_history(self, tx_history):
351 for tx in tx_history[-10:]:
352 address = tx["default_label"]
353 amount = D(tx["value"]) / 10**8
354 self.history_list.append(address, amount)
357 self.actuator.acceptbit(self.quote_currencies[0])
359 def the_website(self):
360 webbrowser.open("http://electrum-desktop.com")
362 def show_about(self):
363 QMessageBox.about(self, "Electrum",
364 _("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"))
366 def show_report_bug(self):
367 QMessageBox.information(self, "Electrum - " + _("Reporting Bugs"),
368 _("Email bug reports to %s") % "genjix" + "@" + "riseup.net")
370 def show_history(self, toggle_state):
372 self.history_list.show()
374 self.history_list.hide()
376 class BalanceLabel(QLabel):
382 def __init__(self, change_quote_currency, parent=None):
383 super(QLabel, self).__init__(_("Connecting..."), parent)
384 self.change_quote_currency = change_quote_currency
385 self.state = self.SHOW_CONNECTING
386 self.balance_text = ""
387 self.amount_text = ""
389 def mousePressEvent(self, event):
390 if self.state != self.SHOW_CONNECTING:
391 self.change_quote_currency()
393 def set_balance_text(self, btc_balance, quote_text):
394 if self.state == self.SHOW_CONNECTING:
395 self.state = self.SHOW_BALANCE
396 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)
397 if self.state == self.SHOW_BALANCE:
398 self.setText(self.balance_text)
400 def set_amount_text(self, quote_text):
401 self.amount_text = "<span style='font-size: 10pt'>%s</span>" % quote_text
402 if self.state == self.SHOW_AMOUNT:
403 self.setText(self.amount_text)
405 def show_balance(self):
406 if self.state == self.SHOW_AMOUNT:
407 self.state = self.SHOW_BALANCE
408 self.setText(self.balance_text)
410 def show_amount(self):
411 if self.state == self.SHOW_BALANCE:
412 self.state = self.SHOW_AMOUNT
413 self.setText(self.amount_text)
415 def ok_cancel_buttons(dialog):
416 row_layout = QHBoxLayout()
417 row_layout.addStretch(1)
418 ok_button = QPushButton(_("OK"))
419 row_layout.addWidget(ok_button)
420 ok_button.clicked.connect(dialog.accept)
421 cancel_button = QPushButton(_("Cancel"))
422 row_layout.addWidget(cancel_button)
423 cancel_button.clicked.connect(dialog.reject)
426 class PasswordDialog(QDialog):
428 def __init__(self, parent):
429 super(QDialog, self).__init__(parent)
433 self.password_input = QLineEdit()
434 self.password_input.setEchoMode(QLineEdit.Password)
436 main_layout = QVBoxLayout(self)
437 message = _('Please enter your password')
438 main_layout.addWidget(QLabel(message))
442 grid.addWidget(QLabel(_('Password')), 1, 0)
443 grid.addWidget(self.password_input, 1, 1)
444 main_layout.addLayout(grid)
446 main_layout.addLayout(ok_cancel_buttons(self))
447 self.setLayout(main_layout)
452 return unicode(self.password_input.text())
454 class ReceivePopup(QDialog):
456 def leaveEvent(self, event):
459 def setup(self, address):
460 label = QLabel(_("Copied your Bitcoin address to the clipboard!"))
461 address_display = QLineEdit(address)
462 address_display.setReadOnly(True)
463 resize_line_edit_width(address_display, address)
465 main_layout = QVBoxLayout(self)
466 main_layout.addWidget(label)
467 main_layout.addWidget(address_display)
469 self.setMouseTracking(True)
470 self.setWindowTitle("Electrum - " + _("Receive Bitcoin payment"))
471 self.setWindowFlags(Qt.Window|Qt.FramelessWindowHint|Qt.MSWindowsFixedSizeDialogHint)
472 self.layout().setSizeConstraint(QLayout.SetFixedSize)
473 #self.setFrameStyle(QFrame.WinPanel|QFrame.Raised)
474 #self.setAlignment(Qt.AlignCenter)
477 parent = self.parent()
478 top_left_pos = parent.mapToGlobal(parent.rect().bottomLeft())
479 self.move(top_left_pos)
480 center_mouse_pos = self.mapToGlobal(self.rect().center())
481 QCursor.setPos(center_mouse_pos)
486 def __init__(self, wallet):
489 def set_configured_currency(self, set_quote_currency):
490 currency = self.wallet.conversion_currency
491 # currency can be none when Electrum is used for the first
492 # time and no setting has been created yet.
493 if currency is not None:
494 set_quote_currency(currency)
496 def set_config_currency(self, conversion_currency):
497 self.wallet.conversion_currency = conversion_currency
499 def copy_address(self, receive_popup):
500 addrs = [addr for addr in self.wallet.all_addresses()
501 if not self.wallet.is_change(addr)]
502 # Select most recent addresses from gap limit
503 addrs = addrs[-self.wallet.gap_limit:]
504 copied_address = random.choice(addrs)
505 qApp.clipboard().setText(copied_address)
506 receive_popup.setup(copied_address)
507 receive_popup.popup()
509 def send(self, address, amount, parent_window):
510 dest_address = self.fetch_destination(address)
512 if dest_address is None or not self.wallet.is_valid(dest_address):
513 QMessageBox.warning(parent_window, _('Error'),
514 _('Invalid Bitcoin Address') + ':\n' + address, _('OK'))
517 convert_amount = lambda amount: \
518 int(D(unicode(amount)) * bitcoin(1))
519 amount = convert_amount(amount)
521 if self.wallet.use_encryption:
522 password_dialog = PasswordDialog(parent_window)
523 password = password_dialog.run()
531 if amount < bitcoin(1) / 10:
533 fee = bitcoin(1) / 1000
536 tx = self.wallet.mktx(dest_address, amount, "", password, fee)
537 except BaseException as error:
538 QMessageBox.warning(parent_window, _('Error'), str(error), _('OK'))
541 status, message = self.wallet.sendtx(tx)
543 QMessageBox.warning(parent_window, _('Error'), message, _('OK'))
546 QMessageBox.information(parent_window, '',
547 _('Payment sent.') + '\n' + message, _('OK'))
550 def fetch_destination(self, address):
551 recipient = unicode(address).strip()
554 match1 = re.match("^(|([\w\-\.]+)@)((\w[\w\-]+\.)+[\w\-]+)$",
557 # label or alias, with address in brackets
558 match2 = re.match("(.*?)\s*\<([1-9A-HJ-NP-Za-km-z]{26,})\>",
563 self.wallet.get_alias(recipient, True,
564 self.show_message, self.question)
567 return match2.group(2)
571 def is_valid(self, address):
572 return self.wallet.is_valid(address)
574 def acceptbit(self, currency):
575 master_pubkey = self.wallet.master_public_key.encode("hex")
576 url = "http://acceptbit.com/mpk/%s/%s" % (master_pubkey, currency)
579 def show_seed_dialog(self):
580 gui_qt.ElectrumWindow.show_seed_dialog(self.wallet)
582 class MiniDriver(QObject):
589 def __init__(self, wallet, window):
590 super(QObject, self).__init__()
595 self.wallet.register_callback(self.update_callback)
600 self.connect(self, SIGNAL("updatesignal()"), self.update)
601 self.update_callback()
603 # This is a hack to workaround that Qt does not like changing the
604 # window properties from this other thread before the runloop has
606 def update_callback(self):
607 self.emit(SIGNAL("updatesignal()"))
610 if not self.wallet.interface:
612 elif not self.wallet.interface.is_connected:
614 elif not self.wallet.blocks == -1:
616 elif not self.wallet.is_up_to_date:
621 if self.wallet.up_to_date:
622 self.update_balance()
623 self.update_completions()
624 self.update_history()
626 def initializing(self):
627 if self.state == self.INITIALIZING:
629 self.state = self.INITIALIZING
630 self.window.deactivate()
632 def connecting(self):
633 if self.state == self.CONNECTING:
635 self.state = self.CONNECTING
636 self.window.deactivate()
638 def synchronizing(self):
639 if self.state == self.SYNCHRONIZING:
641 self.state = self.SYNCHRONIZING
642 self.window.deactivate()
645 if self.state == self.READY:
647 self.state = self.READY
648 self.window.activate()
650 def update_balance(self):
651 conf_balance, unconf_balance = self.wallet.get_balance()
652 balance = D(conf_balance + unconf_balance)
653 self.window.set_balances(balance)
655 def update_completions(self):
657 for addr, label in self.wallet.labels.items():
658 if addr in self.wallet.addressbook:
659 completions.append("%s <%s>" % (label, addr))
660 completions = completions + self.wallet.aliases.keys()
661 self.window.update_completions(completions)
663 def update_history(self):
664 tx_history = self.wallet.get_tx_history()
665 self.window.update_history(tx_history)
667 if __name__ == "__main__":
668 app = QApplication(sys.argv)
669 with open(rsrc("style.css")) as style_file:
670 app.setStyleSheet(style_file.read())
672 sys.exit(app.exec_())