efbbfe9d0a7b61e21cdbe99b83540a2942fa7cc3
[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.receive_button.clicked.connect(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.address_input.textEdited.connect(self.address_field_changed)
136         resize_line_edit_width(self.address_input,
137                                "1BtaFUr3qVvAmwrsuDuu5zk6e4s2rxd2Gy")
138
139         self.address_completions = QStringListModel()
140         address_completer = QCompleter(self.address_input)
141         address_completer.setCaseSensitivity(False)
142         address_completer.setModel(self.address_completions)
143         self.address_input.setCompleter(address_completer)
144
145         address_layout = QHBoxLayout()
146         address_layout.addWidget(self.address_input)
147
148         self.amount_input = QLineEdit()
149         self.amount_input.setPlaceholderText(_("... and amount"))
150         self.amount_input.setObjectName("amount_input")
151         # This is changed according to the user's displayed balance
152         self.amount_validator = QDoubleValidator(self.amount_input)
153         self.amount_validator.setNotation(QDoubleValidator.StandardNotation)
154         self.amount_validator.setDecimals(8)
155         self.amount_input.setValidator(self.amount_validator)
156
157         # This removes the very ugly OSX highlighting, please leave this in :D
158         self.address_input.setAttribute(Qt.WA_MacShowFocusRect, 0)
159         self.amount_input.setAttribute(Qt.WA_MacShowFocusRect, 0)
160         self.amount_input.textChanged.connect(self.amount_input_changed)
161
162         self.send_button = QPushButton(_("&Send"))
163         self.send_button.setObjectName("send_button")
164         self.send_button.setDisabled(True);
165         self.send_button.clicked.connect(self.send)
166
167         main_layout = QGridLayout(self)
168
169         main_layout.addWidget(self.balance_label, 0, 0)
170         main_layout.addWidget(self.receive_button, 0, 1)
171
172         main_layout.addWidget(self.address_input, 1, 0, 1, -1)
173
174         main_layout.addWidget(self.amount_input, 2, 0)
175         main_layout.addWidget(self.send_button, 2, 1)
176
177         self.history_list = history_widget.HistoryWidget()
178         self.history_list.setObjectName("history")
179         self.history_list.hide()
180         self.history_list.setAlternatingRowColors(True)
181         main_layout.addWidget(self.history_list, 3, 0, 1, -1)
182
183         menubar = QMenuBar()
184         electrum_menu = menubar.addMenu(_("&Bitcoin"))
185         self.servers_menu = electrum_menu.addMenu(_("&Servers"))
186         self.servers_menu.addAction(_("Foo"))
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         expert_gui.triggered.connect(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         show_history.toggled.connect(self.show_history)
198
199         settings_menu = menubar.addMenu(_("&Settings"))
200         settings_menu.addAction(_("&Configure Electrum"))
201         
202         help_menu = menubar.addMenu(_("&Help"))
203         the_website = help_menu.addAction(_("&Website"))
204         the_website.triggered.connect(self.the_website)
205         help_menu.addSeparator()
206         report_bug = help_menu.addAction(_("&Report Bug"))
207         report_bug.triggered.connect(self.show_report_bug)
208         show_about = help_menu.addAction(_("&About"))
209         show_about.triggered.connect(self.show_about)
210         main_layout.setMenuBar(menubar)
211
212         quit_shortcut = QShortcut(QKeySequence("Ctrl+Q"), self)
213         quit_shortcut.activated.connect(self.close)
214         close_shortcut = QShortcut(QKeySequence("Ctrl+W"), self)
215         close_shortcut.activated.connect(self.close)
216
217         self.setWindowIcon(QIcon(":electrum.png"))
218         self.setWindowTitle("Electrum")
219         self.setWindowFlags(Qt.Window|Qt.MSWindowsFixedSizeDialogHint)
220         self.layout().setSizeConstraint(QLayout.SetFixedSize)
221         self.setObjectName("main_window")
222         self.show()
223     
224     def recompute_style(self):
225         qApp.style().unpolish(self)
226         qApp.style().polish(self)
227
228     def closeEvent(self, event):
229         super(MiniWindow, self).closeEvent(event)
230         qApp.quit()
231
232     def set_payment_fields(self, dest_address, amount):
233         self.address_input.setText(dest_address)
234         self.address_field_changed(dest_address)
235         self.amount_input.setText(amount)
236
237     def activate(self):
238         pass
239
240     def deactivate(self):
241         pass
242
243     def set_quote_currency(self, currency):
244         assert currency in self.quote_currencies
245         self.quote_currencies.remove(currency)
246         self.quote_currencies = [currency] + self.quote_currencies
247         self.refresh_balance()
248
249     def change_quote_currency(self):
250         self.quote_currencies = \
251             self.quote_currencies[1:] + self.quote_currencies[0:1]
252         self.actuator.set_config_currency(self.quote_currencies[0])
253         self.refresh_balance()
254
255     def refresh_balance(self):
256         if self.btc_balance is None:
257             # Price has been discovered before wallet has been loaded
258             # and server connect... so bail.
259             return
260         self.set_balances(self.btc_balance)
261         self.amount_input_changed(self.amount_input.text())
262
263     def set_balances(self, btc_balance):
264         self.btc_balance = btc_balance
265         quote_text = self.create_quote_text(btc_balance)
266         if quote_text:
267             quote_text = "(%s)" % quote_text
268         btc_balance = "%.2f" % (btc_balance / bitcoin(1))
269         self.balance_label.set_balance_text(btc_balance, quote_text)
270         self.setWindowTitle("Electrum - %s BTC" % btc_balance)
271
272     def amount_input_changed(self, amount_text):
273         self.check_button_status()
274
275         try:
276             amount = D(str(amount_text))
277         except decimal.InvalidOperation:
278             self.balance_label.show_balance()
279         else:
280             quote_text = self.create_quote_text(amount * bitcoin(1))
281             if quote_text:
282                 self.balance_label.set_amount_text(quote_text)
283                 self.balance_label.show_amount()
284             else:
285                 self.balance_label.show_balance()
286
287     def create_quote_text(self, btc_balance):
288         quote_currency = self.quote_currencies[0]
289         quote_balance = self.exchanger.exchange(btc_balance, quote_currency)
290         if quote_balance is None:
291             quote_text = ""
292         else:
293             quote_text = "%.2f %s" % ((quote_balance / bitcoin(1)),
294                                       quote_currency)
295         return quote_text
296
297     def send(self):
298         if self.actuator.send(self.address_input.text(),
299                               self.amount_input.text(), self):
300             self.address_input.setText("")
301             self.amount_input.setText("")
302
303     def check_button_status(self):
304       if (self.address_input.property("isValid") is True and
305           len(self.amount_input.text()) > 0):
306         self.send_button.setDisabled(False)
307       else:
308         self.send_button.setDisabled(True)
309
310     def address_field_changed(self, address):
311         if self.actuator.is_valid(address):
312             self.check_button_status()
313             self.address_input.setProperty("isValid", True)
314             self.recompute_style(self.address_input)
315         else:
316             self.send_button.setDisabled(True)
317             self.address_input.setProperty("isValid", False)
318             self.recompute_style(self.address_input)
319
320         if len(address) == 0:
321             self.address_input.setProperty("isValid", None)
322             self.recompute_style(self.address_input)
323
324     def recompute_style(self, element):
325         self.style().unpolish(element)
326         self.style().polish(element)
327
328     def copy_address(self):
329         receive_popup = ReceivePopup(self.receive_button)
330         self.actuator.copy_address(receive_popup)
331
332     def update_completions(self, completions):
333         self.address_completions.setStringList(completions)
334
335     def update_history(self, tx_history):
336         for tx in tx_history[-10:]:
337             address = tx["default_label"]
338             amount = D(tx["value"]) / 10**8
339             self.history_list.append(address, amount)
340
341     def acceptbit(self):
342         self.actuator.acceptbit(self.quote_currencies[0])
343
344     def the_website(self):
345         webbrowser.open("http://electrum-desktop.com")
346
347     def show_about(self):
348         QMessageBox.about(self, "Electrum",
349             _("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."))
350
351     def show_report_bug(self):
352         QMessageBox.information(self, "Electrum - " + _("Reporting Bugs"),
353             _("Email bug reports to %s") % "genjix" + "@" + "riseup.net")
354
355     def show_history(self, toggle_state):
356         if toggle_state:
357             self.history_list.show()
358         else:
359             self.history_list.hide()
360
361 class BalanceLabel(QLabel):
362
363     SHOW_CONNECTING = 1
364     SHOW_BALANCE = 2
365     SHOW_AMOUNT = 3
366
367     def __init__(self, change_quote_currency, parent=None):
368         super(QLabel, self).__init__(_("Connecting..."), parent)
369         self.change_quote_currency = change_quote_currency
370         self.state = self.SHOW_CONNECTING
371         self.balance_text = ""
372         self.amount_text = ""
373
374     def mousePressEvent(self, event):
375         if self.state != self.SHOW_CONNECTING:
376             self.change_quote_currency()
377
378     def set_balance_text(self, btc_balance, quote_text):
379         if self.state == self.SHOW_CONNECTING:
380             self.state = self.SHOW_BALANCE
381         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)
382         if self.state == self.SHOW_BALANCE:
383             self.setText(self.balance_text)
384
385     def set_amount_text(self, quote_text):
386         self.amount_text = "<span style='font-size: 10pt'>%s</span>" % quote_text
387         if self.state == self.SHOW_AMOUNT:
388             self.setText(self.amount_text)
389
390     def show_balance(self):
391         if self.state == self.SHOW_AMOUNT:
392             self.state = self.SHOW_BALANCE
393             self.setText(self.balance_text)
394
395     def show_amount(self):
396         if self.state == self.SHOW_BALANCE:
397             self.state = self.SHOW_AMOUNT
398             self.setText(self.amount_text)
399
400 def ok_cancel_buttons(dialog):
401     row_layout = QHBoxLayout()
402     row_layout.addStretch(1)
403     ok_button = QPushButton(_("OK"))
404     row_layout.addWidget(ok_button)
405     ok_button.clicked.connect(dialog.accept)
406     cancel_button = QPushButton(_("Cancel"))
407     row_layout.addWidget(cancel_button)
408     cancel_button.clicked.connect(dialog.reject)
409     return row_layout
410
411 class PasswordDialog(QDialog):
412
413     def __init__(self, parent):
414         super(QDialog, self).__init__(parent)
415
416         self.setModal(True)
417
418         self.password_input = QLineEdit()
419         self.password_input.setEchoMode(QLineEdit.Password)
420
421         main_layout = QVBoxLayout(self)
422         message = _('Please enter your password')
423         main_layout.addWidget(QLabel(message))
424
425         grid = QGridLayout()
426         grid.setSpacing(8)
427         grid.addWidget(QLabel(_('Password')), 1, 0)
428         grid.addWidget(self.password_input, 1, 1)
429         main_layout.addLayout(grid)
430
431         main_layout.addLayout(ok_cancel_buttons(self))
432         self.setLayout(main_layout) 
433
434     def run(self):
435         if not self.exec_():
436             return
437         return unicode(self.password_input.text())
438
439 class ReceivePopup(QDialog):
440
441     def leaveEvent(self, event):
442         self.close()
443
444     def setup(self, address):
445         label = QLabel(_("Copied your Bitcoin address to the clipboard!"))
446         address_display = QLineEdit(address)
447         address_display.setReadOnly(True)
448         resize_line_edit_width(address_display, address)
449
450         main_layout = QVBoxLayout(self)
451         main_layout.addWidget(label)
452         main_layout.addWidget(address_display)
453
454         self.setMouseTracking(True)
455         self.setWindowTitle("Electrum - " + _("Receive Bitcoin payment"))
456         self.setWindowFlags(Qt.Window|Qt.FramelessWindowHint|Qt.MSWindowsFixedSizeDialogHint)
457         self.layout().setSizeConstraint(QLayout.SetFixedSize)
458         #self.setFrameStyle(QFrame.WinPanel|QFrame.Raised)
459         #self.setAlignment(Qt.AlignCenter)
460
461     def popup(self):
462         parent = self.parent()
463         top_left_pos = parent.mapToGlobal(parent.rect().bottomLeft())
464         self.move(top_left_pos)
465         center_mouse_pos = self.mapToGlobal(self.rect().center())
466         QCursor.setPos(center_mouse_pos)
467         self.show()
468
469 class MiniActuator:
470
471     def __init__(self, wallet):
472         self.wallet = wallet
473
474     def set_configured_currency(self, set_quote_currency):
475         currency = self.wallet.conversion_currency
476         # currency can be none when Electrum is used for the first
477         # time and no setting has been created yet.
478         if currency is not None:
479             set_quote_currency(currency)
480
481     def set_config_currency(self, conversion_currency):
482         self.wallet.conversion_currency = conversion_currency
483
484     def copy_address(self, receive_popup):
485         addrs = [addr for addr in self.wallet.all_addresses()
486                  if not self.wallet.is_change(addr)]
487         # Select most recent addresses from gap limit
488         addrs = addrs[-self.wallet.gap_limit:]
489         copied_address = random.choice(addrs)
490         qApp.clipboard().setText(copied_address)
491         receive_popup.setup(copied_address)
492         receive_popup.popup()
493
494     def send(self, address, amount, parent_window):
495         dest_address = self.fetch_destination(address)
496
497         if dest_address is None or not self.wallet.is_valid(dest_address):
498             QMessageBox.warning(parent_window, _('Error'), 
499                 _('Invalid Bitcoin Address') + ':\n' + address, _('OK'))
500             return False
501
502         convert_amount = lambda amount: \
503             int(D(unicode(amount)) * bitcoin(1))
504         amount = convert_amount(amount)
505
506         if self.wallet.use_encryption:
507             password_dialog = PasswordDialog(parent_window)
508             password = password_dialog.run()
509             if not password:
510                 return
511         else:
512             password = None
513
514         fee = 0
515         # 0.1 BTC = 10000000
516         if amount < bitcoin(1) / 10:
517             # 0.001 BTC
518             fee = bitcoin(1) / 1000
519
520         try:
521             tx = self.wallet.mktx(dest_address, amount, "", password, fee)
522         except BaseException as error:
523             QMessageBox.warning(parent_window, _('Error'), str(error), _('OK'))
524             return False
525             
526         status, message = self.wallet.sendtx(tx)
527         if not status:
528             QMessageBox.warning(parent_window, _('Error'), message, _('OK'))
529             return False
530
531         QMessageBox.information(parent_window, '',
532             _('Payment sent.') + '\n' + message, _('OK'))
533         return True
534
535     def fetch_destination(self, address):
536         recipient = unicode(address).strip()
537
538         # alias
539         match1 = re.match("^(|([\w\-\.]+)@)((\w[\w\-]+\.)+[\w\-]+)$",
540                           recipient)
541
542         # label or alias, with address in brackets
543         match2 = re.match("(.*?)\s*\<([1-9A-HJ-NP-Za-km-z]{26,})\>",
544                           recipient)
545         
546         if match1:
547             dest_address = \
548                 self.wallet.get_alias(recipient, True, 
549                                       self.show_message, self.question)
550             return dest_address
551         elif match2:
552             return match2.group(2)
553         else:
554             return recipient
555
556     def is_valid(self, address):
557         return self.wallet.is_valid(address)
558
559     def acceptbit(self, currency):
560         master_pubkey = self.wallet.master_public_key.encode("hex")
561         url = "http://acceptbit.com/mpk/%s/%s" % (master_pubkey, currency)
562         webbrowser.open(url)
563
564 class MiniDriver(QObject):
565
566     INITIALIZING = 0
567     CONNECTING = 1
568     SYNCHRONIZING = 2
569     READY = 3
570
571     def __init__(self, wallet, window):
572         super(QObject, self).__init__()
573
574         self.wallet = wallet
575         self.window = window
576
577         self.wallet.register_callback(self.update_callback)
578
579         self.state = None
580
581         self.initializing()
582         self.connect(self, SIGNAL("updatesignal()"), self.update)
583         self.update_callback()
584
585     # This is a hack to workaround that Qt does not like changing the
586     # window properties from this other thread before the runloop has
587     # been called from.
588     def update_callback(self):
589         self.emit(SIGNAL("updatesignal()"))
590
591     def update(self):
592         if not self.wallet.interface:
593             self.initializing()
594         elif not self.wallet.interface.is_connected:
595             self.connecting()
596         elif not self.wallet.blocks == -1:
597             self.connecting()
598         elif not self.wallet.is_up_to_date:
599             self.synchronizing()
600         else:
601             self.ready()
602
603         if self.wallet.up_to_date:
604             self.update_balance()
605             self.update_completions()
606             self.update_history()
607
608     def initializing(self):
609         if self.state == self.INITIALIZING:
610             return
611         self.state = self.INITIALIZING
612         self.window.deactivate()
613
614     def connecting(self):
615         if self.state == self.CONNECTING:
616             return
617         self.state = self.CONNECTING
618         self.window.deactivate()
619
620     def synchronizing(self):
621         if self.state == self.SYNCHRONIZING:
622             return
623         self.state = self.SYNCHRONIZING
624         self.window.deactivate()
625
626     def ready(self):
627         if self.state == self.READY:
628             return
629         self.state = self.READY
630         self.window.activate()
631
632     def update_balance(self):
633         conf_balance, unconf_balance = self.wallet.get_balance()
634         balance = D(conf_balance + unconf_balance)
635         self.window.set_balances(balance)
636
637     def update_completions(self):
638         completions = []
639         for addr, label in self.wallet.labels.items():
640             if addr in self.wallet.addressbook:
641                 completions.append("%s <%s>" % (label, addr))
642         completions = completions + self.wallet.aliases.keys()
643         self.window.update_completions(completions)
644
645     def update_history(self):
646         tx_history = self.wallet.get_tx_history()
647         self.window.update_history(tx_history)
648
649 if __name__ == "__main__":
650     app = QApplication(sys.argv)
651     with open(rsrc("style.css")) as style_file:
652         app.setStyleSheet(style_file.read())
653     mini = MiniWindow()
654     sys.exit(app.exec_())
655