File: playercontainer.cpp

package info (click to toggle)
plasma-workspace 4%3A5.8.6-2.1%2Bdeb9u1
  • links: PTS, VCS
  • area: main
  • in suites: stretch
  • size: 54,996 kB
  • sloc: cpp: 70,006; sh: 868; xml: 867; python: 46; makefile: 16
file content (401 lines) | stat: -rw-r--r-- 15,698 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
/*
 * Copyright 2012  Alex Merry <alex.merry@kdemail.net>
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library 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
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor,
 * Boston, MA  02110-1301  USA
 */

#include "playercontainer.h"

#include <dbusproperties.h>
#include <mprisplayer.h>
#include <mprisroot.h>

#define MPRIS2_PATH "/org/mpris/MediaPlayer2"
#define POS_UPD_STRING "Position last updated (UTC)"

#include <KDesktopFile>

#include <QtDBus>
#include <QDateTime>

#include "debug.h"

static QVariant::Type expPropType(const QString& propName)
{
    if (propName == QLatin1String("Identity"))
        return QVariant::String;
    else if (propName == QLatin1String("DesktopEntry"))
        return QVariant::String;
    else if (propName == QLatin1String("SupportedUriSchemes"))
        return QVariant::StringList;
    else if (propName == QLatin1String("SupportedMimeTypes"))
        return QVariant::StringList;
    else if (propName == QLatin1String("Fullscreen"))
        return QVariant::Bool;
    else if (propName == QLatin1String("PlaybackStatus"))
        return QVariant::String;
    else if (propName == QLatin1String("LoopStatus"))
        return QVariant::String;
    else if (propName == QLatin1String("Shuffle"))
        return QVariant::Bool;
    else if (propName == QLatin1String("Rate"))
        return QVariant::Double;
    else if (propName == QLatin1String("MinimumRate"))
        return QVariant::Double;
    else if (propName == QLatin1String("MaximumRate"))
        return QVariant::Double;
    else if (propName == QLatin1String("Volume"))
        return QVariant::Double;
    else if (propName == QLatin1String("Position"))
        return QVariant::LongLong;
    else if (propName == QLatin1String("Metadata"))
        return QVariant::Map;
    // we give out CanControl, as this may completely
    // change the UI of the widget
    else if (propName == QLatin1String("CanControl"))
        return QVariant::Bool;
    else if (propName == QLatin1String("CanSeek"))
        return QVariant::Bool;
    else if (propName == QLatin1String("CanGoNext"))
        return QVariant::Bool;
    else if (propName == QLatin1String("CanGoPrevious"))
        return QVariant::Bool;
    else if (propName == QLatin1String("CanRaise"))
        return QVariant::Bool;
    else if (propName == QLatin1String("CanQuit"))
        return QVariant::Bool;
    return QVariant::Invalid;
}

static PlayerContainer::Cap capFromName(const QString& capName)
{
    if (capName == QLatin1String("CanQuit"))
        return PlayerContainer::CanQuit;
    else if (capName == QLatin1String("CanRaise"))
        return PlayerContainer::CanRaise;
    else if (capName == QLatin1String("CanSetFullscreen"))
        return PlayerContainer::CanSetFullscreen;
    else if (capName == QLatin1String("CanControl"))
        return PlayerContainer::CanControl;
    else if (capName == QLatin1String("CanPlay"))
        return PlayerContainer::CanPlay;
    else if (capName == QLatin1String("CanPause"))
        return PlayerContainer::CanPause;
    else if (capName == QLatin1String("CanSeek"))
        return PlayerContainer::CanSeek;
    else if (capName == QLatin1String("CanGoNext"))
        return PlayerContainer::CanGoNext;
    else if (capName == QLatin1String("CanGoPrevious"))
        return PlayerContainer::CanGoPrevious;
    return PlayerContainer::NoCaps;
}

