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