electrum-bitcoinprivate/plugins/qrscanner.py

279 lines
8.8 KiB
Python
Raw Normal View History

from electrum.util import print_error
2013-03-03 06:00:12 -08:00
from urlparse import urlparse, parse_qs
from PyQt4.QtGui import QPushButton, QMessageBox, QDialog, QVBoxLayout, QHBoxLayout, QGridLayout, QLabel, QLineEdit, QComboBox
from PyQt4.QtCore import Qt
2013-09-11 02:45:58 -07:00
from electrum.i18n import _
import re
import os
from electrum import Transaction
from electrum.bitcoin import MIN_RELAY_TX_FEE, is_valid
2013-09-24 01:06:03 -07:00
from electrum_gui.qt.qrcodewidget import QRCodeWidget
2013-09-11 02:45:58 -07:00
from electrum import bmp
from electrum_gui.qt import HelpButton, EnterButton
import json
try:
import zbar
2013-03-03 06:00:12 -08:00
except ImportError:
zbar = None
2013-09-11 02:45:58 -07:00
from electrum import BasePlugin
2013-03-15 01:58:05 -07:00
class Plugin(BasePlugin):
2013-03-03 05:49:42 -08:00
def fullname(self): return 'QR scans'
def description(self): return "QR Scans.\nInstall the zbar package to enable this plugin.\nOn linux, type: 'apt-get install python-zbar'"
def __init__(self, gui, name):
BasePlugin.__init__(self, gui, name)
self._is_available = self._init()
def _init(self):
2013-03-15 01:58:05 -07:00
if not zbar:
return False
try:
proc = zbar.Processor()
proc.init(video_device=self.video_device())
2013-03-15 01:58:05 -07:00
except zbar.SystemError:
# Cannot open video device
pass
#return False
2013-03-15 01:58:05 -07:00
return True
2013-03-03 05:49:42 -08:00
2014-06-12 08:40:34 -07:00
def init(self):
self.win = self.gui.main_window
self.win.raw_transaction_menu.addAction(_("&From QR code"), self.read_raw_qr)
2014-06-12 13:32:24 -07:00
b = QPushButton(_("Scan QR code"))
b.clicked.connect(self.fill_from_qr)
self.win.send_grid.addWidget(b, 1, 5)
self.win.send_grid.setColumnStretch(5, 0)
self.win.send_grid.setColumnStretch(6, 1)
def init_transaction_dialog(self, dialog, buttons):
b = QPushButton(_("Show QR code"))
2014-06-12 22:38:34 -07:00
b.clicked.connect(lambda: self.show_raw_qr(dialog.tx))
buttons.insertWidget(1,b)
2014-06-12 08:40:34 -07:00
2013-11-01 11:58:19 -07:00
def is_available(self):
return self._is_available
2013-03-15 01:58:05 -07:00
def scan_qr(self):
proc = zbar.Processor()
try:
proc.init(video_device=self.video_device())
except zbar.SystemError, e:
2014-06-12 08:40:34 -07:00
QMessageBox.warning(self.win, _('Error'), _(e), _('OK'))
return
2013-03-15 01:58:05 -07:00
proc.visible = True
while True:
try:
proc.process_one()
2013-11-10 12:30:57 -08:00
except Exception:
2013-03-15 01:58:05 -07:00
# User closed the preview window
return {}
for r in proc.results:
if str(r.type) != 'QRCODE':
continue
return r.data
2013-03-15 01:58:05 -07:00
2014-06-12 22:38:34 -07:00
def show_raw_qr(self, tx):
try:
json_text = json.dumps(tx.as_dict()).replace(' ', '')
self.show_tx_qrcode(json_text, 'Unsigned Transaction')
2013-11-09 20:21:02 -08:00
except Exception as e:
2014-06-12 08:40:34 -07:00
self.win.show_message(str(e))
def show_tx_qrcode(self, data, title):
if not data: return
2014-06-12 08:40:34 -07:00
d = QDialog(self.win)
d.setModal(1)
d.setWindowTitle(title)
d.setMinimumSize(250, 525)
vbox = QVBoxLayout()
qrw = QRCodeWidget(data)
vbox.addWidget(qrw, 0)
hbox = QHBoxLayout()
hbox.addStretch(1)
def print_qr(self):
filename = "qrcode.bmp"
electrum_gui.bmp.save_qrcode(qrw.qr, filename)
QMessageBox.information(None, _('Message'), _("QR code saved to file") + " " + filename, _('OK'))
b = QPushButton(_("Save"))
hbox.addWidget(b)
b.clicked.connect(print_qr)
b = QPushButton(_("Close"))
hbox.addWidget(b)
b.clicked.connect(d.accept)
b.setDefault(True)
vbox.addLayout(hbox, 1)
d.setLayout(vbox)
d.exec_()
def read_raw_qr(self):
2013-05-27 12:18:29 -07:00
qrcode = self.scan_qr()
if not qrcode:
return
tx = self.win.tx_from_text(qrcode)
if not tx:
return
self.win.show_transaction(tx)
2013-03-15 01:58:05 -07:00
def fill_from_qr(self):
qrcode = parse_uri(self.scan_qr())
if not qrcode:
return
2013-03-15 01:58:05 -07:00
if 'address' in qrcode:
2014-06-12 08:40:34 -07:00
self.win.payto_e.setText(qrcode['address'])
2013-03-15 01:58:05 -07:00
if 'amount' in qrcode:
2014-06-12 08:40:34 -07:00
self.win.amount_e.setText(str(qrcode['amount']))
2013-03-15 01:58:05 -07:00
if 'label' in qrcode:
2014-06-12 08:40:34 -07:00
self.win.message_e.setText(qrcode['label'])
2013-03-15 01:58:05 -07:00
if 'message' in qrcode:
2014-06-12 08:40:34 -07:00
self.win.message_e.setText("%s (%s)" % (self.win.message_e.text(), qrcode['message']))
2013-03-15 01:58:05 -07:00
def video_device(self):
device = self.config.get("video_device", "default")
if device == 'default':
device = ''
return device
def requires_settings(self):
return True
def settings_widget(self, window):
return EnterButton(_('Settings'), self.settings_dialog)
def _find_system_cameras(self):
device_root = "/sys/class/video4linux"
devices = {} # Name -> device
if os.path.exists(device_root):
for device in os.listdir(device_root):
name = open(os.path.join(device_root, device, 'name')).read()
devices[name] = os.path.join("/dev",device)
return devices
def settings_dialog(self):
system_cameras = self._find_system_cameras()
d = QDialog()
layout = QGridLayout(d)
layout.addWidget(QLabel("Choose a video device:"),0,0)
# Create a combo box with the available video devices:
combo = QComboBox()
# on change trigger for video device selection, makes the
# manual device selection only appear when needed:
def on_change(x):
combo_text = str(combo.itemText(x))
combo_data = combo.itemData(x)
if combo_text == "Manually specify a device":
custom_device_label.setVisible(True)
self.video_device_edit.setVisible(True)
if self.config.get("video_device") == "default":
self.video_device_edit.setText("")
else:
self.video_device_edit.setText(self.config.get("video_device"))
else:
custom_device_label.setVisible(False)
self.video_device_edit.setVisible(False)
self.video_device_edit.setText(combo_data.toString())
# on save trigger for the video device selection window,
# stores the chosen video device on close.
def on_save():
device = str(self.video_device_edit.text())
self.config.set_key("video_device", device)
d.accept()
custom_device_label = QLabel("Video device: ")
custom_device_label.setVisible(False)
layout.addWidget(custom_device_label,1,0)
self.video_device_edit = QLineEdit()
self.video_device_edit.setVisible(False)
layout.addWidget(self.video_device_edit, 1,1,2,2)
combo.currentIndexChanged.connect(on_change)
combo.addItem("Default","default")
for camera, device in system_cameras.items():
combo.addItem(camera, device)
combo.addItem("Manually specify a device",self.config.get("video_device"))
# Populate the previously chosen device:
index = combo.findData(self.config.get("video_device"))
combo.setCurrentIndex(index)
layout.addWidget(combo,0,1)
self.accept = QPushButton(_("Done"))
self.accept.clicked.connect(on_save)
layout.addWidget(self.accept,4,2)
if d.exec_():
return True
else:
return False
def parse_uri(uri):
if not uri:
return {}
if ':' not in uri:
# It's just an address (not BIP21)
return {'address': uri}
if '//' not in uri:
# Workaround for urlparse, it don't handle bitcoin: URI properly
uri = uri.replace(':', '://')
uri = urlparse(uri)
result = {'address': uri.netloc}
if uri.query.startswith('?'):
params = parse_qs(uri.query[1:])
else:
params = parse_qs(uri.query)
for k,v in params.items():
if k in ('amount', 'label', 'message'):
result[k] = v[0]
return result
2013-03-03 05:49:42 -08:00
if __name__ == '__main__':
# Run some tests
assert(parse_uri('1Marek48fwU7mugmSe186do2QpUkBnpzSN') ==
{'address': '1Marek48fwU7mugmSe186do2QpUkBnpzSN'})
assert(parse_uri('bitcoin://1Marek48fwU7mugmSe186do2QpUkBnpzSN') ==
{'address': '1Marek48fwU7mugmSe186do2QpUkBnpzSN'})
assert(parse_uri('bitcoin:1Marek48fwU7mugmSe186do2QpUkBnpzSN') ==
{'address': '1Marek48fwU7mugmSe186do2QpUkBnpzSN'})
assert(parse_uri('bitcoin:1Marek48fwU7mugmSe186do2QpUkBnpzSN?amount=10') ==
{'amount': '10', 'address': '1Marek48fwU7mugmSe186do2QpUkBnpzSN'})
assert(parse_uri('bitcoin:1Marek48fwU7mugmSe186do2QpUkBnpzSN?amount=10&label=slush&message=Small%20tip%20to%20slush') ==
{'amount': '10', 'label': 'slush', 'message': 'Small tip to slush', 'address': '1Marek48fwU7mugmSe186do2QpUkBnpzSN'})