screencast.cpp 12.2 KB
Newer Older
Jan Grulich's avatar
Jan Grulich committed
1
/*
2
 * SPDX-FileCopyrightText: 2018 Red Hat Inc
Jan Grulich's avatar
Jan Grulich committed
3
 *
4
 * SPDX-License-Identifier: LGPL-2.0-or-later
Jan Grulich's avatar
Jan Grulich committed
5
 *
6
 * SPDX-FileCopyrightText: 2018 Jan Grulich <jgrulich@redhat.com>
7
 * SPDX-FileCopyrightText: 2022 Harald Sitter <sitter@kde.org>
Jan Grulich's avatar
Jan Grulich committed
8
9
10
 */

#include "screencast.h"
11
#include "notificationinhibition.h"
12
#include "request.h"
Jan Grulich's avatar
Jan Grulich committed
13
#include "screenchooserdialog.h"
14
#include "session.h"
15
#include "utils.h"
Alexander Lohnau's avatar
Alexander Lohnau committed
16
#include "waylandintegration.h"
Jan Grulich's avatar
Jan Grulich committed
17

18
19
20
#include <KConfigGroup>
#include <KLocalizedString>
#include <KSharedConfig>
21
#include <KWayland/Client/plasmawindowmodel.h>
22

23
24
25
#include <QDBusArgument>
#include <QDBusMetaType>
#include <QDataStream>
26
#include <QIODevice>
27
#include <QLoggingCategory>
Jan Grulich's avatar
Jan Grulich committed
28
29
30

Q_LOGGING_CATEGORY(XdgDesktopPortalKdeScreenCast, "xdp-kde-screencast")

31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
struct RestoreData {
    static uint currentRestoreDataVersion()
    {
        return 1;
    }

    QString session;
    quint32 version = 0;
    QVariantMap payload;
};

const QDBusArgument &operator<<(QDBusArgument &arg, const RestoreData &data)
{
    arg.beginStructure();
    arg << data.session;
    arg << data.version;

    QByteArray payloadSerialised;
    {
        QDataStream ds(&payloadSerialised, QIODevice::WriteOnly);
        ds << data.payload;
    }

    arg << QDBusVariant(payloadSerialised);
    arg.endStructure();
    return arg;
}
const QDBusArgument &operator>>(const QDBusArgument &arg, RestoreData &data)
{
    arg.beginStructure();
    arg >> data.session;
    arg >> data.version;

    QDBusVariant payloadVariant;
    arg >> payloadVariant;
    {
        QByteArray payloadSerialised = payloadVariant.variant().toByteArray();
        QDataStream ds(&payloadSerialised, QIODevice::ReadOnly);
        ds >> data.payload;
    }
    arg.endStructure();
    return arg;
}

QDebug operator<<(QDebug dbg, const RestoreData &c)
{
    dbg.nospace() << "RestoreData(" << c.session << ", " << c.version << ", " << c.payload << ")";
    return dbg.space();
}

Q_DECLARE_METATYPE(RestoreData)

Jan Grulich's avatar
Jan Grulich committed
83
84
85
ScreenCastPortal::ScreenCastPortal(QObject *parent)
    : QDBusAbstractAdaptor(parent)
{
86
    qDBusRegisterMetaType<RestoreData>();
Jan Grulich's avatar
Jan Grulich committed
87
88
89
90
91
92
}

ScreenCastPortal::~ScreenCastPortal()
{
}

93
94
95
96
97
98
99
100
101
102
103
104
105
bool ScreenCastPortal::inhibitionsEnabled() const
{
    if (!WaylandIntegration::isStreamingAvailable()) {
        return false;
    }

    auto cfg = KSharedConfig::openConfig(QStringLiteral("plasmanotifyrc"));

    KConfigGroup grp(cfg, "DoNotDisturb");

    return grp.readEntry("WhenScreenSharing", true);
}

Jan Grulich's avatar
Jan Grulich committed
106
107
108
109
110
111
112
113
114
115
116
117
118
119
uint ScreenCastPortal::CreateSession(const QDBusObjectPath &handle,
                                     const QDBusObjectPath &session_handle,
                                     const QString &app_id,
                                     const QVariantMap &options,
                                     QVariantMap &results)
{
    Q_UNUSED(results)

    qCDebug(XdgDesktopPortalKdeScreenCast) << "CreateSession called with parameters:";
    qCDebug(XdgDesktopPortalKdeScreenCast) << "    handle: " << handle.path();
    qCDebug(XdgDesktopPortalKdeScreenCast) << "    session_handle: " << session_handle.path();
    qCDebug(XdgDesktopPortalKdeScreenCast) << "    app_id: " << app_id;
    qCDebug(XdgDesktopPortalKdeScreenCast) << "    options: " << options;

Jan Grulich's avatar
Jan Grulich committed
120
121
122
    Session *session = Session::createSession(this, Session::ScreenCast, app_id, session_handle.path());

    if (!session) {
Jan Grulich's avatar
Jan Grulich committed
123
124
        return 2;
    }
Jan Grulich's avatar
Jan Grulich committed
125

126
127
128
129
130
    if (!WaylandIntegration::isStreamingAvailable()) {
        qCWarning(XdgDesktopPortalKdeScreenCast) << "zkde_screencast_unstable_v1 does not seem to be available";
        return 2;
    }

131
132
133
134
135
136
    connect(session, &Session::closed, [session] {
        auto screencastSession = qobject_cast<ScreenCastSession *>(session);
        const auto streams = screencastSession->streams();
        for (const WaylandIntegration::Stream &stream : streams) {
            WaylandIntegration::stopStreaming(stream.nodeId);
        }
Jan Grulich's avatar
Jan Grulich committed
137
138
    });

139
140
    connect(WaylandIntegration::waylandIntegration(), &WaylandIntegration::WaylandIntegration::streamingStopped, session, &Session::close);

Jan Grulich's avatar
Jan Grulich committed
141
    return 0;
Jan Grulich's avatar
Jan Grulich committed
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
}