PlayerContainer::PlayerContainer(const QString& busAddress, QObject* parent)
    : DataContainer(parent)
    , m_caps(NoCaps)
    , m_fetchesPending(0)
    , m_dbusAddress(busAddress)
    , m_currentRate(0.0)
{
    Q_ASSERT(!busAddress.isEmpty());
    Q_ASSERT(busAddress.startsWith(QLatin1String("org.mpris.MediaPlayer2.")));

    m_propsIface = new OrgFreedesktopDBusPropertiesInterface(
            busAddress, MPRIS2_PATH,
            QDBusConnection::sessionBus(), this);

    m_playerIface = new OrgMprisMediaPlayer2PlayerInterface(
            busAddress, MPRIS2_PATH,
            QDBusConnection::sessionBus(), this);

    m_rootIface = new OrgMprisMediaPlayer2Interface(
            busAddress, MPRIS2_PATH,
            QDBusConnection::sessionBus(), this);

    connect(m_propsIface, &OrgFreedesktopDBusPropertiesInterface::PropertiesChanged,
            this,         &PlayerContainer::propertiesChanged);

    connect(m_playerIface, &OrgMprisMediaPlayer2PlayerInterface::Seeked,
            this,          &PlayerContainer::seeked);

    refresh();
}

void PlayerContainer::refresh()
{
    // despite these calls being async, we should never update values in the
    // wrong order (eg: a stale GetAll response overwriting a more recent value
    // from a PropertiesChanged signal) due to D-Bus message ordering guarantees.

    QDBusPendingCall async = m_propsIface->GetAll(OrgMprisMediaPlayer2Interface::staticInterfaceName());
    QDBusPendingCallWatcher *watcher = new QDBusPendingCallWatcher(async, this);
    connect(watcher, &QDBusPendingCallWatcher::finished,
            this,    &PlayerContainer::getPropsFinished);
    ++m_fetchesPending;

    async = m_propsIface->GetAll(OrgMprisMediaPlayer2PlayerInterface::staticInterfaceName());
    watcher = new QDBusPendingCallWatcher(async, this);
    connect(watcher, &QDBusPendingCallWatcher::finished,
            this,    &PlayerContainer::getPropsFinished);
    ++m_fetchesPending;
}

static bool decodeUri(QVariantMap &map, const QString& entry) {
    if (map.contains(entry)) {
        QString urlString = map.value(entry).toString();
        QUrl url = QUrl::fromEncoded(urlString.toUtf8());
        if (!url.isValid()) {
            // try to be lenient
            url = QUrl(urlString);
        }
        if (url.isValid()) {
            map.insert(entry, QVariant(url));
            return true;
        } else {
            map.remove(entry);
            return false;
        }
    }
    // count it as a success if it doesn't exist
    return true;
}

