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