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