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
18 import lib.gui_qt as gui_qt
20 import electrum.gui_qt as gui_qt
22 bitcoin = lambda v: v * 100000000
24 def IconButton(filename, parent=None):
25 pixmap = QPixmap(filename)
27 return QPushButton(icon, "", parent)
32 self.emit(SIGNAL('timersignal'))
35 def resize_line_edit_width(line_edit, text_input):
36 metrics = QFontMetrics(qApp.font())
37 # Create an extra character to add some space on the end
39 line_edit.setMinimumWidth(metrics.width(text_input))
43 prefix_path = os.path.dirname(sys.argv[0])
44 local_data = os.path.join(prefix_path, "data")
45 if os.path.exists(os.path.join(local_data, "style.css")):
48 data_dir = appdata_dir()
49 QDir.setCurrent(data_dir)
53 def __init__(self, wallet):
55 self.app = QApplication(sys.argv)
56 # Should probably not modify the current path but instead
57 # change the behaviour of rsrc(...)
58 self.old_path = QDir.currentPath()
60 with open(rsrc("style.css")) as style_file:
61 self.app.setStyleSheet(style_file.read())
64 actuator = MiniActuator(self.wallet)
65 self.mini = MiniWindow(actuator, self.expand)
66 driver = MiniDriver(self.wallet, self.mini)
68 # Reset path back to original value now that loading the GUI
70 QDir.setCurrent(self.old_path)
77 self.expert = gui_qt.ElectrumWindow(self.wallet)
78 self.expert.app = self.app
79 self.expert.connect_slots(timer)
80 self.expert.update_wallet()
88 def set_url(self, url):
89 payto, amount, label, message, signature, identity, url = \
90 self.wallet.parse_url(url, self.show_message, self.show_question)
91 self.mini.set_payment_fields(payto, amount)
93 def show_message(self, message):
94 QMessageBox.information(self.mini, _("Message"), message, _("OK"))
96 def show_question(self, message):
97 choice = QMessageBox.question(self.mini, _("Message"), message,
98 QMessageBox.Yes|QMessageBox.No,
100 return choice == QMessageBox.Yes
102 def restore_or_create(self):
103 qt_gui_object = gui_qt.ElectrumGui(self.wallet, self.app)
104 return qt_gui_object.restore_or_create()
106 class MiniWindow(QDialog):
108 def __init__(self, actuator, expand_callback):
109 super(MiniWindow, self).__init__()
111 self.actuator = actuator
113 self.btc_balance = None
114 self.quote_currencies = ["EUR", "USD", "GBP"]
115 self.actuator.set_configured_currency(self.set_quote_currency)
116 self.exchanger = exchange_rate.Exchanger(self)
117 # Needed because price discovery is done in a different thread
118 # which needs to be sent back to this main one to update the GUI
119 self.connect(self, SIGNAL("refresh_balance()"), self.refresh_balance)
121 self.balance_label = BalanceLabel(self.change_quote_currency)
122 self.balance_label.setObjectName("balance_label")
124 self.receive_button = QPushButton(_("&Receive"))
125 self.receive_button.setObjectName("receive_button")
126 self.receive_button.setDefault(True)
127 self.connect(self.receive_button, SIGNAL("clicked()"), self.copy_address)
129 # Bitcoin address code
130 self.address_input = QLineEdit()
131 self.address_input.setPlaceholderText(_("Enter a Bitcoin address..."))
132 self.address_input.setObjectName("address_input")
135 self.connect(self.address_input, SIGNAL("textEdited(QString)"), self.address_field_changed)
136 resize_line_edit_width(self.address_input, "1BtaFUr3qVvAmwrsuDuu5zk6e4s2rxd2Gy")
138 self.address_completions = QStringListModel()
139 address_completer = QCompleter(self.address_input)
140 address_completer.setCaseSensitivity(False)
141 address_completer.setModel(self.address_completions)
142 self.address_input.setCompleter(address_completer)
144 address_layout = QHBoxLayout()
145 address_layout.addWidget(self.address_input)
147 self.amount_input = QLineEdit()
148 self.amount_input.setPlaceholderText(_("... and amount"))
149 self.amount_input.setObjectName("amount_input")
150 # This is changed according to the user's displayed balance
151 self.amount_validator = QDoubleValidator(self.amount_input)
152 self.amount_validator.setNotation(QDoubleValidator.StandardNotation)
153 self.amount_validator.setDecimals(8)
154 self.amount_input.setValidator(self.amount_validator)
156 # This removes the very ugly OSX highlighting, please leave this in :D
157 self.address_input.setAttribute(Qt.WA_MacShowFocusRect, 0)
158 self.amount_input.setAttribute(Qt.WA_MacShowFocusRect, 0)
160 self.connect(self.amount_input, SIGNAL("textChanged(QString)"),
161 self.amount_input_changed)
163 self.send_button = QPushButton(_("&Send"))
164 self.send_button.setObjectName("send_button")
165 self.send_button.setDisabled(True);
166 self.connect(self.send_button, SIGNAL("clicked()"), self.send)
168 main_layout = QGridLayout(self)
170 main_layout.addWidget(self.balance_label, 0, 0)
171 main_layout.addWidget(self.receive_button, 0, 1)
173 main_layout.addWidget(self.address_input, 1, 0, 1, -1)
175 main_layout.addWidget(self.amount_input, 2, 0)
176 main_layout.addWidget(self.send_button, 2, 1)
178 self.history_list = history_widget.HistoryWidget()
179 self.history_list.hide()
180 main_layout.addWidget(self.history_list, 3, 0, 1, -1)
183 electrum_menu = menubar.addMenu(_("&Bitcoin"))
184 electrum_menu.addMenu(_("&Servers"))
185 electrum_menu.addSeparator()
186 electrum_menu.addAction(_("&Quit"))
188 view_menu = menubar.addMenu(_("&View"))
189 expert_gui = view_menu.addAction(_("&Pro Mode"))
190 self.connect(expert_gui, SIGNAL("triggered()"), expand_callback)
191 view_menu.addMenu(_("&Themes"))
192 view_menu.addSeparator()
193 show_history = view_menu.addAction(_("Show History"))
194 show_history.setCheckable(True)
195 self.connect(show_history, SIGNAL("toggled(bool)"), self.show_history)
197 settings_menu = menubar.addMenu(_("&Settings"))
198 settings_menu.addAction(_("&Configure Electrum"))
200 help_menu = menubar.addMenu(_("&Help"))
201 help_menu.addAction(_("&Contents"))
202 help_menu.addSeparator()
203 help_menu.addAction(_("&Report Bug"))
204 help_menu.addAction(_("&About"))
205 main_layout.setMenuBar(menubar)
207 quit_shortcut = QShortcut(QKeySequence("Ctrl+Q"), self)
208 self.connect(quit_shortcut, SIGNAL("activated()"), self.close)
209 close_shortcut = QShortcut(QKeySequence("Ctrl+W"), self)
210 self.connect(close_shortcut, SIGNAL("activated()"), self.close)
212 self.setWindowIcon(QIcon(":electrum.png"))
213 self.setWindowTitle("Electrum")
214 self.setWindowFlags(Qt.Window|Qt.MSWindowsFixedSizeDialogHint)
215 self.layout().setSizeConstraint(QLayout.SetFixedSize)
216 self.setObjectName("main_window")
219 def recompute_style(self):
220 qApp.style().unpolish(self)
221 qApp.style().polish(self)
223 def closeEvent(self, event):
224 super(MiniWindow, self).closeEvent(event)
227 def set_payment_fields(self, dest_address, amount):
228 self.address_input.setText(dest_address)
229 self.address_field_changed(dest_address)
230 self.amount_input.setText(amount)
235 def deactivate(self):
238 def set_quote_currency(self, currency):
239 assert currency in self.quote_currencies
240 self.quote_currencies.remove(currency)
241 self.quote_currencies = [currency] + self.quote_currencies
242 self.refresh_balance()
244 def change_quote_currency(self):
245 self.quote_currencies = \
246 self.quote_currencies[1:] + self.quote_currencies[0:1]
247 self.actuator.set_config_currency(self.quote_currencies[0])
248 self.refresh_balance()
250 def refresh_balance(self):
251 if self.btc_balance is None:
252 # Price has been discovered before wallet has been loaded
253 # and server connect... so bail.
255 self.set_balances(self.btc_balance)
256 self.amount_input_changed(self.amount_input.text())
258 def set_balances(self, btc_balance):
259 self.btc_balance = btc_balance
260 quote_text = self.create_quote_text(btc_balance)
262 quote_text = "(%s)" % quote_text
263 btc_balance = "%.2f" % (btc_balance / bitcoin(1))
264 self.balance_label.set_balance_text(btc_balance, quote_text)
265 self.setWindowTitle("Electrum - %s BTC" % btc_balance)
267 def amount_input_changed(self, amount_text):
268 self.check_button_status()
271 amount = D(str(amount_text))
272 except decimal.InvalidOperation:
273 self.balance_label.show_balance()
275 quote_text = self.create_quote_text(amount * bitcoin(1))
277 self.balance_label.set_amount_text(quote_text)
278 self.balance_label.show_amount()
280 self.balance_label.show_balance()
282 def create_quote_text(self, btc_balance):
283 quote_currency = self.quote_currencies[0]
284 quote_balance = self.exchanger.exchange(btc_balance, quote_currency)
285 if quote_balance is None:
288 quote_text = "%.2f %s" % ((quote_balance / bitcoin(1)),
293 if self.actuator.send(self.address_input.text(),
294 self.amount_input.text(), self):
295 self.address_input.setText("")
296 self.amount_input.setText("")
298 def check_button_status(self):
299 if (self.address_input.property("isValid") is True and
300 len(self.amount_input.text()) > 0):
301 self.send_button.setDisabled(False)
303 self.send_button.setDisabled(True)
305 def address_field_changed(self, address):
306 if self.actuator.is_valid(address):
307 self.check_button_status()
308 self.address_input.setProperty("isValid", True)
309 self.recompute_style(self.address_input)
311 self.send_button.setDisabled(True)
312 self.address_input.setProperty("isValid", False)
313 self.recompute_style(self.address_input)
315 if len(address) == 0:
316 self.address_input.setProperty("isValid", None)
317 self.recompute_style(self.address_input)
319 def recompute_style(self, element):
320 self.style().unpolish(element)
321 self.style().polish(element)
323 def copy_address(self):
324 receive_popup = ReceivePopup(self.receive_button)
325 self.actuator.copy_address(receive_popup)
327 def update_completions(self, completions):
328 self.address_completions.setStringList(completions)
330 def update_history(self, tx_history):
331 for tx in tx_history[-10:]:
332 address = tx["dest_address"]
333 amount = D(tx["value"]) / 10**8
334 self.history_list.append(address, amount)
337 self.actuator.acceptbit(self.quote_currencies[0])
339 def show_about(self):
340 QMessageBox.about(self, "Electrum",
341 _("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."))
343 def show_report_bug(self):
344 QMessageBox.information(self, "Electrum - " + _("Reporting Bugs"),
345 _("Email bug reports to %s") % "genjix" + "@" + "riseup.net")
347 def show_history(self, toggle_state):
349 self.history_list.show()
351 self.history_list.hide()
353 class BalanceLabel(QLabel):
359 def __init__(self, change_quote_currency, parent=None):
360 super(QLabel, self).__init__(_("Connecting..."), parent)
361 self.change_quote_currency = change_quote_currency
362 self.state = self.SHOW_CONNECTING
363 self.balance_text = ""
364 self.amount_text = ""
366 def mousePressEvent(self, event):
367 if self.state != self.SHOW_CONNECTING:
368 self.change_quote_currency()
370 def set_balance_text(self, btc_balance, quote_text):
371 if self.state == self.SHOW_CONNECTING:
372 self.state = self.SHOW_BALANCE
373 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)
374 if self.state == self.SHOW_BALANCE:
375 self.setText(self.balance_text)
377 def set_amount_text(self, quote_text):
378 self.amount_text = "<span style='font-size: 10pt'>%s</span>" % quote_text
379 if self.state == self.SHOW_AMOUNT:
380 self.setText(self.amount_text)
382 def show_balance(self):
383 if self.state == self.SHOW_AMOUNT:
384 self.state = self.SHOW_BALANCE
385 self.setText(self.balance_text)
387 def show_amount(self):
388 if self.state == self.SHOW_BALANCE:
389 self.state = self.SHOW_AMOUNT
390 self.setText(self.amount_text)
392 def ok_cancel_buttons(dialog):
393 row_layout = QHBoxLayout()
394 row_layout.addStretch(1)
395 ok_button = QPushButton(_("OK"))
396 row_layout.addWidget(ok_button)
397 ok_button.clicked.connect(dialog.accept)
398 cancel_button = QPushButton(_("Cancel"))
399 row_layout.addWidget(cancel_button)
400 cancel_button.clicked.connect(dialog.reject)
403 class PasswordDialog(QDialog):
405 def __init__(self, parent):
406 super(QDialog, self).__init__(parent)
410 self.password_input = QLineEdit()
411 self.password_input.setEchoMode(QLineEdit.Password)
413 main_layout = QVBoxLayout(self)
414 message = _('Please enter your password')
415 main_layout.addWidget(QLabel(message))
419 grid.addWidget(QLabel(_('Password')), 1, 0)
420 grid.addWidget(self.password_input, 1, 1)
421 main_layout.addLayout(grid)
423 main_layout.addLayout(ok_cancel_buttons(self))
424 self.setLayout(main_layout)
429 return unicode(self.password_input.text())
431 class ReceivePopup(QDialog):
433 def leaveEvent(self, event):
436 def setup(self, address):
437 label = QLabel(_("Copied your Bitcoin address to the clipboard!"))
438 address_display = QLineEdit(address)
439 address_display.setReadOnly(True)
440 resize_line_edit_width(address_display, address)
442 main_layout = QVBoxLayout(self)
443 main_layout.addWidget(label)
444 main_layout.addWidget(address_display)
446 self.setMouseTracking(True)
447 self.setWindowTitle("Electrum - " + _("Receive Bitcoin payment"))
448 self.setWindowFlags(Qt.Window|Qt.FramelessWindowHint|Qt.MSWindowsFixedSizeDialogHint)
449 self.layout().setSizeConstraint(QLayout.SetFixedSize)
450 #self.setFrameStyle(QFrame.WinPanel|QFrame.Raised)
451 #self.setAlignment(Qt.AlignCenter)
454 parent = self.parent()
455 top_left_pos = parent.mapToGlobal(parent.rect().bottomLeft())
456 self.move(top_left_pos)
457 center_mouse_pos = self.mapToGlobal(self.rect().center())
458 QCursor.setPos(center_mouse_pos)
463 def __init__(self, wallet):
466 def set_configured_currency(self, set_quote_currency):
467 currency = self.wallet.conversion_currency
468 # currency can be none when Electrum is used for the first
469 # time and no setting has been created yet.
470 if currency is not None:
471 set_quote_currency(currency)
473 def set_config_currency(self, conversion_currency):
474 self.wallet.conversion_currency = conversion_currency
476 def copy_address(self, receive_popup):
477 addrs = [addr for addr in self.wallet.all_addresses()
478 if not self.wallet.is_change(addr)]
479 # Select most recent addresses from gap limit
480 addrs = addrs[-self.wallet.gap_limit:]
481 copied_address = random.choice(addrs)
482 qApp.clipboard().setText(copied_address)
483 receive_popup.setup(copied_address)
484 receive_popup.popup()
486 def send(self, address, amount, parent_window):
487 dest_address = self.fetch_destination(address)
489 if dest_address is None or not self.wallet.is_valid(dest_address):
490 QMessageBox.warning(parent_window, _('Error'),
491 _('Invalid Bitcoin Address') + ':\n' + address, _('OK'))
494 convert_amount = lambda amount: \
495 int(D(unicode(amount)) * bitcoin(1))
496 amount = convert_amount(amount)
498 if self.wallet.use_encryption:
499 password_dialog = PasswordDialog(parent_window)
500 password = password_dialog.run()
508 if amount < bitcoin(1) / 10:
510 fee = bitcoin(1) / 1000
513 tx = self.wallet.mktx(dest_address, amount, "", password, fee)
514 except BaseException as error:
515 QMessageBox.warning(parent_window, _('Error'), str(error), _('OK'))
518 status, message = self.wallet.sendtx(tx)
520 QMessageBox.warning(parent_window, _('Error'), message, _('OK'))
523 QMessageBox.information(parent_window, '',
524 _('Payment sent.') + '\n' + message, _('OK'))
527 def fetch_destination(self, address):
528 recipient = unicode(address).strip()
531 match1 = re.match("^(|([\w\-\.]+)@)((\w[\w\-]+\.)+[\w\-]+)$",
534 # label or alias, with address in brackets
535 match2 = re.match("(.*?)\s*\<([1-9A-HJ-NP-Za-km-z]{26,})\>",
540 self.wallet.get_alias(recipient, True,
541 self.show_message, self.question)
544 return match2.group(2)
548 def is_valid(self, address):
549 return self.wallet.is_valid(address)
551 def acceptbit(self, currency):
552 master_pubkey = self.wallet.master_public_key.encode("hex")
553 url = "http://acceptbit.com/mpk/%s/%s" % (master_pubkey, currency)
556 class MiniDriver(QObject):
563 def __init__(self, wallet, window):
564 super(QObject, self).__init__()
569 self.wallet.register_callback(self.update_callback)
574 self.connect(self, SIGNAL("updatesignal()"), self.update)
575 self.update_callback()
577 # This is a hack to workaround that Qt does not like changing the
578 # window properties from this other thread before the runloop has
580 def update_callback(self):
581 self.emit(SIGNAL("updatesignal()"))
584 if not self.wallet.interface:
586 elif not self.wallet.interface.is_connected:
588 elif not self.wallet.blocks == -1:
590 elif not self.wallet.is_up_to_date:
595 if self.wallet.up_to_date:
596 self.update_balance()
597 self.update_completions()
598 self.update_history()
600 def initializing(self):
601 if self.state == self.INITIALIZING:
603 self.state = self.INITIALIZING
604 self.window.deactivate()
606 def connecting(self):
607 if self.state == self.CONNECTING:
609 self.state = self.CONNECTING
610 self.window.deactivate()
612 def synchronizing(self):
613 if self.state == self.SYNCHRONIZING:
615 self.state = self.SYNCHRONIZING
616 self.window.deactivate()
619 if self.state == self.READY:
621 self.state = self.READY
622 self.window.activate()
624 def update_balance(self):
625 conf_balance, unconf_balance = self.wallet.get_balance()
626 balance = D(conf_balance + unconf_balance)
627 self.window.set_balances(balance)
629 def update_completions(self):
631 for addr, label in self.wallet.labels.items():
632 if addr in self.wallet.addressbook:
633 completions.append("%s <%s>" % (label, addr))
634 completions = completions + self.wallet.aliases.keys()
635 self.window.update_completions(completions)
637 def update_history(self):
638 tx_history = self.wallet.get_tx_history()
639 self.window.update_history(tx_history)
641 if __name__ == "__main__":
642 app = QApplication(sys.argv)
643 with open(rsrc("style.css")) as style_file:
644 app.setStyleSheet(style_file.read())
646 sys.exit(app.exec_())