/*
(c) Copyright 2012 - 2026 Anton Sviridenko
https://picapica.im
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, version 3.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see .
*/
#include "qrscandialog.h"
#include "../qrcode.h"
#include "../videodevice.h"
#include "../settings.h"
#include "../globals.h"
#include
#include
#include
#include
#include
#include
#include
#include
// What the camera is asked for. 720p resolves the modules of a code shown on a
// phone held at a comfortable distance, where 480p often does not, and is
// still cheap to search; a camera without it is opened at the nearest size
// below. The rate only has to be enough for the picture to follow the hand.
static const int kScanWidth = 1280;
static const int kScanHeight = 720;
static const int kScanFrameRate = 30;
// The guide square's side, as a share of the shorter side of the picture.
static const double kGuideSize = 0.6;
QrViewfinder::QrViewfinder(QWidget *parent) :
QWidget(parent)
{
setMinimumSize(480, 360);
setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
}
void QrViewfinder::setFrame(const QImage &frame)
{
m_frame = frame;
update();
}
void QrViewfinder::setMessage(const QString &message)
{
m_message = message;
update();
}
void QrViewfinder::paintEvent(QPaintEvent *)
{
QPainter p(this);
p.fillRect(rect(), Qt::black);
if (m_frame.isNull())
{
p.setPen(Qt::white);
p.drawText(rect().adjusted(16, 16, -16, -16), Qt::AlignCenter | Qt::TextWordWrap, m_message);
return;
}
// The picture fitted into the widget, keeping its aspect ratio.
QSize fitted = m_frame.size().scaled(size(), Qt::KeepAspectRatio);
QRect target(QPoint((width() - fitted.width()) / 2, (height() - fitted.height()) / 2), fitted);
p.setRenderHint(QPainter::SmoothPixmapTransform);
p.save();
// Mirrored about the picture's vertical centre line.
p.translate(target.left() * 2 + target.width(), 0);
p.scale(-1, 1);
p.drawImage(target, m_frame);
p.restore();
// The guide: everything but the square dimmed...
const int side = (int)(qMin(target.width(), target.height()) * kGuideSize);
const QRect guide(target.center().x() - side / 2, target.center().y() - side / 2, side, side);
QPainterPath outside;
outside.addRect(target);
QPainterPath inside;
inside.addRect(guide);
p.fillPath(outside.subtracted(inside), QColor(0, 0, 0, 128));
// ...and its corners marked.
const int arm = side / 6;
QPen pen(Qt::white);
pen.setWidth(qMax(3, side / 60));
pen.setCapStyle(Qt::SquareCap);
p.setPen(pen);
p.setRenderHint(QPainter::Antialiasing);
const QPoint corners[4] = { guide.topLeft(), guide.topRight(), guide.bottomRight(), guide.bottomLeft() };
const int dx[4] = { 1, -1, -1, 1 };
const int dy[4] = { 1, 1, -1, -1 };
for (int i = 0; i < 4; i++)
{
p.drawLine(corners[i], corners[i] + QPoint(dx[i] * arm, 0));
p.drawLine(corners[i], corners[i] + QPoint(0, dy[i] * arm));
}
}
QrScanDialog::QrScanDialog(QWidget *parent) :
QDialog(parent),
m_sessionNumber(0),
m_cameraRunning(false),
m_readerBusy(false)
{
setWindowTitle(tr("Scan the QR Code"));
QVBoxLayout *layout = new QVBoxLayout(this);
QLabel *hint = new QLabel(tr("Hold the QR code shown by the other person's Pica Pica "
"(Account → Show My Pica Pica ID) inside the square."));
hint->setTextFormat(Qt::RichText);
hint->setWordWrap(true);
m_cameras = new QComboBox();
m_viewfinder = new QrViewfinder();
m_status = new QLabel();
m_status->setWordWrap(true);
m_cancel = new QPushButton(tr("Cancel"));
connect(m_cancel, SIGNAL(clicked()), this, SLOT(reject()));
QHBoxLayout *cameraRow = new QHBoxLayout();
cameraRow->addWidget(new QLabel(tr("Camera:")));
cameraRow->addWidget(m_cameras, 1);
layout->addWidget(hint);
layout->addLayout(cameraRow);
layout->addWidget(m_viewfinder, 1);
layout->addWidget(m_status);
layout->addWidget(m_cancel, 0, Qt::AlignHCenter);
m_camera = new VideoDevice();
m_camera->moveToThread(&m_cameraThread);
connect(m_camera, SIGNAL(captureStarted(QString,int,int,double)), this, SLOT(cameraStarted(QString,int,int,double)));
connect(m_camera, SIGNAL(frameReady(QImage)), this, SLOT(cameraFrame(QImage)));
connect(m_camera, SIGNAL(errorOccurred(QString)), this, SLOT(cameraError(QString)));
connect(m_camera, SIGNAL(cameraBusy()), this, SLOT(cameraBusy()));
m_cameraThread.start();
m_reader = new QrCodeReader();
m_reader->moveToThread(&m_readerThread);
connect(m_reader, SIGNAL(frameRead(QString)), this, SLOT(frameRead(QString)));
m_readerThread.start();
// The cameras, with the one calls use selected - with nothing configured
// yet, the first one, as a call would.
// Enumerated through an instance of its own: m_camera belongs to its thread.
VideoDevice enumerator;
QList cameras = enumerator.Enumerate(CAPTURE);
const QString configured = Settings(config_dbname).loadValue("video.capture_device", QString()).toString();
int selected = 0;
for (int i = 0; i < cameras.size(); i++)
{
m_cameras->addItem(cameras.at(i).humanReadable.isEmpty()
? cameras.at(i).device
: QString("%1 (%2)").arg(cameras.at(i).humanReadable, cameras.at(i).device),
cameras.at(i).device);
if (cameras.at(i).device == configured)
selected = i;
}
if (cameras.isEmpty())
{
m_cameras->setEnabled(false);
m_viewfinder->setMessage(tr("No camera found"));
return;
}
m_cameras->setCurrentIndex(selected);
connect(m_cameras, SIGNAL(currentIndexChanged(int)), this, SLOT(cameraChanged(int)));
startCamera();
}
QrScanDialog::~QrScanDialog()
{
// Direct call: the camera's thread is inside Preview(), see stopCamera().
m_camera->Close();
m_cameraThread.quit();
m_cameraThread.wait();
delete m_camera;
m_readerThread.quit();
m_readerThread.wait();
delete m_reader;
}
void QrScanDialog::startCamera()
{
const QString device = m_cameras->itemData(m_cameras->currentIndex()).toString();
if (device.isEmpty())
return;
m_sessionId = QString("QR code scan %1").arg(++m_sessionNumber).toUtf8();
m_cameraRunning = true;
m_viewfinder->setFrame(QImage());
m_viewfinder->setMessage(tr("Starting the camera..."));
m_status->clear();
m_camera->openSession(m_sessionId, m_sessionId);
QMetaObject::invokeMethod(m_camera, "configureCapture", Qt::QueuedConnection,
Q_ARG(QString, device),
Q_ARG(int, kScanWidth), Q_ARG(int, kScanHeight),
Q_ARG(int, kScanFrameRate),
Q_ARG(bool, false), Q_ARG(QString, QString()),
Q_ARG(int, 0), Q_ARG(int, 0),
Q_ARG(QByteArray, m_sessionId), Q_ARG(QByteArray, m_sessionId));
QMetaObject::invokeMethod(m_camera, "Preview", Qt::QueuedConnection);
}
void QrScanDialog::stopCamera()
{
// A direct call, since the camera's thread is busy inside Preview() and a
// queued one would wait behind it for good - see VideoDevice.
m_camera->Close();
m_cameraRunning = false;
}
void QrScanDialog::cameraChanged(int)
{
stopCamera();
startCamera();
}
void QrScanDialog::cameraStarted(QString codec, int width, int height, double frameRate)
{
if (!m_cameraRunning)
return;
m_status->setText(tr("Camera: %1x%2 @%3 %4")
.arg(width).arg(height)
.arg(frameRate, 0, 'f', frameRate < 10.0 ? 1 : 0)
.arg(codec.isEmpty() ? tr("uncompressed") : codec));
}
void QrScanDialog::cameraFrame(QImage frame)
{
// Frames of a camera already stopped, still in the event queue.
if (!m_cameraRunning)
return;
m_viewfinder->setFrame(frame);
if (m_readerBusy)
return;
m_readerBusy = true;
QMetaObject::invokeMethod(m_reader, "read", Qt::QueuedConnection, Q_ARG(QImage, frame));
}
void QrScanDialog::cameraError(QString message)
{
if (!m_cameraRunning)
return;
m_cameraRunning = false;
m_viewfinder->setFrame(QImage());
m_viewfinder->setMessage(message);
}
void QrScanDialog::cameraBusy()
{
// Not something to retry from here: the camera is only freed by whoever
// holds it, and the dialog cannot tell when that happens.
cameraError(tr("The camera is in use by a call or another application.\n\n"
"Choose another camera above, or close this window and try again "
"once the camera is free."));
}
void QrScanDialog::frameRead(QString text)
{
m_readerBusy = false;
if (text.isEmpty() || !m_cameraRunning)
return;
const QByteArray id = picaIdFromQrText(text);
if (id.isEmpty())
{
// Some other QR code - a web address, say. Scanning goes on.
m_status->setText(tr("This QR code does not contain a Pica Pica ID"));
return;
}
m_scannedId = id;
stopCamera();
accept();
}