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