File: screenbrightnesscontrol.cpp

package info (click to toggle)
powerdevil 4%3A6.5.4-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 10,680 kB
  • sloc: cpp: 13,284; xml: 1,911; python: 1,204; sh: 19; makefile: 10
file content (312 lines) | stat: -rw-r--r-- 13,425 bytes parent folder | download | duplicates (2)
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
/*
 * SPDX-FileCopyrightText: 2024 Bohdan Onofriichuk <bogdan.onofriuchuk@gmail.com>
 *
 * SPDX-License-Identifier: GPL-2.0-or-later
 */

#include "screenbrightnesscontrol.h"

#include <brightnesscontrolplugin_debug.h>

#include <QCoroDBusPendingCall>
#include <QDBusConnectionInterface>
#include <QDBusMessage>
#include <QDBusPendingCall>
#include <QDBusReply>
#include <QDBusServiceWatcher>
#include <QPointer>
#include <QScopeGuard>

using namespace Qt::StringLiterals;

namespace
{
static const QString SCREENBRIGHTNESS_SERVICE = u"org.kde.ScreenBrightness"_s;
static const QString SCREENBRIGHTNESS_PATH = u"/org/kde/ScreenBrightness"_s;
static const QString SCREENBRIGHTNESS_IFACE = u"org.kde.ScreenBrightness"_s;
static const QString SCREENBRIGHTNESS_DISPLAY_PATH_TEMPLATE = u"/org/kde/ScreenBrightness/%1"_s;
static const QString SCREENBRIGHTNESS_DISPLAY_IFACE = u"org.kde.ScreenBrightness.Display"_s;
static const QString DBUS_PROPERTIES_IFACE = u"org.freedesktop.DBus.Properties"_s;
}

ScreenBrightnessControl::ScreenBrightnessControl(QObject *parent)
    : QObject(parent)
{
    static uint pluginId = 0;
    ++pluginId;
    m_alreadyChangedContext = QStringLiteral("AlreadyChanged-%1").arg(pluginId);

    m_serviceWatcher = std::make_unique<QDBusServiceWatcher>(SCREENBRIGHTNESS_SERVICE,
                                                             QDBusConnection::sessionBus(),
                                                             QDBusServiceWatcher::WatchForRegistration | QDBusServiceWatcher::WatchForUnregistration);
    connect(m_serviceWatcher.get(), &QDBusServiceWatcher::serviceRegistered, this, &ScreenBrightnessControl::onServiceRegistered);
    connect(m_serviceWatcher.get(), &QDBusServiceWatcher::serviceUnregistered, this, &ScreenBrightnessControl::onServiceUnregistered);

    if (QDBusConnection::sessionBus().interface()->isServiceRegistered(SCREENBRIGHTNESS_SERVICE)) {
        onServiceRegistered();
    } else {
        qCWarning(APPLETS::BRIGHTNESS) << "D-Bus service not available:" << SCREENBRIGHTNESS_SERVICE;
    }
}

ScreenBrightnessControl::~ScreenBrightnessControl()
{
}

ScreenBrightnessDisplayModel *ScreenBrightnessControl::displays()
{
    return &m_displays;
}

const ScreenBrightnessDisplayModel *ScreenBrightnessControl::displays() const
{
    return &m_displays;
}

void ScreenBrightnessControl::adjustBrightnessRatio(double delta)
{
    QDBusMessage msg = QDBusMessage::createMethodCall(SCREENBRIGHTNESS_SERVICE, SCREENBRIGHTNESS_PATH, SCREENBRIGHTNESS_IFACE, u"AdjustBrightnessRatio"_s);
    uint flags = m_isSilent ? 0x1 : 0x0;

    msg << delta << flags;
    QDBusConnection::sessionBus().asyncCall(msg);
}

void ScreenBrightnessControl::adjustBrightnessStep(ScreenBrightnessControl::StepAction stepAction)
{
    QDBusMessage msg = QDBusMessage::createMethodCall(SCREENBRIGHTNESS_SERVICE, SCREENBRIGHTNESS_PATH, SCREENBRIGHTNESS_IFACE, u"AdjustBrightnessStep"_s);
    uint flags = m_isSilent ? 0x1 : 0x0;

    msg << qToUnderlying(stepAction) << flags;
    QDBusConnection::sessionBus().asyncCall(msg);
}

