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 data_dir = os.environ["ELECTRUM_DATA_PATH"]
43 data_dir = appdata_dir()
44 QDir.setCurrent(data_dir)
48 def __init__(self, wallet):
50 self.app = QApplication(sys.argv)
51 # Should probably not modify the current path but instead
52 # change the behaviour of rsrc(...)
53 self.old_path = QDir.currentPath()
55 with open(rsrc("style.css")) as style_file:
56 self.app.setStyleSheet(style_file.read())
59 actuator = MiniActuator(self.wallet)
60 self.mini = MiniWindow(actuator, self.expand)
61 driver = MiniDriver(self.wallet, self.mini)
63 # Reset path back to original value now that loading the GUI
65 QDir.setCurrent(self.old_path)
72 self.expert = gui_qt.ElectrumWindow(self.wallet)
73 self.expert.app = self.app
74 self.expert.connect_slots(timer)
75 self.expert.update_wallet()
83 def set_url(self, url):
84 payto, amount, label, message, signature, identity, url = \
85 self.wallet.parse_url(url, self.show_message, self.show_question)
86 self.mini.set_payment_fields(payto, amount)
88 def show_message(self, message):
89 QMessageBox.information(self.mini, _("Message"), message, _("OK"))
91 def show_question(self, message):
92 choice = QMessageBox.question(self.mini, _("Message"), message,
93 QMessageBox.Yes|QMessageBox.No,
95 return choice == QMessageBox.Yes
97 def restore_or_create(self):
98 qt_gui_object = gui_qt.ElectrumGui(self.wallet, self.app)
99 return qt_gui_object.restore_or_create()
101 class MiniWindow(QDialog):
103 def __init__(self, actuator, expand_callback):
104 super(MiniWindow, self).__init__()
106 self.actuator = actuator
108 accounts_button = IconButton(rsrc("icons", "accounts.png"))
109 accounts_button.setObjectName("accounts_button")
111 self.accounts_selector = QMenu()
112 accounts_button.setMenu(self.accounts_selector)
114 interact_button = IconButton(rsrc("icons", "interact.png"))
115 interact_button.setObjectName("interact_button")
117 app_menu = QMenu(interact_button)
118 report_action = app_menu.addAction(_("&Report Bug"))
119 about_action = app_menu.addAction(_("&About Electrum"))
120 app_menu.addSeparator()
121 quit_action = app_menu.addAction(_("&Quit"))
122 interact_button.setMenu(app_menu)
124 self.connect(report_action, SIGNAL("triggered()"),
125 self.show_report_bug)
126 self.connect(about_action, SIGNAL("triggered()"), self.show_about)
127 self.connect(quit_action, SIGNAL("triggered()"), self.close)
129 expand_button = IconButton(rsrc("icons", "expand.png"))
130 expand_button.setObjectName("expand_button")
131 self.connect(expand_button, SIGNAL("clicked()"), expand_callback)
133 self.btc_balance = None
134 self.quote_currencies = ["EUR", "USD", "GBP"]
135 self.actuator.set_configured_currency(self.set_quote_currency)
136 self.exchanger = exchange_rate.Exchanger(self)
137 # Needed because price discovery is done in a different thread
138 # which needs to be sent back to this main one to update the GUI
139 self.connect(self, SIGNAL("refresh_balance()"), self.refresh_balance)
141 self.balance_label = BalanceLabel(self.change_quote_currency)
142 self.balance_label.setObjectName("balance_label")
144 self.receive_button = QPushButton(_("&Receive"))
145 self.receive_button.setObjectName("receive_button")
146 self.receive_button.setDefault(True)
147 self.connect(self.receive_button, SIGNAL("clicked()"),
150 self.address_input = TextedLineEdit(_("Enter a Bitcoin address..."))
151 self.address_input.setObjectName("address_input")
152 self.connect(self.address_input, SIGNAL("textEdited(QString)"),
153 self.address_field_changed)
154 resize_line_edit_width(self.address_input,
155 "1BtaFUr3qVvAmwrsuDuu5zk6e4s2rxd2Gy")
157 self.address_completions = QStringListModel()
158 address_completer = QCompleter(self.address_input)
159 address_completer.setCaseSensitivity(False)
160 address_completer.setModel(self.address_completions)
161 self.address_input.setCompleter(address_completer)
163 self.valid_address = QCheckBox()
164 self.valid_address.setObjectName("valid_address")
165 self.valid_address.setEnabled(False)
166 self.valid_address.setChecked(False)
168 address_layout = QHBoxLayout()
169 address_layout.addWidget(self.address_input)
170 address_layout.addWidget(self.valid_address)
172 self.amount_input = TextedLineEdit(_("... and amount"))
173 self.amount_input.setObjectName("amount_input")
174 # This is changed according to the user's displayed balance
175 self.amount_validator = QDoubleValidator(self.amount_input)
176 self.amount_validator.setNotation(QDoubleValidator.StandardNotation)
177 self.amount_validator.setDecimals(8)
178 self.amount_input.setValidator(self.amount_validator)
180 self.connect(self.amount_input, SIGNAL("textChanged(QString)"),
181 self.amount_input_changed)
183 amount_layout = QHBoxLayout()
184 amount_layout.addWidget(self.amount_input)
185 amount_layout.addStretch()
187 send_button = QPushButton(_("&Send"))
188 send_button.setObjectName("send_button")
189 self.connect(send_button, SIGNAL("clicked()"), self.send)
191 main_layout = QGridLayout(self)
192 main_layout.addWidget(accounts_button, 0, 0)
193 main_layout.addWidget(interact_button, 1, 0)
194 main_layout.addWidget(expand_button, 2, 0)
196 main_layout.addWidget(self.balance_label, 0, 1)
197 main_layout.addWidget(self.receive_button, 0, 2)
199 main_layout.addLayout(address_layout, 1, 1, 1, -1)
201 main_layout.addLayout(amount_layout, 2, 1)
202 main_layout.addWidget(send_button, 2, 2)
204 quit_shortcut = QShortcut(QKeySequence("Ctrl+Q"), self)
205 self.connect(quit_shortcut, SIGNAL("activated()"), self.close)
206 close_shortcut = QShortcut(QKeySequence("Ctrl+W"), self)
207 self.connect(close_shortcut, SIGNAL("activated()"), self.close)
209 self.setWindowIcon(QIcon(":electrum.png"))
210 self.setWindowTitle("Electrum")
211 self.setWindowFlags(Qt.Window|Qt.MSWindowsFixedSizeDialogHint)
212 self.layout().setSizeConstraint(QLayout.SetFixedSize)
213 self.setObjectName("main_window")
216 def closeEvent(self, event):
217 super(MiniWindow, self).closeEvent(event)
220 def set_payment_fields(self, dest_address, amount):
221 self.address_input.become_active()
222 self.address_input.setText(dest_address)
223 self.address_field_changed(dest_address)
224 self.amount_input.become_active()
225 self.amount_input.setText(amount)
230 def deactivate(self):
233 def set_quote_currency(self, currency):
234 assert currency in self.quote_currencies
235 self.quote_currencies.remove(currency)
236 self.quote_currencies = [currency] + self.quote_currencies
237 self.refresh_balance()
239 def change_quote_currency(self):
240 self.quote_currencies = \
241 self.quote_currencies[1:] + self.quote_currencies[0:1]
242 self.actuator.set_config_currency(self.quote_currencies[0])
243 self.refresh_balance()
245 def refresh_balance(self):
246 if self.btc_balance is None:
247 # Price has been discovered before wallet has been loaded
248 # and server connect... so bail.
250 self.set_balances(self.btc_balance)
251 self.amount_input_changed(self.amount_input.text())
253 def set_balances(self, btc_balance):
254 self.btc_balance = btc_balance
255 quote_text = self.create_quote_text(btc_balance)
257 quote_text = "(%s)" % quote_text
258 btc_balance = "%.2f" % (btc_balance / bitcoin(1))
259 self.balance_label.set_balance_text(btc_balance, quote_text)
260 main_account_info = \
261 "Checking - %s BTC" % btc_balance
262 self.setWindowTitle("Electrum - %s" % main_account_info)
263 self.accounts_selector.clear()
264 self.accounts_selector.addAction("%s %s" % (main_account_info,
267 def amount_input_changed(self, amount_text):
269 amount = D(str(amount_text))
270 except decimal.InvalidOperation:
271 self.balance_label.show_balance()
273 quote_text = self.create_quote_text(amount * bitcoin(1))
275 self.balance_label.set_amount_text(quote_text)
276 self.balance_label.show_amount()
278 self.balance_label.show_balance()
280 def create_quote_text(self, btc_balance):
281 quote_currency = self.quote_currencies[0]
282 quote_balance = self.exchanger.exchange(btc_balance, quote_currency)
283 if quote_balance is None:
286 quote_text = "%.2f %s" % ((quote_balance / bitcoin(1)),
291 if self.actuator.send(self.address_input.text(),
292 self.amount_input.text(), self):
293 self.address_input.become_inactive()
294 self.amount_input.become_inactive()
296 def address_field_changed(self, address):
297 if self.actuator.is_valid(address):
298 self.valid_address.setChecked(True)
300 self.valid_address.setChecked(False)
302 def copy_address(self):
303 receive_popup = ReceivePopup(self.receive_button)
304 self.actuator.copy_address(receive_popup)
306 def update_completions(self, completions):
307 self.address_completions.setStringList(completions)
309 def show_about(self):
310 QMessageBox.about(self, "Electrum",
311 _("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."))
313 def show_report_bug(self):
314 QMessageBox.information(self, "Electrum - " + _("Reporting Bugs"),
315 _("Email bug reports to %s") % "genjix" + "@" + "riseup.net")
317 class BalanceLabel(QLabel):
323 def __init__(self, change_quote_currency, parent=None):
324 super(QLabel, self).__init__(_("Connecting..."), parent)
325 self.change_quote_currency = change_quote_currency
326 self.state = self.SHOW_CONNECTING
327 self.balance_text = ""
328 self.amount_text = ""
330 def mousePressEvent(self, event):
331 if self.state != self.SHOW_CONNECTING:
332 self.change_quote_currency()
334 def set_balance_text(self, btc_balance, quote_text):
335 if self.state == self.SHOW_CONNECTING:
336 self.state = self.SHOW_BALANCE
337 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)
338 if self.state == self.SHOW_BALANCE:
339 self.setText(self.balance_text)
341 def set_amount_text(self, quote_text):
342 self.amount_text = "<span style='font-size: 10pt'>%s</span>" % quote_text
343 if self.state == self.SHOW_AMOUNT:
344 self.setText(self.amount_text)
346 def show_balance(self):
347 if self.state == self.SHOW_AMOUNT:
348 self.state = self.SHOW_BALANCE
349 self.setText(self.balance_text)
351 def show_amount(self):
352 if self.state == self.SHOW_BALANCE:
353 self.state = self.SHOW_AMOUNT
354 self.setText(self.amount_text)
356 class TextedLineEdit(QLineEdit):
358 def __init__(self, inactive_text, parent=None):
359 super(QLineEdit, self).__init__(parent)
360 self.inactive_text = inactive_text
361 self.become_inactive()
363 def mousePressEvent(self, event):
364 if self.isReadOnly():
366 QLineEdit.mousePressEvent(self, event)
368 def focusOutEvent(self, event):
369 if self.text() == "":
370 self.become_inactive()
371 QLineEdit.focusOutEvent(self, event)
373 def focusInEvent(self, event):
374 if self.isReadOnly():
376 QLineEdit.focusInEvent(self, event)
378 def become_inactive(self):
379 self.setText(self.inactive_text)
380 self.setReadOnly(True)
381 self.recompute_style()
383 def become_active(self):
385 self.setReadOnly(False)
386 self.recompute_style()
388 def recompute_style(self):
389 qApp.style().unpolish(self)
390 qApp.style().polish(self)
391 # also possible but more expensive:
392 #qApp.setStyleSheet(qApp.styleSheet())
394 def ok_cancel_buttons(dialog):
395 row_layout = QHBoxLayout()
396 row_layout.addStretch(1)
397 ok_button = QPushButton(_("OK"))
398 row_layout.addWidget(ok_button)
399 ok_button.clicked.connect(dialog.accept)
400 cancel_button = QPushButton(_("Cancel"))
401 row_layout.addWidget(cancel_button)
402 cancel_button.clicked.connect(dialog.reject)
405 class PasswordDialog(QDialog):
407 def __init__(self, parent):
408 super(QDialog, self).__init__(parent)
412 self.password_input = QLineEdit()
413 self.password_input.setEchoMode(QLineEdit.Password)
415 main_layout = QVBoxLayout(self)
416 message = _('Please enter your password')
417 main_layout.addWidget(QLabel(message))
421 grid.addWidget(QLabel(_('Password')), 1, 0)
422 grid.addWidget(self.password_input, 1, 1)
423 main_layout.addLayout(grid)
425 main_layout.addLayout(ok_cancel_buttons(self))
426 self.setLayout(main_layout)
431 return unicode(self.password_input.text())
433 class ReceivePopup(QDialog):
435 def leaveEvent(self, event):
438 def setup(self, address):
439 label = QLabel(_("Copied your Bitcoin address to the clipboard!"))
440 address_display = QLineEdit(address)
441 address_display.setReadOnly(True)
442 resize_line_edit_width(address_display, address)
444 main_layout = QVBoxLayout(self)
445 main_layout.addWidget(label)
446 main_layout.addWidget(address_display)
448 self.setMouseTracking(True)
449 self.setWindowTitle("Electrum - " + _("Receive Bitcoin payment"))
450 self.setWindowFlags(Qt.Window|Qt.FramelessWindowHint|Qt.MSWindowsFixedSizeDialogHint)
451 self.layout().setSizeConstraint(QLayout.SetFixedSize)
452 #self.setFrameStyle(QFrame.WinPanel|QFrame.Raised)
453 #self.setAlignment(Qt.AlignCenter)
456 parent = self.parent()
457 top_left_pos = parent.mapToGlobal(parent.rect().bottomLeft())
458 self.move(top_left_pos)
459 center_mouse_pos = self.mapToGlobal(self.rect().center())
460 QCursor.setPos(center_mouse_pos)
465 def __init__(self, wallet):
468 def set_configured_currency(self, set_quote_currency):
469 currency = self.wallet.conversion_currency
470 # currency can be none when Electrum is used for the first
471 # time and no setting has been created yet.
472 if currency is not None:
473 set_quote_currency(currency)
475 def set_config_currency(self, conversion_currency):
476 self.wallet.conversion_currency = conversion_currency
478 def copy_address(self, receive_popup):
479 addrs = [addr for addr in self.wallet.all_addresses()
480 if not self.wallet.is_change(addr)]
481 # Select most recent addresses from gap limit
482 addrs = addrs[-self.wallet.gap_limit:]
483 copied_address = random.choice(addrs)
484 qApp.clipboard().setText(copied_address)
485 receive_popup.setup(copied_address)
486 receive_popup.popup()
488 def send(self, address, amount, parent_window):
489 dest_address = self.fetch_destination(address)
491 if dest_address is None or not self.wallet.is_valid(dest_address):
492 QMessageBox.warning(parent_window, _('Error'),
493 _('Invalid Bitcoin Address') + ':\n' + address, _('OK'))
496 convert_amount = lambda amount: \
497 int(D(unicode(amount)) * bitcoin(1))
498 amount = convert_amount(amount)
500 if self.wallet.use_encryption:
501 password_dialog = PasswordDialog(parent_window)
502 password = password_dialog.run()
510 if amount < bitcoin(1) / 10:
512 fee = bitcoin(1) / 100
515 tx = self.wallet.mktx(dest_address, amount, "", password, fee)
516 except BaseException as error:
517 QMessageBox.warning(parent_window, _('Error'), str(error), _('OK'))
520 status, message = self.wallet.sendtx(tx)
522 QMessageBox.warning(parent_window, _('Error'), message, _('OK'))
525 QMessageBox.information(parent_window, '',
526 _('Payment sent.') + '\n' + message, _('OK'))
529 def fetch_destination(self, address):
530 recipient = unicode(address).strip()
533 match1 = re.match("^(|([\w\-\.]+)@)((\w[\w\-]+\.)+[\w\-]+)$",
536 # label or alias, with address in brackets
537 match2 = re.match("(.*?)\s*\<([1-9A-HJ-NP-Za-km-z]{26,})\>",
542 self.wallet.get_alias(recipient, True,
543 self.show_message, self.question)
546 return match2.group(2)
550 def is_valid(self, address):
551 return self.wallet.is_valid(address)
553 class MiniDriver(QObject):
560 def __init__(self, wallet, window):
561 super(QObject, self).__init__()
566 self.wallet.register_callback(self.update_callback)
571 self.connect(self, SIGNAL("updatesignal()"), self.update)
572 self.update_callback()
574 # This is a hack to workaround that Qt does not like changing the
575 # window properties from this other thread before the runloop has
577 def update_callback(self):
578 self.emit(SIGNAL("updatesignal()"))
581 if not self.wallet.interface:
583 elif not self.wallet.interface.is_connected:
585 elif not self.wallet.blocks == -1:
587 elif not self.wallet.is_up_to_date:
592 if self.wallet.up_to_date:
593 self.update_balance()
594 self.update_completions()
596 def initializing(self):
597 if self.state == self.INITIALIZING:
599 self.state = self.INITIALIZING
600 self.window.deactivate()
602 def connecting(self):
603 if self.state == self.CONNECTING:
605 self.state = self.CONNECTING
606 self.window.deactivate()
608 def synchronizing(self):
609 if self.state == self.SYNCHRONIZING:
611 self.state = self.SYNCHRONIZING
612 self.window.deactivate()
615 if self.state == self.READY:
617 self.state = self.READY
618 self.window.activate()
620 def update_balance(self):
621 conf_balance, unconf_balance = self.wallet.get_balance()
622 balance = D(conf_balance + unconf_balance)
623 self.window.set_balances(balance)
625 def update_completions(self):
627 for addr, label in self.wallet.labels.items():
628 if addr in self.wallet.addressbook:
629 completions.append("%s <%s>" % (label, addr))
630 completions = completions + self.wallet.aliases.keys()
631 self.window.update_completions(completions)
633 if __name__ == "__main__":
634 app = QApplication(sys.argv)
635 with open(rsrc("style.css")) as style_file:
636 app.setStyleSheet(style_file.read())
638 sys.exit(app.exec_())