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