summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
-rw-r--r--Makefile.am18
-rw-r--r--configure.ac108
-rw-r--r--debian/control1
-rwxr-xr-xdebian/rules2
-rwxr-xr-xgentoo/pica-pica-9999.ebuild6
-rw-r--r--pica-client/contactlistwidget.cpp139
-rw-r--r--pica-client/contactlistwidget.h17
-rw-r--r--pica-client/dialogs/qrscandialog.cpp310
-rw-r--r--pica-client/dialogs/qrscandialog.h109
-rw-r--r--pica-client/dialogs/showpicaiddialog.cpp32
-rw-r--r--pica-client/dialogs/showpicaiddialog.h3
-rw-r--r--pica-client/mainwindow.cpp3
-rw-r--r--pica-client/qrcode.cpp148
-rw-r--r--pica-client/qrcode.h67
-rw-r--r--pica-client/videodevice.cpp258
-rw-r--r--pica-client/videodevice.h21
-rwxr-xr-xwindows/cross_build_mxe.sh35
-rw-r--r--windows/zxing-cpp-test.cpp49
-rw-r--r--windows/zxing-cpp.mk41
19 files changed, 1329 insertions, 38 deletions
diff --git a/Makefile.am b/Makefile.am
index e5bbe23..e869607 100644
--- a/Makefile.am
+++ b/Makefile.am
@@ -41,6 +41,8 @@ EXTRA_DIST = iniparser/LICENSE \
windows/installer32.nsi.in \
windows/installer64.nsi.in \
windows/mxe_ffmpeg_strip_excess_deps.patch \
+ windows/zxing-cpp.mk \
+ windows/zxing-cpp-test.cpp \
windows/mxe_qtbase_strip_excess_deps.patch \
windows/pica-client.exe.manifest.in \
windows/pica-client.nsi \
@@ -335,6 +337,22 @@ pica_client_pica_client_LDADD += $(VAAPI_X11_LIBS)
MOCFLAGS += -DHAVE_VAAPI_X11
endif
+# Pica Pica IDs as QR codes: drawn in the "Show My Pica Pica ID" dialog, read
+# from the camera by the "Scan QR Code" one. Both through ZXing-C++.
+if PICA_QRCODE
+pica_client_pica_client_SOURCES += \
+pica-client/qrcode.cpp \
+pica-client/qrcode.h \
+pica-client/dialogs/qrscandialog.cpp \
+pica-client/dialogs/qrscandialog.h
+
+nodist_pica_client_pica_client_SOURCES += moc_qrcode.cpp moc_qrscandialog.cpp
+
+pica_client_pica_client_CPPFLAGS += $(ZXING_CFLAGS)
+pica_client_pica_client_LDADD += $(ZXING_LIBS)
+MOCFLAGS += -DHAVE_QRCODE
+endif
+
pkgpicaclientdir = ${datarootdir}/pica-client
dist_pkgpicaclient_DATA = \
dhparam4096.pem \
diff --git a/configure.ac b/configure.ac
index b29feb9..61b5df0 100644
--- a/configure.ac
+++ b/configure.ac
@@ -136,6 +136,15 @@ AC_ARG_ENABLE([vaapi-x11],
AS_HELP_STRING([--disable-vaapi-x11],
[Disable vaPutSurface() rendering]))
+#checking if QR code support is wanted: showing one's own Pica Pica ID as a QR
+#code, and adding a contact by pointing the camera at theirs. Autodetected
+#like VAAPI; see the check further down.
+AC_ARG_ENABLE([qrcode],
+ AS_HELP_STRING([--enable-qrcode],
+ [Enable showing and scanning Pica Pica IDs as QR codes, using ZXing-C++ (default: autodetect)])
+ AS_HELP_STRING([--disable-qrcode],
+ [Disable QR code support]))
+
#at least one program must be enabled
AS_IF([test "x$PICA_NODE_ENABLED" != "xyes" && test "x$PICA_CLIENT_ENABLED" != "xyes" ],
AC_MSG_ERROR(["Either pica-node or pica-client must be enabled"])
@@ -390,11 +399,110 @@ AS_IF([test "x$TARGET_OS" = "xwindows" && test "x$enable_d3d12va" != "xno"], [
AS_IF([test "x$TARGET_OS" != "xwindows" && test "x$enable_d3d12va" = "xyes"],
[AC_MSG_ERROR(["Direct3D 12 acceleration was requested but it only exists on Windows"])])
+
+#check for ZXing-C++, which both draws the QR code the "Show My Pica Pica ID"
+#dialog shows and reads the one the camera sees in the "Scan QR Code" dialog.
+#
+#2.2 is the floor because that is where ReaderOptions, which the scanner is
+#written against, first appeared - and what Ubuntu 24.04 ships. Distributions
+#with anything older cannot build pica-client anyway, for want of
+#webrtc-audio-processing 1.x.
+#
+#The version alone does not say how a code is drawn, though. ZXing-C++ has two
+#writer APIs, and which of them a given libZXing carries is a build option of
+#its own: 2.x builds the old MultiFormatWriter by default, 3.x the new
+#CreateBarcodeFromText() instead, and either can be built with both or with
+#no writer at all. So the two are tried by linking against them, the new one
+#first, and a ZXing with neither counts as not found - scanning alone would
+#leave nothing to scan from.
+AS_IF([test "x$enable_qrcode" != "xno"], [
+ PKG_CHECK_MODULES([ZXING], [zxing >= 2.2],
+ [pica_zxing_found=yes],
+ [pica_zxing_found=no])
+
+ PICA_ZXING_WRITER=
+ AS_IF([test "x$pica_zxing_found" = "xyes"], [
+ AC_LANG_PUSH([C++])
+ pica_save_CPPFLAGS="$CPPFLAGS"
+ pica_save_LIBS="$LIBS"
+ CPPFLAGS="$CPPFLAGS $ZXING_CFLAGS"
+ LIBS="$ZXING_LIBS $LIBS"
+
+ AC_MSG_CHECKING([whether ZXing-C++ can read QR codes])
+ AC_LINK_IFELSE(
+ [AC_LANG_PROGRAM(
+ [[#include <ZXing/ReadBarcode.h>]],
+ [[unsigned char pixel = 0;
+ ZXing::ImageView image(&pixel, 1, 1, ZXing::ImageFormat::Lum);
+ ZXing::ReaderOptions options;
+ options.setFormats(ZXing::BarcodeFormat::QRCode);
+ return ZXing::ReadBarcode(image, options).text().size() > 0;]])],
+ [AC_MSG_RESULT([yes])],
+ [
+ AC_MSG_RESULT([no])
+ pica_zxing_found=no
+ ])
+
+ AS_IF([test "x$pica_zxing_found" = "xyes"], [
+ AC_MSG_CHECKING([for the ZXing-C++ CreateBarcodeFromText() writer])
+ AC_LINK_IFELSE(
+ [AC_LANG_PROGRAM(
+ [[#include <ZXing/CreateBarcode.h>]],
+ [[ZXing::Barcode barcode = ZXing::CreateBarcodeFromText("pica",
+ ZXing::CreatorOptions(ZXing::BarcodeFormat::QRCode));
+ return barcode.symbol().width();]])],
+ [
+ AC_MSG_RESULT([yes])
+ PICA_ZXING_WRITER=create_barcode
+ ],
+ [AC_MSG_RESULT([no])])
+ ])
+
+ AS_IF([test "x$pica_zxing_found" = "xyes" && test "x$PICA_ZXING_WRITER" = "x"], [
+ AC_MSG_CHECKING([for the ZXing-C++ MultiFormatWriter writer])
+ AC_LINK_IFELSE(
+ [AC_LANG_PROGRAM(
+ [[#include <ZXing/MultiFormatWriter.h>
+ #include <ZXing/BitMatrix.h>]],
+ [[ZXing::BitMatrix matrix =
+ ZXing::MultiFormatWriter(ZXing::BarcodeFormat::QRCode).encode(std::string("pica"), 0, 0);
+ return matrix.width();]])],
+ [
+ AC_MSG_RESULT([yes])
+ PICA_ZXING_WRITER=multi_format_writer
+ ],
+ [AC_MSG_RESULT([no])])
+ ])
+
+ AS_IF([test "x$pica_zxing_found" = "xyes" && test "x$PICA_ZXING_WRITER" = "x"],
+ [pica_zxing_found=no])
+
+ CPPFLAGS="$pica_save_CPPFLAGS"
+ LIBS="$pica_save_LIBS"
+ AC_LANG_POP([C++])
+ ])
+
+ AS_IF([test "x$pica_zxing_found" = "xyes"],
+ [
+ PICA_QRCODE_ENABLED=yes
+ AC_DEFINE([HAVE_QRCODE], [1], [Define to 1 if Pica Pica IDs can be shown and scanned as QR codes])
+ AS_IF([test "x$PICA_ZXING_WRITER" = "xcreate_barcode"],
+ [AC_DEFINE([HAVE_ZXING_CREATE_BARCODE], [1], [Define to 1 if ZXing-C++ draws barcodes with CreateBarcodeFromText()])])
+ AC_SUBST([ZXING_CFLAGS])
+ AC_SUBST([ZXING_LIBS])
+ ],
+ [
+ AS_IF([test "x$enable_qrcode" = "xyes"],
+ [AC_MSG_ERROR(["QR code support was requested but ZXing-C++ 2.2 or newer, built with both a reader and a writer, was not found"])],
+ [AC_MSG_WARN(["ZXing-C++ 2.2 or newer, built with both a reader and a writer, not found - building without QR code support"])])
+ ])
+])
])
AM_CONDITIONAL([PICA_PULSE], [test "x$PICA_PULSE_ENABLED" = "xyes"])
AM_CONDITIONAL([PICA_VAAPI], [test "x$PICA_VAAPI_ENABLED" = "xyes"])
AM_CONDITIONAL([PICA_VAAPI_X11], [test "x$PICA_VAAPI_X11_ENABLED" = "xyes"])
+AM_CONDITIONAL([PICA_QRCODE], [test "x$PICA_QRCODE_ENABLED" = "xyes"])
AC_SUBST([PLATFORM_DEPS_CFLAGS])
AC_SUBST([PLATFORM_DEPS_LIBS])
diff --git a/debian/control b/debian/control
index 4ebf0cc..dab09e4 100644
--- a/debian/control
+++ b/debian/control
@@ -20,6 +20,7 @@ Build-Depends: debhelper-compat (= 13),
libswscale-dev,
libwebrtc-audio-processing-dev (>= 1.3) | libwebrtc-audio-processing-1-dev,
libpulse-dev,
+ libzxing-dev (>= 2.2),
libva-dev,
libegl-dev,
libgl-dev,
diff --git a/debian/rules b/debian/rules
index c3ba0ba..752f745 100755
--- a/debian/rules
+++ b/debian/rules
@@ -24,7 +24,7 @@ export DH_OPTIONS=-v
# which is what Build-Depends and Depends name.
override_dh_auto_configure:
dh_auto_configure -- --localstatedir=/var/lib --with-qt=qt5 \
- --enable-vaapi --enable-vaapi-x11 --enable-pulse
+ --enable-vaapi --enable-vaapi-x11 --enable-pulse --enable-qrcode
%:
dh $@
diff --git a/gentoo/pica-pica-9999.ebuild b/gentoo/pica-pica-9999.ebuild
index 02ab610..187f74a 100755
--- a/gentoo/pica-pica-9999.ebuild
+++ b/gentoo/pica-pica-9999.ebuild
@@ -20,7 +20,7 @@ HOMEPAGE="http://picapica.im/"
LICENSE="GPL-3"
SLOT="0"
-IUSE="+client node upnp +vaapi pulseaudio X"
+IUSE="+client node upnp +vaapi pulseaudio +qrcode X"
DEPEND=">=dev-libs/openssl-1.0.2r
upnp? ( >=net-libs/miniupnpc-2.0 )
@@ -48,6 +48,8 @@ DEPEND=">=dev-libs/openssl-1.0.2r
pulseaudio? ( media-libs/libpulse )
+ qrcode? ( >=media-libs/zxing-cpp-2.3.0-r1:= )
+
vaapi? (
dev-qt/qtbase:6[opengl]
media-libs/libva:=[drm(+),X?]
@@ -82,7 +84,7 @@ src_configure() {
fi
econf $(use_with upnp miniupnpc) $(use_enable client) $(use_enable node) --with-qt=qt6 \
- ${vaapiflags} $(use_enable pulseaudio pulse)
+ ${vaapiflags} $(use_enable pulseaudio pulse) $(use_enable qrcode)
}
src_install() {
diff --git a/pica-client/contactlistwidget.cpp b/pica-client/contactlistwidget.cpp
index eed4abf..078f7db 100644
--- a/pica-client/contactlistwidget.cpp
+++ b/pica-client/contactlistwidget.cpp
@@ -22,6 +22,9 @@
#include "msguirouter.h"
#include "filetransfercontroller.h"
#include "audiovideocallcontroller.h"
+#ifdef HAVE_QRCODE
+#include "dialogs/qrscandialog.h"
+#endif
#include <QMenu>
#include <QMessageBox>
#include <QContextMenuEvent>
@@ -36,6 +39,12 @@ ContactListWidget::ContactListWidget(QWidget *parent) :
addcontactAct->setStatusTip(tr("add new contact"));
connect(addcontactAct, SIGNAL(triggered()), this, SLOT(add_contact()));
+#ifdef HAVE_QRCODE
+ scanqrAct = new QAction(tr("Scan the &QR Code..."), this);
+ scanqrAct->setStatusTip(tr("add new contact by scanning their Pica Pica ID with the camera"));
+ connect(scanqrAct, SIGNAL(triggered()), this, SLOT(scan_qr_code()));
+#endif
+
delcontactAct = new QAction(tr("&Delete Contact"), this);
connect(delcontactAct, SIGNAL(triggered()), this, SLOT(del_contact()));
@@ -84,6 +93,9 @@ void ContactListWidget::contextMenuEvent(QContextMenuEvent *event)
menu.addAction(delcontactAct);
menu.addAction(addcontactAct);
+#ifdef HAVE_QRCODE
+ menu.addAction(scanqrAct);
+#endif
if (this->itemAt(event->pos()) && wgitem_to_recs.contains(this->itemAt(event->pos())))
{
@@ -93,7 +105,7 @@ void ContactListWidget::contextMenuEvent(QContextMenuEvent *event)
menu.addAction(showidAct);
menu.addAction(sendfileAct);
- if (wgitem_to_recs[this->itemAt(event->pos())]->type == Contacts::blacklisted)
+ if (wgitem_to_recs.value(this->itemAt(event->pos())).type == Contacts::blacklisted)
{
menu.addAction(removefromblacklistAct);
}
@@ -116,7 +128,7 @@ void ContactListWidget::setContactsStorage(Contacts *ct, bool show_blacklisted)
for (int i = 0; i < contact_records.size(); i++)
{
addItem(QString("(%1...) %2").arg(contact_records[i].id.toBase64().left(8).constData()).arg(contact_records[i].name));
- wgitem_to_recs[this->item(i)] = &contact_records[i];
+ wgitem_to_recs[this->item(i)] = contact_records[i];
this->item(i)->setStatusTip(contact_records[i].id.toBase64());
this->item(i)->setToolTip(contact_records[i].id.toBase64().constData());
}
@@ -136,7 +148,7 @@ void ContactListWidget::setContactsStorage(Contacts *ct, bool show_blacklisted)
for (int i = 0; i < bl.size(); i++)
{
addItem(QString("(%1...) %2").arg(bl[i].id.toBase64().left(8).constData()).arg(bl[i].name));
- wgitem_to_recs[this->item(i + offset)] = &contact_records[i + offset - 1];
+ wgitem_to_recs[this->item(i + offset)] = contact_records[i + offset - 1];
this->item(i + offset)->setStatusTip(bl[i].id.toBase64());
this->item(i + offset)->setToolTip(bl[i].id.toBase64().constData());
}
@@ -162,42 +174,80 @@ void ContactListWidget::add_contact()
return;
}
- for(int i = 0; i < contact_records.size(); i++)
- if (contact_records[i].id == user_id)
- {
- QMessageBox mbx;
- mbx.setIcon(QMessageBox::Warning);
- mbx.setText(tr("User \"(%1) %2\" already exists").arg(user_id.toBase64().constData()).arg(contact_records[i].name));
- mbx.exec();
- return;
- }
+ add_contact_id(user_id);
+ }
+}
- Contacts::ContactRecord r;
+#ifdef HAVE_QRCODE
+void ContactListWidget::scan_qr_code()
+{
+ QrScanDialog d(this);
- r.id = user_id;
- r.name = "";
+ if (d.exec() != QDialog::Accepted || d.scannedId().isEmpty())
+ return;
- storage->Add(user_id);
+ // The same warning "Add Contact..." gives, and for the same reason: a code
+ // can be shown by anyone, so it is worth a look at who is holding it.
+ QMessageBox mbx;
+ mbx.setIcon(QMessageBox::Question);
+ mbx.setTextFormat(Qt::RichText);
+ mbx.setText(tr("<b>It is very important to make sure this ID actually belongs to the person you want to talk to.</b>"
+ "<br><br>Add contact with Pica Pica ID<br><tt>%1</tt>?")
+ .arg(QString::fromLatin1(d.scannedId().toBase64())));
+ mbx.addButton(QMessageBox::Yes);
+ mbx.addButton(QMessageBox::No);
+ mbx.setDefaultButton(QMessageBox::Yes);
+
+ if (mbx.exec() == QMessageBox::Yes)
+ add_contact_id(d.scannedId());
+}
+#endif
- if (!storage->isOK())
+void ContactListWidget::add_contact_id(const QByteArray &user_id)
+{
+ for(int i = 0; i < contact_records.size(); i++)
+ if (contact_records[i].id == user_id)
{
QMessageBox mbx;
mbx.setIcon(QMessageBox::Warning);
- mbx.setText(storage->GetLastError());
+ mbx.setText(tr("User \"(%1) %2\" already exists").arg(user_id.toBase64().constData()).arg(contact_records[i].name));
mbx.exec();
return;
}
- addItem(QString("(%1) ").arg(user_id.toBase64().constData()));
- contact_records.append(r);
- wgitem_to_recs[this->item(this->count() - 1)] = &contact_records.last();
+ Contacts::ContactRecord r;
+
+ r.id = user_id;
+ r.name = "";
+ storage->Add(user_id);
+
+ if (!storage->isOK())
+ {
+ QMessageBox mbx;
+ mbx.setIcon(QMessageBox::Warning);
+ mbx.setText(storage->GetLastError());
+ mbx.exec();
+ return;
}
+ addItem(QString("(%1) ").arg(user_id.toBase64().constData()));
+ contact_records.append(r);
+ wgitem_to_recs[this->item(this->count() - 1)] = r;
+}
+
+Contacts::ContactRecord ContactListWidget::currentRecord() const
+{
+ return wgitem_to_recs.value(currentItem());
}
void ContactListWidget::del_contact()
{
+ const Contacts::ContactRecord rec = currentRecord();
+
+ if (rec.id.isEmpty())
+ return;
+
QMessageBox mbx;
mbx.setText(QString(tr("Are you sure you want to remove user \"%1\" from your contact list?")).arg(currentItem()->text()));
mbx.setIcon(QMessageBox::Question);
@@ -210,7 +260,7 @@ void ContactListWidget::del_contact()
QByteArray rm_id;
QListWidgetItem *rm_ptr;
- storage->Delete(rm_id = wgitem_to_recs[currentItem()]->id);
+ storage->Delete(rm_id = rec.id);
delete (rm_ptr = takeItem(currentRow()));
for(int i = 0; i < contact_records.size(); i++)
@@ -229,17 +279,28 @@ void ContactListWidget::del_contact()
void ContactListWidget::start_chat()
{
- msguirouter->start_chat(wgitem_to_recs[currentItem()]->id);
+ const Contacts::ContactRecord rec = currentRecord();
+
+ if (!rec.id.isEmpty())
+ msguirouter->start_chat(rec.id);
}
void ContactListWidget::start_call()
{
- avctrl->start_call(wgitem_to_recs[currentItem()]->id);
+ const Contacts::ContactRecord rec = currentRecord();
+
+ if (!rec.id.isEmpty())
+ avctrl->start_call(rec.id);
}
void ContactListWidget::view_cert()
{
- QString cert_pem = storage->GetContactCert(wgitem_to_recs[currentItem()]->id);
+ const Contacts::ContactRecord rec = currentRecord();
+
+ if (rec.id.isEmpty())
+ return;
+
+ QString cert_pem = storage->GetContactCert(rec.id);
if (!storage->isOK())
{
@@ -264,9 +325,12 @@ void ContactListWidget::view_cert()
void ContactListWidget::show_id()
{
- ShowPicaIdDialog d(wgitem_to_recs[currentItem()]->name,
- wgitem_to_recs[currentItem()]->id,
- tr("Contact's ID"));
+ const Contacts::ContactRecord rec = currentRecord();
+
+ if (rec.id.isEmpty())
+ return;
+
+ ShowPicaIdDialog d(rec.name, rec.id, tr("Contact's ID"));
d.exec();
}
@@ -282,17 +346,30 @@ void ContactListWidget::show_blacklist(bool checked)
void ContactListWidget::move_to_blacklist()
{
- storage->SetContactType(wgitem_to_recs[currentItem()]->id, Contacts::blacklisted);
+ const Contacts::ContactRecord rec = currentRecord();
+
+ if (rec.id.isEmpty())
+ return;
+
+ storage->SetContactType(rec.id, Contacts::blacklisted);
setContactsStorage(storage, showblacklistAct->isChecked());
}
void ContactListWidget::remove_from_blacklist()
{
- storage->SetContactType(wgitem_to_recs[currentItem()]->id, Contacts::regular);
+ const Contacts::ContactRecord rec = currentRecord();
+
+ if (rec.id.isEmpty())
+ return;
+
+ storage->SetContactType(rec.id, Contacts::regular);
setContactsStorage(storage, showblacklistAct->isChecked());
}
void ContactListWidget::send_file()
{
- ftctrl->send_file(wgitem_to_recs[currentItem()]->id);
+ const Contacts::ContactRecord rec = currentRecord();
+
+ if (!rec.id.isEmpty())
+ ftctrl->send_file(rec.id);
}
diff --git a/pica-client/contactlistwidget.h b/pica-client/contactlistwidget.h
index 4800b46..a33404e 100644
--- a/pica-client/contactlistwidget.h
+++ b/pica-client/contactlistwidget.h
@@ -31,6 +31,9 @@ public:
~ContactListWidget();
QAction *addcontactAct;
+#ifdef HAVE_QRCODE
+ QAction *scanqrAct;
+#endif
QAction *delcontactAct;
QAction *startchatAct;
QAction *startcallAct;
@@ -45,9 +48,18 @@ protected:
private:
void setContactsStorage(Contacts *ct, bool show_blacklisted = false);
+ // Adds the contact with this Pica Pica ID, telling the user why not if it
+ // cannot be done. What both "Add Contact..." and "Scan the QR Code" end in.
+ void add_contact_id(const QByteArray &user_id);
Contacts* storage;
QList<Contacts::ContactRecord> contact_records;
- QMap<QListWidgetItem*, Contacts::ContactRecord*> wgitem_to_recs;
+ // The record behind each list item, by value: pointing into contact_records
+ // instead would leave every entry dangling as soon as appending to the list
+ // made it reallocate, which a Qt 6 QList does like a vector.
+ QMap<QListWidgetItem*, Contacts::ContactRecord> wgitem_to_recs;
+ // The record behind the current item, or one with an empty id if there is
+ // none - no current item, or the "Blacklisted Contacts" separator.
+ Contacts::ContactRecord currentRecord() const;
//ChatWindow *cw_debug_remove;
@@ -58,6 +70,9 @@ public slots:
private slots:
void add_contact();
+#ifdef HAVE_QRCODE
+ void scan_qr_code();
+#endif
void del_contact();
void start_chat();
void start_call();
diff --git a/pica-client/dialogs/qrscandialog.cpp b/pica-client/dialogs/qrscandialog.cpp
new file mode 100644
index 0000000..db6dac4
--- /dev/null
+++ b/pica-client/dialogs/qrscandialog.cpp
@@ -0,0 +1,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();
+}
diff --git a/pica-client/dialogs/qrscandialog.h b/pica-client/dialogs/qrscandialog.h
new file mode 100644
index 0000000..4ee89e8
--- /dev/null
+++ b/pica-client/dialogs/qrscandialog.h
@@ -0,0 +1,109 @@
+/*
+ (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/>.
+*/
+#ifndef QRSCANDIALOG_H
+#define QRSCANDIALOG_H
+
+// "Scan the QR Code": adds a contact by pointing the camera at the QR code
+// another Pica Pica client shows in its "Show My Pica Pica ID" dialog - on a
+// monitor, or on a phone's screen. Only built with HAVE_QRCODE.
+
+#include <QDialog>
+#include <QWidget>
+#include <QImage>
+#include <QThread>
+#include <QByteArray>
+#include <QString>
+
+class QComboBox;
+class QLabel;
+class QPushButton;
+class VideoDevice;
+class QrCodeReader;
+
+// The camera picture with the guide drawn over it: the area outside a centred
+// square dimmed and the square's corners marked, for the user to bring the code
+// into. Only a guide - the whole picture is searched for a code, wherever in it
+// the code may be.
+//
+// The picture is shown mirrored, the way a camera facing the user is expected to
+// look: moving the code to the left moves it to the left on the screen too.
+class QrViewfinder : public QWidget
+{
+ Q_OBJECT
+public:
+ explicit QrViewfinder(QWidget *parent = nullptr);
+
+ // The newest camera frame; a null image goes back to showing message().
+ void setFrame(const QImage &frame);
+
+ // Shown while there is no picture: the camera starting, or why it did not.
+ void setMessage(const QString &message);
+
+protected:
+ void paintEvent(QPaintEvent *event) override;
+
+private:
+ QImage m_frame;
+ QString m_message;
+};
+
+class QrScanDialog : public QDialog
+{
+ Q_OBJECT
+public:
+ explicit QrScanDialog(QWidget *parent = nullptr);
+ ~QrScanDialog();
+
+ // The Pica Pica ID that was read, once the dialog has been accepted.
+ QByteArray scannedId() const { return m_scannedId; }
+
+private slots:
+ void cameraChanged(int index);
+ void cameraStarted(QString codec, int width, int height, double frameRate);
+ void cameraFrame(QImage frame);
+ void cameraError(QString message);
+ void cameraBusy();
+ void frameRead(QString text);
+
+private:
+ void startCamera();
+ void stopCamera();
+
+ QComboBox *m_cameras;
+ QrViewfinder *m_viewfinder;
+ QLabel *m_status;
+ QPushButton *m_cancel;
+
+ VideoDevice *m_camera;
+ QThread m_cameraThread;
+ QrCodeReader *m_reader;
+ QThread m_readerThread;
+
+ // Each start of the camera is a session of its own - see MediaCallSession.
+ // Reusing one would let a preview that is still on its way out after
+ // Close() carry on as soon as the next start reopened the same session.
+ int m_sessionNumber;
+ QByteArray m_sessionId;
+ bool m_cameraRunning;
+
+ // A frame is with m_reader; the ones arriving meanwhile are only shown.
+ bool m_readerBusy;
+
+ QByteArray m_scannedId;
+};
+
+#endif // QRSCANDIALOG_H
diff --git a/pica-client/dialogs/showpicaiddialog.cpp b/pica-client/dialogs/showpicaiddialog.cpp
index cff91c0..e47e78a 100644
--- a/pica-client/dialogs/showpicaiddialog.cpp
+++ b/pica-client/dialogs/showpicaiddialog.cpp
@@ -18,6 +18,17 @@
#include <QVBoxLayout>
#include <QFontMetrics>
#include <QStyle>
+#include <QPixmap>
+
+#ifdef HAVE_QRCODE
+#include "../qrcode.h"
+
+// The QR code's side, in device independent pixels: large enough for a camera
+// across a desk to resolve its modules, small enough for the dialog to stay a
+// dialog. Rounded to a whole number of physical pixels per module, so that no
+// module comes out a pixel narrower than its neighbour.
+static const int kQrCodeSide = 300;
+#endif
ShowPicaIdDialog::ShowPicaIdDialog(QString name, QByteArray id, QString caption, QWidget *parent) :
QDialog(parent)
@@ -41,6 +52,27 @@ ShowPicaIdDialog::ShowPicaIdDialog(QString name, QByteArray id, QString caption,
layout->addWidget(lbname_);
layout->addWidget(picaid_);
+
+#ifdef HAVE_QRCODE
+ // The same text the line above shows, for another Pica Pica to read with
+ // "Contacts -> Scan the QR Code" - or any phone's scanner app.
+ const QImage code = picaQrCodeImage(picaid_->text());
+
+ if (!code.isNull())
+ {
+ const qreal dpr = devicePixelRatioF();
+ const int modulePixels = qMax(1, qRound(kQrCodeSide * dpr / code.width()));
+ QPixmap pixmap = QPixmap::fromImage(code.scaled(code.size() * modulePixels,
+ Qt::IgnoreAspectRatio,
+ Qt::FastTransformation));
+ pixmap.setDevicePixelRatio(dpr);
+
+ qrcode_ = new QLabel();
+ qrcode_->setPixmap(pixmap);
+ qrcode_->setAlignment(Qt::AlignCenter);
+ layout->addWidget(qrcode_, 0, Qt::AlignHCenter);
+ }
+#endif
layout->addWidget(btok_, 0, Qt::AlignHCenter);
connect(btok_, SIGNAL(clicked()), this, SLOT(Ok()));
diff --git a/pica-client/dialogs/showpicaiddialog.h b/pica-client/dialogs/showpicaiddialog.h
index c8ffd78..82539df 100644
--- a/pica-client/dialogs/showpicaiddialog.h
+++ b/pica-client/dialogs/showpicaiddialog.h
@@ -36,6 +36,9 @@ private slots:
private:
QLabel *lbname_;
QLineEdit *picaid_;
+#ifdef HAVE_QRCODE
+ QLabel *qrcode_ = nullptr;
+#endif
QPushButton *btok_;
};
diff --git a/pica-client/mainwindow.cpp b/pica-client/mainwindow.cpp
index 2e7fed6..807032d 100644
--- a/pica-client/mainwindow.cpp
+++ b/pica-client/mainwindow.cpp
@@ -121,6 +121,9 @@ void MainWindow::createMenus()
{
contactsMenu = menuBar()->addMenu(tr("&Contacts"));
contactsMenu->addAction(contact_list->addcontactAct);
+#ifdef HAVE_QRCODE
+ contactsMenu->addAction(contact_list->scanqrAct);
+#endif
contactsMenu->addAction(contact_list->showblacklistAct);
contactsMenu->addSeparator();
contactsMenu->addAction(action_center->ExitAct());
diff --git a/pica-client/qrcode.cpp b/pica-client/qrcode.cpp
new file mode 100644
index 0000000..0c8545e
--- /dev/null
+++ b/pica-client/qrcode.cpp
@@ -0,0 +1,148 @@
+/*
+ (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 "qrcode.h"
+#include "../PICA_id.h"
+
+#include <QDebug>
+#include <QtEndian>
+
+#include <ZXing/ReadBarcode.h>
+
+// Which of ZXing-C++'s two writer APIs this libZXing has is found out by
+// configure, see the comments there. 3.x builds the new one by default, 2.x
+// the old.
+#ifdef HAVE_ZXING_CREATE_BARCODE
+#include <ZXing/CreateBarcode.h>
+#else
+#include <ZXing/MultiFormatWriter.h>
+#include <ZXing/BitMatrix.h>
+#endif
+
+#include <exception>
+#include <string>
+
+QImage picaQrCodeImage(const QString &text, int quietZone)
+{
+ const std::string utf8 = text.toStdString();
+
+ if (quietZone < 0)
+ quietZone = 0;
+
+ // ZXing reports what it cannot encode by throwing, in both APIs - text too
+ // long for the largest QR code being the one way that could happen here.
+ try
+ {
+#ifdef HAVE_ZXING_CREATE_BARCODE
+ const ZXing::Barcode barcode =
+ ZXing::CreateBarcodeFromText(utf8, ZXing::CreatorOptions(ZXing::BarcodeFormat::QRCode));
+ // One byte per module, 0 for a dark one and 0xff for a light one.
+ const ZXing::ImageView symbol = barcode.symbol();
+ const int width = symbol.width();
+ const int height = symbol.height();
+ auto dark = [&symbol](int x, int y) { return *symbol.data(x, y) < 0x80; };
+#else
+ const ZXing::BitMatrix matrix =
+ ZXing::MultiFormatWriter(ZXing::BarcodeFormat::QRCode).setMargin(0).encode(utf8, 0, 0);
+ const int width = matrix.width();
+ const int height = matrix.height();
+ auto dark = [&matrix](int x, int y) { return matrix.get(x, y); };
+#endif
+
+ if (width <= 0 || height <= 0)
+ return QImage();
+
+ QImage image(width + 2 * quietZone, height + 2 * quietZone, QImage::Format_RGB32);
+
+ if (image.isNull())
+ return QImage();
+
+ image.fill(Qt::white);
+
+ for (int y = 0; y < height; y++)
+ for (int x = 0; x < width; x++)
+ if (dark(x, y))
+ image.setPixel(x + quietZone, y + quietZone, qRgb(0, 0, 0));
+
+ return image;
+ }
+ catch (const std::exception &e)
+ {
+ qWarning() << "Could not encode a QR code:" << e.what();
+ return QImage();
+ }
+}
+
+QByteArray picaIdFromQrText(const QString &text)
+{
+ const QByteArray id = QByteArray::fromBase64(text.trimmed().toLatin1()).left(PICA_ID_SIZE);
+
+ return id.size() == PICA_ID_SIZE ? id : QByteArray();
+}
+
+QrCodeReader::QrCodeReader(QObject *parent) :
+ QObject(parent)
+{
+}
+
+void QrCodeReader::read(QImage frame)
+{
+ if (frame.format() != QImage::Format_RGB32 && frame.format() != QImage::Format_ARGB32)
+ frame = frame.convertToFormat(QImage::Format_RGB32);
+
+ if (frame.isNull())
+ {
+ emit frameRead(QString());
+ return;
+ }
+
+ // Format_RGB32 is a 32 bit 0xffRRGGBB per pixel in the machine's own byte
+ // order, so what ZXing sees in memory depends on it.
+#if Q_BYTE_ORDER == Q_LITTLE_ENDIAN
+ const ZXing::ImageFormat format = ZXing::ImageFormat::BGRX;
+#else
+ const ZXing::ImageFormat format = ZXing::ImageFormat::XRGB;
+#endif
+
+ const ZXing::ImageView image(frame.constBits(), frame.width(), frame.height(), format,
+ (int)frame.bytesPerLine());
+
+ // QR codes only, which spares trying every other symbology on every frame.
+ // tryHarder and tryRotate are what make a code held at an angle in front of
+ // the camera, or a little out of focus, readable at all; tryInvert also
+ // takes light-on-dark codes, as a phone in dark mode may draw them.
+ ZXing::ReaderOptions options;
+ options.setFormats(ZXing::BarcodeFormat::QRCode);
+ options.setTryHarder(true);
+ options.setTryRotate(true);
+ options.setTryInvert(true);
+
+ QString text;
+
+ try
+ {
+ const auto result = ZXing::ReadBarcode(image, options);
+
+ if (result.isValid())
+ text = QString::fromStdString(result.text());
+ }
+ catch (const std::exception &e)
+ {
+ qWarning() << "Could not read a QR code:" << e.what();
+ }
+
+ emit frameRead(text);
+}
diff --git a/pica-client/qrcode.h b/pica-client/qrcode.h
new file mode 100644
index 0000000..30b9564
--- /dev/null
+++ b/pica-client/qrcode.h
@@ -0,0 +1,67 @@
+/*
+ (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/>.
+*/
+#ifndef QRCODE_H
+#define QRCODE_H
+
+// Pica Pica IDs as QR codes, through ZXing-C++. Only built with HAVE_QRCODE.
+//
+// What a code carries is the ID exactly as the "Show My Pica Pica ID" dialog
+// shows it and the "Add Contact" one takes it - its base64 text - so a code can
+// equally be read by any phone's scanner app and pasted by hand.
+
+#include <QObject>
+#include <QImage>
+#include <QString>
+#include <QByteArray>
+
+// The QR code for text: one pixel per module, dark modules black and light
+// ones white, with quietZone light modules all round - the QR specification
+// asks for 4, without which a scanner may not find where the code begins.
+// Meant to be scaled up by a whole factor with Qt::FastTransformation, which
+// keeps the modules sharp. A null image if the text could not be encoded.
+QImage picaQrCodeImage(const QString &text, int quietZone = 4);
+
+// The Pica Pica ID a scanned code's text is the base64 form of, or an empty
+// QByteArray if it is not one - the same rule the "Add Contact" dialog applies
+// to what is typed into it.
+QByteArray picaIdFromQrText(const QString &text);
+
+// Looks for a QR code in camera frames. Lives on a thread of its own: reading a
+// 720p frame takes a few tens of milliseconds, too long for the GUI thread at
+// the rate a camera delivers frames.
+//
+// The caller is meant to hand it a frame only when it has answered the previous
+// one, through frameRead(), and to drop the frames in between - a reader that
+// fell behind would only ever be looking at the past.
+class QrCodeReader : public QObject
+{
+ Q_OBJECT
+public:
+ explicit QrCodeReader(QObject *parent = nullptr);
+
+public slots:
+ // Reads one frame - any QImage format, Format_RGB32 being what the camera
+ // delivers and what is read without a conversion - and answers with
+ // frameRead().
+ void read(QImage frame);
+
+signals:
+ // The text of the QR code found in the frame, empty if none was found.
+ void frameRead(QString text);
+};
+
+#endif // QRCODE_H
diff --git a/pica-client/videodevice.cpp b/pica-client/videodevice.cpp
index ab6f08e..2d15d45 100644
--- a/pica-client/videodevice.cpp
+++ b/pica-client/videodevice.cpp
@@ -2224,6 +2224,264 @@ QList<CallCameraSize> VideoDevice::CallCameraSizes(const QList<VideoCaptureForma
// encoder that cannot take one while running is reopened for it - each reopen
// starts with a keyframe - and how far apart reopens for increases are kept.
// Decreases are not held back: they are what stops the loss.
+// The size Preview() asks the camera for: the wanted one if the camera lists
+// it, otherwise the largest it lists that is no bigger, or failing that the
+// smallest it has. A camera that could not be enumerated is asked for the
+// wanted size and left to adjust, as buildCaptureAttempts() does too.
+static QSize previewSize(const QList<VideoCaptureFormat> &formats, const QSize &wanted)
+{
+ const qint64 wantedArea = (qint64)wanted.width() * wanted.height();
+ QSize best;
+ QSize smallest;
+
+ for (int i = 0; i < formats.size(); i++)
+ {
+ const QSize size(formats.at(i).width, formats.at(i).height);
+ const qint64 area = (qint64)size.width() * size.height();
+
+ if (size == wanted)
+ return size;
+
+ if (!smallest.isValid() || area < (qint64)smallest.width() * smallest.height())
+ smallest = size;
+
+ if (area <= wantedArea &&
+ (!best.isValid() || area > (qint64)best.width() * best.height()))
+ best = size;
+ }
+
+ if (best.isValid())
+ return best;
+
+ return smallest.isValid() ? smallest : wanted;
+}
+
+void VideoDevice::Preview()
+{
+ /* closed before it got to start */
+ if (sessionClosed())
+ return;
+
+ avdevice_register_all();
+#if LIBAVFORMAT_VERSION_MAJOR < 58
+ av_register_all();
+ avcodec_register_all();
+#endif
+
+ const QByteArray deviceUtf8 = cameraOpenUrl(m_deviceName);
+ const QByteArray driverUtf8 = VideoDevice::PlatformDriverName().toUtf8();
+ const AVInputFormat *ifmt = av_find_input_format(driverUtf8.constData());
+
+ if (!ifmt)
+ {
+ QString msg = QString("Could not find '%1' video input driver").arg(VideoDevice::PlatformDriverName());
+ qWarning() << msg;
+ emit errorOccurred(msg);
+ return;
+ }
+
+ const QList<VideoCaptureFormat> formats = VideoDevice::CaptureFormats(m_deviceName);
+ const QSize size = previewSize(formats, QSize(m_width, m_height));
+
+ // The same order of attempts a call's capture goes through, minus
+ // forwarding a compressed stream, which has no meaning here: every frame is
+ // decoded either way, and MJPEG is still preferred over uncompressed where
+ // only it can carry the rate.
+ const QList<CaptureAttempt> attempts =
+ buildCaptureAttempts(m_deviceName, formats, size.width(), size.height(), m_frameRate,
+ false, QString());
+
+ AVFormatContext *ifmt_ctx = nullptr;
+ int ret = AVERROR(EINVAL);
+
+ for (int a = 0; a < attempts.size() && !sessionClosed(); a++)
+ {
+ const CaptureAttempt &attempt = attempts.at(a);
+
+ ret = openCamera(ifmt, deviceUtf8,
+ attempt.constrainSize ? size.width() : 0,
+ attempt.constrainSize ? size.height() : 0,
+ attempt.constrainRate ? m_frameRate : 0,
+ attempt.inputFormat, &ifmt_ctx);
+
+ if (ret >= 0)
+ break;
+
+ // Another handle is streaming from the camera. No other format or size
+ // will change that, so the remaining attempts would only fail the same
+ // way, one log line each.
+ if (ret == AVERROR(EBUSY))
+ {
+ qWarning() << QString("Camera '%1' preview: the camera is busy - %2")
+ .arg(m_deviceName, ff_errstr(ret));
+
+ if (!sessionClosed())
+ emit cameraBusy();
+ return;
+ }
+
+ qWarning() << QString("Camera '%1' preview: no %2 at %3x%4 - %5 (%6)")
+ .arg(m_deviceName,
+ attempt.inputFormat.isEmpty() ? QStringLiteral("stream") : attempt.inputFormat)
+ .arg(size.width()).arg(size.height())
+ .arg(attempt.reason, ff_errstr(ret));
+ }
+
+ if (ret < 0 || !ifmt_ctx)
+ {
+ if (sessionClosed())
+ return;
+
+ QString msg = QString("Could not open camera '%1': %2").arg(m_deviceName, ff_errstr(ret));
+
+#ifdef Q_OS_WIN
+ // See Capture().
+ msg += tr(" - check that \"Let desktop apps access your camera\" is enabled in the "
+ "Windows camera privacy settings, and that no other application is using it");
+#endif
+
+ qWarning() << msg;
+ emit errorOccurred(msg);
+ return;
+ }
+
+ if ((ret = avformat_find_stream_info(ifmt_ctx, nullptr)) < 0 || ifmt_ctx->nb_streams < 1)
+ {
+ QString msg = QString("Could not determine camera stream parameters: %1").arg(ff_errstr(ret));
+ qWarning() << msg;
+ emit errorOccurred(msg);
+ avformat_close_input(&ifmt_ctx);
+ return;
+ }
+
+ AVStream *in_st = ifmt_ctx->streams[0];
+ const AVCodec *cam_dec = avcodec_find_decoder(in_st->codecpar->codec_id);
+ AVCodecContext *dec_ctx = cam_dec ? avcodec_alloc_context3(cam_dec) : nullptr;
+
+ if (!cam_dec || !dec_ctx ||
+ avcodec_parameters_to_context(dec_ctx, in_st->codecpar) < 0 ||
+ avcodec_open2(dec_ctx, cam_dec, nullptr) < 0)
+ {
+ QString msg = "Could not open camera format decoder";
+ qWarning() << msg;
+ emit errorOccurred(msg);
+ if (dec_ctx) avcodec_free_context(&dec_ctx);
+ avformat_close_input(&ifmt_ctx);
+ return;
+ }
+
+ emit captureStarted(in_st->codecpar->codec_id == AV_CODEC_ID_RAWVIDEO
+ ? QString()
+ : QString::fromLatin1(avcodec_get_name(in_st->codecpar->codec_id)),
+ in_st->codecpar->width, in_st->codecpar->height,
+ av_q2d(cameraFrameRate(in_st, m_frameRate)));
+
+ AVPacket *in_pkt = av_packet_alloc();
+ AVFrame *cam_frame = av_frame_alloc();
+ SwsContext *sws = nullptr;
+ // What sws was set up for; rebuilt should the camera's frames change.
+ int sws_width = 0;
+ int sws_height = 0;
+ int sws_format = AV_PIX_FMT_NONE;
+ bool loggedReadError = false;
+
+ if (!in_pkt || !cam_frame)
+ {
+ QString msg = "Could not allocate camera preview buffers";
+ qWarning() << msg;
+ emit errorOccurred(msg);
+ }
+
+ while (in_pkt && cam_frame && !sessionClosed())
+ {
+ ret = av_read_frame(ifmt_ctx, in_pkt);
+ if (ret < 0)
+ {
+ if (ret == AVERROR(EAGAIN))
+ continue;
+ if (!loggedReadError)
+ {
+ qWarning() << QString("Camera read failed: %1").arg(ff_errstr(ret));
+ loggedReadError = true;
+ }
+ break;
+ }
+
+ ret = avcodec_send_packet(dec_ctx, in_pkt);
+ av_packet_unref(in_pkt);
+ if (ret < 0)
+ continue;
+
+ while (avcodec_receive_frame(dec_ctx, cam_frame) == 0)
+ {
+ if (!sws || cam_frame->width != sws_width || cam_frame->height != sws_height ||
+ cam_frame->format != sws_format)
+ {
+ if (sws)
+ sws_freeContext(sws);
+
+ bool srcFullRange = false;
+ const AVPixelFormat srcFormat =
+ swscaleSourceFormat((AVPixelFormat)cam_frame->format, &srcFullRange);
+
+ // AV_PIX_FMT_0RGB32 is laid out exactly as QImage::Format_RGB32,
+ // see decode().
+ sws = sws_getContext(cam_frame->width, cam_frame->height, srcFormat,
+ cam_frame->width, cam_frame->height, AV_PIX_FMT_0RGB32,
+ SWS_BILINEAR, nullptr, nullptr, nullptr);
+
+ if (!sws)
+ {
+ qWarning() << "Could not set up camera preview scaler";
+ av_frame_unref(cam_frame);
+ sws_width = sws_height = 0;
+ continue;
+ }
+
+ // A JPEG frame's full range, which the format name no longer
+ // says - see swscaleSourceFormat(). Without it the picture's
+ // blacks and whites would come out grey, costing a QR code
+ // reader contrast it can use.
+ if (srcFullRange)
+ {
+ const int *coefs = sws_getCoefficients(SWS_CS_DEFAULT);
+
+ sws_setColorspaceDetails(sws, coefs, 1, coefs, 1,
+ 0, 1 << 16, 1 << 16);
+ }
+
+ sws_width = cam_frame->width;
+ sws_height = cam_frame->height;
+ sws_format = cam_frame->format;
+ }
+
+ // A new image per frame, for the same reason decode() makes one:
+ // it goes to another thread without being copied.
+ QImage img(cam_frame->width, cam_frame->height, QImage::Format_RGB32);
+
+ if (!img.isNull())
+ {
+ uint8_t *dst_data[4] = { img.bits(), nullptr, nullptr, nullptr };
+ int dst_linesize[4] = { (int)img.bytesPerLine(), 0, 0, 0 };
+
+ sws_scale(sws, cam_frame->data, cam_frame->linesize, 0, cam_frame->height,
+ dst_data, dst_linesize);
+
+ emit frameReady(img);
+ }
+
+ av_frame_unref(cam_frame);
+ }
+ }
+
+ if (sws)
+ sws_freeContext(sws);
+ av_frame_free(&cam_frame);
+ av_packet_free(&in_pkt);
+ avcodec_free_context(&dec_ctx);
+ avformat_close_input(&ifmt_ctx);
+}
+
static const double kReopenBitrateStep = 0.15;
static const int kReopenIntervalMs = 5000;
diff --git a/pica-client/videodevice.h b/pica-client/videodevice.h
index 2724d63..50f8684 100644
--- a/pica-client/videodevice.h
+++ b/pica-client/videodevice.h
@@ -294,6 +294,16 @@ public slots:
// Close() is called.
virtual void Capture() override;
+ // Blocking camera preview loop, for looking at what the camera sees rather
+ // than sending it anywhere - the QR code scanner. Opens the camera
+ // configureCapture() named, at the size and frame rate given there or the
+ // nearest the camera offers, and emits frameReady() for every frame at the
+ // camera's own resolution, with nothing encoded. Of configureCapture()'s
+ // other parameters only the session ids apply. Emits captureStarted() once
+ // the camera is open, with the codec the camera itself delivers in - empty
+ // for uncompressed. Returns once Close() is called.
+ void Preview();
+
// Blocking decode loop: decodes frames pulled from the internal queue
// (see enqueueFrame()) and emits frameReady() for each decoded picture.
// Returns once Close() is called.
@@ -325,7 +335,8 @@ signals:
// One decoded picture from the remote side, ready to be displayed, as a
// Format_RGB32 image - the format a widget draws without converting it
- // first.
+ // first. Preview() emits its camera frames through here as well, at the
+ // camera's resolution, which the rest of this description is not about.
//
// Already scaled to fit the area last given to setDisplaySize(), keeping
// its aspect ratio, so the receiver can draw it as it stands. At the
@@ -344,6 +355,14 @@ signals:
void errorOccurred(QString message);
+ // Emitted by Preview() instead of errorOccurred() when the camera could not
+ // be opened because something else is capturing from it - a call, or
+ // another application - so that the caller can say so in plain words
+ // rather than pass on an error code. Only where the platform tells this
+ // apart from other failures: v4l2 reports EBUSY, DirectShow reports an
+ // I/O error like any other and ends up in errorOccurred().
+ void cameraBusy();
+
// Says in plain words which path capture or playback actually settled on,
// for the settings dialog to show. A request for GPU work can silently
// come back as software, and forwarding a compressed camera stream skips
diff --git a/windows/cross_build_mxe.sh b/windows/cross_build_mxe.sh
index 4862d32..827ea94 100755
--- a/windows/cross_build_mxe.sh
+++ b/windows/cross_build_mxe.sh
@@ -26,8 +26,12 @@ set -o pipefail
MXE_REPO_URL='https://github.com/mxe/mxe.git'
MXE_COMMIT=${MXE_COMMIT:-a9135e50775889ef9448cf12b72da0ea25aa04c1}
MXE_TARGETS='i686-w64-mingw32.shared x86_64-w64-mingw32.shared'
-MXE_PACKAGES='cc qtbase ffmpeg openssl miniupnpc libevent sqlite webrtc-audio-processing nsis'
+MXE_PACKAGES='cc qtbase ffmpeg openssl miniupnpc libevent sqlite webrtc-audio-processing zxing-cpp nsis'
MXE_PATCHES='mxe_qtbase_strip_excess_deps.patch mxe_ffmpeg_strip_excess_deps.patch'
+# Package recipes MXE does not have (yet), kept in this directory and copied
+# into the MXE tree's src/ - the recipe and, where there is one, the test
+# program it compiles.
+MXE_EXTRA_RECIPES='zxing-cpp.mk zxing-cpp-test.cpp'
windows_dir=$(cd "$(dirname "$0")" && pwd)
mxe_dir=$windows_dir/mxe
@@ -143,6 +147,32 @@ apply the patch again (the affected libraries will be rebuilt by MXE)."
done
}
+# step 3b: copy our own package recipes into the MXE tree. They are new files
+# there, untracked by MXE's git, so they neither count as local modifications
+# for checkout_mxe_commit nor get in the way of the patches above. Copied on
+# every run so that a recipe changed here reaches the tree; MXE does not rebuild
+# a package that is already built because its recipe changed, though - remove
+# usr/<target>/installed/<package> for that.
+function copy_mxe_recipes {
+ local recipe
+
+ for recipe in $MXE_EXTRA_RECIPES
+ do
+ test -f "$windows_dir/$recipe" || die "recipe $windows_dir/$recipe not found"
+
+ if cmp -s "$windows_dir/$recipe" "$mxe_dir/src/$recipe"
+ then
+ echo "*** $recipe is already in place, skipping"
+ continue
+ fi
+
+ test -e "$mxe_dir/src/$recipe" && echo "*** WARNING: replacing $mxe_dir/src/$recipe, which differs from $windows_dir/$recipe" >&2
+
+ echo "*** copying $recipe into $mxe_dir/src"
+ cp "$windows_dir/$recipe" "$mxe_dir/src/$recipe"
+ done
+}
+
# MXE packages from $MXE_PACKAGES that are not built yet, as 'package (target)'
function missing_mxe_packages {
local target package
@@ -228,7 +258,7 @@ rm -rf build_pica-pica
mkdir -p build_pica-pica
cd build_pica-pica
#MXE builds qtbase 5, while configure defaults to Qt 6
-../../../configure --host=$arch --prefix=$PREFIX --with-qt=qt5 --enable-d3d12va
+../../../configure --host=$arch --prefix=$PREFIX --with-qt=qt5 --enable-d3d12va --enable-qrcode
make -j$(nproc)
make install
make clean
@@ -300,6 +330,7 @@ cd ..
clone_mxe
checkout_mxe_commit
apply_mxe_patches
+copy_mxe_recipes
build_mxe_packages
cd "$mxe_dir"
diff --git a/windows/zxing-cpp-test.cpp b/windows/zxing-cpp-test.cpp
new file mode 100644
index 0000000..cf03c67
--- /dev/null
+++ b/windows/zxing-cpp-test.cpp
@@ -0,0 +1,49 @@
+/*
+ * This file is part of MXE. See LICENSE.md for licensing information.
+ */
+
+// Round trip: encode a QR code with the writer, render it to a grayscale
+// image and read it back with the reader.
+
+#include <ZXing/BitMatrix.h>
+#include <ZXing/MultiFormatWriter.h>
+#include <ZXing/ReadBarcode.h>
+
+#include <iostream>
+#include <string>
+#include <vector>
+
+int main()
+{
+ const std::string text = "MXE zxing-cpp test";
+ const int scale = 4;
+ const int quiet = 4;
+
+ ZXing::BitMatrix matrix =
+ ZXing::MultiFormatWriter(ZXing::BarcodeFormat::QRCode).setMargin(0).encode(text, 0, 0);
+
+ const int size = (matrix.width() + 2 * quiet) * scale;
+ std::vector<unsigned char> pixels(size * size, 0xff);
+
+ for (int y = 0; y < matrix.height(); y++)
+ for (int x = 0; x < matrix.width(); x++)
+ if (matrix.get(x, y))
+ for (int dy = 0; dy < scale; dy++)
+ for (int dx = 0; dx < scale; dx++)
+ pixels[((y + quiet) * scale + dy) * size + (x + quiet) * scale + dx] = 0;
+
+ ZXing::ImageView image(pixels.data(), size, size, ZXing::ImageFormat::Lum);
+ ZXing::ReaderOptions options;
+ options.setFormats(ZXing::BarcodeFormat::QRCode);
+
+ const ZXing::Result result = ZXing::ReadBarcode(image, options);
+
+ if (!result.isValid() || result.text() != text)
+ {
+ std::cerr << "decoded \"" << result.text() << "\" instead of \"" << text << "\"" << std::endl;
+ return 1;
+ }
+
+ std::cout << result.text() << std::endl;
+ return 0;
+}
diff --git a/windows/zxing-cpp.mk b/windows/zxing-cpp.mk
new file mode 100644
index 0000000..9c52db6
--- /dev/null
+++ b/windows/zxing-cpp.mk
@@ -0,0 +1,41 @@
+# This file is part of MXE. See LICENSE.md for licensing information.
+
+PKG := zxing-cpp
+$(PKG)_WEBSITE := https://github.com/zxing-cpp/zxing-cpp
+$(PKG)_DESCR := ZXing-C++, a barcode and QR code reading and writing library
+$(PKG)_IGNORE :=
+$(PKG)_VERSION := 2.3.0
+$(PKG)_CHECKSUM := 64e4139103fdbc57752698ee15b5f0b0f7af9a0331ecbdc492047e0772c417ba
+$(PKG)_GH_CONF := zxing-cpp/zxing-cpp/tags,v
+$(PKG)_DEPS := cc
+
+# ZXING_WRITERS=OLD builds the MultiFormatWriter encoder, which needs nothing
+# else. The new CreateBarcodeFromText() one would pull in libzint, either the
+# copy bundled with the sources or one fetched from GitHub at build time.
+#
+# The examples are off because they fetch stb from GitHub at build time, and the
+# tests, the C API and the Python module because nothing here uses them.
+#
+# 2.3 prefers C++20 but builds as C++17 too; asking for 17 keeps MXE's
+# compiler from having to handle C++20 library features it may only partly
+# support.
+define $(PKG)_BUILD
+ cd '$(BUILD_DIR)' && $(TARGET)-cmake '$(SOURCE_DIR)' \
+ -DCMAKE_CXX_STANDARD=17 \
+ -DZXING_READERS=ON \
+ -DZXING_WRITERS=OLD \
+ -DZXING_EXAMPLES=OFF \
+ -DZXING_BLACKBOX_TESTS=OFF \
+ -DZXING_UNIT_TESTS=OFF \
+ -DZXING_C_API=OFF \
+ -DZXING_PYTHON_MODULE=OFF \
+ -DZXING_DEPENDENCIES=LOCAL
+ $(MAKE) -C '$(BUILD_DIR)' -j '$(JOBS)'
+ $(MAKE) -C '$(BUILD_DIR)' -j 1 install
+
+ # compile test
+ '$(TARGET)-g++' \
+ -W -Wall -Werror -std=c++17 \
+ '$(TEST_FILE)' -o '$(PREFIX)/$(TARGET)/bin/test-$(PKG).exe' \
+ `'$(TARGET)-pkg-config' zxing --cflags --libs`
+endef