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