void PlayerContainer::copyProperty(const QString& propName, const QVariant& _value, QVariant::Type expType, UpdateType updType)
{
    QVariant value = _value;
    // we protect our users from bogus values
    if (value.userType() == qMetaTypeId<QDBusArgument>()) {
        if (expType == QVariant::Map) {
            QDBusArgument arg = value.value<QDBusArgument>();
            // Bug 374531: MapType fits all kinds of maps but we crash when we try to stream the arg into a
            // QVariantMap below but get a wrong signature, e.g. a{ss} instead of the expected a{sv}
            if (arg.currentType() != QDBusArgument::MapType || arg.currentSignature() != QLatin1String("a{sv}")) {
                qCWarning(MPRIS2) << m_dbusAddress << "exports" << propName
                    << "with the wrong type; it should be D-Bus type \"a{sv}\"";
                return;
            }
            QVariantMap map;
            arg >> map;
            if (propName == QLatin1String("Metadata")) {
                if (!decodeUri(map, QLatin1String("mpris:artUrl"))) {
                    qCWarning(MPRIS2) << m_dbusAddress << "has an invalid URL for the mpris:artUrl entry of the \"Metadata\" property";
                }
                if (!decodeUri(map, QLatin1String("xesam:url"))) {
                    qCWarning(MPRIS2) << m_dbusAddress << "has an invalid URL for the xesam:url entry of the \"Metadata\" property";
                }
            }
            value = QVariant(map);
        }
    }
    if (value.type() != expType) {
        const char * gotTypeCh = QDBusMetaType::typeToSignature(value.userType());
        QString gotType = gotTypeCh ? QString::fromLatin1(gotTypeCh) : QStringLiteral("<unknown>");
        const char * expTypeCh = QDBusMetaType::typeToSignature(expType);
        QString expType = expTypeCh ? QString::fromLatin1(expTypeCh) : QStringLiteral("<unknown>");

        qCWarning(MPRIS2) << m_dbusAddress << "exports" << propName
            << "as D-Bus type" << gotType
            << "but it should be D-Bus type" << expType;
    }
    if (value.convert(expType)) {
        if (propName == QLatin1String("Position")) {

            setData(POS_UPD_STRING, QDateTime::currentDateTimeUtc());

        } else if (propName == QLatin1String("Metadata")) {

            if (updType == UpdatedSignal) {
                QDBusObjectPath oldTrackId(data().value(QStringLiteral("Metadata")).toMap().value(QStringLiteral("mpris:trackid")).toString());
                QDBusObjectPath newTrackId(value.toMap().value(QStringLiteral("mpris:trackid")).toString());
                if (oldTrackId != newTrackId) {
                    setData(QStringLiteral("Position"), static_cast<qlonglong>(0));
                    setData(POS_UPD_STRING, QDateTime::currentDateTimeUtc());
                }
            }

            if (value.toMap().value(QStringLiteral("mpris:length")).toLongLong() <= 0) {
                QMap<QString, QVariant> metadataMap = value.toMap();
                metadataMap.remove(QStringLiteral("mpris:length"));
                value = QVariant(metadataMap);
            }

        } else if (propName == QLatin1String("Rate") &&
                data().value(QStringLiteral("PlaybackStatus")).toString() == QLatin1String("Playing")) {

            if (data().contains(QStringLiteral("Position")))
                recalculatePosition();
            m_currentRate = value.toDouble();

        } else if (propName == QLatin1String("PlaybackStatus")) {

            if (data().contains(QStringLiteral("Position")) && data().contains(QStringLiteral("PlaybackStatus"))) {
                updatePosition();
            }

            // update the effective rate
            if (data().contains(QStringLiteral("Rate"))) {
                if (value.toString() == QLatin1String("Playing"))
                    m_currentRate = data().value(QStringLiteral("Rate")).toDouble();
                else
                    m_currentRate = 0.0;
            }
            if (value.toString() == QLatin1String("Stopped")) {
                // assume the position has reset to 0, since this is really the
                // only sensible value for a stopped track
                setData(QStringLiteral("Position"), static_cast<qint64>(0));
                setData(POS_UPD_STRING, QDateTime::currentDateTimeUtc());
            }
        } else if (propName == QLatin1String("DesktopEntry")) {
            QString filename = value.toString() + QLatin1String(".desktop");
            KDesktopFile desktopFile(filename);
            QString iconName = desktopFile.readIcon();
            if (!iconName.isEmpty()) {
                setData(QStringLiteral("Desktop Icon Name"), iconName);
            }
        }
        setData(propName, value);
    }
}

void PlayerContainer::updateFromMap(const QVariantMap& map, UpdateType updType)
{
    QMap<QString, QVariant>::const_iterator i = map.constBegin();
    while (i != map.constEnd()) {
        QVariant::Type type = expPropType(i.key());
        if (type != QVariant::Invalid) {
            copyProperty(i.key(), i.value(), type, updType);
        }

        Cap cap = capFromName(i.key());
        if (cap != NoCaps) {
            if (i.value().type() == QVariant::Bool) {
                if (i.value().toBool()) {
                    m_caps |= cap;
                } else {
                    m_caps &= ~cap;
                }
            } else {
                const char * gotTypeCh = QDBusMetaType::typeToSignature(i.value().userType());
                QString gotType = gotTypeCh ? QString::fromLatin1(gotTypeCh) : QStringLiteral("<unknown>");

                qCWarning(MPRIS2) << m_dbusAddress << "exports" << i.key()
                    << "as D-Bus type" << gotType
                    << "but it should be D-Bus type \"b\"";
            }
        }
        // fake the CanStop capability
        if (cap == CanControl || i.key() == QLatin1String("PlaybackStatus")) {
            if ((m_caps & CanControl) && i.value().toString() != QLatin1String("Stopped")) {
                qCDebug(MPRIS2) << "Enabling stop action";
                m_caps |= CanStop;
            } else {
                qCDebug(MPRIS2) << "Disabling stop action";
                m_caps &= ~CanStop;
            }
        }
        ++i;
    }
}

