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