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