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