File: powerdevilupowerbackend.cpp

package info (click to toggle)
powerdevil 4%3A5.20.5-2
  • links: PTS, VCS
  • area: main
  • in suites: bullseye
  • size: 4,372 kB
  • sloc: cpp: 8,987; xml: 1,294; sh: 24; makefile: 12
file content (755 lines) | stat: -rw-r--r-- 32,612 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
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
/*  This file is part of the KDE project
    Copyright (C) 2006 Kevin Ottens <ervin@kde.org>
    Copyright (C) 2008-2010 Dario Freddi <drf@kde.org>
    Copyright (C) 2010 Alejandro Fiestas <alex@eyeos.org>
    Copyright (C) 2010-2013 Lukáš Tinkl <ltinkl@redhat.com>
    Copyright (C) 2015 Kai Uwe Broulik <kde@privat.broulik.de>

    This library is free software; you can redistribute it and/or
    modify it under the terms of the GNU Library General Public
    License version 2 as published by the Free Software Foundation.

    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
    Library General Public License for more details.

    You should have received a copy of the GNU Library General Public License
    along with this library; see the file COPYING.LIB.  If not, write to
    the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
    Boston, MA 02110-1301, USA.

*/

#include "powerdevilupowerbackend.h"

#include <powerdevil_debug.h>
#include <PowerDevilSettings.h>

#include <QTextStream>
#include <QDBusMessage>
#include <QDebug>
#include <QPropertyAnimation>
#include <QTimer>

#include <KAuthAction>
#include <KAuthExecuteJob>
#include <KPluginFactory>
#include <KSharedConfig>

#include "xrandrxcbhelper.h"
#include "xrandrbrightness.h"
#include "ddcutilbrightness.h"
#include "upowersuspendjob.h"
#include "login1suspendjob.h"
#include "udevqt.h"

#define HELPER_ID "org.kde.powerdevil.backlighthelper"

PowerDevilUPowerBackend::PowerDevilUPowerBackend(QObject* parent)
    : BackendInterface(parent)
    , m_displayDevice(nullptr)
    , m_brightnessControl(nullptr)
    , m_randrHelper(nullptr)
    , m_upowerInterface(nullptr)
    , m_kbdBacklight(nullptr)
    , m_kbdMaxBrightness(0)
    , m_lidIsPresent(false)
    , m_lidIsClosed(false)
    , m_onBattery(false)
    , m_isLedBrightnessControl(false)
{

}

PowerDevilUPowerBackend::~PowerDevilUPowerBackend()
{
    delete m_brightnessControl;
}

bool PowerDevilUPowerBackend::isAvailable()
{
    if (!QDBusConnection::systemBus().interface()->isServiceRegistered(UPOWER_SERVICE)) {
        // Is it pending activation?
        qCDebug(POWERDEVIL) << "UPower service, " << UPOWER_SERVICE << ", is not registered on the bus. Trying to find out if it is activated.";
        QDBusMessage message = QDBusMessage::createMethodCall("org.freedesktop.DBus",
                                                              "/org/freedesktop/DBus",
                                                              "org.freedesktop.DBus",
                                                              "ListActivatableNames");

        QDBusPendingReply< QStringList > reply = QDBusConnection::systemBus().asyncCall(message);
        reply.waitForFinished();

        if (reply.isValid()) {
            if (reply.value().contains(UPOWER_SERVICE)) {
                qCDebug(POWERDEVIL) << "UPower was found, activating service...";
                QDBusConnection::systemBus().interface()->startService(UPOWER_SERVICE);
                if (!QDBusConnection::systemBus().interface()->isServiceRegistered(UPOWER_SERVICE)) {
                    // Wait for it
                    QEventLoop e;
                    QTimer *timer = new QTimer;
                    timer->setInterval(10000);
                    timer->setSingleShot(true);

                    connect(QDBusConnection::systemBus().interface(), SIGNAL(serviceRegistered(QString)),
                            &e, SLOT(quit()));
                    connect(timer, SIGNAL(timeout()), &e, SLOT(quit()));

                    timer->start();

                    while (!QDBusConnection::systemBus().interface()->isServiceRegistered(UPOWER_SERVICE)) {
                        e.exec();

                        if (!timer->isActive()) {
                            qCDebug(POWERDEVIL) << "Activation of UPower timed out. There is likely a problem with your configuration.";
                            timer->deleteLater();
                            return false;
                        }
                    }

                    timer->deleteLater();
                }
                return true;
            } else {
                qCDebug(POWERDEVIL) << "UPower cannot be found on this system.";
                return false;
            }
        } else {
            qCWarning(POWERDEVIL) << "Could not request activatable names to DBus!";
            return false;
        }
    } else {
        return true;
    }
}

