install instructions for zbar. fixes #610
[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 to enable this plugin.\nOn linux, type: 'apt-get install python-zbar'"
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 Exception:
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 Exception:
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 Exception:
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 Exception as 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 Exception as 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 Exception as 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 = self.gui.main_window.tx_from_text(qrcode)
172             if tx:
173                 self.create_transaction_details_window(tx)
174
175     def create_transaction_details_window(self, tx):            
176         dialog = QDialog(self.gui.main_window)
177         dialog.setMinimumWidth(500)
178         dialog.setWindowTitle(_('Process Offline transaction'))
179         dialog.setModal(1)
180
181         l = QGridLayout()
182         dialog.setLayout(l)
183
184         l.addWidget(QLabel(_("Transaction status:")), 3,0)
185         l.addWidget(QLabel(_("Actions")), 4,0)
186
187         if tx.is_complete == False:
188             l.addWidget(QLabel(_("Unsigned")), 3,1)
189             if self.gui.main_window.wallet.seed :
190                 b = QPushButton("Sign transaction")
191                 b.clicked.connect(lambda: self.sign_raw_transaction(tx, tx.inputs, dialog))
192                 l.addWidget(b, 4, 1)
193             else:
194                 l.addWidget(QLabel(_("Wallet is de-seeded, can't sign.")), 4,1)
195         else:
196             l.addWidget(QLabel(_("Signed")), 3,1)
197             b = QPushButton("Broadcast transaction")
198             def broadcast(tx):
199                 result, result_message = self.gui.main_window.wallet.sendtx( tx )
200                 if result:
201                     self.gui.main_window.show_message(_("Transaction successfully sent:")+' %s' % (result_message))
202                     if dialog:
203                         dialog.done(0)
204                 else:
205                     self.gui.main_window.show_message(_("There was a problem sending your transaction:") + '\n %s' % (result_message))
206             b.clicked.connect(lambda: broadcast( tx ))
207             l.addWidget(b,4,1)
208     
209         closeButton = QPushButton(_("Close"))
210         closeButton.clicked.connect(lambda: dialog.done(0))
211         l.addWidget(closeButton, 4,2)
212
213         dialog.exec_()
214
215     def do_protect(self, func, args):
216         if self.gui.main_window.wallet.use_encryption:
217             password = self.gui.main_window.password_dialog()
218             if not password:
219                 return
220         else:
221             password = None
222             
223         if args != (False,):
224             args = (self,) + args + (password,)
225         else:
226             args = (self,password)
227         apply( func, args)
228
229     def protected(func):
230         return lambda s, *args: s.do_protect(func, args)
231
232     @protected
233     def sign_raw_transaction(self, tx, input_info, dialog ="", password = ""):
234         try:
235             self.gui.main_window.wallet.signrawtransaction(tx, input_info, [], password)
236             txtext = json.dumps(tx.as_dict()).replace(' ', '')
237             self.show_tx_qrcode(txtext, 'Signed Transaction')
238         except Exception as e:
239             self.gui.main_window.show_message(str(e))
240
241
242     def fill_from_qr(self):
243         qrcode = parse_uri(self.scan_qr())
244         if not qrcode:
245             return
246
247         if 'address' in qrcode:
248             self.gui.main_window.payto_e.setText(qrcode['address'])
249         if 'amount' in qrcode:
250             self.gui.main_window.amount_e.setText(str(qrcode['amount']))
251         if 'label' in qrcode:
252             self.gui.main_window.message_e.setText(qrcode['label'])
253         if 'message' in qrcode:
254             self.gui.main_window.message_e.setText("%s (%s)" % (self.gui.main_window.message_e.text(), qrcode['message']))
255                 
256     def video_device(self):
257         device = self.config.get("video_device", "default")
258         if device == 'default':
259             device = ''
260         return device
261
262     def requires_settings(self):
263         return True
264
265     def settings_widget(self, window):
266         return EnterButton(_('Settings'), self.settings_dialog)
267     
268     def _find_system_cameras(self):
269         device_root = "/sys/class/video4linux"
270         devices = {} # Name -> device
271         if os.path.exists(device_root):
272             for device in os.listdir(device_root):
273                 name = open(os.path.join(device_root, device, 'name')).read()
274                 devices[name] = os.path.join("/dev",device)
275         return devices
276
277     def settings_dialog(self):
278         system_cameras = self._find_system_cameras()
279
280         d = QDialog()
281         layout = QGridLayout(d)
282         layout.addWidget(QLabel("Choose a video device:"),0,0)
283
284         # Create a combo box with the available video devices:
285         combo = QComboBox()
286
287         # on change trigger for video device selection, makes the
288         # manual device selection only appear when needed:
289         def on_change(x):
290             combo_text = str(combo.itemText(x))
291             combo_data = combo.itemData(x)
292             if combo_text == "Manually specify a device":
293                 custom_device_label.setVisible(True)
294                 self.video_device_edit.setVisible(True)
295                 if self.config.get("video_device") == "default":
296                     self.video_device_edit.setText("")
297                 else:
298                     self.video_device_edit.setText(self.config.get("video_device"))
299             else:
300                 custom_device_label.setVisible(False)
301                 self.video_device_edit.setVisible(False)
302                 self.video_device_edit.setText(combo_data.toString())
303
304         # on save trigger for the video device selection window,
305         # stores the chosen video device on close.
306         def on_save():
307             device = str(self.video_device_edit.text())
308             self.config.set_key("video_device", device)
309             d.accept()
310
311         custom_device_label = QLabel("Video device: ")
312         custom_device_label.setVisible(False)
313         layout.addWidget(custom_device_label,1,0)
314         self.video_device_edit = QLineEdit()
315         self.video_device_edit.setVisible(False)
316         layout.addWidget(self.video_device_edit, 1,1,2,2)
317         combo.currentIndexChanged.connect(on_change)
318
319         combo.addItem("Default","default")
320         for camera, device in system_cameras.items():
321             combo.addItem(camera, device)
322         combo.addItem("Manually specify a device",self.config.get("video_device"))
323
324         # Populate the previously chosen device:
325         index = combo.findData(self.config.get("video_device"))
326         combo.setCurrentIndex(index)
327
328         layout.addWidget(combo,0,1)
329
330         self.accept = QPushButton(_("Done"))
331         self.accept.clicked.connect(on_save)
332         layout.addWidget(self.accept,4,2)
333
334         if d.exec_():
335           return True
336         else:
337           return False
338
339
340
341 def parse_uri(uri):
342     if ':' not in uri:
343         # It's just an address (not BIP21)
344         return {'address': uri}
345
346     if '//' not in uri:
347         # Workaround for urlparse, it don't handle bitcoin: URI properly
348         uri = uri.replace(':', '://')
349         
350     uri = urlparse(uri)
351     result = {'address': uri.netloc} 
352     
353     if uri.query.startswith('?'):
354         params = parse_qs(uri.query[1:])
355     else:
356         params = parse_qs(uri.query)    
357
358     for k,v in params.items():
359         if k in ('amount', 'label', 'message'):
360             result[k] = v[0]
361         
362     return result    
363
364
365
366
367
368 if __name__ == '__main__':
369     # Run some tests
370     
371     assert(parse_uri('1Marek48fwU7mugmSe186do2QpUkBnpzSN') ==
372            {'address': '1Marek48fwU7mugmSe186do2QpUkBnpzSN'})
373
374     assert(parse_uri('bitcoin://1Marek48fwU7mugmSe186do2QpUkBnpzSN') ==
375            {'address': '1Marek48fwU7mugmSe186do2QpUkBnpzSN'})
376     
377     assert(parse_uri('bitcoin:1Marek48fwU7mugmSe186do2QpUkBnpzSN') ==
378            {'address': '1Marek48fwU7mugmSe186do2QpUkBnpzSN'})
379     
380     assert(parse_uri('bitcoin:1Marek48fwU7mugmSe186do2QpUkBnpzSN?amount=10') ==
381            {'amount': '10', 'address': '1Marek48fwU7mugmSe186do2QpUkBnpzSN'})
382     
383     assert(parse_uri('bitcoin:1Marek48fwU7mugmSe186do2QpUkBnpzSN?amount=10&label=slush&message=Small%20tip%20to%20slush') ==
384            {'amount': '10', 'label': 'slush', 'message': 'Small tip to slush', 'address': '1Marek48fwU7mugmSe186do2QpUkBnpzSN'})
385     
386