3 from PyQt4.QtCore import *
4 from PyQt4.QtGui import *
6 from decimal import Decimal as D
7 from util import appdata_dir, get_resource_path as rsrc
20 import lib.gui_qt as gui_qt
22 import electrum.gui_qt as gui_qt
24 bitcoin = lambda v: v * 100000000
26 def IconButton(filename, parent=None):
27 pixmap = QPixmap(filename)
29 return QPushButton(icon, "", parent)
34 self.emit(SIGNAL('timersignal'))
37 def resize_line_edit_width(line_edit, text_input):
38 metrics = QFontMetrics(qApp.font())
39 # Create an extra character to add some space on the end
41 line_edit.setMinimumWidth(metrics.width(text_input))
45 prefix_path = os.path.dirname(sys.argv[0])
46 local_data = os.path.join(prefix_path, "data")
47 if os.path.exists(os.path.join(local_data, "style.css")):
50 data_dir = appdata_dir()
51 QDir.setCurrent(data_dir)
55 def __init__(self, wallet):
57 self.app = QApplication(sys.argv)
58 # Should probably not modify the current path but instead
59 # change the behaviour of rsrc(...)
60 self.old_path = QDir.currentPath()
62 with open(rsrc("style.css")) as style_file:
63 self.app.setStyleSheet(style_file.read())
66 actuator = MiniActuator(self.wallet)
67 self.mini = MiniWindow(actuator, self.expand)
68 driver = MiniDriver(self.wallet, self.mini)
70 # Reset path back to original value now that loading the GUI
72 QDir.setCurrent(self.old_path)
79 self.expert = gui_qt.ElectrumWindow(self.wallet)
80 self.expert.app = self.app
81 self.expert.connect_slots(timer)
82 self.expert.update_wallet()
90 def set_url(self, url):
91 payto, amount, label, message, signature, identity, url = \
92 self.wallet.parse_url(url, self.show_message, self.show_question)
93 self.mini.set_payment_fields(payto, amount)
95 def show_message(self, message):
96 QMessageBox.information(self.mini, _("Message"), message, _("OK"))
98 def show_question(self, message):
99 choice = QMessageBox.question(self.mini, _("Message"), message,
100 QMessageBox.Yes|QMessageBox.No,
102 return choice == QMessageBox.Yes
104 def restore_or_create(self):
105 qt_gui_object = gui_qt.ElectrumGui(self.wallet, self.app)
106 return qt_gui_object.restore_or_create()
108 class MiniWindow(QDialog):
110 def __init__(self, actuator, expand_callback):
111 super(MiniWindow, self).__init__()
113 self.actuator = actuator
115 self.btc_balance = None
116 self.quote_currencies = ["EUR", "USD", "GBP"]
117 self.actuator.set_configured_currency(self.set_quote_currency)
118 self.exchanger = exchange_rate.Exchanger(self)
119 # Needed because price discovery is done in a different thread
120 # which needs to be sent back to this main one to update the GUI
121 self.connect(self, SIGNAL("refresh_balance()"), self.refresh_balance)
123 self.balance_label = BalanceLabel(self.change_quote_currency)
124 self.balance_label.setObjectName("balance_label")
126 self.receive_button = QPushButton(_("&Receive"))
127 self.receive_button.setObjectName("receive_button")
128 self.receive_button.setDefault(True)
129 self.receive_button.clicked.connect(self.copy_address)
131 # Bitcoin address code
132 self.address_input = QLineEdit()
133 self.address_input.setPlaceholderText(_("Enter a Bitcoin address..."))
134 self.address_input.setObjectName("address_input")
137 self.address_input.textEdited.connect(self.address_field_changed)
138 resize_line_edit_width(self.address_input,
139 "1BtaFUr3qVvAmwrsuDuu5zk6e4s2rxd2Gy")
141 self.address_completions = QStringListModel()
142 address_completer = QCompleter(self.address_input)
143 address_completer.setCaseSensitivity(False)
144 address_completer.setModel(self.address_completions)
145 self.address_input.setCompleter(address_completer)
147 address_layout = QHBoxLayout()
148 address_layout.addWidget(self.address_input)
150 self.amount_input = QLineEdit()
151 self.amount_input.setPlaceholderText(_("... and amount"))
152 self.amount_input.setObjectName("amount_input")
153 # This is changed according to the user's displayed balance
154 self.amount_validator = QDoubleValidator(self.amount_input)
155 self.amount_validator.setNotation(QDoubleValidator.StandardNotation)
156 self.amount_validator.setDecimals(8)
157 self.amount_input.setValidator(self.amount_validator)
159 # This removes the very ugly OSX highlighting, please leave this in :D
160 self.address_input.setAttribute(Qt.WA_MacShowFocusRect, 0)
161 self.amount_input.setAttribute(Qt.WA_MacShowFocusRect, 0)
162 self.amount_input.textChanged.connect(self.amount_input_changed)
164 self.send_button = QPushButton(_("&Send"))
165 self.send_button.setObjectName("send_button")
166 self.send_button.setDisabled(True);
167 self.send_button.clicked.connect(self.send)
169 main_layout = QGridLayout(self)
171 main_layout.addWidget(self.balance_label, 0, 0)
172 main_layout.addWidget(self.receive_button, 0, 1)
174 main_layout.addWidget(self.address_input, 1, 0, 1, -1)
176 main_layout.addWidget(self.amount_input, 2, 0)
177 main_layout.addWidget(self.send_button, 2, 1)
179 self.history_list = history_widget.HistoryWidget()
180 self.history_list.setObjectName("history")
181 self.history_list.hide()
182 self.history_list.setAlternatingRowColors(True)
183 main_layout.addWidget(self.history_list, 3, 0, 1, -1)
186 electrum_menu = menubar.addMenu(_("&Bitcoin"))
187 self.servers_menu = electrum_menu.addMenu(_("&Servers"))
188 self.servers_menu.addAction(_("Foo"))
189 electrum_menu.addSeparator()
190 brain_seed = electrum_menu.addAction(_("&BrainWallet Info"))
191 brain_seed.triggered.connect(self.actuator.show_seed_dialog)
192 electrum_menu.addAction(_("&Quit"))
194 view_menu = menubar.addMenu(_("&View"))
195 expert_gui = view_menu.addAction(_("&Pro Mode"))
196 expert_gui.triggered.connect(expand_callback)
197 view_menu.addMenu(_("&Themes"))
198 view_menu.addSeparator()
199 show_history = view_menu.addAction(_("Show History"))
200 show_history.setCheckable(True)
201 show_history.toggled.connect(self.show_history)
203 settings_menu = menubar.addMenu(_("&Settings"))
204 settings_menu.addAction(_("&Configure Electrum"))
206 help_menu = menubar.addMenu(_("&Help"))
207 the_website = help_menu.addAction(_("&Website"))
208 the_website.triggered.connect(self.the_website)
209 help_menu.addSeparator()
210 report_bug = help_menu.addAction(_("&Report Bug"))
211 report_bug.triggered.connect(self.show_report_bug)
212 show_about = help_menu.addAction(_("&About"))
213 show_about.triggered.connect(self.show_about)
214 main_layout.setMenuBar(menubar)
216 quit_shortcut = QShortcut(QKeySequence("Ctrl+Q"), self)
217 quit_shortcut.activated.connect(self.close)
218 close_shortcut = QShortcut(QKeySequence("Ctrl+W"), self)
219 close_shortcut.activated.connect(self.close)
221 self.setWindowIcon(QIcon(":electrum.png"))
222 self.setWindowTitle("Electrum")
223 self.setWindowFlags(Qt.Window|Qt.MSWindowsFixedSizeDialogHint)
224 self.layout().setSizeConstraint(QLayout.SetFixedSize)
225 self.setObjectName("main_window")
228 def recompute_style(self):
229 qApp.style().unpolish(self)
230 qApp.style().polish(self)
232 def closeEvent(self, event):
233 super(MiniWindow, self).closeEvent(event)
236 def set_payment_fields(self, dest_address, amount):
237 self.address_input.setText(dest_address)
238 self.address_field_changed(dest_address)
239 self.amount_input.setText(amount)
244 def deactivate(self):
247 def set_quote_currency(self, currency):
248 assert currency in self.quote_currencies
249 self.quote_currencies.remove(currency)
250 self.quote_currencies = [currency] + self.quote_currencies
251 self.refresh_balance()
253 def change_quote_currency(self):
254 self.quote_currencies = \
255 self.quote_currencies[1:] + self.quote_currencies[0:1]
256 self.actuator.set_config_currency(self.quote_currencies[0])
257 self.refresh_balance()
259 def refresh_balance(self):
260 if self.btc_balance is None:
261 # Price has been discovered before wallet has been loaded
262 # and server connect... so bail.
264 self.set_balances(self.btc_balance)
265 self.amount_input_changed(self.amount_input.text())
267 def set_balances(self, btc_balance):
268 self.btc_balance = btc_balance
269 quote_text = self.create_quote_text(btc_balance)
271 quote_text = "(%s)" % quote_text
272 btc_balance = "%.2f" % (btc_balance / bitcoin(1))
273 self.balance_label.set_balance_text(btc_balance, quote_text)
274 self.setWindowTitle("Electrum - %s BTC" % btc_balance)
276 def amount_input_changed(self, amount_text):
277 self.check_button_status()
280 amount = D(str(amount_text))
281 except decimal.InvalidOperation:
282 self.balance_label.show_balance()
284 quote_text = self.create_quote_text(amount * bitcoin(1))
286 self.balance_label.set_amount_text(quote_text)
287 self.balance_label.show_amount()
289 self.balance_label.show_balance()
291 def create_quote_text(self, btc_balance):
292 quote_currency = self.quote_currencies[0]
293 quote_balance = self.exchanger.exchange(btc_balance, quote_currency)
294 if quote_balance is None:
297 quote_text = "%.2f %s" % ((quote_balance / bitcoin(1)),
302 if self.actuator.send(self.address_input.text(),
303 self.amount_input.text(), self):
304 self.address_input.setText("")
305 self.amount_input.setText("")
307 def check_button_status(self):
308 if (self.address_input.property("isValid") == True and
309 len(self.amount_input.text()) > 0):
310 self.send_button.setDisabled(False)
312 self.send_button.setDisabled(True)
314 def address_field_changed(self, address):
315 if self.actuator.is_valid(address):
316 self.check_button_status()
317 self.address_input.setProperty("isValid", True)
318 self.recompute_style(self.address_input)
320 self.send_button.setDisabled(True)
321 self.address_input.setProperty("isValid", False)
322 self.recompute_style(self.address_input)
324 if len(address) == 0:
325 self.address_input.setProperty("isValid", None)
326 self.recompute_style(self.address_input)
328 def recompute_style(self, element):
329 self.style().unpolish(element)
330 self.style().polish(element)
332 def copy_address(self):
333 receive_popup = ReceivePopup(self.receive_button)
334 self.actuator.copy_address(receive_popup)
336 def update_completions(self, completions):
337 self.address_completions.setStringList(completions)
339 def update_history(self, tx_history):
340 for tx in tx_history[-10:]:
341 address = tx["default_label"]
342 amount = D(tx["value"]) / 10**8
343 self.history_list.append(address, amount)
346 self.actuator.acceptbit(self.quote_currencies[0])
348 def the_website(self):
349 webbrowser.open("http://electrum-desktop.com")
351 def show_about(self):
352 QMessageBox.about(self, "Electrum",
353 _("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"))
355 def show_report_bug(self):
356 QMessageBox.information(self, "Electrum - " + _("Reporting Bugs"),
357 _("Email bug reports to %s") % "genjix" + "@" + "riseup.net")
359 def show_history(self, toggle_state):
361 self.history_list.show()
363 self.history_list.hide()
365 class BalanceLabel(QLabel):
371 def __init__(self, change_quote_currency, parent=None):
372 super(QLabel, self).__init__(_("Connecting..."), parent)
373 self.change_quote_currency = change_quote_currency
374 self.state = self.SHOW_CONNECTING
375 self.balance_text = ""
376 self.amount_text = ""
378 def mousePressEvent(self, event):
379 if self.state != self.SHOW_CONNECTING:
380 self.change_quote_currency()
382 def set_balance_text(self, btc_balance, quote_text):
383 if self.state == self.SHOW_CONNECTING:
384 self.state = self.SHOW_BALANCE
385 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)
386 if self.state == self.SHOW_BALANCE:
387 self.setText(self.balance_text)
389 def set_amount_text(self, quote_text):
390 self.amount_text = "<span style='font-size: 10pt'>%s</span>" % quote_text
391 if self.state == self.SHOW_AMOUNT:
392 self.setText(self.amount_text)
394 def show_balance(self):
395 if self.state == self.SHOW_AMOUNT:
396 self.state = self.SHOW_BALANCE
397 self.setText(self.balance_text)
399 def show_amount(self):
400 if self.state == self.SHOW_BALANCE:
401 self.state = self.SHOW_AMOUNT
402 self.setText(self.amount_text)
404 def ok_cancel_buttons(dialog):
405 row_layout = QHBoxLayout()
406 row_layout.addStretch(1)
407 ok_button = QPushButton(_("OK"))
408 row_layout.addWidget(ok_button)
409 ok_button.clicked.connect(dialog.accept)
410 cancel_button = QPushButton(_("Cancel"))
411 row_layout.addWidget(cancel_button)
412 cancel_button.clicked.connect(dialog.reject)
415 class PasswordDialog(QDialog):
417 def __init__(self, parent):
418 super(QDialog, self).__init__(parent)
422 self.password_input = QLineEdit()
423 self.password_input.setEchoMode(QLineEdit.Password)
425 main_layout = QVBoxLayout(self)
426 message = _('Please enter your password')
427 main_layout.addWidget(QLabel(message))
431 grid.addWidget(QLabel(_('Password')), 1, 0)
432 grid.addWidget(self.password_input, 1, 1)
433 main_layout.addLayout(grid)
435 main_layout.addLayout(ok_cancel_buttons(self))
436 self.setLayout(main_layout)
441 return unicode(self.password_input.text())
443 class ReceivePopup(QDialog):
445 def leaveEvent(self, event):
448 def setup(self, address):
449 label = QLabel(_("Copied your Bitcoin address to the clipboard!"))
450 address_display = QLineEdit(address)
451 address_display.setReadOnly(True)
452 resize_line_edit_width(address_display, address)
454 main_layout = QVBoxLayout(self)
455 main_layout.addWidget(label)
456 main_layout.addWidget(address_display)
458 self.setMouseTracking(True)
459 self.setWindowTitle("Electrum - " + _("Receive Bitcoin payment"))
460 self.setWindowFlags(Qt.Window|Qt.FramelessWindowHint|Qt.MSWindowsFixedSizeDialogHint)
461 self.layout().setSizeConstraint(QLayout.SetFixedSize)
462 #self.setFrameStyle(QFrame.WinPanel|QFrame.Raised)
463 #self.setAlignment(Qt.AlignCenter)
466 parent = self.parent()
467 top_left_pos = parent.mapToGlobal(parent.rect().bottomLeft())
468 self.move(top_left_pos)
469 center_mouse_pos = self.mapToGlobal(self.rect().center())
470 QCursor.setPos(center_mouse_pos)
475 def __init__(self, wallet):
478 def set_configured_currency(self, set_quote_currency):
479 currency = self.wallet.conversion_currency
480 # currency can be none when Electrum is used for the first
481 # time and no setting has been created yet.
482 if currency is not None:
483 set_quote_currency(currency)
485 def set_config_currency(self, conversion_currency):
486 self.wallet.conversion_currency = conversion_currency
488 def copy_address(self, receive_popup):
489 addrs = [addr for addr in self.wallet.all_addresses()
490 if not self.wallet.is_change(addr)]
491 # Select most recent addresses from gap limit
492 addrs = addrs[-self.wallet.gap_limit:]
493 copied_address = random.choice(addrs)
494 qApp.clipboard().setText(copied_address)
495 receive_popup.setup(copied_address)
496 receive_popup.popup()
498 def send(self, address, amount, parent_window):
499 dest_address = self.fetch_destination(address)
501 if dest_address is None or not self.wallet.is_valid(dest_address):
502 QMessageBox.warning(parent_window, _('Error'),
503 _('Invalid Bitcoin Address') + ':\n' + address, _('OK'))
506 convert_amount = lambda amount: \
507 int(D(unicode(amount)) * bitcoin(1))
508 amount = convert_amount(amount)
510 if self.wallet.use_encryption:
511 password_dialog = PasswordDialog(parent_window)
512 password = password_dialog.run()
520 if amount < bitcoin(1) / 10:
522 fee = bitcoin(1) / 1000
525 tx = self.wallet.mktx(dest_address, amount, "", password, fee)
526 except BaseException as error:
527 QMessageBox.warning(parent_window, _('Error'), str(error), _('OK'))
530 status, message = self.wallet.sendtx(tx)
532 QMessageBox.warning(parent_window, _('Error'), message, _('OK'))
535 QMessageBox.information(parent_window, '',
536 _('Payment sent.') + '\n' + message, _('OK'))
539 def fetch_destination(self, address):
540 recipient = unicode(address).strip()
543 match1 = re.match("^(|([\w\-\.]+)@)((\w[\w\-]+\.)+[\w\-]+)$",
546 # label or alias, with address in brackets
547 match2 = re.match("(.*?)\s*\<([1-9A-HJ-NP-Za-km-z]{26,})\>",
552 self.wallet.get_alias(recipient, True,
553 self.show_message, self.question)
556 return match2.group(2)
560 def is_valid(self, address):
561 return self.wallet.is_valid(address)
563 def acceptbit(self, currency):
564 master_pubkey = self.wallet.master_public_key.encode("hex")
565 url = "http://acceptbit.com/mpk/%s/%s" % (master_pubkey, currency)
568 def show_seed_dialog(self):
569 gui_qt.ElectrumWindow.show_seed_dialog(self.wallet)
571 class MiniDriver(QObject):
578 def __init__(self, wallet, window):
579 super(QObject, self).__init__()
584 self.wallet.register_callback(self.update_callback)
589 self.connect(self, SIGNAL("updatesignal()"), self.update)
590 self.update_callback()
592 # This is a hack to workaround that Qt does not like changing the
593 # window properties from this other thread before the runloop has
595 def update_callback(self):
596 self.emit(SIGNAL("updatesignal()"))
599 if not self.wallet.interface:
601 elif not self.wallet.interface.is_connected:
603 elif not self.wallet.blocks == -1:
605 elif not self.wallet.is_up_to_date:
610 if self.wallet.up_to_date:
611 self.update_balance()
612 self.update_completions()
613 self.update_history()
615 def initializing(self):
616 if self.state == self.INITIALIZING:
618 self.state = self.INITIALIZING
619 self.window.deactivate()
621 def connecting(self):
622 if self.state == self.CONNECTING:
624 self.state = self.CONNECTING
625 self.window.deactivate()
627 def synchronizing(self):
628 if self.state == self.SYNCHRONIZING:
630 self.state = self.SYNCHRONIZING
631 self.window.deactivate()
634 if self.state == self.READY:
636 self.state = self.READY
637 self.window.activate()
639 def update_balance(self):
640 conf_balance, unconf_balance = self.wallet.get_balance()
641 balance = D(conf_balance + unconf_balance)
642 self.window.set_balances(balance)
644 def update_completions(self):
646 for addr, label in self.wallet.labels.items():
647 if addr in self.wallet.addressbook:
648 completions.append("%s <%s>" % (label, addr))
649 completions = completions + self.wallet.aliases.keys()
650 self.window.update_completions(completions)
652 def update_history(self):
653 tx_history = self.wallet.get_tx_history()
654 self.window.update_history(tx_history)
656 if __name__ == "__main__":
657 app = QApplication(sys.argv)
658 with open(rsrc("style.css")) as style_file:
659 app.setStyleSheet(style_file.read())
661 sys.exit(app.exec_())