void PowerDevilUPowerBackend::init()
{
    // interfaces
    if (!QDBusConnection::systemBus().interface()->isServiceRegistered(LOGIN1_SERVICE)) {
        // Activate it.
        QDBusConnection::systemBus().interface()->startService(LOGIN1_SERVICE);
    }

    if (!QDBusConnection::systemBus().interface()->isServiceRegistered(CONSOLEKIT2_SERVICE)) {
        // Activate it.
        QDBusConnection::systemBus().interface()->startService(CONSOLEKIT2_SERVICE);
    }

    if (!QDBusConnection::systemBus().interface()->isServiceRegistered(UPOWER_SERVICE)) {
        // Activate it.
        QDBusConnection::systemBus().interface()->startService(UPOWER_SERVICE);
    }

    if (QDBusConnection::systemBus().interface()->isServiceRegistered(LOGIN1_SERVICE)) {
        m_login1Interface = new QDBusInterface(LOGIN1_SERVICE, "/org/freedesktop/login1", "org.freedesktop.login1.Manager", QDBusConnection::systemBus(), this);
    }

    // if login1 isn't available, try using the same interface with ConsoleKit2
    if (!m_login1Interface && QDBusConnection::systemBus().interface()->isServiceRegistered(CONSOLEKIT2_SERVICE)) {
        m_login1Interface = new QDBusInterface(CONSOLEKIT2_SERVICE, "/org/freedesktop/ConsoleKit/Manager", "org.freedesktop.ConsoleKit.Manager", QDBusConnection::systemBus(), this);
    }

    connect(this, &PowerDevilUPowerBackend::brightnessSupportQueried, this, &PowerDevilUPowerBackend::initWithBrightness);
    m_upowerInterface = new OrgFreedesktopUPowerInterface(UPOWER_SERVICE, "/org/freedesktop/UPower", QDBusConnection::systemBus(), this);
    m_brightnessControl = new XRandrBrightness();
    if (!m_brightnessControl->isSupported()) {
        qCWarning(POWERDEVIL)<<"Xrandr not supported, trying ddc, helper";
        m_ddcBrightnessControl = new DDCutilBrightness();
        m_ddcBrightnessControl->detect();
        if (!m_ddcBrightnessControl->isSupported()) {
            qCDebug(POWERDEVIL) << "Falling back to helper to get brightness";

            KAuth::Action brightnessAction("org.kde.powerdevil.backlighthelper.brightness");
            brightnessAction.setHelperId(HELPER_ID);
            KAuth::ExecuteJob *brightnessJob = brightnessAction.execute();
            connect(brightnessJob, &KJob::result, this,
                [this, brightnessJob]  {
                    if (brightnessJob->error()) {
                        qCWarning(POWERDEVIL) << "org.kde.powerdevil.backlighthelper.brightness failed";
                        qCDebug(POWERDEVIL) << brightnessJob->errorText();
                        Q_EMIT brightnessSupportQueried(false);
                        return;
                    }
                    m_cachedBrightnessMap.insert(Screen, brightnessJob->data()["brightness"].toFloat());

                    KAuth::Action brightnessMaxAction("org.kde.powerdevil.backlighthelper.brightnessmax");
                    brightnessMaxAction.setHelperId(HELPER_ID);
                    KAuth::ExecuteJob *brightnessMaxJob = brightnessMaxAction.execute();
                    connect(brightnessMaxJob, &KJob::result, this,
                        [this, brightnessMaxJob] {
                            if (brightnessMaxJob->error()) {
                                qCWarning(POWERDEVIL) << "org.kde.powerdevil.backlighthelper.brightnessmax failed";
                                qCDebug(POWERDEVIL) << brightnessMaxJob->errorText();
                            } else {
                                m_brightnessMax = brightnessMaxJob->data()["brightnessmax"].toInt();
                            }

                            KAuth::Action syspathAction("org.kde.powerdevil.backlighthelper.syspath");
                            syspathAction.setHelperId(HELPER_ID);
                            KAuth::ExecuteJob* syspathJob = syspathAction.execute();
                            connect(syspathJob, &KJob::result, this,
                                [this, syspathJob] {
                                    if (syspathJob->error()) {
                                        qCWarning(POWERDEVIL) << "org.kde.powerdevil.backlighthelper.syspath failed";
                                        qCDebug(POWERDEVIL) << syspathJob->errorText();
                                        Q_EMIT brightnessSupportQueried(false);
                                        return;
                                    }
                                    m_syspath = syspathJob->data()["syspath"].toString();
                                    m_syspath = QFileInfo(m_syspath).symLinkTarget();

                                    m_isLedBrightnessControl = m_syspath.contains(QLatin1String("/leds/"));
                                    if (!m_isLedBrightnessControl) {
                                        UdevQt::Client *client =  new UdevQt::Client(QStringList("backlight"), this);
                                        connect(client, SIGNAL(deviceChanged(UdevQt::Device)), SLOT(onDeviceChanged(UdevQt::Device)));
                                    }

                                    Q_EMIT brightnessSupportQueried(m_brightnessMax > 0);
                                }
                            );
                            syspathJob->start();
                        }
                    );
                    brightnessMaxJob->start();
                }
            );
            brightnessJob->start();
        }
        else{
            qCDebug(POWERDEVIL) << "Using DDCutillib";
            m_cachedBrightnessMap.insert(Screen, brightness(Screen));

            const int duration = PowerDevilSettings::brightnessAnimationDuration();
            if (duration > 0 && brightnessMax() >= PowerDevilSettings::brightnessAnimationThreshold()) {
                m_brightnessAnimation = new QPropertyAnimation(this);
                m_brightnessAnimation->setTargetObject(this);
                m_brightnessAnimation->setDuration(duration);
                m_brightnessAnimation->setEasingCurve(QEasingCurve::OutQuad);
                connect(m_brightnessAnimation, &QPropertyAnimation::valueChanged, this, &PowerDevilUPowerBackend::animationValueChanged);
                connect(m_brightnessAnimation, &QPropertyAnimation::finished, this, &PowerDevilUPowerBackend::slotScreenBrightnessChanged);
            }
            Q_EMIT brightnessSupportQueried(true);
        }
    } else {
        qCDebug(POWERDEVIL) << "Using XRandR";
        m_randrHelper = XRandRXCBHelper::self();
        Q_ASSERT(m_randrHelper);
        connect(m_randrHelper, &XRandRXCBHelper::brightnessChanged, this, &PowerDevilUPowerBackend::slotScreenBrightnessChanged);
        m_cachedBrightnessMap.insert(Screen, brightness(Screen));

        const int duration = PowerDevilSettings::brightnessAnimationDuration();
        if (duration > 0 && brightnessMax() >= PowerDevilSettings::brightnessAnimationThreshold()) {
            m_brightnessAnimation = new QPropertyAnimation(this);
            m_brightnessAnimation->setTargetObject(this);
            m_brightnessAnimation->setDuration(duration);
            m_brightnessAnimation->setEasingCurve(QEasingCurve::InOutQuad);
            connect(m_brightnessAnimation, &QPropertyAnimation::valueChanged, this, &PowerDevilUPowerBackend::animationValueChanged);
            connect(m_brightnessAnimation, &QPropertyAnimation::finished, this, &PowerDevilUPowerBackend::slotScreenBrightnessChanged);
        }
        Q_EMIT brightnessSupportQueried(true);
    }
}

