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 self.send_button = QPushButton(_("&Send"))
163 self.send_button.setObjectName("send_button")
164 self.send_button.setDisabled(True);
165 self.connect(self.send_button, SIGNAL("clicked()"), self.send)
167 main_layout = QGridLayout(self)
169 main_layout.addWidget(self.balance_label, 0, 0)
170 main_layout.addWidget(self.receive_button, 0, 1)
172 main_layout.addWidget(self.address_input, 1, 0, 1, -1)
174 main_layout.addWidget(self.amount_input, 2, 0)
175 main_layout.addWidget(self.send_button, 2, 1)
178 electrum_menu = menubar.addMenu(_("&Electrum"))
179 #electrum_menu.addMenu(_("&Servers"))
180 #electrum_menu.addSeparator()
181 electrum_menu.addAction(_("&Quit"))
183 view_menu = menubar.addMenu(_("&View"))
184 expert_gui = view_menu.addAction(_("&Pro Mode"))
185 self.connect(expert_gui, SIGNAL("triggered()"), expand_callback)
186 #view_menu.addMenu(_("&Themes"))
187 #view_menu.addSeparator()
188 #view_menu.addAction(_("Show History"))
190 #settings_menu = menubar.addMenu(_("&Settings"))
191 #settings_menu.addAction(_("&Configure Electrum"))
193 help_menu = menubar.addMenu(_("&Help"))
194 help_menu.addAction(_("&Contents"))
195 help_menu.addSeparator()
196 help_menu.addAction(_("&Report Bug"))
197 help_menu.addAction(_("&About"))
198 main_layout.setMenuBar(menubar)
200 quit_shortcut = QShortcut(QKeySequence("Ctrl+Q"), self)
201 self.connect(quit_shortcut, SIGNAL("activated()"), self.close)
202 close_shortcut = QShortcut(QKeySequence("Ctrl+W"), self)
203 self.connect(close_shortcut, SIGNAL("activated()"), self.close)
205 self.setWindowIcon(QIcon(":electrum.png"))
206 self.setWindowTitle("Electrum")
207 self.setWindowFlags(Qt.Window|Qt.MSWindowsFixedSizeDialogHint)
208 self.layout().setSizeConstraint(QLayout.SetFixedSize)
209 self.setObjectName("main_window")
212 def recompute_style(self):
213 qApp.style().unpolish(self)
214 qApp.style().polish(self)
216 def closeEvent(self, event):
217 super(MiniWindow, self).closeEvent(event)
220 def set_payment_fields(self, dest_address, amount):
221 self.address_input.setText(dest_address)
222 self.address_field_changed(dest_address)
223 self.amount_input.setText(amount)
228 def deactivate(self):
231 def set_quote_currency(self, currency):
232 assert currency in self.quote_currencies
233 self.quote_currencies.remove(currency)
234 self.quote_currencies = [currency] + self.quote_currencies
235 self.refresh_balance()
237 def change_quote_currency(self):
238 self.quote_currencies = \
239 self.quote_currencies[1:] + self.quote_currencies[0:1]
240 self.actuator.set_config_currency(self.quote_currencies[0])
241 self.refresh_balance()
243 def refresh_balance(self):
244 if self.btc_balance is None:
245 # Price has been discovered before wallet has been loaded
246 # and server connect... so bail.
248 self.set_balances(self.btc_balance)
249 self.amount_input_changed(self.amount_input.text())
251 def set_balances(self, btc_balance):
252 self.btc_balance = btc_balance
253 quote_text = self.create_quote_text(btc_balance)
255 quote_text = "(%s)" % quote_text
256 btc_balance = "%.2f" % (btc_balance / bitcoin(1))
257 self.balance_label.set_balance_text(btc_balance, quote_text)
258 self.setWindowTitle("Electrum - %s BTC" % btc_balance)
260 def amount_input_changed(self, amount_text):
261 self.check_button_status()
264 amount = D(str(amount_text))
265 except decimal.InvalidOperation:
266 self.balance_label.show_balance()
268 quote_text = self.create_quote_text(amount * bitcoin(1))
270 self.balance_label.set_amount_text(quote_text)
271 self.balance_label.show_amount()
273 self.balance_label.show_balance()
275 def create_quote_text(self, btc_balance):
276 quote_currency = self.quote_currencies[0]
277 quote_balance = self.exchanger.exchange(btc_balance, quote_currency)
278 if quote_balance is None:
281 quote_text = "%.2f %s" % ((quote_balance / bitcoin(1)),
286 if self.actuator.send(self.address_input.text(),
287 self.amount_input.text(), self):
288 self.address_input.setText("")
289 self.amount_input.setText("")
291 def check_button_status(self):
292 if (self.address_input.property("isValid") is True and
293 len(self.amount_input.text()) > 0):
294 self.send_button.setDisabled(False)
296 self.send_button.setDisabled(True)
298 def address_field_changed(self, address):
299 if self.actuator.is_valid(address):
300 self.check_button_status()
301 self.address_input.setProperty("isValid", True)
302 self.recompute_style(self.address_input)
304 self.send_button.setDisabled(True)
305 self.address_input.setProperty("isValid", False)
306 self.recompute_style(self.address_input)
308 if len(address) == 0:
309 self.address_input.setProperty("isValid", None)
310 self.recompute_style(self.address_input)
312 def recompute_style(self, element):
313 self.style().unpolish(element)
314 self.style().polish(element)
316 def copy_address(self):
317 receive_popup = ReceivePopup(self.receive_button)
318 self.actuator.copy_address(receive_popup)
320 def update_completions(self, completions):
321 self.address_completions.setStringList(completions)
324 self.actuator.acceptbit(self.quote_currencies[0])
326 def show_about(self):
327 QMessageBox.about(self, "Electrum",
328 _("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."))
330 def show_report_bug(self):
331 QMessageBox.information(self, "Electrum - " + _("Reporting Bugs"),
332 _("Email bug reports to %s") % "genjix" + "@" + "riseup.net")
334 class BalanceLabel(QLabel):
340 def __init__(self, change_quote_currency, parent=None):
341 super(QLabel, self).__init__(_("Connecting..."), parent)
342 self.change_quote_currency = change_quote_currency
343 self.state = self.SHOW_CONNECTING
344 self.balance_text = ""
345 self.amount_text = ""
347 def mousePressEvent(self, event):
348 if self.state != self.SHOW_CONNECTING:
349 self.change_quote_currency()
351 def set_balance_text(self, btc_balance, quote_text):
352 if self.state == self.SHOW_CONNECTING:
353 self.state = self.SHOW_BALANCE
354 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)
355 if self.state == self.SHOW_BALANCE:
356 self.setText(self.balance_text)
358 def set_amount_text(self, quote_text):
359 self.amount_text = "<span style='font-size: 10pt'>%s</span>" % quote_text
360 if self.state == self.SHOW_AMOUNT:
361 self.setText(self.amount_text)
363 def show_balance(self):
364 if self.state == self.SHOW_AMOUNT:
365 self.state = self.SHOW_BALANCE
366 self.setText(self.balance_text)
368 def show_amount(self):
369 if self.state == self.SHOW_BALANCE:
370 self.state = self.SHOW_AMOUNT
371 self.setText(self.amount_text)
373 def ok_cancel_buttons(dialog):
374 row_layout = QHBoxLayout()
375 row_layout.addStretch(1)
376 ok_button = QPushButton(_("OK"))
377 row_layout.addWidget(ok_button)
378 ok_button.clicked.connect(dialog.accept)
379 cancel_button = QPushButton(_("Cancel"))
380 row_layout.addWidget(cancel_button)
381 cancel_button.clicked.connect(dialog.reject)
384 class PasswordDialog(QDialog):
386 def __init__(self, parent):
387 super(QDialog, self).__init__(parent)
391 self.password_input = QLineEdit()
392 self.password_input.setEchoMode(QLineEdit.Password)
394 main_layout = QVBoxLayout(self)
395 message = _('Please enter your password')
396 main_layout.addWidget(QLabel(message))
400 grid.addWidget(QLabel(_('Password')), 1, 0)
401 grid.addWidget(self.password_input, 1, 1)
402 main_layout.addLayout(grid)
404 main_layout.addLayout(ok_cancel_buttons(self))
405 self.setLayout(main_layout)
410 return unicode(self.password_input.text())
412 class ReceivePopup(QDialog):
414 def leaveEvent(self, event):
417 def setup(self, address):
418 label = QLabel(_("Copied your Bitcoin address to the clipboard!"))
419 address_display = QLineEdit(address)
420 address_display.setReadOnly(True)
421 resize_line_edit_width(address_display, address)
423 main_layout = QVBoxLayout(self)
424 main_layout.addWidget(label)
425 main_layout.addWidget(address_display)
427 self.setMouseTracking(True)
428 self.setWindowTitle("Electrum - " + _("Receive Bitcoin payment"))
429 self.setWindowFlags(Qt.Window|Qt.FramelessWindowHint|Qt.MSWindowsFixedSizeDialogHint)
430 self.layout().setSizeConstraint(QLayout.SetFixedSize)
431 #self.setFrameStyle(QFrame.WinPanel|QFrame.Raised)
432 #self.setAlignment(Qt.AlignCenter)
435 parent = self.parent()
436 top_left_pos = parent.mapToGlobal(parent.rect().bottomLeft())
437 self.move(top_left_pos)
438 center_mouse_pos = self.mapToGlobal(self.rect().center())
439 QCursor.setPos(center_mouse_pos)
444 def __init__(self, wallet):
447 def set_configured_currency(self, set_quote_currency):
448 currency = self.wallet.conversion_currency
449 # currency can be none when Electrum is used for the first
450 # time and no setting has been created yet.
451 if currency is not None:
452 set_quote_currency(currency)
454 def set_config_currency(self, conversion_currency):
455 self.wallet.conversion_currency = conversion_currency
457 def copy_address(self, receive_popup):
458 addrs = [addr for addr in self.wallet.all_addresses()
459 if not self.wallet.is_change(addr)]
460 # Select most recent addresses from gap limit
461 addrs = addrs[-self.wallet.gap_limit:]
462 copied_address = random.choice(addrs)
463 qApp.clipboard().setText(copied_address)
464 receive_popup.setup(copied_address)
465 receive_popup.popup()
467 def send(self, address, amount, parent_window):
468 dest_address = self.fetch_destination(address)
470 if dest_address is None or not self.wallet.is_valid(dest_address):
471 QMessageBox.warning(parent_window, _('Error'),
472 _('Invalid Bitcoin Address') + ':\n' + address, _('OK'))
475 convert_amount = lambda amount: \
476 int(D(unicode(amount)) * bitcoin(1))
477 amount = convert_amount(amount)
479 if self.wallet.use_encryption:
480 password_dialog = PasswordDialog(parent_window)
481 password = password_dialog.run()
489 if amount < bitcoin(1) / 10:
491 fee = bitcoin(1) / 1000
494 tx = self.wallet.mktx(dest_address, amount, "", password, fee)
495 except BaseException as error:
496 QMessageBox.warning(parent_window, _('Error'), str(error), _('OK'))
499 status, message = self.wallet.sendtx(tx)
501 QMessageBox.warning(parent_window, _('Error'), message, _('OK'))
504 QMessageBox.information(parent_window, '',
505 _('Payment sent.') + '\n' + message, _('OK'))
508 def fetch_destination(self, address):
509 recipient = unicode(address).strip()
512 match1 = re.match("^(|([\w\-\.]+)@)((\w[\w\-]+\.)+[\w\-]+)$",
515 # label or alias, with address in brackets
516 match2 = re.match("(.*?)\s*\<([1-9A-HJ-NP-Za-km-z]{26,})\>",
521 self.wallet.get_alias(recipient, True,
522 self.show_message, self.question)
525 return match2.group(2)
529 def is_valid(self, address):
530 return self.wallet.is_valid(address)
532 def acceptbit(self, currency):
533 master_pubkey = self.wallet.master_public_key.encode("hex")
534 url = "http://acceptbit.com/mpk/%s/%s" % (master_pubkey, currency)
537 class MiniDriver(QObject):
544 def __init__(self, wallet, window):
545 super(QObject, self).__init__()
550 self.wallet.register_callback(self.update_callback)
555 self.connect(self, SIGNAL("updatesignal()"), self.update)
556 self.update_callback()
558 # This is a hack to workaround that Qt does not like changing the
559 # window properties from this other thread before the runloop has
561 def update_callback(self):
562 self.emit(SIGNAL("updatesignal()"))
565 if not self.wallet.interface:
567 elif not self.wallet.interface.is_connected:
569 elif not self.wallet.blocks == -1:
571 elif not self.wallet.is_up_to_date:
576 if self.wallet.up_to_date:
577 self.update_balance()
578 self.update_completions()
580 def initializing(self):
581 if self.state == self.INITIALIZING:
583 self.state = self.INITIALIZING
584 self.window.deactivate()
586 def connecting(self):
587 if self.state == self.CONNECTING:
589 self.state = self.CONNECTING
590 self.window.deactivate()
592 def synchronizing(self):
593 if self.state == self.SYNCHRONIZING:
595 self.state = self.SYNCHRONIZING
596 self.window.deactivate()
599 if self.state == self.READY:
601 self.state = self.READY
602 self.window.activate()
604 def update_balance(self):
605 conf_balance, unconf_balance = self.wallet.get_balance()
606 balance = D(conf_balance + unconf_balance)
607 self.window.set_balances(balance)
609 def update_completions(self):
611 for addr, label in self.wallet.labels.items():
612 if addr in self.wallet.addressbook:
613 completions.append("%s <%s>" % (label, addr))
614 completions = completions + self.wallet.aliases.keys()
615 self.window.update_completions(completions)
617 if __name__ == "__main__":
618 app = QApplication(sys.argv)
619 with open(rsrc("style.css")) as style_file:
620 app.setStyleSheet(style_file.read())
622 sys.exit(app.exec_())