Fixed issue 19 by jimboman77: https://github.com/spesmilo/electrum/issues/19
[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         try:
336             value = D(str(self.amount_input.text())) * 10**8
337         except decimal.InvalidOperation:
338             value = None
339         # self.address_input.property(...) returns a qVariant, not a bool.
340         # The == is needed to properly invoke a comparison.
341         if (self.address_input.property("isValid") == True and
342             value is not None and 0 < value <= self.btc_balance):
343             self.send_button.setDisabled(False)
344         else:
345             self.send_button.setDisabled(True)
346
347     def address_field_changed(self, address):
348         if self.actuator.is_valid(address):
349             self.check_button_status()
350             self.address_input.setProperty("isValid", True)
351             self.recompute_style(self.address_input)
352         else:
353             self.send_button.setDisabled(True)
354             self.address_input.setProperty("isValid", False)
355             self.recompute_style(self.address_input)
356
357         if len(address) == 0:
358             self.address_input.setProperty("isValid", None)
359             self.recompute_style(self.address_input)
360
361     def recompute_style(self, element):
362         self.style().unpolish(element)
363         self.style().polish(element)
364
365     def copy_address(self):
366         receive_popup = ReceivePopup(self.receive_button)
367         self.actuator.copy_address(receive_popup)
368
369     def update_completions(self, completions):
370         self.address_completions.setStringList(completions)
371
372     def update_history(self, tx_history):
373         for tx in tx_history[-10:]:
374             address = tx["default_label"]
375             amount = D(tx["value"]) / 10**8
376             self.history_list.append(address, amount)
377
378     def acceptbit(self):
379         self.actuator.acceptbit(self.quote_currencies[0])
380
381     def the_website(self):
382         webbrowser.open("http://electrum-desktop.com")
383
384     def show_about(self):
385         QMessageBox.about(self, "Electrum",
386             _("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"))
387
388     def show_report_bug(self):
389         QMessageBox.information(self, "Electrum - " + _("Reporting Bugs"),
390             _("Email bug reports to %s") % "genjix" + "@" + "riseup.net")
391
392     def show_history(self, toggle_state):
393         if toggle_state:
394             self.history_list.show()
395         else:
396             self.history_list.hide()
397
398 class BalanceLabel(QLabel):
399
400     SHOW_CONNECTING = 1
401     SHOW_BALANCE = 2
402     SHOW_AMOUNT = 3
403
404     def __init__(self, change_quote_currency, parent=None):
405         super(QLabel, self).__init__(_("Connecting..."), parent)
406         self.change_quote_currency = change_quote_currency
407         self.state = self.SHOW_CONNECTING
408         self.balance_text = ""
409         self.amount_text = ""
410
411     def mousePressEvent(self, event):
412         """Change the fiat currency selection if window background is clicked."""
413         if self.state != self.SHOW_CONNECTING:
414             self.change_quote_currency()
415
416     def set_balance_text(self, btc_balance, quote_text):
417         """Set the amount of bitcoins in the gui."""
418         if self.state == self.SHOW_CONNECTING:
419             self.state = self.SHOW_BALANCE
420         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)
421         if self.state == self.SHOW_BALANCE:
422             self.setText(self.balance_text)
423
424     def set_amount_text(self, quote_text):
425         self.amount_text = "<span style='font-size: 10pt'>%s</span>" % quote_text
426         if self.state == self.SHOW_AMOUNT:
427             self.setText(self.amount_text)
428
429     def show_balance(self):
430         if self.state == self.SHOW_AMOUNT:
431             self.state = self.SHOW_BALANCE
432             self.setText(self.balance_text)
433
434     def show_amount(self):
435         if self.state == self.SHOW_BALANCE:
436             self.state = self.SHOW_AMOUNT
437             self.setText(self.amount_text)
438
439 def ok_cancel_buttons(dialog):
440     row_layout = QHBoxLayout()
441     row_layout.addStretch(1)
442     ok_button = QPushButton(_("OK"))
443     row_layout.addWidget(ok_button)
444     ok_button.clicked.connect(dialog.accept)
445     cancel_button = QPushButton(_("Cancel"))
446     row_layout.addWidget(cancel_button)
447     cancel_button.clicked.connect(dialog.reject)
448     return row_layout
449
450 class PasswordDialog(QDialog):
451
452     def __init__(self, parent):
453         super(QDialog, self).__init__(parent)
454
455         self.setModal(True)
456
457         self.password_input = QLineEdit()
458         self.password_input.setEchoMode(QLineEdit.Password)
459
460         main_layout = QVBoxLayout(self)
461         message = _('Please enter your password')
462         main_layout.addWidget(QLabel(message))
463
464         grid = QGridLayout()
465         grid.setSpacing(8)
466         grid.addWidget(QLabel(_('Password')), 1, 0)
467         grid.addWidget(self.password_input, 1, 1)
468         main_layout.addLayout(grid)
469
470         main_layout.addLayout(ok_cancel_buttons(self))
471         self.setLayout(main_layout) 
472
473     def run(self):
474         if not self.exec_():
475             return
476         return unicode(self.password_input.text())
477
478 class ReceivePopup(QDialog):
479
480     def leaveEvent(self, event):
481         self.close()
482
483     def setup(self, address):
484         label = QLabel(_("Copied your Bitcoin address to the clipboard!"))
485         address_display = QLineEdit(address)
486         address_display.setReadOnly(True)
487         resize_line_edit_width(address_display, address)
488
489         main_layout = QVBoxLayout(self)
490         main_layout.addWidget(label)
491         main_layout.addWidget(address_display)
492
493         self.setMouseTracking(True)
494         self.setWindowTitle("Electrum - " + _("Receive Bitcoin payment"))
495         self.setWindowFlags(Qt.Window|Qt.FramelessWindowHint|
496                             Qt.MSWindowsFixedSizeDialogHint)
497         self.layout().setSizeConstraint(QLayout.SetFixedSize)
498         #self.setFrameStyle(QFrame.WinPanel|QFrame.Raised)
499         #self.setAlignment(Qt.AlignCenter)
500
501     def popup(self):
502         parent = self.parent()
503         top_left_pos = parent.mapToGlobal(parent.rect().bottomLeft())
504         self.move(top_left_pos)
505         center_mouse_pos = self.mapToGlobal(self.rect().center())
506         QCursor.setPos(center_mouse_pos)
507         self.show()
508
509 class MiniActuator:
510     """Initialize the definitions relating to themes and 
511     sending/recieving bitcoins."""
512     
513     
514     def __init__(self, wallet):
515         """Retrieve the gui theme used in previous session."""
516         self.wallet = wallet
517         self.theme_name = self.wallet.theme
518         self.themes = util.load_theme_paths()
519
520     def load_theme(self):
521         """Load theme retrieved from wallet file."""
522         try:
523             theme_prefix, theme_path = self.themes[self.theme_name]
524         except KeyError:
525             util.print_error("Theme not found!", self.theme_name)
526             return
527         QDir.setCurrent(os.path.join(theme_prefix, theme_path))
528         with open(rsrc("style.css")) as style_file:
529             qApp.setStyleSheet(style_file.read())
530
531     def theme_names(self):
532         """Sort themes."""
533         return sorted(self.themes.keys())
534     
535     def selected_theme(self):
536         """Select theme."""
537         return self.theme_name
538
539     def change_theme(self, theme_name):
540         """Change theme."""
541         self.wallet.theme = self.theme_name = theme_name
542         self.load_theme()
543     
544     def set_configured_currency(self, set_quote_currency):
545         """Set the inital fiat currency conversion country (USD/EUR/GBP) in 
546         the GUI to what it was set to in the wallet."""
547         currency = self.wallet.conversion_currency
548         # currency can be none when Electrum is used for the first
549         # time and no setting has been created yet.
550         if currency is not None:
551             set_quote_currency(currency)
552
553     def set_config_currency(self, conversion_currency):
554         """Change the wallet fiat currency country."""
555         self.wallet.conversion_currency = conversion_currency
556
557     def set_servers_gui_stuff(self, servers_menu, servers_group):
558         self.servers_menu = servers_menu
559         self.servers_group = servers_group
560
561     def populate_servers_menu(self):
562         interface = self.wallet.interface
563         if not interface.servers:
564             print "No servers loaded yet."
565             self.servers_list = []
566             for server_string in DEFAULT_SERVERS:
567                 host, port, protocol = server_string.split(':')
568                 transports = [(protocol,port)]
569                 self.servers_list.append((host, transports))
570         else:
571             print "Servers loaded."
572             self.servers_list = interface.servers
573         server_names = [details[0] for details in self.servers_list]
574         current_server = self.wallet.server.split(":")[0]
575         for server_name in server_names:
576             server_action = self.servers_menu.addAction(server_name)
577             server_action.setCheckable(True)
578             if server_name == current_server:
579                 server_action.setChecked(True)
580             class SelectServerFunctor:
581                 def __init__(self, server_name, server_selected):
582                     self.server_name = server_name
583                     self.server_selected = server_selected
584                 def __call__(self, checked):
585                     if checked:
586                         # call server_selected
587                         self.server_selected(self.server_name)
588             delegate = SelectServerFunctor(server_name, self.server_selected)
589             server_action.toggled.connect(delegate)
590             self.servers_group.addAction(server_action)
591
592     def update_servers_list(self):
593         # Clear servers_group
594         for action in self.servers_group.actions():
595             self.servers_group.removeAction(action)
596         self.populate_servers_menu()
597
598     def server_selected(self, server_name):
599         match = [transports for (host, transports) in self.servers_list
600                  if host == server_name]
601         assert len(match) == 1
602         match = match[0]
603         # Default to TCP if available else use anything
604         # TODO: protocol should be selectable.
605         tcp_port = [port for (protocol, port) in match if protocol == "t"]
606         if len(tcp_port) == 0:
607             protocol = match[0][0]
608             port = match[0][1]
609         else:
610             protocol = "t"
611             port = tcp_port[0]
612         server_line = "%s:%s:%s" % (server_name, port, protocol)
613         # Should this have exception handling?
614         self.wallet.set_server(server_line)
615
616     def copy_address(self, receive_popup):
617         """Copy the wallet addresses into the client."""
618         addrs = [addr for addr in self.wallet.all_addresses()
619                  if not self.wallet.is_change(addr)]
620         # Select most recent addresses from gap limit
621         addrs = addrs[-self.wallet.gap_limit:]
622         copied_address = random.choice(addrs)
623         qApp.clipboard().setText(copied_address)
624         receive_popup.setup(copied_address)
625         receive_popup.popup()
626
627     def send(self, address, amount, parent_window):
628         """Send bitcoins to the target address."""
629         dest_address = self.fetch_destination(address)
630
631         if dest_address is None or not self.wallet.is_valid(dest_address):
632             QMessageBox.warning(parent_window, _('Error'), 
633                 _('Invalid Bitcoin Address') + ':\n' + address, _('OK'))
634             return False
635
636         convert_amount = lambda amount: \
637             int(D(unicode(amount)) * bitcoin(1))
638         amount = convert_amount(amount)
639
640         if self.wallet.use_encryption:
641             password_dialog = PasswordDialog(parent_window)
642             password = password_dialog.run()
643             if not password:
644                 return
645         else:
646             password = None
647
648         fee = 0
649         # 0.1 BTC = 10000000
650         if amount < bitcoin(1) / 10:
651             # 0.001 BTC
652             fee = bitcoin(1) / 1000
653
654         try:
655             tx = self.wallet.mktx(dest_address, amount, "", password, fee)
656         except BaseException as error:
657             QMessageBox.warning(parent_window, _('Error'), str(error), _('OK'))
658             return False
659             
660         status, message = self.wallet.sendtx(tx)
661         if not status:
662             QMessageBox.warning(parent_window, _('Error'), message, _('OK'))
663             return False
664
665         QMessageBox.information(parent_window, '',
666             _('Payment sent.') + '\n' + message, _('OK'))
667         return True
668
669     def fetch_destination(self, address):
670         recipient = unicode(address).strip()
671
672         # alias
673         match1 = re.match("^(|([\w\-\.]+)@)((\w[\w\-]+\.)+[\w\-]+)$",
674                           recipient)
675
676         # label or alias, with address in brackets
677         match2 = re.match("(.*?)\s*\<([1-9A-HJ-NP-Za-km-z]{26,})\>",
678                           recipient)
679         
680         if match1:
681             dest_address = \
682                 self.wallet.get_alias(recipient, True, 
683                                       self.show_message, self.question)
684             return dest_address
685         elif match2:
686             return match2.group(2)
687         else:
688             return recipient
689
690     def is_valid(self, address):
691         """Check if bitcoin address is valid."""
692         return self.wallet.is_valid(address)
693
694     def acceptbit(self, currency):
695         master_pubkey = self.wallet.master_public_key.encode("hex")
696         url = "http://acceptbit.com/mpk/%s/%s" % (master_pubkey, currency)
697         webbrowser.open(url)
698
699     def show_seed_dialog(self):
700         gui_qt.ElectrumWindow.show_seed_dialog(self.wallet)
701
702 class MiniDriver(QObject):
703
704     INITIALIZING = 0
705     CONNECTING = 1
706     SYNCHRONIZING = 2
707     READY = 3
708
709     def __init__(self, wallet, window):
710         super(QObject, self).__init__()
711
712         self.wallet = wallet
713         self.window = window
714
715         self.wallet.register_callback(self.update_callback)
716
717         self.state = None
718
719         self.initializing()
720         self.connect(self, SIGNAL("updatesignal()"), self.update)
721         self.update_callback()
722
723     # This is a hack to workaround that Qt does not like changing the
724     # window properties from this other thread before the runloop has
725     # been called from.
726     def update_callback(self):
727         self.emit(SIGNAL("updatesignal()"))
728
729     def update(self):
730         if not self.wallet.interface:
731             self.initializing()
732         elif not self.wallet.interface.is_connected:
733             self.connecting()
734         elif not self.wallet.blocks == -1:
735             self.connecting()
736         elif not self.wallet.is_up_to_date:
737             self.synchronizing()
738         else:
739             self.ready()
740
741         if self.wallet.up_to_date:
742             self.update_balance()
743             self.update_completions()
744             self.update_history()
745
746     def initializing(self):
747         if self.state == self.INITIALIZING:
748             return
749         self.state = self.INITIALIZING
750         self.window.deactivate()
751
752     def connecting(self):
753         if self.state == self.CONNECTING:
754             return
755         self.state = self.CONNECTING
756         self.window.deactivate()
757
758     def synchronizing(self):
759         if self.state == self.SYNCHRONIZING:
760             return
761         self.state = self.SYNCHRONIZING
762         self.window.deactivate()
763
764     def ready(self):
765         if self.state == self.READY:
766             return
767         self.state = self.READY
768         self.window.activate()
769
770     def update_balance(self):
771         conf_balance, unconf_balance = self.wallet.get_balance()
772         balance = D(conf_balance + unconf_balance)
773         self.window.set_balances(balance)
774
775     def update_completions(self):
776         completions = []
777         for addr, label in self.wallet.labels.items():
778             if addr in self.wallet.addressbook:
779                 completions.append("%s <%s>" % (label, addr))
780         completions = completions + self.wallet.aliases.keys()
781         self.window.update_completions(completions)
782
783     def update_history(self):
784         tx_history = self.wallet.get_tx_history()
785         self.window.update_history(tx_history)
786
787 if __name__ == "__main__":
788     app = QApplication(sys.argv)
789     with open(rsrc("style.css")) as style_file:
790         app.setStyleSheet(style_file.read())
791     mini = MiniWindow()
792     sys.exit(app.exec_())
793