void PowerDevilUPowerBackend::initWithBrightness(bool screenBrightnessAvailable)
{
    disconnect(this, &PowerDevilUPowerBackend::brightnessSupportQueried, this, &PowerDevilUPowerBackend::initWithBrightness);
    // Capabilities
    setCapabilities(SignalResumeFromSuspend);

    // devices
    enumerateDevices();

    connect(m_upowerInterface, SIGNAL(Changed()), this, SLOT(slotPropertyChanged()));
    // for UPower >= 0.99.0, missing Changed() signal
    QDBusConnection::systemBus().connect(UPOWER_SERVICE, UPOWER_PATH, "org.freedesktop.DBus.Properties", "PropertiesChanged", this,
                                         SLOT(onPropertiesChanged(QString,QVariantMap,QStringList)));

    connect(m_upowerInterface, SIGNAL(DeviceAdded(QString)), this, SLOT(slotDeviceAdded(QString)));
    connect(m_upowerInterface, SIGNAL(DeviceRemoved(QString)), this, SLOT(slotDeviceRemoved(QString)));
    // for UPower >= 0.99.0, changed signature :o/
    QDBusConnection::systemBus().connect(UPOWER_SERVICE, UPOWER_PATH, UPOWER_IFACE, "DeviceAdded",
                                         this, SLOT(slotDeviceAdded(QDBusObjectPath)));
    QDBusConnection::systemBus().connect(UPOWER_SERVICE, UPOWER_PATH, UPOWER_IFACE, "DeviceRemoved",
                                         this, SLOT(slotDeviceRemoved(QDBusObjectPath)));

    connect(m_upowerInterface, SIGNAL(DeviceChanged(QString)), this, SLOT(slotDeviceChanged(QString)));
    // for UPower >= 0.99.0, see slotDeviceAdded(const QString & device)

    // Brightness Controls available
    BrightnessControlsList controls;
    if (screenBrightnessAvailable) {
        controls.insert(QLatin1String("LVDS1"), Screen);
        qCDebug(POWERDEVIL) << "current screen brightness value: " << m_cachedBrightnessMap.value(Screen);
    }

    m_kbdBacklight = new OrgFreedesktopUPowerKbdBacklightInterface(UPOWER_SERVICE, "/org/freedesktop/UPower/KbdBacklight", QDBusConnection::systemBus(), this);
    if (m_kbdBacklight->isValid()) {
        // Cache max value
        QDBusPendingReply<int> rep = m_kbdBacklight->GetMaxBrightness();
        rep.waitForFinished();
        if (rep.isValid()) {
            m_kbdMaxBrightness = rep.value();
        }
        // TODO Do a proper check if the kbd backlight dbus object exists. But that should work for now ..
        if (m_kbdMaxBrightness) {
            controls.insert(QLatin1String("KBD"), Keyboard);
            m_cachedBrightnessMap.insert(Keyboard, brightness(Keyboard));
            qCDebug(POWERDEVIL) << "current keyboard backlight brightness value: " << m_cachedBrightnessMap.value(Keyboard);
            connect(m_kbdBacklight, SIGNAL(BrightnessChanged(int)), this, SLOT(onKeyboardBrightnessChanged(int)));
        }
    }

    // Supported suspend methods
    SuspendMethods supported = UnknownSuspendMethod;
    if (m_login1Interface) {
        QDBusPendingReply<QString> canSuspend = m_login1Interface.data()->asyncCall("CanSuspend");
        canSuspend.waitForFinished();
        if (canSuspend.isValid() && (canSuspend.value() == QLatin1String("yes") || canSuspend.value() == QLatin1String("challenge")))
            supported |= ToRam;

        QDBusPendingReply<QString> canHibernate = m_login1Interface.data()->asyncCall("CanHibernate");
        canHibernate.waitForFinished();
        if (canHibernate.isValid() && (canHibernate.value() == QLatin1String("yes") || canHibernate.value() == QLatin1String("challenge")))
            supported |= ToDisk;

        QDBusPendingReply<QString> canHybridSleep = m_login1Interface.data()->asyncCall("CanHybridSleep");
        canHybridSleep.waitForFinished();
        if (canHybridSleep.isValid() && (canHybridSleep.value() == QLatin1String("yes") || canHybridSleep.value() == QLatin1String("challenge")))
            supported |= HybridSuspend;

        QDBusPendingReply<QString> canSuspendThenHibernate = m_login1Interface.data()->asyncCall("CanSuspendThenHibernate");
        canSuspendThenHibernate.waitForFinished();
        if (canSuspendThenHibernate.isValid() && (canSuspendThenHibernate.value() == QLatin1String("yes") || canSuspendThenHibernate.value() == QLatin1String("challenge")))
            supported |= SuspendThenHibernate;
    }

    /* There's a chance we're using ConsoleKit rather than ConsoleKit2 as the
     * m_login1Interface, so check if we can suspend/hibernate with UPower < 0.99 */
    if (supported == UnknownSuspendMethod) {
        if (m_upowerInterface->canSuspend() && m_upowerInterface->SuspendAllowed()) {
            qCDebug(POWERDEVIL) << "Can suspend";
            supported |= ToRam;
        }

        if (m_upowerInterface->canHibernate() && m_upowerInterface->HibernateAllowed()) {
            qCDebug(POWERDEVIL) << "Can hibernate";
            supported |= ToDisk;
        }

        if (supported != UnknownSuspendMethod) {
            m_useUPowerSuspend = true;
        }
    }

    // "resuming" signal
    if (m_login1Interface && !m_useUPowerSuspend) {
        connect(m_login1Interface.data(), SIGNAL(PrepareForSleep(bool)), this, SLOT(slotLogin1PrepareForSleep(bool)));
    } else {
        connect(m_upowerInterface, &OrgFreedesktopUPowerInterface::Sleeping, this, &PowerDevilUPowerBackend::aboutToSuspend);
        connect(m_upowerInterface, &OrgFreedesktopUPowerInterface::Resuming, this, &PowerDevilUPowerBackend::resumeFromSuspend);
    }

    // battery
    for (const OrgFreedesktopUPowerDeviceInterface * upowerDevice : qAsConst(m_devices)) {
        if (upowerDevice->type() == 2 && upowerDevice->powerSupply()) {
            QString udi = upowerDevice->path();
            setCapacityForBattery(udi, qRound(upowerDevice->capacity()));  // acknowledge capacity
        }
    }

    // backend ready
    setBackendIsReady(controls, supported);
}

