qrscanner: use win.show_qr_code
[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(lambda: self.show_raw_qr(dialog.tx))
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, tx):
85         try:
86             json_text = json.dumps(tx.as_dict()).replace(' ', '')
87             self.win.show_qrcode(json_text, 'Unsigned Transaction')
88         except Exception as e:
89             self.win.show_message(str(e))
90
91
92     def read_raw_qr(self):
93         qrcode = self.scan_qr()
94         if not qrcode:
95             return
96         tx = self.win.tx_from_text(qrcode)
97         if not tx:
98             return
99         self.win.show_transaction(tx)
100
101
102     def fill_from_qr(self):
103         qrcode = parse_uri(self.scan_qr())
104         if not qrcode:
105             return
106
107         if 'address' in qrcode:
108             self.win.payto_e.setText(qrcode['address'])
109         if 'amount' in qrcode:
110             self.win.amount_e.setText(str(qrcode['amount']))
111         if 'label' in qrcode:
112             self.win.message_e.setText(qrcode['label'])
113         if 'message' in qrcode:
114             self.win.message_e.setText("%s (%s)" % (self.win.message_e.text(), qrcode['message']))
115                 
116     def video_device(self):
117         device = self.config.get("video_device", "default")
118         if device == 'default':
119             device = ''
120         return device
121
122     def requires_settings(self):
123         return True
124
125     def settings_widget(self, window):
126         return EnterButton(_('Settings'), self.settings_dialog)
127     
128     def _find_system_cameras(self):
129         device_root = "/sys/class/video4linux"
130         devices = {} # Name -> device
131         if os.path.exists(device_root):
132             for device in os.listdir(device_root):
133                 name = open(os.path.join(device_root, device, 'name')).read()
134                 devices[name] = os.path.join("/dev",device)
135         return devices
136
137     def settings_dialog(self):
138         system_cameras = self._find_system_cameras()
139
140         d = QDialog()
141         layout = QGridLayout(d)
142         layout.addWidget(QLabel("Choose a video device:"),0,0)
143
144         # Create a combo box with the available video devices:
145         combo = QComboBox()
146
147         # on change trigger for video device selection, makes the
148         # manual device selection only appear when needed:
149         def on_change(x):
150             combo_text = str(combo.itemText(x))
151             combo_data = combo.itemData(x)
152             if combo_text == "Manually specify a device":
153                 custom_device_label.setVisible(True)
154                 self.video_device_edit.setVisible(True)
155                 if self.config.get("video_device") == "default":
156                     self.video_device_edit.setText("")
157                 else:
158                     self.video_device_edit.setText(self.config.get("video_device"))
159             else:
160                 custom_device_label.setVisible(False)
161                 self.video_device_edit.setVisible(False)
162                 self.video_device_edit.setText(combo_data.toString())
163
164         # on save trigger for the video device selection window,
165         # stores the chosen video device on close.
166         def on_save():
167             device = str(self.video_device_edit.text())
168             self.config.set_key("video_device", device)
169             d.accept()
170
171         custom_device_label = QLabel("Video device: ")
172         custom_device_label.setVisible(False)
173         layout.addWidget(custom_device_label,1,0)
174         self.video_device_edit = QLineEdit()
175         self.video_device_edit.setVisible(False)
176         layout.addWidget(self.video_device_edit, 1,1,2,2)
177         combo.currentIndexChanged.connect(on_change)
178
179         combo.addItem("Default","default")
180         for camera, device in system_cameras.items():
181             combo.addItem(camera, device)
182         combo.addItem("Manually specify a device",self.config.get("video_device"))
183
184         # Populate the previously chosen device:
185         index = combo.findData(self.config.get("video_device"))
186         combo.setCurrentIndex(index)
187
188         layout.addWidget(combo,0,1)
189
190         self.accept = QPushButton(_("Done"))
191         self.accept.clicked.connect(on_save)
192         layout.addWidget(self.accept,4,2)
193
194         if d.exec_():
195           return True
196         else:
197           return False
198
199
200
201 def parse_uri(uri):
202     if not uri:
203         return {}
204
205     if ':' not in uri:
206         # It's just an address (not BIP21)
207         return {'address': uri}
208
209     if '//' not in uri:
210         # Workaround for urlparse, it don't handle bitcoin: URI properly
211         uri = uri.replace(':', '://')
212         
213     uri = urlparse(uri)
214     result = {'address': uri.netloc} 
215     
216     if uri.query.startswith('?'):
217         params = parse_qs(uri.query[1:])
218     else:
219         params = parse_qs(uri.query)    
220
221     for k,v in params.items():
222         if k in ('amount', 'label', 'message'):
223             result[k] = v[0]
224         
225     return result    
226
227
228
229
230
231 if __name__ == '__main__':
232     # Run some tests
233     
234     assert(parse_uri('1Marek48fwU7mugmSe186do2QpUkBnpzSN') ==
235            {'address': '1Marek48fwU7mugmSe186do2QpUkBnpzSN'})
236
237     assert(parse_uri('bitcoin://1Marek48fwU7mugmSe186do2QpUkBnpzSN') ==
238            {'address': '1Marek48fwU7mugmSe186do2QpUkBnpzSN'})
239     
240     assert(parse_uri('bitcoin:1Marek48fwU7mugmSe186do2QpUkBnpzSN') ==
241            {'address': '1Marek48fwU7mugmSe186do2QpUkBnpzSN'})
242     
243     assert(parse_uri('bitcoin:1Marek48fwU7mugmSe186do2QpUkBnpzSN?amount=10') ==
244            {'amount': '10', 'address': '1Marek48fwU7mugmSe186do2QpUkBnpzSN'})
245     
246     assert(parse_uri('bitcoin:1Marek48fwU7mugmSe186do2QpUkBnpzSN?amount=10&label=slush&message=Small%20tip%20to%20slush') ==
247            {'amount': '10', 'label': 'slush', 'message': 'Small tip to slush', 'address': '1Marek48fwU7mugmSe186do2QpUkBnpzSN'})
248     
249