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