void PowerDevilUPowerBackend::onDeviceChanged(const UdevQt::Device &device)
{
    // If we're currently in the process of changing brightness, ignore any such events
    if (m_brightnessAnimationTimer && m_brightnessAnimationTimer->isActive()) {
        return;
    }

    qCDebug(POWERDEVIL) << "Udev device changed" << m_syspath << device.sysfsPath();
    if (device.sysfsPath() != m_syspath) {
        return;
    }

    int maxBrightness = device.sysfsProperty("max_brightness").toInt();
    if (maxBrightness <= 0) {
        return;
    }
    int newBrightness = device.sysfsProperty("brightness").toInt();

    if (newBrightness != m_cachedBrightnessMap[Screen]) {
        m_cachedBrightnessMap[Screen] = newBrightness;
        onBrightnessChanged(Screen, newBrightness, maxBrightness);
    }
}

int PowerDevilUPowerBackend::brightnessKeyPressed(PowerDevil::BrightnessLogic::BrightnessKeyType type, BrightnessControlType controlType)
{
    BrightnessControlsList allControls = brightnessControlsAvailable();
    QList<QString> controls = allControls.keys(controlType);

    if (controls.isEmpty()) {
        return -1; // ignore as we are not able to determine the brightness level
    }

    int currentBrightness = brightness(controlType);
    // m_cachedBrightnessMap is not being updated during animation, thus checking the m_cachedBrightnessMap
    // value here doesn't make much sense, use the endValue from brightness() anyway.
    // This prevents brightness key being ignored during the animation.
    if (!(controlType == Screen &&
          m_brightnessAnimation &&
          m_brightnessAnimation->state() == QPropertyAnimation::Running) &&
        currentBrightness != m_cachedBrightnessMap.value(controlType)) {
        m_cachedBrightnessMap[controlType] = currentBrightness;
        return currentBrightness;
    }

    int maxBrightness = brightnessMax(controlType);
    int newBrightness = calculateNextStep(currentBrightness, maxBrightness, controlType, type);

    if (newBrightness < 0) {
        return -1;
    }

    setBrightness(newBrightness, controlType);
    return newBrightness;
}