uint ScreenCastPortal::SelectSources(const QDBusObjectPath &handle,
                                     const QDBusObjectPath &session_handle,
                                     const QString &app_id,
                                     const QVariantMap &options,
                                     QVariantMap &results)
{
    Q_UNUSED(results)

    qCDebug(XdgDesktopPortalKdeScreenCast) << "SelectSource called with parameters:";
    qCDebug(XdgDesktopPortalKdeScreenCast) << "    handle: " << handle.path();
    qCDebug(XdgDesktopPortalKdeScreenCast) << "    session_handle: " << session_handle.path();
    qCDebug(XdgDesktopPortalKdeScreenCast) << "    app_id: " << app_id;
    qCDebug(XdgDesktopPortalKdeScreenCast) << "    options: " << options;

Alexander Lohnau's avatar
Alexander Lohnau committed
158
    ScreenCastSession *session = qobject_cast<ScreenCastSession *>(Session::getSession(session_handle.path()));
Jan Grulich's avatar
Jan Grulich committed
159
160
161
162
163
164

    if (!session) {
        qCWarning(XdgDesktopPortalKdeScreenCast) << "Tried to select sources on non-existing session " << session_handle.path();
        return 2;
    }

165
    session->setOptions(options);
Jan Grulich's avatar
Jan Grulich committed
166

167
168
    // Might be also a RemoteDesktopSession
    if (session->type() == Session::RemoteDesktop) {
Alexander Lohnau's avatar
Alexander Lohnau committed
169
        RemoteDesktopSession *remoteDesktopSession = qobject_cast<RemoteDesktopSession *>(session);
170
171
172
173
174
        if (remoteDesktopSession) {
            remoteDesktopSession->setScreenSharingEnabled(true);
        }
    }

Jan Grulich's avatar
Jan Grulich committed
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
    return 0;
}

