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