int PowerDevilUPowerBackend::brightness(PowerDevil::BackendInterface::BrightnessControlType type) const
{
    int result = 0;

    if (type == Screen) {
        if (m_brightnessControl->isSupported()) {
            if (m_brightnessAnimation && m_brightnessAnimation->state() == QPropertyAnimation::Running) {
                result = m_brightnessAnimation->endValue().toInt();
            } else {
                //qCDebug(POWERDEVIL) << "Calling xrandr brightness";
                result = (int) m_brightnessControl->brightness();
            }
        } else if (m_ddcBrightnessControl->isSupported()){
            if (m_brightnessAnimation && m_brightnessAnimation->state() == QPropertyAnimation::Running) {
                result = m_brightnessAnimation->endValue().toInt();
            } else {
                result = (int)m_ddcBrightnessControl->brightness();
            }
        }else{
            result = m_cachedBrightnessMap[Screen];
        }
        qCDebug(POWERDEVIL) << "Screen brightness value: " << result;
    } else if (type == Keyboard) {
        result = m_kbdBacklight->GetBrightness();
        qCDebug(POWERDEVIL) << "Kbd backlight brightness value: " << result;
    }

    return result;
}

int PowerDevilUPowerBackend::brightnessMax(PowerDevil::BackendInterface::BrightnessControlType type) const
{
    int result = 0;

    if (type == Screen) {
        if (m_brightnessControl->isSupported()) {
            //qCDebug(POWERDEVIL) << "Calling xrandr brightness";
            result = (int) m_brightnessControl->brightnessMax();
        } else if (m_ddcBrightnessControl->isSupported()){
            result = (int)m_ddcBrightnessControl->brightnessMax();
        }else{
            result = m_brightnessMax;
        }
        qCDebug(POWERDEVIL) << "Screen brightness value max: " << result;
    } else if (type == Keyboard) {
        result = m_kbdMaxBrightness;
        qCDebug(POWERDEVIL) << "Kbd backlight brightness value max: " << result;
    }

    return result;
}

