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