uint ScreenCastPortal::Start(const QDBusObjectPath &handle,
                             const QDBusObjectPath &session_handle,
                             const QString &app_id,
                             const QString &parent_window,
                             const QVariantMap &options,
                             QVariantMap &results)
{
    qCDebug(XdgDesktopPortalKdeScreenCast) << "Start called with parameters:";
    qCDebug(XdgDesktopPortalKdeScreenCast) << "    handle: " << handle.path();
    qCDebug(XdgDesktopPortalKdeScreenCast) << "    session_handle: " << session_handle.path();
    qCDebug(XdgDesktopPortalKdeScreenCast) << "    app_id: " << app_id;
    qCDebug(XdgDesktopPortalKdeScreenCast) << "    parent_window: " << parent_window;
    qCDebug(XdgDesktopPortalKdeScreenCast) << "    options: " << options;

Alexander Lohnau's avatar
Alexander Lohnau committed
192
    ScreenCastSession *session = qobject_cast<ScreenCastSession *>(Session::getSession(session_handle.path()));
Jan Grulich's avatar
Jan Grulich committed
193
194

    if (!session) {
195
        qCWarning(XdgDesktopPortalKdeScreenCast) << "Tried to call start on non-existing session " << session_handle.path();
Jan Grulich's avatar
Jan Grulich committed
196
197
198
        return 2;
    }

199
    if (WaylandIntegration::screens().isEmpty()) {
Jan Grulich's avatar
Jan Grulich committed
200
201
202
203
        qCWarning(XdgDesktopPortalKdeScreenCast) << "Failed to show dialog as there is no screen to select";
        return 2;
    }

204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
    const PersistMode persist = session->persistMode();
    bool valid = false;
    QList<Output> selectedOutputs;
    QVector<QMap<int, QVariant>> selectedWindows;
    if (persist != NoPersist && session->restoreData().isValid()) {
        RestoreData restoreData;
        auto arg = session->restoreData().value<QDBusArgument>();
        arg >> restoreData;
        if (restoreData.session == QLatin1String("KDE") && restoreData.version == RestoreData::currentRestoreDataVersion()) {
            const QVariantMap restoreDataPayload = restoreData.payload;
            const QVariantList restoreOutputs = restoreDataPayload[QStringLiteral("outputs")].toList();
            if (!restoreOutputs.isEmpty()) {
                OutputsModel model(OutputsModel::WorkspaceIncluded, this);
                for (const auto &outputUniqueId : restoreOutputs) {
                    for (int i = 0, c = model.rowCount(); i < c; ++i) {
                        const Output &iOutput = model.outputAt(i);
                        if (iOutput.uniqueId() == outputUniqueId) {
                            selectedOutputs << iOutput;
                        }
                    }
                }
                valid = selectedOutputs.count() == restoreOutputs.count();
            }

            const QStringList restoreWindows = restoreDataPayload[QStringLiteral("windows")].toStringList();
            if (!restoreWindows.isEmpty()) {
                const KWayland::Client::PlasmaWindowModel model(WaylandIntegration::plasmaWindowManagement());
                for (const QString &windowUuid : restoreWindows) {
                    for (int i = 0, c = model.rowCount(); i < c; ++i) {
                        const QModelIndex index = model.index(i, 0);

                        if (model.data(index, KWayland::Client::PlasmaWindowModel::Uuid) == windowUuid) {
                            selectedWindows << model.itemData(index);
                        }
                    }
                }
                valid = selectedWindows.count() == restoreWindows.count();
            }
        }
    }
244

245
    bool allowRestore = valid;
246
247
248
249
250
    if (!valid) {
        QScopedPointer<ScreenChooserDialog, QScopedPointerDeleteLater> screenDialog(
            new ScreenChooserDialog(app_id, session->multipleSources(), SourceTypes(session->types())));
        connect(session, &Session::closed, screenDialog.data(), &ScreenChooserDialog::reject);
        Utils::setParentWindow(screenDialog->windowHandle(), parent_window);
251
        Request::makeClosableDialogRequest(handle, screenDialog.get());
252
253
254
255
256
257
258
        valid = screenDialog->exec();
        if (valid) {
            allowRestore = screenDialog->allowRestore();
            selectedOutputs = screenDialog->selectedOutputs();
            selectedWindows = screenDialog->selectedWindows();
        }
    }
259

260
261
262
    if (valid) {
        QVariantList outputs;
        QStringList windows;
263
        WaylandIntegration::Streams streams;
264
        for (const auto &output : qAsConst(selectedOutputs)) {
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
            WaylandIntegration::Stream stream;
            switch (output.outputType()) {
            case WaylandIntegration::WaylandOutput::Workspace:
                stream = WaylandIntegration::startStreamingWorkspace(Screencasting::CursorMode(session->cursorMode()));
                break;
            case WaylandIntegration::WaylandOutput::Virtual:
                stream = WaylandIntegration::startStreamingVirtual(output.uniqueId(), {1920, 1080}, Screencasting::CursorMode(session->cursorMode()));
                break;
            default:
                stream = WaylandIntegration::startStreamingOutput(output.waylandOutputName(), Screencasting::CursorMode(session->cursorMode()));
                break;
            }

            if (!stream.isValid()) {
                qCWarning(XdgDesktopPortalKdeScreenCast) << "Invalid screen!" << output.outputType() << output.uniqueId();
280
281
                return 2;
            }
282
283
284
285

            if (allowRestore) {
                outputs += output.uniqueId();
            }
286
            streams << stream;
287
        }
288
        for (const auto &win : qAsConst(selectedWindows)) {
289
290
291
            WaylandIntegration::Stream stream = WaylandIntegration::startStreamingWindow(win);
            if (!stream.isValid()) {
                qCWarning(XdgDesktopPortalKdeScreenCast) << "Invalid window!" << win;
292
293
                return 2;
            }
294
295
296
297

            if (allowRestore) {
                windows += win[KWayland::Client::PlasmaWindowModel::Uuid].toString();
            }
298
            streams << stream;
299
300
        }

301
        if (streams.isEmpty()) {
Jan Grulich's avatar
Jan Grulich committed
302
303
304
305
            qCWarning(XdgDesktopPortalKdeScreenCast) << "Pipewire stream is not ready to be streamed";
            return 2;
        }

306
        session->setStreams(streams);
307
        results.insert(QStringLiteral("streams"), QVariant::fromValue<WaylandIntegration::Streams>(streams));
308
309
310
311
312
313
314
315
316
317
318
319
        if (allowRestore) {
            results.insert("persist_mode", quint32(persist));
            if (persist != NoPersist) {
                const RestoreData restoreData = {"KDE",
                                                 RestoreData::currentRestoreDataVersion(),
                                                 QVariantMap{
                                                     {"outputs", outputs},
                                                     {"windows", windows},
                                                 }};
                results.insert("restore_data", QVariant::fromValue<RestoreData>(restoreData));
            }
        }
Jan Grulich's avatar
Jan Grulich committed
320

321
322
323
        if (inhibitionsEnabled()) {
            new NotificationInhibition(app_id, i18nc("Do not disturb mode is enabled because...", "Screen sharing in progress"), session);
        }
Jan Grulich's avatar
Jan Grulich committed
324
325
326
        return 0;
    }

327
    return 1;
Jan Grulich's avatar
Jan Grulich committed
328
}