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 self.btc_balance = None
113 self.quote_currencies = ["EUR", "USD", "GBP"]
114 self.actuator.set_configured_currency(self.set_quote_currency)
115 self.exchanger = exchange_rate.Exchanger(self)
116 # Needed because price discovery is done in a different thread
117 # which needs to be sent back to this main one to update the GUI
118 self.connect(self, SIGNAL("refresh_balance()"), self.refresh_balance)
120 self.balance_label = BalanceLabel(self.change_quote_currency)
121 self.balance_label.setObjectName("balance_label")
123 self.receive_button = QPushButton(_("&Receive"))
124 self.receive_button.setObjectName("receive_button")
125 self.receive_button.setDefault(True)
126 self.connect(self.receive_button, SIGNAL("clicked()"),
129 self.address_input = TextedLineEdit(_("Enter a Bitcoin address..."))
130 self.address_input.setObjectName("address_input")
131 self.connect(self.address_input, SIGNAL("textEdited(QString)"),
132 self.address_field_changed)
133 resize_line_edit_width(self.address_input,
134 "1BtaFUr3qVvAmwrsuDuu5zk6e4s2rxd2Gy")
136 self.address_completions = QStringListModel()
137 address_completer = QCompleter(self.address_input)
138 address_completer.setCaseSensitivity(False)
139 address_completer.setModel(self.address_completions)
140 self.address_input.setCompleter(address_completer)
142 address_layout = QHBoxLayout()
143 address_layout.addWidget(self.address_input)
145 self.amount_input = TextedLineEdit(_("... and amount"))
146 self.amount_input.setObjectName("amount_input")
147 # This is changed according to the user's displayed balance
148 self.amount_validator = QDoubleValidator(self.amount_input)
149 self.amount_validator.setNotation(QDoubleValidator.StandardNotation)
150 self.amount_validator.setDecimals(8)
151 self.amount_input.setValidator(self.amount_validator)
153 self.connect(self.amount_input, SIGNAL("textChanged(QString)"),
154 self.amount_input_changed)
156 amount_layout = QHBoxLayout()
157 amount_layout.addWidget(self.amount_input)
158 amount_layout.addStretch()
160 self.send_button = QPushButton(_("&Send"))
161 self.send_button.setObjectName("send_button")
162 self.send_button.setDisabled(True);
163 self.connect(self.send_button, SIGNAL("clicked()"), self.send)
165 main_layout = QGridLayout(self)
167 main_layout.addWidget(self.balance_label, 0, 0)
168 main_layout.addWidget(self.receive_button, 0, 1)
170 main_layout.addWidget(self.address_input, 1, 0, 1, -1)
172 main_layout.addLayout(amount_layout, 2, 0)
173 main_layout.addWidget(self.send_button, 2, 1)
176 file_menu = menubar.addMenu(_("&File"))
177 file_menu.addAction(_("Open"))
178 view_menu = menubar.addMenu(_("&View"))
179 view_menu.addMenu(_("&Themes"))
180 view_menu.addAction(_("Show History"))
182 settings_menu = menubar.addMenu(_("&Settings"))
183 expert_gui = settings_menu.addAction(_("&Switch to expert GUI"))
184 self.connect(expert_gui, SIGNAL("triggered()"), expand_callback)
186 menubar.addMenu(_("&Help"))
187 main_layout.setMenuBar(menubar)
189 quit_shortcut = QShortcut(QKeySequence("Ctrl+Q"), self)
190 self.connect(quit_shortcut, SIGNAL("activated()"), self.close)
191 close_shortcut = QShortcut(QKeySequence("Ctrl+W"), self)
192 self.connect(close_shortcut, SIGNAL("activated()"), self.close)
194 self.setWindowIcon(QIcon(":electrum.png"))
195 self.setWindowTitle("Electrum")
196 self.setWindowFlags(Qt.Window|Qt.MSWindowsFixedSizeDialogHint)
197 self.layout().setSizeConstraint(QLayout.SetFixedSize)
198 self.setObjectName("main_window")
201 def recompute_style(self):
202 qApp.style().unpolish(self)
203 qApp.style().polish(self)
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 self.setWindowTitle("Electrum - %s BTC" % btc_balance)
251 def amount_input_changed(self, amount_text):
252 self.check_button_status()
255 amount = D(str(amount_text))
256 except decimal.InvalidOperation:
257 self.balance_label.show_balance()
259 quote_text = self.create_quote_text(amount * bitcoin(1))
261 self.balance_label.set_amount_text(quote_text)
262 self.balance_label.show_amount()
264 self.balance_label.show_balance()
266 def create_quote_text(self, btc_balance):
267 quote_currency = self.quote_currencies[0]
268 quote_balance = self.exchanger.exchange(btc_balance, quote_currency)
269 if quote_balance is None:
272 quote_text = "%.2f %s" % ((quote_balance / bitcoin(1)),
277 if self.actuator.send(self.address_input.text(),
278 self.amount_input.text(), self):
279 self.address_input.become_inactive()
280 self.amount_input.become_inactive()
282 def check_button_status(self):
283 if self.amount_input.text() != _("... and amount") and len(self.amount_input.text()) != 0:
284 self.send_button.setDisabled(False)
286 self.send_button.setDisabled(True)
288 def address_field_changed(self, address):
289 if self.actuator.is_valid(address):
290 self.check_button_status()
291 self.address_input.setProperty("isValid", True)
292 self.style().unpolish(self.address_input)
293 self.style().polish(self.address_input)
295 self.send_button.setDisabled(True)
296 self.address_input.setProperty("isValid", False)
297 self.style().unpolish(self.address_input)
298 self.style().polish(self.address_input)
300 def copy_address(self):
301 receive_popup = ReceivePopup(self.receive_button)
302 self.actuator.copy_address(receive_popup)
304 def update_completions(self, completions):
305 self.address_completions.setStringList(completions)
308 self.actuator.acceptbit(self.quote_currencies[0])
310 def show_about(self):
311 QMessageBox.about(self, "Electrum",
312 _("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."))
314 def show_report_bug(self):
315 QMessageBox.information(self, "Electrum - " + _("Reporting Bugs"),
316 _("Email bug reports to %s") % "genjix" + "@" + "riseup.net")
318 class BalanceLabel(QLabel):
324 def __init__(self, change_quote_currency, parent=None):
325 super(QLabel, self).__init__(_("Connecting..."), parent)
326 self.change_quote_currency = change_quote_currency
327 self.state = self.SHOW_CONNECTING
328 self.balance_text = ""
329 self.amount_text = ""
331 def mousePressEvent(self, event):
332 if self.state != self.SHOW_CONNECTING:
333 self.change_quote_currency()
335 def set_balance_text(self, btc_balance, quote_text):
336 if self.state == self.SHOW_CONNECTING:
337 self.state = self.SHOW_BALANCE
338 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)
339 if self.state == self.SHOW_BALANCE:
340 self.setText(self.balance_text)
342 def set_amount_text(self, quote_text):
343 self.amount_text = "<span style='font-size: 10pt'>%s</span>" % quote_text
344 if self.state == self.SHOW_AMOUNT:
345 self.setText(self.amount_text)
347 def show_balance(self):
348 if self.state == self.SHOW_AMOUNT:
349 self.state = self.SHOW_BALANCE
350 self.setText(self.balance_text)
352 def show_amount(self):
353 if self.state == self.SHOW_BALANCE:
354 self.state = self.SHOW_AMOUNT
355 self.setText(self.amount_text)
357 class TextedLineEdit(QLineEdit):
359 def __init__(self, inactive_text, parent=None):
360 super(QLineEdit, self).__init__(parent)
361 self.inactive_text = inactive_text
362 self.become_inactive()
364 def mousePressEvent(self, event):
365 if self.isReadOnly():
367 QLineEdit.mousePressEvent(self, event)
369 def focusOutEvent(self, event):
370 if self.text() == "":
371 self.become_inactive()
372 QLineEdit.focusOutEvent(self, event)
374 def focusInEvent(self, event):
375 if self.isReadOnly():
377 QLineEdit.focusInEvent(self, event)
379 def become_inactive(self):
380 self.setReadOnly(True)
381 self.recompute_style()
382 self.setText(self.inactive_text)
384 def become_active(self):
385 self.setReadOnly(False)
386 self.recompute_style()
389 def recompute_style(self):
390 qApp.style().unpolish(self)
391 qApp.style().polish(self)
392 # also possible but more expensive:
393 #qApp.setStyleSheet(qApp.styleSheet())
395 def ok_cancel_buttons(dialog):
396 row_layout = QHBoxLayout()
397 row_layout.addStretch(1)
398 ok_button = QPushButton(_("OK"))
399 row_layout.addWidget(ok_button)
400 ok_button.clicked.connect(dialog.accept)
401 cancel_button = QPushButton(_("Cancel"))
402 row_layout.addWidget(cancel_button)
403 cancel_button.clicked.connect(dialog.reject)
406 class PasswordDialog(QDialog):
408 def __init__(self, parent):
409 super(QDialog, self).__init__(parent)
413 self.password_input = QLineEdit()
414 self.password_input.setEchoMode(QLineEdit.Password)
416 main_layout = QVBoxLayout(self)
417 message = _('Please enter your password')
418 main_layout.addWidget(QLabel(message))
422 grid.addWidget(QLabel(_('Password')), 1, 0)
423 grid.addWidget(self.password_input, 1, 1)
424 main_layout.addLayout(grid)
426 main_layout.addLayout(ok_cancel_buttons(self))
427 self.setLayout(main_layout)
432 return unicode(self.password_input.text())
434 class ReceivePopup(QDialog):
436 def leaveEvent(self, event):
439 def setup(self, address):
440 label = QLabel(_("Copied your Bitcoin address to the clipboard!"))
441 address_display = QLineEdit(address)
442 address_display.setReadOnly(True)
443 resize_line_edit_width(address_display, address)
445 main_layout = QVBoxLayout(self)
446 main_layout.addWidget(label)
447 main_layout.addWidget(address_display)
449 self.setMouseTracking(True)
450 self.setWindowTitle("Electrum - " + _("Receive Bitcoin payment"))
451 self.setWindowFlags(Qt.Window|Qt.FramelessWindowHint|Qt.MSWindowsFixedSizeDialogHint)
452 self.layout().setSizeConstraint(QLayout.SetFixedSize)
453 #self.setFrameStyle(QFrame.WinPanel|QFrame.Raised)
454 #self.setAlignment(Qt.AlignCenter)
457 parent = self.parent()
458 top_left_pos = parent.mapToGlobal(parent.rect().bottomLeft())
459 self.move(top_left_pos)
460 center_mouse_pos = self.mapToGlobal(self.rect().center())
461 QCursor.setPos(center_mouse_pos)
466 def __init__(self, wallet):
469 def set_configured_currency(self, set_quote_currency):
470 currency = self.wallet.conversion_currency
471 # currency can be none when Electrum is used for the first
472 # time and no setting has been created yet.
473 if currency is not None:
474 set_quote_currency(currency)
476 def set_config_currency(self, conversion_currency):
477 self.wallet.conversion_currency = conversion_currency
479 def copy_address(self, receive_popup):
480 addrs = [addr for addr in self.wallet.all_addresses()
481 if not self.wallet.is_change(addr)]
482 # Select most recent addresses from gap limit
483 addrs = addrs[-self.wallet.gap_limit:]
484 copied_address = random.choice(addrs)
485 qApp.clipboard().setText(copied_address)
486 receive_popup.setup(copied_address)
487 receive_popup.popup()
489 def send(self, address, amount, parent_window):
490 dest_address = self.fetch_destination(address)
492 if dest_address is None or not self.wallet.is_valid(dest_address):
493 QMessageBox.warning(parent_window, _('Error'),
494 _('Invalid Bitcoin Address') + ':\n' + address, _('OK'))
497 convert_amount = lambda amount: \
498 int(D(unicode(amount)) * bitcoin(1))
499 amount = convert_amount(amount)
501 if self.wallet.use_encryption:
502 password_dialog = PasswordDialog(parent_window)
503 password = password_dialog.run()
511 if amount < bitcoin(1) / 10:
513 fee = bitcoin(1) / 1000
516 tx = self.wallet.mktx(dest_address, amount, "", password, fee)
517 except BaseException as error:
518 QMessageBox.warning(parent_window, _('Error'), str(error), _('OK'))
521 status, message = self.wallet.sendtx(tx)
523 QMessageBox.warning(parent_window, _('Error'), message, _('OK'))
526 QMessageBox.information(parent_window, '',
527 _('Payment sent.') + '\n' + message, _('OK'))
530 def fetch_destination(self, address):
531 recipient = unicode(address).strip()
534 match1 = re.match("^(|([\w\-\.]+)@)((\w[\w\-]+\.)+[\w\-]+)$",
537 # label or alias, with address in brackets
538 match2 = re.match("(.*?)\s*\<([1-9A-HJ-NP-Za-km-z]{26,})\>",
543 self.wallet.get_alias(recipient, True,
544 self.show_message, self.question)
547 return match2.group(2)
551 def is_valid(self, address):
552 return self.wallet.is_valid(address)
554 def acceptbit(self, currency):
555 master_pubkey = self.wallet.master_public_key.encode("hex")
556 url = "http://acceptbit.com/mpk/%s/%s" % (master_pubkey, currency)
559 class MiniDriver(QObject):
566 def __init__(self, wallet, window):
567 super(QObject, self).__init__()
572 self.wallet.register_callback(self.update_callback)
577 self.connect(self, SIGNAL("updatesignal()"), self.update)
578 self.update_callback()
580 # This is a hack to workaround that Qt does not like changing the
581 # window properties from this other thread before the runloop has
583 def update_callback(self):
584 self.emit(SIGNAL("updatesignal()"))
587 if not self.wallet.interface:
589 elif not self.wallet.interface.is_connected:
591 elif not self.wallet.blocks == -1:
593 elif not self.wallet.is_up_to_date:
598 if self.wallet.up_to_date:
599 self.update_balance()
600 self.update_completions()
602 def initializing(self):
603 if self.state == self.INITIALIZING:
605 self.state = self.INITIALIZING
606 self.window.deactivate()
608 def connecting(self):
609 if self.state == self.CONNECTING:
611 self.state = self.CONNECTING
612 self.window.deactivate()
614 def synchronizing(self):
615 if self.state == self.SYNCHRONIZING:
617 self.state = self.SYNCHRONIZING
618 self.window.deactivate()
621 if self.state == self.READY:
623 self.state = self.READY
624 self.window.activate()
626 def update_balance(self):
627 conf_balance, unconf_balance = self.wallet.get_balance()
628 balance = D(conf_balance + unconf_balance)
629 self.window.set_balances(balance)
631 def update_completions(self):
633 for addr, label in self.wallet.labels.items():
634 if addr in self.wallet.addressbook:
635 completions.append("%s <%s>" % (label, addr))
636 completions = completions + self.wallet.aliases.keys()
637 self.window.update_completions(completions)
639 if __name__ == "__main__":
640 app = QApplication(sys.argv)
641 with open(rsrc("style.css")) as style_file:
642 app.setStyleSheet(style_file.read())
644 sys.exit(app.exec_())