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()"), self.copy_address)
128 # Bitcoin address code
129 self.address_input = QLineEdit()
130 self.address_input.setPlaceholderText(_("Enter a Bitcoin address..."))
131 self.address_input.setObjectName("address_input")
134 self.connect(self.address_input, SIGNAL("textEdited(QString)"), self.address_field_changed)
135 resize_line_edit_width(self.address_input, "1BtaFUr3qVvAmwrsuDuu5zk6e4s2rxd2Gy")
137 self.address_completions = QStringListModel()
138 address_completer = QCompleter(self.address_input)
139 address_completer.setCaseSensitivity(False)
140 address_completer.setModel(self.address_completions)
141 self.address_input.setCompleter(address_completer)
143 address_layout = QHBoxLayout()
144 address_layout.addWidget(self.address_input)
146 self.amount_input = QLineEdit()
147 self.amount_input.setPlaceholderText(_("... and amount"))
148 self.amount_input.setObjectName("amount_input")
149 # This is changed according to the user's displayed balance
150 self.amount_validator = QDoubleValidator(self.amount_input)
151 self.amount_validator.setNotation(QDoubleValidator.StandardNotation)
152 self.amount_validator.setDecimals(8)
153 self.amount_input.setValidator(self.amount_validator)
155 # This removes the very ugly OSX highlighting, please leave this in :D
156 self.address_input.setAttribute(Qt.WA_MacShowFocusRect, 0)
157 self.amount_input.setAttribute(Qt.WA_MacShowFocusRect, 0)
159 self.connect(self.amount_input, SIGNAL("textChanged(QString)"),
160 self.amount_input_changed)
162 amount_layout = QHBoxLayout()
163 amount_layout.addWidget(self.amount_input)
164 amount_layout.addStretch()
166 self.send_button = QPushButton(_("&Send"))
167 self.send_button.setObjectName("send_button")
168 self.send_button.setDisabled(True);
169 self.connect(self.send_button, SIGNAL("clicked()"), self.send)
171 main_layout = QGridLayout(self)
173 main_layout.addWidget(self.balance_label, 0, 0)
174 main_layout.addWidget(self.receive_button, 0, 1)
176 main_layout.addWidget(self.address_input, 1, 0, 1, -1)
178 main_layout.addLayout(amount_layout, 2, 0)
179 main_layout.addWidget(self.send_button, 2, 1)
182 electrum_menu = menubar.addMenu(_("&Electrum"))
183 electrum_menu.addMenu(_("&Servers"))
184 electrum_menu.addSeparator()
185 electrum_menu.addAction(_("&Quit"))
187 view_menu = menubar.addMenu(_("&View"))
188 expert_gui = view_menu.addAction(_("&Pro Mode"))
189 self.connect(expert_gui, SIGNAL("triggered()"), expand_callback)
190 view_menu.addMenu(_("&Themes"))
191 view_menu.addSeparator()
192 view_menu.addAction(_("Show History"))
194 settings_menu = menubar.addMenu(_("&Settings"))
195 settings_menu.addAction(_("&Configure Electrum"))
197 help_menu = menubar.addMenu(_("&Help"))
198 help_menu.addAction(_("&Contents"))
199 help_menu.addSeparator()
200 help_menu.addAction(_("&Report Bug"))
201 help_menu.addAction(_("&About"))
202 main_layout.setMenuBar(menubar)
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 recompute_style(self):
217 qApp.style().unpolish(self)
218 qApp.style().polish(self)
220 def closeEvent(self, event):
221 super(MiniWindow, self).closeEvent(event)
224 def set_payment_fields(self, dest_address, amount):
225 self.address_input.setText(dest_address)
226 self.address_field_changed(dest_address)
227 self.amount_input.setText(amount)
232 def deactivate(self):
235 def set_quote_currency(self, currency):
236 assert currency in self.quote_currencies
237 self.quote_currencies.remove(currency)
238 self.quote_currencies = [currency] + self.quote_currencies
239 self.refresh_balance()
241 def change_quote_currency(self):
242 self.quote_currencies = \
243 self.quote_currencies[1:] + self.quote_currencies[0:1]
244 self.actuator.set_config_currency(self.quote_currencies[0])
245 self.refresh_balance()
247 def refresh_balance(self):
248 if self.btc_balance is None:
249 # Price has been discovered before wallet has been loaded
250 # and server connect... so bail.
252 self.set_balances(self.btc_balance)
253 self.amount_input_changed(self.amount_input.text())
255 def set_balances(self, btc_balance):
256 self.btc_balance = btc_balance
257 quote_text = self.create_quote_text(btc_balance)
259 quote_text = "(%s)" % quote_text
260 btc_balance = "%.2f" % (btc_balance / bitcoin(1))
261 self.balance_label.set_balance_text(btc_balance, quote_text)
262 self.setWindowTitle("Electrum - %s BTC" % btc_balance)
264 def amount_input_changed(self, amount_text):
265 self.check_button_status()
268 amount = D(str(amount_text))
269 except decimal.InvalidOperation:
270 self.balance_label.show_balance()
272 quote_text = self.create_quote_text(amount * bitcoin(1))
274 self.balance_label.set_amount_text(quote_text)
275 self.balance_label.show_amount()
277 self.balance_label.show_balance()
279 def create_quote_text(self, btc_balance):
280 quote_currency = self.quote_currencies[0]
281 quote_balance = self.exchanger.exchange(btc_balance, quote_currency)
282 if quote_balance is None:
285 quote_text = "%.2f %s" % ((quote_balance / bitcoin(1)),
290 if self.actuator.send(self.address_input.text(), self.amount_input.text(), self):
291 self.address_input.setText("")
292 self.amount_input.setText("")
294 def check_button_status(self):
295 if self.address_input.property("isValid") == True and len(self.amount_input.text()) != 0:
296 self.send_button.setDisabled(False)
298 self.send_button.setDisabled(True)
300 def address_field_changed(self, address):
301 if self.actuator.is_valid(address):
302 self.check_button_status()
303 self.address_input.setProperty("isValid", True)
304 self.recompute_style(self.address_input)
306 self.send_button.setDisabled(True)
307 self.address_input.setProperty("isValid", False)
308 self.recompute_style(self.address_input)
310 if len(address) == 0:
311 self.address_input.setProperty("isValid", None)
312 self.recompute_style(self.address_input)
314 def recompute_style(self, element):
315 self.style().unpolish(element)
316 self.style().polish(element)
318 def copy_address(self):
319 receive_popup = ReceivePopup(self.receive_button)
320 self.actuator.copy_address(receive_popup)
322 def update_completions(self, completions):
323 self.address_completions.setStringList(completions)
326 self.actuator.acceptbit(self.quote_currencies[0])
328 def show_about(self):
329 QMessageBox.about(self, "Electrum",
330 _("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."))
332 def show_report_bug(self):
333 QMessageBox.information(self, "Electrum - " + _("Reporting Bugs"),
334 _("Email bug reports to %s") % "genjix" + "@" + "riseup.net")
336 class BalanceLabel(QLabel):
342 def __init__(self, change_quote_currency, parent=None):
343 super(QLabel, self).__init__(_("Connecting..."), parent)
344 self.change_quote_currency = change_quote_currency
345 self.state = self.SHOW_CONNECTING
346 self.balance_text = ""
347 self.amount_text = ""
349 def mousePressEvent(self, event):
350 if self.state != self.SHOW_CONNECTING:
351 self.change_quote_currency()
353 def set_balance_text(self, btc_balance, quote_text):
354 if self.state == self.SHOW_CONNECTING:
355 self.state = self.SHOW_BALANCE
356 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)
357 if self.state == self.SHOW_BALANCE:
358 self.setText(self.balance_text)
360 def set_amount_text(self, quote_text):
361 self.amount_text = "<span style='font-size: 10pt'>%s</span>" % quote_text
362 if self.state == self.SHOW_AMOUNT:
363 self.setText(self.amount_text)
365 def show_balance(self):
366 if self.state == self.SHOW_AMOUNT:
367 self.state = self.SHOW_BALANCE
368 self.setText(self.balance_text)
370 def show_amount(self):
371 if self.state == self.SHOW_BALANCE:
372 self.state = self.SHOW_AMOUNT
373 self.setText(self.amount_text)
375 def ok_cancel_buttons(dialog):
376 row_layout = QHBoxLayout()
377 row_layout.addStretch(1)
378 ok_button = QPushButton(_("OK"))
379 row_layout.addWidget(ok_button)
380 ok_button.clicked.connect(dialog.accept)
381 cancel_button = QPushButton(_("Cancel"))
382 row_layout.addWidget(cancel_button)
383 cancel_button.clicked.connect(dialog.reject)
386 class PasswordDialog(QDialog):
388 def __init__(self, parent):
389 super(QDialog, self).__init__(parent)
393 self.password_input = QLineEdit()
394 self.password_input.setEchoMode(QLineEdit.Password)
396 main_layout = QVBoxLayout(self)
397 message = _('Please enter your password')
398 main_layout.addWidget(QLabel(message))
402 grid.addWidget(QLabel(_('Password')), 1, 0)
403 grid.addWidget(self.password_input, 1, 1)
404 main_layout.addLayout(grid)
406 main_layout.addLayout(ok_cancel_buttons(self))
407 self.setLayout(main_layout)
412 return unicode(self.password_input.text())
414 class ReceivePopup(QDialog):
416 def leaveEvent(self, event):
419 def setup(self, address):
420 label = QLabel(_("Copied your Bitcoin address to the clipboard!"))
421 address_display = QLineEdit(address)
422 address_display.setReadOnly(True)
423 resize_line_edit_width(address_display, address)
425 main_layout = QVBoxLayout(self)
426 main_layout.addWidget(label)
427 main_layout.addWidget(address_display)
429 self.setMouseTracking(True)
430 self.setWindowTitle("Electrum - " + _("Receive Bitcoin payment"))
431 self.setWindowFlags(Qt.Window|Qt.FramelessWindowHint|Qt.MSWindowsFixedSizeDialogHint)
432 self.layout().setSizeConstraint(QLayout.SetFixedSize)
433 #self.setFrameStyle(QFrame.WinPanel|QFrame.Raised)
434 #self.setAlignment(Qt.AlignCenter)
437 parent = self.parent()
438 top_left_pos = parent.mapToGlobal(parent.rect().bottomLeft())
439 self.move(top_left_pos)
440 center_mouse_pos = self.mapToGlobal(self.rect().center())
441 QCursor.setPos(center_mouse_pos)
446 def __init__(self, wallet):
449 def set_configured_currency(self, set_quote_currency):
450 currency = self.wallet.conversion_currency
451 # currency can be none when Electrum is used for the first
452 # time and no setting has been created yet.
453 if currency is not None:
454 set_quote_currency(currency)
456 def set_config_currency(self, conversion_currency):
457 self.wallet.conversion_currency = conversion_currency
459 def copy_address(self, receive_popup):
460 addrs = [addr for addr in self.wallet.all_addresses()
461 if not self.wallet.is_change(addr)]
462 # Select most recent addresses from gap limit
463 addrs = addrs[-self.wallet.gap_limit:]
464 copied_address = random.choice(addrs)
465 qApp.clipboard().setText(copied_address)
466 receive_popup.setup(copied_address)
467 receive_popup.popup()
469 def send(self, address, amount, parent_window):
470 dest_address = self.fetch_destination(address)
472 if dest_address is None or not self.wallet.is_valid(dest_address):
473 QMessageBox.warning(parent_window, _('Error'),
474 _('Invalid Bitcoin Address') + ':\n' + address, _('OK'))
477 convert_amount = lambda amount: \
478 int(D(unicode(amount)) * bitcoin(1))
479 amount = convert_amount(amount)
481 if self.wallet.use_encryption:
482 password_dialog = PasswordDialog(parent_window)
483 password = password_dialog.run()
491 if amount < bitcoin(1) / 10:
493 fee = bitcoin(1) / 1000
496 tx = self.wallet.mktx(dest_address, amount, "", password, fee)
497 except BaseException as error:
498 QMessageBox.warning(parent_window, _('Error'), str(error), _('OK'))
501 status, message = self.wallet.sendtx(tx)
503 QMessageBox.warning(parent_window, _('Error'), message, _('OK'))
506 QMessageBox.information(parent_window, '',
507 _('Payment sent.') + '\n' + message, _('OK'))
510 def fetch_destination(self, address):
511 recipient = unicode(address).strip()
514 match1 = re.match("^(|([\w\-\.]+)@)((\w[\w\-]+\.)+[\w\-]+)$",
517 # label or alias, with address in brackets
518 match2 = re.match("(.*?)\s*\<([1-9A-HJ-NP-Za-km-z]{26,})\>",
523 self.wallet.get_alias(recipient, True,
524 self.show_message, self.question)
527 return match2.group(2)
531 def is_valid(self, address):
532 return self.wallet.is_valid(address)
534 def acceptbit(self, currency):
535 master_pubkey = self.wallet.master_public_key.encode("hex")
536 url = "http://acceptbit.com/mpk/%s/%s" % (master_pubkey, currency)
539 class MiniDriver(QObject):
546 def __init__(self, wallet, window):
547 super(QObject, self).__init__()
552 self.wallet.register_callback(self.update_callback)
557 self.connect(self, SIGNAL("updatesignal()"), self.update)
558 self.update_callback()
560 # This is a hack to workaround that Qt does not like changing the
561 # window properties from this other thread before the runloop has
563 def update_callback(self):
564 self.emit(SIGNAL("updatesignal()"))
567 if not self.wallet.interface:
569 elif not self.wallet.interface.is_connected:
571 elif not self.wallet.blocks == -1:
573 elif not self.wallet.is_up_to_date:
578 if self.wallet.up_to_date:
579 self.update_balance()
580 self.update_completions()
582 def initializing(self):
583 if self.state == self.INITIALIZING:
585 self.state = self.INITIALIZING
586 self.window.deactivate()
588 def connecting(self):
589 if self.state == self.CONNECTING:
591 self.state = self.CONNECTING
592 self.window.deactivate()
594 def synchronizing(self):
595 if self.state == self.SYNCHRONIZING:
597 self.state = self.SYNCHRONIZING
598 self.window.deactivate()
601 if self.state == self.READY:
603 self.state = self.READY
604 self.window.activate()
606 def update_balance(self):
607 conf_balance, unconf_balance = self.wallet.get_balance()
608 balance = D(conf_balance + unconf_balance)
609 self.window.set_balances(balance)
611 def update_completions(self):
613 for addr, label in self.wallet.labels.items():
614 if addr in self.wallet.addressbook:
615 completions.append("%s <%s>" % (label, addr))
616 completions = completions + self.wallet.aliases.keys()
617 self.window.update_completions(completions)
619 if __name__ == "__main__":
620 app = QApplication(sys.argv)
621 with open(rsrc("style.css")) as style_file:
622 app.setStyleSheet(style_file.read())
624 sys.exit(app.exec_())