void PowerDevilUPowerBackend::setBrightness(int value, PowerDevil::BackendInterface::BrightnessControlType type)
{
    if (type == Screen) {
        qCDebug(POWERDEVIL) << "set screen brightness value: " << value;
        if (m_brightnessControl->isSupported()) {
            if (m_brightnessAnimation) {
                m_brightnessAnimation->stop();
                disconnect(m_brightnessAnimation, &QPropertyAnimation::valueChanged, this, &PowerDevilUPowerBackend::animationValueChanged);
                m_brightnessAnimation->setStartValue(brightness());
                m_brightnessAnimation->setEndValue(value);
                connect(m_brightnessAnimation, &QPropertyAnimation::valueChanged, this, &PowerDevilUPowerBackend::animationValueChanged);
                m_brightnessAnimation->start();
            } else {
                m_brightnessControl->setBrightness(value);
            }
        } else if (m_ddcBrightnessControl->isSupported()){
            if (m_brightnessAnimation) {
                m_brightnessAnimation->stop();
                disconnect(m_brightnessAnimation, &QPropertyAnimation::valueChanged, this, &PowerDevilUPowerBackend::animationValueChanged);
                m_brightnessAnimation->setStartValue(brightness());
                m_brightnessAnimation->setEndValue(value);
                connect(m_brightnessAnimation, &QPropertyAnimation::valueChanged, this, &PowerDevilUPowerBackend::animationValueChanged);
                m_brightnessAnimation->start();
            } else {
                m_ddcBrightnessControl->setBrightness((long)value);
            }
        } else {
            //qCDebug(POWERDEVIL) << "Falling back to helper to set brightness";

            KAuth::Action action("org.kde.powerdevil.backlighthelper.setbrightness");
            action.setHelperId(HELPER_ID);
            action.addArgument("brightness", value);
            if (brightnessMax() >= PowerDevilSettings::brightnessAnimationThreshold()) {
                action.addArgument("animationDuration", PowerDevilSettings::brightnessAnimationDuration());
            }
            auto *job = action.execute();
            connect(job, &KAuth::ExecuteJob::result, this, [this, job, value] {
                if (job->error()) {
                    qCWarning(POWERDEVIL) << "Failed to set screen brightness" << job->errorText();
                    return;
                }

                // Immediately announce the new brightness to everyone while we still animate to it
                m_cachedBrightnessMap[Screen] = value;
                onBrightnessChanged(Screen, value, brightnessMax(Screen));

                // So we ignore any brightness changes during the animation
                if (!m_brightnessAnimationTimer) {
                    m_brightnessAnimationTimer = new QTimer(this);
                    m_brightnessAnimationTimer->setSingleShot(true);
                }
                m_brightnessAnimationTimer->start(PowerDevilSettings::brightnessAnimationDuration());
            });
            job->start();
        }
    } else if (type == Keyboard) {
        qCDebug(POWERDEVIL) << "set kbd backlight value: " << value;
        m_kbdBacklight->SetBrightness(value);
    }
}

