diff options
| author | Anton <anton@picapica.im> | 2026-12-02 03:52:50 +0400 |
|---|---|---|
| committer | Anton <anton@picapica.im> | 2026-12-02 03:52:50 +0400 |
| commit | c3298beb0779a8cc09b6d4ea0d2132c0612ea776 (patch) | |
| tree | 910842506249d59a05cae4a72229b61049fcab19 /pica-client | |
| parent | 56863d74399c8d7354a00bc8ddc87b924ef870ab (diff) | |
| download | pica-pica-qr_codes.tar.gz pica-pica-qr_codes.zip | |
pica-client: show and scan contact ID as a QR codeqr_codes
Diffstat (limited to 'pica-client')
| -rw-r--r-- | pica-client/contactlistwidget.cpp | 139 | ||||
| -rw-r--r-- | pica-client/contactlistwidget.h | 17 | ||||
| -rw-r--r-- | pica-client/dialogs/qrscandialog.cpp | 310 | ||||
| -rw-r--r-- | pica-client/dialogs/qrscandialog.h | 109 | ||||
| -rw-r--r-- | pica-client/dialogs/showpicaiddialog.cpp | 32 | ||||
| -rw-r--r-- | pica-client/dialogs/showpicaiddialog.h | 3 | ||||
| -rw-r--r-- | pica-client/mainwindow.cpp | 3 | ||||
| -rw-r--r-- | pica-client/qrcode.cpp | 148 | ||||
| -rw-r--r-- | pica-client/qrcode.h | 67 | ||||
| -rw-r--r-- | pica-client/videodevice.cpp | 258 | ||||
| -rw-r--r-- | pica-client/videodevice.h | 21 |
11 files changed, 1074 insertions, 33 deletions
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 → 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 |
