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