qrscanner: add scan button in init()
[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         self.win.raw_transaction_menu.addAction(_("&From QR code"), self.read_raw_qr)
48         b = QPushButton(_("Scan QR code"))
49         b.clicked.connect(self.fill_from_qr)
50         self.win.send_grid.addWidget(b, 1, 5)
51         self.win.send_grid.setColumnStretch(5, 0)
52         self.win.send_grid.setColumnStretch(6, 1)
53
54     def init_transaction_dialog(self, dialog, buttons):
55         b = QPushButton(_("Show QR code"))
56         b.clicked.connect(self.show_raw_qr)
57         buttons.insertWidget(1,b)
58
59     def is_available(self):
60         return self._is_available
61
62     def scan_qr(self):
63         proc = zbar.Processor()
64         try:
65             proc.init(video_device=self.video_device())
66         except zbar.SystemError, e:
67             QMessageBox.warning(self.win, _('Error'), _(e), _('OK'))
68             return
69
70         proc.visible = True
71
72         while True:
73             try:
74                 proc.process_one()
75             except Exception:
76                 # User closed the preview window
77                 return {}
78
79             for r in proc.results:
80                 if str(r.type) != 'QRCODE':
81                     continue
82                 return r.data
83         
84     def show_raw_qr(self):
85         r = self.win.read_send_tab()
86         if not r:
87             return
88
89         outputs, fee, label, coins = r
90         try:
91             tx = self.win.wallet.make_unsigned_transaction(outputs, fee, None, None, coins)
92         except Exception as e:
93             self.win.show_message(str(e))
94             return
95
96         if tx.requires_fee(self.win.wallet.verifier) and fee < MIN_RELAY_TX_FEE:
97             QMessageBox.warning(self.win, _('Error'), _("This transaction requires a higher fee, or it will not be propagated by the network."), _('OK'))
98             return
99
100         try:
101             out = {
102             "hex" : tx.hash(),
103             "complete" : "false"
104             }
105     
106             input_info = []
107
108         except Exception as e:
109             self.win.show_message(str(e))
110
111         try:
112             json_text = json.dumps(tx.as_dict()).replace(' ', '')
113             self.show_tx_qrcode(json_text, 'Unsigned Transaction')
114         except Exception as e:
115             self.win.show_message(str(e))
116
117     def show_tx_qrcode(self, data, title):
118         if not data: return
119         d = QDialog(self.win)
120         d.setModal(1)
121         d.setWindowTitle(title)
122         d.setMinimumSize(250, 525)
123         vbox = QVBoxLayout()
124         qrw = QRCodeWidget(data)
125         vbox.addWidget(qrw, 0)
126         hbox = QHBoxLayout()
127         hbox.addStretch(1)
128
129         def print_qr(self):
130             filename = "qrcode.bmp"
131             electrum_gui.bmp.save_qrcode(qrw.qr, filename)
132             QMessageBox.information(None, _('Message'), _("QR code saved to file") + " " + filename, _('OK'))
133
134         b = QPushButton(_("Save"))
135         hbox.addWidget(b)
136         b.clicked.connect(print_qr)
137
138         b = QPushButton(_("Close"))
139         hbox.addWidget(b)
140         b.clicked.connect(d.accept)
141         b.setDefault(True)
142
143         vbox.addLayout(hbox, 1)
144         d.setLayout(vbox)
145         d.exec_()
146
147     def read_raw_qr(self):
148         qrcode = self.scan_qr()
149         if not qrcode:
150             return
151         tx = self.win.tx_from_text(qrcode)
152         if not tx:
153             return
154         self.win.show_transaction(tx)
155
156
157     def fill_from_qr(self):
158         qrcode = parse_uri(self.scan_qr())
159         if not qrcode:
160             return
161
162         if 'address' in qrcode:
163             self.win.payto_e.setText(qrcode['address'])
164         if 'amount' in qrcode:
165             self.win.amount_e.setText(str(qrcode['amount']))
166         if 'label' in qrcode:
167             self.win.message_e.setText(qrcode['label'])
168         if 'message' in qrcode:
169             self.win.message_e.setText("%s (%s)" % (self.win.message_e.text(), qrcode['message']))
170                 
171     def video_device(self):
172         device = self.config.get("video_device", "default")
173         if device == 'default':
174             device = ''
175         return device
176
177     def requires_settings(self):
178         return True
179
180     def settings_widget(self, window):
181         return EnterButton(_('Settings'), self.settings_dialog)
182     
183     def _find_system_cameras(self):
184         device_root = "/sys/class/video4linux"
185         devices = {} # Name -> device
186         if os.path.exists(device_root):
187             for device in os.listdir(device_root):
188                 name = open(os.path.join(device_root, device, 'name')).read()
189                 devices[name] = os.path.join("/dev",device)
190         return devices
191
192     def settings_dialog(self):
193         system_cameras = self._find_system_cameras()
194
195         d = QDialog()
196         layout = QGridLayout(d)
197         layout.addWidget(QLabel("Choose a video device:"),0,0)
198
199         # Create a combo box with the available video devices:
200         combo = QComboBox()
201
202         # on change trigger for video device selection, makes the
203         # manual device selection only appear when needed:
204         def on_change(x):
205             combo_text = str(combo.itemText(x))
206             combo_data = combo.itemData(x)
207             if combo_text == "Manually specify a device":
208                 custom_device_label.setVisible(True)
209                 self.video_device_edit.setVisible(True)
210                 if self.config.get("video_device") == "default":
211                     self.video_device_edit.setText("")
212                 else:
213                     self.video_device_edit.setText(self.config.get("video_device"))
214             else:
215                 custom_device_label.setVisible(False)
216                 self.video_device_edit.setVisible(False)
217                 self.video_device_edit.setText(combo_data.toString())
218
219         # on save trigger for the video device selection window,
220         # stores the chosen video device on close.
221         def on_save():
222             device = str(self.video_device_edit.text())
223             self.config.set_key("video_device", device)
224             d.accept()
225
226         custom_device_label = QLabel("Video device: ")
227         custom_device_label.setVisible(False)
228         layout.addWidget(custom_device_label,1,0)
229         self.video_device_edit = QLineEdit()
230         self.video_device_edit.setVisible(False)
231         layout.addWidget(self.video_device_edit, 1,1,2,2)
232         combo.currentIndexChanged.connect(on_change)
233
234         combo.addItem("Default","default")
235         for camera, device in system_cameras.items():
236             combo.addItem(camera, device)
237         combo.addItem("Manually specify a device",self.config.get("video_device"))
238
239         # Populate the previously chosen device:
240         index = combo.findData(self.config.get("video_device"))
241         combo.setCurrentIndex(index)
242
243         layout.addWidget(combo,0,1)
244
245         self.accept = QPushButton(_("Done"))
246         self.accept.clicked.connect(on_save)
247         layout.addWidget(self.accept,4,2)
248
249         if d.exec_():
250           return True
251         else:
252           return False
253
254
255
256 def parse_uri(uri):
257     if not uri:
258         return {}
259
260     if ':' not in uri:
261         # It's just an address (not BIP21)
262         return {'address': uri}
263
264     if '//' not in uri:
265         # Workaround for urlparse, it don't handle bitcoin: URI properly
266         uri = uri.replace(':', '://')
267         
268     uri = urlparse(uri)
269     result = {'address': uri.netloc} 
270     
271     if uri.query.startswith('?'):
272         params = parse_qs(uri.query[1:])
273     else:
274         params = parse_qs(uri.query)    
275
276     for k,v in params.items():
277         if k in ('amount', 'label', 'message'):
278             result[k] = v[0]
279         
280     return result    
281
282
283
284
285
286 if __name__ == '__main__':
287     # Run some tests
288     
289     assert(parse_uri('1Marek48fwU7mugmSe186do2QpUkBnpzSN') ==
290            {'address': '1Marek48fwU7mugmSe186do2QpUkBnpzSN'})
291
292     assert(parse_uri('bitcoin://1Marek48fwU7mugmSe186do2QpUkBnpzSN') ==
293            {'address': '1Marek48fwU7mugmSe186do2QpUkBnpzSN'})
294     
295     assert(parse_uri('bitcoin:1Marek48fwU7mugmSe186do2QpUkBnpzSN') ==
296            {'address': '1Marek48fwU7mugmSe186do2QpUkBnpzSN'})
297     
298     assert(parse_uri('bitcoin:1Marek48fwU7mugmSe186do2QpUkBnpzSN?amount=10') ==
299            {'amount': '10', 'address': '1Marek48fwU7mugmSe186do2QpUkBnpzSN'})
300     
301     assert(parse_uri('bitcoin:1Marek48fwU7mugmSe186do2QpUkBnpzSN?amount=10&label=slush&message=Small%20tip%20to%20slush') ==
302            {'amount': '10', 'label': 'slush', 'message': 'Small tip to slush', 'address': '1Marek48fwU7mugmSe186do2QpUkBnpzSN'})
303     
304