Commit 756d5c51 authored by Méven Car's avatar Méven Car Committed by Méven Car
Browse files

Use KGuiAddons::KSystemClipboard to better handle wayland

Allow klipper to read image data from clipboard

BUG: 442923
parent 91909b57
......@@ -3,8 +3,6 @@ add_definitions(-DTRANSLATION_DOMAIN=\"klipper\")
add_definitions("-DQT_NO_CAST_FROM_ASCII -DQT_NO_CAST_TO_ASCII")
add_definitions(-DQT_NO_NARROWING_CONVERSIONS_IN_CONNECT)
add_subdirectory(systemclipboard)
set(libklipper_common_SRCS
klipper.cpp
urlgrabber.cpp
......@@ -35,6 +33,7 @@ target_link_libraries(libklipper_common_static
KF5::ConfigGui
KF5::CoreAddons
KF5::DBusAddons
KF5::GuiAddons
KF5::GlobalAccel
KF5::KIOWidgets
KF5::Notifications
......@@ -44,8 +43,7 @@ target_link_libraries(libklipper_common_static
KF5::WindowSystem
KF5::WidgetsAddons
KF5::XmlGui
${ZLIB_LIBRARY}
systemclipboard)
${ZLIB_LIBRARY})
if (X11_FOUND)
target_link_libraries(libklipper_common_static XCB::XCB Qt::X11Extras)
endif()
......@@ -80,8 +78,8 @@ target_link_libraries(plasma_engine_clipboard
KF5::WidgetsAddons # KMessageBox
KF5::WindowSystem
KF5::XmlGui # KActionCollection
KF5::GuiAddons
${ZLIB_LIBRARY}
systemclipboard
)
if (X11_FOUND)
target_link_libraries(plasma_engine_clipboard XCB::XCB Qt::X11Extras)
......
......@@ -25,6 +25,7 @@
#include <KGlobalAccel>
#include <KMessageBox>
#include <KNotification>
#include <KSystemClipboard>
#include <KTextEdit>
#include <KToggleAction>
#include <KWindowSystem>
......@@ -37,8 +38,6 @@
#include "klipperpopup.h"
#include "klippersettings.h"
#include "systemclipboard.h"
#include <prison/Prison>
#include <config-X11.h>
......@@ -112,9 +111,9 @@ Klipper::Klipper(QObject *parent, const KSharedConfigPtr &config, KlipperMode mo
QDBusConnection::sessionBus().registerObject(QStringLiteral("/klipper"), this, QDBusConnection::ExportScriptableSlots);
updateTimestamp(); // read initial X user time
m_clip = SystemClipboard::instance();
m_clip = KSystemClipboard::instance();
connect(m_clip, &SystemClipboard::changed, this, &Klipper::newClipData);
connect(m_clip, &KSystemClipboard::changed, this, &Klipper::newClipData);
connect(&m_overflowClearTimer, &QTimer::timeout, this, &Klipper::slotClearOverflow);
......
......@@ -29,7 +29,7 @@ class QMenu;
class QMimeData;
class HistoryItem;
class KNotification;
class SystemClipboard;
class KSystemClipboard;
enum class KlipperMode {
Standalone,
......@@ -171,7 +171,7 @@ private Q_SLOTS:
private:
static void updateTimestamp();
SystemClipboard *m_clip;
KSystemClipboard *m_clip;
QElapsedTimer m_showTimer;
......
find_package(QtWaylandScanner REQUIRED)
include_directories(SYSTEM ${Qt5Gui_PRIVATE_INCLUDE_DIRS}) # for native interface to get wl_seat
find_package(Wayland 1.15 COMPONENTS Client)
find_package(Qt5 ${QT_MIN_VERSION} CONFIG REQUIRED COMPONENTS WaylandClient)
set(systemclipboard_SRCS
systemclipboard.cpp
qtclipboard.cpp
waylandclipboard.cpp
)
ecm_add_qtwayland_client_protocol(systemclipboard_SRCS
PROTOCOL wlr-data-control-unstable-v1.xml
BASENAME wlr-data-control-unstable-v1
)
add_library(systemclipboard STATIC ${systemclipboard_SRCS})
target_link_libraries(systemclipboard
Qt::Gui
Qt::WaylandClient
Wayland::Client
KF5::WindowSystem
)
if(BUILD_TESTING)
add_subdirectory(tests)
endif()
/*
SPDX-FileCopyrightText: 2020 David Edmundson <davidedmundson@kde.org>
SPDX-License-Identifier: LGPL-2.0-or-later
*/
#include "qtclipboard.h"
#include <QClipboard>
#include <QGuiApplication>
QtClipboard::QtClipboard(QObject *parent)
: SystemClipboard(parent)
{
connect(qApp->clipboard(), &QClipboard::changed, this, &QtClipboard::changed);
}
void QtClipboard::setMimeData(QMimeData *mime, QClipboard::Mode mode)
{
qApp->clipboard()->setMimeData(mime, mode);
}
void QtClipboard::clear(QClipboard::Mode mode)
{
qApp->clipboard()->clear(mode);
}
const QMimeData *QtClipboard::mimeData(QClipboard::Mode mode) const
{
return qApp->clipboard()->mimeData(mode);
}
/*
SPDX-FileCopyrightText: 2020 David Edmundson <davidedmundson@kde.org>
SPDX-License-Identifier: LGPL-2.0-or-later
*/
#pragma once
#include "systemclipboard.h"
class QtClipboard : public SystemClipboard
{
public:
explicit QtClipboard(QObject *parent);
void setMimeData(QMimeData *mime, QClipboard::Mode mode) override;
void clear(QClipboard::Mode mode) override;
const QMimeData *mimeData(QClipboard::Mode mode) const override;
};
/*
SPDX-FileCopyrightText: 2020 David Edmundson <davidedmundson@kde.org>
SPDX-License-Identifier: LGPL-2.0-or-later
*/
#include "systemclipboard.h"
#include "qtclipboard.h"
#include "waylandclipboard.h"
#include <KWindowSystem>
#include <QGuiApplication>
SystemClipboard *SystemClipboard::instance()
{
if (!qApp || qApp->closingDown()) {
return nullptr;
}
static SystemClipboard *systemClipboard = nullptr;
if (!systemClipboard) {
if (KWindowSystem::isPlatformWayland()) {
systemClipboard = new WaylandClipboard(qApp);
} else {
systemClipboard = new QtClipboard(qApp);
}
}
return systemClipboard;
}
SystemClipboard::SystemClipboard(QObject *parent)
: QObject(parent)
{
}
/*
SPDX-FileCopyrightText: 2020 David Edmundson <davidedmundson@kde.org>
SPDX-License-Identifier: LGPL-2.0-or-later
*/
#pragma once
#include <QClipboard>
#include <QMimeData>
#include <QObject>
/**
* This class mimics QClipboard but unlike QClipboard it will continue
* to get updates even when our window does not have focus.
*
* This may require extra access permissions
*/
class SystemClipboard : public QObject
{
Q_OBJECT
public:
/**
* Returns a shared global SystemClipboard instance
*/
static SystemClipboard *instance();
/**
* Sets the clipboard to the new contents
* The clpboard takes ownership of mime
*/
// maybe I should unique_ptr it to be expressive, but then I don't match QClipboard?
virtual void setMimeData(QMimeData *mime, QClipboard::Mode mode) = 0;
/**
* Clears the current clipboard
*/
virtual void clear(QClipboard::Mode mode) = 0;
/**
* Returns the current mime data received by the clipboard
*/
virtual const QMimeData *mimeData(QClipboard::Mode mode) const = 0;
Q_SIGNALS:
void changed(QClipboard::Mode mode);
protected:
SystemClipboard(QObject *parent);
};
add_executable(pasteclient paste.cpp)
target_link_libraries(pasteclient
systemclipboard
)
/*
SPDX-FileCopyrightText: 2020 David Edmundson <davidedmundson@kde.org>
SPDX-License-Identifier: GPL-2.0-or-later
*/
#include <QDebug>
#include <QGuiApplication>
#include "../systemclipboard/systemclipboard.h"
int main(int argc, char **argv)
{
QGuiApplication app(argc, argv);
auto clip = SystemClipboard::instance();
QObject::connect(clip, &SystemClipboard::changed, &app, [clip](QClipboard::Mode mode) {
if (mode != QClipboard::Clipboard) {
return;
}
auto dbg = qDebug();
dbg << "New clipboard content: ";
if (clip->mimeData(QClipboard::Clipboard)) {
dbg << clip->mimeData(QClipboard::Clipboard)->text();
} else {
dbg << "[empty]";
}
});
qDebug() << "Watching for new clipboard content...";
app.exec();
}
/*
SPDX-FileCopyrightText: 2020 David Edmundson <davidedmundson@kde.org>
SPDX-License-Identifier: LGPL-2.0-or-later
*/
#include "waylandclipboard.h"
#include <QDebug>
#include <QFile>
#include <QFutureWatcher>
#include <QGuiApplication>
#include <QPointer>
#include <QtWaylandClient/QWaylandClientExtension>
#include <qpa/qplatformnativeinterface.h>
#include <errno.h>
#include <poll.h>
#include <string.h>
#include <unistd.h>
#include "qwayland-wlr-data-control-unstable-v1.h"
static QString utf8Text()
{
return QStringLiteral("text/plain;charset=utf-8");
}
class DataControlDeviceManager : public QWaylandClientExtensionTemplate<DataControlDeviceManager>, public QtWayland::zwlr_data_control_manager_v1
{
Q_OBJECT
public:
DataControlDeviceManager()
: QWaylandClientExtensionTemplate<DataControlDeviceManager>(2)
{
}
~DataControlDeviceManager()
{
destroy();
}
};
class DataControlOffer : public QMimeData, public QtWayland::zwlr_data_control_offer_v1
{
Q_OBJECT
public:
DataControlOffer(struct ::zwlr_data_control_offer_v1 *id)
: QtWayland::zwlr_data_control_offer_v1(id)
{
}
~DataControlOffer()
{
destroy();
}
QStringList formats() const override
{
return m_receivedFormats;
}
bool hasFormat(const QString &mimeType) const override
{
if (mimeType == QStringLiteral("text/plain") && m_receivedFormats.contains(utf8Text())) {
return true;
}
return m_receivedFormats.contains(mimeType);
}
protected:
void zwlr_data_control_offer_v1_offer(const QString &mime_type) override
{
m_receivedFormats << mime_type;
}
QVariant retrieveData(const QString &mimeType, QVariant::Type type) const override;
private:
static bool readData(int fd, QByteArray &data);
QStringList m_receivedFormats;
};
QVariant DataControlOffer::retrieveData(const QString &mimeType, QVariant::Type type) const
{
Q_UNUSED(type);
QString mime = mimeType;
if (!m_receivedFormats.contains(mimeType)) {
if (mimeType == QStringLiteral("text/plain") && m_receivedFormats.contains(utf8Text())) {
mime = utf8Text();
} else {
return QVariant();
}
}
int pipeFds[2];
if (pipe(pipeFds) != 0) {
return QVariant();
}
auto t = const_cast<DataControlOffer *>(this);
t->receive(mime, pipeFds[1]);
close(pipeFds[1]);
/*
* Ideally we need to introduce a non-blocking QMimeData object
* Or a non-blocking constructor to QMimeData with the mimetypes that are relevant
*
* However this isn't actually any worse than X.
*/
QPlatformNativeInterface *native = qApp->platformNativeInterface();
auto display = static_cast<struct ::wl_display *>(native->nativeResourceForIntegration("wl_display"));
wl_display_flush(display);
QFile readPipe;
if (readPipe.open(pipeFds[0], QIODevice::ReadOnly)) {
QByteArray data;
if (readData(pipeFds[0], data)) {
close(pipeFds[0]);
return data;
}
close(pipeFds[0]);
}
return QVariant();
}
// reads data from a file descriptor with a timeout of 1 second
// true if data is read successfully
bool DataControlOffer::readData(int fd, QByteArray &data)
{
pollfd pfds[1];
pfds[0].fd = fd;
pfds[0].events = POLLIN;
while (true) {
const int ready = poll(pfds, 1, 1000);
if (ready < 0) {
if (errno != EINTR) {
qWarning("DataControlOffer: poll() failed: %s", strerror(errno));
return false;
}
} else if (ready == 0) {
qWarning("DataControlOffer: timeout reading from pipe");
return false;
} else {
char buf[4096];
int n = read(fd, buf, sizeof buf);
if (n < 0) {
qWarning("DataControlOffer: read() failed: %s", strerror(errno));
return false;
} else if (n == 0) {
return true;
} else if (n > 0) {
data.append(buf, n);
}
}
}
}
class DataControlSource : public QObject, public QtWayland::zwlr_data_control_source_v1
{
Q_OBJECT
public:
DataControlSource(struct ::zwlr_data_control_source_v1 *id, QMimeData *mimeData);
DataControlSource();
~DataControlSource()
{
destroy();
}
QMimeData *mimeData()
{
return m_mimeData;
}
Q_SIGNALS:
void cancelled();
protected:
void zwlr_data_control_source_v1_send(const QString &mime_type, int32_t fd) override;
void zwlr_data_control_source_v1_cancelled() override;
private:
QMimeData *m_mimeData;
};
DataControlSource::DataControlSource(struct ::zwlr_data_control_source_v1 *id, QMimeData *mimeData)
: QtWayland::zwlr_data_control_source_v1(id)
, m_mimeData(mimeData)
{
for (const QString &format : mimeData->formats()) {
offer(format);
}
if (mimeData->hasText()) {
// ensure GTK applications get this mimetype to avoid them discarding the offer
offer(QStringLiteral("text/plain;charset=utf-8"));
}
}
void DataControlSource::zwlr_data_control_source_v1_send(const QString &mime_type, int32_t fd)
{
QFile c;
QString send_mime_type = mime_type;
if (send_mime_type == QStringLiteral("text/plain;charset=utf-8")) {
// if we get a request on the fallback mime, send the data from the original mime type
send_mime_type = QStringLiteral("text/plain");
}
if (c.open(fd, QFile::WriteOnly, QFile::AutoCloseHandle)) {
c.write(m_mimeData->data(send_mime_type));
c.close();
}
}
void DataControlSource::zwlr_data_control_source_v1_cancelled()
{
Q_EMIT cancelled();
}
class DataControlDevice : public QObject, public QtWayland::zwlr_data_control_device_v1
{
Q_OBJECT
public:
DataControlDevice(struct ::zwlr_data_control_device_v1 *id)
: QtWayland::zwlr_data_control_device_v1(id)
{
}
~DataControlDevice()
{
destroy();
}
void setSelection(std::unique_ptr<DataControlSource> selection);
QMimeData *receivedSelection()
{
return m_receivedSelection.get();
}
QMimeData *selection()
{
return m_selection ? m_selection->mimeData() : nullptr;
}
void setPrimarySelection(std::unique_ptr<DataControlSource> selection);
QMimeData *receivedPrimarySelection()
{
return m_receivedPrimarySelection.get();
}
QMimeData *primarySelection()
{
return m_primarySelection ? m_primarySelection->mimeData() : nullptr;
}
Q_SIGNALS:
void receivedSelectionChanged();
void selectionChanged();
void receivedPrimarySelectionChanged();
void primarySelectionChanged();
protected:
void zwlr_data_control_device_v1_data_offer(struct ::zwlr_data_control_offer_v1 *id) override
{
new DataControlOffer(id);
// this will become memory managed when we retrieve the selection event
// a compositor calling data_offer without doing that would be a bug
}
void zwlr_data_control_device_v1_selection(struct ::zwlr_data_control_offer_v1 *id) override
{
if (!id) {
m_receivedSelection.reset();
} else {
auto deriv = QtWayland::zwlr_data_control_offer_v1::fromObject(id);
auto offer = dynamic_cast<DataControlOffer *>(deriv); // dynamic because of the dual inheritance
m_receivedSelection.reset(offer);
}
emit receivedSelectionChanged();
}
void zwlr_data_control_device_v1_primary_selection(struct ::zwlr_data_control_offer_v1 *id) override
{
if (!id) {
m_receivedPrimarySelection.reset();
} else {
auto deriv = QtWayland::zwlr_data_control_offer_v1::fromObject(id);
auto offer = dynamic_cast<DataControlOffer *>(deriv); // dynamic because of the dual inheritance
m_receivedPrimarySelection.reset(offer);
}
emit receivedPrimarySelectionChanged();
}
private:
std::unique_ptr<DataControlSource> m_selection; // selection set locally
std::unique_ptr<DataControlOffer> m_receivedSelection; // latest selection set from externally to here
std::unique_ptr<DataControlSource> m_primarySelection; // selection set locally
std::unique_ptr<DataControlOffer> m_receivedPrimarySelection; // latest selection set from externally to here
};
void DataControlDevice::setSelection(std::unique_ptr<DataControlSource> selection)
{
m_selection = std::move(selection);
connect(m_selection.get(), &DataControlSource::cancelled, this, [this]() {
m_selection.reset();
Q_EMIT selectionChanged();
});
set_selection(m_selection->object());
Q_EMIT selectionChanged();
}
void DataControlDevice::setPrimarySelection(std::unique_ptr<DataControlSource> selection)
{
m_primarySelection = std::move(selection);
connect(m_primarySelection.get(), &DataControlSource::cancelled, this, [this]() {
m_primarySelection.reset();
Q_EMIT primarySelectionChanged();
});
if (zwlr_data_control_device_v1_get_version(object()) >= ZWLR_DATA_CONTROL_DEVICE_V1_SET_PRIMARY_SELECTION_SINCE_VERSION) {
set_primary_selection(m_primarySelection->object());
Q_EMIT primarySelectionChanged();