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