c42347c27cb5dfa3142c1cfd614f4eda57b11e2d
[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.UnsupportedError:
39             return False
40         except zbar.SystemError:
41             # Cannot open video device
42             pass
43             #return False
44
45         return True
46
47     def init(self):
48         self.win = self.gui.main_window
49         self.win.raw_transaction_menu.addAction(_("&From QR code"), self.read_raw_qr)
50
51     def is_available(self):
52         return self._is_available
53
54     def scan_qr_hook(self, func):
55         data = self.scan_qr()
56         if type(data) != str:
57             return
58         func(data)
59
60     def scan_qr(self):
61         proc = zbar.Processor()
62         try:
63             proc.init(video_device=self.video_device())
64         except zbar.SystemError, e:
65             QMessageBox.warning(self.win, _('Error'), _(e), _('OK'))
66             return
67
68         proc.visible = True
69
70         while True:
71             try:
72                 proc.process_one()
73             except Exception:
74                 # User closed the preview window
75                 return {}
76
77             for r in proc.results:
78                 if str(r.type) != 'QRCODE':
79                     continue
80                 return r.data
81         
82
83     def read_raw_qr(self):
84         qrcode = self.scan_qr()
85         if not qrcode:
86             return
87         data = qrcode
88
89         # transactions are binary, but qrcode seems to return utf8...
90         z = data.decode('utf8')
91         s = ''
92         for b in z:
93             s += chr(ord(b))
94         data = s.encode('hex')
95         tx = self.win.tx_from_text(data)
96         if not tx:
97             return
98         self.win.show_transaction(tx)
99
100     def video_device(self):
101         device = self.config.get("video_device", "default")
102         if device == 'default':
103             device = ''
104         return device
105
106     def requires_settings(self):
107         return True
108
109     def settings_widget(self, window):
110         return EnterButton(_('Settings'), self.settings_dialog)
111     
112     def _find_system_cameras(self):
113         device_root = "/sys/class/video4linux"
114         devices = {} # Name -> device
115         if os.path.exists(device_root):
116             for device in os.listdir(device_root):
117                 name = open(os.path.join(device_root, device, 'name')).read()
118                 devices[name] = os.path.join("/dev",device)
119         return devices
120
121     def settings_dialog(self):
122         system_cameras = self._find_system_cameras()
123
124         d = QDialog()
125         layout = QGridLayout(d)
126         layout.addWidget(QLabel("Choose a video device:"),0,0)
127
128         # Create a combo box with the available video devices:
129         combo = QComboBox()
130
131         # on change trigger for video device selection, makes the
132         # manual device selection only appear when needed:
133         def on_change(x):
134             combo_text = str(combo.itemText(x))
135             combo_data = combo.itemData(x)
136             if combo_text == "Manually specify a device":
137                 custom_device_label.setVisible(True)
138                 self.video_device_edit.setVisible(True)
139                 if self.config.get("video_device") == "default":
140                     self.video_device_edit.setText("")
141                 else:
142                     self.video_device_edit.setText(self.config.get("video_device",''))
143             else:
144                 custom_device_label.setVisible(False)
145                 self.video_device_edit.setVisible(False)
146                 self.video_device_edit.setText(combo_data.toString())
147
148         # on save trigger for the video device selection window,
149         # stores the chosen video device on close.
150         def on_save():
151             device = str(self.video_device_edit.text())
152             self.config.set_key("video_device", device)
153             d.accept()
154
155         custom_device_label = QLabel("Video device: ")
156         custom_device_label.setVisible(False)
157         layout.addWidget(custom_device_label,1,0)
158         self.video_device_edit = QLineEdit()
159         self.video_device_edit.setVisible(False)
160         layout.addWidget(self.video_device_edit, 1,1,2,2)
161         combo.currentIndexChanged.connect(on_change)
162
163         combo.addItem("Default","default")
164         for camera, device in system_cameras.items():
165             combo.addItem(camera, device)
166         combo.addItem("Manually specify a device",self.config.get("video_device"))
167
168         # Populate the previously chosen device:
169         index = combo.findData(self.config.get("video_device"))
170         combo.setCurrentIndex(index)
171
172         layout.addWidget(combo,0,1)
173
174         self.accept = QPushButton(_("Done"))
175         self.accept.clicked.connect(on_save)
176         layout.addWidget(self.accept,4,2)
177
178         if d.exec_():
179           return True
180         else:
181           return False