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