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