Adds a settings dialog for qrscanner plugin - allows device selection
[electrum-nvc.git] / plugins / qrscanner.py
1 from electrum.util import print_error
2 from urlparse import urlparse, parse_qs
3 from PyQt4.QtGui import QPushButton, QMessageBox, QDialog, QVBoxLayout, QHBoxLayout, QGridLayout, QLabel, QLineEdit, QComboBox
4 from PyQt4.QtCore import Qt
5
6 from electrum.i18n import _
7 import re
8 import os
9 from electrum import Transaction
10 from electrum.bitcoin import MIN_RELAY_TX_FEE, is_valid
11 from electrum_gui.qt.qrcodewidget import QRCodeWidget
12 from electrum import bmp
13 from electrum_gui.qt import HelpButton, EnterButton
14 import json
15
16 try:
17     import zbar
18 except ImportError:
19     zbar = None
20
21 from electrum import BasePlugin
22 class Plugin(BasePlugin):
23
24     def fullname(self): return 'QR scans'
25
26     def description(self): return "QR Scans.\nInstall the zbar package (http://zbar.sourceforge.net/download.html) to enable this plugin"
27
28     def __init__(self, gui, name):
29         BasePlugin.__init__(self, gui, name)
30         self._is_available = self._init()
31
32     def _init(self):
33         if not zbar:
34             return False
35         try:
36             proc = zbar.Processor()
37             proc.init(video_device=self.video_device())
38         except zbar.SystemError:
39             # Cannot open video device
40             pass
41             #return False
42
43         return True
44
45     def load_wallet(self, wallet):
46         b = QPushButton(_("Scan QR code"))
47         b.clicked.connect(self.fill_from_qr)
48         self.send_tab_grid.addWidget(b, 1, 5)
49         b2 = QPushButton(_("Scan TxQR"))
50         b2.clicked.connect(self.read_raw_qr)
51         
52         if not wallet.seed:
53             b3 = QPushButton(_("Show unsigned TxQR"))
54             b3.clicked.connect(self.show_raw_qr)
55             self.send_tab_grid.addWidget(b3, 7, 1)
56             self.send_tab_grid.addWidget(b2, 7, 2)
57         else:
58             self.send_tab_grid.addWidget(b2, 7, 1)
59
60     def is_available(self):
61         return self._is_available
62
63     def create_send_tab(self, grid):
64         self.send_tab_grid = grid
65
66     def scan_qr(self):
67         proc = zbar.Processor()
68         try:
69             proc.init(video_device=self.video_device())
70         except zbar.SystemError, e:
71             QMessageBox.warning(self.gui.main_window, _('Error'), _(e), _('OK'))
72             return
73
74         proc.visible = True
75
76         while True:
77             try:
78                 proc.process_one()
79             except:
80                 # User closed the preview window
81                 return {}
82
83             for r in proc.results:
84                 if str(r.type) != 'QRCODE':
85                     continue
86                 return r.data
87         
88     def show_raw_qr(self):
89         r = unicode( self.gui.main_window.payto_e.text() )
90         r = r.strip()
91
92         # label or alias, with address in brackets
93         m = re.match('(.*?)\s*\<([1-9A-HJ-NP-Za-km-z]{26,})\>', r)
94         to_address = m.group(2) if m else r
95
96         if not is_valid(to_address):
97             QMessageBox.warning(self.gui.main_window, _('Error'), _('Invalid Bitcoin Address') + ':\n' + to_address, _('OK'))
98             return
99
100         try:
101             amount = self.gui.main_window.read_amount(unicode( self.gui.main_window.amount_e.text()))
102         except:
103             QMessageBox.warning(self.gui.main_window, _('Error'), _('Invalid Amount'), _('OK'))
104             return
105         try:
106             fee = self.gui.main_window.read_amount(unicode( self.gui.main_window.fee_e.text()))
107         except:
108             QMessageBox.warning(self.gui.main_window, _('Error'), _('Invalid Fee'), _('OK'))
109             return
110
111         try:
112             tx = self.gui.main_window.wallet.mktx( [(to_address, amount)], None, fee)
113         except BaseException, e:
114             self.gui.main_window.show_message(str(e))
115             return
116
117         if tx.requires_fee(self.gui.main_window.wallet.verifier) and fee < MIN_RELAY_TX_FEE:
118             QMessageBox.warning(self.gui.main_window, _('Error'), _("This transaction requires a higher fee, or it will not be propagated by the network."), _('OK'))
119             return
120
121         try:
122             out = {
123             "hex" : tx.hash(),
124             "complete" : "false"
125             }
126     
127             input_info = []
128
129         except BaseException, e:
130             self.gui.main_window.show_message(str(e))
131
132         try:
133             json_text = json.dumps(tx.as_dict()).replace(' ', '')
134             self.show_tx_qrcode(json_text, 'Unsigned Transaction')
135         except BaseException, e:
136             self.gui.main_window.show_message(str(e))
137
138     def show_tx_qrcode(self, data, title):
139         if not data: return
140         d = QDialog(self.gui.main_window)
141         d.setModal(1)
142         d.setWindowTitle(title)
143         d.setMinimumSize(250, 525)
144         vbox = QVBoxLayout()
145         qrw = QRCodeWidget(data)
146         vbox.addWidget(qrw, 0)
147         hbox = QHBoxLayout()
148         hbox.addStretch(1)
149
150         def print_qr(self):
151             filename = "qrcode.bmp"
152             electrum_gui.bmp.save_qrcode(qrw.qr, filename)
153             QMessageBox.information(None, _('Message'), _("QR code saved to file") + " " + filename, _('OK'))
154
155         b = QPushButton(_("Save"))
156         hbox.addWidget(b)
157         b.clicked.connect(print_qr)
158
159         b = QPushButton(_("Close"))
160         hbox.addWidget(b)
161         b.clicked.connect(d.accept)
162         b.setDefault(True)
163
164         vbox.addLayout(hbox, 1)
165         d.setLayout(vbox)
166         d.exec_()
167
168     def read_raw_qr(self):
169         qrcode = self.scan_qr()
170         if qrcode:
171             tx_dict = self.gui.main_window.tx_dict_from_text(qrcode)
172             if tx_dict:
173                 self.create_transaction_details_window(tx_dict)
174
175
176     def create_transaction_details_window(self, tx_dict):
177         tx = Transaction(tx_dict["hex"])
178             
179         dialog = QDialog(self.gui.main_window)
180         dialog.setMinimumWidth(500)
181         dialog.setWindowTitle(_('Process Offline transaction'))
182         dialog.setModal(1)
183
184         l = QGridLayout()
185         dialog.setLayout(l)
186
187         l.addWidget(QLabel(_("Transaction status:")), 3,0)
188         l.addWidget(QLabel(_("Actions")), 4,0)
189
190         if tx_dict["complete"] == False:
191             l.addWidget(QLabel(_("Unsigned")), 3,1)
192             if self.gui.main_window.wallet.seed :
193                 b = QPushButton("Sign transaction")
194                 input_info = json.loads(tx_dict["input_info"])
195                 b.clicked.connect(lambda: self.sign_raw_transaction(tx, input_info, dialog))
196                 l.addWidget(b, 4, 1)
197             else:
198                 l.addWidget(QLabel(_("Wallet is de-seeded, can't sign.")), 4,1)
199         else:
200             l.addWidget(QLabel(_("Signed")), 3,1)
201             b = QPushButton("Broadcast transaction")
202             b.clicked.connect(lambda: self.gui.main_window.send_raw_transaction(tx, dialog))
203             l.addWidget(b,4,1)
204     
205         l.addWidget( self.gui.main_window.generate_transaction_information_widget(tx), 0,0,2,3)
206         closeButton = QPushButton(_("Close"))
207         closeButton.clicked.connect(lambda: dialog.done(0))
208         l.addWidget(closeButton, 4,2)
209
210         dialog.exec_()
211
212     def do_protect(self, func, args):
213         if self.gui.main_window.wallet.use_encryption:
214             password = self.gui.main_window.password_dialog()
215             if not password:
216                 return
217         else:
218             password = None
219             
220         if args != (False,):
221             args = (self,) + args + (password,)
222         else:
223             args = (self,password)
224         apply( func, args)
225
226     def protected(func):
227         return lambda s, *args: s.do_protect(func, args)
228
229     @protected
230     def sign_raw_transaction(self, tx, input_info, dialog ="", password = ""):
231         try:
232             self.gui.main_window.wallet.signrawtransaction(tx, input_info, [], password)
233             txtext = json.dumps(tx.as_dict()).replace(' ', '')
234             self.show_tx_qrcode(txtext, 'Signed Transaction')
235         except BaseException, e:
236             self.gui.main_window.show_message(str(e))
237
238
239     def fill_from_qr(self):
240         qrcode = parse_uri(self.scan_qr())
241         if not qrcode:
242             return
243
244         if 'address' in qrcode:
245             self.gui.main_window.payto_e.setText(qrcode['address'])
246         if 'amount' in qrcode:
247             self.gui.main_window.amount_e.setText(str(qrcode['amount']))
248         if 'label' in qrcode:
249             self.gui.main_window.message_e.setText(qrcode['label'])
250         if 'message' in qrcode:
251             self.gui.main_window.message_e.setText("%s (%s)" % (self.gui.main_window.message_e.text(), qrcode['message']))
252                 
253     def video_device(self):
254         device = self.config.get("video_device", "default")
255         if device == 'default':
256             device = ''
257         return device
258
259     def requires_settings(self):
260         return True
261
262     def settings_widget(self, window):
263         return EnterButton(_('Settings'), self.settings_dialog)
264     
265     def _find_system_cameras(self):
266         device_root = "/sys/class/video4linux"
267         devices = {} # Name -> device
268         if os.path.exists(device_root):
269             for device in os.listdir(device_root):
270                 name = open(os.path.join(device_root, device, 'name')).read()
271                 devices[name] = os.path.join("/dev",device)
272         return devices
273
274     def settings_dialog(self):
275         system_cameras = self._find_system_cameras()
276
277         d = QDialog()
278         layout = QGridLayout(d)
279         layout.addWidget(QLabel("Choose a video device:"),0,0)
280
281         # Create a combo box with the available video devices:
282         combo = QComboBox()
283
284         # on change trigger for video device selection, makes the
285         # manual device selection only appear when needed:
286         def on_change(x):
287             combo_text = str(combo.itemText(x))
288             combo_data = combo.itemData(x)
289             if combo_text == "Manually specify a device":
290                 custom_device_label.setVisible(True)
291                 self.video_device_edit.setVisible(True)
292                 if self.config.get("video_device") == "default":
293                     self.video_device_edit.setText("")
294                 else:
295                     self.video_device_edit.setText(self.config.get("video_device"))
296             else:
297                 custom_device_label.setVisible(False)
298                 self.video_device_edit.setVisible(False)
299                 self.video_device_edit.setText(combo_data.toString())
300
301         # on save trigger for the video device selection window,
302         # stores the chosen video device on close.
303         def on_save():
304             device = str(self.video_device_edit.text())
305             self.config.set_key("video_device", device)
306             d.accept()
307
308         custom_device_label = QLabel("Video device: ")
309         custom_device_label.setVisible(False)
310         layout.addWidget(custom_device_label,1,0)
311         self.video_device_edit = QLineEdit()
312         self.video_device_edit.setVisible(False)
313         layout.addWidget(self.video_device_edit, 1,1,2,2)
314         combo.currentIndexChanged.connect(on_change)
315
316         combo.addItem("Default","default")
317         for camera, device in system_cameras.items():
318             combo.addItem(camera, device)
319         combo.addItem("Manually specify a device",self.config.get("video_device"))
320
321         # Populate the previously chosen device:
322         index = combo.findData(self.config.get("video_device"))
323         combo.setCurrentIndex(index)
324
325         layout.addWidget(combo,0,1)
326
327         self.accept = QPushButton(_("Done"))
328         self.accept.clicked.connect(on_save)
329         layout.addWidget(self.accept,4,2)
330
331         if d.exec_():
332           return True
333         else:
334           return False
335
336
337
338 def parse_uri(uri):
339     if ':' not in uri:
340         # It's just an address (not BIP21)
341         return {'address': uri}
342
343     if '//' not in uri:
344         # Workaround for urlparse, it don't handle bitcoin: URI properly
345         uri = uri.replace(':', '://')
346         
347     uri = urlparse(uri)
348     result = {'address': uri.netloc} 
349     
350     if uri.path.startswith('?'):
351         params = parse_qs(uri.path[1:])
352     else:
353         params = parse_qs(uri.path)    
354
355     for k,v in params.items():
356         if k in ('amount', 'label', 'message'):
357             result[k] = v[0]
358         
359     return result    
360
361
362
363
364
365 if __name__ == '__main__':
366     # Run some tests
367     
368     assert(parse_uri('1Marek48fwU7mugmSe186do2QpUkBnpzSN') ==
369            {'address': '1Marek48fwU7mugmSe186do2QpUkBnpzSN'})
370
371     assert(parse_uri('bitcoin://1Marek48fwU7mugmSe186do2QpUkBnpzSN') ==
372            {'address': '1Marek48fwU7mugmSe186do2QpUkBnpzSN'})
373     
374     assert(parse_uri('bitcoin:1Marek48fwU7mugmSe186do2QpUkBnpzSN') ==
375            {'address': '1Marek48fwU7mugmSe186do2QpUkBnpzSN'})
376     
377     assert(parse_uri('bitcoin:1Marek48fwU7mugmSe186do2QpUkBnpzSN?amount=10') ==
378            {'amount': '10', 'address': '1Marek48fwU7mugmSe186do2QpUkBnpzSN'})
379     
380     assert(parse_uri('bitcoin:1Marek48fwU7mugmSe186do2QpUkBnpzSN?amount=10&label=slush&message=Small%20tip%20to%20slush') ==
381            {'amount': '10', 'label': 'slush', 'message': 'Small tip to slush', 'address': '1Marek48fwU7mugmSe186do2QpUkBnpzSN'})
382     
383