completion support for destination addresses.
[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 i18n import _
5 import decimal
6 import exchange_rate
7 import random
8 import re
9 import sys
10 import time
11 import wallet
12
13 try:
14     import lib.gui_qt as gui_qt
15 except ImportError:
16     import electrum.gui_qt as gui_qt
17
18 bitcoin = lambda v: v * 100000000
19
20 def IconButton(filename, parent=None):
21     pixmap = QPixmap(filename)
22     icon = QIcon(pixmap)
23     return QPushButton(icon, "", parent)
24
25 class Timer(QThread):
26     def run(self):
27         while True:
28             self.emit(SIGNAL('timersignal'))
29             time.sleep(0.5)
30
31 class ElectrumGui:
32
33     def __init__(self, wallet):
34         self.wallet = wallet
35         self.app = QApplication(sys.argv)
36         with open("data/style.css") as style_file:
37             self.app.setStyleSheet(style_file.read())
38
39     def main(self, url):
40         actuator = MiniActuator(self.wallet)
41         self.mini = MiniWindow(actuator, self.expand)
42         driver = MiniDriver(self.wallet, self.mini)
43
44         timer = Timer()
45         timer.start()
46         self.expert = gui_qt.ElectrumWindow(self.wallet)
47         self.expert.app = self.app
48         self.expert.connect_slots(timer)
49         self.expert.update_wallet()
50
51         sys.exit(self.app.exec_())
52
53     def expand(self):
54         self.mini.hide()
55         self.expert.show()
56
57 class MiniWindow(QDialog):
58
59     def __init__(self, actuator, expand_callback):
60         super(MiniWindow, self).__init__()
61
62         self.actuator = actuator
63
64         accounts_button = IconButton("data/icons/accounts.png")
65         accounts_button.setObjectName("accounts_button")
66
67         self.accounts_selector = QMenu()
68         accounts_button.setMenu(self.accounts_selector)
69
70         interact_button = IconButton("data/icons/interact.png")
71         interact_button.setObjectName("interact_button")
72
73         app_menu = QMenu()
74         report_action = app_menu.addAction(_("&Report Bug"))
75         about_action = app_menu.addAction(_("&About Electrum"))
76         app_menu.addSeparator()
77         quit_action = app_menu.addAction(_("&Quit"))
78         interact_button.setMenu(app_menu)
79
80         self.connect(report_action, SIGNAL("triggered()"),
81                      self.show_report_bug)
82         self.connect(about_action, SIGNAL("triggered()"), self.show_about)
83         self.connect(quit_action, SIGNAL("triggered()"), self.close)
84
85         expand_button = IconButton("data/icons/expand.png")
86         expand_button.setObjectName("expand_button")
87         self.connect(expand_button, SIGNAL("clicked()"), expand_callback)
88
89         self.btc_balance = 0
90         self.quote_currencies = ("EUR", "USD", "GBP")
91         self.exchanger = exchange_rate.Exchanger(self.quote_currencies,
92                                                  self.refresh_balance)
93         QTimer.singleShot(1000, self.exchanger.discovery)
94
95         self.balance_label = BalanceLabel(self.change_quote_currency)
96         self.balance_label.setObjectName("balance_label")
97
98         copy_button = QPushButton(_("&Copy Address"))
99         copy_button.setObjectName("copy_button")
100         copy_button.setDefault(True)
101         self.connect(copy_button, SIGNAL("clicked()"),
102                      self.actuator.copy_address)
103
104         self.address_input = TextedLineEdit(_("Enter a Bitcoin address..."))
105         self.address_input.setObjectName("address_input")
106         self.connect(self.address_input, SIGNAL("textEdited(QString)"),
107                      self.address_field_changed)
108         metrics = QFontMetrics(qApp.font())
109         self.address_input.setMinimumWidth(
110             metrics.width("1E4vM9q25xsyDwWwdqHUWnwshdWC9PykmL"))
111
112         self.address_completions = QStringListModel()
113         address_completer = QCompleter(self.address_input)
114         address_completer.setCaseSensitivity(False)
115         address_completer.setModel(self.address_completions)
116         self.address_input.setCompleter(address_completer)
117         self.address_completions.setStringList(["1brmlab", "hello"])
118
119         self.valid_address = QCheckBox()
120         self.valid_address.setObjectName("valid_address")
121         self.valid_address.setEnabled(False)
122         self.valid_address.setChecked(False)
123
124         address_layout = QHBoxLayout()
125         address_layout.addWidget(self.address_input)
126         address_layout.addWidget(self.valid_address)
127
128         self.amount_input = TextedLineEdit(_("... and amount"))
129         self.amount_input.setObjectName("amount_input")
130         # This is changed according to the user's displayed balance
131         self.amount_validator = QDoubleValidator(self.amount_input)
132         self.amount_validator.setNotation(QDoubleValidator.StandardNotation)
133         self.amount_validator.setDecimals(8)
134         self.amount_input.setValidator(self.amount_validator)
135
136         self.connect(self.amount_input, SIGNAL("textChanged(QString)"),
137                      self.amount_input_changed)
138
139         amount_layout = QHBoxLayout()
140         amount_layout.addWidget(self.amount_input)
141         amount_layout.addStretch()
142
143         send_button = QPushButton(_("&Send"))
144         send_button.setObjectName("send_button")
145         self.connect(send_button, SIGNAL("clicked()"), self.send)
146
147         main_layout = QGridLayout(self)
148         main_layout.addWidget(accounts_button, 0, 0)
149         main_layout.addWidget(interact_button, 1, 0)
150         main_layout.addWidget(expand_button, 2, 0)
151
152         main_layout.addWidget(self.balance_label, 0, 1)
153         main_layout.addWidget(copy_button, 0, 2)
154
155         main_layout.addLayout(address_layout, 1, 1, 1, -1)
156
157         main_layout.addLayout(amount_layout, 2, 1)
158         main_layout.addWidget(send_button, 2, 2)
159
160         self.setWindowTitle("Electrum")
161         self.setWindowFlags(Qt.Window|Qt.MSWindowsFixedSizeDialogHint)
162         self.layout().setSizeConstraint(QLayout.SetFixedSize)
163         self.setObjectName("main_window")
164         self.show()
165
166     def closeEvent(self, event):
167         super(MiniWindow, self).closeEvent(event)
168         qApp.quit()
169
170     def activate(self):
171         pass
172
173     def deactivate(self):
174         pass
175
176     def change_quote_currency(self):
177         self.quote_currencies = \
178             self.quote_currencies[1:] + self.quote_currencies[0:1]
179         self.refresh_balance()
180
181     def refresh_balance(self):
182         self.set_balances(self.btc_balance)
183         self.amount_input_changed(self.amount_input.text())
184
185     def set_balances(self, btc_balance):
186         self.btc_balance = btc_balance
187         quote_text = self.create_quote_text(btc_balance)
188         if quote_text:
189             quote_text = "(%s)" % quote_text
190         btc_balance = "%.2f" % (btc_balance / bitcoin(1))
191         self.balance_label.set_balance_text(btc_balance, quote_text)
192         main_account_info = \
193             "Checking - %s BTC %s" % (btc_balance, quote_text)
194         self.setWindowTitle("Electrum - %s" % main_account_info)
195         self.accounts_selector.clear()
196         self.accounts_selector.addAction("%s" % main_account_info)
197
198     def amount_input_changed(self, amount_text):
199         try:
200             amount = D(str(amount_text))
201         except decimal.InvalidOperation:
202             self.balance_label.show_balance()
203         else:
204             quote_text = self.create_quote_text(amount * bitcoin(1))
205             if quote_text:
206                 self.balance_label.set_amount_text(quote_text)
207                 self.balance_label.show_amount()
208             else:
209                 self.balance_label.show_balance()
210
211     def create_quote_text(self, btc_balance):
212         quote_currency = self.quote_currencies[0]
213         quote_balance = self.exchanger.exchange(btc_balance, quote_currency)
214         if quote_balance is None:
215             quote_text = ""
216         else:
217             quote_text = "%.2f %s" % ((quote_balance / bitcoin(1)),
218                                       quote_currency)
219         return quote_text
220
221     def send(self):
222         if self.actuator.send(self.address_input.text(),
223                               self.amount_input.text(), self):
224             self.address_input.become_inactive()
225             self.amount_input.become_inactive()
226
227     def address_field_changed(self, address):
228         if self.actuator.is_valid(address):
229             self.valid_address.setChecked(True)
230         else:
231             self.valid_address.setChecked(False)
232
233     def update_completions(self, completions):
234         self.address_completions.setStringList(completions)
235
236     def show_about(self):
237         QMessageBox.about(self, "Electrum",
238             _("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."))
239
240     def show_report_bug(self):
241         QMessageBox.information(self, "Electrum - " + _("Reporting Bugs"),
242             _("Email bug reports to %s") % "genjix" + "@" + "riseup.net")
243
244 class BalanceLabel(QLabel):
245
246     SHOW_CONNECTING = 1
247     SHOW_BALANCE = 2
248     SHOW_AMOUNT = 3
249
250     def __init__(self, change_quote_currency, parent=None):
251         super(QLabel, self).__init__(_("Connecting..."), parent)
252         self.change_quote_currency = change_quote_currency
253         self.state = self.SHOW_CONNECTING
254         self.balance_text = ""
255         self.amount_text = ""
256
257     def mousePressEvent(self, event):
258         if self.state != self.SHOW_CONNECTING:
259             self.change_quote_currency()
260
261     def set_balance_text(self, btc_balance, quote_text):
262         if self.state == self.SHOW_CONNECTING:
263             self.state = self.SHOW_BALANCE
264         self.balance_text = "<span style='font-size: 16pt'>%s</span> <span style='font-size: 10pt'>BTC</span> <span style='font-size: 10pt'>%s</span>" % (btc_balance, quote_text)
265         if self.state == self.SHOW_BALANCE:
266             self.setText(self.balance_text)
267
268     def set_amount_text(self, quote_text):
269         self.amount_text = "<span style='font-size: 10pt'>%s</span>" % quote_text
270         if self.state == self.SHOW_AMOUNT:
271             self.setText(self.amount_text)
272
273     def show_balance(self):
274         if self.state == self.SHOW_AMOUNT:
275             self.state = self.SHOW_BALANCE
276             self.setText(self.balance_text)
277
278     def show_amount(self):
279         if self.state == self.SHOW_BALANCE:
280             self.state = self.SHOW_AMOUNT
281             self.setText(self.amount_text)
282
283 class TextedLineEdit(QLineEdit):
284
285     def __init__(self, inactive_text, parent=None):
286         super(QLineEdit, self).__init__(parent)
287         self.inactive_text = inactive_text
288         self.become_inactive()
289
290     def mousePressEvent(self, event):
291         if self.isReadOnly():
292             self.become_active()
293         QLineEdit.mousePressEvent(self, event)
294
295     def focusOutEvent(self, event):
296         if self.text() == "":
297             self.become_inactive()
298         QLineEdit.focusOutEvent(self, event)
299
300     def focusInEvent(self, event):
301         if self.isReadOnly():
302             self.become_active()
303         QLineEdit.focusInEvent(self, event)
304
305     def become_inactive(self):
306         self.setText(self.inactive_text)
307         self.setReadOnly(True)
308         self.recompute_style()
309
310     def become_active(self):
311         self.setText("")
312         self.setReadOnly(False)
313         self.recompute_style()
314
315     def recompute_style(self):
316         qApp.style().unpolish(self)
317         qApp.style().polish(self)
318         # also possible but more expensive:
319         #qApp.setStyleSheet(qApp.styleSheet())
320
321 def ok_cancel_buttons(dialog):
322     row_layout = QHBoxLayout()
323     row_layout.addStretch(1)
324     ok_button = QPushButton("OK")
325     row_layout.addWidget(ok_button)
326     ok_button.clicked.connect(dialog.accept)
327     cancel_button = QPushButton("Cancel")
328     row_layout.addWidget(cancel_button)
329     cancel_button.clicked.connect(dialog.reject)
330     return row_layout
331
332 class PasswordDialog(QDialog):
333
334     def __init__(self, parent):
335         super(QDialog, self).__init__(parent)
336
337         self.setModal(True)
338
339         self.password_input = QLineEdit()
340         self.password_input.setEchoMode(QLineEdit.Password)
341
342         main_layout = QVBoxLayout(self)
343         message = _('Please enter your password')
344         main_layout.addWidget(QLabel(message))
345
346         grid = QGridLayout()
347         grid.setSpacing(8)
348         grid.addWidget(QLabel(_('Password')), 1, 0)
349         grid.addWidget(self.password_input, 1, 1)
350         main_layout.addLayout(grid)
351
352         main_layout.addLayout(ok_cancel_buttons(self))
353         self.setLayout(main_layout) 
354
355     def run(self):
356         if not self.exec_():
357             return
358         return unicode(self.password_input.text())
359
360 class MiniActuator:
361
362     def __init__(self, wallet):
363         self.wallet = wallet
364
365     def copy_address(self):
366         addrs = [addr for addr in self.wallet.all_addresses()
367                  if not self.wallet.is_change(addr)]
368         qApp.clipboard().setText(random.choice(addrs))
369
370     def send(self, address, amount, parent_window):
371         dest_address = self.fetch_destination(address)
372
373         if dest_address is None or not self.wallet.is_valid(dest_address):
374             QMessageBox.warning(parent_window, _('Error'), 
375                 _('Invalid Bitcoin Address') + ':\n' + address, _('OK'))
376             return False
377
378         convert_amount = lambda amount: \
379             int(D(unicode(amount)) * bitcoin(1))
380         amount = convert_amount(amount)
381
382         if self.wallet.use_encryption:
383             password_dialog = PasswordDialog(parent_window)
384             password = password_dialog.run()
385             if not password:
386                 return
387         else:
388             password = None
389
390         fee = 0
391         # 0.1 BTC = 10000000
392         if amount < bitcoin(1) / 10:
393             # 0.01 BTC
394             fee = bitcoin(1) / 100
395
396         try:
397             tx = self.wallet.mktx(dest_address, amount, "", password, fee)
398         except BaseException as error:
399             QMessageBox.warning(parent_window, _('Error'), str(error), _('OK'))
400             return False
401             
402         status, message = self.wallet.sendtx(tx)
403         if not status:
404             QMessageBox.warning(parent_window, _('Error'), message, _('OK'))
405             return False
406
407         QMessageBox.information(parent_window, '',
408             _('Payment sent.') + '\n' + message, _('OK'))
409         return True
410
411     def fetch_destination(self, address):
412         recipient = unicode(address).strip()
413
414         # alias
415         match1 = re.match("^(|([\w\-\.]+)@)((\w[\w\-]+\.)+[\w\-]+)$",
416                           recipient)
417
418         # label or alias, with address in brackets
419         match2 = re.match("(.*?)\s*\<([1-9A-HJ-NP-Za-km-z]{26,})\>",
420                           recipient)
421         
422         if match1:
423             dest_address = \
424                 self.wallet.get_alias(recipient, True, 
425                                       self.show_message, self.question)
426             return dest_address
427         elif match2:
428             return match2.group(2)
429         else:
430             return recipient
431
432     def is_valid(self, address):
433         return self.wallet.is_valid(address)
434
435 class MiniDriver(QObject):
436
437     INITIALIZING = 0
438     CONNECTING = 1
439     SYNCHRONIZING = 2
440     READY = 3
441
442     def __init__(self, wallet, window):
443         super(QObject, self).__init__()
444
445         self.wallet = wallet
446         self.window = window
447
448         self.wallet.register_callback(self.update_callback)
449
450         self.state = None
451
452         self.initializing()
453         self.connect(self, SIGNAL("updatesignal()"), self.update)
454
455     # This is a hack to workaround that Qt does not like changing the
456     # window properties from this other thread before the runloop has
457     # been called from.
458     def update_callback(self):
459         self.emit(SIGNAL("updatesignal()"))
460
461     def update(self):
462         if not self.wallet.interface:
463             self.initializing()
464         elif not self.wallet.interface.is_connected:
465             self.connecting()
466         elif not self.wallet.blocks == -1:
467             self.connecting()
468         elif not self.wallet.is_up_to_date:
469             self.synchronizing()
470         else:
471             self.ready()
472
473         if self.wallet.up_to_date:
474             self.update_balance()
475             self.update_completions()
476
477     def initializing(self):
478         if self.state == self.INITIALIZING:
479             return
480         self.state = self.INITIALIZING
481         self.window.deactivate()
482
483     def connecting(self):
484         if self.state == self.CONNECTING:
485             return
486         self.state = self.CONNECTING
487         self.window.deactivate()
488
489     def synchronizing(self):
490         if self.state == self.SYNCHRONIZING:
491             return
492         self.state = self.SYNCHRONIZING
493         self.window.deactivate()
494
495     def ready(self):
496         if self.state == self.READY:
497             return
498         self.state = self.READY
499         self.window.activate()
500
501     def update_balance(self):
502         conf_balance, unconf_balance = self.wallet.get_balance()
503         balance = D(conf_balance + unconf_balance)
504         self.window.set_balances(balance)
505
506     def update_completions(self):
507         completions = []
508         for addr, label in self.wallet.labels.items():
509             if addr in self.wallet.addressbook:
510                 completions.append("%s <%s>" % (label, addr))
511         completions = completions + self.wallet.aliases.keys()
512         self.window.update_completions(completions)
513
514 if __name__ == "__main__":
515     app = QApplication(sys.argv)
516     with open("data/style.css") as style_file:
517         app.setStyleSheet(style_file.read())
518     mini = MiniWindow()
519     sys.exit(app.exec_())
520