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