void PowerDevilUPowerBackend::slotScreenBrightnessChanged()
{
    if (m_brightnessAnimation && m_brightnessAnimation->state() != QPropertyAnimation::Stopped) {
        return;
    }

    if (m_brightnessAnimationTimer && m_brightnessAnimationTimer->isActive()) {
        return;
    }

    int value = brightness(Screen);
    if (value != m_cachedBrightnessMap[Screen] || m_isLedBrightnessControl) {
        m_cachedBrightnessMap[Screen] = value;
        onBrightnessChanged(Screen, value, brightnessMax(Screen));
    }
}

void PowerDevilUPowerBackend::onKeyboardBrightnessChanged(int value)
{
    qCDebug(POWERDEVIL) << "Keyboard brightness changed!!";
    if (value != m_cachedBrightnessMap[Keyboard]) {
        m_cachedBrightnessMap[Keyboard] = value;
        onBrightnessChanged(Keyboard, value, brightnessMax(Keyboard));
    }
}

KJob* PowerDevilUPowerBackend::suspend(PowerDevil::BackendInterface::SuspendMethod method)
{
    if (m_login1Interface && !m_useUPowerSuspend) {
        return new Login1SuspendJob(m_login1Interface.data(), method, supportedSuspendMethods());
    } else {
        return new UPowerSuspendJob(m_upowerInterface, method, supportedSuspendMethods());
    }
}

void PowerDevilUPowerBackend::enumerateDevices()
{
    m_lidIsPresent = m_upowerInterface->lidIsPresent();
    setLidPresent(m_lidIsPresent);
    m_lidIsClosed = m_upowerInterface->lidIsClosed();
    m_onBattery = m_upowerInterface->onBattery();

    const QList<QDBusObjectPath> deviceList = m_upowerInterface->EnumerateDevices();
    for (const QDBusObjectPath & device : deviceList) {
        addDevice(device.path());
    }

    QDBusReply<QDBusObjectPath> reply = m_upowerInterface->call("GetDisplayDevice");
    if (reply.isValid()) {
        const QString path = reply.value().path();
        if (!path.isEmpty() && path != QStringLiteral("/")) {
            m_displayDevice = new OrgFreedesktopUPowerDeviceInterface(UPOWER_SERVICE, path, QDBusConnection::systemBus(), this);
        }
    }

    updateDeviceProps();

    if (m_onBattery)
        setAcAdapterState(Unplugged);
    else
        setAcAdapterState(Plugged);
}

void PowerDevilUPowerBackend::addDevice(const QString & device)
{
    OrgFreedesktopUPowerDeviceInterface * upowerDevice =
            new OrgFreedesktopUPowerDeviceInterface(UPOWER_SERVICE, device, QDBusConnection::systemBus(), this);
    m_devices.insert(device, upowerDevice);

    // for UPower >= 0.99.0 which doesn't emit the DeviceChanged(QString) signal
    QDBusConnection::systemBus().connect(UPOWER_SERVICE, device, "org.freedesktop.DBus.Properties", "PropertiesChanged", this,
                                         SLOT(onDevicePropertiesChanged(QString,QVariantMap,QStringList)));
}

void PowerDevilUPowerBackend::slotDeviceAdded(const QString & device)
{
    addDevice(device);
    updateDeviceProps();
}

void PowerDevilUPowerBackend::slotDeviceRemoved(const QString & device)
{
    OrgFreedesktopUPowerDeviceInterface * upowerDevice = m_devices.take(device);

    delete upowerDevice;

    updateDeviceProps();
}

void PowerDevilUPowerBackend::slotDeviceAdded(const QDBusObjectPath &path)
{
    slotDeviceAdded(path.path());
}

void PowerDevilUPowerBackend::slotDeviceRemoved(const QDBusObjectPath &path)
{
    slotDeviceRemoved(path.path());
}

