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