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