void PowerDevilUPowerBackend::slotDeviceChanged(const QString & /*device*/)
{
    updateDeviceProps();
}

void PowerDevilUPowerBackend::updateDeviceProps()
{
    qlonglong remainingTime = 0;

    if (m_displayDevice && m_displayDevice->isPresent()) {
        const uint state = m_displayDevice->state();
        if (state == 1) // charging
            remainingTime = m_displayDevice->timeToFull();
        else if (state == 2) //discharging
            remainingTime = m_displayDevice->timeToEmpty();
    } else {
        qreal energyTotal = 0.0;
        qreal energyRateTotal = 0.0;
        qreal energyFullTotal = 0.0;
        uint stateTotal = 0;

        for (const OrgFreedesktopUPowerDeviceInterface * upowerDevice : qAsConst(m_devices)) {
            const uint type = upowerDevice->type();
            if (( type == 2 || type == 3) && upowerDevice->powerSupply()) {
                const uint state = upowerDevice->state();
                energyFullTotal += upowerDevice->energyFull();
                energyTotal += upowerDevice->energy();
                energyRateTotal += upowerDevice->energyRate();

                if (state == 1) { // total is charging
                    stateTotal = 1;
                } else if (state == 2 && stateTotal != 1) { // total is discharging
                    stateTotal = 2;
                } else if (state == 4 && stateTotal != 0) { // total is fully-charged
                    stateTotal = 4;
                }

                if (state == 1) { // charging
                    remainingTime += upowerDevice->timeToFull();
                } else if (state == 2) { // discharging
                    remainingTime += upowerDevice->timeToEmpty();
                }
            }
        }

        if (energyRateTotal > 0) {
            if (stateTotal == 1) { // charging
                remainingTime = 3600 * ((energyFullTotal - energyTotal) / energyRateTotal);
            } else if (stateTotal == 2) { // discharging
                remainingTime = 3600 * (energyTotal / energyRateTotal);
            }
        }
    }

    setBatteryRemainingTime(remainingTime * 1000);
}

void PowerDevilUPowerBackend::slotPropertyChanged()
{
    // check for lid button changes
    if (m_lidIsPresent) {
        const bool lidIsClosed = m_upowerInterface->lidIsClosed();
        if (lidIsClosed != m_lidIsClosed) {
            if (lidIsClosed)
                setButtonPressed(LidClose);
            else
                setButtonPressed(LidOpen);
        }
        m_lidIsClosed = lidIsClosed;
    }

    // check for AC adapter changes
    const bool onBattery = m_upowerInterface->onBattery();
    if (m_onBattery != onBattery) {
        if (onBattery)
            setAcAdapterState(Unplugged);
        else
            setAcAdapterState(Plugged);
    }

    m_onBattery = onBattery;
}

void PowerDevilUPowerBackend::onPropertiesChanged(const QString &ifaceName, const QVariantMap &changedProps, const QStringList &invalidatedProps)
{
    Q_UNUSED(changedProps);
    Q_UNUSED(invalidatedProps);

    if (ifaceName == UPOWER_IFACE) {
        slotPropertyChanged(); // TODO maybe process the 2 properties separately?
    }
}

void PowerDevilUPowerBackend::onDevicePropertiesChanged(const QString &ifaceName, const QVariantMap &changedProps, const QStringList &invalidatedProps)
{
    Q_UNUSED(changedProps);
    Q_UNUSED(invalidatedProps);

    if (ifaceName == UPOWER_IFACE_DEVICE) {
        updateDeviceProps(); // TODO maybe process the properties separately?
    }
}

void PowerDevilUPowerBackend::slotLogin1PrepareForSleep(bool active)
{
    if (active) {
        Q_EMIT aboutToSuspend();
    } else {
        Q_EMIT resumeFromSuspend();
    }
}

void PowerDevilUPowerBackend::animationValueChanged(const QVariant &value)
{
    if (m_brightnessControl->isSupported()) {
        m_brightnessControl->setBrightness(value.toInt());
    }else if (m_ddcBrightnessControl->isSupported()) {
        m_ddcBrightnessControl->setBrightness(value.toInt());
    }
    else{
        qCInfo(POWERDEVIL)<<"PowerDevilUPowerBackend::animationValueChanged: brightness control not supported";
    }
}