File indexing completed on 2024-05-19 09:29:22
0001 // SPDX-FileCopyrightText: 2022-2023 Devin Lin <devin@kde.org> 0002 // SPDX-License-Identifier: GPL-2.0-or-later 0003 0004 #include "screenrotationutil.h" 0005 0006 #include <fcntl.h> 0007 #include <unistd.h> 0008 0009 #include <kscreen/configmonitor.h> 0010 #include <kscreen/getconfigoperation.h> 0011 #include <kscreen/output.h> 0012 #include <kscreen/setconfigoperation.h> 0013 0014 #include <QDebug> 0015 #include <QOrientationSensor> 0016 0017 ScreenRotationUtil::ScreenRotationUtil(QObject *parent) 0018 : QObject{parent} 0019 , m_config{nullptr} 0020 , m_sensor{new QOrientationSensor(this)} 0021 { 0022 connect(m_sensor, &QOrientationSensor::activeChanged, this, &ScreenRotationUtil::availableChanged); 0023 0024 connect(new KScreen::GetConfigOperation(), &KScreen::GetConfigOperation::finished, this, [this](auto *op) { 0025 m_config = qobject_cast<KScreen::GetConfigOperation *>(op)->config(); 0026 0027 // update all screens with event connect 0028 for (KScreen::OutputPtr output : m_config->outputs()) { 0029 connect(output.data(), &KScreen::Output::autoRotatePolicyChanged, this, &ScreenRotationUtil::autoScreenRotationEnabledChanged); 0030 } 0031 0032 // listen to all new screens and connect 0033 connect(m_config.data(), &KScreen::Config::outputAdded, this, [this](const auto &output) { 0034 Q_EMIT autoScreenRotationEnabledChanged(); 0035 connect(output.data(), &KScreen::Output::autoRotatePolicyChanged, this, &ScreenRotationUtil::autoScreenRotationEnabledChanged); 0036 }); 0037 0038 // trigger update 0039 Q_EMIT autoScreenRotationEnabledChanged(); 0040 }); 0041 } 0042 0043 bool ScreenRotationUtil::autoScreenRotationEnabled() 0044 { 0045 if (!m_config) { 0046 return false; 0047 } 0048 const auto outputs = m_config->outputs(); 0049 0050 for (KScreen::OutputPtr output : outputs) { 0051 if (output->autoRotatePolicy() == KScreen::Output::AutoRotatePolicy::Never) { 0052 return false; 0053 } 0054 } 0055 0056 return true; 0057 } 0058 0059 void ScreenRotationUtil::setAutoScreenRotationEnabled(bool value) 0060 { 0061 if (!m_config) { 0062 return; 0063 } 0064 0065 KScreen::Output::AutoRotatePolicy policy = value ? KScreen::Output::AutoRotatePolicy::Always : KScreen::Output::AutoRotatePolicy::Never; 0066 0067 const auto outputs = m_config->outputs(); 0068 for (KScreen::OutputPtr output : outputs) { 0069 if (output->autoRotatePolicy() != policy) { 0070 output->setAutoRotatePolicy(policy); 0071 } 0072 } 0073 0074 auto setop = new KScreen::SetConfigOperation(m_config, this); 0075 setop->exec(); 0076 0077 Q_EMIT autoScreenRotationEnabledChanged(); 0078 } 0079 0080 bool ScreenRotationUtil::isAvailable() 0081 { 0082 return m_sensor->connectToBackend(); 0083 }