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