void ScreenBrightnessControl::setBrightness(const QString &displayName, int value)
{
    QVariant oldBrightness = m_displays.data(m_displays.displayIndex(displayName), ScreenBrightnessDisplayModel::BrightnessRole);

    if (oldBrightness == value) {
        return;
    }

    QDBusMessage msg = QDBusMessage::createMethodCall(SCREENBRIGHTNESS_SERVICE,
                                                      SCREENBRIGHTNESS_DISPLAY_PATH_TEMPLATE.arg(displayName),
                                                      SCREENBRIGHTNESS_DISPLAY_IFACE,
                                                      u"SetBrightnessWithContext"_s);
    uint flags = m_isSilent ? 0x1 : 0x0;

    msg << value << flags << m_alreadyChangedContext;
    QDBusPendingCall async = QDBusConnection::sessionBus().asyncCall(msg);
    m_brightnessChangeWatcher.reset(new QDBusPendingCallWatcher(async));

    connect(m_brightnessChangeWatcher.get(),
            &QDBusPendingCallWatcher::finished,
            this,
            [this, displayName, oldValue = oldBrightness.toInt()](QDBusPendingCallWatcher *watcher) {
                const QDBusPendingReply<void> reply = *watcher;
                if (reply.isError()) {
                    qCWarning(APPLETS::BRIGHTNESS) << "error setting brightness via dbus" << reply.error();
                    m_displays.onBrightnessChanged(displayName, oldValue);
                }
                m_brightnessChangeWatcher.reset();
            });

    m_displays.onBrightnessChanged(displayName, value);
}

void ScreenBrightnessControl::onGlobalPropertiesChanged(const QString &ifaceName, const QVariantMap &changedProps, const QStringList &invalidatedProps)
{
    const QString displayNamesKey = u"DisplaysDBusNames"_s;

    if (ifaceName == SCREENBRIGHTNESS_IFACE) {
        if (changedProps.contains(displayNamesKey) || invalidatedProps.contains(displayNamesKey)) {
            queryAndUpdateDisplays();
        }
    }
}

void ScreenBrightnessControl::onBrightnessChanged(const QString &displayName, int value, const QString &sourceClientName, const QString &sourceClientContext)
{
    if (sourceClientName == QDBusConnection::sessionBus().baseService() && sourceClientContext == m_alreadyChangedContext) {
        qCDebug(APPLETS::BRIGHTNESS) << "ignoring brightness change, it's coming from the applet itself";
        return;
    }
    m_displays.onBrightnessChanged(displayName, value);
}

void ScreenBrightnessControl::onBrightnessRangeChanged(const QString &displayName, int max, int value)
{
    m_displays.onBrightnessRangeChanged(displayName, max, value);

    QVariant firstDisplayMax = m_displays.data(m_displays.index(0, 0), ScreenBrightnessDisplayModel::MaxBrightnessRole);

    m_isBrightnessAvailable = firstDisplayMax.isValid() && firstDisplayMax.toInt() > 0;
}

QCoro::Task<void> ScreenBrightnessControl::onServiceRegistered()
{
    m_serviceRegistered = true;
    QPointer<ScreenBrightnessControl> alive{this};

    if (!QDBusConnection::sessionBus().connect(SCREENBRIGHTNESS_SERVICE,
                                               SCREENBRIGHTNESS_PATH,
                                               DBUS_PROPERTIES_IFACE,
                                               u"PropertiesChanged"_s,
                                               this,
                                               SLOT(onGlobalPropertiesChanged(QString, QVariantMap, QStringList)))) {
        qCWarning(APPLETS::BRIGHTNESS) << "error connecting to property changes via dbus";
        co_return;
    }

    if (!QDBusConnection::sessionBus().connect(SCREENBRIGHTNESS_SERVICE,
                                               SCREENBRIGHTNESS_PATH,
                                               SCREENBRIGHTNESS_IFACE,
                                               u"BrightnessChanged"_s,
                                               this,
                                               SLOT(onBrightnessChanged(QString, int, QString, QString)))) {
        qCWarning(APPLETS::BRIGHTNESS) << "error connecting to Brightness changes via dbus";
        co_return;
    }

    if (!QDBusConnection::sessionBus().connect(SCREENBRIGHTNESS_SERVICE,
                                               SCREENBRIGHTNESS_PATH,
                                               SCREENBRIGHTNESS_IFACE,
                                               u"BrightnessRangeChanged"_s,
                                               this,
                                               SLOT(onBrightnessRangeChanged(QString, int, int)))) {
        qCWarning(APPLETS::BRIGHTNESS) << "error connecting to brightness range changes via dbus";
        co_return;
    }

    if (!co_await queryAndUpdateDisplays()) {
        qCWarning(APPLETS::BRIGHTNESS) << "error fetching display names via dbus";
        co_return;
    }

    if (!alive || !m_serviceRegistered) {
        qCWarning(APPLETS::BRIGHTNESS) << "ScreenBrightnessControl destroyed during initialization, or service got unregistered. Returning early";
        co_return;
    }

    m_isBrightnessAvailable = true;
}

