Added pretty errors when pyqt is not found or qt is not the right version
[electrum-nvc.git] / lib / gui_lite.py
1 import sys
2
3 try:
4   from PyQt4.QtCore import *
5   from PyQt4.QtGui import *
6 except ImportError:
7   print "You need to have PyQT installed to run Electrum"
8   print "If you have pip installed try 'sudo pip install pyqt' if you are on Debian/Ubuntu try 'sudo apt-get install python-qt4'"
9   sys.exit(1)
10
11 from decimal import Decimal as D
12 from util import appdata_dir, get_resource_path as rsrc
13 from i18n import _
14 import decimal
15 import exchange_rate
16 import os.path
17 import random
18 import re
19 import time
20 import wallet
21 import webbrowser
22 import history_widget
23
24 try:
25     import lib.gui_qt as gui_qt
26 except ImportError:
27     import electrum.gui_qt as gui_qt
28
29 bitcoin = lambda v: v * 100000000
30
31 def IconButton(filename, parent=None):
32     pixmap = QPixmap(filename)
33     icon = QIcon(pixmap)
34     return QPushButton(icon, "", parent)
35
36 class Timer(QThread):
37     def run(self):
38         while True:
39             self.emit(SIGNAL('timersignal'))
40             time.sleep(0.5)
41
42 def resize_line_edit_width(line_edit, text_input):
43     metrics = QFontMetrics(qApp.font())
44     # Create an extra character to add some space on the end
45     text_input += "A"
46     line_edit.setMinimumWidth(metrics.width(text_input))
47
48 def cd_data_dir():
49     assert sys.argv
50     prefix_path = os.path.dirname(sys.argv[0])
51     local_data = os.path.join(prefix_path, "data")
52     if os.path.exists(os.path.join(local_data, "style.css")):
53         data_dir = local_data
54     else:
55         data_dir = appdata_dir()
56     QDir.setCurrent(data_dir)
57
58 class ElectrumGui:
59
60     def __init__(self, wallet):
61         qtVersion = qVersion()
62         if not(int(qtVersion[0]) >= 4 and int(qtVersion[2]) >= 7):
63           print "Sorry, Electrum requires Qt >= 4.7 to run"
64           print "Check your distributions packages or download it at http://qt.nokia.com/downloads"
65           sys.exit(0)
66           
67         self.wallet = wallet
68         self.app = QApplication(sys.argv)
69         # Should probably not modify the current path but instead
70         # change the behaviour of rsrc(...)
71         self.old_path = QDir.currentPath()
72         cd_data_dir()
73         with open(rsrc("style.css")) as style_file:
74             self.app.setStyleSheet(style_file.read())
75
76     def main(self, url):
77         actuator = MiniActuator(self.wallet)
78         self.mini = MiniWindow(actuator, self.expand)
79         driver = MiniDriver(self.wallet, self.mini)
80
81         # Reset path back to original value now that loading the GUI
82         # is completed.
83         QDir.setCurrent(self.old_path)
84
85         if url:
86             self.set_url(url)
87
88         timer = Timer()
89         timer.start()
90         self.expert = gui_qt.ElectrumWindow(self.wallet)
91         self.expert.app = self.app
92         self.expert.connect_slots(timer)
93         self.expert.update_wallet()
94
95         self.app.exec_()
96
97     def expand(self):
98         self.mini.hide()
99         self.expert.show()
100
101     def set_url(self, url):
102         payto, amount, label, message, signature, identity, url = \
103             self.wallet.parse_url(url, self.show_message, self.show_question)
104         self.mini.set_payment_fields(payto, amount)
105
106     def show_message(self, message):
107         QMessageBox.information(self.mini, _("Message"), message, _("OK"))
108
109     def show_question(self, message):
110         choice = QMessageBox.question(self.mini, _("Message"), message,
111                                       QMessageBox.Yes|QMessageBox.No,
112                                       QMessageBox.No)
113         return choice == QMessageBox.Yes
114
115     def restore_or_create(self):
116         qt_gui_object = gui_qt.ElectrumGui(self.wallet, self.app)
117         return qt_gui_object.restore_or_create()
118
119 class MiniWindow(QDialog):
120
121     def __init__(self, actuator, expand_callback):
122         super(MiniWindow, self).__init__()
123
124         self.actuator = actuator
125
126         self.btc_balance = None
127         self.quote_currencies = ["EUR", "USD", "GBP"]
128         self.actuator.set_configured_currency(self.set_quote_currency)
129         self.exchanger = exchange_rate.Exchanger(self)
130         # Needed because price discovery is done in a different thread
131         # which needs to be sent back to this main one to update the GUI
132         self.connect(self, SIGNAL("refresh_balance()"), self.refresh_balance)
133
134         self.balance_label = BalanceLabel(self.change_quote_currency)
135         self.balance_label.setObjectName("balance_label")
136
137         self.receive_button = QPushButton(_("&Receive"))
138         self.receive_button.setObjectName("receive_button")
139         self.receive_button.setDefault(True)
140         self.receive_button.clicked.connect(self.copy_address)
141
142         # Bitcoin address code
143         self.address_input = QLineEdit()
144         self.address_input.setPlaceholderText(_("Enter a Bitcoin address..."))
145         self.address_input.setObjectName("address_input")
146
147
148         self.address_input.textEdited.connect(self.address_field_changed)
149         resize_line_edit_width(self.address_input,
150                                "1BtaFUr3qVvAmwrsuDuu5zk6e4s2rxd2Gy")
151
152         self.address_completions = QStringListModel()
153         address_completer = QCompleter(self.address_input)
154         address_completer.setCaseSensitivity(False)
155         address_completer.setModel(self.address_completions)
156         self.address_input.setCompleter(address_completer)
157
158         address_layout = QHBoxLayout()
159         address_layout.addWidget(self.address_input)
160
161         self.amount_input = QLineEdit()
162         self.amount_input.setPlaceholderText(_("... and amount"))
163         self.amount_input.setObjectName("amount_input")
164         # This is changed according to the user's displayed balance
165         self.amount_validator = QDoubleValidator(self.amount_input)
166         self.amount_validator.setNotation(QDoubleValidator.StandardNotation)
167         self.amount_validator.setDecimals(8)
168         self.amount_input.setValidator(self.amount_validator)
169
170         # This removes the very ugly OSX highlighting, please leave this in :D
171         self.address_input.setAttribute(Qt.WA_MacShowFocusRect, 0)
172         self.amount_input.setAttribute(Qt.WA_MacShowFocusRect, 0)
173         self.amount_input.textChanged.connect(self.amount_input_changed)
174
175         self.send_button = QPushButton(_("&Send"))
176         self.send_button.setObjectName("send_button")
177         self.send_button.setDisabled(True);
178         self.send_button.clicked.connect(self.send)
179
180         main_layout = QGridLayout(self)
181
182         main_layout.addWidget(self.balance_label, 0, 0)
183         main_layout.addWidget(self.receive_button, 0, 1)
184
185         main_layout.addWidget(self.address_input, 1, 0, 1, -1)
186
187         main_layout.addWidget(self.amount_input, 2, 0)
188         main_layout.addWidget(self.send_button, 2, 1)
189
190         self.history_list = history_widget.HistoryWidget()
191         self.history_list.setObjectName("history")
192         self.history_list.hide()
193         self.history_list.setAlternatingRowColors(True)
194         main_layout.addWidget(self.history_list, 3, 0, 1, -1)
195
196         menubar = QMenuBar()
197         electrum_menu = menubar.addMenu(_("&Bitcoin"))
198         self.servers_menu = electrum_menu.addMenu(_("&Servers"))
199         self.servers_menu.addAction(_("Foo"))
200         electrum_menu.addSeparator()
201         brain_seed = electrum_menu.addAction(_("&BrainWallet Info"))
202         brain_seed.triggered.connect(self.actuator.show_seed_dialog)
203         electrum_menu.addAction(_("&Quit"))
204
205         view_menu = menubar.addMenu(_("&View"))
206         expert_gui = view_menu.addAction(_("&Pro Mode"))
207         expert_gui.triggered.connect(expand_callback)
208         view_menu.addMenu(_("&Themes"))
209         view_menu.addSeparator()
210         show_history = view_menu.addAction(_("Show History"))
211         show_history.setCheckable(True)
212         show_history.toggled.connect(self.show_history)
213
214         settings_menu = menubar.addMenu(_("&Settings"))
215         settings_menu.addAction(_("&Configure Electrum"))
216         
217         help_menu = menubar.addMenu(_("&Help"))
218         the_website = help_menu.addAction(_("&Website"))
219         the_website.triggered.connect(self.the_website)
220         help_menu.addSeparator()
221         report_bug = help_menu.addAction(_("&Report Bug"))
222         report_bug.triggered.connect(self.show_report_bug)
223         show_about = help_menu.addAction(_("&About"))
224         show_about.triggered.connect(self.show_about)
225         main_layout.setMenuBar(menubar)
226
227         quit_shortcut = QShortcut(QKeySequence("Ctrl+Q"), self)
228         quit_shortcut.activated.connect(self.close)
229         close_shortcut = QShortcut(QKeySequence("Ctrl+W"), self)
230         close_shortcut.activated.connect(self.close)
231
232         self.setWindowIcon(QIcon(":electrum.png"))
233         self.setWindowTitle("Electrum")
234         self.setWindowFlags(Qt.Window|Qt.MSWindowsFixedSizeDialogHint)
235         self.layout().setSizeConstraint(QLayout.SetFixedSize)
236         self.setObjectName("main_window")
237         self.show()
238     
239     def recompute_style(self):
240         qApp.style().unpolish(self)
241         qApp.style().polish(self)
242
243     def closeEvent(self, event):
244         super(MiniWindow, self).closeEvent(event)
245         qApp.quit()
246
247     def set_payment_fields(self, dest_address, amount):
248         self.address_input.setText(dest_address)
249         self.address_field_changed(dest_address)
250         self.amount_input.setText(amount)
251
252     def activate(self):
253         pass
254
255     def deactivate(self):
256         pass
257
258     def set_quote_currency(self, currency):
259         assert currency in self.quote_currencies
260         self.quote_currencies.remove(currency)
261         self.quote_currencies = [currency] + self.quote_currencies
262         self.refresh_balance()
263
264     def change_quote_currency(self):
265         self.quote_currencies = \
266             self.quote_currencies[1:] + self.quote_currencies[0:1]
267         self.actuator.set_config_currency(self.quote_currencies[0])
268         self.refresh_balance()
269
270     def refresh_balance(self):
271         if self.btc_balance is None:
272             # Price has been discovered before wallet has been loaded
273             # and server connect... so bail.
274             return
275         self.set_balances(self.btc_balance)
276         self.amount_input_changed(self.amount_input.text())
277
278     def set_balances(self, btc_balance):
279         self.btc_balance = btc_balance
280         quote_text = self.create_quote_text(btc_balance)
281         if quote_text:
282             quote_text = "(%s)" % quote_text
283         btc_balance = "%.2f" % (btc_balance / bitcoin(1))
284         self.balance_label.set_balance_text(btc_balance, quote_text)
285         self.setWindowTitle("Electrum - %s BTC" % btc_balance)
286
287     def amount_input_changed(self, amount_text):
288         self.check_button_status()
289
290         try:
291             amount = D(str(amount_text))
292         except decimal.InvalidOperation:
293             self.balance_label.show_balance()
294         else:
295             quote_text = self.create_quote_text(amount * bitcoin(1))
296             if quote_text:
297                 self.balance_label.set_amount_text(quote_text)
298                 self.balance_label.show_amount()
299             else:
300                 self.balance_label.show_balance()
301
302     def create_quote_text(self, btc_balance):
303         quote_currency = self.quote_currencies[0]
304         quote_balance = self.exchanger.exchange(btc_balance, quote_currency)
305         if quote_balance is None:
306             quote_text = ""
307         else:
308             quote_text = "%.2f %s" % ((quote_balance / bitcoin(1)),
309                                       quote_currency)
310         return quote_text
311
312     def send(self):
313         if self.actuator.send(self.address_input.text(),
314                               self.amount_input.text(), self):
315             self.address_input.setText("")
316             self.amount_input.setText("")
317
318     def check_button_status(self):
319         if (self.address_input.property("isValid") == True and
320             len(self.amount_input.text()) > 0):
321             self.send_button.setDisabled(False)
322         else:
323             self.send_button.setDisabled(True)
324
325     def address_field_changed(self, address):
326         if self.actuator.is_valid(address):
327             self.check_button_status()
328             self.address_input.setProperty("isValid", True)
329             self.recompute_style(self.address_input)
330         else:
331             self.send_button.setDisabled(True)
332             self.address_input.setProperty("isValid", False)
333             self.recompute_style(self.address_input)
334
335         if len(address) == 0:
336             self.address_input.setProperty("isValid", None)
337             self.recompute_style(self.address_input)
338
339     def recompute_style(self, element):
340         self.style().unpolish(element)
341         self.style().polish(element)
342
343     def copy_address(self):
344         receive_popup = ReceivePopup(self.receive_button)
345         self.actuator.copy_address(receive_popup)
346
347     def update_completions(self, completions):
348         self.address_completions.setStringList(completions)
349
350     def update_history(self, tx_history):
351         for tx in tx_history[-10:]:
352             address = tx["default_label"]
353             amount = D(tx["value"]) / 10**8
354             self.history_list.append(address, amount)
355
356     def acceptbit(self):
357         self.actuator.acceptbit(self.quote_currencies[0])
358
359     def the_website(self):
360         webbrowser.open("http://electrum-desktop.com")
361
362     def show_about(self):
363         QMessageBox.about(self, "Electrum",
364             _("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.\n\nSend donations to 1JwTMv4GWaPdf931N6LNPJeZBfZgZJ3zX1"))
365
366     def show_report_bug(self):
367         QMessageBox.information(self, "Electrum - " + _("Reporting Bugs"),
368             _("Email bug reports to %s") % "genjix" + "@" + "riseup.net")
369
370     def show_history(self, toggle_state):
371         if toggle_state:
372             self.history_list.show()
373         else:
374             self.history_list.hide()
375
376 class BalanceLabel(QLabel):
377
378     SHOW_CONNECTING = 1
379     SHOW_BALANCE = 2
380     SHOW_AMOUNT = 3
381
382     def __init__(self, change_quote_currency, parent=None):
383         super(QLabel, self).__init__(_("Connecting..."), parent)
384         self.change_quote_currency = change_quote_currency
385         self.state = self.SHOW_CONNECTING
386         self.balance_text = ""
387         self.amount_text = ""
388
389     def mousePressEvent(self, event):
390         if self.state != self.SHOW_CONNECTING:
391             self.change_quote_currency()
392
393     def set_balance_text(self, btc_balance, quote_text):
394         if self.state == self.SHOW_CONNECTING:
395             self.state = self.SHOW_BALANCE
396         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)
397         if self.state == self.SHOW_BALANCE:
398             self.setText(self.balance_text)
399
400     def set_amount_text(self, quote_text):
401         self.amount_text = "<span style='font-size: 10pt'>%s</span>" % quote_text
402         if self.state == self.SHOW_AMOUNT:
403             self.setText(self.amount_text)
404
405     def show_balance(self):
406         if self.state == self.SHOW_AMOUNT:
407             self.state = self.SHOW_BALANCE
408             self.setText(self.balance_text)
409
410     def show_amount(self):
411         if self.state == self.SHOW_BALANCE:
412             self.state = self.SHOW_AMOUNT
413             self.setText(self.amount_text)
414
415 def ok_cancel_buttons(dialog):
416     row_layout = QHBoxLayout()
417     row_layout.addStretch(1)
418     ok_button = QPushButton(_("OK"))
419     row_layout.addWidget(ok_button)
420     ok_button.clicked.connect(dialog.accept)
421     cancel_button = QPushButton(_("Cancel"))
422     row_layout.addWidget(cancel_button)
423     cancel_button.clicked.connect(dialog.reject)
424     return row_layout
425
426 class PasswordDialog(QDialog):
427
428     def __init__(self, parent):
429         super(QDialog, self).__init__(parent)
430
431         self.setModal(True)
432
433         self.password_input = QLineEdit()
434         self.password_input.setEchoMode(QLineEdit.Password)
435
436         main_layout = QVBoxLayout(self)
437         message = _('Please enter your password')
438         main_layout.addWidget(QLabel(message))
439
440         grid = QGridLayout()
441         grid.setSpacing(8)
442         grid.addWidget(QLabel(_('Password')), 1, 0)
443         grid.addWidget(self.password_input, 1, 1)
444         main_layout.addLayout(grid)
445
446         main_layout.addLayout(ok_cancel_buttons(self))
447         self.setLayout(main_layout) 
448
449     def run(self):
450         if not self.exec_():
451             return
452         return unicode(self.password_input.text())
453
454 class ReceivePopup(QDialog):
455
456     def leaveEvent(self, event):
457         self.close()
458
459     def setup(self, address):
460         label = QLabel(_("Copied your Bitcoin address to the clipboard!"))
461         address_display = QLineEdit(address)
462         address_display.setReadOnly(True)
463         resize_line_edit_width(address_display, address)
464
465         main_layout = QVBoxLayout(self)
466         main_layout.addWidget(label)
467         main_layout.addWidget(address_display)
468
469         self.setMouseTracking(True)
470         self.setWindowTitle("Electrum - " + _("Receive Bitcoin payment"))
471         self.setWindowFlags(Qt.Window|Qt.FramelessWindowHint|Qt.MSWindowsFixedSizeDialogHint)
472         self.layout().setSizeConstraint(QLayout.SetFixedSize)
473         #self.setFrameStyle(QFrame.WinPanel|QFrame.Raised)
474         #self.setAlignment(Qt.AlignCenter)
475
476     def popup(self):
477         parent = self.parent()
478         top_left_pos = parent.mapToGlobal(parent.rect().bottomLeft())
479         self.move(top_left_pos)
480         center_mouse_pos = self.mapToGlobal(self.rect().center())
481         QCursor.setPos(center_mouse_pos)
482         self.show()
483
484 class MiniActuator:
485
486     def __init__(self, wallet):
487         self.wallet = wallet
488
489     def set_configured_currency(self, set_quote_currency):
490         currency = self.wallet.conversion_currency
491         # currency can be none when Electrum is used for the first
492         # time and no setting has been created yet.
493         if currency is not None:
494             set_quote_currency(currency)
495
496     def set_config_currency(self, conversion_currency):
497         self.wallet.conversion_currency = conversion_currency
498
499     def copy_address(self, receive_popup):
500         addrs = [addr for addr in self.wallet.all_addresses()
501                  if not self.wallet.is_change(addr)]
502         # Select most recent addresses from gap limit
503         addrs = addrs[-self.wallet.gap_limit:]
504         copied_address = random.choice(addrs)
505         qApp.clipboard().setText(copied_address)
506         receive_popup.setup(copied_address)
507         receive_popup.popup()
508
509     def send(self, address, amount, parent_window):
510         dest_address = self.fetch_destination(address)
511
512         if dest_address is None or not self.wallet.is_valid(dest_address):
513             QMessageBox.warning(parent_window, _('Error'), 
514                 _('Invalid Bitcoin Address') + ':\n' + address, _('OK'))
515             return False
516
517         convert_amount = lambda amount: \
518             int(D(unicode(amount)) * bitcoin(1))
519         amount = convert_amount(amount)
520
521         if self.wallet.use_encryption:
522             password_dialog = PasswordDialog(parent_window)
523             password = password_dialog.run()
524             if not password:
525                 return
526         else:
527             password = None
528
529         fee = 0
530         # 0.1 BTC = 10000000
531         if amount < bitcoin(1) / 10:
532             # 0.001 BTC
533             fee = bitcoin(1) / 1000
534
535         try:
536             tx = self.wallet.mktx(dest_address, amount, "", password, fee)
537         except BaseException as error:
538             QMessageBox.warning(parent_window, _('Error'), str(error), _('OK'))
539             return False
540             
541         status, message = self.wallet.sendtx(tx)
542         if not status:
543             QMessageBox.warning(parent_window, _('Error'), message, _('OK'))
544             return False
545
546         QMessageBox.information(parent_window, '',
547             _('Payment sent.') + '\n' + message, _('OK'))
548         return True
549
550     def fetch_destination(self, address):
551         recipient = unicode(address).strip()
552
553         # alias
554         match1 = re.match("^(|([\w\-\.]+)@)((\w[\w\-]+\.)+[\w\-]+)$",
555                           recipient)
556
557         # label or alias, with address in brackets
558         match2 = re.match("(.*?)\s*\<([1-9A-HJ-NP-Za-km-z]{26,})\>",
559                           recipient)
560         
561         if match1:
562             dest_address = \
563                 self.wallet.get_alias(recipient, True, 
564                                       self.show_message, self.question)
565             return dest_address
566         elif match2:
567             return match2.group(2)
568         else:
569             return recipient
570
571     def is_valid(self, address):
572         return self.wallet.is_valid(address)
573
574     def acceptbit(self, currency):
575         master_pubkey = self.wallet.master_public_key.encode("hex")
576         url = "http://acceptbit.com/mpk/%s/%s" % (master_pubkey, currency)
577         webbrowser.open(url)
578
579     def show_seed_dialog(self):
580         gui_qt.ElectrumWindow.show_seed_dialog(self.wallet)
581
582 class MiniDriver(QObject):
583
584     INITIALIZING = 0
585     CONNECTING = 1
586     SYNCHRONIZING = 2
587     READY = 3
588
589     def __init__(self, wallet, window):
590         super(QObject, self).__init__()
591
592         self.wallet = wallet
593         self.window = window
594
595         self.wallet.register_callback(self.update_callback)
596
597         self.state = None
598
599         self.initializing()
600         self.connect(self, SIGNAL("updatesignal()"), self.update)
601         self.update_callback()
602
603     # This is a hack to workaround that Qt does not like changing the
604     # window properties from this other thread before the runloop has
605     # been called from.
606     def update_callback(self):
607         self.emit(SIGNAL("updatesignal()"))
608
609     def update(self):
610         if not self.wallet.interface:
611             self.initializing()
612         elif not self.wallet.interface.is_connected:
613             self.connecting()
614         elif not self.wallet.blocks == -1:
615             self.connecting()
616         elif not self.wallet.is_up_to_date:
617             self.synchronizing()
618         else:
619             self.ready()
620
621         if self.wallet.up_to_date:
622             self.update_balance()
623             self.update_completions()
624             self.update_history()
625
626     def initializing(self):
627         if self.state == self.INITIALIZING:
628             return
629         self.state = self.INITIALIZING
630         self.window.deactivate()
631
632     def connecting(self):
633         if self.state == self.CONNECTING:
634             return
635         self.state = self.CONNECTING
636         self.window.deactivate()
637
638     def synchronizing(self):
639         if self.state == self.SYNCHRONIZING:
640             return
641         self.state = self.SYNCHRONIZING
642         self.window.deactivate()
643
644     def ready(self):
645         if self.state == self.READY:
646             return
647         self.state = self.READY
648         self.window.activate()
649
650     def update_balance(self):
651         conf_balance, unconf_balance = self.wallet.get_balance()
652         balance = D(conf_balance + unconf_balance)
653         self.window.set_balances(balance)
654
655     def update_completions(self):
656         completions = []
657         for addr, label in self.wallet.labels.items():
658             if addr in self.wallet.addressbook:
659                 completions.append("%s <%s>" % (label, addr))
660         completions = completions + self.wallet.aliases.keys()
661         self.window.update_completions(completions)
662
663     def update_history(self):
664         tx_history = self.wallet.get_tx_history()
665         self.window.update_history(tx_history)
666
667 if __name__ == "__main__":
668     app = QApplication(sys.argv)
669     with open(rsrc("style.css")) as style_file:
670         app.setStyleSheet(style_file.read())
671     mini = MiniWindow()
672     sys.exit(app.exec_())
673