1 from PyQt4.QtCore import *
2 from PyQt4.QtGui import *
3 from decimal import Decimal as D
4 from util import appdata_dir, get_resource_path as rsrc
18 import lib.gui_qt as gui_qt
20 import electrum.gui_qt as gui_qt
22 bitcoin = lambda v: v * 100000000
24 def IconButton(filename, parent=None):
25 pixmap = QPixmap(filename)
27 return QPushButton(icon, "", parent)
32 self.emit(SIGNAL('timersignal'))
35 def resize_line_edit_width(line_edit, text_input):
36 metrics = QFontMetrics(qApp.font())
37 # Create an extra character to add some space on the end
39 line_edit.setMinimumWidth(metrics.width(text_input))
43 prefix_path = os.path.dirname(sys.argv[0])
44 local_data = os.path.join(prefix_path, "data")
45 if os.path.exists(os.path.join(local_data, "style.css")):
48 data_dir = appdata_dir()
49 QDir.setCurrent(data_dir)
53 def __init__(self, wallet):
55 self.app = QApplication(sys.argv)
56 # Should probably not modify the current path but instead
57 # change the behaviour of rsrc(...)
58 self.old_path = QDir.currentPath()
60 with open(rsrc("style.css")) as style_file:
61 self.app.setStyleSheet(style_file.read())
64 actuator = MiniActuator(self.wallet)
65 self.mini = MiniWindow(actuator, self.expand)
66 driver = MiniDriver(self.wallet, self.mini)
68 # Reset path back to original value now that loading the GUI
70 QDir.setCurrent(self.old_path)
77 self.expert = gui_qt.ElectrumWindow(self.wallet)
78 self.expert.app = self.app
79 self.expert.connect_slots(timer)
80 self.expert.update_wallet()
88 def set_url(self, url):
89 payto, amount, label, message, signature, identity, url = \
90 self.wallet.parse_url(url, self.show_message, self.show_question)
91 self.mini.set_payment_fields(payto, amount)
93 def show_message(self, message):
94 QMessageBox.information(self.mini, _("Message"), message, _("OK"))
96 def show_question(self, message):
97 choice = QMessageBox.question(self.mini, _("Message"), message,
98 QMessageBox.Yes|QMessageBox.No,
100 return choice == QMessageBox.Yes
102 def restore_or_create(self):
103 qt_gui_object = gui_qt.ElectrumGui(self.wallet, self.app)
104 return qt_gui_object.restore_or_create()
106 class MiniWindow(QDialog):
108 def __init__(self, actuator, expand_callback):
109 super(MiniWindow, self).__init__()
111 self.actuator = actuator
113 self.btc_balance = None
114 self.quote_currencies = ["EUR", "USD", "GBP"]
115 self.actuator.set_configured_currency(self.set_quote_currency)
116 self.exchanger = exchange_rate.Exchanger(self)
117 # Needed because price discovery is done in a different thread
118 # which needs to be sent back to this main one to update the GUI
119 self.connect(self, SIGNAL("refresh_balance()"), self.refresh_balance)
121 self.balance_label = BalanceLabel(self.change_quote_currency)
122 self.balance_label.setObjectName("balance_label")
124 self.receive_button = QPushButton(_("&Receive"))
125 self.receive_button.setObjectName("receive_button")
126 self.receive_button.setDefault(True)
127 self.receive_button.clicked.connect(self.copy_address)
129 # Bitcoin address code
130 self.address_input = QLineEdit()
131 self.address_input.setPlaceholderText(_("Enter a Bitcoin address..."))
132 self.address_input.setObjectName("address_input")
135 self.address_input.textEdited.connect(self.address_field_changed)
136 resize_line_edit_width(self.address_input,
137 "1BtaFUr3qVvAmwrsuDuu5zk6e4s2rxd2Gy")
139 self.address_completions = QStringListModel()
140 address_completer = QCompleter(self.address_input)
141 address_completer.setCaseSensitivity(False)
142 address_completer.setModel(self.address_completions)
143 self.address_input.setCompleter(address_completer)
145 address_layout = QHBoxLayout()
146 address_layout.addWidget(self.address_input)
148 self.amount_input = QLineEdit()
149 self.amount_input.setPlaceholderText(_("... and amount"))
150 self.amount_input.setObjectName("amount_input")
151 # This is changed according to the user's displayed balance
152 self.amount_validator = QDoubleValidator(self.amount_input)
153 self.amount_validator.setNotation(QDoubleValidator.StandardNotation)
154 self.amount_validator.setDecimals(8)
155 self.amount_input.setValidator(self.amount_validator)
157 # This removes the very ugly OSX highlighting, please leave this in :D
158 self.address_input.setAttribute(Qt.WA_MacShowFocusRect, 0)
159 self.amount_input.setAttribute(Qt.WA_MacShowFocusRect, 0)
160 self.amount_input.textChanged.connect(self.amount_input_changed)
162 self.send_button = QPushButton(_("&Send"))
163 self.send_button.setObjectName("send_button")
164 self.send_button.setDisabled(True);
165 self.send_button.clicked.connect(self.send)
167 main_layout = QGridLayout(self)
169 main_layout.addWidget(self.balance_label, 0, 0)
170 main_layout.addWidget(self.receive_button, 0, 1)
172 main_layout.addWidget(self.address_input, 1, 0, 1, -1)
174 main_layout.addWidget(self.amount_input, 2, 0)
175 main_layout.addWidget(self.send_button, 2, 1)
177 self.history_list = history_widget.HistoryWidget()
178 self.history_list.setObjectName("history")
179 self.history_list.hide()
180 self.history_list.setAlternatingRowColors(True)
181 main_layout.addWidget(self.history_list, 3, 0, 1, -1)
184 electrum_menu = menubar.addMenu(_("&Bitcoin"))
185 self.servers_menu = electrum_menu.addMenu(_("&Servers"))
186 self.servers_menu.addAction(_("Foo"))
187 electrum_menu.addSeparator()
188 brain_seed = electrum_menu.addAction(_("&BrainWallet Info"))
189 brain_seed.triggered.connect(self.actuator.show_seed_dialog)
190 electrum_menu.addAction(_("&Quit"))
192 view_menu = menubar.addMenu(_("&View"))
193 expert_gui = view_menu.addAction(_("&Pro Mode"))
194 expert_gui.triggered.connect(expand_callback)
195 view_menu.addMenu(_("&Themes"))
196 view_menu.addSeparator()
197 show_history = view_menu.addAction(_("Show History"))
198 show_history.setCheckable(True)
199 show_history.toggled.connect(self.show_history)
201 settings_menu = menubar.addMenu(_("&Settings"))
202 settings_menu.addAction(_("&Configure Electrum"))
204 help_menu = menubar.addMenu(_("&Help"))
205 the_website = help_menu.addAction(_("&Website"))
206 the_website.triggered.connect(self.the_website)
207 help_menu.addSeparator()
208 report_bug = help_menu.addAction(_("&Report Bug"))
209 report_bug.triggered.connect(self.show_report_bug)
210 show_about = help_menu.addAction(_("&About"))
211 show_about.triggered.connect(self.show_about)
212 main_layout.setMenuBar(menubar)
214 quit_shortcut = QShortcut(QKeySequence("Ctrl+Q"), self)
215 quit_shortcut.activated.connect(self.close)
216 close_shortcut = QShortcut(QKeySequence("Ctrl+W"), self)
217 close_shortcut.activated.connect(self.close)
219 self.setWindowIcon(QIcon(":electrum.png"))
220 self.setWindowTitle("Electrum")
221 self.setWindowFlags(Qt.Window|Qt.MSWindowsFixedSizeDialogHint)
222 self.layout().setSizeConstraint(QLayout.SetFixedSize)
223 self.setObjectName("main_window")
226 def recompute_style(self):
227 qApp.style().unpolish(self)
228 qApp.style().polish(self)
230 def closeEvent(self, event):
231 super(MiniWindow, self).closeEvent(event)
234 def set_payment_fields(self, dest_address, amount):
235 self.address_input.setText(dest_address)
236 self.address_field_changed(dest_address)
237 self.amount_input.setText(amount)
242 def deactivate(self):
245 def set_quote_currency(self, currency):
246 assert currency in self.quote_currencies
247 self.quote_currencies.remove(currency)
248 self.quote_currencies = [currency] + self.quote_currencies
249 self.refresh_balance()
251 def change_quote_currency(self):
252 self.quote_currencies = \
253 self.quote_currencies[1:] + self.quote_currencies[0:1]
254 self.actuator.set_config_currency(self.quote_currencies[0])
255 self.refresh_balance()
257 def refresh_balance(self):
258 if self.btc_balance is None:
259 # Price has been discovered before wallet has been loaded
260 # and server connect... so bail.
262 self.set_balances(self.btc_balance)
263 self.amount_input_changed(self.amount_input.text())
265 def set_balances(self, btc_balance):
266 self.btc_balance = btc_balance
267 quote_text = self.create_quote_text(btc_balance)
269 quote_text = "(%s)" % quote_text
270 btc_balance = "%.2f" % (btc_balance / bitcoin(1))
271 self.balance_label.set_balance_text(btc_balance, quote_text)
272 self.setWindowTitle("Electrum - %s BTC" % btc_balance)
274 def amount_input_changed(self, amount_text):
275 self.check_button_status()
278 amount = D(str(amount_text))
279 except decimal.InvalidOperation:
280 self.balance_label.show_balance()
282 quote_text = self.create_quote_text(amount * bitcoin(1))
284 self.balance_label.set_amount_text(quote_text)
285 self.balance_label.show_amount()
287 self.balance_label.show_balance()
289 def create_quote_text(self, btc_balance):
290 quote_currency = self.quote_currencies[0]
291 quote_balance = self.exchanger.exchange(btc_balance, quote_currency)
292 if quote_balance is None:
295 quote_text = "%.2f %s" % ((quote_balance / bitcoin(1)),
300 if self.actuator.send(self.address_input.text(),
301 self.amount_input.text(), self):
302 self.address_input.setText("")
303 self.amount_input.setText("")
305 def check_button_status(self):
306 if (self.address_input.property("isValid") == True and
307 len(self.amount_input.text()) > 0):
308 self.send_button.setDisabled(False)
310 self.send_button.setDisabled(True)
312 def address_field_changed(self, address):
313 if self.actuator.is_valid(address):
314 self.check_button_status()
315 self.address_input.setProperty("isValid", True)
316 self.recompute_style(self.address_input)
318 self.send_button.setDisabled(True)
319 self.address_input.setProperty("isValid", False)
320 self.recompute_style(self.address_input)
322 if len(address) == 0:
323 self.address_input.setProperty("isValid", None)
324 self.recompute_style(self.address_input)
326 def recompute_style(self, element):
327 self.style().unpolish(element)
328 self.style().polish(element)
330 def copy_address(self):
331 receive_popup = ReceivePopup(self.receive_button)
332 self.actuator.copy_address(receive_popup)
334 def update_completions(self, completions):
335 self.address_completions.setStringList(completions)
337 def update_history(self, tx_history):
338 for tx in tx_history[-10:]:
339 address = tx["default_label"]
340 amount = D(tx["value"]) / 10**8
341 self.history_list.append(address, amount)
344 self.actuator.acceptbit(self.quote_currencies[0])
346 def the_website(self):
347 webbrowser.open("http://electrum-desktop.com")
349 def show_about(self):
350 QMessageBox.about(self, "Electrum",
351 _("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"))
353 def show_report_bug(self):
354 QMessageBox.information(self, "Electrum - " + _("Reporting Bugs"),
355 _("Email bug reports to %s") % "genjix" + "@" + "riseup.net")
357 def show_history(self, toggle_state):
359 self.history_list.show()
361 self.history_list.hide()
363 class BalanceLabel(QLabel):
369 def __init__(self, change_quote_currency, parent=None):
370 super(QLabel, self).__init__(_("Connecting..."), parent)
371 self.change_quote_currency = change_quote_currency
372 self.state = self.SHOW_CONNECTING
373 self.balance_text = ""
374 self.amount_text = ""
376 def mousePressEvent(self, event):
377 if self.state != self.SHOW_CONNECTING:
378 self.change_quote_currency()
380 def set_balance_text(self, btc_balance, quote_text):
381 if self.state == self.SHOW_CONNECTING:
382 self.state = self.SHOW_BALANCE
383 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)
384 if self.state == self.SHOW_BALANCE:
385 self.setText(self.balance_text)
387 def set_amount_text(self, quote_text):
388 self.amount_text = "<span style='font-size: 10pt'>%s</span>" % quote_text
389 if self.state == self.SHOW_AMOUNT:
390 self.setText(self.amount_text)
392 def show_balance(self):
393 if self.state == self.SHOW_AMOUNT:
394 self.state = self.SHOW_BALANCE
395 self.setText(self.balance_text)
397 def show_amount(self):
398 if self.state == self.SHOW_BALANCE:
399 self.state = self.SHOW_AMOUNT
400 self.setText(self.amount_text)
402 def ok_cancel_buttons(dialog):
403 row_layout = QHBoxLayout()
404 row_layout.addStretch(1)
405 ok_button = QPushButton(_("OK"))
406 row_layout.addWidget(ok_button)
407 ok_button.clicked.connect(dialog.accept)
408 cancel_button = QPushButton(_("Cancel"))
409 row_layout.addWidget(cancel_button)
410 cancel_button.clicked.connect(dialog.reject)
413 class PasswordDialog(QDialog):
415 def __init__(self, parent):
416 super(QDialog, self).__init__(parent)
420 self.password_input = QLineEdit()
421 self.password_input.setEchoMode(QLineEdit.Password)
423 main_layout = QVBoxLayout(self)
424 message = _('Please enter your password')
425 main_layout.addWidget(QLabel(message))
429 grid.addWidget(QLabel(_('Password')), 1, 0)
430 grid.addWidget(self.password_input, 1, 1)
431 main_layout.addLayout(grid)
433 main_layout.addLayout(ok_cancel_buttons(self))
434 self.setLayout(main_layout)
439 return unicode(self.password_input.text())
441 class ReceivePopup(QDialog):
443 def leaveEvent(self, event):
446 def setup(self, address):
447 label = QLabel(_("Copied your Bitcoin address to the clipboard!"))
448 address_display = QLineEdit(address)
449 address_display.setReadOnly(True)
450 resize_line_edit_width(address_display, address)
452 main_layout = QVBoxLayout(self)
453 main_layout.addWidget(label)
454 main_layout.addWidget(address_display)
456 self.setMouseTracking(True)
457 self.setWindowTitle("Electrum - " + _("Receive Bitcoin payment"))
458 self.setWindowFlags(Qt.Window|Qt.FramelessWindowHint|Qt.MSWindowsFixedSizeDialogHint)
459 self.layout().setSizeConstraint(QLayout.SetFixedSize)
460 #self.setFrameStyle(QFrame.WinPanel|QFrame.Raised)
461 #self.setAlignment(Qt.AlignCenter)
464 parent = self.parent()
465 top_left_pos = parent.mapToGlobal(parent.rect().bottomLeft())
466 self.move(top_left_pos)
467 center_mouse_pos = self.mapToGlobal(self.rect().center())
468 QCursor.setPos(center_mouse_pos)
473 def __init__(self, wallet):
476 def set_configured_currency(self, set_quote_currency):
477 currency = self.wallet.conversion_currency
478 # currency can be none when Electrum is used for the first
479 # time and no setting has been created yet.
480 if currency is not None:
481 set_quote_currency(currency)
483 def set_config_currency(self, conversion_currency):
484 self.wallet.conversion_currency = conversion_currency
486 def copy_address(self, receive_popup):
487 addrs = [addr for addr in self.wallet.all_addresses()
488 if not self.wallet.is_change(addr)]
489 # Select most recent addresses from gap limit
490 addrs = addrs[-self.wallet.gap_limit:]
491 copied_address = random.choice(addrs)
492 qApp.clipboard().setText(copied_address)
493 receive_popup.setup(copied_address)
494 receive_popup.popup()
496 def send(self, address, amount, parent_window):
497 dest_address = self.fetch_destination(address)
499 if dest_address is None or not self.wallet.is_valid(dest_address):
500 QMessageBox.warning(parent_window, _('Error'),
501 _('Invalid Bitcoin Address') + ':\n' + address, _('OK'))
504 convert_amount = lambda amount: \
505 int(D(unicode(amount)) * bitcoin(1))
506 amount = convert_amount(amount)
508 if self.wallet.use_encryption:
509 password_dialog = PasswordDialog(parent_window)
510 password = password_dialog.run()
518 if amount < bitcoin(1) / 10:
520 fee = bitcoin(1) / 1000
523 tx = self.wallet.mktx(dest_address, amount, "", password, fee)
524 except BaseException as error:
525 QMessageBox.warning(parent_window, _('Error'), str(error), _('OK'))
528 status, message = self.wallet.sendtx(tx)
530 QMessageBox.warning(parent_window, _('Error'), message, _('OK'))
533 QMessageBox.information(parent_window, '',
534 _('Payment sent.') + '\n' + message, _('OK'))
537 def fetch_destination(self, address):
538 recipient = unicode(address).strip()
541 match1 = re.match("^(|([\w\-\.]+)@)((\w[\w\-]+\.)+[\w\-]+)$",
544 # label or alias, with address in brackets
545 match2 = re.match("(.*?)\s*\<([1-9A-HJ-NP-Za-km-z]{26,})\>",
550 self.wallet.get_alias(recipient, True,
551 self.show_message, self.question)
554 return match2.group(2)
558 def is_valid(self, address):
559 return self.wallet.is_valid(address)
561 def acceptbit(self, currency):
562 master_pubkey = self.wallet.master_public_key.encode("hex")
563 url = "http://acceptbit.com/mpk/%s/%s" % (master_pubkey, currency)
566 def show_seed_dialog(self):
567 gui_qt.ElectrumWindow.show_seed_dialog(self.wallet)
569 class MiniDriver(QObject):
576 def __init__(self, wallet, window):
577 super(QObject, self).__init__()
582 self.wallet.register_callback(self.update_callback)
587 self.connect(self, SIGNAL("updatesignal()"), self.update)
588 self.update_callback()
590 # This is a hack to workaround that Qt does not like changing the
591 # window properties from this other thread before the runloop has
593 def update_callback(self):
594 self.emit(SIGNAL("updatesignal()"))
597 if not self.wallet.interface:
599 elif not self.wallet.interface.is_connected:
601 elif not self.wallet.blocks == -1:
603 elif not self.wallet.is_up_to_date:
608 if self.wallet.up_to_date:
609 self.update_balance()
610 self.update_completions()
611 self.update_history()
613 def initializing(self):
614 if self.state == self.INITIALIZING:
616 self.state = self.INITIALIZING
617 self.window.deactivate()
619 def connecting(self):
620 if self.state == self.CONNECTING:
622 self.state = self.CONNECTING
623 self.window.deactivate()
625 def synchronizing(self):
626 if self.state == self.SYNCHRONIZING:
628 self.state = self.SYNCHRONIZING
629 self.window.deactivate()
632 if self.state == self.READY:
634 self.state = self.READY
635 self.window.activate()
637 def update_balance(self):
638 conf_balance, unconf_balance = self.wallet.get_balance()
639 balance = D(conf_balance + unconf_balance)
640 self.window.set_balances(balance)
642 def update_completions(self):
644 for addr, label in self.wallet.labels.items():
645 if addr in self.wallet.addressbook:
646 completions.append("%s <%s>" % (label, addr))
647 completions = completions + self.wallet.aliases.keys()
648 self.window.update_completions(completions)
650 def update_history(self):
651 tx_history = self.wallet.get_tx_history()
652 self.window.update_history(tx_history)
654 if __name__ == "__main__":
655 app = QApplication(sys.argv)
656 with open(rsrc("style.css")) as style_file:
657 app.setStyleSheet(style_file.read())
659 sys.exit(app.exec_())