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