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