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
17 import lib.gui_qt as gui_qt
19 import electrum.gui_qt as gui_qt
21 bitcoin = lambda v: v * 100000000
23 def IconButton(filename, parent=None):
24 pixmap = QPixmap(filename)
26 return QPushButton(icon, "", parent)
31 self.emit(SIGNAL('timersignal'))
34 def resize_line_edit_width(line_edit, text_input):
35 metrics = QFontMetrics(qApp.font())
36 # Create an extra character to add some space on the end
38 line_edit.setMinimumWidth(metrics.width(text_input))
42 prefix_path = os.path.dirname(sys.argv[0])
43 local_data = os.path.join(prefix_path, "data")
44 if os.path.exists(os.path.join(local_data, "style.css")):
47 data_dir = appdata_dir()
48 QDir.setCurrent(data_dir)
52 def __init__(self, wallet):
54 self.app = QApplication(sys.argv)
55 # Should probably not modify the current path but instead
56 # change the behaviour of rsrc(...)
57 self.old_path = QDir.currentPath()
59 with open(rsrc("style.css")) as style_file:
60 self.app.setStyleSheet(style_file.read())
63 actuator = MiniActuator(self.wallet)
64 self.mini = MiniWindow(actuator, self.expand)
65 driver = MiniDriver(self.wallet, self.mini)
67 # Reset path back to original value now that loading the GUI
69 QDir.setCurrent(self.old_path)
76 self.expert = gui_qt.ElectrumWindow(self.wallet)
77 self.expert.app = self.app
78 self.expert.connect_slots(timer)
79 self.expert.update_wallet()
87 def set_url(self, url):
88 payto, amount, label, message, signature, identity, url = \
89 self.wallet.parse_url(url, self.show_message, self.show_question)
90 self.mini.set_payment_fields(payto, amount)
92 def show_message(self, message):
93 QMessageBox.information(self.mini, _("Message"), message, _("OK"))
95 def show_question(self, message):
96 choice = QMessageBox.question(self.mini, _("Message"), message,
97 QMessageBox.Yes|QMessageBox.No,
99 return choice == QMessageBox.Yes
101 def restore_or_create(self):
102 qt_gui_object = gui_qt.ElectrumGui(self.wallet, self.app)
103 return qt_gui_object.restore_or_create()
105 class MiniWindow(QDialog):
107 def __init__(self, actuator, expand_callback):
108 super(MiniWindow, self).__init__()
110 self.actuator = actuator
112 accounts_button = IconButton(rsrc("icons", "accounts.png"))
113 accounts_button.setObjectName("accounts_button")
115 self.accounts_selector = QMenu()
116 accounts_button.setMenu(self.accounts_selector)
118 interact_button = IconButton(rsrc("icons", "interact.png"))
119 interact_button.setObjectName("interact_button")
121 app_menu = QMenu(interact_button)
122 acceptbit_action = app_menu.addAction(_("A&cceptBit"))
123 report_action = app_menu.addAction(_("&Report Bug"))
124 about_action = app_menu.addAction(_("&About Electrum"))
125 app_menu.addSeparator()
126 quit_action = app_menu.addAction(_("&Quit"))
127 interact_button.setMenu(app_menu)
129 self.connect(acceptbit_action, SIGNAL("triggered()"),
131 self.connect(report_action, SIGNAL("triggered()"),
132 self.show_report_bug)
133 self.connect(about_action, SIGNAL("triggered()"), self.show_about)
134 self.connect(quit_action, SIGNAL("triggered()"), self.close)
136 expand_button = IconButton(rsrc("icons", "expand.png"))
137 expand_button.setObjectName("expand_button")
138 self.connect(expand_button, SIGNAL("clicked()"), expand_callback)
140 self.btc_balance = None
141 self.quote_currencies = ["EUR", "USD", "GBP"]
142 self.actuator.set_configured_currency(self.set_quote_currency)
143 self.exchanger = exchange_rate.Exchanger(self)
144 # Needed because price discovery is done in a different thread
145 # which needs to be sent back to this main one to update the GUI
146 self.connect(self, SIGNAL("refresh_balance()"), self.refresh_balance)
148 self.balance_label = BalanceLabel(self.change_quote_currency)
149 self.balance_label.setObjectName("balance_label")
151 self.receive_button = QPushButton(_("&Receive"))
152 self.receive_button.setObjectName("receive_button")
153 self.receive_button.setDefault(True)
154 self.connect(self.receive_button, SIGNAL("clicked()"),
157 self.address_input = TextedLineEdit(_("Enter a Bitcoin address..."))
158 self.address_input.setObjectName("address_input")
159 self.connect(self.address_input, SIGNAL("textEdited(QString)"),
160 self.address_field_changed)
161 resize_line_edit_width(self.address_input,
162 "1BtaFUr3qVvAmwrsuDuu5zk6e4s2rxd2Gy")
164 self.address_completions = QStringListModel()
165 address_completer = QCompleter(self.address_input)
166 address_completer.setCaseSensitivity(False)
167 address_completer.setModel(self.address_completions)
168 self.address_input.setCompleter(address_completer)
170 self.valid_address = QCheckBox()
171 self.valid_address.setObjectName("valid_address")
172 self.valid_address.setEnabled(False)
173 self.valid_address.setChecked(False)
175 address_layout = QHBoxLayout()
176 address_layout.addWidget(self.address_input)
177 address_layout.addWidget(self.valid_address)
179 self.amount_input = TextedLineEdit(_("... and amount"))
180 self.amount_input.setObjectName("amount_input")
181 # This is changed according to the user's displayed balance
182 self.amount_validator = QDoubleValidator(self.amount_input)
183 self.amount_validator.setNotation(QDoubleValidator.StandardNotation)
184 self.amount_validator.setDecimals(8)
185 self.amount_input.setValidator(self.amount_validator)
187 self.connect(self.amount_input, SIGNAL("textChanged(QString)"),
188 self.amount_input_changed)
190 amount_layout = QHBoxLayout()
191 amount_layout.addWidget(self.amount_input)
192 amount_layout.addStretch()
194 send_button = QPushButton(_("&Send"))
195 send_button.setObjectName("send_button")
196 self.connect(send_button, SIGNAL("clicked()"), self.send)
198 main_layout = QGridLayout(self)
199 main_layout.addWidget(accounts_button, 0, 0)
200 main_layout.addWidget(interact_button, 1, 0)
201 main_layout.addWidget(expand_button, 2, 0)
203 main_layout.addWidget(self.balance_label, 0, 1)
204 main_layout.addWidget(self.receive_button, 0, 2)
206 main_layout.addLayout(address_layout, 1, 1, 1, -1)
208 main_layout.addLayout(amount_layout, 2, 1)
209 main_layout.addWidget(send_button, 2, 2)
211 quit_shortcut = QShortcut(QKeySequence("Ctrl+Q"), self)
212 self.connect(quit_shortcut, SIGNAL("activated()"), self.close)
213 close_shortcut = QShortcut(QKeySequence("Ctrl+W"), self)
214 self.connect(close_shortcut, SIGNAL("activated()"), self.close)
216 self.setWindowIcon(QIcon(":electrum.png"))
217 self.setWindowTitle("Electrum")
218 self.setWindowFlags(Qt.Window|Qt.MSWindowsFixedSizeDialogHint)
219 self.layout().setSizeConstraint(QLayout.SetFixedSize)
220 self.setObjectName("main_window")
223 def closeEvent(self, event):
224 super(MiniWindow, self).closeEvent(event)
227 def set_payment_fields(self, dest_address, amount):
228 self.address_input.become_active()
229 self.address_input.setText(dest_address)
230 self.address_field_changed(dest_address)
231 self.amount_input.become_active()
232 self.amount_input.setText(amount)
237 def deactivate(self):
240 def set_quote_currency(self, currency):
241 assert currency in self.quote_currencies
242 self.quote_currencies.remove(currency)
243 self.quote_currencies = [currency] + self.quote_currencies
244 self.refresh_balance()
246 def change_quote_currency(self):
247 self.quote_currencies = \
248 self.quote_currencies[1:] + self.quote_currencies[0:1]
249 self.actuator.set_config_currency(self.quote_currencies[0])
250 self.refresh_balance()
252 def refresh_balance(self):
253 if self.btc_balance is None:
254 # Price has been discovered before wallet has been loaded
255 # and server connect... so bail.
257 self.set_balances(self.btc_balance)
258 self.amount_input_changed(self.amount_input.text())
260 def set_balances(self, btc_balance):
261 self.btc_balance = btc_balance
262 quote_text = self.create_quote_text(btc_balance)
264 quote_text = "(%s)" % quote_text
265 btc_balance = "%.2f" % (btc_balance / bitcoin(1))
266 self.balance_label.set_balance_text(btc_balance, quote_text)
267 main_account_info = \
268 "Checking - %s BTC" % btc_balance
269 self.setWindowTitle("Electrum - %s" % main_account_info)
270 self.accounts_selector.clear()
271 self.accounts_selector.addAction("%s %s" % (main_account_info,
274 def amount_input_changed(self, amount_text):
276 amount = D(str(amount_text))
277 except decimal.InvalidOperation:
278 self.balance_label.show_balance()
280 quote_text = self.create_quote_text(amount * bitcoin(1))
282 self.balance_label.set_amount_text(quote_text)
283 self.balance_label.show_amount()
285 self.balance_label.show_balance()
287 def create_quote_text(self, btc_balance):
288 quote_currency = self.quote_currencies[0]
289 quote_balance = self.exchanger.exchange(btc_balance, quote_currency)
290 if quote_balance is None:
293 quote_text = "%.2f %s" % ((quote_balance / bitcoin(1)),
298 if self.actuator.send(self.address_input.text(),
299 self.amount_input.text(), self):
300 self.address_input.become_inactive()
301 self.amount_input.become_inactive()
303 def address_field_changed(self, address):
304 if self.actuator.is_valid(address):
305 self.valid_address.setChecked(True)
307 self.valid_address.setChecked(False)
309 def copy_address(self):
310 receive_popup = ReceivePopup(self.receive_button)
311 self.actuator.copy_address(receive_popup)
313 def update_completions(self, completions):
314 self.address_completions.setStringList(completions)
317 self.actuator.acceptbit(self.quote_currencies[0])
319 def show_about(self):
320 QMessageBox.about(self, "Electrum",
321 _("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."))
323 def show_report_bug(self):
324 QMessageBox.information(self, "Electrum - " + _("Reporting Bugs"),
325 _("Email bug reports to %s") % "genjix" + "@" + "riseup.net")
327 class BalanceLabel(QLabel):
333 def __init__(self, change_quote_currency, parent=None):
334 super(QLabel, self).__init__(_("Connecting..."), parent)
335 self.change_quote_currency = change_quote_currency
336 self.state = self.SHOW_CONNECTING
337 self.balance_text = ""
338 self.amount_text = ""
340 def mousePressEvent(self, event):
341 if self.state != self.SHOW_CONNECTING:
342 self.change_quote_currency()
344 def set_balance_text(self, btc_balance, quote_text):
345 if self.state == self.SHOW_CONNECTING:
346 self.state = self.SHOW_BALANCE
347 self.balance_text = "<span style='font-size: 16pt'>%s</span> <span style='font-size: 10pt'>BTC</span> <span style='font-size: 10pt'>%s</span>" % (btc_balance, quote_text)
348 if self.state == self.SHOW_BALANCE:
349 self.setText(self.balance_text)
351 def set_amount_text(self, quote_text):
352 self.amount_text = "<span style='font-size: 10pt'>%s</span>" % quote_text
353 if self.state == self.SHOW_AMOUNT:
354 self.setText(self.amount_text)
356 def show_balance(self):
357 if self.state == self.SHOW_AMOUNT:
358 self.state = self.SHOW_BALANCE
359 self.setText(self.balance_text)
361 def show_amount(self):
362 if self.state == self.SHOW_BALANCE:
363 self.state = self.SHOW_AMOUNT
364 self.setText(self.amount_text)
366 class TextedLineEdit(QLineEdit):
368 def __init__(self, inactive_text, parent=None):
369 super(QLineEdit, self).__init__(parent)
370 self.inactive_text = inactive_text
371 self.become_inactive()
373 def mousePressEvent(self, event):
374 if self.isReadOnly():
376 QLineEdit.mousePressEvent(self, event)
378 def focusOutEvent(self, event):
379 if self.text() == "":
380 self.become_inactive()
381 QLineEdit.focusOutEvent(self, event)
383 def focusInEvent(self, event):
384 if self.isReadOnly():
386 QLineEdit.focusInEvent(self, event)
388 def become_inactive(self):
389 self.setReadOnly(True)
390 self.recompute_style()
391 self.setText(self.inactive_text)
393 def become_active(self):
394 self.setReadOnly(False)
395 self.recompute_style()
398 def recompute_style(self):
399 qApp.style().unpolish(self)
400 qApp.style().polish(self)
401 # also possible but more expensive:
402 #qApp.setStyleSheet(qApp.styleSheet())
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 class MiniDriver(QObject):
575 def __init__(self, wallet, window):
576 super(QObject, self).__init__()
581 self.wallet.register_callback(self.update_callback)
586 self.connect(self, SIGNAL("updatesignal()"), self.update)
587 self.update_callback()
589 # This is a hack to workaround that Qt does not like changing the
590 # window properties from this other thread before the runloop has
592 def update_callback(self):
593 self.emit(SIGNAL("updatesignal()"))
596 if not self.wallet.interface:
598 elif not self.wallet.interface.is_connected:
600 elif not self.wallet.blocks == -1:
602 elif not self.wallet.is_up_to_date:
607 if self.wallet.up_to_date:
608 self.update_balance()
609 self.update_completions()
611 def initializing(self):
612 if self.state == self.INITIALIZING:
614 self.state = self.INITIALIZING
615 self.window.deactivate()
617 def connecting(self):
618 if self.state == self.CONNECTING:
620 self.state = self.CONNECTING
621 self.window.deactivate()
623 def synchronizing(self):
624 if self.state == self.SYNCHRONIZING:
626 self.state = self.SYNCHRONIZING
627 self.window.deactivate()
630 if self.state == self.READY:
632 self.state = self.READY
633 self.window.activate()
635 def update_balance(self):
636 conf_balance, unconf_balance = self.wallet.get_balance()
637 balance = D(conf_balance + unconf_balance)
638 self.window.set_balances(balance)
640 def update_completions(self):
642 for addr, label in self.wallet.labels.items():
643 if addr in self.wallet.addressbook:
644 completions.append("%s <%s>" % (label, addr))
645 completions = completions + self.wallet.aliases.keys()
646 self.window.update_completions(completions)
648 if __name__ == "__main__":
649 app = QApplication(sys.argv)
650 with open(rsrc("style.css")) as style_file:
651 app.setStyleSheet(style_file.read())
653 sys.exit(app.exec_())