move qr code operations to transaction window and transaction menu
[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
49     def init_transaction_dialog(self, dialog, buttons):
50         print dialog, buttons
51         #if not wallet.seed:
52         b = QPushButton(_("Show QR code"))
53         b.clicked.connect(self.show_raw_qr)
54         buttons.insertWidget(1,b)
55
56     def load_wallet(self, wallet):
57         b = QPushButton(_("Scan QR code"))
58         b.clicked.connect(self.fill_from_qr)
59         self.send_tab_grid.addWidget(b, 1, 5)
60         self.send_tab_grid.setColumnStretch(5, 0)
61         self.send_tab_grid.setColumnStretch(6, 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 not qrcode:
157             return
158         tx = self.win.tx_from_text(qrcode)
159         if not tx:
160             return
161         self.win.show_transaction(tx)
162
163
164     def fill_from_qr(self):
165         qrcode = parse_uri(self.scan_qr())
166         if not qrcode:
167             return
168
169         if 'address' in qrcode:
170             self.win.payto_e.setText(qrcode['address'])
171         if 'amount' in qrcode:
172             self.win.amount_e.setText(str(qrcode['amount']))
173         if 'label' in qrcode:
174             self.win.message_e.setText(qrcode['label'])
175         if 'message' in qrcode:
176             self.win.message_e.setText("%s (%s)" % (self.win.message_e.text(), qrcode['message']))
177                 
178     def video_device(self):
179         device = self.config.get("video_device", "default")
180         if device == 'default':
181             device = ''
182         return device
183
184     def requires_settings(self):
185         return True
186
187     def settings_widget(self, window):
188         return EnterButton(_('Settings'), self.settings_dialog)
189     
190     def _find_system_cameras(self):
191         device_root = "/sys/class/video4linux"
192         devices = {} # Name -> device
193         if os.path.exists(device_root):
194             for device in os.listdir(device_root):
195                 name = open(os.path.join(device_root, device, 'name')).read()
196                 devices[name] = os.path.join("/dev",device)
197         return devices
198
199     def settings_dialog(self):
200         system_cameras = self._find_system_cameras()
201
202         d = QDialog()
203         layout = QGridLayout(d)
204         layout.addWidget(QLabel("Choose a video device:"),0,0)
205
206         # Create a combo box with the available video devices:
207         combo = QComboBox()
208
209         # on change trigger for video device selection, makes the
210         # manual device selection only appear when needed:
211         def on_change(x):
212             combo_text = str(combo.itemText(x))
213             combo_data = combo.itemData(x)
214             if combo_text == "Manually specify a device":
215                 custom_device_label.setVisible(True)
216                 self.video_device_edit.setVisible(True)
217                 if self.config.get("video_device") == "default":
218                     self.video_device_edit.setText("")
219                 else:
220                     self.video_device_edit.setText(self.config.get("video_device"))
221             else:
222                 custom_device_label.setVisible(False)
223                 self.video_device_edit.setVisible(False)
224                 self.video_device_edit.setText(combo_data.toString())
225
226         # on save trigger for the video device selection window,
227         # stores the chosen video device on close.
228         def on_save():
229             device = str(self.video_device_edit.text())
230             self.config.set_key("video_device", device)
231             d.accept()
232
233         custom_device_label = QLabel("Video device: ")
234         custom_device_label.setVisible(False)
235         layout.addWidget(custom_device_label,1,0)
236         self.video_device_edit = QLineEdit()
237         self.video_device_edit.setVisible(False)
238         layout.addWidget(self.video_device_edit, 1,1,2,2)
239         combo.currentIndexChanged.connect(on_change)
240
241         combo.addItem("Default","default")
242         for camera, device in system_cameras.items():
243             combo.addItem(camera, device)
244         combo.addItem("Manually specify a device",self.config.get("video_device"))
245
246         # Populate the previously chosen device:
247         index = combo.findData(self.config.get("video_device"))
248         combo.setCurrentIndex(index)
249
250         layout.addWidget(combo,0,1)
251
252         self.accept = QPushButton(_("Done"))
253         self.accept.clicked.connect(on_save)
254         layout.addWidget(self.accept,4,2)
255
256         if d.exec_():
257           return True
258         else:
259           return False
260
261
262
263 def parse_uri(uri):
264     if not uri:
265         return {}
266
267     if ':' not in uri:
268         # It's just an address (not BIP21)
269         return {'address': uri}
270
271     if '//' not in uri:
272         # Workaround for urlparse, it don't handle bitcoin: URI properly
273         uri = uri.replace(':', '://')
274         
275     uri = urlparse(uri)
276     result = {'address': uri.netloc} 
277     
278     if uri.query.startswith('?'):
279         params = parse_qs(uri.query[1:])
280     else:
281         params = parse_qs(uri.query)    
282
283     for k,v in params.items():
284         if k in ('amount', 'label', 'message'):
285             result[k] = v[0]
286         
287     return result    
288
289
290
291
292
293 if __name__ == '__main__':
294     # Run some tests
295     
296     assert(parse_uri('1Marek48fwU7mugmSe186do2QpUkBnpzSN') ==
297            {'address': '1Marek48fwU7mugmSe186do2QpUkBnpzSN'})
298
299     assert(parse_uri('bitcoin://1Marek48fwU7mugmSe186do2QpUkBnpzSN') ==
300            {'address': '1Marek48fwU7mugmSe186do2QpUkBnpzSN'})
301     
302     assert(parse_uri('bitcoin:1Marek48fwU7mugmSe186do2QpUkBnpzSN') ==
303            {'address': '1Marek48fwU7mugmSe186do2QpUkBnpzSN'})
304     
305     assert(parse_uri('bitcoin:1Marek48fwU7mugmSe186do2QpUkBnpzSN?amount=10') ==
306            {'amount': '10', 'address': '1Marek48fwU7mugmSe186do2QpUkBnpzSN'})
307     
308     assert(parse_uri('bitcoin:1Marek48fwU7mugmSe186do2QpUkBnpzSN?amount=10&label=slush&message=Small%20tip%20to%20slush') ==
309            {'amount': '10', 'label': 'slush', 'message': 'Small tip to slush', 'address': '1Marek48fwU7mugmSe186do2QpUkBnpzSN'})
310     
311