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
16 import lib.gui_qt as gui_qt
18 import electrum.gui_qt as gui_qt
20 bitcoin = lambda v: v * 100000000
22 def IconButton(filename, parent=None):
23 pixmap = QPixmap(filename)
25 return QPushButton(icon, "", parent)
30 self.emit(SIGNAL('timersignal'))
33 def resize_line_edit_width(line_edit, text_input):
34 metrics = QFontMetrics(qApp.font())
35 # Create an extra character to add some space on the end
37 line_edit.setMinimumWidth(metrics.width(text_input))
41 def __init__(self, wallet):
43 self.app = QApplication(sys.argv)
44 if os.path.exists("data"):
45 QDir.setCurrent("data")
47 QDir.setCurrent(appdata_dir())
48 with open(rsrc("style.css")) as style_file:
49 self.app.setStyleSheet(style_file.read())
52 actuator = MiniActuator(self.wallet)
53 self.mini = MiniWindow(actuator, self.expand)
54 driver = MiniDriver(self.wallet, self.mini)
61 self.expert = gui_qt.ElectrumWindow(self.wallet)
62 self.expert.app = self.app
63 self.expert.connect_slots(timer)
64 self.expert.update_wallet()
72 def set_url(self, url):
73 payto, amount, label, message, signature, identity, url = \
74 self.wallet.parse_url(url, self.show_message, self.show_question)
75 self.mini.set_payment_fields(payto, amount)
77 def show_message(self, message):
78 QMessageBox.information(self.mini, _("Message"), message, _("OK"))
80 def show_question(self, message):
81 choice = QMessageBox.question(self.mini, _("Message"), message,
82 QMessageBox.Yes|QMessageBox.No,
84 return choice == QMessageBox.Yes
86 def restore_or_create(self):
87 qt_gui_object = gui_qt.ElectrumGui(self.wallet, self.app)
88 return qt_gui_object.restore_or_create()
90 class MiniWindow(QDialog):
92 def __init__(self, actuator, expand_callback):
93 super(MiniWindow, self).__init__()
95 self.actuator = actuator
97 accounts_button = IconButton(rsrc("icons", "accounts.png"))
98 accounts_button.setObjectName("accounts_button")
100 self.accounts_selector = QMenu()
101 accounts_button.setMenu(self.accounts_selector)
103 interact_button = IconButton(rsrc("icons", "interact.png"))
104 interact_button.setObjectName("interact_button")
106 app_menu = QMenu(interact_button)
107 report_action = app_menu.addAction(_("&Report Bug"))
108 about_action = app_menu.addAction(_("&About Electrum"))
109 app_menu.addSeparator()
110 quit_action = app_menu.addAction(_("&Quit"))
111 interact_button.setMenu(app_menu)
113 self.connect(report_action, SIGNAL("triggered()"),
114 self.show_report_bug)
115 self.connect(about_action, SIGNAL("triggered()"), self.show_about)
116 self.connect(quit_action, SIGNAL("triggered()"), self.close)
118 expand_button = IconButton(rsrc("icons", "expand.png"))
119 expand_button.setObjectName("expand_button")
120 self.connect(expand_button, SIGNAL("clicked()"), expand_callback)
122 self.btc_balance = None
123 self.quote_currencies = ["EUR", "USD", "GBP"]
124 self.actuator.set_configured_currency(self.set_quote_currency)
125 self.exchanger = exchange_rate.Exchanger(self)
126 # Needed because price discovery is done in a different thread
127 # which needs to be sent back to this main one to update the GUI
128 self.connect(self, SIGNAL("refresh_balance()"), self.refresh_balance)
130 self.balance_label = BalanceLabel(self.change_quote_currency)
131 self.balance_label.setObjectName("balance_label")
133 self.receive_button = QPushButton(_("&Receive"))
134 self.receive_button.setObjectName("receive_button")
135 self.receive_button.setDefault(True)
136 self.connect(self.receive_button, SIGNAL("clicked()"),
139 self.address_input = TextedLineEdit(_("Enter a Bitcoin address..."))
140 self.address_input.setObjectName("address_input")
141 self.connect(self.address_input, SIGNAL("textEdited(QString)"),
142 self.address_field_changed)
143 resize_line_edit_width(self.address_input,
144 "1BtaFUr3qVvAmwrsuDuu5zk6e4s2rxd2Gy")
146 self.address_completions = QStringListModel()
147 address_completer = QCompleter(self.address_input)
148 address_completer.setCaseSensitivity(False)
149 address_completer.setModel(self.address_completions)
150 self.address_input.setCompleter(address_completer)
152 self.valid_address = QCheckBox()
153 self.valid_address.setObjectName("valid_address")
154 self.valid_address.setEnabled(False)
155 self.valid_address.setChecked(False)
157 address_layout = QHBoxLayout()
158 address_layout.addWidget(self.address_input)
159 address_layout.addWidget(self.valid_address)
161 self.amount_input = TextedLineEdit(_("... and amount"))
162 self.amount_input.setObjectName("amount_input")
163 # This is changed according to the user's displayed balance
164 self.amount_validator = QDoubleValidator(self.amount_input)
165 self.amount_validator.setNotation(QDoubleValidator.StandardNotation)
166 self.amount_validator.setDecimals(8)
167 self.amount_input.setValidator(self.amount_validator)
169 self.connect(self.amount_input, SIGNAL("textChanged(QString)"),
170 self.amount_input_changed)
172 amount_layout = QHBoxLayout()
173 amount_layout.addWidget(self.amount_input)
174 amount_layout.addStretch()
176 send_button = QPushButton(_("&Send"))
177 send_button.setObjectName("send_button")
178 self.connect(send_button, SIGNAL("clicked()"), self.send)
180 main_layout = QGridLayout(self)
181 main_layout.addWidget(accounts_button, 0, 0)
182 main_layout.addWidget(interact_button, 1, 0)
183 main_layout.addWidget(expand_button, 2, 0)
185 main_layout.addWidget(self.balance_label, 0, 1)
186 main_layout.addWidget(self.receive_button, 0, 2)
188 main_layout.addLayout(address_layout, 1, 1, 1, -1)
190 main_layout.addLayout(amount_layout, 2, 1)
191 main_layout.addWidget(send_button, 2, 2)
193 quit_shortcut = QShortcut(QKeySequence("Ctrl+Q"), self)
194 self.connect(quit_shortcut, SIGNAL("activated()"), self.close)
195 close_shortcut = QShortcut(QKeySequence("Ctrl+W"), self)
196 self.connect(close_shortcut, SIGNAL("activated()"), self.close)
198 self.setWindowIcon(QIcon(":electrum.png"))
199 self.setWindowTitle("Electrum")
200 self.setWindowFlags(Qt.Window|Qt.MSWindowsFixedSizeDialogHint)
201 self.layout().setSizeConstraint(QLayout.SetFixedSize)
202 self.setObjectName("main_window")
205 def closeEvent(self, event):
206 super(MiniWindow, self).closeEvent(event)
209 def set_payment_fields(self, dest_address, amount):
210 self.address_input.become_active()
211 self.address_input.setText(dest_address)
212 self.address_field_changed(dest_address)
213 self.amount_input.become_active()
214 self.amount_input.setText(amount)
219 def deactivate(self):
222 def set_quote_currency(self, currency):
223 assert currency in self.quote_currencies
224 self.quote_currencies.remove(currency)
225 self.quote_currencies = [currency] + self.quote_currencies
226 self.refresh_balance()
228 def change_quote_currency(self):
229 self.quote_currencies = \
230 self.quote_currencies[1:] + self.quote_currencies[0:1]
231 self.actuator.set_config_currency(self.quote_currencies[0])
232 self.refresh_balance()
234 def refresh_balance(self):
235 if self.btc_balance is None:
236 # Price has been discovered before wallet has been loaded
237 # and server connect... so bail.
239 self.set_balances(self.btc_balance)
240 self.amount_input_changed(self.amount_input.text())
242 def set_balances(self, btc_balance):
243 self.btc_balance = btc_balance
244 quote_text = self.create_quote_text(btc_balance)
246 quote_text = "(%s)" % quote_text
247 btc_balance = "%.2f" % (btc_balance / bitcoin(1))
248 self.balance_label.set_balance_text(btc_balance, quote_text)
249 main_account_info = \
250 "Checking - %s BTC" % btc_balance
251 self.setWindowTitle("Electrum - %s" % main_account_info)
252 self.accounts_selector.clear()
253 self.accounts_selector.addAction("%s %s" % (main_account_info,
256 def amount_input_changed(self, amount_text):
258 amount = D(str(amount_text))
259 except decimal.InvalidOperation:
260 self.balance_label.show_balance()
262 quote_text = self.create_quote_text(amount * bitcoin(1))
264 self.balance_label.set_amount_text(quote_text)
265 self.balance_label.show_amount()
267 self.balance_label.show_balance()
269 def create_quote_text(self, btc_balance):
270 quote_currency = self.quote_currencies[0]
271 quote_balance = self.exchanger.exchange(btc_balance, quote_currency)
272 if quote_balance is None:
275 quote_text = "%.2f %s" % ((quote_balance / bitcoin(1)),
280 if self.actuator.send(self.address_input.text(),
281 self.amount_input.text(), self):
282 self.address_input.become_inactive()
283 self.amount_input.become_inactive()
285 def address_field_changed(self, address):
286 if self.actuator.is_valid(address):
287 self.valid_address.setChecked(True)
289 self.valid_address.setChecked(False)
291 def copy_address(self):
292 receive_popup = ReceivePopup(self.receive_button)
293 self.actuator.copy_address(receive_popup)
295 def update_completions(self, completions):
296 self.address_completions.setStringList(completions)
298 def show_about(self):
299 QMessageBox.about(self, "Electrum",
300 _("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."))
302 def show_report_bug(self):
303 QMessageBox.information(self, "Electrum - " + _("Reporting Bugs"),
304 _("Email bug reports to %s") % "genjix" + "@" + "riseup.net")
306 class BalanceLabel(QLabel):
312 def __init__(self, change_quote_currency, parent=None):
313 super(QLabel, self).__init__(_("Connecting..."), parent)
314 self.change_quote_currency = change_quote_currency
315 self.state = self.SHOW_CONNECTING
316 self.balance_text = ""
317 self.amount_text = ""
319 def mousePressEvent(self, event):
320 if self.state != self.SHOW_CONNECTING:
321 self.change_quote_currency()
323 def set_balance_text(self, btc_balance, quote_text):
324 if self.state == self.SHOW_CONNECTING:
325 self.state = self.SHOW_BALANCE
326 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)
327 if self.state == self.SHOW_BALANCE:
328 self.setText(self.balance_text)
330 def set_amount_text(self, quote_text):
331 self.amount_text = "<span style='font-size: 10pt'>%s</span>" % quote_text
332 if self.state == self.SHOW_AMOUNT:
333 self.setText(self.amount_text)
335 def show_balance(self):
336 if self.state == self.SHOW_AMOUNT:
337 self.state = self.SHOW_BALANCE
338 self.setText(self.balance_text)
340 def show_amount(self):
341 if self.state == self.SHOW_BALANCE:
342 self.state = self.SHOW_AMOUNT
343 self.setText(self.amount_text)
345 class TextedLineEdit(QLineEdit):
347 def __init__(self, inactive_text, parent=None):
348 super(QLineEdit, self).__init__(parent)
349 self.inactive_text = inactive_text
350 self.become_inactive()
352 def mousePressEvent(self, event):
353 if self.isReadOnly():
355 QLineEdit.mousePressEvent(self, event)
357 def focusOutEvent(self, event):
358 if self.text() == "":
359 self.become_inactive()
360 QLineEdit.focusOutEvent(self, event)
362 def focusInEvent(self, event):
363 if self.isReadOnly():
365 QLineEdit.focusInEvent(self, event)
367 def become_inactive(self):
368 self.setText(self.inactive_text)
369 self.setReadOnly(True)
370 self.recompute_style()
372 def become_active(self):
374 self.setReadOnly(False)
375 self.recompute_style()
377 def recompute_style(self):
378 qApp.style().unpolish(self)
379 qApp.style().polish(self)
380 # also possible but more expensive:
381 #qApp.setStyleSheet(qApp.styleSheet())
383 def ok_cancel_buttons(dialog):
384 row_layout = QHBoxLayout()
385 row_layout.addStretch(1)
386 ok_button = QPushButton(_("OK"))
387 row_layout.addWidget(ok_button)
388 ok_button.clicked.connect(dialog.accept)
389 cancel_button = QPushButton(_("Cancel"))
390 row_layout.addWidget(cancel_button)
391 cancel_button.clicked.connect(dialog.reject)
394 class PasswordDialog(QDialog):
396 def __init__(self, parent):
397 super(QDialog, self).__init__(parent)
401 self.password_input = QLineEdit()
402 self.password_input.setEchoMode(QLineEdit.Password)
404 main_layout = QVBoxLayout(self)
405 message = _('Please enter your password')
406 main_layout.addWidget(QLabel(message))
410 grid.addWidget(QLabel(_('Password')), 1, 0)
411 grid.addWidget(self.password_input, 1, 1)
412 main_layout.addLayout(grid)
414 main_layout.addLayout(ok_cancel_buttons(self))
415 self.setLayout(main_layout)
420 return unicode(self.password_input.text())
422 class ReceivePopup(QDialog):
424 def leaveEvent(self, event):
427 def setup(self, address):
428 label = QLabel(_("Copied your Bitcoin address to the clipboard!"))
429 address_display = QLineEdit(address)
430 address_display.setReadOnly(True)
431 resize_line_edit_width(address_display, address)
433 main_layout = QVBoxLayout(self)
434 main_layout.addWidget(label)
435 main_layout.addWidget(address_display)
437 self.setMouseTracking(True)
438 self.setWindowTitle("Electrum - " + _("Receive Bitcoin payment"))
439 self.setWindowFlags(Qt.Window|Qt.FramelessWindowHint|Qt.MSWindowsFixedSizeDialogHint)
440 self.layout().setSizeConstraint(QLayout.SetFixedSize)
441 #self.setFrameStyle(QFrame.WinPanel|QFrame.Raised)
442 #self.setAlignment(Qt.AlignCenter)
445 parent = self.parent()
446 top_left_pos = parent.mapToGlobal(parent.rect().bottomLeft())
447 self.move(top_left_pos)
448 center_mouse_pos = self.mapToGlobal(self.rect().center())
449 QCursor.setPos(center_mouse_pos)
454 def __init__(self, wallet):
457 def set_configured_currency(self, set_quote_currency):
458 currency = self.wallet.conversion_currency
459 # currency can be none when Electrum is used for the first
460 # time and no setting has been created yet.
461 if currency is not None:
462 set_quote_currency(currency)
464 def set_config_currency(self, conversion_currency):
465 self.wallet.conversion_currency = conversion_currency
467 def copy_address(self, receive_popup):
468 addrs = [addr for addr in self.wallet.all_addresses()
469 if not self.wallet.is_change(addr)]
470 # Select most recent addresses from gap limit
471 addrs = addrs[-self.wallet.gap_limit:]
472 copied_address = random.choice(addrs)
473 qApp.clipboard().setText(copied_address)
474 receive_popup.setup(copied_address)
475 receive_popup.popup()
477 def send(self, address, amount, parent_window):
478 dest_address = self.fetch_destination(address)
480 if dest_address is None or not self.wallet.is_valid(dest_address):
481 QMessageBox.warning(parent_window, _('Error'),
482 _('Invalid Bitcoin Address') + ':\n' + address, _('OK'))
485 convert_amount = lambda amount: \
486 int(D(unicode(amount)) * bitcoin(1))
487 amount = convert_amount(amount)
489 if self.wallet.use_encryption:
490 password_dialog = PasswordDialog(parent_window)
491 password = password_dialog.run()
499 if amount < bitcoin(1) / 10:
501 fee = bitcoin(1) / 100
504 tx = self.wallet.mktx(dest_address, amount, "", password, fee)
505 except BaseException as error:
506 QMessageBox.warning(parent_window, _('Error'), str(error), _('OK'))
509 status, message = self.wallet.sendtx(tx)
511 QMessageBox.warning(parent_window, _('Error'), message, _('OK'))
514 QMessageBox.information(parent_window, '',
515 _('Payment sent.') + '\n' + message, _('OK'))
518 def fetch_destination(self, address):
519 recipient = unicode(address).strip()
522 match1 = re.match("^(|([\w\-\.]+)@)((\w[\w\-]+\.)+[\w\-]+)$",
525 # label or alias, with address in brackets
526 match2 = re.match("(.*?)\s*\<([1-9A-HJ-NP-Za-km-z]{26,})\>",
531 self.wallet.get_alias(recipient, True,
532 self.show_message, self.question)
535 return match2.group(2)
539 def is_valid(self, address):
540 return self.wallet.is_valid(address)
542 class MiniDriver(QObject):
549 def __init__(self, wallet, window):
550 super(QObject, self).__init__()
555 self.wallet.register_callback(self.update_callback)
560 self.connect(self, SIGNAL("updatesignal()"), self.update)
561 self.update_callback()
563 # This is a hack to workaround that Qt does not like changing the
564 # window properties from this other thread before the runloop has
566 def update_callback(self):
567 self.emit(SIGNAL("updatesignal()"))
570 if not self.wallet.interface:
572 elif not self.wallet.interface.is_connected:
574 elif not self.wallet.blocks == -1:
576 elif not self.wallet.is_up_to_date:
581 if self.wallet.up_to_date:
582 self.update_balance()
583 self.update_completions()
585 def initializing(self):
586 if self.state == self.INITIALIZING:
588 self.state = self.INITIALIZING
589 self.window.deactivate()
591 def connecting(self):
592 if self.state == self.CONNECTING:
594 self.state = self.CONNECTING
595 self.window.deactivate()
597 def synchronizing(self):
598 if self.state == self.SYNCHRONIZING:
600 self.state = self.SYNCHRONIZING
601 self.window.deactivate()
604 if self.state == self.READY:
606 self.state = self.READY
607 self.window.activate()
609 def update_balance(self):
610 conf_balance, unconf_balance = self.wallet.get_balance()
611 balance = D(conf_balance + unconf_balance)
612 self.window.set_balances(balance)
614 def update_completions(self):
616 for addr, label in self.wallet.labels.items():
617 if addr in self.wallet.addressbook:
618 completions.append("%s <%s>" % (label, addr))
619 completions = completions + self.wallet.aliases.keys()
620 self.window.update_completions(completions)
622 if __name__ == "__main__":
623 app = QApplication(sys.argv)
624 with open(rsrc("style.css")) as style_file:
625 app.setStyleSheet(style_file.read())
627 sys.exit(app.exec_())