void ScreenBrightnessControl::onServiceUnregistered()
{
    m_serviceRegistered = false;

    QDBusConnection::sessionBus().disconnect(SCREENBRIGHTNESS_SERVICE,
                                             SCREENBRIGHTNESS_PATH,
                                             DBUS_PROPERTIES_IFACE,
                                             u"PropertiesChanged"_s,
                                             this,
                                             SLOT(onGlobalPropertiesChanged(QString, QVariantMap, QStringList)));

    QDBusConnection::sessionBus().disconnect(SCREENBRIGHTNESS_SERVICE,
                                             SCREENBRIGHTNESS_PATH,
                                             SCREENBRIGHTNESS_IFACE,
                                             u"BrightnessChanged"_s,
                                             this,
                                             SLOT(onBrightnessChanged(QString, int, QString, QString)));

    QDBusConnection::sessionBus().disconnect(SCREENBRIGHTNESS_SERVICE,
                                             SCREENBRIGHTNESS_PATH,
                                             SCREENBRIGHTNESS_IFACE,
                                             u"BrightnessRangeChanged"_s,
                                             this,
                                             SLOT(onBrightnessRangeChanged(QString, int, int)));

    m_displays.setKnownDisplayNames({});
    m_isBrightnessAvailable = false;
}

QCoro::Task<bool> ScreenBrightnessControl::queryAndUpdateDisplays()
{
    m_shouldRecheckDisplays = true;
    if (m_displaysUpdating) {
        // With m_shouldRecheckDisplays == true, the loop below will be repeated
        // by the already running function once it's done with its current update.
        co_return false;
    }
    QPointer<ScreenBrightnessControl> alive{this};

    while (m_shouldRecheckDisplays) {
        m_shouldRecheckDisplays = false; // can be set to true while waiting for async calls
        m_displaysUpdating = true;
        QScopeGuard whenDone([this, alive] {
            if (alive) {
                m_displaysUpdating = false;
            }
        });

        QDBusMessage msg = QDBusMessage::createMethodCall(SCREENBRIGHTNESS_SERVICE, SCREENBRIGHTNESS_PATH, DBUS_PROPERTIES_IFACE, u"Get"_s);
        msg << SCREENBRIGHTNESS_IFACE << u"DisplaysDBusNames"_s;

        const QDBusReply<QVariant> reply = co_await QDBusConnection::sessionBus().asyncCall(msg);
        if (!alive || !reply.isValid() || !m_serviceRegistered) {
            qCWarning(APPLETS::BRIGHTNESS) << "error getting display ids via dbus:" << reply.error();
            co_return false;
        }
        const QStringList displayNames = reply.value().value<QStringList>();

        m_displays.setKnownDisplayNames(displayNames);

        for (const QString &displayName : m_displays.knownDisplayNamesWithMissingData()) {
            co_await queryAndInsertDisplayData(displayName);
            if (!alive || !m_serviceRegistered) {
                qCWarning(APPLETS::BRIGHTNESS) << "ScreenBrightnessControl destroyed while querying displays, returning early";
                co_return false;
            }
        }
    }
    co_return true;
}

QCoro::Task<void> ScreenBrightnessControl::queryAndInsertDisplayData(const QString &displayName)
{
    QDBusMessage msg = QDBusMessage::createMethodCall(SCREENBRIGHTNESS_SERVICE,
                                                      SCREENBRIGHTNESS_DISPLAY_PATH_TEMPLATE.arg(displayName),
                                                      DBUS_PROPERTIES_IFACE,
                                                      QStringLiteral("GetAll"));
    msg << SCREENBRIGHTNESS_DISPLAY_IFACE;
    QPointer<ScreenBrightnessControl> alive{this};
    const QDBusReply<QVariantMap> reply = co_await QDBusConnection::sessionBus().asyncCall(msg);
    if (!alive || !reply.isValid() || !m_serviceRegistered) {
        qCWarning(APPLETS::BRIGHTNESS) << "error getting display properties via dbus:" << reply.error();
        co_return;
    }
    const QVariantMap &props = reply.value();

    auto label = props.value(u"Label"_s).value<QString>();
    if (label.isEmpty()) {
        qCWarning(APPLETS::BRIGHTNESS) << "error getting display label via dbus: property missing";
        co_return;
    }

    if (!props.contains(u"IsInternal"_s)) {
        qCWarning(APPLETS::BRIGHTNESS) << "error getting display is-internal via dbus: property missing";
        co_return;
    }
    auto isInternal = props.value(u"IsInternal"_s).value<bool>();

    if (!props.contains(u"Brightness"_s)) {
        qCWarning(APPLETS::BRIGHTNESS) << "error getting display brightness via dbus: property missing";
        co_return;
    }
    auto brightness = props.value(u"Brightness"_s).value<int>();

    auto maxBrightness = props.value(u"MaxBrightness"_s).value<int>();
    if (maxBrightness <= 0) {
        qCWarning(APPLETS::BRIGHTNESS) << "error getting max display brightness via dbus: property missing";
        co_return;
    }

    m_displays.setDisplayData(displayName, label, isInternal, brightness, maxBrightness);
}

QBindable<bool> ScreenBrightnessControl::bindableIsBrightnessAvailable()
{
    return &m_isBrightnessAvailable;
}

#include "moc_screenbrightnesscontrol.cpp"