summaryrefslogtreecommitdiffstats
path: root/pica-client/dialogs/qrscandialog.cpp
blob: db6dac47654465e161528d21789682b801954ebd (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
/*
	(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 <https://www.gnu.org/licenses/>.
*/
#include "qrscandialog.h"
#include "../qrcode.h"
#include "../videodevice.h"
#include "../settings.h"
#include "../globals.h"

#include <QComboBox>
#include <QLabel>
#include <QPushButton>
#include <QVBoxLayout>
#include <QHBoxLayout>
#include <QPainter>
#include <QPainterPath>
#include <QMetaObject>

// 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 "
	                             "(<i>Account &rarr; Show My Pica Pica ID</i>) 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<MediaDeviceInfo> 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();
}