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