void PlayerContainer::getPropsFinished(QDBusPendingCallWatcher* watcher)
{
    QDBusPendingReply<QVariantMap> propsReply = *watcher;
    watcher->deleteLater();

    if (m_fetchesPending < 1) {
        // we already failed
        return;
    }

    if (propsReply.isError()) {
        qCWarning(MPRIS2) << m_dbusAddress << "does not implement"
            << OrgFreedesktopDBusPropertiesInterface::staticInterfaceName()
            << "correctly";
        qCDebug(MPRIS2) << "Error message was" << propsReply.error().name() << propsReply.error().message();
        m_fetchesPending = 0;
        emit initialFetchFailed(this);
        return;
    }

    updateFromMap(propsReply.value(), FetchAll);
    checkForUpdate();

    --m_fetchesPending;
    if (m_fetchesPending == 0) {
        emit initialFetchFinished(this);
    }
}

void PlayerContainer::updatePosition()
{
    QDBusPendingCall async = m_propsIface->Get(OrgMprisMediaPlayer2PlayerInterface::staticInterfaceName(), QStringLiteral("Position"));
    QDBusPendingCallWatcher *watcher = new QDBusPendingCallWatcher(async, this);
    connect(watcher, &QDBusPendingCallWatcher::finished,
            this,    &PlayerContainer::getPositionFinished);
}

void PlayerContainer::getPositionFinished(QDBusPendingCallWatcher* watcher)
{
    QDBusPendingReply<QVariant> propsReply = *watcher;
    watcher->deleteLater();

    if (propsReply.isError()) {
        qCWarning(MPRIS2) << m_dbusAddress << "does not implement"
            << OrgFreedesktopDBusPropertiesInterface::staticInterfaceName()
            << "correctly";
        qCDebug(MPRIS2) << "Error message was" << propsReply.error().name() << propsReply.error().message();
        return;
    }

    setData(QStringLiteral("Position"), propsReply.value().toLongLong());
    setData(POS_UPD_STRING, QDateTime::currentDateTimeUtc());
    checkForUpdate();
}

void PlayerContainer::propertiesChanged(
        const QString& interface,
        const QVariantMap& changedProperties,
        const QStringList& invalidatedProperties)
{
    Q_UNUSED(interface)

    updateFromMap(changedProperties, UpdatedSignal);
    if (!invalidatedProperties.isEmpty()) {
        refresh();
    }
    checkForUpdate();
}

void PlayerContainer::seeked(qlonglong position)
{
    setData(QStringLiteral("Position"), position);
    setData(POS_UPD_STRING, QDateTime::currentDateTimeUtc());
    checkForUpdate();
}

void PlayerContainer::recalculatePosition()
{
    Q_ASSERT(data().contains("Position"));

    qint64 pos = data().value(QStringLiteral("Position")).toLongLong();
    QDateTime lastUpdated = data().value(POS_UPD_STRING).toDateTime();
    QDateTime now = QDateTime::currentDateTimeUtc();
    qint64 diff = lastUpdated.msecsTo(now) * 1000;
    qint64 newPos = pos + static_cast<qint64>(diff * m_currentRate);
    setData(QStringLiteral("Position"), newPos);
    setData(POS_UPD_STRING, now);
}