ukui-power-manager-4.0.0.1/0000755000175000017500000000000014601232446014013 5ustar fengfengukui-power-manager-4.0.0.1/doc/0000775000175000017500000000000014601232446014562 5ustar fengfengukui-power-manager-4.0.0.1/doc/schedules.md0000664000175000017500000000404014601232446017061 0ustar fengfeng## 计划表 ``` 计划8月份基本完成电源管理的改版工作 保证9月30号之前新版电源管理能够上线使用使用 具体时间节点: 电源显示界面: 0813 :ui改版,去除ui文件【处理中,由于新插入其他工作,预计延期】 0820 :新增消息通知类,用以处理极低电量,低电量等消息通知 0827 :托盘图标显示界面分离 0903 :快捷键亮度调节界面重写 电源管理事件调度后台: 0805 :电源管理基础 调研文档(第一阶段)基本结束(包括upower,亮度调节,cpu调频等)[基本完成] 0806 :亮度调节,cpu调频,关闭显示器的dbus服务接口完成 【亮度调节接口未完成,其他基本完成,demo未补充,预计0810之前完成】 0813 :电源管理事件调度中心核心代码编写完毕;gpu调频接口处理【已经开始着手处理,处理的时候务必保证功能稳定性】 0820 :电源管理基础 调研文档(第二阶段)结束。 电源管理后台( 事件分发,事件调度,策略修改) 代码联调 整机测试,分别在华为990笔记本,华为990台式机,华为9a0笔记本, 飞腾,鲲鹏,清华同方,龙芯4000,龙芯5000,联想机器联调功能。 (国产机器驱动书写未必符合规范,所以一定要) 0827 :新版电源管理后台满足全部设计稿中的功能 0903 :代码优化,编包等,使新版电源管理达到可上线的状态 0910 :电源管理评审,完善设计文档,需求文档 0917 :准备上线,全量测试 ``` ``` 0807备注: 为保证功能稳定性,计划采用逐步替换旧版功能的方式进行修改 预计上线的流程为: -> ui替换 -> 空闲-关闭显示器功能后台采用新版 【时间节点0813】 -> 空闲-all 采用新版 (包括cpu调频,暂不包括gpu调频)【时间节点0820】 -> 合盖处理 采用新版 ;监听电源键 采用新版【时间节点 0827】 -> 完全替换【0903】 -> gpu调频 低电量处理 【0910】 ``` ukui-power-manager-4.0.0.1/doc/电源管理需求文档.md0000664000175000017500000000351514601232446025525 0ustar fengfeng# 电源管理需求文档 ### 目录 ``` 1.托盘图标 2.任务栏上弹出窗口 3.亮度调节界面 4.消息通知 5.后台服务 6.upower封装 7.upower代码改动 8.低电量处理 9.文档输出 ``` ## 托盘图标 ``` 功能点罗列: 1.支持显示正确的图标 2.区分台式机与笔记本(台式机上不显示图标) 3.支持悬浮显示tooltip 4.支持右键弹出窗口 5.支持选择显示剩余充电时间 需求分析: 1.通过upower接口获取图标名称 2.通过upower获取电量 3.通过upower获取电量改变的信号 4.通过upower封装的接口获取剩余多久充满电(需要用upower封装的接口原因是原生接口数值波动过大) ``` ## 任务栏上弹出窗口 ``` 功能点罗列: 1.支持显示在正确的位置(包括多屏,并且需要监听屏幕改变) 2.支持透明度与毛玻璃效果 3.支持圆角阴影 4.支持跟随主题 5.支持跟随文字大小变化 6.界面内的图标与托盘图标保持一致 7.界面内的文字保持与托盘tooltip一致 ``` ## 亮度调节界面 ``` 功能点罗列: 1.支持透明度与毛玻璃效果 2.支持圆角阴影 3.支持跟随主题 4.支持图标高亮协议 5.支持双屏显示 6.绑定快捷键显示 7.禁止显示10%以下亮度 ``` ## 消息通知 ``` 功能点罗列 1.接收upower的信号和电量,进行消息通知 ``` ## 低电量处理 ``` 功能点罗列: 1.电池低电量之后自动进入省电模式 2.使用电池时自动进入节能模式 3.低电量通知 4.极低电量关机等功能 ``` ## 后台服务 ``` 功能点罗列: 一. 合盖处理 二. 关机键处理 三. 空闲处理 合盖处理 1. 选择合盖子之后的操作,调用相关接口即可 关机键处理 1. 选择关机键按下之后的操作即可 空闲处理 1.关闭显示器 2.睡眠/休眠 3.降低屏幕亮度 ```ukui-power-manager-4.0.0.1/doc/性能测试注意事项.md0000664000175000017500000000112614601232446025640 0ustar fengfeng# 性能测试注意事项 ``` 1.连接电源【使用电池的情况下电源管理会更改调频策略】 2.控制面板设置电源计划为性能模式 如果控制面板-系统-电源-使用电源时的模式选择没有性能模式则需要手动设置【v10sp1 0820-1 版本暂时没有性能模式选项】 gsettings set org.ukui.power-manager power-policy-ac 0 3.控制面板-系统-电源-此时间段后关闭显示器 选为从不 4.控制面板-系统-电源-此时间段后进入睡眠 选为从不 5.控制面板-个性化-屏保-此时间段后开启屏保 选为从不 ``` ukui-power-manager-4.0.0.1/doc/设计文档.md0000664000175000017500000000003314601232446021447 0ustar fengfeng# 电源管理设计文档 ukui-power-manager-4.0.0.1/PowerManagementDaemon/0000775000175000017500000000000014601232446020232 5ustar fengfengukui-power-manager-4.0.0.1/PowerManagementDaemon/upm-upower-dbus/0000775000175000017500000000000014601232446023305 5ustar fengfengukui-power-manager-4.0.0.1/PowerManagementDaemon/upm-upower-dbus/upowerbatterydbus.cpp0000664000175000017500000001235514601232446027611 0ustar fengfeng/* * Copyright 2023 KylinSoft Co., Ltd. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ #include #include "upowerbatterydbus.h" UpowerBatteryDBus::UpowerBatteryDBus(int batteryId, const QString &batteryDBusPath, QObject *parent) : QObject(parent), m_batteryId(batteryId) { m_DBusInterface = new QDBusInterface("org.freedesktop.UPower", batteryDBusPath, "org.freedesktop.DBus.Properties", QDBusConnection::systemBus(), this); QDBusConnection::systemBus().connect("org.freedesktop.UPower", batteryDBusPath, "org.freedesktop.DBus.Properties", "PropertiesChanged", this, SLOT(dealBatteryPropertiesMessage(QDBusMessage))); initBatteryInfo(); } UpowerBatteryDBus::~UpowerBatteryDBus() {} void UpowerBatteryDBus::dealBatteryPropertiesMessage(QDBusMessage msg) { const QDBusArgument &dbusArgs = msg.arguments().at(1).value(); QMap map; dbusArgs >> map; QStringList batteryInfoChangedList; if (map.contains("State")) { m_batteryState = map.value(QString("State")).toInt(); batteryInfoChangedList.append("State"); } if (map.contains("Percentage")) { m_percentage = map.value(QString("Percentage")).toDouble(); batteryInfoChangedList.append("Percentage"); } if (map.contains("Energy")) { m_energy = map.value(QString("Energy")).toDouble(); batteryInfoChangedList.append("Energy"); } if (map.contains("EnergyRate")) { m_energyRate = map.value(QString("EnergyRate")).toDouble(); batteryInfoChangedList.append("EnergyRate"); } if (map.contains("TimeToFull")) { m_timeToFull = map.value(QString("TimeToFull")).toLongLong(); batteryInfoChangedList.append("TimeToFull"); } if (map.contains("TimeToEmpty")) { m_timeToEmpty = map.value(QString("TimeToEmpty")).toLongLong(); batteryInfoChangedList.append("TimeToEmpty"); } if (map.contains("Temperature")) { m_temperature = map.value(QString("Temperature")).toDouble(); batteryInfoChangedList.append("Temperature"); } if (map.contains("WarningLevel")) { m_warninglevel = map.value(QString("WarningLevel")).toInt(); batteryInfoChangedList.append("WarningLevel"); } emit batteryInfoChanged(m_batteryId, batteryInfoChangedList); } void UpowerBatteryDBus::initBatteryInfo() { QDBusMessage msg = m_DBusInterface->call("GetAll", "org.freedesktop.UPower.Device"); if (msg.type() == QDBusMessage::ReplyMessage) { const QDBusArgument &dbusArgs = msg.arguments().at(0).value(); QMap map; dbusArgs >> map; m_batteryState = map.value(QString("State")).toInt(); m_percentage = map.value(QString("Percentage")).toDouble(); m_energy = map.value(QString("Energy")).toDouble(); m_energyFull = map.value(QString("EnergyFull")).toDouble(); m_energyFullDesign = map.value(QString("EnergyFullDesign")).toDouble(); m_energyRate = map.value(QString("EnergyRate")).toDouble(); m_timeToFull = map.value(QString("TimeToFull")).toLongLong(); m_timeToEmpty = map.value(QString("TimeToEmpty")).toLongLong(); m_temperature = map.value(QString("Temperature")).toDouble(); m_warninglevel = map.value(QString("WarningLevel")).toInt(); m_vendor = map.value(QString("Vendor")).toString(); m_model = map.value(QString("Model")).toString(); } } int UpowerBatteryDBus::getBatteryState() { return m_batteryState; } double UpowerBatteryDBus::getBatteryPercentage() { return m_percentage; } double UpowerBatteryDBus::getEnergyNow() { return m_energy; } double UpowerBatteryDBus::getEnergyFull() { return m_energyFull; } double UpowerBatteryDBus::getEnergyFullDesign() { return m_energyFullDesign; } double UpowerBatteryDBus::getEnergyRate() { return m_energyRate; } qlonglong UpowerBatteryDBus::getTimeToFull() { return m_timeToFull; } qlonglong UpowerBatteryDBus::getTimeToEmpty() { return m_timeToEmpty; } double UpowerBatteryDBus::getBatteryTemperature() { return m_temperature; } int UpowerBatteryDBus::getWarninglevel() { return m_warninglevel; } QString UpowerBatteryDBus::getBatteryVendor() { return m_vendor; } QString UpowerBatteryDBus::getBatteryModel() { return m_model; } ukui-power-manager-4.0.0.1/PowerManagementDaemon/upm-upower-dbus/upowerdbus.h0000664000175000017500000000404614601232446025661 0ustar fengfeng/* * Copyright 2023 KylinSoft Co., Ltd. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ #ifndef UPOWERDBUS_H #define UPOWERDBUS_H #include #include #include enum up_device_type { up_device_type_unknown = 0, up_device_type_line_power, up_device_type_battery, up_device_type_ups, up_device_type_monitor, up_device_type_mouse, up_device_type_keyboard, up_device_type_pda, up_device_type_phone, up_device_type_media_player, up_device_type_tablet, up_device_type_computer, up_device_type_max }; class UPowerDBus : public QObject { Q_OBJECT public: explicit UPowerDBus(QObject *parent = nullptr); ~UPowerDBus(); private: int getDeviceType(const QString &); void initDeviceInfo(); void dealLidClosedMessage(bool); void dealBatteryOnlineMessage(bool); QDBusInterface *m_DBusInterface; bool m_lidIsPresent; bool m_lidIsClosed; bool m_batteryOnline; QString m_upowerDaemonVersion; QStringList m_batteryPathList; QStringList m_linePowerPathList; private slots: void dealUPowerDBusMessage(QDBusMessage); signals: void lidStateChanged(bool); void batteryOnlineStateChanged(bool); public: bool hasLid(); bool getLidClosedState(); bool getBatteryOnlineState(); QString getUpowerDaemonVersion(); QStringList getBatteryPathList(); QStringList getLinePowerPathList(); }; #endif // UPOWERDBUS_H ukui-power-manager-4.0.0.1/PowerManagementDaemon/upm-upower-dbus/upowerbatterydbus.h0000664000175000017500000000364714601232446027262 0ustar fengfeng/* * Copyright 2023 KylinSoft Co., Ltd. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ #ifndef UPOWERBATTERYDBUS_H #define UPOWERBATTERYDBUS_H #include #include #include class UpowerBatteryDBus : public QObject { Q_OBJECT public: explicit UpowerBatteryDBus(int batteryId, const QString &batteryDBusPath, QObject *parent = nullptr); ~UpowerBatteryDBus(); private: void initBatteryInfo(); int m_batteryId; QDBusInterface *m_DBusInterface; int m_batteryState; double m_percentage; double m_energy; double m_energyFull; double m_energyFullDesign; double m_energyRate; qlonglong m_timeToFull; qlonglong m_timeToEmpty; double m_temperature; int m_warninglevel; QString m_vendor; QString m_model; signals: void batteryInfoChanged(int, QStringList); private slots: void dealBatteryPropertiesMessage(QDBusMessage); public: int getBatteryState(); double getBatteryPercentage(); double getEnergyNow(); double getEnergyFull(); double getEnergyFullDesign(); double getEnergyRate(); qlonglong getTimeToFull(); qlonglong getTimeToEmpty(); double getBatteryTemperature(); int getWarninglevel(); QString getBatteryVendor(); QString getBatteryModel(); }; #endif // UPOWERBATTERYDBUS_H ukui-power-manager-4.0.0.1/PowerManagementDaemon/upm-upower-dbus/upowerlinepowerdbus.h0000664000175000017500000000244614601232446027610 0ustar fengfeng/* * Copyright 2023 KylinSoft Co., Ltd. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ #ifndef UPOWERLINEPOWERDBUS_H #define UPOWERLINEPOWERDBUS_H #include #include #include class UpowerLinePowerDBus : public QObject { Q_OBJECT public: explicit UpowerLinePowerDBus(int linePowerId, const QString &linePowerDBusPath, QObject *parent = nullptr); ~UpowerLinePowerDBus(); private: int m_linePowerId; QDBusInterface *m_DBusInterface; bool m_acOnlineStat; signals: void acOnlineStateChanged(int, bool); private slots: void dealLinePowerPropertiesMessage(QDBusMessage); public: int getAcOnlineState(); }; #endif // UPOWERLINEPOWERDBUS_H ukui-power-manager-4.0.0.1/PowerManagementDaemon/upm-upower-dbus/upm_upowerdbus.h0000664000175000017500000000472014601232446026541 0ustar fengfeng/* * Copyright 2023 KylinSoft Co., Ltd. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ #ifndef UPM_UPOWERDBUS_H #define UPM_UPOWERDBUS_H #include #include "upowerdbus.h" #include "upowerbatterydbus.h" #include "upowerlinepowerdbus.h" class UpmUpowerDBus : public QObject { Q_OBJECT public: explicit UpmUpowerDBus(QObject *parent = nullptr); ~UpmUpowerDBus(); static UpmUpowerDBus* self(); private: UPowerDBus *m_upowerDBus; QVector m_batteryDBusVector; QVector m_linePowerDBusVector; QString m_batteryIconName; signals: void lidStateChanged(bool); void batteryOnlineStateChanged(bool); void batteryInfoChanged(int, QStringList); void acOnlineStateChanged(int, bool); private: void dealLidStateChanged(bool); void dealBatteryOnlineStateChanged(bool); void dealBatteryInfoChanged(int, QStringList); void dealAcOnlineStateChanged(int, bool); public slots: bool getLidClosedState(); bool getBatteryOnlineState(); QString getUpowerDaemonVersion(); int getBatteryNum(); int getLinePowerNum(); int getBatteryState(int index = 0); double getOneBatteryPercentage(int index = 0); double getBatteryPercentage(); double calcBatteryPercentage(); double getEnergyNow(int index = 0); double getEnergyFull(int index = 0); double getEnergyFullDesign(int index = 0); double getEnergyRate(int index = 0); qlonglong getTimeToFull(int index = 0); qlonglong getTimeToEmpty(int index = 0); double getBatteryTemperature(int index = 0); int getWarninglevel(int index = 0); QString getBatteryVendor(int index = 0); QString getBatteryModel(int index = 0); QString getOneBatteryIconName(int index = 0); QString getBatteryIconName(); bool getAcOnlineState(); }; #endif // UPM_UPOWERDBUS_H ukui-power-manager-4.0.0.1/PowerManagementDaemon/upm-upower-dbus/upm_upowerdbus.cpp0000664000175000017500000001724614601232446027103 0ustar fengfeng/* * Copyright 2023 KylinSoft Co., Ltd. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ #include #include "upm_upowerdbus.h" Q_GLOBAL_STATIC(UpmUpowerDBus, s_upowerDBus) UpmUpowerDBus::UpmUpowerDBus(QObject *parent) : QObject(parent) { m_upowerDBus = new UPowerDBus(this); connect(m_upowerDBus, &UPowerDBus::lidStateChanged, this, &UpmUpowerDBus::dealLidStateChanged); connect(m_upowerDBus, &UPowerDBus::batteryOnlineStateChanged, this, &UpmUpowerDBus::dealBatteryOnlineStateChanged); int index = 0; QStringList batteryPathList = m_upowerDBus->getBatteryPathList(); for (index = 0; index < batteryPathList.size(); ++index) { UpowerBatteryDBus *upowerBatteryDBus = new UpowerBatteryDBus(index, batteryPathList.at(index), this); connect(upowerBatteryDBus, &UpowerBatteryDBus::batteryInfoChanged, this, &UpmUpowerDBus::dealBatteryInfoChanged); m_batteryDBusVector << upowerBatteryDBus; } QStringList linePowerPathList = m_upowerDBus->getLinePowerPathList(); for (index = 0; index < linePowerPathList.size(); ++index) { UpowerLinePowerDBus *upowerLinePowerDBus = new UpowerLinePowerDBus(index, linePowerPathList.at(index), this); connect(upowerLinePowerDBus, &UpowerLinePowerDBus::acOnlineStateChanged, this, &UpmUpowerDBus::dealAcOnlineStateChanged); m_linePowerDBusVector << upowerLinePowerDBus; } qDebug() << "Battery Num:" << m_batteryDBusVector.size(); qDebug() << "line power Num:" << m_linePowerDBusVector.size(); } UpmUpowerDBus::~UpmUpowerDBus() {} UpmUpowerDBus *UpmUpowerDBus::self() { return s_upowerDBus; } void UpmUpowerDBus::dealLidStateChanged(bool value) { qDebug() << "lid state changed:" << value; emit lidStateChanged(value); } void UpmUpowerDBus::dealBatteryOnlineStateChanged(bool value) { emit batteryOnlineStateChanged(value); } void UpmUpowerDBus::dealBatteryInfoChanged(int index, QStringList batteryInfoChangedList) { qDebug() << "battery info changed"; emit batteryInfoChanged(index, batteryInfoChangedList); } void UpmUpowerDBus::dealAcOnlineStateChanged(int index, bool value) { qDebug() << "ac online changed:" << value; emit acOnlineStateChanged(index, value); } bool UpmUpowerDBus::getLidClosedState() { return m_upowerDBus->getLidClosedState(); } bool UpmUpowerDBus::getBatteryOnlineState() { return m_upowerDBus->getBatteryOnlineState(); } QString UpmUpowerDBus::getUpowerDaemonVersion() { return m_upowerDBus->getUpowerDaemonVersion(); } int UpmUpowerDBus::getBatteryNum() { return m_batteryDBusVector.size(); } int UpmUpowerDBus::getLinePowerNum() { return m_linePowerDBusVector.size(); } int UpmUpowerDBus::getBatteryState(int index) { if (0 == m_batteryDBusVector.size()) { return 0; } return m_batteryDBusVector.at(index)->getBatteryState(); } double UpmUpowerDBus::getOneBatteryPercentage(int index) { if (0 == m_batteryDBusVector.size()) { return 0; } return m_batteryDBusVector.at(index)->getBatteryPercentage(); } double UpmUpowerDBus::getBatteryPercentage() { if (0 == m_batteryDBusVector.size()) { return 0; } double percentage = 0.0; for (int index = 0; index < m_batteryDBusVector.size(); ++index) { percentage += m_batteryDBusVector.at(index)->getBatteryPercentage(); } return percentage / m_batteryDBusVector.size(); } double UpmUpowerDBus::calcBatteryPercentage() { if (0 == m_batteryDBusVector.size()) { return 0; } double energyNow = 0.0; double energyFull = 0.0; for (int index = 0; index < m_batteryDBusVector.size(); ++index) { energyNow += m_batteryDBusVector.at(index)->getEnergyNow(); energyFull += m_batteryDBusVector.at(index)->getEnergyFull(); } if (0 == energyFull) { return 0; } return energyNow / energyFull * 100; } double UpmUpowerDBus::getEnergyNow(int index) { if (0 == m_batteryDBusVector.size()) { return 0; } return m_batteryDBusVector.at(index)->getEnergyNow(); } double UpmUpowerDBus::getEnergyFull(int index) { if (0 == m_batteryDBusVector.size()) { return 0; } return m_batteryDBusVector.at(index)->getEnergyFull(); } double UpmUpowerDBus::getEnergyFullDesign(int index) { if (0 == m_batteryDBusVector.size()) { return 0; } return m_batteryDBusVector.at(index)->getEnergyFullDesign(); } double UpmUpowerDBus::getEnergyRate(int index) { if (0 == m_batteryDBusVector.size()) { return 0; } return m_batteryDBusVector.at(index)->getEnergyRate(); } qlonglong UpmUpowerDBus::getTimeToFull(int index) { if (0 == m_batteryDBusVector.size()) { return 0; } return m_batteryDBusVector.at(index)->getTimeToFull(); } qlonglong UpmUpowerDBus::getTimeToEmpty(int index) { if (0 == m_batteryDBusVector.size()) { return 0; } return m_batteryDBusVector.at(index)->getTimeToEmpty(); } double UpmUpowerDBus::getBatteryTemperature(int index) { if (0 == m_batteryDBusVector.size()) { return 0; } return m_batteryDBusVector.at(index)->getBatteryTemperature(); } int UpmUpowerDBus::getWarninglevel(int index) { if (0 == m_batteryDBusVector.size()) { return 0; } return m_batteryDBusVector.at(index)->getWarninglevel(); } QString UpmUpowerDBus::getBatteryVendor(int index) { if (0 == m_batteryDBusVector.size()) { return "unknown"; } return m_batteryDBusVector.at(index)->getBatteryVendor(); } QString UpmUpowerDBus::getBatteryModel(int index) { if (0 == m_batteryDBusVector.size()) { return "unknown"; } return m_batteryDBusVector.at(index)->getBatteryModel(); } QString UpmUpowerDBus::getOneBatteryIconName(int index) { if (0 == m_batteryDBusVector.size() || 0 == m_linePowerDBusVector.size()) { return "battery-level-0-charging-symbolic"; } double percentage = m_batteryDBusVector.at(index)->getBatteryPercentage(); if (true == m_linePowerDBusVector.at(index)->getAcOnlineState()) { m_batteryIconName = QString("battery-level-%1-charging-symbolic").arg((int)percentage / 10 * 10); } else { m_batteryIconName = QString("battery-level-%1-symbolic").arg((int)percentage / 10 * 10); } return m_batteryIconName; } QString UpmUpowerDBus::getBatteryIconName() { if (0 == m_batteryDBusVector.size() || 0 == m_linePowerDBusVector.size()) { return "battery-level-0-charging-symbolic"; } double percentage = getBatteryPercentage(); if (true == getAcOnlineState()) { m_batteryIconName = QString("battery-level-%1-charging-symbolic").arg((int)percentage / 10 * 10); } else { m_batteryIconName = QString("battery-level-%1-symbolic").arg((int)percentage / 10 * 10); } return m_batteryIconName; } bool UpmUpowerDBus::getAcOnlineState() { if (0 == m_batteryDBusVector.size() || 0 == m_linePowerDBusVector.size()) { return true; } for (int index = 0; index < m_linePowerDBusVector.size(); ++index) { if (true == m_linePowerDBusVector.at(index)->getAcOnlineState()) { return true; } } return false; } ukui-power-manager-4.0.0.1/PowerManagementDaemon/upm-upower-dbus/upowerdbus.cpp0000664000175000017500000001167214601232446026217 0ustar fengfeng/* * Copyright 2023 KylinSoft Co., Ltd. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ #include #include "upowerdbus.h" UPowerDBus::UPowerDBus(QObject *parent) : QObject(parent) { m_DBusInterface = new QDBusInterface("org.freedesktop.UPower", "/org/freedesktop/UPower", "org.freedesktop.DBus.Properties", QDBusConnection::systemBus()); QDBusConnection::systemBus().connect("org.freedesktop.UPower", "/org/freedesktop/UPower", "org.freedesktop.DBus.Properties", "PropertiesChanged", this, SLOT(dealUPowerDBusMessage(QDBusMessage))); QDBusInterface dBusInterface("org.freedesktop.UPower", "/org/freedesktop/UPower", "org.freedesktop.UPower", QDBusConnection::systemBus()); QDBusReply> reply = dBusInterface.call("EnumerateDevices"); if (dBusInterface.isValid()) { for (QDBusObjectPath dBusObjectPath : reply.value()) { int upDeviceType = getDeviceType(dBusObjectPath.path()); qDebug() << "device type:" << upDeviceType; if (up_device_type_line_power == upDeviceType) { m_linePowerPathList << dBusObjectPath.path(); qDebug() << "line_power dBusObjectPath:" << dBusObjectPath.path(); } else if (up_device_type_battery == upDeviceType) { m_batteryPathList << dBusObjectPath.path(); qDebug() << "battery dBusObjectPath:" << dBusObjectPath.path(); } } } initDeviceInfo(); } UPowerDBus::~UPowerDBus() { delete m_DBusInterface; } int UPowerDBus::getDeviceType(const QString &dBusPath) { qDebug() << "device dBus object path:" << dBusPath; QDBusInterface dBusInterface("org.freedesktop.UPower", dBusPath, "org.freedesktop.DBus.Properties", QDBusConnection::systemBus()); QDBusReply reply = dBusInterface.call("Get", "org.freedesktop.UPower.Device", "Type"); if (reply.isValid()) { return reply.value().toInt(); } else { qDebug() << "Get device type failed"; return up_device_type_unknown; } } void UPowerDBus::initDeviceInfo() { QDBusMessage msg = m_DBusInterface->call("GetAll", "org.freedesktop.UPower"); if (msg.type() == QDBusMessage::ReplyMessage) { const QDBusArgument &dbusArgs = msg.arguments().at(0).value(); QMap map; dbusArgs >> map; m_lidIsPresent = map.value(QString("LidIsPresent")).toBool(); m_lidIsClosed = map.value(QString("LidIsClosed")).toBool(); m_batteryOnline = map.value(QString("OnBattery")).toBool(); m_upowerDaemonVersion = map.value(QString("DaemonVersion")).toString(); } } void UPowerDBus::dealLidClosedMessage(bool value) { if (m_lidIsClosed != value) { m_lidIsClosed = value; emit lidStateChanged(m_lidIsClosed); } } void UPowerDBus::dealBatteryOnlineMessage(bool value) { if (m_batteryOnline != value) { m_batteryOnline = value; emit batteryOnlineStateChanged(m_batteryOnline); } } void UPowerDBus::dealUPowerDBusMessage(QDBusMessage msg) { const QDBusArgument &dbusArgs = msg.arguments().at(1).value(); QMap map; dbusArgs >> map; if (map.contains("LidIsClosed")) { dealLidClosedMessage(map.value(QString("LidIsClosed")).toBool()); } if (map.contains("OnBattery")) { dealBatteryOnlineMessage(map.value(QString("OnBattery")).toBool()); } } bool UPowerDBus::hasLid() { return m_lidIsPresent; } bool UPowerDBus::getLidClosedState() { return m_lidIsClosed; } bool UPowerDBus::getBatteryOnlineState() { return m_batteryOnline; } QString UPowerDBus::getUpowerDaemonVersion() { return m_upowerDaemonVersion; } QStringList UPowerDBus::getBatteryPathList() { return m_batteryPathList; } QStringList UPowerDBus::getLinePowerPathList() { return m_linePowerPathList; } ukui-power-manager-4.0.0.1/PowerManagementDaemon/upm-upower-dbus/upowerlinepowerdbus.cpp0000664000175000017500000000465114601232446030143 0ustar fengfeng/* * Copyright 2023 KylinSoft Co., Ltd. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ #include #include "upowerlinepowerdbus.h" UpowerLinePowerDBus::UpowerLinePowerDBus(int linePowerId, const QString &linePowerDBusPath, QObject *parent) : QObject(parent), m_linePowerId(linePowerId) { m_DBusInterface = new QDBusInterface("org.freedesktop.UPower", linePowerDBusPath, "org.freedesktop.DBus.Properties", QDBusConnection::systemBus(), this); QDBusConnection::systemBus().connect("org.freedesktop.UPower", linePowerDBusPath, "org.freedesktop.DBus.Properties", "PropertiesChanged", this, SLOT(dealLinePowerPropertiesMessage(QDBusMessage))); QDBusReply reply = m_DBusInterface->call("Get", "org.freedesktop.UPower.Device", "Online"); if (reply.isValid()) { m_acOnlineStat = reply.value().toBool(); } else { m_acOnlineStat = false; } } UpowerLinePowerDBus::~UpowerLinePowerDBus() {} void UpowerLinePowerDBus::dealLinePowerPropertiesMessage(QDBusMessage msg) { const QDBusArgument &dbusArgs = msg.arguments().at(1).value(); QMap map; dbusArgs >> map; if (map.contains("Online")) { if (m_acOnlineStat != map.value(QString("Online")).toBool()) { m_acOnlineStat = map.value(QString("Online")).toBool(); emit acOnlineStateChanged(m_linePowerId, m_acOnlineStat); } } } int UpowerLinePowerDBus::getAcOnlineState() { return m_acOnlineStat; } ukui-power-manager-4.0.0.1/PowerManagementDaemon/upm_brightness.h0000664000175000017500000000216514601232446023440 0ustar fengfeng/* * Copyright (C) 2023, KylinSoft Co., Ltd. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . * */ #ifndef UPM_BRIGHTNESS_H #define UPM_BRIGHTNESS_H #include #include "common.h" class UpmBrightness : public QObject { Q_OBJECT public: explicit UpmBrightness(QObject *parent = nullptr); private: int m_brightnessPercentage; void dealBrightnessAcChanged(QVariant value); signals: public: int getBrightnessPercentage(void); void setBrightnessPercentage(int percentage); }; #endif // UPM_BRIGHTNESS_H ukui-power-manager-4.0.0.1/PowerManagementDaemon/upm-gsettings/0000775000175000017500000000000014601232446023040 5ustar fengfengukui-power-manager-4.0.0.1/PowerManagementDaemon/upm-gsettings/upm_gsettings.h0000664000175000017500000000750314601232446026106 0ustar fengfeng/* * Copyright (C) 2023, KylinSoft Co., Ltd. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . * */ #ifndef UPM_GSETTINGS_H #define UPM_GSETTINGS_H #include #include #include #include //gsettings 配置 #define POWER_MANAGER_SETTINGS "org.ukui.power-manager" //电源策略(0:节能 1:平衡 2:性能) #define GSETTINGS_KEY_POWER_POLICY_AC "powerPolicyAc" #define GSETTINGS_KEY_POWER_POLICY_BATTERY "powerPolicyBattery" #define GSETTINGS_KEY_POWER_POLICY_BATTERY_BACKUP "powerPolicyBatteryBackup" //空闲关闭显示器 #define GSETTINGS_KEY_SLEEP_DISPLAY_AC "sleepDisplayAc" #define GSETTINGS_KEY_SLEEP_DISPLAY_BATTERY "sleepDisplayBattery" //空闲睡眠 #define GSETTINGS_KEY_SLEEP_COMPUTER_AC "sleepComputerAc" #define GSETTINGS_KEY_SLEEP_COMPUTER_BATTERY "sleepComputerBattery" //盒盖事件触发操作 #define GSETTINGS_KEY_BUTTON_LID_AC "buttonLidAc" #define GSETTINGS_KEY_BUTTON_LID_BATTERY "buttonLidBattery" //低电量百分百通知 #define GSETTINGS_KEY_PERCENTAGE_LOW "percentageLow" //极低电量 #define GSETTINGS_KEY_PERCENTAGE_ACTION "percentageAction" //极低电量时执行 #define GSETTINGS_KEY_ACTION_CRITICAL_BATTERY "actionCriticalBattery" //开启节能模式 #define GSETTINGS_KEY_BATTERY_SAVE_SWITCH "batterySaveSwitch" //低电量时自动开启节能模式 #define GSETTINGS_KEY_LOW_BATTERY_AUTO_SAVE "lowBatteryAutoSave" //节能模式降低亮度 #define GSETTINGS_KEY_BATTERY_SAVE_REDUCE_BRIGHTNESS "batterySaveReduceBrightness" //亮度值 #define GSETTINGS_KEY_BRIGHTNESS_AC "brightnessAc" class UpmGsettings : public QObject { Q_OBJECT public: explicit UpmGsettings(QObject *parent = nullptr); ~UpmGsettings(); static UpmGsettings* self(); typedef void (UpmGsettings::*pSignalFun)(QVariant); private: QGSettings *m_gsettingsConfig; QHash m_qHashValue; QHash m_qHashSignalsFuns; QHash m_qHashValueType; QStringList m_allGsettingsKey; void initGsettingsConfig(); void addConfigMonitor(const QString &configName, pSignalFun signalFun, QVariant::Type type); signals: void powerPolicyAcChanged(QVariant); void powerPolicyBatteryChanged(QVariant); void powerPolicyBatteryBackupChanged(QVariant); void sleepDisplayAcChanged(QVariant); void sleepDisplayBatteryChanged(QVariant); void sleepComputerAcChanged(QVariant); void sleepComputerBatteryChanged(QVariant); void buttonLidAcChanged(QVariant); void buttonLidBatteryChanged(QVariant); void percentageLowChanged(QVariant); void percentageActionChanged(QVariant); void actionCriticalBatteryChanged(QVariant); void batterySaveSwitchChanged(QVariant); void lowBatteryAutoSaveChanged(QVariant); void batterySaveReduceBrightnessChanged(QVariant); void brightnessAcChanged(QVariant); private slots: void dealGsettingsChanged(const QString &key); public: void setGsettingsConfig(const QString &configName, QVariant value); bool getGsettingsConfig(const QString &configName, QVariant &value); QVariant::Type getValueType(const QString &configName); }; #endif // UPM_GSETTINGS_H ukui-power-manager-4.0.0.1/PowerManagementDaemon/upm-gsettings/upm_gsettings.cpp0000664000175000017500000001273014601232446026437 0ustar fengfeng/* * Copyright (C) 2023, KylinSoft Co., Ltd. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . * */ #include "upm_gsettings.h" #include Q_GLOBAL_STATIC(UpmGsettings, s_upmGsettings) UpmGsettings::UpmGsettings(QObject *parent) : QObject(parent) { const QByteArray gsettingsID("org.ukui.power-manager"); m_gsettingsConfig = new QGSettings(gsettingsID); m_allGsettingsKey = m_gsettingsConfig->keys(); initGsettingsConfig(); connect(m_gsettingsConfig, &QGSettings::changed, this, &UpmGsettings::dealGsettingsChanged); } UpmGsettings::~UpmGsettings() { delete m_gsettingsConfig; } UpmGsettings *UpmGsettings::self() { return s_upmGsettings; } void UpmGsettings::dealGsettingsChanged(const QString &key) { qDebug() << "gsetting key:" << key << "changed!"; if (true == m_qHashValue.contains(key)) { m_qHashValue[key] = m_gsettingsConfig->get(key); emit (this->*m_qHashSignalsFuns[key])(m_qHashValue[key]); } else { qDebug() << "this key:" << key << "is not monitored!"; } } void UpmGsettings::setGsettingsConfig(const QString &configName, QVariant value) { qDebug() << "set key:" << configName; if (true == m_qHashValue.contains(configName)) { m_qHashValue[configName] = value; m_gsettingsConfig->set(configName, value); } else { qDebug() << "this key:" << configName << "is not monitored!"; } } bool UpmGsettings::getGsettingsConfig(const QString &configName, QVariant &value) { qDebug() << "get key:" << configName; if (true == m_qHashValue.contains(configName)) { value = m_qHashValue[configName]; return true; } qDebug() << "this key:" << configName << "is not monitored!"; return false; } void UpmGsettings::addConfigMonitor(const QString &configName, pSignalFun signalFun, QVariant::Type type) { qDebug() << "add config" << configName; if (m_allGsettingsKey.contains(configName)) { m_qHashValue[configName] = m_gsettingsConfig->get(configName); m_qHashSignalsFuns[configName] = signalFun; m_qHashValueType[configName] = type; qDebug() << configName << "to be monitored!"; } } QVariant::Type UpmGsettings::getValueType(const QString &configName) { if (m_qHashValueType.contains(configName)) { return m_qHashValueType[configName]; } return QVariant::Invalid; } void UpmGsettings::initGsettingsConfig() { addConfigMonitor(GSETTINGS_KEY_POWER_POLICY_AC, &UpmGsettings::powerPolicyAcChanged, QVariant::Int); addConfigMonitor(GSETTINGS_KEY_POWER_POLICY_BATTERY, &UpmGsettings::powerPolicyBatteryChanged, QVariant::Int); addConfigMonitor(GSETTINGS_KEY_POWER_POLICY_BATTERY_BACKUP, &UpmGsettings::powerPolicyBatteryBackupChanged, QVariant::Int); addConfigMonitor(GSETTINGS_KEY_SLEEP_DISPLAY_AC, &UpmGsettings::sleepDisplayAcChanged, QVariant::Int); addConfigMonitor(GSETTINGS_KEY_SLEEP_DISPLAY_BATTERY, &UpmGsettings::sleepDisplayBatteryChanged, QVariant::Int); addConfigMonitor(GSETTINGS_KEY_SLEEP_COMPUTER_AC, &UpmGsettings::sleepComputerAcChanged, QVariant::Int); addConfigMonitor(GSETTINGS_KEY_SLEEP_COMPUTER_BATTERY, &UpmGsettings::sleepComputerBatteryChanged, QVariant::Int); addConfigMonitor(GSETTINGS_KEY_BUTTON_LID_AC, &UpmGsettings::buttonLidAcChanged, QVariant::String); addConfigMonitor(GSETTINGS_KEY_BUTTON_LID_BATTERY, &UpmGsettings::buttonLidBatteryChanged, QVariant::String); addConfigMonitor(GSETTINGS_KEY_PERCENTAGE_LOW, &UpmGsettings::percentageLowChanged, QVariant::Int); //极低电量百分比 addConfigMonitor(GSETTINGS_KEY_PERCENTAGE_ACTION, &UpmGsettings::percentageActionChanged, QVariant::Int); //极低电量操作 addConfigMonitor(GSETTINGS_KEY_ACTION_CRITICAL_BATTERY, &UpmGsettings::actionCriticalBatteryChanged, QVariant::String); addConfigMonitor(GSETTINGS_KEY_BATTERY_SAVE_SWITCH, &UpmGsettings::batterySaveSwitchChanged, QVariant::Bool); addConfigMonitor(GSETTINGS_KEY_LOW_BATTERY_AUTO_SAVE, &UpmGsettings::lowBatteryAutoSaveChanged, QVariant::Bool); addConfigMonitor(GSETTINGS_KEY_BATTERY_SAVE_REDUCE_BRIGHTNESS, &UpmGsettings::batterySaveReduceBrightnessChanged, QVariant::Bool); addConfigMonitor(GSETTINGS_KEY_BRIGHTNESS_AC, &UpmGsettings::brightnessAcChanged, QVariant::Int); } ukui-power-manager-4.0.0.1/PowerManagementDaemon/upm_powerchanged.cpp0000664000175000017500000000461514601232446024273 0ustar fengfeng/* * Copyright (C) 2023, KylinSoft Co., Ltd. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . * */ #include "upm_powerchanged.h" UpmPowerChanged::UpmPowerChanged(QObject *parent) : QObject(parent) { connect(UpmUpowerDBus::self(), &UpmUpowerDBus::acOnlineStateChanged, this, &UpmPowerChanged::dealAcOnlineStateChanged); } void UpmPowerChanged::dealAcOnlineStateChanged(int acIndex, bool acOnline) { qDebug() << "ac index:" << acIndex << "ac online state :" << acOnline; if (true == UpmUpowerDBus::self()->getAcOnlineState()) { setPowerModePolicy(); // UpmCommonDBus::self()->playSystemSound(POWER_PLUG); } else { setBatteryModePolicy(); } } void UpmPowerChanged::setPowerModePolicy() { QVariant value; if (true == UpmGsettings::self()->getGsettingsConfig(GSETTINGS_KEY_POWER_POLICY_AC, value)) { UpmControlDBus::self()->controlPowerManagement(UPM_DBUS_METHOD_SET_PC_POLICY, value.toInt()); } } void UpmPowerChanged::setBatteryModePolicy() { QVariant value; int percentageLow = 0; bool lowBatteryAutoSave = false; double currentPercent = UpmUpowerDBus::self()->getBatteryPercentage(); if (true == UpmGsettings::self()->getGsettingsConfig(GSETTINGS_KEY_LOW_BATTERY_AUTO_SAVE, value)) { lowBatteryAutoSave = value.toBool(); } if (true == UpmGsettings::self()->getGsettingsConfig(GSETTINGS_KEY_PERCENTAGE_LOW, value)) { percentageLow = value.toInt(); } if (percentageLow > currentPercent && true == lowBatteryAutoSave) { qDebug() << "power low and auto save"; } else { if (true == UpmGsettings::self()->getGsettingsConfig(GSETTINGS_KEY_POWER_POLICY_BATTERY, value)) { UpmControlDBus::self()->controlPowerManagement(UPM_DBUS_METHOD_SET_PC_POLICY, value.toInt()); } } } ukui-power-manager-4.0.0.1/PowerManagementDaemon/upm_systemidle.h0000664000175000017500000000315414601232446023451 0ustar fengfeng/* * Copyright (C) 2023, KylinSoft Co., Ltd. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . * */ #ifndef UPM_SYSTEMIDLE_H #define UPM_SYSTEMIDLE_H #include #include #include "common.h" #define DEFAULE_SLEEP_DISPLAY_TIME 600 #define DEFAULE_SLEEP_COMPUTER_TIME 900 class UpmSystemIdle : public QObject { Q_OBJECT public: explicit UpmSystemIdle(QObject *parent = nullptr); private: int m_turnoffDisplayAc; int m_turnoffDisplayBattery; int m_systemSuspendAc; int m_systemSuspendBattery; QTimer *m_turnOffDisplayTimer; QTimer *m_systemSuspendTimer; QTimer *m_reduceBrightnessTimer; int m_enterIdleTime = 60; void dealSystemStatusChanged(quint32); int getTurnOffDisplayTime(); int getSystemSuspendTime(); private slots: void dealSystemIdleStatus(bool); void dealTurnOffDisplay(); void dealSystemSuspend(); void dealReduceBrightness(); void stopTimer(); signals: void brightnessControlSignal(int); }; #endif // UPM_SYSTEMIDLE_H ukui-power-manager-4.0.0.1/PowerManagementDaemon/upm-control-dbus/0000775000175000017500000000000014601232446023444 5ustar fengfengukui-power-manager-4.0.0.1/PowerManagementDaemon/upm-control-dbus/upm_controldbus.cpp0000664000175000017500000001221514601232446027370 0ustar fengfeng/* * Copyright (C) 2023, KylinSoft Co., Ltd. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . * */ #include "upm_controldbus.h" Q_GLOBAL_STATIC(UpmControlDBus, s_controlDBus) UpmControlDBus::UpmControlDBus(QObject *parent) : QObject(parent) { m_userName = qgetenv("USER"); if (m_userName.isEmpty()) { m_userName = qgetenv("USERNAME"); } qDebug() << "current user:" << m_userName; controlPowerManagement(UPM_DBUS_METHOD_USER_LOGIN, m_userName); m_userActive = true; QDBusConnection::systemBus().connect( UPM_DBUS_SERVICE, UPM_DBUS_PATH, UPM_DBUS_INTERFACE, "SystemConfigChanged", this, SLOT(dealSystemConfigChanged(const QString, const QString, const QString))); QDBusConnection::systemBus().connect( UPM_DBUS_SERVICE, UPM_DBUS_PATH, UPM_DBUS_INTERFACE, "ActiveUserChanged", this, SLOT(dealActiveUserChanged(const QString))); } UpmControlDBus::~UpmControlDBus() { controlPowerManagement(UPM_DBUS_METHOD_USER_LOGOUT, m_userName); } UpmControlDBus *UpmControlDBus::self() { return s_controlDBus; } QString UpmControlDBus::getUserName() { return m_userName; } void UpmControlDBus::setUserActive(bool userActive) { m_userActive = userActive; if (true == userActive) { controlPowerManagement(UPM_DBUS_METHOD_USER_ACTIVE, m_userName); } } void UpmControlDBus::controlPowerManagement(const QString &method, QVariant parameter, bool effective) { if (false == m_userActive) { return ; } QDBusInterface dBusInterface(UPM_DBUS_SERVICE, UPM_DBUS_PATH, UPM_DBUS_INTERFACE, QDBusConnection::systemBus()); QVariant::Type valueType = parameter.type(); if (true == effective) { if (QVariant::String == valueType) { dBusInterface.call(method, parameter.toString()); } else if (QVariant::Int == valueType) { dBusInterface.call(method, parameter.toInt()); } else if (QVariant::Bool == valueType) { dBusInterface.call(method, parameter.toBool()); } } else { dBusInterface.call(method); } } QString UpmControlDBus::getUpmSystemConfig(const QString &key) { QDBusInterface dBusInterface(UPM_DBUS_SERVICE, UPM_DBUS_PATH, UPM_DBUS_INTERFACE, QDBusConnection::systemBus()); QDBusReply reply = dBusInterface.call(UPM_DBUS_METHOD_GET_SYS_CONFIG, key); if (reply.isValid()) { return reply.value(); } return QString(); } void UpmControlDBus::setUpmSystemConfig(const QString &key, const QString &value) { if (false == m_userActive) { return ; } QDBusInterface dBusInterface(UPM_DBUS_SERVICE, UPM_DBUS_PATH, UPM_DBUS_INTERFACE, QDBusConnection::systemBus()); dBusInterface.call(UPM_DBUS_METHOD_SET_SYS_CONFIG, m_userName, key, value); } void UpmControlDBus::controlDisplay(const QString &action) { if (false == m_userActive) { return ; } QString strCmd; if ("wayland" == qgetenv("XDG_SESSION_TYPE")) { strCmd = QString("export QT_QPA_PLATFORM=wayland && "); strCmd.append(QString("kscreen-doctor --dpms %1").arg(action)); } else { strCmd = QString("xset dpms force %1").arg(action); } qDebug() << "The display:" << qgetenv("XDG_SESSION_TYPE") << "turn" << action; QProcess process; process.start("bash", QStringList() << "-c" << strCmd); process.waitForFinished(); } void UpmControlDBus::turnOffDisplaySignal() { const bool state = true; QDBusMessage msg = QDBusMessage::createSignal("/", "ukui.power.manager", "TurnOffDisplay"); msg << state; QDBusConnection::sessionBus().send(msg); qDebug() << "send turn off display msg"; } void UpmControlDBus::delayLockScreen(const QString &action) { QString strCmd = QString("ukui-screensaver-command -b "); strCmd.append(action); QProcess process; //执行命令 process.start(strCmd); //等待命令执行结束 process.waitForFinished(); } void UpmControlDBus::dealSystemConfigChanged(const QString userName, const QString key, const QString value) { emit systemConfigChangedSignal(userName, key, value); } void UpmControlDBus::dealActiveUserChanged(const QString userName) { if (userName != m_userName) { m_userActive = false; } } ukui-power-manager-4.0.0.1/PowerManagementDaemon/upm-control-dbus/upm_controldbus.h0000664000175000017500000000617414601232446027044 0ustar fengfeng/* * Copyright (C) 2023, KylinSoft Co., Ltd. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . * */ #ifndef UPM_CONTROLDBUS_H #define UPM_CONTROLDBUS_H #include #include #include #define UPM_DBUS_SERVICE "org.ukui.powermanagement" #define UPM_DBUS_PATH "/" #define UPM_DBUS_INTERFACE "org.ukui.powermanagement.interface" #define UPM_DBUS_METHOD_USER_LOGIN "UserLogin" #define UPM_DBUS_METHOD_USER_LOGOUT "UserLogout" #define UPM_DBUS_METHOD_USER_ACTIVE "UserActive" #define UPM_DBUS_METHOD_SET_SYS_CONFIG "SetSystemConfig" #define UPM_DBUS_METHOD_GET_SYS_CONFIG "GetSystemConfig" #define UPM_DBUS_METHOD_SET_PC_POLICY "SetPcPolicy" #define UPM_DBUS_METHOD_SET_CPU_POLICY "SetCpuPolicy" #define UPM_DBUS_METHOD_SET_GPU_POLICY "SetGpuPolicy" #define UPM_DBUS_METHOD_SET_AUDIO_POLICY "SetAudioPolicy" #define UPM_DBUS_METHOD_SET_ASPM_POLICY "SetAspmPolicy" #define UPM_DBUS_METHOD_SET_POWEROFF "PowerOff" #define UPM_DBUS_METHOD_SET_SUSPEND "Suspend" #define UPM_DBUS_METHOD_SET_HIBERNATE "Hibernate" #define UPM_DBUS_METHOD_SET_SUSPEND_THEN_HIBERNATE "SuspendThenHibernate" #define UPM_DBUS_METHOD_SET_BRIGHTNESS_PERCENT "SetBrightnessPercent" #define UPM_DBUS_METHOD_GET_BRIGHTNESS_PERCENT "GetBrightnessPercent" #define UPM_DBUS_METHOD_SET_BATTERY_SAVE_SWITCH "SetBatterySaveSwitch" #define UPM_DBUS_METHOD_SET_AUTO_BATTERY_SAVE_SWITCH "SetAutoBatterySaveSwitch" #define UPM_DBUS_METHOD_SET_REDUCE_BACKLIGHT_SWITCH "SetReduceBacklightSwitch" class UpmControlDBus : public QObject { Q_OBJECT public: explicit UpmControlDBus(QObject *parent = nullptr); ~UpmControlDBus(); static UpmControlDBus* self(); private: QString m_userName; bool m_userActive; public: QString getUserName(); void setUserActive(bool userActive); void controlPowerManagement(const QString &method, QVariant parameter = 0, bool effective = true); QString getUpmSystemConfig(const QString &key); void setUpmSystemConfig(const QString &key, const QString &value); void controlDisplay(const QString &action); void turnOffDisplaySignal(); void delayLockScreen(const QString &action); private slots: void dealSystemConfigChanged(const QString, const QString, const QString); void dealActiveUserChanged(const QString); signals: void systemConfigChangedSignal(const QString, const QString, const QString); }; #endif // UPM_CONTROLDBUS_H ukui-power-manager-4.0.0.1/PowerManagementDaemon/upm-common-dbus/0000775000175000017500000000000014601232446023254 5ustar fengfengukui-power-manager-4.0.0.1/PowerManagementDaemon/upm-common-dbus/upm_commondbus.cpp0000664000175000017500000001111514601232446027006 0ustar fengfeng/* * Copyright (C) 2023, KylinSoft Co., Ltd. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . * */ #include "upm_commondbus.h" Q_GLOBAL_STATIC(UpmCommonDBus, s_commonDBus) UpmCommonDBus::UpmCommonDBus(QObject *parent) : QObject(parent) { //systemd login1 dbus QDBusConnection::systemBus().connect( "org.freedesktop.login1", "/org/freedesktop/login1", "org.freedesktop.login1.Manager", "PrepareForSleep", this, SLOT(dealPrepareForSleep(bool))); //system idle status QDBusConnection::sessionBus().connect( "org.gnome.SessionManager", "/org/gnome/SessionManager/Presence", "org.gnome.SessionManager.Presence", "StatusChanged", this, SLOT(dealSystemStatusChanged(quint32))); //user active signal QDBusConnection::sessionBus().connect("org.ukui.SettingsDaemon", "/GlobaSignal", "org.ukui.SettingsDaemon.GlobalSignal", "Active", this, SLOT(dealUserActiveSignal(bool))); initPlatformType(); } UpmCommonDBus::~UpmCommonDBus() {} UpmCommonDBus *UpmCommonDBus::self() { return s_commonDBus; } void UpmCommonDBus::dealPrepareForSleep(bool isSleep) { emit systemSleepStatus(isSleep); } void UpmCommonDBus::dealSystemStatusChanged(quint32 status) { qDebug() << "Idle signal received from Session Manager" << status; if (SYSTEM_IDEL_SIGNAL_VALUE == status) { emit systemIdleStatus(true); } else { emit systemIdleStatus(false); } } void UpmCommonDBus::dealUserActiveSignal(bool active) { emit userActiveSignal(active); } quint32 UpmCommonDBus::sendNotification( const QString &type, const QString &arg, bool permanent) { QDBusInterface dbusInterface("org.freedesktop.Notifications", "/org/freedesktop/Notifications", "org.freedesktop.Notifications", QDBusConnection::sessionBus()); QList args; QStringList argg; QMap pear_map; if (true == permanent) { pear_map.insert("x-ukui-popup-timeout", -1); } args << tr("Power Manager") << ((unsigned int)0) << QString("ukui-power-manager") << type //显示的是什么类型的信息 << arg //显示的具体信息 << argg << pear_map << 0; QDBusReply reply = dbusInterface.callWithArgumentList(QDBus::AutoDetect, "Notify", args); qDebug() << "notification id is:" << reply.value(); return reply.value(); } void UpmCommonDBus::closeNotification(quint32 notificationId) { qDebug() << "close notification id is:" << notificationId; QDBusInterface dbusInterface("org.freedesktop.Notifications", "/org/freedesktop/Notifications", "org.freedesktop.Notifications", QDBusConnection::sessionBus()); dbusInterface.call("CloseNotification", notificationId); } void UpmCommonDBus::initPlatformType() { QString cloudPlatForm = QString(QLatin1String("")); QString hostType = QString(QLatin1String("")); #ifdef KY_SDK_SYSINFO cloudPlatForm = QString(QLatin1String(kdk_system_get_hostCloudPlatform())); hostType = QString(QLatin1String(kdk_system_get_hostVirtType())); #endif qDebug() << "cloud platform name:" << cloudPlatForm << "host type:" << hostType; if ((cloudPlatForm == "huawei" || cloudPlatForm == "ctyun" || hostType != "none")) { m_isCloudPlatform = true; qDebug() << "is cloud platform"; } } bool UpmCommonDBus::isCloudPlatform() { return m_isCloudPlatform; } /* void UpmCommonDBus::playSystemSound(SoundType type) { KSoundEffects::playSound(type); } */ ukui-power-manager-4.0.0.1/PowerManagementDaemon/upm-common-dbus/upm_commondbus.h0000664000175000017500000000343014601232446026454 0ustar fengfeng/* * Copyright (C) 2023, KylinSoft Co., Ltd. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . * */ #ifndef UPM_COMMONDBUS_H #define UPM_COMMONDBUS_H #include #include #include #ifdef KY_SDK_SYSINFO #include #endif //#include //using namespace kdk; #define SYSTEM_BUSY_SIGNAL_VALUE 0 #define SYSTEM_IDEL_SIGNAL_VALUE 3 class UpmCommonDBus : public QObject { Q_OBJECT public: explicit UpmCommonDBus(QObject *parent = nullptr); ~UpmCommonDBus(); static UpmCommonDBus* self(); quint32 sendNotification(const QString &type, const QString &arg, bool permanent); void closeNotification(quint32 notificationId); // void playSystemSound(SoundType type); bool isCloudPlatform(); private: bool m_isCloudPlatform = false; void initPlatformType(); private slots: void dealPrepareForSleep(bool); void dealSystemStatusChanged(quint32); void dealUserActiveSignal(bool); signals: void systemSleepStatus(bool); void systemIdleStatus(bool); void userActiveSignal(bool); }; #endif // UPM_COMMONDBUS_H ukui-power-manager-4.0.0.1/PowerManagementDaemon/upm_checkconfig.cpp0000664000175000017500000001365014601232446024067 0ustar fengfeng/* * Copyright (C) 2023, KylinSoft Co., Ltd. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . * */ #include "upm_checkconfig.h" UpmCheckConfig::UpmCheckConfig(QObject *parent) : QObject(parent) {} QVariant UpmCheckConfig::checkConfig( const QString &configName, QVariant defaultValue, QVariant::Type dataType, const QStringList &valueRange, bool continuousValue) { QVariant gsettingsValue; QString systemConfigValue; QVariant tempValue; systemConfigValue = UpmControlDBus::self()->getUpmSystemConfig(configName); if (systemConfigValue.isNull()) { tempValue = QString(); qDebug() << "get" << configName << "error"; } else { if (false == checkSystemConfigValue(systemConfigValue, valueRange, continuousValue)) { tempValue = QString(); } else { if (QVariant::String == dataType) { tempValue = systemConfigValue; } else if (QVariant::Int == dataType) { tempValue = systemConfigValue.toInt(); } else if (QVariant::Bool == dataType) { "true" == systemConfigValue ? tempValue = true : tempValue = false; } } qDebug() << "system config:" << configName << "value:" << tempValue; } if (true == UpmGsettings::self()->getGsettingsConfig(configName, gsettingsValue)) { if (true == checkGsettingsConfigValue(gsettingsValue, dataType, valueRange, continuousValue)) { if (tempValue.isNull()) { tempValue = gsettingsValue; if (QVariant::String == dataType) { UpmControlDBus::self()->setUpmSystemConfig(configName, tempValue.toString()); } else if (QVariant::Int == dataType) { UpmControlDBus::self()->setUpmSystemConfig(configName, QString::number(tempValue.toInt())); } else if (QVariant::Bool == dataType) { true == tempValue ? UpmControlDBus::self()->setUpmSystemConfig(configName, "true") : UpmControlDBus::self()->setUpmSystemConfig(configName, "false"); } qDebug() << "sync gsettings config:" << configName << "action:" << tempValue; } else { UpmGsettings::self()->setGsettingsConfig(configName, tempValue); qDebug() << "sync sytstem config:" << configName << "action:" << tempValue; } } else { if (!tempValue.isNull()) { UpmGsettings::self()->setGsettingsConfig(configName, tempValue); qDebug() << "sync sytstem config:" << configName << "action:" << tempValue; } } } if (tempValue.isNull()) { tempValue = defaultValue; UpmGsettings::self()->setGsettingsConfig(configName, tempValue); if (QVariant::String == dataType) { UpmControlDBus::self()->setUpmSystemConfig(configName, tempValue.toString()); } else if (QVariant::Int == dataType) { UpmControlDBus::self()->setUpmSystemConfig(configName, QString::number(tempValue.toInt())); } else if (QVariant::Bool == dataType) { true == tempValue ? UpmControlDBus::self()->setUpmSystemConfig(configName, "true") : UpmControlDBus::self()->setUpmSystemConfig(configName, "false"); } qDebug() << "use default value:" << defaultValue; } return tempValue; } bool UpmCheckConfig::checkSystemConfigValue( const QString &configValue, const QStringList &valueRange, bool continuousValue) { qDebug() << "check system config value:" << configValue; if (UPM_POWER_CONFIG_ERROR == configValue) { return false; } qDebug() << "config value range:" << valueRange; if (true == continuousValue) { qDebug() << "config value is continuous:" << continuousValue; int value = configValue.toInt(); int minValue = valueRange.at(0).toInt(); int maxValue = valueRange.at(1).toInt(); if (value < minValue || value > maxValue) { return false; } else { return true; } } return valueRange.contains(configValue); } bool UpmCheckConfig::checkGsettingsConfigValue( QVariant &configValue, QVariant::Type dataType, const QStringList &valueRange, bool continuousValue) { qDebug() << "check gsettings config value:" << configValue; QString tempValue; if (QVariant::String == dataType) { tempValue = configValue.toString(); } else if (QVariant::Int == dataType) { tempValue = QString::number(configValue.toInt()); } else if (QVariant::Bool == dataType) { if (true == configValue.toBool()) { tempValue = "true"; } else { tempValue = "false"; } } qDebug() << "config value range:" << valueRange; if (true == continuousValue) { qDebug() << "config value is continuous:" << continuousValue; int value = tempValue.toInt(); int minValue = valueRange.at(0).toInt(); int maxValue = valueRange.at(1).toInt(); if (value < minValue || value > maxValue) { return false; } else { return true; } } return valueRange.contains(tempValue); } ukui-power-manager-4.0.0.1/PowerManagementDaemon/upm_externalinterface.h0000664000175000017500000000257414601232446024777 0ustar fengfeng/* * Copyright (C) 2023, KylinSoft Co., Ltd. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . * */ #ifndef UPM_EXTERNALINTERFACE_H #define UPM_EXTERNALINTERFACE_H #include #include "common.h" enum batterySaverState { batterySaverOff = 0, batterySaverOn, batterySaverUnavailable }; class UpmExternalInterface : public QObject, protected QDBusContext { Q_OBJECT Q_CLASSINFO("D-Bus Interface", "org.ukui.powerManager") public: explicit UpmExternalInterface(QObject *parent = nullptr); private slots: void dealBatterySaveSwitchChanged(QVariant); void dealAcOnlineStateChanged(int, bool); public slots: void SetBatterySaver(const int); int GetBatterySaver(); signals: void PowerConfigChanged(QStringList); }; #endif // UPM_EXTERNALINTERFACE_H ukui-power-manager-4.0.0.1/PowerManagementDaemon/translations/0000775000175000017500000000000014601232446022753 5ustar fengfengukui-power-manager-4.0.0.1/PowerManagementDaemon/translations/ukui-power-manager-daemon_zh_CN.ts0000664000175000017500000000164614601232446031373 0ustar fengfeng UpmCommonDBus Power Manager 电源管理器 UpmLowPower Low battery notification 低电量消息通知 The system enters a low battery state 系统进入低电量状态 ukui-power-manager-4.0.0.1/PowerManagementDaemon/translations/ukui-power-manager-daemon_tr.ts0000664000175000017500000000163514601232446031015 0ustar fengfeng UpmCommonDBus Power Manager UpmLowPower Low battery notification The system enters a low battery state ukui-power-manager-4.0.0.1/PowerManagementDaemon/translations/ukui-power-manager-daemon_bo_CN.ts0000664000175000017500000000212714601232446031345 0ustar fengfeng UpmCommonDBus Power Manager གློག་ཁུངས་དོ་དམ་ཆས་ UpmLowPower Low battery notification དམའ་གློག་ཚད་གནས་ཚུལ་བརྡ་སྦྱོར། The system enters a low battery state མ་ལག་སླེབས་པ་དམའ་གློག་ཚད་རྣམ་པ། ukui-power-manager-4.0.0.1/PowerManagementDaemon/upm_brightness.cpp0000664000175000017500000000476214601232446024000 0ustar fengfeng/* * Copyright (C) 2023, KylinSoft Co., Ltd. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . * */ #include "upm_brightness.h" UpmBrightness::UpmBrightness(QObject *parent) : QObject(parent) { QStringList valueRange = {QString::number(0), QString::number(100)}; m_brightnessPercentage = UpmCheckConfig::checkConfig( GSETTINGS_KEY_BRIGHTNESS_AC, DEFAULE_BRIGHTNESS_PERCNET, QVariant::Int, valueRange, true).toInt(); connect(UpmGsettings::self(), &UpmGsettings::brightnessAcChanged, this, &UpmBrightness::dealBrightnessAcChanged); } void UpmBrightness::dealBrightnessAcChanged(QVariant value) { int percentage = value.toInt(); if (percentage >= 0 && percentage <= 100) { qDebug() << "brightness percentage:" << percentage; m_brightnessPercentage = percentage; UpmControlDBus::self()->controlPowerManagement( UPM_DBUS_METHOD_SET_BRIGHTNESS_PERCENT, m_brightnessPercentage); UpmControlDBus::self()->setUpmSystemConfig( GSETTINGS_KEY_BRIGHTNESS_AC, QString::number(percentage)); } else { qDebug() << "brightness percentage error:" << percentage; } } int UpmBrightness::getBrightnessPercentage(void) { return m_brightnessPercentage; } void UpmBrightness::setBrightnessPercentage(int percentage) { qDebug() << "set brightness percentage:" << percentage; if (percentage >= 0 && percentage <= 100) { UpmControlDBus::self()->controlPowerManagement( UPM_DBUS_METHOD_SET_BRIGHTNESS_PERCENT, percentage); } else { if (percentage < 0) { UpmControlDBus::self()->controlPowerManagement( UPM_DBUS_METHOD_SET_BRIGHTNESS_PERCENT, 0); } else { UpmControlDBus::self()->controlPowerManagement( UPM_DBUS_METHOD_SET_BRIGHTNESS_PERCENT, 100); } } } ukui-power-manager-4.0.0.1/PowerManagementDaemon/upm_lowpower.h0000664000175000017500000000367714601232446023157 0ustar fengfeng/* * Copyright (C) 2023, KylinSoft Co., Ltd. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . * */ #ifndef UPM_LOWPOWER_H #define UPM_LOWPOWER_H #include #include "common.h" #define DEFAULE_PERCENTAGE_LOW 20 #define DEFAULE_PERCENTAGE_ACTION 5 class UpmLowPower : public QObject { Q_OBJECT public: explicit UpmLowPower(QObject *parent = nullptr); bool getBatterySaveSwitch(void); bool getBatteryLowState(void); private: int m_percentageLow = 0; int m_percentageAction = 0; quint32 m_notificationId = 0; bool m_batteryLowState = false; bool m_enableBatterySaver; bool m_autoEnableBatterySaver; bool m_enableReduceBrightness; int getPowerPolicyBattery(const QString &configName); void setUpmSystemConfig(const QString &key, bool value); void batteryPercentageLowAction(); void batteryPercentageRecoveryAction(); private slots: void dealAcOnlineStateChanged(int, bool); void dealBatteryInfoChanged(int, QStringList); void dealPercentageLowChanged(QVariant); void dealPercentageActionChanged(QVariant); void dealBatterySaveSwitchChanged(QVariant); void dealLowBatteryAutoSaveChanged(QVariant); void dealBatterySaveReduceBrightnessChanged(QVariant); signals: void percentageLowSignal(bool); void brightnessControlSignal(int); }; #endif // UPM_LOWPOWER_H ukui-power-manager-4.0.0.1/PowerManagementDaemon/common.h0000664000175000017500000000321014601232446021667 0ustar fengfeng/* * Copyright 2023 KylinSoft Co., Ltd. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ #ifndef COMMON_H #define COMMON_H #include #include "upm-control-dbus/upm_controldbus.h" #include "upm-upower-dbus/upm_upowerdbus.h" #include "upm-gsettings/upm_gsettings.h" #include "upm-common-dbus/upm_commondbus.h" #include "upm_checkconfig.h" #define REDUCE_BRIGHTNESS 0 #define INCREASE_BRIGHTNESS 1 #define UPM_POWER_CONFIG_ERROR "error" #define UPM_POWER_ACTION_NOTHING "nothing" #define UPM_POWER_ACTION_BLANK "blank" #define UPM_POWER_ACTION_SUSPEND "suspend" #define UPM_POWER_ACTION_HIBERNATE "hibernate" #define UPM_POWER_ACTION_SHUTDOWN "shutdown" #define DEFAULE_BRIGHTNESS_PERCNET 66 #define DEFAULE_PERCENTAGE_LOW 20 #define DEFAULE_PERCENTAGE_ACTION 5 #define DEFAULE_SLEEP_DISPLAY_TIME 600 #define DEFAULE_SLEEP_COMPUTER_TIME 900 enum policy { power_policy_performance = 0, power_policy_balance, power_policy_powersave, power_policy_unknown }; #endif // COMMON_H ukui-power-manager-4.0.0.1/PowerManagementDaemon/upm_lid.cpp0000664000175000017500000001074614601232446022377 0ustar fengfeng/* * Copyright (C) 2023, KylinSoft Co., Ltd. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . * */ #include "upm_lid.h" UpmLid::UpmLid(QObject *parent) : QObject(parent) { m_displayIsOn = true; m_lidIsClosed = UpmUpowerDBus::self()->getLidClosedState(); initLidActionFun(); QStringList valueRange = {UPM_POWER_ACTION_NOTHING, UPM_POWER_ACTION_BLANK, UPM_POWER_ACTION_SUSPEND, UPM_POWER_ACTION_HIBERNATE, UPM_POWER_ACTION_SHUTDOWN}; m_closeLidActionAc = UpmCheckConfig::checkConfig( GSETTINGS_KEY_BUTTON_LID_AC, QString(UPM_POWER_ACTION_SUSPEND), QVariant::String, valueRange, false).toString(); m_closeLidActionBattery = UpmCheckConfig::checkConfig( GSETTINGS_KEY_BUTTON_LID_BATTERY, UPM_POWER_ACTION_SUSPEND, QVariant::String, valueRange, false).toString(); connect(UpmGsettings::self(), &UpmGsettings::buttonLidAcChanged, this, [=](QVariant value) { m_closeLidActionAc = value.toString(); UpmControlDBus::self()->setUpmSystemConfig(GSETTINGS_KEY_BUTTON_LID_AC, m_closeLidActionAc); }); connect(UpmGsettings::self(), &UpmGsettings::buttonLidBatteryChanged, this, [=](QVariant value) { m_closeLidActionBattery = value.toString(); UpmControlDBus::self()->setUpmSystemConfig(GSETTINGS_KEY_BUTTON_LID_BATTERY, m_closeLidActionBattery); }); connect(UpmCommonDBus::self(), &UpmCommonDBus::systemSleepStatus, this, &UpmLid::dealSystemSleepStatus); connect(UpmUpowerDBus::self(), &UpmUpowerDBus::lidStateChanged, this, &UpmLid::dealLidStateChanged); } void UpmLid::initLidActionFun() { addLidActionFun(UPM_POWER_ACTION_NOTHING, &UpmLid::closeLidNothingToDo); addLidActionFun(UPM_POWER_ACTION_BLANK, &UpmLid::closeLidTurnOffDisplay); addLidActionFun(UPM_POWER_ACTION_SUSPEND, &UpmLid::closeLidToSuspend); addLidActionFun(UPM_POWER_ACTION_HIBERNATE, &UpmLid::closeLidToHibernate); addLidActionFun(UPM_POWER_ACTION_SHUTDOWN, &UpmLid::closeLidToShutdown); } void UpmLid::addLidActionFun(const QString &action, pCloseLidActionFun actionFun) { m_closeLidActionFun[action] = actionFun; } void UpmLid::dealLidStateChanged(bool lidIsClosed) { QString action; m_lidIsClosed = lidIsClosed; if (true == UpmUpowerDBus::self()->getAcOnlineState()) { action = m_closeLidActionAc; } else { action = m_closeLidActionBattery; } qDebug() << "lid state:" << m_lidIsClosed << "action:" << action; if (true == m_lidIsClosed) { (this->*m_closeLidActionFun[action])(); } else { if("blank" == action && false == m_displayIsOn) { UpmControlDBus::self()->controlDisplay("on"); m_displayIsOn = true; } } } void UpmLid::dealSystemSleepStatus(bool isSleep) { if (isSleep) { qDebug() << "The computer is going to sleep"; } else { if (m_lidIsClosed) { qWarning() << "Sleep is awakened unexpectedly!"; dealLidStateChanged(m_lidIsClosed); } else { qDebug() << "The computer wakes up"; } } } void UpmLid::closeLidNothingToDo() {} void UpmLid::closeLidTurnOffDisplay() { UpmControlDBus::self()->delayLockScreen("lid"); UpmControlDBus::self()->controlDisplay("off"); UpmControlDBus::self()->turnOffDisplaySignal(); m_displayIsOn = false; } void UpmLid::closeLidToSuspend() { UpmControlDBus::self()->controlPowerManagement("Suspend", 0, false); } void UpmLid::closeLidToShutdown() { UpmControlDBus::self()->controlPowerManagement("PowerOff", 0, false); } void UpmLid::closeLidToHibernate() { UpmControlDBus::self()->controlPowerManagement("Hibernate", 0, false); } ukui-power-manager-4.0.0.1/PowerManagementDaemon/resources/0000775000175000017500000000000014601232446022244 5ustar fengfengukui-power-manager-4.0.0.1/PowerManagementDaemon/resources/10-monitor.conf0000664000175000017500000000023714601232446025022 0ustar fengfengSection "ServerFlags" option "StanbyTime" "0" option "SuspendTime" "0" option "OffTime" "0" option "BlankTime" "0" EndSection ukui-power-manager-4.0.0.1/PowerManagementDaemon/resources/ukui-powermanagement-daemon.desktop0000664000175000017500000000065514601232446031252 0ustar fengfeng[Desktop Entry] Name=Power Manager Name[zh_CN]=电源管理器 Name[bo_CN]=གློག་ཁུངས་དོ་དམ་ཆས་ Comment=Power management daemon Comment[zh_CN]=电源管理守护程序 Comment[bo_CN]=གློག་ཁུངས་དོ་དམ་ཆས་ Icon=ukui-power-manager Exec=ukui-powermanagement Terminal=false Type=Application NoDisplay=true Categories= OnlyShowIn=UKUI; X-UKUI-AutoRestart=true ukui-power-manager-4.0.0.1/PowerManagementDaemon/resources/upm-global.conf0000664000175000017500000000042414601232446025152 0ustar fengfeng[power-mode-default-balance] boardName = ":rnNL203B:,:rnNZ252B-Inspur:,:rnNF251B-Inspur:,:rnNF251D-Inspur:" [lenovo_backlight] boardName = ":rnLXKT-ZXE-N70:,:rnLXKT-ZXEG-N6:" [iic-white-list] boardName = "" [pci-white-list] boardName = "" [sata-white-list] boardName = "" ukui-power-manager-4.0.0.1/PowerManagementDaemon/resources/org.ukui.power-manager.gschema.xml0000664000175000017500000005114014601232446030703 0ustar fengfeng 'suspend' Whether to hibernate, suspend or do nothing when inactive The type of sleeping that should be performed when the computer is inactive. 'suspend' Battery critical low action The action to take when the battery is critically low. true If the battery event should occur when the lid is shut and the power disconnected If the battery lid close event should occur (for example 'Suspend when lid closed on battery') when the lid is previously shut and the AC power disconnected at a later time. 'suspend' Whether to hibernate, suspend or do nothing when inactive The type of sleeping that should be performed when the computer is inactive. 'shutdown' UPS critical low action The action to take when the UPS is critically low. 'hibernate' UPS low power action The action to take when the UPS is low. true Allow backlight brightness adjustment If the screen brightness should be changed when switching between AC and battery power. true Reduce the backlight brightness when on battery power If the screen should be reduced in brightness when the computer is on battery power. true Reduce the keyboard backlight when on battery power If the keyboard backlight brightness should be reduced when the computer is on battery power 100 Keyboard backlight brightness when on AC power. Percent brightness to set keyboard backlight at when on AC power. Legal values are between 0 and 100. 50 Percent to reduce keyboard backlight by when on battery power. The percentage to reduce the keyboard backlight by when on battery power. For example, if set to '60', the backlight will be cut by 40% on battery power. Legal values are between 0 and 100. 75 Percent to reduce keyboard backlight by when idle. The percentage to reduce the keyboard backlight by when idle. For example, if set to '60', the backlight will be cut by 40% when idle. Legal values are between 0 and 100. 100 The brightness of the screen when idle This is the laptop panel screen brightness used when the session is idle. Only valid when use-time-for-policy is true. true Dim the screen after a period of inactivity when on battery power If the screen should be dimmed to save power when the computer is idle when on battery power. 60 The default amount of time to dim the screen after idle The default amount of time to dim the screen after idle. 50 LCD dimming amount when on battery The amount to dim the brightness of the display when on battery power. Possible values are between 0 and 100. false Dim the screen after a period of inactivity when on AC power If the screen should be dimmed to save power when the computer is idle when on AC power. 'off' Method used to blank screen on AC The DPMS method used to blank the screen when on AC power. 'off' Method used to blank screen on battery The DPMS method used to blank the screen when on battery power. -1.0 LCD brightness when on AC The brightness of the display when on AC power. Possible values are between 0.0 and 100.0. 100.0 LCD brightness when on BAT The brightness of the display when on BAT power. Possible values are between 0.0 and 100.0. 'suspend' Suspend button action The action to take when the system suspend button is pressed. 'hibernate' Hibernate button action The action to take when the system hibernate button is pressed. 'interactive' Power button action The action to take when the system power button is pressed. 'suspend' Laptop lid close action on battery The action to take when the laptop lid is closed and the laptop is on battery power. 'suspend' Laptop lid close action when on AC The action to take when the laptop lid is closed and the laptop is on AC power. true Whether to use time-based notifications If time based notifications should be used. If set to false, then the percentage change is used instead, which may fix a broken ACPI BIOS. false Check CPU load before sleeping If the CPU load should be checked before doing the idle action. false Whether NetworkManager should be connected and disconnected on sleep. Whether NetworkManager should disconnect before suspending or hibernating and connect on resume. true Use ukui-screensaver lock setting Whether to use the screen lock setting of ukui-screensaver to decide if the screen is locked after a hibernate, suspend or blank screen. true Lock screen when blanked Whether the screen is locked when the screen is turned off. Only used if lock-use-screensaver is false. true Lock screen on suspend Whether the screen is locked when the computer wakes up from a suspend. Only used if lock-use-screensaver is false. true Lock screen on hibernate Whether the screen is locked when the computer wakes up from a hibernate. Only used if lock-use-screensaver is false. false Lock GNOME keyring on sleep Whether the GNOME keyring is locked before the computer enters suspend. This means the keyring will have to be unlocked on resume. true Lock GNOME keyring on sleep Whether the GNOME keyring is locked before the computer enters hibernate. This means the keyring will have to be unlocked on resume. true If we should show the low capacity warning for a broken battery If we should show the low capacity warning for a broken battery. true Notify when AC adapter is disconnected If the user should be notified when the AC adapter is disconnected. false Notify when fully charged If a notification message should be displayed when the battery is fully charged. true Notify on a sleep failure If a notification message should be displayed after suspend or hibernate failed. '' The URI to show to the user on sleep failure When sleep fails we can show the user a button to help fix the situation. Leave this blank if the button should not be shown. true Notify on a low power If a notification message should be displayed when the battery is getting low. true Whether we should show the history data points Whether we should show the history data points in the statistics window. true Whether we should smooth the history data Whether we should smooth the history data in the graph. 'power' The default graph type to show for history The default graph type to show in the history window. 21600 The maximum time displayed for history The maximum duration of time displayed on the x-axis of the history graph. true Whether we should show the stats data points Whether we should show the stats data points in the statistics window. true Whether we should smooth the stats data Whether we should smooth the stats data in the graph. 'power' The default graph type to show for stats The default graph type to show in the stats window. 0 The index of the page number to show by default The index of the page number to show by default which is used to return focus to the correct page. '' The ID of the last device selected The identifier of the last device which is used to return focus to the correct device. 20 Percentage considered low The percentage of the battery when it is considered low. Only valid when use-time-for-policy is false. 10 Percentage considered critical The percentage of the battery when it is considered critical. Only valid when use-time-for-policy is false. 5 Percentage action is taken The percentage of the battery when the critical action is performed. Only valid when use-time-for-policy is false. 1200 The time remaining when low The time remaining in seconds of the battery when it is considered low. Only valid when use-time-for-policy is true. 300 The time remaining when critical The time remaining in seconds of the battery when it is considered critical. Only valid when use-time-for-policy is true. 120 The time remaining when action is taken The time remaining in seconds of the battery when critical action is taken. Only valid when use-time-for-policy is true. 900 Sleep timeout computer when on battery The amount of time in seconds the computer on battery power needs to be inactive before it goes to sleep. 900 Sleep timeout computer when on AC The amount of time in seconds the computer on AC power needs to be inactive before it goes to sleep. 0 Sleep timeout computer when on UPS The amount of time in seconds the computer on UPS power needs to be inactive before it goes to sleep. 600 Sleep timeout display when on AC The amount of time in seconds before the display goes to sleep when the computer is on AC power. 600 Sleep timeout display when on battery The amount of time in seconds the computer on battery power needs to be inactive before the display goes to sleep. 600 Sleep timeout display when on UPS The amount of time in seconds the computer on UPS power needs to be inactive before the display goes to sleep. true If sounds should be used If sounds should be used when the power is critically low, or inhibit requests have stopped the policy action. true If preferences and statistics items should be shown in the context menu false If power policy mode should be auto switched when plugged in and out false If power policy mode should be auto switched when plugged in and out 2 power policy mode 0 power policy current 0 power policy current 3 power policy current false battery save switch false power policy current false power policy current 1 power policy current 1 power policy current 'present' When to show the notification icon Display options for the notification icon. false init power manager config false Adjust the power mode strategy based on local mainline information ukui-power-manager-4.0.0.1/PowerManagementDaemon/upm_powerchanged.h0000664000175000017500000000207714601232446023740 0ustar fengfeng/* * Copyright (C) 2023, KylinSoft Co., Ltd. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . * */ #ifndef UPM_POWERCHANGED_H #define UPM_POWERCHANGED_H #include #include "common.h" class UpmPowerChanged : public QObject { Q_OBJECT public: explicit UpmPowerChanged(QObject *parent = nullptr); private: void setPowerModePolicy(); void setBatteryModePolicy(); private slots: void dealAcOnlineStateChanged(int, bool); }; #endif // UPM_POWERCHANGED_H ukui-power-manager-4.0.0.1/PowerManagementDaemon/upm_systemidle.cpp0000664000175000017500000002036614601232446024010 0ustar fengfeng/* * Copyright (C) 2023, KylinSoft Co., Ltd. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . * */ #include "upm_systemidle.h" UpmSystemIdle::UpmSystemIdle(QObject *parent) : QObject(parent) { QStringList valueRange = {QString::number(300), QString::number(600), QString::number(900), QString::number(1800), QString::number(3600), QString::number(7200), QString::number(10800), QString::number(-1)}; m_turnoffDisplayAc = UpmCheckConfig::checkConfig( GSETTINGS_KEY_SLEEP_DISPLAY_AC, DEFAULE_SLEEP_DISPLAY_TIME, QVariant::Int, valueRange, false).toInt(); m_turnoffDisplayBattery = UpmCheckConfig::checkConfig( GSETTINGS_KEY_SLEEP_DISPLAY_BATTERY, DEFAULE_SLEEP_DISPLAY_TIME, QVariant::Int, valueRange, false).toInt(); m_systemSuspendAc = UpmCheckConfig::checkConfig( GSETTINGS_KEY_SLEEP_COMPUTER_AC, DEFAULE_SLEEP_COMPUTER_TIME, QVariant::Int, valueRange, false).toInt(); m_systemSuspendBattery = UpmCheckConfig::checkConfig( GSETTINGS_KEY_SLEEP_COMPUTER_BATTERY, DEFAULE_SLEEP_COMPUTER_TIME, QVariant::Int, valueRange, false).toInt(); connect(UpmGsettings::self(), &UpmGsettings::sleepDisplayAcChanged, this, [=](QVariant value) { m_turnoffDisplayAc = value.toInt(); UpmControlDBus::self()->setUpmSystemConfig(GSETTINGS_KEY_SLEEP_DISPLAY_AC, QString::number(m_turnoffDisplayAc)); }); connect(UpmGsettings::self(), &UpmGsettings::sleepDisplayBatteryChanged, this, [=](QVariant value) { m_turnoffDisplayBattery = value.toInt(); UpmControlDBus::self()->setUpmSystemConfig(GSETTINGS_KEY_SLEEP_DISPLAY_BATTERY, QString::number(m_turnoffDisplayBattery)); }); connect(UpmGsettings::self(), &UpmGsettings::sleepComputerAcChanged, this, [=](QVariant value) { m_systemSuspendAc = value.toInt(); UpmControlDBus::self()->setUpmSystemConfig(GSETTINGS_KEY_SLEEP_COMPUTER_AC, QString::number(m_systemSuspendAc)); }); connect(UpmGsettings::self(), &UpmGsettings::sleepComputerBatteryChanged, this, [=](QVariant value) { m_systemSuspendBattery = value.toInt(); UpmControlDBus::self()->setUpmSystemConfig(GSETTINGS_KEY_SLEEP_COMPUTER_BATTERY, QString::number(m_systemSuspendBattery)); }); connect(UpmCommonDBus::self(), &UpmCommonDBus::systemSleepStatus, this, &UpmSystemIdle::stopTimer); connect(UpmCommonDBus::self(), &UpmCommonDBus::systemIdleStatus, this, &UpmSystemIdle::dealSystemIdleStatus); m_turnOffDisplayTimer = new QTimer(this); connect(m_turnOffDisplayTimer, &QTimer::timeout, this, &UpmSystemIdle::dealTurnOffDisplay); m_systemSuspendTimer = new QTimer(this); connect(m_systemSuspendTimer, &QTimer::timeout, this, &UpmSystemIdle::dealSystemSuspend); m_reduceBrightnessTimer = new QTimer(this); connect(m_reduceBrightnessTimer, &QTimer::timeout, this, &UpmSystemIdle::dealReduceBrightness); } void UpmSystemIdle::dealSystemIdleStatus(bool systemIdle) { int turnOffDisplayTime = getTurnOffDisplayTime(); int systemSuspendTime = getSystemSuspendTime(); int reduceBrightness = -1; QVariant value; qDebug() << "system enter idle:" << systemIdle; if (true == systemIdle) { if (turnOffDisplayTime > 0) { m_turnOffDisplayTimer->start(turnOffDisplayTime * 1000); } else { qDebug() << "turn off display timer not started!"; } if (systemSuspendTime > 0) { m_systemSuspendTimer->start(systemSuspendTime * 1000); } else { qDebug() << "system suspend timer not started!"; } if (turnOffDisplayTime > 0) { reduceBrightness = turnOffDisplayTime - 10; m_reduceBrightnessTimer->start(reduceBrightness * 1000); qDebug() << "reduce brightness time:" << reduceBrightness; } if (true == UpmUpowerDBus::self()->getAcOnlineState()) { if (true == UpmGsettings::self()->getGsettingsConfig( GSETTINGS_KEY_POWER_POLICY_AC, value)) { if (power_policy_balance == value.toInt()) { UpmControlDBus::self()->controlPowerManagement( UPM_DBUS_METHOD_SET_GPU_POLICY, power_policy_powersave); } } } else { if (true == UpmGsettings::self()->getGsettingsConfig( GSETTINGS_KEY_POWER_POLICY_BATTERY, value)) { if (power_policy_balance == value.toInt()) { UpmControlDBus::self()->controlPowerManagement( UPM_DBUS_METHOD_SET_GPU_POLICY, power_policy_powersave); } } } } else { stopTimer(); emit brightnessControlSignal(INCREASE_BRIGHTNESS); if (true == UpmUpowerDBus::self()->getAcOnlineState()) { if (true == UpmGsettings::self()->getGsettingsConfig( GSETTINGS_KEY_POWER_POLICY_AC, value)) { if (power_policy_balance == value.toInt()) { UpmControlDBus::self()->controlPowerManagement( UPM_DBUS_METHOD_SET_GPU_POLICY, power_policy_balance); } } } else { if (true == UpmGsettings::self()->getGsettingsConfig( GSETTINGS_KEY_POWER_POLICY_BATTERY, value)) { if (power_policy_balance == value.toInt()) { UpmControlDBus::self()->controlPowerManagement( UPM_DBUS_METHOD_SET_GPU_POLICY, power_policy_balance); } } } } } int UpmSystemIdle::getTurnOffDisplayTime() { int turnOffDisplayTime = 0; if (true == UpmUpowerDBus::self()->getAcOnlineState()) { turnOffDisplayTime = m_turnoffDisplayAc - m_enterIdleTime; } else { turnOffDisplayTime = m_turnoffDisplayBattery - m_enterIdleTime; } return turnOffDisplayTime; } int UpmSystemIdle::getSystemSuspendTime() { int systemSuspendTime = 0; if (true == UpmUpowerDBus::self()->getAcOnlineState()) { systemSuspendTime = m_systemSuspendAc - m_enterIdleTime; } else { systemSuspendTime = m_systemSuspendBattery - m_enterIdleTime; } return systemSuspendTime; } void UpmSystemIdle::dealTurnOffDisplay() { UpmControlDBus::self()->delayLockScreen("idle"); UpmControlDBus::self()->controlDisplay("off"); UpmControlDBus::self()->turnOffDisplaySignal(); m_turnOffDisplayTimer->stop(); } void UpmSystemIdle::dealSystemSuspend() { UpmControlDBus::self()->controlPowerManagement("Suspend", 0, false); m_systemSuspendTimer->stop(); } void UpmSystemIdle::dealReduceBrightness() { emit brightnessControlSignal(REDUCE_BRIGHTNESS); m_reduceBrightnessTimer->stop(); } void UpmSystemIdle::stopTimer() { qDebug() << "stop timer"; if (m_turnOffDisplayTimer->isActive()) { m_turnOffDisplayTimer->stop(); } if (m_systemSuspendTimer->isActive()) { m_systemSuspendTimer->stop(); } if (m_reduceBrightnessTimer->isActive()) { m_reduceBrightnessTimer->stop(); } } ukui-power-manager-4.0.0.1/PowerManagementDaemon/upm_lid.h0000664000175000017500000000274614601232446022045 0ustar fengfeng/* * Copyright (C) 2023, KylinSoft Co., Ltd. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . * */ #ifndef UPM_LID_H #define UPM_LID_H #include #include "common.h" class UpmLid : public QObject { Q_OBJECT public: explicit UpmLid(QObject *parent = nullptr); typedef void (UpmLid::*pCloseLidActionFun)(void); private: bool m_lidIsClosed; bool m_displayIsOn; QString m_closeLidActionAc; QString m_closeLidActionBattery; QMap m_closeLidActionFun; void initLidActionFun(); void addLidActionFun(const QString &action, pCloseLidActionFun actionFun); void closeLidNothingToDo(); void closeLidTurnOffDisplay(); void closeLidToSuspend(); void closeLidToShutdown(); void closeLidToHibernate(); private slots: void dealLidStateChanged(bool); void dealSystemSleepStatus(bool); }; #endif // UPM_LID_H ukui-power-manager-4.0.0.1/PowerManagementDaemon/upm_daemon.h0000664000175000017500000000344314601232446022533 0ustar fengfeng/* * Copyright (C) 2023, KylinSoft Co., Ltd. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . * */ #ifndef UPM_DAEMON_H #define UPM_DAEMON_H #include #include #include "common.h" #include "upm_brightness.h" #include "upm_systemidle.h" #include "upm_powerchanged.h" #include "upm_lid.h" #include "upm_lowpower.h" #include "upm_externalinterface.h" class UpmDaemon : public QObject { Q_OBJECT public: explicit UpmDaemon(QObject *parent = nullptr); private: UpmBrightness *m_brightness; UpmSystemIdle *m_systemIdle; UpmPowerChanged *m_powerChanged; UpmLid *m_lid; UpmLowPower *m_lowPower; int m_powerPolicyAc; int m_powerPolicyBattery; int m_powerPolicyBatteryBackup; QLocalSocket *m_socket; void initAcpiSocket(); UpmExternalInterface *m_externalInterface; void registerExternalInterface(); private slots: void dealPowerPolicyAcChanged(QVariant value); void dealPowerPolicyBatteryChanged(QVariant value); void dealPowerPolicyBatteryBackupChanged(QVariant value); void dealBrightnessControlSignal(int action); void dealSystemConfigChanged(const QString, const QString, const QString); }; #endif // UPM_DAEMON_H ukui-power-manager-4.0.0.1/PowerManagementDaemon/upm_checkconfig.h0000664000175000017500000000250114601232446023525 0ustar fengfeng/* * Copyright (C) 2023, KylinSoft Co., Ltd. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . * */ #ifndef UPM_CHECKCONFIG_H #define UPM_CHECKCONFIG_H #include #include "common.h" class UpmCheckConfig : public QObject { Q_OBJECT public: explicit UpmCheckConfig(QObject *parent = nullptr); typedef bool (UpmCheckConfig::*pCheckConfigFun)(const QString &, const QStringList &); static QVariant checkConfig(const QString &, QVariant, QVariant::Type, const QStringList &, bool); private: static bool checkSystemConfigValue(const QString &, const QStringList &, bool); static bool checkGsettingsConfigValue(QVariant &, QVariant::Type, const QStringList &, bool); signals: }; #endif // UPM_CHECKCONFIG_H ukui-power-manager-4.0.0.1/PowerManagementDaemon/main.cpp0000664000175000017500000000235114601232446021663 0ustar fengfeng/* * Copyright 2023 KylinSoft Co., Ltd. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ #include //#include #include "upm_daemon.h" #include "upmpreprocessor.h" int main(int argc, char *argv[]) { // initUkuiLog4qt("ukui-powermanagement"); QApplication a(argc, argv); QTranslator translator; if (translator.load(QLocale(), "ukui-power-manager-daemon", "_", QM_FILES_INSTALL_PATH)) { a.installTranslator(&translator); } else { qDebug() << "load ukui-power-manager-tray qm file error"; } UpmPreprocessor upp; upp.start(); UpmDaemon upmDaemon; return a.exec(); } ukui-power-manager-4.0.0.1/PowerManagementDaemon/PowerManagementDaemon.pro0000664000175000017500000000660314601232446025176 0ustar fengfengQT += core gui dbus network greaterThan(QT_MAJOR_VERSION, 4): QT += widgets TARGET = ukui-powermanagement CONFIG += c++11 link_pkgconfig PKGCONFIG += gsettings-qt exists(/usr/include/kysdk/kysdk-system/libkysysinfo.h) { DEFINES += KY_SDK_SYSINFO PKGCONFIG += kysdk-sysinfo } //LIBS += -lukui-log4qt # The following define makes your compiler emit warnings if you use # any Qt feature that has been marked deprecated (the exact warnings # depend on your compiler). Please consult the documentation of the # deprecated API in order to know how to port your code away from it. DEFINES += QT_DEPRECATED_WARNINGS # You can also make your code fail to compile if it uses deprecated APIs. # In order to do so, uncomment the following line. # You can also select to disable deprecated APIs only up to a certain version of Qt. #DEFINES += QT_DISABLE_DEPRECATED_BEFORE=0x060000 # disables all the APIs deprecated before Qt 6.0.0 TRANSLATIONS+=\ translations/ukui-power-manager-daemon_bo_CN.ts \ translations/ukui-power-manager-daemon_zh_CN.ts \ translations/ukui-power-manager-daemon_tr.ts QM_FILES_INSTALL_PATH = /usr/share/ukui-power-manager/daemon/translations/ # CONFIG += lrelase not work for qt5.6, add those from lrelease.prf for compatibility qtPrepareTool(QMAKE_LRELEASE, lrelease) lrelease.name = lrelease lrelease.input = TRANSLATIONS lrelease.output = ${QMAKE_FILE_IN_BASE}.qm lrelease.commands = $$QMAKE_LRELEASE ${QMAKE_FILE_IN} -qm ${QMAKE_FILE_OUT} lrelease.CONFIG = no_link QMAKE_EXTRA_COMPILERS += lrelease PRE_TARGETDEPS += compiler_lrelease_make_all for (translation, TRANSLATIONS) { translation = $$basename(translation) QM_FILES += $$OUT_PWD/$$replace(translation, \\..*$, .qm) } qm_files.files = $$QM_FILES qm_files.path = $$QM_FILES_INSTALL_PATH qm_files.CONFIG = no_check_exist INSTALLS += qm_files DEFINES += QM_FILES_INSTALL_PATH='\\"$${QM_FILES_INSTALL_PATH}\\"' include($$PWD/../common/common.pri) SOURCES += \ main.cpp \ upm-common-dbus/upm_commondbus.cpp \ upm-control-dbus/upm_controldbus.cpp \ upm-gsettings/upm_gsettings.cpp \ upm-upower-dbus/upm_upowerdbus.cpp \ upm-upower-dbus/upowerbatterydbus.cpp \ upm-upower-dbus/upowerdbus.cpp \ upm-upower-dbus/upowerlinepowerdbus.cpp \ upm_brightness.cpp \ upm_checkconfig.cpp \ upm_daemon.cpp \ upm_externalinterface.cpp \ upm_lid.cpp \ upm_lowpower.cpp \ upm_powerchanged.cpp \ upm_systemidle.cpp HEADERS += \ common.h \ upm-common-dbus/upm_commondbus.h \ upm-control-dbus/upm_controldbus.h \ upm-gsettings/upm_gsettings.h \ upm-upower-dbus/upm_upowerdbus.h \ upm-upower-dbus/upowerbatterydbus.h \ upm-upower-dbus/upowerdbus.h \ upm-upower-dbus/upowerlinepowerdbus.h \ upm_brightness.h \ upm_checkconfig.h \ upm_daemon.h \ upm_externalinterface.h \ upm_lid.h \ upm_lowpower.h \ upm_powerchanged.h \ upm_systemidle.h # Default rules for deployment. qnx: target.path = /tmp/usr/bin else: unix:!android: target.path = /usr/bin !isEmpty(target.path): INSTALLS += target desktop.files += resources/ukui-powermanagement-daemon.desktop desktop.path = /etc/xdg/autostart/ INSTALLS += desktop conf.files += resources/org.ukui.power-manager.gschema.xml conf.path=/usr/share/glib-2.0/schemas/ INSTALLS += conf upmConf.files += resources/upm-global.conf upmConf.path = /etc/ukui/ukui-power-manager INSTALLS += upmConf ukui-power-manager-4.0.0.1/PowerManagementDaemon/upm_externalinterface.cpp0000664000175000017500000000417314601232446025327 0ustar fengfeng/* * Copyright (C) 2023, KylinSoft Co., Ltd. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . * */ #include "upm_externalinterface.h" UpmExternalInterface::UpmExternalInterface(QObject *parent) : QObject(parent) { connect(UpmGsettings::self(), &UpmGsettings::batterySaveSwitchChanged, this, &UpmExternalInterface::dealBatterySaveSwitchChanged); connect(UpmUpowerDBus::self(), &UpmUpowerDBus::acOnlineStateChanged, this, &UpmExternalInterface::dealAcOnlineStateChanged); } void UpmExternalInterface::dealBatterySaveSwitchChanged(QVariant) { QStringList batterySaver = {"batterySaver"}; emit PowerConfigChanged(batterySaver); } void UpmExternalInterface::dealAcOnlineStateChanged(int index, bool value) { Q_UNUSED(index) Q_UNUSED(value) QStringList batterySaver = {"batterySaver"}; emit PowerConfigChanged(batterySaver); } void UpmExternalInterface::SetBatterySaver(const int value) { if (1 == value) { UpmGsettings::self()->setGsettingsConfig(GSETTINGS_KEY_BATTERY_SAVE_SWITCH, true); } else { UpmGsettings::self()->setGsettingsConfig(GSETTINGS_KEY_BATTERY_SAVE_SWITCH, false); } } int UpmExternalInterface::GetBatterySaver() { if (true == UpmUpowerDBus::self()->getAcOnlineState()) { return batterySaverUnavailable; } QVariant value; if (true == UpmGsettings::self()->getGsettingsConfig(GSETTINGS_KEY_BATTERY_SAVE_SWITCH, value)) { if (true == value.toBool()) { return batterySaverOn; } } return batterySaverOff; } ukui-power-manager-4.0.0.1/PowerManagementDaemon/upm_lowpower.cpp0000664000175000017500000002424514601232446023504 0ustar fengfeng/* * Copyright (C) 2023, KylinSoft Co., Ltd. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . * */ #include "upm_lowpower.h" UpmLowPower::UpmLowPower(QObject *parent) : QObject(parent) { QStringList valueRange = {QString::number(10), QString::number(20), QString::number(30), QString::number(40)}; m_percentageLow = UpmCheckConfig::checkConfig( GSETTINGS_KEY_PERCENTAGE_LOW, DEFAULE_PERCENTAGE_LOW, QVariant::Int, valueRange, false).toInt(); valueRange.clear(); valueRange << QString::number(5) << QString::number(9); m_percentageAction = UpmCheckConfig::checkConfig( GSETTINGS_KEY_PERCENTAGE_ACTION, DEFAULE_PERCENTAGE_ACTION, QVariant::Int, valueRange, true).toInt(); valueRange.clear(); valueRange << UPM_POWER_ACTION_NOTHING << UPM_POWER_ACTION_HIBERNATE << UPM_POWER_ACTION_SHUTDOWN; UpmCheckConfig::checkConfig( GSETTINGS_KEY_ACTION_CRITICAL_BATTERY, UPM_POWER_ACTION_HIBERNATE, QVariant::String, valueRange, false); valueRange.clear(); valueRange << "true" << "false"; m_enableBatterySaver = UpmCheckConfig::checkConfig( GSETTINGS_KEY_BATTERY_SAVE_SWITCH, false, QVariant::Bool, valueRange, false).toBool(); m_autoEnableBatterySaver = UpmCheckConfig::checkConfig( GSETTINGS_KEY_LOW_BATTERY_AUTO_SAVE, false, QVariant::Bool, valueRange, false).toBool(); m_enableReduceBrightness = UpmCheckConfig::checkConfig( GSETTINGS_KEY_BATTERY_SAVE_REDUCE_BRIGHTNESS, false, QVariant::Bool, valueRange, false).toBool(); connect(UpmGsettings::self(), &UpmGsettings::percentageLowChanged, this, &UpmLowPower::dealPercentageLowChanged); connect(UpmGsettings::self(), &UpmGsettings::percentageActionChanged, this, &UpmLowPower::dealPercentageActionChanged); connect(UpmGsettings::self(), &UpmGsettings::actionCriticalBatteryChanged, this, [=](QVariant value) { UpmControlDBus::self()->setUpmSystemConfig(GSETTINGS_KEY_ACTION_CRITICAL_BATTERY, value.toString()); }); connect(UpmGsettings::self(), &UpmGsettings::batterySaveSwitchChanged, this, &UpmLowPower::dealBatterySaveSwitchChanged); connect(UpmGsettings::self(), &UpmGsettings::lowBatteryAutoSaveChanged, this, &UpmLowPower::dealLowBatteryAutoSaveChanged); connect(UpmGsettings::self(), &UpmGsettings::batterySaveReduceBrightnessChanged, this, &UpmLowPower::dealBatterySaveReduceBrightnessChanged); connect(UpmUpowerDBus::self(), &UpmUpowerDBus::acOnlineStateChanged, this, &UpmLowPower::dealAcOnlineStateChanged); connect(UpmUpowerDBus::self(), &UpmUpowerDBus::batteryInfoChanged, this, &UpmLowPower::dealBatteryInfoChanged); if (true == UpmUpowerDBus::self()->getAcOnlineState()) { UpmGsettings::self()->setGsettingsConfig(GSETTINGS_KEY_BATTERY_SAVE_SWITCH, false); } else { if (true == m_enableBatterySaver) { UpmGsettings::self()->setGsettingsConfig(GSETTINGS_KEY_BATTERY_SAVE_SWITCH, true); } } } int UpmLowPower::getPowerPolicyBattery(const QString &configName) { QVariant value; if (true == UpmGsettings::self()->getGsettingsConfig(configName, value)) { return value.toInt(); } else { return power_policy_unknown; } } void UpmLowPower::setUpmSystemConfig(const QString &key, bool value) { if (true == value) { UpmControlDBus::self()->setUpmSystemConfig(key, "true"); } else { UpmControlDBus::self()->setUpmSystemConfig(key, "false"); } } void UpmLowPower::dealPercentageLowChanged(QVariant value) { m_percentageLow = value.toInt(); UpmControlDBus::self()->setUpmSystemConfig(GSETTINGS_KEY_PERCENTAGE_LOW, QString::number(m_percentageLow)); double percentage = UpmUpowerDBus::self()->getBatteryPercentage(); if (false == m_batteryLowState) { if (m_percentageLow >= percentage && percentage > m_percentageAction) { m_batteryLowState = true; m_notificationId = UpmCommonDBus::self()->sendNotification( tr("Low battery notification"), tr("The system enters a low battery state"), true); // UpmCommonDBus::self()->playSystemSound(BATTERY_LOW); if (true == m_autoEnableBatterySaver) { UpmGsettings::self()->setGsettingsConfig(GSETTINGS_KEY_BATTERY_SAVE_SWITCH, true); } emit percentageLowSignal(true); } } else { if (percentage > m_percentageLow) { batteryPercentageRecoveryAction(); } } } void UpmLowPower::dealPercentageActionChanged(QVariant value) { m_percentageAction = value.toInt(); UpmControlDBus::self()->setUpmSystemConfig(GSETTINGS_KEY_PERCENTAGE_ACTION, QString::number(m_percentageAction)); } void UpmLowPower::dealBatterySaveSwitchChanged(QVariant value) { int policy = power_policy_unknown; m_enableBatterySaver = value.toBool(); setUpmSystemConfig(GSETTINGS_KEY_BATTERY_SAVE_SWITCH, m_enableBatterySaver); if (true == m_enableBatterySaver) { policy = getPowerPolicyBattery(GSETTINGS_KEY_POWER_POLICY_BATTERY); UpmGsettings::self()->setGsettingsConfig( GSETTINGS_KEY_POWER_POLICY_BATTERY_BACKUP, policy); UpmGsettings::self()->setGsettingsConfig( GSETTINGS_KEY_POWER_POLICY_BATTERY, power_policy_powersave); if (true == m_enableReduceBrightness) { UpmControlDBus::self()->controlPowerManagement( UPM_DBUS_METHOD_SET_REDUCE_BACKLIGHT_SWITCH, true); } } else { policy = getPowerPolicyBattery(GSETTINGS_KEY_POWER_POLICY_BATTERY_BACKUP); UpmGsettings::self()->setGsettingsConfig(GSETTINGS_KEY_POWER_POLICY_BATTERY_BACKUP, power_policy_unknown); if (power_policy_powersave != policy) { UpmGsettings::self()->setGsettingsConfig(GSETTINGS_KEY_POWER_POLICY_BATTERY, policy); } if (true == m_enableReduceBrightness) { UpmControlDBus::self()->controlPowerManagement( UPM_DBUS_METHOD_SET_REDUCE_BACKLIGHT_SWITCH, false); } } } void UpmLowPower::dealLowBatteryAutoSaveChanged(QVariant value) { m_autoEnableBatterySaver = value.toBool(); setUpmSystemConfig(GSETTINGS_KEY_LOW_BATTERY_AUTO_SAVE, m_autoEnableBatterySaver); if (true == m_enableBatterySaver) { return ; } if (true == m_autoEnableBatterySaver && true == m_batteryLowState) { UpmGsettings::self()->setGsettingsConfig(GSETTINGS_KEY_BATTERY_SAVE_SWITCH, true); } } void UpmLowPower::dealBatterySaveReduceBrightnessChanged(QVariant value) { m_enableReduceBrightness = value.toBool(); setUpmSystemConfig(GSETTINGS_KEY_BATTERY_SAVE_REDUCE_BRIGHTNESS, m_enableReduceBrightness); if (false == m_enableReduceBrightness) { if (true == m_enableBatterySaver) { UpmControlDBus::self()->controlPowerManagement( UPM_DBUS_METHOD_SET_REDUCE_BACKLIGHT_SWITCH, false); } return ; } if (true == m_enableBatterySaver) { UpmControlDBus::self()->controlPowerManagement( UPM_DBUS_METHOD_SET_REDUCE_BACKLIGHT_SWITCH, true); } } bool UpmLowPower::getBatterySaveSwitch(void) { return m_enableBatterySaver; } bool UpmLowPower::getBatteryLowState(void) { return m_batteryLowState; } void UpmLowPower::batteryPercentageLowAction() { if (false == m_batteryLowState) { double percentage = UpmUpowerDBus::self()->getBatteryPercentage(); if (m_percentageLow >= percentage && percentage > m_percentageAction) { m_batteryLowState = true; m_notificationId = UpmCommonDBus::self()->sendNotification(tr("Low battery notification"), tr("The system enters a low battery state"), true); // UpmCommonDBus::self()->playSystemSound(BATTERY_LOW); if (true == m_autoEnableBatterySaver) { UpmGsettings::self()->setGsettingsConfig(GSETTINGS_KEY_BATTERY_SAVE_SWITCH, true); } emit percentageLowSignal(true); } } } void UpmLowPower::batteryPercentageRecoveryAction() { if (true == m_batteryLowState) { m_batteryLowState = false; UpmCommonDBus::self()->closeNotification(m_notificationId); m_notificationId = 0; if (true == m_enableBatterySaver) { UpmGsettings::self()->setGsettingsConfig(GSETTINGS_KEY_BATTERY_SAVE_SWITCH, false); } emit percentageLowSignal(false); } } void UpmLowPower::dealAcOnlineStateChanged(int index, bool acOnline) { qDebug() << "ac index:" << index << "ac online state :" << acOnline; if (true == UpmUpowerDBus::self()->getAcOnlineState()) { batteryPercentageRecoveryAction(); } else { batteryPercentageLowAction(); } } void UpmLowPower::dealBatteryInfoChanged(int index, QStringList batteryInfo) { qDebug() << "battery index:" << index << "battery online state :" << batteryInfo; if (false == UpmUpowerDBus::self()->getAcOnlineState()) { batteryPercentageLowAction(); } } ukui-power-manager-4.0.0.1/PowerManagementDaemon/upm_daemon.cpp0000664000175000017500000002024714601232446023067 0ustar fengfeng/* * Copyright (C) 2023, KylinSoft Co., Ltd. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . * */ #include "upm_daemon.h" static QStringList g_policyList = {"performance", "balance", "powersave"}; UpmDaemon::UpmDaemon(QObject *parent) : QObject(parent) { QStringList valueRange = {QString::number(0), QString::number(3)}; m_powerPolicyAc = UpmCheckConfig::checkConfig( GSETTINGS_KEY_POWER_POLICY_AC, power_policy_performance, QVariant::Int, valueRange, true).toInt(); if (true == UpmUpowerDBus::self()->getAcOnlineState()) { UpmControlDBus::self()->controlPowerManagement( UPM_DBUS_METHOD_SET_PC_POLICY, m_powerPolicyAc); } connect(UpmGsettings::self(), &UpmGsettings::powerPolicyAcChanged, this, &UpmDaemon::dealPowerPolicyAcChanged); m_brightness = new UpmBrightness(this); if (false == UpmCommonDBus::self()->isCloudPlatform()) { m_systemIdle = new UpmSystemIdle(this); connect(m_systemIdle, &UpmSystemIdle::brightnessControlSignal, this, &UpmDaemon::dealBrightnessControlSignal); } if (UpmUpowerDBus::self()->getBatteryNum() > 0) { m_powerPolicyBattery = UpmCheckConfig::checkConfig( GSETTINGS_KEY_POWER_POLICY_BATTERY, power_policy_performance, QVariant::Int, valueRange, true).toInt(); if (false == UpmUpowerDBus::self()->getAcOnlineState()) { UpmControlDBus::self()->controlPowerManagement( UPM_DBUS_METHOD_SET_PC_POLICY, m_powerPolicyBattery); } connect(UpmGsettings::self(), &UpmGsettings::powerPolicyBatteryChanged, this, &UpmDaemon::dealPowerPolicyBatteryChanged); m_powerPolicyBatteryBackup = UpmCheckConfig::checkConfig( GSETTINGS_KEY_POWER_POLICY_BATTERY_BACKUP, power_policy_unknown, QVariant::Int, valueRange, true).toInt(); connect(UpmGsettings::self(), &UpmGsettings::powerPolicyBatteryBackupChanged, this, &UpmDaemon::dealPowerPolicyBatteryBackupChanged); m_powerChanged = new UpmPowerChanged(this); m_lid = new UpmLid(this); m_lowPower = new UpmLowPower(this); } connect(UpmControlDBus::self(), &UpmControlDBus::systemConfigChangedSignal, this, &UpmDaemon::dealSystemConfigChanged); connect(UpmCommonDBus::self(), &UpmCommonDBus::userActiveSignal, UpmControlDBus::self(), &UpmControlDBus::setUserActive); initAcpiSocket(); registerExternalInterface(); } void UpmDaemon::dealSystemConfigChanged(const QString userName, const QString key, const QString value) { if (userName == UpmControlDBus::self()->getUserName()) { return ; } QVariant::Type type = UpmGsettings::self()->getValueType(key); switch (type) { case QVariant::Int: UpmGsettings::self()->setGsettingsConfig(key, value.toInt()); break; case QVariant::Bool: if ("true" == value) { UpmGsettings::self()->setGsettingsConfig(key, true); } else { UpmGsettings::self()->setGsettingsConfig(key, false); } break; case QVariant::String: UpmGsettings::self()->setGsettingsConfig(key, value); break; default: break; } } void UpmDaemon::initAcpiSocket() { m_socket = new QLocalSocket(this); connect(m_socket, &QLocalSocket::connected, this, [=]() { qDebug() << "acpi socket connected success"; }); connect(m_socket, &QLocalSocket::readyRead, this, [=]() { QByteArray data = m_socket->readAll(); QString str = QString(data).simplified(); qDebug() << "acpi signal is" << str; if (-1 != str.indexOf("thermal_zone LNXTHERM:00 000000f1 00000001", 0, Qt::CaseInsensitive)) { UpmControlDBus::self()->controlPowerManagement(UPM_DBUS_METHOD_SET_HIBERNATE, 0, false); } qDebug() << str.indexOf("thermal_zone LNXTHERM:00 000000f1 00000001", 0, Qt::CaseInsensitive); }); m_socket->connectToServer("/var/run/acpid.socket"); qDebug() << m_socket->state(); } void UpmDaemon::registerExternalInterface() { m_externalInterface = new UpmExternalInterface(this); QDBusConnection connection = QDBusConnection::sessionBus(); if (!connection.registerService("org.ukui.upower")) { qWarning() << "QDbus register service failed reason:" << connection.lastError(); return; } if (!connection.registerObject("/upower/PowerManager", m_externalInterface, QDBusConnection::ExportAllSlots | QDBusConnection::ExportAllSignals)) { qWarning() << "QDbus register object failed reason:" << connection.lastError(); } } void UpmDaemon::dealPowerPolicyAcChanged(QVariant value) { int policy = value.toInt(); switch (policy) { case power_policy_performance: case power_policy_balance: case power_policy_powersave: UpmControlDBus::self()->setUpmSystemConfig(GSETTINGS_KEY_POWER_POLICY_AC, QString::number(policy)); if (true == UpmUpowerDBus::self()->getAcOnlineState()) { UpmControlDBus::self()->controlPowerManagement(UPM_DBUS_METHOD_SET_PC_POLICY, policy); } qDebug() << "power policy on ac:" << g_policyList[policy]; break; default: qDebug() << "ac policy index error:" << policy; break; } } void UpmDaemon::dealPowerPolicyBatteryChanged(QVariant value) { int policy = value.toInt(); switch (policy) { case power_policy_performance: case power_policy_balance: case power_policy_powersave: UpmControlDBus::self()->setUpmSystemConfig(GSETTINGS_KEY_POWER_POLICY_BATTERY, QString::number(policy)); if (false == UpmUpowerDBus::self()->getAcOnlineState()) { UpmControlDBus::self()->controlPowerManagement(UPM_DBUS_METHOD_SET_PC_POLICY, policy); } qDebug() << "power policy on battery:" << g_policyList[policy]; if (true == m_lowPower->getBatterySaveSwitch() && policy != power_policy_powersave) { UpmGsettings::self()->setGsettingsConfig(GSETTINGS_KEY_BATTERY_SAVE_SWITCH, false); if (true == m_lowPower->getBatteryLowState()) { UpmGsettings::self()->setGsettingsConfig(GSETTINGS_KEY_LOW_BATTERY_AUTO_SAVE, false); } } break; default: qDebug() << "battery policy index error:" << policy; break; } } void UpmDaemon::dealPowerPolicyBatteryBackupChanged(QVariant value) { int policy = value.toInt(); switch (policy) { case power_policy_performance: case power_policy_balance: case power_policy_powersave: UpmControlDBus::self()->setUpmSystemConfig(GSETTINGS_KEY_POWER_POLICY_BATTERY_BACKUP, QString::number(policy)); qDebug() << "backup power policy on battery:" << g_policyList[policy]; break; default: qDebug() << "backup battery policy index error:" << policy; break; } } void UpmDaemon::dealBrightnessControlSignal(int action) { int percentage = m_brightness->getBrightnessPercentage(); switch (action) { case REDUCE_BRIGHTNESS: m_brightness->setBrightnessPercentage(percentage * 0.7); break; case INCREASE_BRIGHTNESS: m_brightness->setBrightnessPercentage(percentage); break; default: break; } qDebug() << "brightness control action :" << action; } ukui-power-manager-4.0.0.1/plugin-power/0000775000175000017500000000000014607363245016455 5ustar fengfengukui-power-manager-4.0.0.1/plugin-power/translations/0000775000175000017500000000000014601232446021166 5ustar fengfengukui-power-manager-4.0.0.1/plugin-power/translations/en_US.ts0000664000175000017500000002140114601232446022545 0ustar fengfeng Power Power General /Power/General Select power plan /Power/Select power plan Battery saving plan /Power/Battery saving plan Reduce the occupation of backend running program resources and ensure smooth operation of key and focus applications. Require password when sleep/hibernate Require password when hibernate Require password when sleep Password required when waking up the screen Press the power button Time to close display Time to sleep Notebook cover Dynamic resource scheduling Using power Using battery Open battery saving Automatically run saving mode when low battery Auto display brightness level Low battery notification Battery level is lower than Run interactive shutdown suspend hibernate 5min 10min 15min 30min 1h 2h never 3h nothing blank Balance Energy Efficiency Performance ukui-power-manager-4.0.0.1/plugin-power/translations/bo_CN.ts0000664000175000017500000002770214601232446022526 0ustar fengfeng Power Power སྟོབས་ཤུགས། The system will sleep before turning off the display མ་ལག་གི་སྒོ་རྒྱག་འཆར་ཆས་གོང་ལ་གཉིད་། Reduce the occupation of backend running program resources and ensure smooth operation of key and focus applications. རྒྱབ་སྟེགས་འཁོར་རྒྱུག་གོ་རིམ་གྱི་ཐོན་ཁུངས་བཟུང་སྤྱོད་ཉུང་དུ་གཏོང་བ།འགག་རྩའི་བཀོལ་སྤྱོད་དང་མདོ་གནད་བཀོལ་སྤྱོད་བདེ་བླག་ཡོང་བའི་འགན་ལེན་བཅས་བྱེད་དགོས།. Require password when sleep/hibernate གཉིད་དང་གཉིད།གཉིད།གཉིད་སད་པའི་རྗེས་ནས་གསང་གྲངས་ Require password when sleep གཉིད་ཉལ་སྐབས་གསང་གྲངས་དགོས་ Require password when hibernate གཉིད་ལས་བསད་པར་གསང་གྲངས་དགོས། Password required when waking up the screen བརྙན་ཤེལ་གཉིད་ལས་སད་སྐབས་མཁོ་བའི་གསང་གྲངས། Press the power button སྒུལ་ཤུགས་ཀྱི་མཐེབ་གཅུས་ Time to close display འགྲེམས་སྟོན་མཇུག་སྒྲིལ་བའི་དུས་ཚོད། Time to sleep གཉིད་ཉལ་བའི་དུས་ཚོད། Notebook cover ཟིན་བྲིས་ཀྱི་ཁེབས་རས། Dynamic resource scheduling ཐོན་ཁུངས་འགུལ་རྣམ་བཀོད་གཏོང་ Using power དབང་ཆ་བེད་སྤྱོད་བྱ་དགོས། Using battery གློག་སྨན་བཀོལ་སྤྱོད་བྱེད་པ། Time to darken མུན་ནག་ཏུ་འགྱུར་བའི་དུས་ཚོད། Battery level is lower than གློག་གཡིས་ཀྱི་ཆུ་ཚད་ལས་དམའ་བ། Run འཁོར་སྐྱོད་བྱེད་བཞིན་ Low battery notification གློག་གཡིས་ཀྱི་བརྡ་ཐོ་དམའ་བ། Automatically run saving mode when low battery གློག་གཡིས་དམའ་བའི་དུས་སུ་རང་འགུལ་གྱིས་གྲོན་ཆུང་བྱེད་ཐབས་ Automatically run saving mode when using battery གློག་གཡིས་བཀོལ་སྤྱོད་བྱེད་སྐབས་རང་འགུལ་གྱིས་གྲོན་ཆུང་བྱེད་སྟངས་བཀོལ Display remaining charging time and usage time དེ་བྱིངས་ཀྱི་གློག་གསོག་དུས་ཚོད་དང་བཀོལ་སྤྱོད་ཀྱི་དུས་ཚོད་མངོན་པར་བྱས་ཡོད། General སྤྱིར་བཏང་གི་གནས /Power/General Select power plan སྒུལ་ཤུགས་འཆར་གཞི་བདམས་པ། /Power/Select power plan Battery saving plan གློག་གཡིས་གྲོན་ཆུང་གི་འཆར་ /Power/Battery saving plan nothing ཅི་ཡང་མ་རེད། blank སྟོང་ཆ། shutdown ཁ་རྒྱག Open battery saving སྒོ་ཕྱེ་བའི་གློག་སྨན་གྲོན་ཆུང Auto display brightness level རང་འགུལ་གྱིས་མངོན་པའི་གསལ་ཚད་ཀྱི་ཆུ་ suspend གཉིད་ hibernate མངལ་གནས་སུ་སྦས་པ། interactive ཕན་ཚུན་སྐུལ་འདེད་ 5min 5སྐར་མ་ 10min 10སྐར་མ་ 15min 15སྐར་མ་ 30min 30སྐར་མ་ 1h 1ཆུ་ཚོད། 2h 2ཆུ་ཚོད། never གཏན་ནས་བྱེད་མི་ 3h 3ཆུ་ཚོད། Balance དོ་མཉམ། Energy Efficiency ཕན་འབྲས་ལེགས་ཤོས་ Performance མཆོག་གྱུར་གཤིས་ནུས། ukui-power-manager-4.0.0.1/plugin-power/translations/zh_CN.ts0000664000175000017500000002274214601232446022546 0ustar fengfeng Power Power 电源 The system will sleep before turning off the display 系统将在关闭显示器之前进入睡眠 Reduce the occupation of backend running program resources and ensure smooth operation of key and focus applications. 减少后台运行程序资源占用,保障关键应用与焦点应用流畅运行。 Require password when sleep/hibernate 睡眠/休眠后唤醒需要密码 Require password when sleep 睡眠后唤醒需要密码 Require password when hibernate 休眠后唤醒需要密码 Password required when waking up the screen 唤醒屏幕时需要密码 Press the power button 按电源键时执行 Time to close display 此时间段后关闭显示器 Time to sleep 此时间段后系统进入睡眠 Notebook cover 合上盖子时执行 Dynamic resource scheduling 资源动态调度 Using power 使用电源时 Using battery 使用电池时 Time to darken 此时间段后降低屏幕亮度 Battery level is lower than 电量低于 Run 时执行 Low battery notification 低电量时通知 Automatically run saving mode when low battery 低电量时自动开启节能模式 Automatically run saving mode when using battery 使用电池时自动开启节能模式 Display remaining charging time and usage time 显示剩余充电时间和剩余使用时间 General 通用 /Power/General Select power plan 电源计划 /Power/Select power plan Battery saving plan 电池节电计划 /Power/Battery saving plan nothing 无操作 blank 关闭显示器 shutdown 关机 Open battery saving 开启节电计划 Auto display brightness level 节电模式下自动降低屏幕亮度 suspend 睡眠 hibernate 休眠 interactive 询问 5min 5 分钟 10min 10 分钟 15min 15 分钟 30min 30 分钟 1h 1 小时 2h 2 小时 never 从不 3h 3 小时 Balance 平衡 Energy Efficiency 最佳能效 Performance 最佳性能 ukui-power-manager-4.0.0.1/plugin-power/powermacrodata.h0000664000175000017500000000531214601232446021627 0ustar fengfeng/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 2023 KylinSoft Co., Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. * */ #ifndef POWERMACRODATA_H #define POWERMACRODATA_H #define MACHINE_TYPE_ONLY_TABLET 2 #define MACHINE_TYPE_PC_AND_TABLET 3 #define POWER_SUPPLY_TYPE_BATTERY 2 #define FIXES 60 #define STYLE_FONT_SCHEMA "org.ukui.style" #define PROC_MANAGER "org.ukui.process-manager" #define RESOURCE_LIMIT_ENABLE "resourceLimitEnable" #define SCREENSAVER_SCHEMA "org.ukui.screensaver" #define SLEEP_ACTIVATION_ENABLED "sleepActivationEnabled" #define CLOSE_ACTIVATION_ENABLED "closeActivationEnabled" #define POWER_MANAGER_SETTINGS "org.ukui.power-manager" //按电源键时执行 #define GSETTINGS_KEY_BUTTON_POWER "buttonPower" //空闲关闭显示器 #define GSETTINGS_KEY_SLEEP_DISPLAY_AC "sleepDisplayAc" #define GSETTINGS_KEY_SLEEP_DISPLAY_BATTERY "sleepDisplayBattery" //空闲睡眠 #define GSETTINGS_KEY_SLEEP_COMPUTER_AC "sleepComputerAc" #define GSETTINGS_KEY_SLEEP_COMPUTER_BATTERY "sleepComputerBattery" //盒盖事件触发操作 #define GSETTINGS_KEY_BUTTON_LID_AC "buttonLidAc" #define GSETTINGS_KEY_BUTTON_LID_BATTERY "buttonLidBattery" //电源策略(0:节能 1:平衡 2:性能) #define GSETTINGS_KEY_POWER_POLICY_AC "powerPolicyAc" #define GSETTINGS_KEY_POWER_POLICY_BATTERY "powerPolicyBattery" //开启节能模式 #define GSETTINGS_KEY_BATTERY_SAVE_SWITCH "batterySaveSwitch" //低电量时自动开启节能模式 #define GSETTINGS_KEY_LOW_BATTERY_AUTO_SAVE "lowBatteryAutoSave" //节能模式降低亮度 #define GSETTINGS_KEY_BATTERY_SAVE_REDUCE_BRIGHTNESS "batterySaveReduceBrightness" //低电量百分百通知 #define GSETTINGS_KEY_PERCENTAGE_LOW "percentageLow" //极低电量 #define GSETTINGS_KEY_PERCENTAGE_ACTION "percentageAction" //极低电量时执行 #define GSETTINGS_KEY_ACTION_CRITICAL_BATTERY "actionCriticalBattery" #endif // POWERMACRODATA_H ukui-power-manager-4.0.0.1/plugin-power/plugin-power.pro0000664000175000017500000000162014601232446021616 0ustar fengfengQT += widgets dbus TEMPLATE = lib CONFIG += plugin link_pkgconfig c++11 LIBS += -lukcc PKGCONFIG += gsettings-qt \ gio-2.0 \ gio-unix-2.0 \ upower-glib \ kysdk-qtwidgets exists(/usr/include/kysdk/kysdk-system/libkysysinfo.h) { DEFINES += KY_SDK_SYSINFO PKGCONFIG += kysdk-sysinfo } TARGET = $$qtLibraryTarget(power) target.path = $$[QT_INSTALL_LIBS]/ukui-control-center isEmpty(PREFIX) { PREFIX = /usr } trans.files = translations/* trans.path = /usr/share/ukui-power-manager/power-plugin/translations CONFIG(release, debug|release) { !system($$PWD/translate_generation.sh): error("Failed to generate translation") } INSTALLS += target \ trans HEADERS += \ power.h \ powermacrodata.h SOURCES += \ power.cpp TRANSLATIONS += \ translations/zh_CN.ts \ translations/bo_CN.ts \ translations/en_US.ts ukui-power-manager-4.0.0.1/plugin-power/translate_generation.sh0000775000175000017500000000052214601232446023213 0ustar fengfeng#!/bin/bash ts_list=(`ls translations/*.ts`) source /etc/os-release version=(`echo $ID`) for ts in "${ts_list[@]}" do printf "\nprocess ${ts}\n" if [ "$version" == "fedora" ] || [ "$version" == "opensuse-leap" ] || [ "$version" == "opensuse-tumbleweed" ];then lrelease-qt5 "${ts}" else lrelease "${ts}" fi done ukui-power-manager-4.0.0.1/plugin-power/power.h0000664000175000017500000001330314601232446017752 0ustar fengfeng/* * Copyright (C) 2023, KylinSoft Co., Ltd. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . * */ #ifndef POWER_H #define POWER_H #include #include #include #include #include #include #include #include #include #include #include #include #include #ifdef KY_SDK_SYSINFO #include #endif #include #include "kswitchbutton.h" using namespace kdk; namespace Ui { class Power; } enum policy { power_policy_performance = 0, power_policy_balance, power_policy_powersave, }; class Power : public QObject, CommonInterface { Q_OBJECT Q_PLUGIN_METADATA(IID "org.ukcc.CommonInterface") Q_INTERFACES(CommonInterface) public: explicit Power(); ~Power(); QString plugini18nName() Q_DECL_OVERRIDE; int pluginTypes() Q_DECL_OVERRIDE; QWidget *pluginUi() Q_DECL_OVERRIDE; bool isEnable() const Q_DECL_OVERRIDE; const QString name() const Q_DECL_OVERRIDE; bool isShowOnHomePage() const Q_DECL_OVERRIDE; QIcon icon() const Q_DECL_OVERRIDE; QString translationPath() const Q_DECL_OVERRIDE; private: QString m_pluginName; int m_pluginType; bool m_firstLoad; QGSettings *m_powerManagerSettings = nullptr; QGSettings *m_styleSettings = nullptr; QGSettings *m_screenSettings = nullptr; QGSettings *m_procManagerSettings = nullptr; bool m_isWayland = false; bool m_isTablet = false; bool m_canSuspend = false; bool m_canHibernate = false; bool m_hasBattery = false; bool m_hasLid = false; bool m_batteryOnline = false; QWidget *m_pluginWidget; #define defineMainWidgetFrame(frameName) \ TitleLabel *m_##frameName##TitleLabel; \ QFrame *m_##frameName##Frame; \ QVBoxLayout *m_##frameName##Layout; \ void frameName##SettingsFrame(QWidget *) #define defineButtonWidgetFrame(frameName) \ QFrame *m_##frameName##Frame; \ QLabel *m_##frameName##Label; \ KSwitchButton *m_##frameName##Btn; \ QFrame *m_##frameName##Line #define defineComboBoxWidgetFrame(frameName) \ QFrame *m_##frameName##Frame; \ QLabel *m_##frameName##Label; \ QComboBox *m_##frameName##ComboBox; \ QFrame *m_##frameName##Line; \ QStringList m_##frameName##Options defineMainWidgetFrame(generalPower); defineButtonWidgetFrame(wakeUpComputerNeedPwd); defineButtonWidgetFrame(wakeUpDisplayNeedPwd); defineComboBoxWidgetFrame(powerKeyAction); defineComboBoxWidgetFrame(idleTurnOffDisplay); defineComboBoxWidgetFrame(idleSuspend); defineComboBoxWidgetFrame(closeLidAction); // DRS dynamic resource scheduling QFrame *m_generalPowerDRSFrame; QHBoxLayout *m_DRSHBoxLayout; QLabel *m_generalPowerDRSLabel; FixLabel *m_DRSDetialLabel; KSwitchButton *m_generalPowerDRSBtn; void generalPowerDRSSettingsFrame(QWidget *widget); QSpacerItem *m_spacerItem; defineMainWidgetFrame(powerPlan); defineComboBoxWidgetFrame(acPolicy); defineComboBoxWidgetFrame(batteryPolicy); defineMainWidgetFrame(batterySavePlan); defineButtonWidgetFrame(batterySaveSwitch); defineButtonWidgetFrame(lowPowerAutoBatterySaveSwitch); defineButtonWidgetFrame(reduceBrightnessSwitch); defineComboBoxWidgetFrame(lowPowerNotification); defineComboBoxWidgetFrame(criticalPercentageAction); QLabel *m_criticalPercentageLable; QComboBox *m_criticalPercentageComboBox; QStringList m_criticalPercentageOptions; void criticalPercentageActionFrame(); defineButtonWidgetFrame(showBatteryTime); void checkMachineType(); void initLogin1DBus(); void initUpowerDBus(); void initPluginWidget(QWidget *widget); void setupLableText(); void setupComboBoxText(); void initWidgetValue(); void connectWidgetSignals(); void initMainFrame( QWidget *widget, QFrame **mainFrame, QVBoxLayout **vBoxLayout); void addButtonSubFrame( QFrame *fatherFrame, QFrame **subFrame, QVBoxLayout *vBoxLayout, QFrame **lineBetween, QLabel **subFrameLabel, KSwitchButton **button, const QString &buttonName); void addComboBoxSubFrame( QFrame *fatherFrame, QFrame **subFrame, QVBoxLayout *vBoxLayout, QFrame **lineBetween, QLabel **subFrameLabel, QComboBox **comboBox, const QString &comboBoxName); void setFrame_Noframe(QFrame *frame); bool QLabelSetText(QLabel *label, QString string); QFrame *setLine(QFrame *frame); bool buriedSettings(QString, QString, QString, QString); int getDeviceType(const QString &); private slots: void setVisibleBySecurity(); void dealUPMSettingsChanged(const QString &); void dealUPowerDBusMessage(QDBusMessage msg); }; #endif // POWER_H ukui-power-manager-4.0.0.1/plugin-power/power.cpp0000664000175000017500000014245314607363245020326 0ustar fengfeng/* * Copyright (C) 2023, KylinSoft Co., Ltd. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . * */ #include "power.h" #include "powermacrodata.h" #include #include Power::Power() : m_firstLoad(true) { QTranslator *translator = new QTranslator(this); translator->load("/usr/share/ukui-power-manager/power-plugin/translations/" + QLocale::system().name()); QApplication::installTranslator(translator); m_pluginName = tr("Power"); m_pluginType = SYSTEM; } Power::~Power() {} QString Power::plugini18nName() { return m_pluginName; } int Power::pluginTypes() { return m_pluginType; } QWidget * Power::pluginUi() { if (m_firstLoad) { m_pluginWidget = new QWidget; m_pluginWidget->setAttribute(Qt::WA_DeleteOnClose); const QByteArray styleID(STYLE_FONT_SCHEMA); const QByteArray powerManagerID(POWER_MANAGER_SETTINGS); const QByteArray sessionID(SCREENSAVER_SCHEMA); const QByteArray procID(PROC_MANAGER); if (QGSettings::isSchemaInstalled(procID)) { m_procManagerSettings = new QGSettings(procID, QByteArray(), this); } if (QGSettings::isSchemaInstalled(powerManagerID) && QGSettings::isSchemaInstalled(styleID) && QGSettings::isSchemaInstalled(sessionID)) { m_powerManagerSettings = new QGSettings(powerManagerID, QByteArray(), this); m_styleSettings = new QGSettings(styleID, QByteArray(), this); m_screenSettings = new QGSettings(sessionID, QByteArray(), this); checkMachineType(); initLogin1DBus(); initUpowerDBus(); initPluginWidget(m_pluginWidget); setupLableText(); setupComboBoxText(); initWidgetValue(); connectWidgetSignals(); setVisibleBySecurity(); QDBusConnection::sessionBus().connect( QString(), QString("/"), "org.ukui.ukcc.session.interface", "configChanged", this, SLOT(setVisibleBySecurity())); connect(m_powerManagerSettings, &QGSettings::changed, this, &Power::dealUPMSettingsChanged); connect(m_screenSettings, &QGSettings::changed, [=](QString key) { if (SLEEP_ACTIVATION_ENABLED == key) { m_wakeUpComputerNeedPwdBtn->setChecked(m_screenSettings->get(key).toBool()); } else if (CLOSE_ACTIVATION_ENABLED == key) { m_wakeUpDisplayNeedPwdBtn->setChecked(m_screenSettings->get(key).toBool()); } }); if (m_procManagerSettings != nullptr && m_procManagerSettings->keys().contains("resourceLimitEnable")) { connect(m_procManagerSettings, &QGSettings::changed, [=](QString key) { if (RESOURCE_LIMIT_ENABLE == key) { m_generalPowerDRSBtn->setChecked(m_procManagerSettings->get(key).toBool()); } }); } connect(m_styleSettings, &QGSettings::changed, [=](QString key) { if("systemFont" == key || "systemFontSize" == key) { setupLableText(); } }); m_firstLoad = false; } } return m_pluginWidget; } const QString Power::name() const { return QStringLiteral("Power"); } bool Power::isShowOnHomePage() const { return true; } QIcon Power::icon() const { return QIcon::fromTheme("system-shutdown-symbolic"); } QString Power::translationPath() const { return "/usr/share/ukui-power-manager/power-plugin/translations/%1.ts"; } bool Power::isEnable() const { #ifdef KY_SDK_SYSINFO QString cloudPlatForm = QString(QLatin1String("")); QString hostType = QString(QLatin1String("")); cloudPlatForm = QString(QLatin1String(kdk_system_get_hostCloudPlatform())); hostType = QString(QLatin1String(kdk_system_get_hostVirtType())); return !(cloudPlatForm == "huawei" || cloudPlatForm == "ctyun" || hostType != "none"); #endif return true; } void Power::checkMachineType() { #ifdef KY_SDK_SYSINFO quint32 productFeature = kdk_system_get_productFeatures(); if (MACHINE_TYPE_ONLY_TABLET == productFeature || MACHINE_TYPE_PC_AND_TABLET == productFeature) { m_isTablet = true; qDebug() << "machine is tablet:" << m_isTablet; } #else m_isTablet = false; #endif if ("wayland" == qgetenv("XDG_SESSION_TYPE")) { m_isWayland = true; qDebug() << "machine is wayland:" << m_isWayland; } } void Power::initLogin1DBus() { QDBusInterface login1Dbus("org.freedesktop.login1", "/org/freedesktop/login1", "org.freedesktop.login1.Manager", QDBusConnection::systemBus()); QDBusReply reply = login1Dbus.call("CanSuspend"); if (reply.isValid()) { if ("yes" == reply.value()) { m_canSuspend = true; qDebug() << "system can syspend:" << m_canSuspend; } } reply = login1Dbus.call("CanHibernate"); if (reply.isValid()) { if ("yes" == reply.value()) { m_canHibernate = true; qDebug() << "system can hibernate:" << m_canHibernate; } } } void Power::initUpowerDBus() { m_hasBattery = false; m_hasLid = false; m_batteryOnline = false; QDBusInterface dBusInterface("org.freedesktop.UPower", "/org/freedesktop/UPower", "org.freedesktop.UPower", QDBusConnection::systemBus()); QDBusReply> reply = dBusInterface.call("EnumerateDevices"); if (dBusInterface.isValid()) { for (QDBusObjectPath dBusObjectPath : reply.value()) { int upDeviceType = getDeviceType(dBusObjectPath.path()); qDebug() << "device type:" << upDeviceType; if (POWER_SUPPLY_TYPE_BATTERY == upDeviceType) { m_hasBattery = true; qDebug() << "battery dBusObjectPath:" << dBusObjectPath.path(); break; } } } QDBusInterface upowerProperties("org.freedesktop.UPower", "/org/freedesktop/UPower", "org.freedesktop.DBus.Properties", QDBusConnection::systemBus()); QDBusMessage msg = upowerProperties.call("GetAll", "org.freedesktop.UPower"); if (msg.type() == QDBusMessage::ReplyMessage) { const QDBusArgument &dbusArgs = msg.arguments().at(0).value(); QMap map; dbusArgs >> map; m_hasLid = map.value(QString("LidIsPresent")).toBool(); qDebug() << "system has lid:" << m_hasLid; m_batteryOnline = map.value(QString("OnBattery")).toBool(); qDebug() << "battery online state:" << m_batteryOnline; } QDBusConnection::systemBus().connect("org.freedesktop.UPower", "/org/freedesktop/UPower", "org.freedesktop.DBus.Properties", "PropertiesChanged", this, SLOT(dealUPowerDBusMessage(QDBusMessage))); } void Power::initPluginWidget(QWidget *widget) { qDebug() << "init power page"; // 整体布局 QVBoxLayout *verticalLayout = new QVBoxLayout(widget); verticalLayout->setSpacing(8); verticalLayout->setContentsMargins(0, 0, 0, 0); qDebug() << "init general power main page"; m_generalPowerTitleLabel = new TitleLabel(widget); //~ contents_path /Power/General m_generalPowerTitleLabel->setText(tr("General")); verticalLayout->addWidget(m_generalPowerTitleLabel); generalPowerSettingsFrame(widget); verticalLayout->addWidget(m_generalPowerFrame); qDebug() << "init dynamic resource scheduling main page"; generalPowerDRSSettingsFrame(widget); verticalLayout->addWidget(m_generalPowerDRSFrame); m_spacerItem = new QSpacerItem(20, 24, QSizePolicy::Fixed); verticalLayout->addSpacerItem(m_spacerItem); qDebug() << "init power plan main page"; m_powerPlanTitleLabel = new TitleLabel(widget); //~ contents_path /Power/Select power plan m_powerPlanTitleLabel->setText(tr("Select power plan")); verticalLayout->addWidget(m_powerPlanTitleLabel); powerPlanSettingsFrame(widget); verticalLayout->addWidget(m_powerPlanFrame); verticalLayout->addSpacing(24); qDebug() << "init battery save plan main page"; m_batterySavePlanTitleLabel = new TitleLabel(widget); //~ contents_path /Power/Battery saving plan m_batterySavePlanTitleLabel->setText(tr("Battery saving plan")); verticalLayout->addWidget(m_batterySavePlanTitleLabel); batterySavePlanSettingsFrame(widget); verticalLayout->addWidget(m_batterySavePlanFrame); if (false == m_hasBattery || false == m_batteryOnline) { m_batterySavePlanTitleLabel->hide(); m_batterySavePlanFrame->hide(); } verticalLayout->addStretch(); } void Power::generalPowerSettingsFrame(QWidget *widget) { initMainFrame(widget, &m_generalPowerFrame, &m_generalPowerLayout); qDebug() << "init UI: wake up computer need pwd"; addButtonSubFrame(m_generalPowerFrame, &m_wakeUpComputerNeedPwdFrame, m_generalPowerLayout, &m_wakeUpComputerNeedPwdLine, &m_wakeUpComputerNeedPwdLabel, &m_wakeUpComputerNeedPwdBtn, "sleepwaken"); if (false == m_canSuspend && false == m_canHibernate) { m_wakeUpComputerNeedPwdFrame->hide(); m_wakeUpComputerNeedPwdLine->hide(); } qDebug() << "init UI: wake up display need pwd"; addButtonSubFrame(m_generalPowerFrame, &m_wakeUpDisplayNeedPwdFrame, m_generalPowerLayout, &m_wakeUpDisplayNeedPwdLine, &m_wakeUpDisplayNeedPwdLabel, &m_wakeUpDisplayNeedPwdBtn, "lockwaken"); qDebug() << "init UI: power key action"; addComboBoxSubFrame(m_generalPowerFrame, &m_powerKeyActionFrame, m_generalPowerLayout, &m_powerKeyActionLine, &m_powerKeyActionLabel, &m_powerKeyActionComboBox, "powerkey"); if (true == m_isTablet) { m_powerKeyActionFrame->hide(); m_powerKeyActionLine->hide(); } qDebug() << "init UI: idle turn off display"; addComboBoxSubFrame(m_generalPowerFrame, &m_idleTurnOffDisplayFrame, m_generalPowerLayout, &m_idleTurnOffDisplayLine, &m_idleTurnOffDisplayLabel, &m_idleTurnOffDisplayComboBox, "idleTurnOffDisplay"); qDebug() << "init UI: idle suspend"; addComboBoxSubFrame(m_generalPowerFrame, &m_idleSuspendFrame, m_generalPowerLayout, &m_idleSuspendLine, &m_idleSuspendLabel, &m_idleSuspendComboBox, "idleSuspend"); if (false == m_canSuspend) { m_idleSuspendFrame->hide(); m_idleSuspendLine->hide(); } qDebug() << "init UI: close lid action"; addComboBoxSubFrame(m_generalPowerFrame, &m_closeLidActionFrame, m_generalPowerLayout, &m_closeLidActionLine, &m_closeLidActionLabel, &m_closeLidActionComboBox, "closeLidAction"); if (false == m_hasLid) { m_closeLidActionFrame->hide(); m_closeLidActionLine->hide(); } } void Power::generalPowerDRSSettingsFrame(QWidget *widget) { m_generalPowerDRSFrame = new QFrame(widget); m_generalPowerDRSFrame->setMinimumSize(QSize(550, 0)); m_generalPowerDRSFrame->setMaximumSize(QSize(16777215, 16777215)); m_generalPowerDRSFrame->setFrameShape(QFrame::Box); m_DRSHBoxLayout = new QHBoxLayout(m_generalPowerDRSFrame); m_DRSHBoxLayout->setContentsMargins(16, 0, 16, 0); m_generalPowerDRSLabel = new QLabel(m_generalPowerDRSFrame); m_generalPowerDRSLabel->setAlignment(Qt::AlignBottom); m_generalPowerDRSLabel->setFixedWidth(550); m_DRSDetialLabel = new FixLabel(widget); m_DRSDetialLabel->setText(tr("Reduce the occupation of backend running program resources and ensure smooth operation of key and focus applications.")); m_DRSDetialLabel->setFixedWidth(550); m_DRSDetialLabel->setAlignment(Qt::AlignTop); QVBoxLayout *DRSLabelLayout = new QVBoxLayout(m_generalPowerDRSFrame); DRSLabelLayout->setSpacing(0); DRSLabelLayout->setContentsMargins(0,0,0,0); DRSLabelLayout->addWidget(m_generalPowerDRSLabel); DRSLabelLayout->addWidget(m_DRSDetialLabel); m_generalPowerDRSBtn = new KSwitchButton(m_generalPowerDRSFrame); m_DRSHBoxLayout->addLayout(DRSLabelLayout); m_DRSHBoxLayout->addStretch(); m_DRSHBoxLayout->addWidget(m_generalPowerDRSBtn); #ifndef UKCC2309 m_generalPowerDRSFrame->hide(); #endif } void Power::powerPlanSettingsFrame(QWidget *widget) { initMainFrame(widget, &m_powerPlanFrame, &m_powerPlanLayout); qDebug() << "init UI: ac policy"; addComboBoxSubFrame(m_powerPlanFrame, &m_acPolicyFrame, m_powerPlanLayout, &m_acPolicyLine, &m_acPolicyLabel, &m_acPolicyComboBox, "acPolicy"); qDebug() << "init UI: battery policy"; addComboBoxSubFrame(m_powerPlanFrame, &m_batteryPolicyFrame, m_powerPlanLayout, &m_batteryPolicyLine, &m_batteryPolicyLabel, &m_batteryPolicyComboBox, "batteryPolicy"); if (false == m_hasBattery) { m_batteryPolicyFrame->hide(); m_batteryPolicyLine->hide(); } } void Power::batterySavePlanSettingsFrame(QWidget *widget) { initMainFrame(widget, &m_batterySavePlanFrame, &m_batterySavePlanLayout); qDebug() << "init UI: battery save switch"; addButtonSubFrame(m_batterySavePlanFrame, &m_batterySaveSwitchFrame, m_batterySavePlanLayout, &m_batterySaveSwitchLine, &m_batterySaveSwitchLabel, &m_batterySaveSwitchBtn, "batterySaveSwitch"); qDebug() << "init UI: low power auto battery save switch"; addButtonSubFrame(m_batterySavePlanFrame, &m_lowPowerAutoBatterySaveSwitchFrame, m_batterySavePlanLayout, &m_lowPowerAutoBatterySaveSwitchLine, &m_lowPowerAutoBatterySaveSwitchLabel, &m_lowPowerAutoBatterySaveSwitchBtn, "lowPowerAutoBatterySaveSwitch"); qDebug() << "init UI: reduce brightness switch"; addButtonSubFrame(m_batterySavePlanFrame, &m_reduceBrightnessSwitchFrame, m_batterySavePlanLayout, &m_reduceBrightnessSwitchLine, &m_reduceBrightnessSwitchLabel, &m_reduceBrightnessSwitchBtn, "reduceBrightnessSwitch"); qDebug() << "init UI: low power notification"; addComboBoxSubFrame(m_batterySavePlanFrame, &m_lowPowerNotificationFrame, m_batterySavePlanLayout, &m_lowPowerNotificationLine, &m_lowPowerNotificationLabel, &m_lowPowerNotificationComboBox, "lowPowerNotification"); qDebug() << "init UI: critical percentage action"; criticalPercentageActionFrame(); qDebug() << "init UI: show battery time"; addButtonSubFrame(m_batterySavePlanFrame, &m_showBatteryTimeFrame, m_batterySavePlanLayout, &m_showBatteryTimeLine, &m_showBatteryTimeLabel, &m_showBatteryTimeBtn, "showBatteryTime"); m_showBatteryTimeFrame->hide(); m_showBatteryTimeLine->hide(); } void Power::criticalPercentageActionFrame() { m_criticalPercentageActionFrame = new QFrame(m_batterySavePlanFrame); setFrame_Noframe(m_criticalPercentageActionFrame); m_criticalPercentageLable = new QLabel(m_criticalPercentageActionFrame); m_criticalPercentageLable->setFixedHeight(60); m_criticalPercentageActionLabel = new QLabel(m_criticalPercentageActionFrame); m_criticalPercentageActionLabel->setFixedSize(370,60); QHBoxLayout *criticalPercentageActionLayout = new QHBoxLayout(m_criticalPercentageActionFrame); criticalPercentageActionLayout->setContentsMargins(16, 0, 16, 0); m_criticalPercentageComboBox = new QComboBox(m_criticalPercentageActionFrame); m_criticalPercentageComboBox->setObjectName("criticalPercentage"); m_criticalPercentageComboBox->setFixedWidth(80); m_criticalPercentageActionComboBox = new QComboBox(m_criticalPercentageActionFrame); m_criticalPercentageActionComboBox->setObjectName("criticalPercentageAction"); m_criticalPercentageActionComboBox->setMinimumWidth(200); criticalPercentageActionLayout->setSpacing(8); criticalPercentageActionLayout->addWidget(m_criticalPercentageLable); criticalPercentageActionLayout->addWidget(m_criticalPercentageComboBox); criticalPercentageActionLayout->addWidget(m_criticalPercentageActionLabel); criticalPercentageActionLayout->addStretch(); criticalPercentageActionLayout->addWidget(m_criticalPercentageActionComboBox); m_batterySavePlanLayout->addWidget(m_criticalPercentageActionFrame); m_criticalPercentageActionLine = setLine(m_batterySavePlanFrame); m_batterySavePlanLayout->addWidget(m_criticalPercentageActionLine); } void Power::initMainFrame( QWidget *widget, QFrame **mainFrame, QVBoxLayout **vBoxLayout) { (*mainFrame) = new QFrame(widget); (*mainFrame)->setMinimumSize(QSize(550, 0)); (*mainFrame)->setMaximumSize(QSize(16777215, 16777215)); (*mainFrame)->setFrameShape(QFrame::Box); (*vBoxLayout) = new QVBoxLayout(*mainFrame); (*vBoxLayout)->setContentsMargins(0, 0, 0, 0); (*vBoxLayout)->setSpacing(0); } void Power::addButtonSubFrame( QFrame *fatherFrame, QFrame **subFrame, QVBoxLayout *vBoxLayout, QFrame **lineBetween, QLabel **subFrameLabel, KSwitchButton **button, const QString &buttonName) { (*subFrame) = new QFrame(fatherFrame); setFrame_Noframe(*subFrame); QHBoxLayout *SubFrameLayout = new QHBoxLayout(*subFrame); SubFrameLayout->setContentsMargins(16, 0, 16, 0); (*subFrameLabel) = new QLabel(*subFrame); (*subFrameLabel)->setFixedSize(550,60); (*button) = new KSwitchButton(*subFrame); (*button)->setObjectName(buttonName); SubFrameLayout->addWidget(*subFrameLabel); SubFrameLayout->addStretch(); SubFrameLayout->addWidget(*button); vBoxLayout->addWidget(*subFrame); (*lineBetween) = setLine(fatherFrame); vBoxLayout->addWidget(*lineBetween); } void Power::addComboBoxSubFrame( QFrame *fatherFrame, QFrame **subFrame, QVBoxLayout *vBoxLayout, QFrame **lineBetween, QLabel **subFrameLabel, QComboBox **comboBox, const QString &comboBoxName) { (*subFrame) = new QFrame(fatherFrame); setFrame_Noframe(*subFrame); QHBoxLayout *SubFrameLayout = new QHBoxLayout(*subFrame); SubFrameLayout->setContentsMargins(16, 0, 16, 0); (*subFrameLabel) = new QLabel(*subFrame); (*subFrameLabel)->setFixedSize(550,59); (*comboBox) = new QComboBox(*subFrame); (*comboBox)->setObjectName(comboBoxName); (*comboBox)->setMinimumWidth(200); SubFrameLayout->addWidget(*subFrameLabel); SubFrameLayout->addStretch(); SubFrameLayout->addWidget(*comboBox); vBoxLayout->addWidget(*subFrame); (*lineBetween) = setLine(fatherFrame); vBoxLayout->addWidget(*lineBetween); } void Power::setFrame_Noframe(QFrame *frame) { frame->setMinimumSize(QSize(550, 60)); frame->setFrameShape(QFrame::NoFrame); } bool Power::QLabelSetText(QLabel *label, QString string) { bool is_over_length = false; QFontMetrics fontMetrics(label->font()); int fontSize = fontMetrics.width(string); QString str = string; if (fontSize > (label->width()-5)) { str = fontMetrics.elidedText(string, Qt::ElideRight, label->width()); is_over_length = true; } label->setText(str); return is_over_length; } QFrame *Power::setLine(QFrame *frame) { QFrame *line = new QFrame(frame); line->setFixedHeight(1); line->setLineWidth(0); line->setFrameShape(QFrame::HLine); line->setFrameShadow(QFrame::Sunken); return line; } void Power::setupLableText() { QString str; if (true == m_canHibernate && true == m_canSuspend) { str = tr("Require password when sleep/hibernate"); } else { if (true == m_canHibernate) { str = tr("Require password when hibernate"); } if (true == m_canSuspend) { str = tr("Require password when sleep"); } } if (QLabelSetText(m_wakeUpComputerNeedPwdLabel, str)) { m_wakeUpComputerNeedPwdLabel->setToolTip(str); } if (QLabelSetText(m_wakeUpDisplayNeedPwdLabel, tr("Password required when waking up the screen"))) { m_wakeUpDisplayNeedPwdLabel->setToolTip(tr("Password required when waking up the screen")); } if (QLabelSetText(m_powerKeyActionLabel, tr("Press the power button"))) { m_powerKeyActionLabel->setToolTip("Press the power button"); } if (QLabelSetText(m_idleTurnOffDisplayLabel, tr("Time to close display"))) { m_idleTurnOffDisplayLabel->setToolTip(tr("Time to close display")); } if (QLabelSetText(m_idleSuspendLabel, tr("Time to sleep"))) { m_idleSuspendLabel->setToolTip(tr("Time to sleep")); } if (QLabelSetText(m_closeLidActionLabel, tr("Notebook cover"))) { m_closeLidActionLabel->setToolTip(tr("Notebook cover")); } if (QLabelSetText(m_generalPowerDRSLabel, tr("Dynamic resource scheduling"))) { m_generalPowerDRSLabel->setToolTip(tr("Dynamic resource scheduling")); } if (QLabelSetText(m_acPolicyLabel, tr("Using power"))) { m_acPolicyLabel->setToolTip(tr("Using power")); } if (QLabelSetText(m_batteryPolicyLabel, tr("Using battery"))) { m_batteryPolicyLabel->setToolTip(tr("Using power")); } if (QLabelSetText(m_batterySaveSwitchLabel, tr("Open battery saving"))) { m_batterySaveSwitchLabel->setToolTip(tr("Open battery saving")); } if (QLabelSetText(m_lowPowerAutoBatterySaveSwitchLabel, tr("Automatically run saving mode when low battery"))) { m_lowPowerAutoBatterySaveSwitchLabel->setToolTip(tr("Automatically run saving mode when low battery")); } if (QLabelSetText(m_reduceBrightnessSwitchLabel, tr("Auto display brightness level"))) { m_lowPowerAutoBatterySaveSwitchLabel->setToolTip(tr("Auto display brightness level")); } if (QLabelSetText(m_lowPowerNotificationLabel, tr("Low battery notification"))) { m_lowPowerNotificationLabel->setToolTip(tr("Low battery notification")); } if (QLabelSetText(m_criticalPercentageLable, tr("Battery level is lower than"))) { m_criticalPercentageLable->setToolTip(tr("Battery level is lower than")); } m_criticalPercentageActionLabel->setText(tr("Run")); } void Power::setupComboBoxText() { m_powerKeyActionOptions << tr("interactive") << tr("shutdown") << tr("suspend") << tr("hibernate"); m_powerKeyActionComboBox->insertItem(0, m_powerKeyActionOptions.at(0), "interactive"); m_powerKeyActionComboBox->insertItem(1, m_powerKeyActionOptions.at(1), "shutdown"); if (true == m_canSuspend) { m_powerKeyActionComboBox->insertItem(2, m_powerKeyActionOptions.at(2), "suspend"); } if (true == m_canHibernate) { m_powerKeyActionComboBox->insertItem(3, m_powerKeyActionOptions.at(3), "hibernate"); } m_idleTurnOffDisplayOptions << tr("5min") << tr("10min") << tr("15min") << tr("30min") << tr("1h") << tr("2h") << tr("never"); m_idleTurnOffDisplayComboBox->insertItem(0, m_idleTurnOffDisplayOptions.at(0), QVariant::fromValue(5)); m_idleTurnOffDisplayComboBox->insertItem(1, m_idleTurnOffDisplayOptions.at(1), QVariant::fromValue(10)); m_idleTurnOffDisplayComboBox->insertItem(2, m_idleTurnOffDisplayOptions.at(2), QVariant::fromValue(15)); m_idleTurnOffDisplayComboBox->insertItem(3, m_idleTurnOffDisplayOptions.at(3), QVariant::fromValue(30)); m_idleTurnOffDisplayComboBox->insertItem(4, m_idleTurnOffDisplayOptions.at(4), QVariant::fromValue(60)); m_idleTurnOffDisplayComboBox->insertItem(5, m_idleTurnOffDisplayOptions.at(5), QVariant::fromValue(120)); m_idleTurnOffDisplayComboBox->insertItem(6, m_idleTurnOffDisplayOptions.at(6), QVariant::fromValue(0)); m_idleSuspendOptions << tr("10min") << tr("15min") << tr("30min") << tr("1h") << tr("2h") << tr("3h") << tr("never"); m_idleSuspendComboBox->insertItem(0, m_idleSuspendOptions.at(0), QVariant::fromValue(10)); m_idleSuspendComboBox->insertItem(1, m_idleSuspendOptions.at(1), QVariant::fromValue(15)); m_idleSuspendComboBox->insertItem(2, m_idleSuspendOptions.at(2), QVariant::fromValue(30)); m_idleSuspendComboBox->insertItem(3, m_idleSuspendOptions.at(3), QVariant::fromValue(60)); m_idleSuspendComboBox->insertItem(4, m_idleSuspendOptions.at(4), QVariant::fromValue(120)); m_idleSuspendComboBox->insertItem(5, m_idleSuspendOptions.at(5), QVariant::fromValue(180)); m_idleSuspendComboBox->insertItem(6, m_idleSuspendOptions.at(6), QVariant::fromValue(0)); m_closeLidActionOptions << tr("nothing") << tr("blank") << tr("shutdown") << tr("suspend") << tr("hibernate"); m_closeLidActionComboBox->insertItem(0, m_closeLidActionOptions.at(0), "nothing"); m_closeLidActionComboBox->insertItem(1, m_closeLidActionOptions.at(1), "blank"); m_closeLidActionComboBox->insertItem(2, m_closeLidActionOptions.at(2), "shutdown"); if (true == m_canSuspend) { m_closeLidActionComboBox->insertItem(3, m_closeLidActionOptions.at(3), "suspend"); } if (false == m_isWayland && true == m_canHibernate) { m_closeLidActionComboBox->insertItem(4, m_closeLidActionOptions.at(4), "hibernate"); } m_acPolicyOptions << tr("Balance") << tr("Energy Efficiency")<< tr("Performance"); m_acPolicyComboBox->insertItem(0, m_acPolicyOptions.at(0), "Balance"); m_acPolicyComboBox->insertItem(1, m_acPolicyOptions.at(1), "Energy Efficiency"); m_acPolicyComboBox->insertItem(2, m_acPolicyOptions.at(2), "Performance"); m_batteryPolicyOptions << tr("Balance") << tr("Energy Efficiency")<< tr("Performance"); m_batteryPolicyComboBox->insertItem(0, m_batteryPolicyOptions.at(0), "Balance"); m_batteryPolicyComboBox->insertItem(1, m_batteryPolicyOptions.at(1), "Energy Efficiency"); m_batteryPolicyComboBox->insertItem(2, m_batteryPolicyOptions.at(2), "Performance"); m_lowPowerNotificationOptions << "10%" << "20%" << "30%" << "40%"; for (int i = 0; i < m_lowPowerNotificationOptions.size(); ++i) { m_lowPowerNotificationComboBox->insertItem(i, m_lowPowerNotificationOptions.at(i)); } m_criticalPercentageOptions << "5%" << "6%" << "7%" << "8%" << "9%"; for (int i = 0; i < m_criticalPercentageOptions.size(); ++i) { m_criticalPercentageComboBox->insertItem(i, m_criticalPercentageOptions.at(i)); } m_criticalPercentageActionOptions << tr("nothing") << tr("shutdown") << tr("hibernate") << tr("suspend"); m_criticalPercentageActionComboBox->insertItem(0, m_criticalPercentageActionOptions.at(0), "nothing"); m_criticalPercentageActionComboBox->insertItem(1, m_criticalPercentageActionOptions.at(1), "shutdown"); if (true == m_canHibernate) { m_criticalPercentageActionComboBox->insertItem(2, m_criticalPercentageActionOptions.at(2), "hibernate"); } if (true == m_canSuspend) { m_criticalPercentageActionComboBox->insertItem(3, m_criticalPercentageActionOptions.at(3), "suspend"); } } void Power::initWidgetValue() { if (m_screenSettings->keys().contains(SLEEP_ACTIVATION_ENABLED)) { m_wakeUpComputerNeedPwdBtn->setChecked( m_screenSettings->get(SLEEP_ACTIVATION_ENABLED).toBool()); } if (m_screenSettings->keys().contains(CLOSE_ACTIVATION_ENABLED)) { m_wakeUpDisplayNeedPwdBtn->setChecked( m_screenSettings->get(CLOSE_ACTIVATION_ENABLED).toBool()); } if (m_powerManagerSettings->keys().contains(GSETTINGS_KEY_BUTTON_POWER)) { m_powerKeyActionComboBox->setCurrentIndex( m_powerKeyActionComboBox->findData( m_powerManagerSettings->get(GSETTINGS_KEY_BUTTON_POWER).toString())); } QVariant value; if (m_powerManagerSettings->keys().contains(GSETTINGS_KEY_SLEEP_DISPLAY_AC)) { value = m_powerManagerSettings->get(GSETTINGS_KEY_SLEEP_DISPLAY_AC); if(-1 == value.toInt()) { m_idleTurnOffDisplayComboBox->setCurrentIndex(m_idleTurnOffDisplayComboBox->findData(0)); } else { m_idleTurnOffDisplayComboBox->setCurrentIndex(m_idleTurnOffDisplayComboBox->findData(value.toInt() / FIXES)); } } if (m_powerManagerSettings->keys().contains(GSETTINGS_KEY_SLEEP_COMPUTER_AC)) { value = m_powerManagerSettings->get(GSETTINGS_KEY_SLEEP_COMPUTER_AC); if(-1 == value.toInt()) { m_idleSuspendComboBox->setCurrentIndex(m_idleSuspendComboBox->findData(0)); } else { m_idleSuspendComboBox->setCurrentIndex(m_idleSuspendComboBox->findData(value.toInt() / FIXES)); } } if (m_powerManagerSettings->keys().contains(GSETTINGS_KEY_BUTTON_LID_AC)) { m_closeLidActionComboBox->setCurrentIndex( m_closeLidActionComboBox->findData( m_powerManagerSettings->get(GSETTINGS_KEY_BUTTON_LID_AC).toString())); } if (m_procManagerSettings != nullptr && m_procManagerSettings->keys().contains("resourceLimitEnable")) { m_generalPowerDRSBtn->setChecked(m_procManagerSettings->get(RESOURCE_LIMIT_ENABLE).toBool()); } int policy; if (m_powerManagerSettings->keys().contains(GSETTINGS_KEY_POWER_POLICY_AC)) { policy = m_powerManagerSettings->get(GSETTINGS_KEY_POWER_POLICY_AC).toInt(); switch (policy) { case power_policy_performance: m_acPolicyComboBox->setCurrentIndex(2); break; case power_policy_balance: m_acPolicyComboBox->setCurrentIndex(0); break; case power_policy_powersave: m_acPolicyComboBox->setCurrentIndex(1); break; default: break; } } if (m_powerManagerSettings->keys().contains(GSETTINGS_KEY_POWER_POLICY_BATTERY)) { policy = m_powerManagerSettings->get(GSETTINGS_KEY_POWER_POLICY_BATTERY).toInt(); switch (policy) { case power_policy_performance: m_batteryPolicyComboBox->setCurrentIndex(2); break; case power_policy_balance: m_batteryPolicyComboBox->setCurrentIndex(0); break; case power_policy_powersave: m_batteryPolicyComboBox->setCurrentIndex(1); break; default: break; } } if (m_powerManagerSettings->keys().contains(GSETTINGS_KEY_BATTERY_SAVE_SWITCH)) { m_batterySaveSwitchBtn->setChecked( m_powerManagerSettings->get(GSETTINGS_KEY_BATTERY_SAVE_SWITCH).toBool()); } if (m_powerManagerSettings->keys().contains(GSETTINGS_KEY_LOW_BATTERY_AUTO_SAVE)) { m_lowPowerAutoBatterySaveSwitchBtn->setChecked( m_powerManagerSettings->get(GSETTINGS_KEY_LOW_BATTERY_AUTO_SAVE).toBool()); } if (m_powerManagerSettings->keys().contains(GSETTINGS_KEY_BATTERY_SAVE_REDUCE_BRIGHTNESS)) { m_reduceBrightnessSwitchBtn->setChecked( m_powerManagerSettings->get(GSETTINGS_KEY_BATTERY_SAVE_REDUCE_BRIGHTNESS).toBool()); } if (m_powerManagerSettings->keys().contains(GSETTINGS_KEY_PERCENTAGE_LOW)) { m_lowPowerNotificationComboBox->setCurrentIndex( m_powerManagerSettings->get(GSETTINGS_KEY_PERCENTAGE_LOW).toInt() / 10 - 1); } if (m_powerManagerSettings->keys().contains(GSETTINGS_KEY_PERCENTAGE_ACTION)) { m_criticalPercentageComboBox->setCurrentIndex( m_powerManagerSettings->get(GSETTINGS_KEY_PERCENTAGE_ACTION).toInt() - 5); } if (m_powerManagerSettings->keys().contains(GSETTINGS_KEY_ACTION_CRITICAL_BATTERY)) { m_criticalPercentageActionComboBox->setCurrentIndex( m_criticalPercentageActionComboBox->findData( m_powerManagerSettings->get(GSETTINGS_KEY_ACTION_CRITICAL_BATTERY).toString())); } } void Power::connectWidgetSignals() { connect(m_wakeUpComputerNeedPwdBtn, &KSwitchButton::stateChanged, [=](bool checked){ Power::buriedSettings(name(), "whether password is required for wake-up after sleep", QString("settings"), checked ? "true" : "false"); m_screenSettings->set(SLEEP_ACTIVATION_ENABLED, checked); }); if (m_screenSettings->keys().contains("closeActivationEnabled")) { connect(m_wakeUpDisplayNeedPwdBtn, &KSwitchButton::stateChanged, [=](bool checked){ Power::buriedSettings(name(), "whether password is required for wake-up screen", QString("settings"), checked ? "true" : "false"); m_screenSettings->set(CLOSE_ACTIVATION_ENABLED, checked); }); } connect(m_powerKeyActionComboBox, QOverload::of(&QComboBox::currentIndexChanged), this, [=](int index) { Power::buriedSettings(name(), "execute when pressing the power key", QString("select"), m_powerKeyActionComboBox->itemData(index).toString()); m_powerManagerSettings->set(GSETTINGS_KEY_BUTTON_POWER, m_powerKeyActionComboBox->itemData(index)); }); connect(m_idleTurnOffDisplayComboBox, QOverload::of(&QComboBox::currentIndexChanged), this, [=](int index) { Q_UNUSED(index) Power::buriedSettings(name(), "turn off the display after this time period", QString("select"), m_idleTurnOffDisplayComboBox->currentData().toString()); int closeDisplayTime = m_idleTurnOffDisplayComboBox->currentData(Qt::UserRole).toInt() * 60; int sleepComputerTime = m_idleSuspendComboBox->currentData(Qt::UserRole).toInt() * 60; if (0 == closeDisplayTime) { m_powerManagerSettings->set(GSETTINGS_KEY_SLEEP_DISPLAY_AC, -1); m_powerManagerSettings->set(GSETTINGS_KEY_SLEEP_DISPLAY_BATTERY, -1); m_powerManagerSettings->set(GSETTINGS_KEY_SLEEP_COMPUTER_AC, -1); m_powerManagerSettings->set(GSETTINGS_KEY_SLEEP_COMPUTER_BATTERY, -1); } else { m_powerManagerSettings->set(GSETTINGS_KEY_SLEEP_DISPLAY_AC, QVariant(closeDisplayTime)); m_powerManagerSettings->set(GSETTINGS_KEY_SLEEP_DISPLAY_BATTERY, QVariant(closeDisplayTime)); if (0 != sleepComputerTime && closeDisplayTime > sleepComputerTime) { m_powerManagerSettings->set(GSETTINGS_KEY_SLEEP_COMPUTER_AC, QVariant(closeDisplayTime)); m_powerManagerSettings->set(GSETTINGS_KEY_SLEEP_COMPUTER_BATTERY, QVariant(closeDisplayTime)); } } }); connect(m_idleSuspendComboBox, QOverload::of(&QComboBox::currentIndexChanged), this, [=](int index) { Q_UNUSED(index) Power::buriedSettings(name(), "the system go to sleep after this time period", QString("select"), m_idleSuspendComboBox->currentData().toString()); int closeDisplayTime = m_idleTurnOffDisplayComboBox->currentData(Qt::UserRole).toInt() * 60; int sleepComputerTime = m_idleSuspendComboBox->currentData(Qt::UserRole).toInt() * 60; if (0 == sleepComputerTime) { m_powerManagerSettings->set(GSETTINGS_KEY_SLEEP_COMPUTER_AC, -1); m_powerManagerSettings->set(GSETTINGS_KEY_SLEEP_COMPUTER_BATTERY, -1); } else { m_powerManagerSettings->set(GSETTINGS_KEY_SLEEP_COMPUTER_AC, QVariant(sleepComputerTime)); m_powerManagerSettings->set(GSETTINGS_KEY_SLEEP_COMPUTER_BATTERY, QVariant(sleepComputerTime)); if (0 == closeDisplayTime || closeDisplayTime > sleepComputerTime) { if (10800 == sleepComputerTime) { m_powerManagerSettings->set(GSETTINGS_KEY_SLEEP_DISPLAY_AC, QVariant(7200)); m_powerManagerSettings->set(GSETTINGS_KEY_SLEEP_DISPLAY_BATTERY, QVariant(7200)); } else { m_powerManagerSettings->set(GSETTINGS_KEY_SLEEP_DISPLAY_AC, QVariant(sleepComputerTime)); m_powerManagerSettings->set(GSETTINGS_KEY_SLEEP_DISPLAY_BATTERY, QVariant(sleepComputerTime)); } } } }); connect(m_closeLidActionComboBox, QOverload::of(&QComboBox::currentIndexChanged), this, [=](int index) { Power::buriedSettings(name(), "execute when the notebook is closed", QString("select"), m_closeLidActionComboBox->currentData().toString()); m_powerManagerSettings->set(GSETTINGS_KEY_BUTTON_LID_AC, m_closeLidActionComboBox->itemData(index)); m_powerManagerSettings->set(GSETTINGS_KEY_BUTTON_LID_BATTERY, m_closeLidActionComboBox->itemData(index)); }); connect(m_generalPowerDRSBtn, &KSwitchButton::clicked, this, [=](bool checked){ Power::buriedSettings(name(), "whether to enable dynamic resource scheduling", QString("select"), checked ? "true" : "false"); if (m_procManagerSettings != nullptr && m_procManagerSettings->keys().contains("resourceLimitEnable")) { m_procManagerSettings->set(RESOURCE_LIMIT_ENABLE, checked); } }); connect(m_acPolicyComboBox, QOverload::of(&QComboBox::currentIndexChanged), this, [=](int index) { Power::buriedSettings(name(), "mode when using power supply", QString("select"), m_acPolicyComboBox->currentData().toString()); if (index == 0) { m_powerManagerSettings->set(GSETTINGS_KEY_POWER_POLICY_AC, power_policy_balance); } else if (index == 1) { m_powerManagerSettings->set(GSETTINGS_KEY_POWER_POLICY_AC, power_policy_powersave); } else { m_powerManagerSettings->set(GSETTINGS_KEY_POWER_POLICY_AC, power_policy_performance); } }); connect(m_batteryPolicyComboBox, QOverload::of(&QComboBox::currentIndexChanged), this, [=](int index) { Power::buriedSettings(name(), "mode when using battery supply", QString("select"), m_batteryPolicyComboBox->currentData().toString()); if (index == 0) { m_powerManagerSettings->set(GSETTINGS_KEY_POWER_POLICY_BATTERY, power_policy_balance); } else if (index == 1) { m_powerManagerSettings->set(GSETTINGS_KEY_POWER_POLICY_BATTERY, power_policy_powersave); } else { m_powerManagerSettings->set(GSETTINGS_KEY_POWER_POLICY_BATTERY, power_policy_performance); } }); connect(m_batterySaveSwitchBtn, &KSwitchButton::clicked, this, [=](bool checked){ Power::buriedSettings(name(), "whether to enable battery save mode", QString("select"), checked ? "true" : "false"); m_powerManagerSettings->set(GSETTINGS_KEY_BATTERY_SAVE_SWITCH, checked); }); connect(m_lowPowerAutoBatterySaveSwitchBtn, &KSwitchButton::clicked, this, [=](bool checked){ Power::buriedSettings(name(), "whether the saving mode is autoturned on when the battery is low", QString("select"), checked ? "true" : "false"); m_powerManagerSettings->set(GSETTINGS_KEY_LOW_BATTERY_AUTO_SAVE, checked); }); connect(m_reduceBrightnessSwitchBtn, &KSwitchButton::clicked, this, [=](bool checked){ Power::buriedSettings(name(), "whether to reduce brightness when battery save mode is enabled", QString("select"), checked ? "true" : "false"); m_powerManagerSettings->set(GSETTINGS_KEY_BATTERY_SAVE_REDUCE_BRIGHTNESS, checked); }); connect(m_lowPowerNotificationComboBox, QOverload::of(&QComboBox::currentIndexChanged), this, [=](int index) { Power::buriedSettings(name(), "notify when the power is lower than this value", QString("select"), m_lowPowerNotificationComboBox->currentData().toString()); m_powerManagerSettings->set(GSETTINGS_KEY_PERCENTAGE_LOW, (index + 1) * 10); }); connect(m_criticalPercentageComboBox, QOverload::of(&QComboBox::currentIndexChanged), this, [=](int index) { Power::buriedSettings(name(), "critical battery value", QString("select"), m_criticalPercentageComboBox->currentData().toString()); m_powerManagerSettings->set(GSETTINGS_KEY_PERCENTAGE_ACTION, index + 5); }); connect(m_criticalPercentageActionComboBox, QOverload::of(&QComboBox::currentIndexChanged), this, [=](int index) { Power::buriedSettings(name(), "execute below low battery level", QString("select"), m_criticalPercentageActionComboBox->currentData().toString()); m_powerManagerSettings->set(GSETTINGS_KEY_ACTION_CRITICAL_BATTERY, m_criticalPercentageActionComboBox->itemData(index)); }); } void Power::dealUPMSettingsChanged(const QString &key) { if (GSETTINGS_KEY_BUTTON_POWER == key) { m_powerKeyActionComboBox->blockSignals(true); m_powerKeyActionComboBox->setCurrentIndex( m_powerKeyActionComboBox->findData( m_powerManagerSettings->get(key).toString())); m_powerKeyActionComboBox->blockSignals(false); } else if (GSETTINGS_KEY_SLEEP_DISPLAY_AC == key) { m_idleTurnOffDisplayComboBox->blockSignals(true); QVariant value = m_powerManagerSettings->get(key); if(-1 == value.toInt()) { m_idleTurnOffDisplayComboBox->setCurrentIndex( m_idleTurnOffDisplayComboBox->findData(0)); } else { m_idleTurnOffDisplayComboBox->setCurrentIndex( m_idleTurnOffDisplayComboBox->findData(value.toInt() / FIXES)); } m_idleTurnOffDisplayComboBox->blockSignals(false); } else if (GSETTINGS_KEY_SLEEP_COMPUTER_AC == key) { m_idleSuspendComboBox->blockSignals(true); QVariant value = m_powerManagerSettings->get(key); if(-1 == value.toInt()) { m_idleSuspendComboBox->setCurrentIndex( m_idleSuspendComboBox->findData(0)); } else { m_idleSuspendComboBox->setCurrentIndex( m_idleSuspendComboBox->findData(value.toInt() / FIXES)); } m_idleSuspendComboBox->blockSignals(false); } else if (GSETTINGS_KEY_BUTTON_LID_AC == key) { m_closeLidActionComboBox->blockSignals(true); m_closeLidActionComboBox->setCurrentIndex( m_closeLidActionComboBox->findData( m_powerManagerSettings->get(key).toString())); m_closeLidActionComboBox->blockSignals(false); } else if (GSETTINGS_KEY_POWER_POLICY_AC == key) { m_acPolicyComboBox->blockSignals(true); int policy = m_powerManagerSettings->get(key).toInt(); switch (policy) { case power_policy_performance: m_acPolicyComboBox->setCurrentIndex(2); break; case power_policy_balance: m_acPolicyComboBox->setCurrentIndex(0); break; case power_policy_powersave: m_acPolicyComboBox->setCurrentIndex(1); break; default: break; } m_acPolicyComboBox->blockSignals(false); } else if (GSETTINGS_KEY_POWER_POLICY_BATTERY == key) { m_batteryPolicyComboBox->blockSignals(true); int policy = m_powerManagerSettings->get(key).toInt(); switch (policy) { case power_policy_performance: m_batteryPolicyComboBox->setCurrentIndex(2); break; case power_policy_balance: m_batteryPolicyComboBox->setCurrentIndex(0); break; case power_policy_powersave: m_batteryPolicyComboBox->setCurrentIndex(1); break; default: break; } m_batteryPolicyComboBox->blockSignals(false); } else if (GSETTINGS_KEY_BATTERY_SAVE_SWITCH == key) { m_batterySaveSwitchBtn->blockSignals(true); m_batterySaveSwitchBtn->setChecked( m_powerManagerSettings->get(key).toBool()); m_batterySaveSwitchBtn->blockSignals(false); } else if (GSETTINGS_KEY_LOW_BATTERY_AUTO_SAVE == key) { m_lowPowerAutoBatterySaveSwitchBtn->blockSignals(true); m_lowPowerAutoBatterySaveSwitchBtn->setChecked( m_powerManagerSettings->get(key).toBool()); m_lowPowerAutoBatterySaveSwitchBtn->blockSignals(false); } else if (GSETTINGS_KEY_BATTERY_SAVE_REDUCE_BRIGHTNESS == key) { m_reduceBrightnessSwitchBtn->blockSignals(true); m_reduceBrightnessSwitchBtn->setChecked( m_powerManagerSettings->get(key).toBool()); m_reduceBrightnessSwitchBtn->blockSignals(false); } else if (GSETTINGS_KEY_PERCENTAGE_LOW == key) { m_lowPowerNotificationComboBox->blockSignals(true); m_lowPowerNotificationComboBox->setCurrentIndex( m_powerManagerSettings->get(key).toInt() / 10 - 1); m_lowPowerNotificationComboBox->blockSignals(false); } else if (GSETTINGS_KEY_PERCENTAGE_ACTION == key) { m_criticalPercentageComboBox->blockSignals(true); m_criticalPercentageComboBox->setCurrentIndex( m_powerManagerSettings->get(key).toInt() - 5); m_criticalPercentageComboBox->blockSignals(false); } else if (GSETTINGS_KEY_ACTION_CRITICAL_BATTERY == key) { m_criticalPercentageActionComboBox->blockSignals(true); m_criticalPercentageActionComboBox->setCurrentIndex( m_criticalPercentageActionComboBox->findData( m_powerManagerSettings->get(key).toString())); m_criticalPercentageActionComboBox->blockSignals(false); } } void Power::dealUPowerDBusMessage(QDBusMessage msg) { const QDBusArgument &dbusArgs = msg.arguments().at(1).value(); QMap map; dbusArgs >> map; if (m_hasBattery) { if (map.contains("OnBattery")) { m_batteryOnline = map.value(QString("OnBattery")).toBool(); if (m_batteryOnline) { m_batterySavePlanTitleLabel->show(); m_batterySavePlanFrame->show(); } else { m_batterySavePlanTitleLabel->hide(); m_batterySavePlanFrame->hide(); } } } } void Power::setVisibleBySecurity() { // 安全管控 免密登录及自动登录设置项的显示与隐藏 QDBusInterface m_interface("org.ukui.ukcc.session", "/", "org.ukui.ukcc.session.interface", QDBusConnection::sessionBus()); QDBusReply obj_reply = m_interface.call("getModuleHideStatus"); if (!obj_reply.isValid()) { qDebug()<<"execute dbus method getModuleHideStatus failed"; } QVariantMap ModuleMap = obj_reply.value(); QString moduleSettings = ModuleMap.value(name().toLower() + "Settings").toString(); QStringList setItems = moduleSettings.split(","); qDebug() << "--------------------" << moduleSettings << "===" << name().toLower(); foreach (const QString &setItem, setItems) { QStringList item = setItem.split(":"); qDebug() << "set item Name: " << item.at(0); if (item.at(0) == "CloseDisplayFrame") { m_wakeUpDisplayNeedPwdFrame->setVisible(item.at(1) == "true"); m_wakeUpDisplayNeedPwdLine->setVisible(item.at(1) == "true"); } if (item.at(0) == "SleepFrame") { m_wakeUpComputerNeedPwdFrame->setVisible(item.at(1) == "true"); m_wakeUpComputerNeedPwdLine->setVisible(item.at(1) == "true"); } } } bool Power::buriedSettings(QString pluginName, QString settingsName, QString action, QString value) { // 埋点数据 char appName[] = "ukui-control-center"; QByteArray actiontr = action.toLocal8Bit(); // toLocal8Bit 支持中文 char *messageType = actiontr.data(); KBuriedPoint pt[3]; pt[0].key = "pluginName"; std::string pluginStr = pluginName.toStdString(); pt[0].value = pluginStr.c_str(); pt[1].key = "settingsName"; std::string settingStr = settingsName.toStdString(); pt[1].value = settingStr.c_str(); pt[2].key = "value"; std::string valueStr = value.toStdString(); pt[2].value = valueStr.c_str(); if (kdk_buried_point(appName, messageType, pt, 3) == -1) { qDebug() << __FUNCTION__ << "messageType:" << action << "pluginName:" << pluginName << "settingsName:" << settingsName << "value:" << value << "buried point fail !" << __LINE__; return false; } return true; } int Power::getDeviceType(const QString &dBusPath) { qDebug() << "device dBus object path:" << dBusPath; QDBusInterface dBusInterface("org.freedesktop.UPower", dBusPath, "org.freedesktop.DBus.Properties", QDBusConnection::systemBus()); QDBusReply reply = dBusInterface.call("Get", "org.freedesktop.UPower.Device", "Type"); if (reply.isValid()) { return reply.value().toInt(); } else { qDebug() << "Get device type failed"; return 0; } } ukui-power-manager-4.0.0.1/ukui-power-manager-tray/0000775000175000017500000000000014607363245020521 5ustar fengfengukui-power-manager-4.0.0.1/ukui-power-manager-tray/powertray.h0000664000175000017500000000425014601232446022717 0ustar fengfeng/* * Copyright 2023 KylinSoft Co., Ltd. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ #ifndef POWERTRAY_H #define POWERTRAY_H #include #include #include #include #include #include "powerwindow.h" #include "powersupplydev.h" #include "criticalpercentageaction.h" class PowerTray : public QObject { Q_OBJECT public: explicit PowerTray(QObject *parent = 0); ~PowerTray(); void initPowerTray(); private: void setTrayIconToolTipForAcOnlineChanged(bool acOnlineState, double percentage); void setTrayIconToolTipForBatteryInfoChanged(double percentage); void setTrayIcon(QString strIconName); void initTrayMenuUI(); void initPowerWindowUI(); void setPowerWindowProperties(); void updateBatteryInfo(); void acOnlineStateChangedAction(); private: PowerSupplyDev *m_powerSupplyDev; QTimer *m_acChangeTimer; bool m_isPowerSupplyChange; QGSettings *m_settings; int m_showBatteryLeftTime; QMenu *m_TrayMenu; powerwindow *m_powerWindow; QSystemTrayIcon *m_trayIcon; bool m_acOnlineState; int m_batteryState; double m_batteryPercentage; QString m_trayIconName; CriticalPercentageAction *m_criticalPercentageAction; NotificationDialog *m_dialog; private Q_SLOTS: void onActivatedIcon(QSystemTrayIcon::ActivationReason reason); void dealAcOnlineStateChanged(int, bool); void dealBatteryInfoChanged(int, QStringList); }; #endif // POWERTRAY_H ukui-power-manager-4.0.0.1/ukui-power-manager-tray/customstyle.h0000664000175000017500000002012414601232446023254 0ustar fengfeng/* * Copyright (C) 2023 KylinSoft Co., Ltd. * * This program or 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 Street, Fifth Floor, * Boston, MA 02110-1301 USA */ #ifndef CUSTOMSTYLE_H #define CUSTOMSTYLE_H #include #include /*! * \brief The CustomStyle class * \details * 自定义QStyle * 基于QProxyStyle,默认使用QProxyStyle的实例绘制控件,你需要针对某一个控件重新实现若干对应的接口。 * QProxyStyle可以从现有的qt style实例化,我们只需要知道这个style的名字即可。 * 这种做法带来了不错的扩展性和自由度,因为我们不需要将某个style的代码直接引入我们的项目中, * 也能够“继承”这个style类进行二次开发。 * * 下面的方法展现了QStyle的所有的接口,使用QStyle进行控件的绘制使得qt应用能够进行风格的切换, * 从而达到不修改项目源码却对应用外观产生巨大影响的效果。 * * \note * 需要注意QStyle与QSS并不兼容,因为QSS本身其实上也是QStyle的一种实现,对一个控件而言,本身理论上只能 * 在同一时间调用唯一一个QStyle进行绘制。 */ class CustomStyle : public QProxyStyle { Q_OBJECT public: //proxyStyleName 是关于样式类型的,&proxyStyleName = "windows" 会造成toolTips的样式为windows类型样式 explicit CustomStyle(const QString &proxyStyleName = "ukui",bool multileWins=false, QObject *parent = nullptr); ~CustomStyle(); /*! * \brief drawComplexControl * \param control 比如ScrollBar,对应CC枚举类型 * \param option * \param painter * \param widget * \details * drawComplexControl用于绘制具有子控件的复杂控件,它本身一般不直接绘制控件, * 而是通过QStyle的其它方法将复杂控件分解成子控件再调用其它的draw方法绘制。 * 如果你需要重新实现一个复杂控件的绘制方法,首先考虑的应该是在不改变它原有的绘制流程的情况下, * 对它调用到的其它方法进行重写。 * * 如果你不想使用原有的绘制流程,那你需要重写这个接口,然后自己实现一切, * 包括背景的绘制,子控件的位置和状态计算,子控件的绘制等。 * 所以,你需要对这个控件有足够的了解之后再尝试直接重写这个接口。 */ virtual void drawComplexControl(QStyle::ComplexControl control, const QStyleOptionComplex *option, QPainter *painter, const QWidget *widget = nullptr) const; /*! * \brief drawControl * \param element 比如按钮,对应CE枚举类型 * \param option * \param painter * \param widget * \details * drawControl用于绘制基本控件元素,它本身一般只负责绘制控件的一部分或者一层。 * 如果你想要知道控件具体如何绘制,你需要同时研究这个控件的源码和QStyle中的源码, * 因为它们都有可能改变控件的绘制流程。 * * QStyle一般会遵循QCommonStyle的绘制流程,QCommenStyle是大部分主流style的最基类, * 它本身不能完全称之为一个主题,如果你直接使用它,你的控件将不能被正常绘制,因为它有可能只是 * 在特定的时候执行了特定却未实现的绘制方法,它更像一个框架或者规范。 */ virtual void drawControl(QStyle::ControlElement element, const QStyleOption *option, QPainter *painter, const QWidget *widget = nullptr) const; virtual void drawItemPixmap(QPainter *painter, const QRect &rectangle, int alignment, const QPixmap &pixmap) const; virtual void drawItemText(QPainter *painter, const QRect &rectangle, int alignment, const QPalette &palette, bool enabled, const QString &text, QPalette::ColorRole textRole = QPalette::NoRole) const; /*! * \brief drawPrimitive * \param element 背景绘制,对应PE枚举类型 * \param option * \param painter * \param widget * \details * drawPrimitive用于绘制控件背景,比如按钮和菜单的背景, * 我们一般需要判断控件的状态来绘制不同的背景, * 比如按钮的hover和点击效果。 */ virtual void drawPrimitive(QStyle::PrimitiveElement element, const QStyleOption *option, QPainter *painter, const QWidget *widget = nullptr) const; virtual QPixmap generatedIconPixmap(QIcon::Mode iconMode, const QPixmap &pixmap, const QStyleOption *option) const; virtual QStyle::SubControl hitTestComplexControl(QStyle::ComplexControl control, const QStyleOptionComplex *option, const QPoint &position, const QWidget *widget = nullptr) const; virtual QRect itemPixmapRect(const QRect &rectangle, int alignment, const QPixmap &pixmap) const; virtual QRect itemTextRect(const QFontMetrics &metrics, const QRect &rectangle, int alignment, bool enabled, const QString &text) const; //virtual int layoutSpacing(QSizePolicy::ControlType control1, QSizePolicy::ControlType control2, Qt::Orientation orientation, const QStyleOption *option, const QWidget *widget); virtual int pixelMetric(QStyle::PixelMetric metric, const QStyleOption *option = nullptr, const QWidget *widget = nullptr) const; /*! * \brief polish * \param widget * \details * polish用于对widget进行预处理,一般我们可以在polish中修改其属性, * 另外,polish是对动画和特效实现而言十分重要的一个方法, * 通过polish我们能够使widget和特效和动画形成对应关系。 */ virtual void polish(QWidget *widget); virtual void polish(QApplication *application); virtual void polish(QPalette &palette); virtual void unpolish(QWidget *widget); virtual void unpolish(QApplication *application); virtual QSize sizeFromContents(QStyle::ContentsType type, const QStyleOption *option, const QSize &contentsSize, const QWidget *widget = nullptr) const; virtual QIcon standardIcon(QStyle::StandardPixmap standardIcon, const QStyleOption *option, const QWidget *widget) const; virtual QPalette standardPalette() const; /*! * \brief styleHint * \param hint 对应的枚举是SH * \param option * \param widget * \param returnData * \return * \details * styleHint比较特殊,通过它我们能够改变一些控件的绘制流程或者方式,比如说QMenu是否可以滚动。 */ virtual int styleHint(QStyle::StyleHint hint, const QStyleOption *option = nullptr, const QWidget *widget = nullptr, QStyleHintReturn *returnData = nullptr) const; /*! * \brief subControlRect * \param control * \param option * \param subControl * \param widget * \return * \details * subControlRect返回子控件的位置和大小信息,这个方法一般在内置流程中调用, * 如果我们要重写某个绘制方法,可能需要用到它 */ virtual QRect subControlRect(QStyle::ComplexControl control, const QStyleOptionComplex *option, QStyle::SubControl subControl, const QWidget *widget = nullptr) const; /*! * \brief subElementRect * \param element * \param option * \param widget * \return * \details * 与subControlRect类似 */ virtual QRect subElementRect(QStyle::SubElement element, const QStyleOption *option, const QWidget *widget = nullptr) const; Q_SIGNALS: public Q_SLOTS: private: QString pluginName; bool multileWindow = false; }; #endif // CUSTOMSTYLE_H ukui-power-manager-4.0.0.1/ukui-power-manager-tray/notificationdialog.h0000664000175000017500000000352714601232446024537 0ustar fengfeng/* * Copyright 2023 KylinSoft Co., Ltd. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ #ifndef NOTIFICATIONDIALOG_H #define NOTIFICATIONDIALOG_H #include #include #include #include #include #include #include #include #include class NotificationDialog : public QDialog { Q_OBJECT private: QVBoxLayout *m_layout = nullptr; QHBoxLayout *m_topLayout = nullptr; QVBoxLayout *m_verLayout = nullptr; QPushButton *m_confirmBtn = nullptr; QPushButton *m_closeButton = nullptr; QLabel *m_tipsLabel = nullptr; QLabel *m_icon = nullptr; QLabel *m_title = nullptr; QTimer *m_showTimer = nullptr; QTimer *m_clockTimer = nullptr; QString m_showText; QString m_warningText; void uiInit(); void timerInit(); protected Q_SLOTS: void confirmBtnClicked(); void showTime(); void stopTimer(); protected: void paintEvent(QPaintEvent *); bool eventFilter(QObject *watched, QEvent *event); public: void start(); void setShowMsg(QString str); NotificationDialog(QWidget *parent = nullptr); ~NotificationDialog(); Q_SIGNALS: void dialogClosed(); }; #endif // NOTIFICATIONDIALOG_H ukui-power-manager-4.0.0.1/ukui-power-manager-tray/kylable.cpp0000664000175000017500000000642714601232446022651 0ustar fengfeng/* * Copyright (C) 2023, KylinSoft Co., Ltd. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . * */ #include "kylable.h" #include #include #include #include #include #define FOREGROUND_COLOR_NORMAL qApp->palette().text().color() static inline qreal mixQreal(qreal a, qreal b, qreal bias) { return a + (b - a) * bias; } QColor mixColor(const QColor &c1, const QColor &c2, qreal bias) { if (bias <= 0.0) { return c1; } if (bias >= 1.0) { return c2; } if (qIsNaN(bias)) { return c1; } qreal r = mixQreal(c1.redF(), c2.redF(), bias); qreal g = mixQreal(c1.greenF(), c2.greenF(), bias); qreal b = mixQreal(c1.blueF(), c2.blueF(), bias); qreal a = mixQreal(c1.alphaF(), c2.alphaF(), bias); return QColor::fromRgbF(r, g, b, a); } KyLable::KyLable(QWidget *parent) : QLabel(parent), m_styleSettings(new QGSettings(QByteArray("org.ukui.style"))) { connect(qApp, &QApplication::paletteChanged, this, &KyLable::onPaletteChanged); connect(m_styleSettings, &QGSettings::changed, this, [=](QString key) { if ("styleName" == key) { setNormalColor(); this->update(); } }); onPaletteChanged(); } void KyLable::onPaletteChanged() { qDebug() << "palette changed!"; m_foregroundColor = FOREGROUND_COLOR_NORMAL; this->repaint(); } void KyLable::setPressColor() { QColor hightlight = this->palette().color(QPalette::Active, QPalette::Highlight); QColor mix = this->palette().color(QPalette::Active, QPalette::BrightText); m_foregroundColor = mixColor(hightlight, mix, 0.05); } void KyLable::setHoverColor() { QColor hightlight = this->palette().color(QPalette::Active, QPalette::Highlight); QColor mix = this->palette().color(QPalette::Active, QPalette::BrightText); m_foregroundColor = mixColor(hightlight, mix, 0.2); } void KyLable::setNormalColor() { m_foregroundColor = FOREGROUND_COLOR_NORMAL; } void KyLable::paintEvent(QPaintEvent *event) { QPalette pal = this->palette(); pal.setColor(QPalette::WindowText, m_foregroundColor); this->setPalette(pal); return QLabel::paintEvent(event); } void KyLable::enterEvent(QEvent *event) { setHoverColor(); this->update(); } void KyLable::leaveEvent(QEvent *event) { setNormalColor(); this->update(); } void KyLable::mousePressEvent(QMouseEvent *event) { setPressColor(); this->update(); return QLabel::mousePressEvent(event); } void KyLable::mouseReleaseEvent(QMouseEvent *event) { setHoverColor(); this->update(); QProcess::startDetached(QString("ukui-control-center -m Power")); return QLabel::mouseReleaseEvent(event); } ukui-power-manager-4.0.0.1/ukui-power-manager-tray/criticalpercentageaction.h0000664000175000017500000000327514601232446025717 0ustar fengfeng/* * Copyright 2023 KylinSoft Co., Ltd. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ #ifndef CRITICALPERCENTAGEACTION_H #define CRITICALPERCENTAGEACTION_H #include #include #include #include "powersupplydev.h" #include "notificationdialog.h" #include "fullscreenmask.h" class CriticalPercentageAction : public QObject { Q_OBJECT public: explicit CriticalPercentageAction(PowerSupplyDev *powerSupplyDev, QObject *parent = nullptr); ~CriticalPercentageAction(); private: PowerSupplyDev *m_powerSupplyDev; bool m_acOnlineState; double m_batteryPercentage; QGSettings *m_settings; QTimer *m_timer; int m_criticalPercentage; QString m_action; NotificationDialog *m_notificationDialog; FullScreenMask *m_fullScreenMask; bool m_criticalState; void dealAction(); void stopAction(); void doAction(); private Q_SLOTS: void dealAcOnlineStateChanged(int, bool); void dealBatteryInfoChanged(int, QStringList); }; #endif // CRITICALPERCENTAGEACTION_H ukui-power-manager-4.0.0.1/ukui-power-manager-tray/ukui-power-manager-tray.pro0000664000175000017500000000570114601232446025732 0ustar fengfeng#------------------------------------------------- # # Project created by QtCreator 2020-01-06T10:55:07 # #------------------------------------------------- QT += core gui dbus KWindowSystem x11extras greaterThan(QT_MAJOR_VERSION, 4): QT += widgets TARGET = ukui-power-manager-tray TEMPLATE = app target.path = /usr/bin INSTALLS += target # The following define makes your compiler emit warnings if you use # any feature of Qt which has been marked as deprecated (the exact warnings # depend on your compiler). Please consult the documentation of the # deprecated API in order to know how to port your code away from it. DEFINES += QT_DEPRECATED_WARNINGS # You can also make your code fail to compile if you use deprecated APIs. # In order to do so, uncomment the following line. # You can also select to disable deprecated APIs only up to a certain version of Qt. #DEFINES += QT_DISABLE_DEPRECATED_BEFORE=0x060000 # disables all the APIs deprecated before Qt 6.0.0 TRANSLATIONS+=\ translations/ukui-power-manager-tray_bo_CN.ts \ translations/ukui-power-manager-tray_zh_CN.ts \ translations/ukui-power-manager-tray_tr.ts QM_FILES_INSTALL_PATH = /usr/share/ukui-power-manager/tray/translations/ # CONFIG += lrelase not work for qt5.6, add those from lrelease.prf for compatibility qtPrepareTool(QMAKE_LRELEASE, lrelease) lrelease.name = lrelease lrelease.input = TRANSLATIONS lrelease.output = ${QMAKE_FILE_IN_BASE}.qm lrelease.commands = $$QMAKE_LRELEASE ${QMAKE_FILE_IN} -qm ${QMAKE_FILE_OUT} lrelease.CONFIG = no_link QMAKE_EXTRA_COMPILERS += lrelease PRE_TARGETDEPS += compiler_lrelease_make_all for (translation, TRANSLATIONS) { translation = $$basename(translation) QM_FILES += $$OUT_PWD/$$replace(translation, \\..*$, .qm) } qm_files.files = $$QM_FILES qm_files.path = $$QM_FILES_INSTALL_PATH qm_files.CONFIG = no_check_exist INSTALLS += qm_files # So we can access it from main.cpp DEFINES += QM_FILES_INSTALL_PATH='\\"$${QM_FILES_INSTALL_PATH}\\"' #LIBS += -lukui-log4qt CONFIG += c++11 no_keywords link_pkgconfig PKGCONFIG += gsettings-qt x11 kysdk-qtwidgets kysdk-waylandhelper SOURCES += \ criticalpercentageaction.cpp \ divider.cpp \ fullscreenmask.cpp \ main.cpp \ notificationdialog.cpp \ powersupplydev.cpp \ powertray.cpp \ powerwindow.cpp \ kylable.cpp \ upower-dbus/upowerbatterydbus.cpp \ upower-dbus/upowerdbus.cpp \ upower-dbus/upowerlinepowerdbus.cpp \ xatom-helper.cpp \ customstyle.cpp HEADERS += \ criticalpercentageaction.h \ divider.h \ fullscreenmask.h \ notificationdialog.h \ powersupplydev.h \ powertray.h \ powerwindow.h \ kylable.h \ upower-dbus/upowerbatterydbus.h \ upower-dbus/upowerdbus.h \ upower-dbus/upowerlinepowerdbus.h \ xatom-helper.h \ customstyle.h FORMS += desktop.files += resources/ukui-power-manager-tray.desktop desktop.path = /etc/xdg/autostart/ INSTALLS += desktop # Default rules for deployment. ukui-power-manager-4.0.0.1/ukui-power-manager-tray/xatom-helper.cpp0000664000175000017500000001374614601232446023635 0ustar fengfeng/* * KWin Style UKUI * * Copyright (C) 2020, KylinSoft Co., Ltd. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . * * Authors: Yue Lan * */ #include "xatom-helper.h" #include #include #include #include static XAtomHelper *global_instance = nullptr; XAtomHelper *XAtomHelper::getInstance() { if (!global_instance) global_instance = new XAtomHelper; return global_instance; } bool XAtomHelper::isFrameLessWindow(int winId) { auto hints = getInstance()->getWindowMotifHint(winId); if (hints.flags == MWM_HINTS_DECORATIONS && hints.functions == 1) { return true; } return false; } bool XAtomHelper::isWindowDecorateBorderOnly(int winId) { return isWindowMotifHintDecorateBorderOnly(getInstance()->getWindowMotifHint(winId)); } bool XAtomHelper::isWindowMotifHintDecorateBorderOnly(const MotifWmHints &hint) { bool isDeco = false; if (hint.flags & MWM_HINTS_DECORATIONS && hint.flags != MWM_HINTS_DECORATIONS) { if (hint.decorations == MWM_DECOR_BORDER) isDeco = true; } return isDeco; } bool XAtomHelper::isUKUICsdSupported() { // fixme: return false; } bool XAtomHelper::isUKUIDecorationWindow(int winId) { if (m_ukuiDecorationAtion == None) return false; Atom type; int format; ulong nitems; ulong bytes_after; uchar *data; bool isUKUIDecoration = false; XGetWindowProperty(QX11Info::display(), winId, m_ukuiDecorationAtion, 0, LONG_MAX, false, m_ukuiDecorationAtion, &type, &format, &nitems, &bytes_after, &data); if (type == m_ukuiDecorationAtion) { if (nitems == 1) { isUKUIDecoration = data[0]; } } return isUKUIDecoration; } UnityCorners XAtomHelper::getWindowBorderRadius(int winId) { UnityCorners corners; Atom type; int format; ulong nitems; ulong bytes_after; uchar *data; if (m_unityBorderRadiusAtom != None) { XGetWindowProperty(QX11Info::display(), winId, m_unityBorderRadiusAtom, 0, LONG_MAX, false, XA_CARDINAL, &type, &format, &nitems, &bytes_after, &data); if (type == XA_CARDINAL) { if (nitems == 4) { corners.topLeft = static_cast(data[0]); corners.topRight = static_cast(data[1*sizeof (ulong)]); corners.bottomLeft = static_cast(data[2*sizeof (ulong)]); corners.bottomRight = static_cast(data[3*sizeof (ulong)]); } XFree(data); } } return corners; } void XAtomHelper::setWindowBorderRadius(int winId, const UnityCorners &data) { if (m_unityBorderRadiusAtom == None) return; ulong corners[4] = {data.topLeft, data.topRight, data.bottomLeft, data.bottomRight}; XChangeProperty(QX11Info::display(), winId, m_unityBorderRadiusAtom, XA_CARDINAL, 32, XCB_PROP_MODE_REPLACE, (const unsigned char *) &corners, sizeof (corners)/sizeof (corners[0])); } void XAtomHelper::setWindowBorderRadius(int winId, int topLeft, int topRight, int bottomLeft, int bottomRight) { if (m_unityBorderRadiusAtom == None) return; ulong corners[4] = {(ulong)topLeft, (ulong)topRight, (ulong)bottomLeft, (ulong)bottomRight}; XChangeProperty(QX11Info::display(), winId, m_unityBorderRadiusAtom, XA_CARDINAL, 32, XCB_PROP_MODE_REPLACE, (const unsigned char *) &corners, sizeof (corners)/sizeof (corners[0])); } void XAtomHelper::setUKUIDecoraiontHint(int winId, bool set) { if (m_ukuiDecorationAtion == None) return; XChangeProperty(QX11Info::display(), winId, m_ukuiDecorationAtion, m_ukuiDecorationAtion, 32, XCB_PROP_MODE_REPLACE, (const unsigned char *) &set, 1); } void XAtomHelper::setWindowMotifHint(int winId, const MotifWmHints &hints) { if (m_unityBorderRadiusAtom == None) return; XChangeProperty(QX11Info::display(), winId, m_motifWMHintsAtom, m_motifWMHintsAtom, 32, XCB_PROP_MODE_REPLACE, (const unsigned char *)&hints, sizeof (MotifWmHints)/ sizeof (ulong)); } MotifWmHints XAtomHelper::getWindowMotifHint(int winId) { MotifWmHints hints; if (m_unityBorderRadiusAtom == None) return hints; uchar *data; Atom type; int format; ulong nitems; ulong bytes_after; XGetWindowProperty(QX11Info::display(), winId, m_motifWMHintsAtom, 0, sizeof (MotifWmHints)/sizeof (long), false, AnyPropertyType, &type, &format, &nitems, &bytes_after, &data); if (type == None) { return hints; } else { hints = *(MotifWmHints *)data; XFree(data); } return hints; } XAtomHelper::XAtomHelper(QObject *parent) : QObject(parent) { if (!QX11Info::isPlatformX11()) return; m_motifWMHintsAtom = XInternAtom(QX11Info::display(), "_MOTIF_WM_HINTS", true); m_unityBorderRadiusAtom = XInternAtom(QX11Info::display(), "_UNITY_GTK_BORDER_RADIUS", false); m_ukuiDecorationAtion = XInternAtom(QX11Info::display(), "_KWIN_UKUI_DECORAION", false); } Atom XAtomHelper::registerUKUICsdNetWmSupportAtom() { // fixme: return None; } void XAtomHelper::unregisterUKUICsdNetWmSupportAtom() { // fixme: } ukui-power-manager-4.0.0.1/ukui-power-manager-tray/powersupplydev.cpp0000664000175000017500000001704314601232446024332 0ustar fengfeng/* * Copyright 2023 KylinSoft Co., Ltd. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ #include #include "powersupplydev.h" PowerSupplyDev::PowerSupplyDev(QObject *parent) : QObject(parent) { m_upowerDBus = new UPowerDBus(this); connect(m_upowerDBus, &UPowerDBus::lidStateChanged, this, &PowerSupplyDev::dealLidStateChanged); connect(m_upowerDBus, &UPowerDBus::batteryOnlineStateChanged, this, &PowerSupplyDev::dealBatteryOnlineStateChanged); int index = 0; QStringList batteryPathList = m_upowerDBus->getBatteryPathList(); for (index = 0; index < batteryPathList.size(); ++index) { UpowerBatteryDBus *upowerBatteryDBus = new UpowerBatteryDBus(index, batteryPathList.at(index), this); connect(upowerBatteryDBus, &UpowerBatteryDBus::batteryInfoChanged, this, &PowerSupplyDev::dealBatteryInfoChanged); m_batteryDBusVector << upowerBatteryDBus; } QStringList linePowerPathList = m_upowerDBus->getLinePowerPathList(); for (index = 0; index < linePowerPathList.size(); ++index) { UpowerLinePowerDBus *upowerLinePowerDBus = new UpowerLinePowerDBus(index, linePowerPathList.at(index), this); connect(upowerLinePowerDBus, &UpowerLinePowerDBus::acOnlineStateChanged, this, &PowerSupplyDev::dealAcOnlineStateChanged); m_linePowerDBusVector << upowerLinePowerDBus; } qDebug() << "Battery Num:" << m_batteryDBusVector.size(); qDebug() << "line power Num:" << m_linePowerDBusVector.size(); } PowerSupplyDev::~PowerSupplyDev() {} void PowerSupplyDev::dealLidStateChanged(bool value) { qDebug() << "dealLidStateChanged"; Q_EMIT lidStateChanged(value); } void PowerSupplyDev::dealBatteryOnlineStateChanged(bool value) { Q_EMIT batteryOnlineStateChanged(value); } void PowerSupplyDev::dealBatteryInfoChanged(int index, QStringList batteryInfoChangedList) { qDebug() << "dealBatteryInfoChanged"; Q_EMIT batteryInfoChanged(index, batteryInfoChangedList); } void PowerSupplyDev::dealAcOnlineStateChanged(int index, bool value) { qDebug() << "dealAcOnlineStateChanged"; Q_EMIT acOnlineStateChanged(index, value); } bool PowerSupplyDev::getLidClosedState() { return m_upowerDBus->getLidClosedState(); } bool PowerSupplyDev::getBatteryOnlineState() { return m_upowerDBus->getBatteryOnlineState(); } QString PowerSupplyDev::getUpowerDaemonVersion() { return m_upowerDBus->getUpowerDaemonVersion(); } int PowerSupplyDev::getBatteryNum() { return m_batteryDBusVector.size(); } int PowerSupplyDev::getLinePowerNum() { return m_linePowerDBusVector.size(); } int PowerSupplyDev::getBatteryState(int index) { if (0 == m_batteryDBusVector.size()) { return 0; } return m_batteryDBusVector.at(index)->getBatteryState(); } double PowerSupplyDev::getOneBatteryPercentage(int index) { if (0 == m_batteryDBusVector.size()) { return 0; } return m_batteryDBusVector.at(index)->getBatteryPercentage(); } double PowerSupplyDev::getBatteryPercentage() { if (0 == m_batteryDBusVector.size()) { return 0; } double percentage = 0.0; for (int index = 0; index < m_batteryDBusVector.size(); ++index) { percentage += m_batteryDBusVector.at(index)->getBatteryPercentage(); } return percentage / m_batteryDBusVector.size(); } double PowerSupplyDev::calcBatteryPercentage() { if (0 == m_batteryDBusVector.size()) { return 0; } double energyNow = 0.0; double energyFull = 0.0; for (int index = 0; index < m_batteryDBusVector.size(); ++index) { energyNow += m_batteryDBusVector.at(index)->getEnergyNow(); energyFull += m_batteryDBusVector.at(index)->getEnergyFull(); } return energyNow / energyFull * 100; } double PowerSupplyDev::getEnergyNow(int index) { if (0 == m_batteryDBusVector.size()) { return 0; } return m_batteryDBusVector.at(index)->getEnergyNow(); } double PowerSupplyDev::getEnergyFull(int index) { if (0 == m_batteryDBusVector.size()) { return 0; } return m_batteryDBusVector.at(index)->getEnergyFull(); } double PowerSupplyDev::getEnergyFullDesign(int index) { if (0 == m_batteryDBusVector.size()) { return 0; } return m_batteryDBusVector.at(index)->getEnergyFullDesign(); } double PowerSupplyDev::getEnergyRate(int index) { if (0 == m_batteryDBusVector.size()) { return 0; } return m_batteryDBusVector.at(index)->getEnergyRate(); } qlonglong PowerSupplyDev::getTimeToFull(int index) { if (0 == m_batteryDBusVector.size()) { return 0; } return m_batteryDBusVector.at(index)->getTimeToFull(); } qlonglong PowerSupplyDev::getTimeToEmpty(int index) { if (0 == m_batteryDBusVector.size()) { return 0; } return m_batteryDBusVector.at(index)->getTimeToEmpty(); } double PowerSupplyDev::getBatteryTemperature(int index) { if (0 == m_batteryDBusVector.size()) { return 0; } return m_batteryDBusVector.at(index)->getBatteryTemperature(); } int PowerSupplyDev::getWarninglevel(int index) { if (0 == m_batteryDBusVector.size()) { return 0; } return m_batteryDBusVector.at(index)->getWarninglevel(); } QString PowerSupplyDev::getBatteryVendor(int index) { if (0 == m_batteryDBusVector.size()) { return "unknown"; } return m_batteryDBusVector.at(index)->getBatteryVendor(); } QString PowerSupplyDev::getBatteryModel(int index) { if (0 == m_batteryDBusVector.size()) { return "unknown"; } return m_batteryDBusVector.at(index)->getBatteryModel(); } QString PowerSupplyDev::getOneBatteryIconName(int index) { if (0 == m_batteryDBusVector.size() || 0 == m_linePowerDBusVector.size()) { return "battery-level-0-charging-symbolic"; } double percentage = m_batteryDBusVector.at(index)->getBatteryPercentage(); if (true == m_linePowerDBusVector.at(index)->getAcOnlineState()) { m_batteryIconName = QString("battery-level-%1-charging-symbolic").arg((int)percentage / 10 * 10); } else { m_batteryIconName = QString("battery-level-%1-symbolic").arg((int)percentage / 10 * 10); } return m_batteryIconName; } QString PowerSupplyDev::getBatteryIconName() { if (0 == m_batteryDBusVector.size() || 0 == m_linePowerDBusVector.size()) { return "battery-level-0-charging-symbolic"; } double percentage = getBatteryPercentage(); if (true == getAcOnlineState()) { m_batteryIconName = QString("battery-level-%1-charging-symbolic").arg((int)percentage / 10 * 10); } else { m_batteryIconName = QString("battery-level-%1-symbolic").arg((int)percentage / 10 * 10); } return m_batteryIconName; } bool PowerSupplyDev::getAcOnlineState() { if (0 == m_batteryDBusVector.size() || 0 == m_linePowerDBusVector.size()) { return true; } for (int index = 0; index < m_linePowerDBusVector.size(); ++index) { if (true == m_linePowerDBusVector.at(index)->getAcOnlineState()) { return true; } } return false; } ukui-power-manager-4.0.0.1/ukui-power-manager-tray/upower-dbus/0000775000175000017500000000000014601232446022765 5ustar fengfengukui-power-manager-4.0.0.1/ukui-power-manager-tray/upower-dbus/upowerbatterydbus.cpp0000664000175000017500000001233514601232446027267 0ustar fengfeng/* * Copyright 2023 KylinSoft Co., Ltd. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ #include "upowerbatterydbus.h" UpowerBatteryDBus::UpowerBatteryDBus(int batteryId, const QString &batteryDBusPath, QObject *parent) : QObject(parent), m_batteryId(batteryId) { m_DBusInterface = new QDBusInterface("org.freedesktop.UPower", batteryDBusPath, "org.freedesktop.DBus.Properties", QDBusConnection::systemBus(), this); QDBusConnection::systemBus().connect("org.freedesktop.UPower", batteryDBusPath, "org.freedesktop.DBus.Properties", "PropertiesChanged", this, SLOT(dealBatteryPropertiesMessage(QDBusMessage))); initBatteryInfo(); } UpowerBatteryDBus::~UpowerBatteryDBus() {} void UpowerBatteryDBus::dealBatteryPropertiesMessage(QDBusMessage msg) { const QDBusArgument &dbusArgs = msg.arguments().at(1).value(); QMap map; dbusArgs >> map; QStringList batteryInfoChangedList; if (map.contains("State")) { m_batteryState = map.value(QString("State")).toInt(); batteryInfoChangedList.append("State"); } if (map.contains("Percentage")) { m_percentage = map.value(QString("Percentage")).toDouble(); batteryInfoChangedList.append("Percentage"); } if (map.contains("Energy")) { m_energy = map.value(QString("Energy")).toDouble(); batteryInfoChangedList.append("Energy"); } if (map.contains("EnergyRate")) { m_energyRate = map.value(QString("EnergyRate")).toDouble(); batteryInfoChangedList.append("EnergyRate"); } if (map.contains("TimeToFull")) { m_timeToFull = map.value(QString("TimeToFull")).toLongLong(); batteryInfoChangedList.append("TimeToFull"); } if (map.contains("TimeToEmpty")) { m_timeToEmpty = map.value(QString("TimeToEmpty")).toLongLong(); batteryInfoChangedList.append("TimeToEmpty"); } if (map.contains("Temperature")) { m_temperature = map.value(QString("Temperature")).toDouble(); batteryInfoChangedList.append("Temperature"); } if (map.contains("WarningLevel")) { m_warninglevel = map.value(QString("WarningLevel")).toInt(); batteryInfoChangedList.append("WarningLevel"); } Q_EMIT batteryInfoChanged(m_batteryId, batteryInfoChangedList); } void UpowerBatteryDBus::initBatteryInfo() { QDBusMessage msg = m_DBusInterface->call("GetAll", "org.freedesktop.UPower.Device"); if (msg.type() == QDBusMessage::ReplyMessage) { const QDBusArgument &dbusArgs = msg.arguments().at(0).value(); QMap map; dbusArgs >> map; m_batteryState = map.value(QString("State")).toInt(); m_percentage = map.value(QString("Percentage")).toDouble(); m_energy = map.value(QString("Energy")).toDouble(); m_energyFull = map.value(QString("EnergyFull")).toDouble(); m_energyFullDesign = map.value(QString("EnergyFullDesign")).toDouble(); m_energyRate = map.value(QString("EnergyRate")).toDouble(); m_timeToFull = map.value(QString("TimeToFull")).toLongLong(); m_timeToEmpty = map.value(QString("TimeToEmpty")).toLongLong(); m_temperature = map.value(QString("Temperature")).toDouble(); m_warninglevel = map.value(QString("WarningLevel")).toInt(); m_vendor = map.value(QString("Vendor")).toString(); m_model = map.value(QString("Model")).toString(); } } int UpowerBatteryDBus::getBatteryState() { return m_batteryState; } double UpowerBatteryDBus::getBatteryPercentage() { return m_percentage; } double UpowerBatteryDBus::getEnergyNow() { return m_energy; } double UpowerBatteryDBus::getEnergyFull() { return m_energyFull; } double UpowerBatteryDBus::getEnergyFullDesign() { return m_energyFullDesign; } double UpowerBatteryDBus::getEnergyRate() { return m_energyRate; } qlonglong UpowerBatteryDBus::getTimeToFull() { return m_timeToFull; } qlonglong UpowerBatteryDBus::getTimeToEmpty() { return m_timeToEmpty; } double UpowerBatteryDBus::getBatteryTemperature() { return m_temperature; } int UpowerBatteryDBus::getWarninglevel() { return m_warninglevel; } QString UpowerBatteryDBus::getBatteryVendor() { return m_vendor; } QString UpowerBatteryDBus::getBatteryModel() { return m_model; } ukui-power-manager-4.0.0.1/ukui-power-manager-tray/upower-dbus/upowerdbus.h0000664000175000017500000000404514601232446025340 0ustar fengfeng/* * Copyright 2023 KylinSoft Co., Ltd. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ #ifndef UPOWERDBUS_H #define UPOWERDBUS_H #include #include #include enum up_device_type { up_device_type_unknown = 0, up_device_type_line_power, up_device_type_battery, up_device_type_ups, up_device_type_monitor, up_device_type_mouse, up_device_type_keyboard, up_device_type_pda, up_device_type_phone, up_device_type_media_player, up_device_type_tablet, up_device_type_computer, up_device_type_max }; class UPowerDBus : public QObject { Q_OBJECT public: explicit UPowerDBus(QObject *parent = nullptr); ~UPowerDBus(); private: int getDeviceType(const QString &); void initDeviceInfo(); void dealLidClosedMessage(bool); void dealBatteryOnlineMessage(bool); QDBusInterface *m_DBusInterface; bool m_hasLid; bool m_lidIsClosed; bool m_batteryOnline; QString m_upowerDaemonVersion; QStringList m_batteryPathList; QStringList m_linePowerPathList; private Q_SLOTS: void dealUPowerDBusMessage(QDBusMessage); Q_SIGNALS: void lidStateChanged(bool); void batteryOnlineStateChanged(bool); public: bool hasLid(); bool getLidClosedState(); bool getBatteryOnlineState(); QString getUpowerDaemonVersion(); QStringList getBatteryPathList(); QStringList getLinePowerPathList(); }; #endif // UPOWERDBUS_H ukui-power-manager-4.0.0.1/ukui-power-manager-tray/upower-dbus/upowerbatterydbus.h0000664000175000017500000000365414601232446026740 0ustar fengfeng/* * Copyright 2023 KylinSoft Co., Ltd. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ #ifndef UPOWERBATTERYDBUS_H #define UPOWERBATTERYDBUS_H #include #include #include class UpowerBatteryDBus : public QObject { Q_OBJECT public: explicit UpowerBatteryDBus(int batteryId, const QString &batteryDBusPath, QObject *parent = nullptr); ~UpowerBatteryDBus(); private: void initBatteryInfo(); int m_batteryId; QDBusInterface *m_DBusInterface; int m_batteryState; double m_percentage; double m_energy; double m_energyFull; double m_energyFullDesign; double m_energyRate; qlonglong m_timeToFull; qlonglong m_timeToEmpty; double m_temperature; int m_warninglevel; QString m_vendor; QString m_model; Q_SIGNALS: void batteryInfoChanged(int, QStringList); private Q_SLOTS: void dealBatteryPropertiesMessage(QDBusMessage); public: int getBatteryState(); double getBatteryPercentage(); double getEnergyNow(); double getEnergyFull(); double getEnergyFullDesign(); double getEnergyRate(); qlonglong getTimeToFull(); qlonglong getTimeToEmpty(); double getBatteryTemperature(); int getWarninglevel(); QString getBatteryVendor(); QString getBatteryModel(); }; #endif // UPOWERBATTERYDBUS_H ukui-power-manager-4.0.0.1/ukui-power-manager-tray/upower-dbus/upowerlinepowerdbus.h0000664000175000017500000000245414601232446027267 0ustar fengfeng/* * Copyright 2023 KylinSoft Co., Ltd. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ #ifndef UPOWERLINEPOWERDBUS_H #define UPOWERLINEPOWERDBUS_H #include #include #include class UpowerLinePowerDBus : public QObject { Q_OBJECT public: explicit UpowerLinePowerDBus(int linePowerId, const QString &linePowerDBusPath, QObject *parent = nullptr); ~UpowerLinePowerDBus(); private: int m_linePowerId; QDBusInterface *m_DBusInterface; bool m_acOnlineState; Q_SIGNALS: void acOnlineStateChanged(int, bool); private Q_SLOTS: void dealLinePowerPropertiesMessage(QDBusMessage); public: int getAcOnlineState(); }; #endif // UPOWERLINEPOWERDBUS_H ukui-power-manager-4.0.0.1/ukui-power-manager-tray/upower-dbus/upowerdbus.cpp0000664000175000017500000001164014601232446025672 0ustar fengfeng/* * Copyright 2023 KylinSoft Co., Ltd. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ #include "upowerdbus.h" UPowerDBus::UPowerDBus(QObject *parent) : QObject(parent) { m_DBusInterface = new QDBusInterface("org.freedesktop.UPower", "/org/freedesktop/UPower", "org.freedesktop.DBus.Properties", QDBusConnection::systemBus()); QDBusConnection::systemBus().connect("org.freedesktop.UPower", "/org/freedesktop/UPower", "org.freedesktop.DBus.Properties", "PropertiesChanged", this, SLOT(dealUPowerDBusMessage(QDBusMessage))); QDBusInterface dBusInterface("org.freedesktop.UPower", "/org/freedesktop/UPower", "org.freedesktop.UPower", QDBusConnection::systemBus()); QDBusReply> reply = dBusInterface.call("EnumerateDevices"); if (dBusInterface.isValid()) { for (QDBusObjectPath dBusObjectPath : reply.value()) { int upDeviceType = getDeviceType(dBusObjectPath.path()); qDebug() << "device type:" << upDeviceType; if (up_device_type_line_power == upDeviceType) { m_linePowerPathList << dBusObjectPath.path(); qDebug() << "line_power dBusObjectPath:" << dBusObjectPath.path(); } else if (up_device_type_battery == upDeviceType) { m_batteryPathList << dBusObjectPath.path(); qDebug() << "battery dBusObjectPath:" << dBusObjectPath.path(); } } } initDeviceInfo(); } UPowerDBus::~UPowerDBus() { delete m_DBusInterface; } int UPowerDBus::getDeviceType(const QString &dBusPath) { qDebug() << "device dBus object path:" << dBusPath; QDBusInterface dBusInterface("org.freedesktop.UPower", dBusPath, "org.freedesktop.DBus.Properties", QDBusConnection::systemBus()); QDBusReply reply = dBusInterface.call("Get", "org.freedesktop.UPower.Device", "Type"); if (reply.isValid()) { return reply.value().toInt(); } else { qDebug() << "Get device type failed"; return up_device_type_unknown; } } void UPowerDBus::initDeviceInfo() { QDBusMessage msg = m_DBusInterface->call("GetAll", "org.freedesktop.UPower"); if (msg.type() == QDBusMessage::ReplyMessage) { const QDBusArgument &dbusArgs = msg.arguments().at(0).value(); QMap map; dbusArgs >> map; m_hasLid = map.value(QString("LidIsPresent")).toBool(); m_lidIsClosed = map.value(QString("LidIsClosed")).toBool(); m_batteryOnline = map.value(QString("OnBattery")).toBool(); m_upowerDaemonVersion = map.value(QString("DaemonVersion")).toString(); } } void UPowerDBus::dealLidClosedMessage(bool value) { if (m_lidIsClosed != value) { m_lidIsClosed = value; Q_EMIT lidStateChanged(m_lidIsClosed); } } void UPowerDBus::dealBatteryOnlineMessage(bool value) { if (m_batteryOnline != value) { m_batteryOnline = value; Q_EMIT batteryOnlineStateChanged(m_batteryOnline); } } void UPowerDBus::dealUPowerDBusMessage(QDBusMessage msg) { const QDBusArgument &dbusArgs = msg.arguments().at(1).value(); QMap map; dbusArgs >> map; if (map.contains("LidIsClosed")) { dealLidClosedMessage(map.value(QString("LidIsClosed")).toBool()); } if (map.contains("OnBattery")) { dealBatteryOnlineMessage(map.value(QString("OnBattery")).toBool()); } } bool UPowerDBus::hasLid() { return m_hasLid; } bool UPowerDBus::getLidClosedState() { return m_lidIsClosed; } bool UPowerDBus::getBatteryOnlineState() { return m_batteryOnline; } QString UPowerDBus::getUpowerDaemonVersion() { return m_upowerDaemonVersion; } QStringList UPowerDBus::getBatteryPathList() { return m_batteryPathList; } QStringList UPowerDBus::getLinePowerPathList() { return m_linePowerPathList; } ukui-power-manager-4.0.0.1/ukui-power-manager-tray/upower-dbus/upowerlinepowerdbus.cpp0000664000175000017500000000504214601232446027616 0ustar fengfeng/* * Copyright 2023 KylinSoft Co., Ltd. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ #include "upowerlinepowerdbus.h" UpowerLinePowerDBus::UpowerLinePowerDBus(int linePowerId, const QString &linePowerDBusPath, QObject *parent) : QObject(parent), m_linePowerId(linePowerId) { qDebug() << "linePowerDBusPath :" << linePowerDBusPath; m_DBusInterface = new QDBusInterface("org.freedesktop.UPower", linePowerDBusPath, "org.freedesktop.DBus.Properties", QDBusConnection::systemBus(), this); QDBusConnection::systemBus().connect("org.freedesktop.UPower", linePowerDBusPath, "org.freedesktop.DBus.Properties", "PropertiesChanged", this, SLOT(dealLinePowerPropertiesMessage(QDBusMessage))); QDBusReply reply = m_DBusInterface->call("Get", "org.freedesktop.UPower.Device", "Online"); if (reply.isValid()) { m_acOnlineState = reply.value().toBool(); } else { m_acOnlineState = false; } } UpowerLinePowerDBus::~UpowerLinePowerDBus() {} void UpowerLinePowerDBus::dealLinePowerPropertiesMessage(QDBusMessage msg) { const QDBusArgument &dbusArgs = msg.arguments().at(1).value(); QMap map; dbusArgs >> map; qDebug() << "line power id:" << m_linePowerId; if (map.contains("Online")) { bool acOnlineState = map.value(QString("Online")).toBool(); if (m_acOnlineState != acOnlineState) { m_acOnlineState = acOnlineState; Q_EMIT acOnlineStateChanged(m_linePowerId, m_acOnlineState); } } } int UpowerLinePowerDBus::getAcOnlineState() { return m_acOnlineState; } ukui-power-manager-4.0.0.1/ukui-power-manager-tray/criticalpercentageaction.cpp0000664000175000017500000001243314601232446026246 0ustar fengfeng/* * Copyright 2023 KylinSoft Co., Ltd. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ #include #include #include #include "criticalpercentageaction.h" #define POWER_MANAGER_SETTINGS "org.ukui.power-manager" #define POWER_PERCENTAGE_ACTION "percentageAction" #define POWER_ACTION_CRITICAL_BATTERY "actionCriticalBattery" CriticalPercentageAction::CriticalPercentageAction(PowerSupplyDev *powerSupplyDev, QObject *parent) : QObject(parent) { if (nullptr == powerSupplyDev) { m_powerSupplyDev = new PowerSupplyDev(this); } else { m_powerSupplyDev = powerSupplyDev; } m_acOnlineState = m_powerSupplyDev->getAcOnlineState(); connect(m_powerSupplyDev, &PowerSupplyDev::acOnlineStateChanged, this, &CriticalPercentageAction::dealAcOnlineStateChanged); connect(m_powerSupplyDev, &PowerSupplyDev::batteryInfoChanged, this, &CriticalPercentageAction::dealBatteryInfoChanged); m_settings = new QGSettings(POWER_MANAGER_SETTINGS); m_criticalPercentage = m_settings->get(POWER_PERCENTAGE_ACTION).toInt(); m_action = m_settings->get(POWER_ACTION_CRITICAL_BATTERY).toString(); connect(m_settings, &QGSettings::changed, this, [=](const QString &key) { qDebug() << "m_settings changed key:" << key; if (key == POWER_PERCENTAGE_ACTION) { m_criticalPercentage = m_settings->get(POWER_PERCENTAGE_ACTION).toInt(); qDebug() << "critical percentage :" << m_criticalPercentage; } if (key == POWER_ACTION_CRITICAL_BATTERY) { m_action = m_settings->get(POWER_ACTION_CRITICAL_BATTERY).toString(); qDebug() << "critical percentage action:" << m_action; } }); m_criticalState = false; m_timer = new QTimer(this); connect(m_timer, &QTimer::timeout, this, [=]() { doAction(); stopAction(); }); } CriticalPercentageAction::~CriticalPercentageAction() { if (nullptr != m_settings) { delete m_settings; m_settings = nullptr; } if (nullptr != m_notificationDialog) { delete m_notificationDialog; m_notificationDialog = nullptr; } } void CriticalPercentageAction::dealAcOnlineStateChanged(int index, bool value) { Q_UNUSED(index) Q_UNUSED(value) qDebug() << "Critical percentage action deal ac online changed"; m_acOnlineState = m_powerSupplyDev->getAcOnlineState(); if (true == m_acOnlineState) { stopAction(); } else { dealAction(); } } void CriticalPercentageAction::dealBatteryInfoChanged(int index, QStringList batteryInfoChangedList) { Q_UNUSED(index) Q_UNUSED(batteryInfoChangedList) qDebug() << "Critical percentage action deal battery info changed"; if (true == m_acOnlineState) { stopAction(); } else { dealAction(); } } void CriticalPercentageAction::dealAction() { m_batteryPercentage = m_powerSupplyDev->getBatteryPercentage(); if (m_batteryPercentage > m_criticalPercentage) { return ; } if ("nothing" == m_action || true == m_criticalState) { return ; } m_fullScreenMask = new FullScreenMask(); m_fullScreenMask->show(); m_notificationDialog = new NotificationDialog(); connect(m_notificationDialog, &NotificationDialog::dialogClosed, m_fullScreenMask, &FullScreenMask::hide); m_notificationDialog->setShowMsg(m_action); m_notificationDialog->show(); m_notificationDialog->move( (QApplication::desktop()->width() - m_notificationDialog->width()) / 2, (QApplication::desktop()->height() - m_notificationDialog->height()) / 2); m_notificationDialog->start(); m_criticalState = true; m_timer->start(60000); } void CriticalPercentageAction::stopAction() { if (m_timer->isActive()) { m_timer->stop(); m_notificationDialog->hide(); delete m_notificationDialog; m_notificationDialog = nullptr; m_fullScreenMask->hide(); delete m_fullScreenMask; m_fullScreenMask = nullptr; m_criticalState = false; qDebug() << "stop critical percentage action timer success"; } } void CriticalPercentageAction::doAction() { QDBusInterface qDBusInterface("org.ukui.powermanagement", "/", "org.ukui.powermanagement.interface", QDBusConnection::systemBus()); qDebug() << "action:" << m_action; if ("shutdown" == m_action) { qDBusInterface.call("PowerOff"); } else if ("hibernate" == m_action) { qDBusInterface.call("Hibernate"); } else if ("suspend" == m_action){ qDBusInterface.call("Suspend"); } else { ; } } ukui-power-manager-4.0.0.1/ukui-power-manager-tray/xatom-helper.h0000664000175000017500000000624314601232446023274 0ustar fengfeng/* * KWin Style UKUI * * Copyright (C) 2020, KylinSoft Co., Ltd. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . * * Authors: Yue Lan * */ #ifndef XATOMHELPER_H #define XATOMHELPER_H #include #include struct UnityCorners { ulong topLeft = 0; ulong topRight = 0; ulong bottomLeft = 0; ulong bottomRight = 0; }; typedef struct { ulong flags = 0; ulong functions = 0; ulong decorations = 0; long input_mode = 0; ulong status = 0; } MotifWmHints, MwmHints; #define MWM_HINTS_FUNCTIONS (1L << 0) #define MWM_HINTS_DECORATIONS (1L << 1) #define MWM_HINTS_INPUT_MODE (1L << 2) #define MWM_HINTS_STATUS (1L << 3) #define MWM_FUNC_ALL (1L << 0) #define MWM_FUNC_RESIZE (1L << 1) #define MWM_FUNC_MOVE (1L << 2) #define MWM_FUNC_MINIMIZE (1L << 3) #define MWM_FUNC_MAXIMIZE (1L << 4) #define MWM_FUNC_CLOSE (1L << 5) #define MWM_DECOR_ALL (1L << 0) #define MWM_DECOR_BORDER (1L << 1) #define MWM_DECOR_RESIZEH (1L << 2) #define MWM_DECOR_TITLE (1L << 3) #define MWM_DECOR_MENU (1L << 4) #define MWM_DECOR_MINIMIZE (1L << 5) #define MWM_DECOR_MAXIMIZE (1L << 6) #define MWM_INPUT_MODELESS 0 #define MWM_INPUT_PRIMARY_APPLICATION_MODAL 1 #define MWM_INPUT_SYSTEM_MODAL 2 #define MWM_INPUT_FULL_APPLICATION_MODAL 3 #define MWM_INPUT_APPLICATION_MODAL MWM_INPUT_PRIMARY_APPLICATION_MODAL #define MWM_TEAROFF_WINDOW (1L<<0) namespace UKUI { class Decoration; } class XAtomHelper : public QObject { friend class UKUI::Decoration; Q_OBJECT public: static XAtomHelper *getInstance(); static bool isFrameLessWindow(int winId); bool isWindowDecorateBorderOnly(int winId); bool isWindowMotifHintDecorateBorderOnly(const MotifWmHints &hint); bool isUKUICsdSupported(); bool isUKUIDecorationWindow(int winId); UnityCorners getWindowBorderRadius(int winId); void setWindowBorderRadius(int winId, const UnityCorners &data); void setWindowBorderRadius(int winId, int topLeft, int topRight, int bottomLeft, int bottomRight); void setUKUIDecoraiontHint(int winId, bool set = true); void setWindowMotifHint(int winId, const MotifWmHints &hints); MotifWmHints getWindowMotifHint(int winId); private: explicit XAtomHelper(QObject *parent = nullptr); Atom registerUKUICsdNetWmSupportAtom(); void unregisterUKUICsdNetWmSupportAtom(); Atom m_motifWMHintsAtom = None; Atom m_unityBorderRadiusAtom = None; Atom m_ukuiDecorationAtion = None; }; #endif // XATOMHELPER_H ukui-power-manager-4.0.0.1/ukui-power-manager-tray/translations/0000775000175000017500000000000014601232446023232 5ustar fengfengukui-power-manager-4.0.0.1/ukui-power-manager-tray/translations/ukui-power-manager-tray_tr.ts0000664000175000017500000002161014601232446031003 0ustar fengfeng NotificationDialog The system will %1 in 60 seconds as the battery is about to run out. I know The system will %1 in %2 seconds as the battery is about to run out. shutdown hibernate suspend PowerTray SetPower 设置电源和睡眠 fully charged (100%) 已充满 (100%) %1% available (plugged in) %1% 可用 (已接通电源) %1% remaining %1% 可用 %1 min to fully charge (%2%) 剩余 %1 分钟充满 (%2%) %1 hr %2 min to fully charge (%3%) 剩余 %1 小时 %2 分钟充满 (%3%) %1 min (%2%) remaining 剩余 %1 分钟 (%2%) %1 hr %2 min (%3%) remaining 剩余 %1 小时 %2 分钟 (%3%) powerwindow Charging 正在充电 Discharging 正在放电 fully charged 已充满 Endurance 续航 Performance 性能 PowerSettings 电源设置 PowerMode 电源模式 BatteryMode 电池模式 %1 minutes until fully charged %1 分钟后 电池将充满 %1 hour %2 minute until fully charged %1 hour until fully charged %1 hour %2 minutes until fully charged %1 hours %2 minute until fully charged %1 hours until fully charged %1 hours %2 minutes until fully charged %1 小时 %2 分钟后 电池将充满 %1 minutes remaining 剩余 %1 分钟 %1 hour %2 minute remaining %1 hour remaining %1 hour %2 minutes remaining %1 hours %2 minute remaining %1 hours remaining %1 hours %2 minutes remaining 剩余 %1 小时 %2 分钟 Better endurance 更好续航 Better performance 更好性能 Best performance 最佳性能 ukui-power-manager-4.0.0.1/ukui-power-manager-tray/translations/ukui-power-manager-tray_zh_CN.ts0000664000175000017500000002201414601232446031356 0ustar fengfeng NotificationDialog The system will %1 in 60 seconds as the battery is about to run out. 电池电量即将耗尽,系统将在60秒后%1。 I know 确定 The system will %1 in %2 seconds as the battery is about to run out. 电池电量即将耗尽,系统将在%2秒后%1。 shutdown 关机 hibernate 休眠 suspend 睡眠 PowerTray SetPower 设置电源和睡眠 fully charged (100%) 已充满 (100%) %1% available (plugged in) %1% 可用 (已接通电源) %1% remaining %1% 可用 %1 min to fully charge (%2%) 剩余 %1 分钟充满 (%2%) %1 hr %2 min to fully charge (%3%) 剩余 %1 小时 %2 分钟充满 (%3%) %1 min (%2%) remaining 剩余 %1 分钟 (%2%) %1 hr %2 min (%3%) remaining 剩余 %1 小时 %2 分钟 (%3%) powerwindow Charging 正在充电 Discharging 正在放电 fully charged 已充满 Endurance 最佳能效 Performance 最佳性能 PowerSettings 电源设置 PowerMode 电源模式 BatteryMode 电池模式 %1 minutes until fully charged %1 分钟后 电池将充满 %1 hour %2 minute until fully charged %1 小时 %2 分钟后 电池将充满 %1 hour until fully charged %1 小时后 电池将充满 %1 hour %2 minutes until fully charged %1 小时 %2 分钟后 电池将充满 %1 hours %2 minute until fully charged %1 小时 %2 分钟后 电池将充满 %1 hours until fully charged %1 小时后 电池将充满 %1 hours %2 minutes until fully charged %1 小时 %2 分钟后 电池将充满 %1 minutes remaining 剩余 %1 分钟 %1 hour %2 minute remaining 剩余 %1 小时 %2 分钟 %1 hour remaining 剩余 %1 小时 %1 hour %2 minutes remaining 剩余 %1 小时 %2 分钟 %1 hours %2 minute remaining 剩余 %1 小时 %2 分钟 %1 hours remaining 剩余 %1 小时 %1 hours %2 minutes remaining 剩余 %1 小时 %2 分钟 Better endurance 更好续航 Better performance 更好性能 Best performance 最佳性能 ukui-power-manager-4.0.0.1/ukui-power-manager-tray/translations/ukui-power-manager-tray_bo_CN.ts0000664000175000017500000002647514601232446031354 0ustar fengfeng NotificationDialog The system will %1 in 60 seconds as the battery is about to run out. གློག་སྨན་གྱི་གློག་ཚད་ཟད་གྲབས་ཡོད་པས་མ་ལག་སྐར་ཆ་དྲུག་ཅུའི་རྗེས་སུ་%1ཡིན།. I know ངས་ཧ་གོ་སོང་། The system will %1 in %2 seconds as the battery is about to run out. གློག་སྨན་གྱི་གློག་ཚད་ཟད་གྲབས་ཡོད་པ་དང་། མ་ལག་%1དུས་ཚོད་སྐར་ཆ་ཙམ་འགོར་རྗེས་%2རེད།. shutdown ཁ་རྒྱག hibernate མངལ་གནས་སུ་སྦས་པ། suspend གཉིད་ PowerTray SetPower བཀོད་སྒྲིག། fully charged (100%) གློག་གསོག་ཚད་ཚང་མ་(100%) %1% available (plugged in) %1% བཀོལ་སྤྱོད་བྱས་ཆོག (ནང་དུ་བཅུག་པ།) %1% remaining %1% དེ་བྱིངས་ཚང་མ་ལྷག %1 min to fully charge (%2%) སྐར་མ་ %1 ཡི་རིང་ལ་གློག་གསོག་དགོས། (%2%) %1 hr %2 min to fully charge (%3%) ཆུ་ཚོད་ %1 དང་སྐར་མ་ %2 ཡི་རིང་ལ་གློག་གསོག་དགོས། (%3%) %1 min (%2%) remaining དང་སྐར་མ་ %1 ལྷག་ཡོད། (%2%) %1 hr %2 min (%3%) remaining སྐར་མ་ %1 དང་སྐར་མ་ %2 ལྷག་ཡོད། (%3%) powerwindow Charging གློག་གསོག་པའི་ནང། Endurance གློག་གསོག་པའི་ནང། Performance ནུས་པ། PowerSettings བཀོད་སྒྲིག། PowerMode གློག་ཁུངས་དཔེ་དབྱིབས། BatteryMode གློག་གཡིས་དཔེ་དབྱིབས། Discharging གློག་འཁྱུག་པ། %1 minutes until fully charged སྐར་མ་%1 ཕྱོགས་ཡོངས་ནས་གློག་གསོག་རག་བར་ %1 hour %2 minute until fully charged ཆུ་ཚོད་%1དང་སྐར་མ་%2 ཕྱོགས་ཡོངས་ནས་གློག་གསོག་རག་བར་ %1 hour until fully charged ཆུ་ཚོད་%1 ཕྱོགས་ཡོངས་ནས་གློག་གསོག་རག་བར་ %1 hour %2 minutes until fully charged ཆུ་ཚོད་%1དང་སྐར་མ་%2 ཕྱོགས་ཡོངས་ནས་གློག་གསོག་རག་བར་ %1 hours %2 minute until fully charged ཆུ་ཚོད་%1དང་སྐར་མ་%2 ཕྱོགས་ཡོངས་ནས་གློག་གསོག་རག་བར་ %1 hours until fully charged ཆུ་ཚོད་%1 ཕྱོགས་ཡོངས་ནས་གློག་གསོག་རག་བར་ %1 hours %2 minutes until fully charged ཆུ་ཚོད་%1དང་སྐར་མ་%2 ཕྱོགས་ཡོངས་ནས་གློག་གསོག་རག་བར་ %1 minutes remaining དེ་བྱིངས་ཚང་མ་ལྷག སྐར་མ་%1 %1 hour %2 minute remaining དེ་བྱིངས་ཚང་མ་ལྷག ཆུ་ཚོད་%1དང་སྐར་མ་%2 %1 hour remaining དེ་བྱིངས་ཚང་མ་ལྷག ཆུ་ཚོད་%1 %1 hour %2 minutes remaining དེ་བྱིངས་ཚང་མ་ལྷག ཆུ་ཚོད་%1དང་སྐར་མ་%2 %1 hours %2 minute remaining དེ་བྱིངས་ཚང་མ་ལྷག ཆུ་ཚོད་%1དང་སྐར་མ་%2 %1 hours remaining དེ་བྱིངས་ཚང་མ་ལྷག ཆུ་ཚོད་%1 %1 hours %2 minutes remaining དེ་བྱིངས་ཚང་མ་ལྷག ཆུ་ཚོད་%1དང་སྐར་མ་%2 fully charged གློག་གསོག་ཚད་ཚང་མ་ Better endurance གློག་སྨན། Better performance དོ་མཉམ། Best performance ཆེས་ལེགས་པའི་ནུས་པ། ukui-power-manager-4.0.0.1/ukui-power-manager-tray/powersupplydev.h0000664000175000017500000000534314601232446023777 0ustar fengfeng/* * Copyright 2023 KylinSoft Co., Ltd. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ #ifndef POWERSUPPLYDEV_H #define POWERSUPPLYDEV_H #include #include "upower-dbus/upowerdbus.h" #include "upower-dbus/upowerbatterydbus.h" #include "upower-dbus/upowerlinepowerdbus.h" typedef enum { battery_state_unknown = 0, battery_state_charging, battery_state_discharging, battery_state_empty, battery_state_fully, battery_state_pending_charge, battery_state_pending_discharge, battery_state_last } BatteryState; class PowerSupplyDev : public QObject { Q_OBJECT public: explicit PowerSupplyDev(QObject *parent = nullptr); ~PowerSupplyDev(); private: UPowerDBus *m_upowerDBus; QVector m_batteryDBusVector; QVector m_linePowerDBusVector; QString m_batteryIconName; Q_SIGNALS: void lidStateChanged(bool); void batteryOnlineStateChanged(bool); void batteryInfoChanged(int, QStringList); void acOnlineStateChanged(int, bool); private: void dealLidStateChanged(bool); void dealBatteryOnlineStateChanged(bool); void dealBatteryInfoChanged(int, QStringList); void dealAcOnlineStateChanged(int, bool); public Q_SLOTS: bool getLidClosedState(); bool getBatteryOnlineState(); QString getUpowerDaemonVersion(); int getBatteryNum(); int getLinePowerNum(); int getBatteryState(int index = 0); double getOneBatteryPercentage(int index = 0); double getBatteryPercentage(); double calcBatteryPercentage(); double getEnergyNow(int index = 0); double getEnergyFull(int index = 0); double getEnergyFullDesign(int index = 0); double getEnergyRate(int index = 0); qlonglong getTimeToFull(int index = 0); qlonglong getTimeToEmpty(int index = 0); double getBatteryTemperature(int index = 0); int getWarninglevel(int index = 0); QString getBatteryVendor(int index = 0); QString getBatteryModel(int index = 0); QString getOneBatteryIconName(int index = 0); QString getBatteryIconName(); bool getAcOnlineState(); }; #endif // POWERSUPPLYDEV_H ukui-power-manager-4.0.0.1/ukui-power-manager-tray/divider.h0000664000175000017500000000165714601232446022321 0ustar fengfeng/* * Copyright (C) 2023, KylinSoft Co., Ltd. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . * */ #ifndef DIVIDER_H #define DIVIDER_H #include class Divider : public QFrame { public: Divider(QWidget * parent = nullptr); ~Divider() = default; protected: void paintEvent(QPaintEvent *event); }; #endif // DIVIDER_H ukui-power-manager-4.0.0.1/ukui-power-manager-tray/resources/0000775000175000017500000000000014601232446022523 5ustar fengfengukui-power-manager-4.0.0.1/ukui-power-manager-tray/resources/ukui-power-manager-tray.desktop0000664000175000017500000000064314601232446030615 0ustar fengfeng[Desktop Entry] _Name=Power Manager Tray Name[zh_CN]=电源管理程序 _Comment=Power management tray Icon=ukui-power-manager Exec=ukui-power-manager-tray Terminal=false Type=Application NoDisplay=true Categories= OnlyShowIn=UKUI; X-UKUI-Bugzilla-Bugzilla=UKUI X-UKUI-Bugzilla-Product=ukui-power-manager-tray X-UKUI-Bugzilla-Component=ukui-power-manager-tray X-UKUI-Bugzilla-Version=@VERSION@ X-UKUI-AutoRestart=true ukui-power-manager-4.0.0.1/ukui-power-manager-tray/divider.cpp0000664000175000017500000000222614601232446022645 0ustar fengfeng/* * Copyright (C) 2023, KylinSoft Co., Ltd. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . * */ #include "divider.h" #include #include Divider::Divider(QWidget *parent) : QFrame(parent) { this->setFixedHeight(1); } void Divider::paintEvent(QPaintEvent *e) { QPainter p(this); QColor color = qApp->palette().color(QPalette::BrightText); color.setAlphaF(0.08); p.save(); p.setBrush(color); p.setPen(Qt::transparent); p.drawRoundedRect(this->rect(), 6, 6); p.restore(); return QFrame::paintEvent(e); } ukui-power-manager-4.0.0.1/ukui-power-manager-tray/fullscreenmask.h0000664000175000017500000000202514601232446023677 0ustar fengfeng/* * Copyright (C) 2023, KylinSoft Co., Ltd. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . * */ #ifndef FULLSCREENMASK_H #define FULLSCREENMASK_H #include #include "notificationdialog.h" class FullScreenMask : public QWidget { Q_OBJECT public: explicit FullScreenMask(QWidget *parent = nullptr); private: protected: void paintEvent(QPaintEvent *event) Q_DECL_OVERRIDE; Q_SIGNALS: }; #endif // FULLSCREENMASK_H ukui-power-manager-4.0.0.1/ukui-power-manager-tray/main.cpp0000664000175000017500000000424114601232446022142 0ustar fengfeng/* * Copyright 2023 KylinSoft Co., Ltd. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ #include "powertray.h" #include #include #include #include #include #include #include #include #include #include #include #include #include //#include int main(int argc, char *argv[]) { QApplication::setAttribute(Qt::AA_EnableHighDpiScaling); QApplication::setAttribute(Qt::AA_UseHighDpiPixmaps); #if (QT_VERSION >= QT_VERSION_CHECK(5, 14, 0)) QApplication::setHighDpiScaleFactorRoundingPolicy(Qt::HighDpiScaleFactorRoundingPolicy::PassThrough); #endif QStringList homePath = QStandardPaths::standardLocations(QStandardPaths::HomeLocation); int fd = open( QString(homePath.at(0) + "/.config/ukui-power-manager-tray%1.lock").arg(getenv("DISPLAY")).toUtf8().data(), O_WRONLY | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR); if (fd < 0) { exit(1); } if (lockf(fd, F_TLOCK, 0)) { qDebug() << "cant lock single file, ukui-power-manager-tray is already running"; exit(0); } QApplication app(argc, argv); // initUkuiLog4qt("ukui-power-manager-tray"); QTranslator translator; if (translator.load(QLocale(), "ukui-power-manager-tray", "_", QM_FILES_INSTALL_PATH)) { app.installTranslator(&translator); } else { qDebug() << "load ukui-power-manager-tray qm file error"; } PowerTray p; return app.exec(); } ukui-power-manager-4.0.0.1/ukui-power-manager-tray/powertray.cpp0000664000175000017500000002331214601232446023252 0ustar fengfeng/* * Copyright 2023 KylinSoft Co., Ltd. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ #include #include "powertray.h" #include "powerwindow.h" #include "kwindowsystem.h" #define UPM_SETTINGS_SCHEMA "org.ukui.power-manager" #define UPM_SETTINGS_DISPLAY_LEFT_TIME "dispaly-left-time-of-charge-and-discharge" PowerTray::PowerTray(QObject *parent) : QObject(parent) { m_powerSupplyDev = new PowerSupplyDev(this); qDebug() << "upower version is:" << m_powerSupplyDev->getUpowerDaemonVersion(); if (0 == m_powerSupplyDev->getBatteryNum()) { exit(0); } initPowerTray(); m_criticalPercentageAction = new CriticalPercentageAction(m_powerSupplyDev, this); } PowerTray::~PowerTray() { if (nullptr != m_TrayMenu) { delete m_TrayMenu; m_TrayMenu = nullptr; } if (nullptr != m_powerWindow) { delete m_powerWindow; m_powerWindow = nullptr; } } void PowerTray::initPowerTray() { m_settings = new QGSettings(UPM_SETTINGS_SCHEMA); m_showBatteryLeftTime = m_settings->get(UPM_SETTINGS_DISPLAY_LEFT_TIME).toInt(); m_acChangeTimer = new QTimer(this); m_isPowerSupplyChange = false; connect(m_acChangeTimer, &QTimer::timeout, this, [=](){ m_isPowerSupplyChange = false; m_acChangeTimer->stop(); }); updateBatteryInfo(); m_trayIcon = new QSystemTrayIcon(this); setTrayIconToolTipForAcOnlineChanged(m_acOnlineState, m_batteryPercentage); m_trayIconName = m_powerSupplyDev->getBatteryIconName(); setTrayIcon(m_trayIconName); initTrayMenuUI(); initPowerWindowUI(); connect(m_trayIcon, SIGNAL(activated(QSystemTrayIcon::ActivationReason)), this, SLOT(onActivatedIcon(QSystemTrayIcon::ActivationReason))); connect(m_powerSupplyDev, &PowerSupplyDev::acOnlineStateChanged, this, &PowerTray::dealAcOnlineStateChanged); connect(m_powerSupplyDev, &PowerSupplyDev::batteryInfoChanged, this, &PowerTray::dealBatteryInfoChanged); } void PowerTray::initTrayMenuUI() { qDebug() << "init tray menu ui"; m_TrayMenu = new QMenu(); m_TrayMenu->setAttribute(Qt::WA_TranslucentBackground); m_trayIcon->setContextMenu(m_TrayMenu); QAction *setPreference = new QAction(m_TrayMenu); QIcon icon = QIcon::fromTheme("document-page-setup-symbolic"); setPreference->setIcon(icon); setPreference->setText(tr("SetPower")); connect(setPreference, &QAction::triggered,[=]{QProcess::startDetached(QString("ukui-control-center -m Power"));}); m_TrayMenu->addAction(setPreference); } void PowerTray::initPowerWindowUI() { qDebug() << "init power window ui"; m_powerWindow = new powerwindow(); m_powerWindow->hide(); setPowerWindowProperties(); m_powerWindow->setPowerStateLabelForAcOnlineChanged(); } void PowerTray::setPowerWindowProperties() { m_powerWindow->setIconName(m_trayIconName); m_powerWindow->setAcOnlineState(m_acOnlineState); m_powerWindow->setBatteryState(m_batteryState); m_powerWindow->setBatteryPercentage(m_batteryPercentage); m_powerWindow->setShowPowerLeftTime(m_showBatteryLeftTime); m_powerWindow->setBatteryLeftTime( m_powerSupplyDev->getTimeToFull(), m_powerSupplyDev->getTimeToEmpty()); } void PowerTray::setTrayIconToolTipForAcOnlineChanged(bool acOnlineState, double percentage) { if (true == acOnlineState) { if (100 == percentage) { m_trayIcon->setToolTip(tr("fully charged (100%)")); } else { m_trayIcon->setToolTip(tr("%1% available (plugged in)").arg(percentage)); } } else { m_trayIcon->setToolTip(tr("%1% remaining").arg(percentage)); } } void PowerTray::setTrayIconToolTipForBatteryInfoChanged(double percentage) { qlonglong batteryLeftTime = 0; int hour = 0; switch (m_powerSupplyDev->getBatteryState()) { case battery_state_unknown: case battery_state_fully: if (100 == percentage) { m_trayIcon->setToolTip(tr("fully charged (100%)")); } else { m_trayIcon->setToolTip(tr("%1% remaining").arg(percentage)); } break; case battery_state_charging: batteryLeftTime = m_powerSupplyDev->getTimeToFull(); if (0 == m_showBatteryLeftTime || 0 == batteryLeftTime || percentage > 95 ) { if (100 == percentage) { m_trayIcon->setToolTip(tr("fully charged (100%)")); } else { m_trayIcon->setToolTip(tr("%1% available (plugged in)").arg(percentage)); } } else { hour = batteryLeftTime / 3600; if (0 == hour) { m_trayIcon->setToolTip(tr("%1 min to fully charge (%2%)") .arg(((batteryLeftTime) % 3600) / 60) .arg(percentage)); } else if (hour > 10) { m_trayIcon->setToolTip(tr("%1% available (plugged in)").arg(percentage)); } else { m_trayIcon->setToolTip(tr("%1 hr %2 min to fully charge (%3%)") .arg(hour) .arg(((batteryLeftTime) % 3600) / 60) .arg(percentage)); } } break; case battery_state_discharging: batteryLeftTime = m_powerSupplyDev->getTimeToEmpty(); if (0 == m_showBatteryLeftTime || 0 == batteryLeftTime) { m_trayIcon->setToolTip(tr("%1% remaining").arg(percentage)); } else { hour = batteryLeftTime / 3600; if (0 == hour) { m_trayIcon->setToolTip(tr("%1 min (%2%) remaining") .arg(((batteryLeftTime) % 3600) / 60) .arg(percentage)); } else if (hour > 20) { m_trayIcon->setToolTip(tr("%1% remaining").arg(percentage)); } else { m_trayIcon->setToolTip(tr("%1 hr %2 min (%3%) remaining") .arg(hour) .arg(((batteryLeftTime) % 3600) / 60) .arg(percentage)); } } break; default: m_trayIcon->setToolTip(tr("%1% remaining").arg(percentage)); break; } } void PowerTray::setTrayIcon(QString strIconName) { qDebug() << "icon name is : " << strIconName; if (!strIconName.isNull()) { QIcon icon = QIcon::fromTheme(strIconName); m_trayIcon->setIcon(icon); m_trayIcon->show(); } else { m_trayIcon->hide(); } } void PowerTray::onActivatedIcon(QSystemTrayIcon::ActivationReason reason) { if (reason == 3) { bool isVisible = m_powerWindow->isVisible(); if (true == isVisible) { qDebug() << "m_powerWindow isVisible:" << isVisible; m_powerWindow->hide(); } else { qDebug() << "m_powerWindow isVisible:" << isVisible; m_powerWindow->showPowerWindow(); } } else { qDebug() << "on Activated Icon reason:" << reason; } } void PowerTray::acOnlineStateChangedAction() { updateBatteryInfo(); //deal tray icon setTrayIconToolTipForAcOnlineChanged(m_acOnlineState, m_batteryPercentage); m_trayIconName = m_powerSupplyDev->getBatteryIconName(); setTrayIcon(m_trayIconName); //deal power window setPowerWindowProperties(); m_powerWindow->setPowerStateLabelForAcOnlineChanged(); } void PowerTray::dealAcOnlineStateChanged(int index, bool value) { qDebug() << "power tray ac online state changed"; m_isPowerSupplyChange = true; m_acChangeTimer->start(60 * 1000); acOnlineStateChangedAction(); } void PowerTray::dealBatteryInfoChanged(int index, QStringList batteryInfoChangedList) { qDebug() << "power tray battery info changed"; if (true == m_isPowerSupplyChange) { qDebug() << "ac online changed, not deal battery info changed"; acOnlineStateChangedAction(); return ; } m_showBatteryLeftTime = m_settings->get(UPM_SETTINGS_DISPLAY_LEFT_TIME).toInt(); updateBatteryInfo(); //deal tray icon setTrayIconToolTipForBatteryInfoChanged(m_batteryPercentage); QString trayIconName = m_powerSupplyDev->getBatteryIconName(); if (m_trayIconName != trayIconName) { m_trayIconName = trayIconName; setTrayIcon(m_trayIconName); } //deal power window setPowerWindowProperties(); m_powerWindow->setPowerStateLabelForBatteryInfoChanged(); } void PowerTray::updateBatteryInfo() { m_acOnlineState = m_powerSupplyDev->getAcOnlineState(); qDebug() << "power tray ac online:" << m_acOnlineState; m_batteryState = m_powerSupplyDev->getBatteryState(); qDebug() << "power tray battery state:" << m_batteryState; m_batteryPercentage = m_powerSupplyDev->getBatteryPercentage(); qDebug() << "power tray battery percentage:" << m_batteryPercentage; } ukui-power-manager-4.0.0.1/ukui-power-manager-tray/powerwindow.cpp0000664000175000017500000005220414607363245023614 0ustar fengfeng/* * Copyright 2023 KylinSoft Co., Ltd. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ #include "powerwindow.h" #include "xatom-helper.h" #include "qdesktopwidget.h" #include #include #include #include #include #define ORG_UKUI_STYLE "org.ukui.style" #define POWER_MANAGER_SETTINGS "org.ukui.power-manager" #define SYSTEM_FONT_SIZE "systemFontSize" #define STYLE_NAME "styleName" #define MARGIN 8 #define TRANSPARENCY_SETTINGS "org.ukui.control-center.personalise" #define TRANSPARENCY_KEY "transparency" #define POWER_POLICY_AC "powerPolicyAc" #define POWER_POLICY_BATTERY "powerPolicyBattery" powerwindow::powerwindow(QWidget *parent) : QWidget(parent) { qDebug() << " power window init start"; initPlatformType(); setWindowProperty(); //设置窗口属性 initgsetting(); initUI(); //初始化UI setSliderValue(); watchTranspartency(); if (true == m_isWayland) { kdk::UkuiStyleHelper::self()->removeHeader(this); kdk::WindowManager::setSkipTaskBar(this->windowHandle(), true); kdk::WindowManager::setSkipSwitcher(this->windowHandle(), true); resetWindowPosition(); } //监听屏幕改变的信号 connect(QApplication::desktop(), &QDesktopWidget::resized, this, [=]() { QTimer::singleShot(1000, this, [=]() { resetWindowPosition(); }); }); connect(QApplication::desktop(), &QDesktopWidget::screenCountChanged, this, [=]() { resetWindowPosition(); }); connect(QApplication::desktop(), &QDesktopWidget::primaryScreenChanged, this, [=]() { resetWindowPosition(); }); installEventFilter(this); } powerwindow::~powerwindow() { if (nullptr != m_transparencyGsettings) { delete m_transparencyGsettings; m_transparencyGsettings = nullptr; } } void powerwindow::setWindowProperty() { //设置任务栏无显示 setWindowOpacity(1); setAttribute(Qt::WA_TranslucentBackground); //设置窗口背景透明 setProperty("useSystemStyleBlur", true); //设置毛玻璃效果 setProperty("useStyleWindowManager", false); if (false == m_isWayland) { KWindowEffects::enableBlurBehind(this->winId(), true); // 添加窗管协议 MotifWmHints hints; hints.flags = MWM_HINTS_FUNCTIONS | MWM_HINTS_DECORATIONS; hints.functions = MWM_FUNC_ALL; hints.decorations = MWM_DECOR_BORDER; XAtomHelper::getInstance()->setWindowMotifHint(this->winId(), hints); } } void powerwindow::initUI() { this->setFixedSize(420, 265 + m_deviceNum * 60); m_pmainlayout = new QVBoxLayout(this); m_firstlayout = new QHBoxLayout(this); m_toplayout = new QHBoxLayout(this); m_lastlayout = new QHBoxLayout(this); m_statelayout = new QHBoxLayout(this); m_firstwidget = new QWidget(this); m_topwidget = new QWidget(this); m_lastWidget = new QWidget(this); m_statewidget = new QWidget(this); m_iconButton = new QPushButton(this); m_iconButton->setFixedSize(QSize(48, 65)); m_iconButton->setIconSize(QSize(30, 30)); m_iconButton->setStyle(new CustomStyle); m_iconButton->setProperty("useIconHighlightEffect", 0x10); m_iconButton->setFlat(true); m_iconButton->setAttribute(Qt::WA_TransparentForMouseEvents); m_percentageLabel = new QLabel(this); setPercentageLabelFontsize(); m_powerStateLabel = new QLabel(this); m_segmentationLine_1 = new Divider(this); m_segmentationLine_2 = new Divider(this); m_StateSlider = new KSlider(this); m_StateSlider->setOrientation(Qt::Orientation::Horizontal); m_StateSlider->setSliderType(KSliderType::SingleSelectSlider); m_StateSlider->setMaximum(2); m_StateSlider->setSingleStep(1); m_StateSlider->setPageStep(1); m_StateSlider->setFixedWidth(372); m_StateSlider->setProperty("needTranslucent", true); m_StateSlider->setTranslucent(true); connect(m_StateSlider, &KSlider::valueChanged, this, &powerwindow::sliderValueChanged); m_enduranceIconButtun = new QToolButton(this); m_enduranceIconButtun->setIconSize(QSize(16, 16)); m_enduranceIconButtun->setToolButtonStyle(Qt::ToolButtonTextBesideIcon); m_enduranceIconButtun->setProperty("useIconHighlightEffect", 0x2); m_enduranceIconButtun->setStyle(new CustomStyle); QIcon icon1 = QIcon::fromTheme("ukui-eco-symbolic"); m_enduranceIconButtun->setIcon(icon1); m_enduranceIconButtun->setText(tr("Endurance")); m_performanceIconButtun = new QToolButton(this); m_performanceIconButtun->setToolButtonStyle(Qt::ToolButtonTextBesideIcon); m_performanceIconButtun->setProperty("useIconHighlightEffect", 0x2); m_performanceIconButtun->setStyle(new CustomStyle); QIcon icon2 = QIcon::fromTheme("ukui-performance-symbolic"); m_performanceIconButtun->setIcon(icon2); m_performanceIconButtun->setText(tr("Performance")); //电源设置按钮 m_settingLabel = new KyLable(this); m_settingLabel->setText(tr("PowerSettings")); m_toplabel = new QLabel(this); m_toplabel->setText(tr("PowerMode")); m_toplayout->setContentsMargins(24, 0, 24, 0); m_toplayout->setSpacing(0); m_toplayout->addWidget(m_toplabel); m_toplayout->addItem(new QSpacerItem(10, 2)); m_topwidget->setLayout(m_toplayout); //第一行布局 m_firstlayout->setContentsMargins(18, 0, 24, 0); m_firstlayout->setSpacing(0); m_firstlayout->addWidget(m_iconButton, 0, Qt::AlignLeft | Qt::AlignVCenter); m_firstlayout->addWidget(m_percentageLabel, 0, Qt::AlignLeft | Qt::AlignVCenter); m_firstlayout->addStretch(); m_firstlayout->addWidget(m_powerStateLabel, 0, Qt::AlignRight | Qt::AlignVCenter); m_firstwidget->setLayout(m_firstlayout); //滑动条下方标识布局 m_statelayout->setContentsMargins(18, 0, 5, 0); m_statelayout->setSpacing(0); m_statelayout->addWidget(m_enduranceIconButtun, 0, Qt::AlignLeft | Qt::AlignCenter); m_statelayout->addStretch(); m_statelayout->addWidget(m_performanceIconButtun, 0, Qt::AlignRight); m_statewidget->setLayout(m_statelayout); //电源设置按钮布局 m_lastlayout->setContentsMargins(24, 0, 24, 0); m_lastlayout->setSpacing(0); m_lastlayout->addWidget(m_settingLabel); m_lastlayout->addStretch(); m_lastWidget->setLayout(m_lastlayout); m_settingLabel->setCursor(Qt::PointingHandCursor); //总体布局 m_pmainlayout->setContentsMargins(0, 0, 0, 0); m_pmainlayout->setSpacing(0); m_pmainlayout->addWidget(m_topwidget); m_pmainlayout->addWidget(m_segmentationLine_1); m_pmainlayout->addSpacing(12); m_pmainlayout->addWidget(m_firstwidget); m_pmainlayout->addSpacing(0); m_pmainlayout->addWidget(m_StateSlider, 0, Qt::AlignCenter); m_pmainlayout->addSpacing(0); m_pmainlayout->addWidget(m_statewidget); m_pmainlayout->addWidget(m_segmentationLine_2); m_pmainlayout->addWidget(m_lastWidget); this->setLayout(m_pmainlayout); } void powerwindow::initgsetting() { const QByteArray styleId(ORG_UKUI_STYLE); if (QGSettings::isSchemaInstalled(styleId)) { m_styleSettings = new QGSettings(styleId); if (m_styleSettings->keys().contains(SYSTEM_FONT_SIZE)) { m_sysFontSize = m_styleSettings->get(SYSTEM_FONT_SIZE).toDouble(); } connect(m_styleSettings, &QGSettings::changed, this, [=](const QString &key) { if (key == SYSTEM_FONT_SIZE) { m_sysFontSize = m_styleSettings->get(SYSTEM_FONT_SIZE).toDouble(); setPercentageLabelFontsize(); if (true == m_acOnlineChange) { setPowerStateLabelForAcOnlineChanged(); } else { setPowerStateLabelForBatteryInfoChanged(); } } if (key == STYLE_NAME) { m_iconButton->setIcon(QIcon::fromTheme(m_iconName)); } }); } const QByteArray powerId(POWER_MANAGER_SETTINGS); m_PowerManagerGsettings = new QGSettings(powerId); connect(m_PowerManagerGsettings, &QGSettings::changed, this, [=](const QString &key) { if (key == POWER_POLICY_AC || key == POWER_POLICY_BATTERY) { qDebug() << "m_PowerManagerGsettings changed !"; setSliderValue(); } }); } void powerwindow::initPlatformType() { if ("wayland" == qgetenv("XDG_SESSION_TYPE")) { m_isWayland = true; } qDebug() << "Platform is wayland:" << m_isWayland; } void powerwindow::setIconName(QString iconName) { m_iconName = iconName; m_iconButton->setIcon(QIcon::fromTheme(m_iconName)); } void powerwindow::setAcOnlineState(bool acOnlineState) { if (m_acOnlineState == acOnlineState) { return; } m_acOnlineState = acOnlineState; if (true == m_acOnlineState) { m_toplabel->setText(tr("PowerMode")); } else { m_toplabel->setText(tr("BatteryMode")); } setSliderValue(); } void powerwindow::setBatteryState(int iBatteryState) { if (m_batteryState == iBatteryState) { m_batteryStateChanged = false; } else { m_batteryStateChanged = true; m_batteryState = iBatteryState; setSliderValue(); } } void powerwindow::setBatteryPercentage(int iBatteryPercentage) { m_batteryPercentage = iBatteryPercentage; m_percentageLabel->setText(QString("%1%").arg(m_batteryPercentage)); } void powerwindow::setShowPowerLeftTime(int iShowPowerLeftTime) { m_showBatteryLeftTime = iShowPowerLeftTime; } void powerwindow::setBatteryLeftTime(qlonglong timeToFull, qlonglong timeToEmpty) { m_timeToFull = timeToFull; m_timeToEmpty = timeToEmpty; } void powerwindow::setPowerStateLabelForAcOnlineChanged() { if (true == m_acOnlineState) { if (100 == m_batteryPercentage) { m_powerStateLabel->setText(tr("fully charged")); } else { m_powerStateLabel->setText(tr("Charging")); } } else { m_powerStateLabel->setText(tr("Discharging")); } m_acOnlineChange = true; } void powerwindow::setPowerStateLabelForBatteryInfoChanged() { QString power_state_text(""); int hour = 0; int minute = 0; switch (m_batteryState) { case battery_state_unknown: case battery_state_fully: if (100 == m_batteryPercentage) { power_state_text = QString(tr("fully charged")); } break; case battery_state_charging: if (false == m_showBatteryLeftTime || 0 == m_timeToFull || true == m_batteryStateChanged || m_batteryPercentage > 95) { if (100 == m_batteryPercentage) { power_state_text = QString(tr("fully charged")); } else { power_state_text = QString(tr("Charging")); } } else { hour = m_timeToFull / 3600; minute = ((m_timeToFull) % 3600) / 60; if (0 == hour) { power_state_text = QString(tr("%1 minutes \nuntil fully charged")).arg(minute); } else if (hour > 10) { power_state_text = QString(tr("Charging")); } else { if (1 == hour) { if (1 == minute) { power_state_text = QString(tr("%1 hour %2 minute \nuntil fully charged")) .arg(hour).arg(minute); } else if (0 == minute) { power_state_text = QString(tr("%1 hour \nuntil fully charged")).arg(hour); } else { power_state_text = QString(tr("%1 hour %2 minutes \nuntil fully charged")) .arg(hour).arg(minute); } } else { if (1 == minute) { power_state_text = QString(tr("%1 hours %2 minute \nuntil fully charged")) .arg(hour).arg(minute); } else if (0 == minute) { power_state_text = QString(tr("%1 hours \nuntil fully charged")).arg(hour); } else { power_state_text = QString(tr("%1 hours %2 minutes \nuntil fully charged")) .arg(hour).arg(minute); } } } } break; case battery_state_discharging: if (false == m_showBatteryLeftTime || 0 == m_timeToEmpty || true == m_batteryStateChanged) { power_state_text = QString(tr("Discharging")); } else { hour = m_timeToEmpty / 3600; minute = ((m_timeToEmpty) % 3600) / 60; if (0 == hour) { power_state_text = QString(tr("%1 minutes \nremaining")).arg(minute); } else if (hour > 20) { power_state_text = QString(tr("Discharging")); } else { if (1 == hour) { if (1 == minute) { power_state_text = QString(tr("%1 hour %2 minute \nremaining")) .arg(hour).arg(minute); } else if (0 == minute) { power_state_text = QString(tr("%1 hour \nremaining")) .arg(hour); } else { power_state_text = QString(tr("%1 hour %2 minutes \nremaining")) .arg(hour).arg(minute); } } else { if (1 == minute) { power_state_text = QString(tr("%1 hours %2 minute \nremaining")) .arg(hour).arg(minute); } else if (0 == minute) { power_state_text = QString(tr("%1 hours \nremaining")) .arg(hour); } else { power_state_text = QString(tr("%1 hours %2 minutes \nremaining")) .arg(hour).arg(minute); } } } } default: break; } m_powerStateLabel->setText(power_state_text); m_acOnlineChange = false; } void powerwindow::setPercentageLabelFontsize() { QFont font; font.setPointSize((int)(m_sysFontSize * 1.5)); m_percentageLabel->setFont(font); } void powerwindow::showPowerWindow() { if (false == m_isWayland) { resetWindowPosition(); KWindowSystem::setState(this->winId(), NET::SkipTaskbar | NET::SkipPager | NET::SkipSwitcher); this->show(); } else { this->show(); kdk::UkuiStyleHelper::self()->removeHeader(this); kdk::WindowManager::setSkipTaskBar(this->windowHandle(), true); kdk::WindowManager::setSkipSwitcher(this->windowHandle(), true); resetWindowPosition(); } } void powerwindow::resetWindowPosition() { QDBusInterface panelDBus("org.ukui.panel", "/panel/position", "org.ukui.panel", QDBusConnection::sessionBus()); QDBusReply reply = panelDBus.call("GetPrimaryScreenGeometry"); switch (reply.value().at(4).toInt()) { case PanelUp: m_windowPositionRect = QRect(reply.value().at(0).toInt() + reply.value().at(2).toInt() - this->width() - MARGIN, reply.value().at(1).toInt() + MARGIN, this->width(), this->height()); break; case PanelLeft: m_windowPositionRect = QRect(reply.value().at(0).toInt() + MARGIN, reply.value().at(1).toInt() + reply.value().at(3).toInt() - this->height() - MARGIN, this->width(), this->height()); break; case PanelRight: m_windowPositionRect = QRect(reply.value().at(0).toInt() + reply.value().at(2).toInt() - this->width() - MARGIN, reply.value().at(1).toInt() + reply.value().at(3).toInt() - this->height() - MARGIN, this->width(), this->height()); break; default: m_windowPositionRect = QRect(reply.value().at(0).toInt() + reply.value().at(2).toInt() - this->width() - MARGIN, reply.value().at(1).toInt() + reply.value().at(3).toInt() - this->height() - MARGIN, this->width(), this->height()); break; } if (false == m_isWayland) { this->setGeometry(m_windowPositionRect); } else { kdk::WindowManager::setGeometry(this->windowHandle(), m_windowPositionRect); } } void powerwindow::watchTranspartency() { const QByteArray transparency_id(TRANSPARENCY_SETTINGS); if (QGSettings::isSchemaInstalled(transparency_id)) { m_transparencyGsettings = new QGSettings(transparency_id); if (m_transparencyGsettings->keys().contains(TRANSPARENCY_KEY)) { m_transparency = m_transparencyGsettings->get(TRANSPARENCY_KEY).toDouble() * 255; } this->update(); connect(m_transparencyGsettings, &QGSettings::changed, this, [=](const QString &key) { if (key == TRANSPARENCY_KEY) { m_transparency = m_transparencyGsettings->get(TRANSPARENCY_KEY).toDouble() * 255; this->update(); } }); } else { m_transparency = 0.75; } } void powerwindow::sliderValueChanged(int value) { qDebug() << "ac online state:" << m_acOnlineState << "slider value:" << value; if (true == m_acOnlineState) { switch (value) { case 0: m_PowerManagerGsettings->set(POWER_POLICY_AC, EnergySaving); m_StateSlider->setToolTip(tr("Better endurance")); break; case 1: m_PowerManagerGsettings->set(POWER_POLICY_AC, Balance); m_StateSlider->setToolTip(tr("Better performance")); break; case 2: m_PowerManagerGsettings->set(POWER_POLICY_AC, Performance); m_StateSlider->setToolTip(tr("Best performance")); break; default: break; } } else { switch (value) { case 0: m_PowerManagerGsettings->set(POWER_POLICY_BATTERY, EnergySaving); m_StateSlider->setToolTip(tr("Better endurance")); break; case 1: m_PowerManagerGsettings->set(POWER_POLICY_BATTERY, Balance); m_StateSlider->setToolTip(tr("Better performance")); break; case 2: m_PowerManagerGsettings->set(POWER_POLICY_BATTERY, Performance); m_StateSlider->setToolTip(tr("Best performance")); break; default: break; } } } void powerwindow::setSliderValue() { int policy = -1; if (true == m_acOnlineState) { policy = m_PowerManagerGsettings->get(POWER_POLICY_AC).toInt(); } else { policy = m_PowerManagerGsettings->get(POWER_POLICY_BATTERY).toInt(); } qDebug() << "ac online state:" << m_acOnlineState << "policy:" << policy; switch (policy) { case Performance: m_StateSlider->setValue(2); m_StateSlider->setToolTip(tr("Best performance")); break; case Balance: m_StateSlider->setValue(1); m_StateSlider->setToolTip(tr("Better performance")); break; case EnergySaving: m_StateSlider->setValue(0); m_StateSlider->setToolTip(tr("Better endurance")); break; default: break; } } void powerwindow::paintEvent(QPaintEvent *e) { QStyleOption opt; opt.init(this); QPainter p(this); p.setPen(Qt::NoPen); QColor color = palette().color(QPalette::Base); color.setAlpha(m_transparency); QBrush brush = QBrush(color); p.setBrush(brush); p.setRenderHints(QPainter::Antialiasing | QPainter::SmoothPixmapTransform); p.drawRect(opt.rect); } bool powerwindow::eventFilter(QObject *watched, QEvent *event) { if (watched == this) { if (event->type() == QEvent::WindowDeactivate) { hide(); return true; } else { return false; } } else { return false; } } void powerwindow::keyPressEvent(QKeyEvent *event) { if (event->key() == Qt::Key_Escape) { hide(); } QWidget::keyPressEvent(event); } ukui-power-manager-4.0.0.1/ukui-power-manager-tray/customstyle.cpp0000664000175000017500000005170014601232446023613 0ustar fengfeng/* * Copyright (C) 2023 KylinSoft Co., Ltd. * * This program or 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 Street, Fifth Floor, * Boston, MA 02110-1301 USA */ #include "customstyle.h" #include #include #include //#if QT_CONFIG(toolbutton) /*以下代码是为了处理toolbutton 的箭头*/ static void drawArrow( const QStyle *style, const QStyleOptionToolButton *toolbutton, const QRect &rect, QPainter *painter, const QWidget *widget = 0) { QStyle::PrimitiveElement pe; switch (toolbutton->arrowType) { case Qt::LeftArrow: pe = QStyle::PE_IndicatorArrowLeft; break; case Qt::RightArrow: pe = QStyle::PE_IndicatorArrowRight; break; case Qt::UpArrow: pe = QStyle::PE_IndicatorArrowUp; break; case Qt::DownArrow: pe = QStyle::PE_IndicatorArrowDown; break; default: return; } QStyleOption arrowOpt = *toolbutton; arrowOpt.rect = rect; style->drawPrimitive(pe, &arrowOpt, painter, widget); } //#endif // QT_CONFIG(toolbutton) CustomStyle::CustomStyle(const QString &proxyStyleName, bool multileWins, QObject *parent) : QProxyStyle(proxyStyleName) { pluginName = proxyStyleName; multileWindow = multileWins; } CustomStyle::~CustomStyle() {} /*Draws the given control using the provided painter with the style options specified by option.*/ void CustomStyle::drawComplexControl( QStyle::ComplexControl cc, const QStyleOptionComplex *opt, QPainter *p, const QWidget *widget) const { // if(control == CC_ToolButton) // { // /// 我们需要获取ToolButton的详细信息,通过qstyleoption_cast可以得到 // /// 对应的option,通过拷贝构造函数得到一CustomStyle份备份用于绘制子控件 // /// 我们一般不用在意option是怎么得到的,大部分的Qt控件都能够提供了option的init方法 // } switch (cc) { case CC_ToolButton: if (const QStyleOptionToolButton *toolbutton = qstyleoption_cast(opt)) { QRect button, menuarea; button = proxy()->subControlRect(cc, toolbutton, SC_ToolButton, widget); menuarea = proxy()->subControlRect(cc, toolbutton, SC_ToolButtonMenu, widget); State bflags = toolbutton->state & ~State_Sunken; if (bflags & State_AutoRaise) { if (!(bflags & State_MouseOver) || !(bflags & State_Enabled)) { bflags &= ~State_Raised; } } State mflags = bflags; if (toolbutton->state & State_Sunken) { if (toolbutton->activeSubControls & SC_ToolButton) bflags |= State_Sunken; mflags |= State_Sunken; } QStyleOption tool = *toolbutton; if (toolbutton->subControls & SC_ToolButton) { if (bflags & (State_Sunken | State_On | State_Raised)) { tool.rect = button; tool.state = bflags; proxy()->drawPrimitive(PE_PanelButtonTool, &tool, p, widget); } } if (toolbutton->state & State_HasFocus) { QStyleOptionFocusRect fr; fr.QStyleOption::operator=(*toolbutton); fr.rect.adjust(3, 3, -3, -3); if (toolbutton->features & QStyleOptionToolButton::MenuButtonPopup) fr.rect.adjust( 0, 0, -proxy()->pixelMetric(QStyle::PM_MenuButtonIndicator, toolbutton, widget), 0); proxy()->drawPrimitive(PE_FrameFocusRect, &fr, p, widget); } QStyleOptionToolButton label = *toolbutton; label.state = bflags; int fw = proxy()->pixelMetric(PM_DefaultFrameWidth, opt, widget); label.rect = button.adjusted(fw, fw, -fw, -fw); proxy()->drawControl(CE_ToolButtonLabel, &label, p, widget); if (toolbutton->subControls & SC_ToolButtonMenu) { tool.rect = menuarea; tool.state = mflags; if (mflags & (State_Sunken | State_On | State_Raised)) proxy()->drawPrimitive(PE_IndicatorButtonDropDown, &tool, p, widget); proxy()->drawPrimitive(PE_IndicatorArrowDown, &tool, p, widget); } else if (toolbutton->features & QStyleOptionToolButton::HasMenu) { int mbi = proxy()->pixelMetric(PM_MenuButtonIndicator, toolbutton, widget); QRect ir = toolbutton->rect; QStyleOptionToolButton newBtn = *toolbutton; newBtn.rect = QRect(ir.right() + 5 - mbi, ir.y() + ir.height() - mbi + 4, mbi - 6, mbi - 6); newBtn.rect = visualRect(toolbutton->direction, button, newBtn.rect); // proxy()->drawPrimitive(PE_IndicatorArrowDown, &newBtn, p, widget); } } return; default: break; } return QProxyStyle::drawComplexControl(cc, opt, p, widget); } /*下面对于CE_ToolButtonLabel 的处理是因为quicklaunch 插件出现了箭头*/ void CustomStyle::drawControl( QStyle::ControlElement element, const QStyleOption *opt, QPainter *p, const QWidget *widget) const { switch (element) { case CE_PushButton: if (const QStyleOptionButton *btn = qstyleoption_cast(opt)) { proxy()->drawControl(CE_PushButtonBevel, btn, p, widget); QStyleOptionButton subopt = *btn; subopt.rect = subElementRect(SE_PushButtonContents, btn, widget); proxy()->drawControl(CE_PushButtonLabel, &subopt, p, widget); } break; case CE_PushButtonBevel: { if (const QStyleOptionButton *btn = qstyleoption_cast(opt)) { QRect br = btn->rect; int dbi = proxy()->pixelMetric(PM_ButtonDefaultIndicator, btn, widget); if (btn->features & QStyleOptionButton::AutoDefaultButton) br.setCoords(br.left() + dbi, br.top() + dbi, br.right() - dbi, br.bottom() - dbi); QStyleOptionButton tmpBtn = *btn; tmpBtn.rect = br; drawPrimitive(PE_PanelButtonCommand, &tmpBtn, p, widget); return; // qDebug()<<" ************** PushButton *********************** "; // p->save(); // // painter->setRenderHint(QPainter::Antialiasing,true); // // painter->setPen(Qt::NoPen); // // painter->drawRoundedRect(option->rect,6,6); // if (opt->state & State_MouseOver) { // if (opt->state & State_Sunken) { // p->setRenderHint(QPainter::Antialiasing,true); // p->setPen(Qt::NoPen); // p->setBrush(QColor(0xff,0xff,0xff)); // p->drawRoundedRect(opt->rect.adjusted(2,2,-2,-2),6,6); // } else { // p->setRenderHint(QPainter::Antialiasing,true); // p->setPen(Qt::NoPen); // p->setBrush(QColor(0xff,0xff,0xff)); // p->drawRoundedRect(opt->rect.adjusted(2,2,-2,-2),6,6); // } // } // p->restore(); // return; } break; } case CE_ToolButtonLabel: { if (const QStyleOptionToolButton *toolbutton = qstyleoption_cast(opt)) { QRect rect = toolbutton->rect; int shiftX = 0; int shiftY = 0; // if (toolbutton->state & (State_Sunken | State_On)) { // shiftX = proxy()->pixelMetric(PM_ButtonShiftHorizontal, toolbutton, widget); // shiftY = proxy()->pixelMetric(PM_ButtonShiftVertical, toolbutton, widget); // } // Arrow type always overrules and is always shown bool hasArrow = toolbutton->features & QStyleOptionToolButton::Arrow; if (((!hasArrow && toolbutton->icon.isNull()) && !toolbutton->text.isEmpty()) || toolbutton->toolButtonStyle == Qt::ToolButtonTextOnly) { int alignment = Qt::AlignCenter | Qt::TextShowMnemonic; if (!proxy()->styleHint(SH_UnderlineShortcut, opt, widget)) alignment |= Qt::TextHideMnemonic; rect.translate(shiftX, shiftY); p->setFont(toolbutton->font); proxy()->drawItemText( p, rect, alignment, toolbutton->palette, opt->state & State_Enabled, toolbutton->text, QPalette::ButtonText); } else { QPixmap pm; QSize pmSize = toolbutton->iconSize; if (!toolbutton->icon.isNull()) { QIcon::State state = toolbutton->state & State_On ? QIcon::On : QIcon::Off; QIcon::Mode mode; if (!(toolbutton->state & State_Enabled)) mode = QIcon::Disabled; else if ((opt->state & State_MouseOver) && (opt->state & State_AutoRaise)) mode = QIcon::Active; else mode = QIcon::Normal; pm = toolbutton->icon.pixmap( widget->window()->windowHandle(), toolbutton->rect.size().boundedTo(toolbutton->iconSize), mode, state); pmSize = pm.size() / pm.devicePixelRatio(); } if (toolbutton->toolButtonStyle != Qt::ToolButtonIconOnly) { p->setFont(toolbutton->font); QRect pr = rect, tr = rect; int alignment = Qt::TextShowMnemonic; if (!proxy()->styleHint(SH_UnderlineShortcut, opt, widget)) alignment |= Qt::TextHideMnemonic; if (toolbutton->toolButtonStyle == Qt::ToolButtonTextUnderIcon) { pr.setHeight(pmSize.height() + 4); //### 4 is currently hardcoded in QToolButton::sizeHint() tr.adjust(0, pr.height() - 1, 0, -1); pr.translate(shiftX, shiftY); if (!hasArrow) { proxy()->drawItemPixmap(p, pr, Qt::AlignCenter, pm); } else { drawArrow(proxy(), toolbutton, pr, p, widget); } alignment |= Qt::AlignCenter; } else { pr.setWidth(pmSize.width() + 4); //### 4 is currently hardcoded in QToolButton::sizeHint() tr.adjust(pr.width(), 0, 0, 0); pr.translate(shiftX, shiftY); if (!hasArrow) { proxy()->drawItemPixmap( p, QStyle::visualRect(opt->direction, rect, pr), Qt::AlignCenter, pm); } else { drawArrow(proxy(), toolbutton, pr, p, widget); } alignment |= Qt::AlignLeft | Qt::AlignVCenter; } tr.translate(shiftX, shiftY); // const QString text = d->toolButtonElideText(toolbutton, tr, alignment); proxy()->drawItemText( p, QStyle::visualRect(opt->direction, rect, tr), alignment, toolbutton->palette, toolbutton->state & State_Enabled, toolbutton->text, QPalette::ButtonText); } else { rect.translate(shiftX, shiftY); if (hasArrow) { drawArrow(proxy(), toolbutton, rect, p, widget); } else { proxy()->drawItemPixmap(p, rect, Qt::AlignCenter, pm); } } } } return; } default: break; } return QProxyStyle::drawControl(element, opt, p, widget); } void CustomStyle::drawItemPixmap(QPainter *painter, const QRect &rectangle, int alignment, const QPixmap &pixmap) const { return QProxyStyle::drawItemPixmap(painter, rectangle, alignment, pixmap); } void CustomStyle::drawItemText( QPainter *painter, const QRect &rectangle, int alignment, const QPalette &palette, bool enabled, const QString &text, QPalette::ColorRole textRole) const { return QProxyStyle::drawItemText(painter, rectangle, alignment, palette, enabled, text, textRole); } //绘制简单的颜色圆角等 void CustomStyle::drawPrimitive( QStyle::PrimitiveElement element, const QStyleOption *option, QPainter *painter, const QWidget *widget) const { switch (element) { /*绘制 ToolButton * 任务栏的不同插件需要的样式存在差异 * 在同一个PE中有两个toolbutton 的样式 */ case PE_PanelButtonTool: { { painter->save(); painter->setRenderHint(QPainter::Antialiasing, true); painter->setPen(Qt::NoPen); painter->drawRoundedRect(option->rect, 6, 6); if (option->state & State_MouseOver) { if (option->state & State_Sunken) { // painter->setRenderHint(QPainter::Antialiasing,true); // painter->setPen(Qt::NoPen); // painter->setBrush(QColor(0xff,0xff,0xff,0x0f)); // painter->drawRoundedRect(option->rect,6,6); } else { // painter->setRenderHint(QPainter::Antialiasing,true); // painter->setPen(Qt::NoPen); // painter->setBrush(QColor(0xff,0xff,0xff,0x1f)); // painter->drawRoundedRect(option->rect.adjusted(2,2,-2,-2),6,6); } } painter->restore(); return; } } case PE_PanelButtonCommand: { if (const QStyleOptionButton *button = qstyleoption_cast(option)) { painter->save(); if (option->state & State_MouseOver) { if (option->state & State_Sunken) { // painter->setRenderHint(QPainter::Antialiasing,true); // painter->setPen(Qt::NoPen); // painter->setBrush(QColor(0xff,0xff,0xff,0x0f)); // painter->drawRoundedRect(button->rect,6,6); } else { // painter->setRenderHint(QPainter::Antialiasing,true); // painter->setPen(Qt::NoPen); // painter->setBrush(QColor(0xff,0xff,0xff,0x1f)); // painter->drawRoundedRect(button->rect.adjusted(2,2,-2,-2),6,6); } } painter->restore(); return; } break; } break; } return QProxyStyle::drawPrimitive(element, option, painter, widget); } QPixmap CustomStyle::generatedIconPixmap(QIcon::Mode iconMode, const QPixmap &pixmap, const QStyleOption *option) const { return QProxyStyle::generatedIconPixmap(iconMode, pixmap, option); } QStyle::SubControl CustomStyle::hitTestComplexControl( QStyle::ComplexControl control, const QStyleOptionComplex *option, const QPoint &position, const QWidget *widget) const { return QProxyStyle::hitTestComplexControl(control, option, position, widget); } QRect CustomStyle::itemPixmapRect(const QRect &rectangle, int alignment, const QPixmap &pixmap) const { return QProxyStyle::itemPixmapRect(rectangle, alignment, pixmap); } QRect CustomStyle::itemTextRect( const QFontMetrics &metrics, const QRect &rectangle, int alignment, bool enabled, const QString &text) const { return QProxyStyle::itemTextRect(metrics, rectangle, alignment, enabled, text); } // int CustomStyle::pixelMetric(QStyle::PixelMetric metric, const QStyleOption *option, const QWidget *widget) const { switch (metric) { case PM_ToolBarIconSize: { return (int)48 * qApp->devicePixelRatio(); } default: break; } return QProxyStyle::pixelMetric(metric, option, widget); } /*使悬浮点击等样式生效*/ void CustomStyle::polish(QWidget *widget) { widget->setAttribute(Qt::WA_Hover); return QProxyStyle::polish(widget); } void CustomStyle::polish(QApplication *application) { return QProxyStyle::polish(application); } // void CustomStyle::polish(QPalette &palette) { // return QProxyStyle::polish(palette); // QProxyStyle::polish(palette); // palette.setBrush(QPalette::Foreground, Qt::black); QColor lightBlue(200, 0, 0); palette.setBrush(QPalette::Highlight, lightBlue); } void CustomStyle::unpolish(QWidget *widget) { return QProxyStyle::unpolish(widget); } void CustomStyle::unpolish(QApplication *application) { return QProxyStyle::unpolish(application); } QSize CustomStyle::sizeFromContents( QStyle::ContentsType type, const QStyleOption *option, const QSize &contentsSize, const QWidget *widget) const { return QProxyStyle::sizeFromContents(type, option, contentsSize, widget); } QIcon CustomStyle::standardIcon( QStyle::StandardPixmap standardIcon, const QStyleOption *option, const QWidget *widget) const { return QProxyStyle::standardIcon(standardIcon, option, widget); } QPalette CustomStyle::standardPalette() const { return QProxyStyle::standardPalette(); } //如果需要背景透明也许需要用到这个函数 int CustomStyle::styleHint( QStyle::StyleHint hint, const QStyleOption *option, const QWidget *widget, QStyleHintReturn *returnData) const { switch (hint) { /// 让ScrollView viewport的绘制区域包含scrollbar和corner widget /// 这个例子中没有什么作用,如果我们需要绘制一个背景透明的滚动条 /// 这个style hint对我们的意义应该很大,因为我们希望视图能够帮助 /// 我们填充滚动条的背景区域,否则当背景透明时底下会出现明显的分割 case SH_ScrollView_FrameOnlyAroundContents: { return false; } default: break; } return QProxyStyle::styleHint(hint, option, widget, returnData); } QRect CustomStyle::subControlRect( QStyle::ComplexControl control, const QStyleOptionComplex *option, QStyle::SubControl subControl, const QWidget *widget) const { return QProxyStyle::subControlRect(control, option, subControl, widget); } QRect CustomStyle::subElementRect(QStyle::SubElement element, const QStyleOption *option, const QWidget *widget) const { return QProxyStyle::subElementRect(element, option, widget); } ukui-power-manager-4.0.0.1/ukui-power-manager-tray/powerwindow.h0000664000175000017500000000756714601232446023265 0ustar fengfeng/* * Copyright 2023 KylinSoft Co., Ltd. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ #ifndef POWERWINDOW_H #define POWERWINDOW_H #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include "kylable.h" #include "kslider.h" #include "divider.h" #include "kwindowsystem.h" #include "customstyle.h" #include "powersupplydev.h" using namespace kdk; class powerwindow : public QWidget { Q_OBJECT public: explicit powerwindow(QWidget *parent = nullptr); ~powerwindow(); void setIconName(QString iconName); void setAcOnlineState(bool acOnlineState); void setBatteryState(int iBatteryState); void setBatteryPercentage(int iBatteryPercentage); void setShowPowerLeftTime(int iShowPowerLeftTime); void setBatteryLeftTime(qlonglong timeToFull, qlonglong timeToEmpty); void setPowerStateLabelForAcOnlineChanged(); void setPowerStateLabelForBatteryInfoChanged(); void setPercentageLabelFontsize(); void showPowerWindow(); private : int m_deviceNum = 0; double m_sysFontSize; bool m_isWayland = false; int m_batteryState = battery_state_last; bool m_batteryStateChanged = false; int m_batteryPercentage; bool m_acOnlineState = true; bool m_acOnlineChange; int m_showBatteryLeftTime; qlonglong m_timeToFull; qlonglong m_timeToEmpty; QString m_iconName; double m_transparency; QGSettings *m_transparencyGsettings = nullptr; QGSettings *m_PowerManagerGsettings; QGSettings *m_styleSettings; QDBusInterface *m_interface; QVBoxLayout *m_pmainlayout = nullptr; QHBoxLayout *m_toplayout = nullptr; QHBoxLayout *m_firstlayout = nullptr; QHBoxLayout *m_lastlayout = nullptr; QHBoxLayout *m_statelayout = nullptr; QWidget *m_firstwidget; QWidget *m_lastWidget; QWidget *m_topwidget; QWidget *m_statewidget; QPushButton *m_iconButton; QLabel *m_percentageLabel; QLabel *m_powerStateLabel; QLabel *m_toplabel; QToolButton *m_enduranceIconButtun; QToolButton *m_performanceIconButtun; Divider *m_segmentationLine_1; Divider *m_segmentationLine_2; KSlider *m_StateSlider; KyLable *m_settingLabel; QRect m_windowPositionRect; enum PanelStatePosition { PanelDown = 0, PanelUp, PanelLeft, PanelRight }; enum powerPolicy { Performance = 0, Balance, EnergySaving, }; void initUI(); void initgsetting(); void initPlatformType(); void resetWindowPosition(); void setWindowProperty(); bool eventFilter(QObject *watched, QEvent *event); void keyPressEvent(QKeyEvent *event); void watchTranspartency(); void setSliderValue(); private Q_SLOTS: void sliderValueChanged(int); protected: void paintEvent(QPaintEvent *e); }; #endif // POWERWINDOW_H ukui-power-manager-4.0.0.1/ukui-power-manager-tray/notificationdialog.cpp0000664000175000017500000001234514601232446025070 0ustar fengfeng/* * Copyright 2023 KylinSoft Co., Ltd. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ #include "notificationdialog.h" #include #include #include NotificationDialog::NotificationDialog(QWidget *parent) : QDialog(parent) { uiInit(); setWindowFlags(Qt::FramelessWindowHint | Qt::X11BypassWindowManagerHint); //无边框、禁止拖动、禁止改变大小、不受窗管管理); setAttribute(Qt::WA_TranslucentBackground); //透明背景 timerInit(); } NotificationDialog::~NotificationDialog() {} void NotificationDialog::uiInit() { //初始化弹窗界面 setFixedSize(480, 174); setWindowFlag(Qt::WindowStaysOnTopHint); m_layout = new QVBoxLayout(this); m_topLayout = new QHBoxLayout(this); m_verLayout = new QVBoxLayout(this); m_verLayout->setContentsMargins(10, 10, 10, 10); m_closeButton = new QPushButton(this); m_closeButton->setFixedSize(32, 32); m_closeButton->setProperty("isWindowButton", 0x02); m_closeButton->setProperty("useIconHighlightEffect", 0x08); m_closeButton->setIcon(QIcon::fromTheme("window-close-symbolic")); m_closeButton->setFlat(true); //初始化消息提示 m_tipsLabel = new QLabel(this); m_tipsLabel->setAlignment(Qt::AlignVCenter); m_tipsLabel->setMinimumWidth(1); m_tipsLabel->setFixedWidth(462); m_warningText = tr("The system will %1 in 60 seconds as the battery is about to run out.") .arg(m_showText); QFontMetricsF fm(this->font()); QString elidedText = fm.elidedText(m_warningText, Qt::ElideRight, 450, Qt::TextSingleLine); m_tipsLabel->setText(elidedText); m_tipsLabel->installEventFilter(this); //初始化确认按钮 m_confirmBtn = new QPushButton(this); m_confirmBtn->setFixedSize(100, 36); m_confirmBtn->setProperty("isImportant", true); m_confirmBtn->setText(tr("I know")); connect(m_closeButton, &QPushButton::clicked, this, &NotificationDialog::confirmBtnClicked); connect(m_confirmBtn, &QPushButton::clicked, this, &NotificationDialog::confirmBtnClicked); m_topLayout->addWidget(m_closeButton, 0, Qt::AlignRight); m_verLayout->addWidget(m_tipsLabel, 0, Qt::AlignLeft | Qt::AlignCenter); m_verLayout->addWidget(m_confirmBtn, 0, Qt::AlignRight | Qt::AlignCenter); m_layout->addLayout(m_topLayout); m_layout->addLayout(m_verLayout); this->setLayout(m_layout); } void NotificationDialog::timerInit() { m_showTimer = new QTimer(this); m_clockTimer = new QTimer(this); connect(m_showTimer, &QTimer::timeout, this, &NotificationDialog::showTime); connect(m_clockTimer, &QTimer::timeout, this, &NotificationDialog::stopTimer); } void NotificationDialog::start() { m_clockTimer->start(60000); m_showTimer->start(250); } void NotificationDialog::confirmBtnClicked() { stopTimer(); this->hide(); Q_EMIT dialogClosed(); } void NotificationDialog::showTime() { m_warningText = tr("The system will %1 in %2 seconds as the battery is about to run out.") .arg(m_showText) .arg(m_clockTimer->remainingTime() / 1000); QFontMetricsF fm(this->font()); QString elidedText = fm.elidedText(m_warningText, Qt::ElideRight, 450, Qt::TextSingleLine); m_tipsLabel->setText(elidedText); } void NotificationDialog::stopTimer() { if (m_showTimer->isActive()) { m_showTimer->stop(); } if (m_clockTimer->isActive()) { m_clockTimer->stop(); } qDebug() << "dialog timer stop!"; } void NotificationDialog::setShowMsg(QString str) { if (0 == str.compare("shutdown")) { m_showText = tr("shutdown"); } else if (0 == str.compare("hibernate")) { m_showText = tr("hibernate"); } else if (0 == str.compare("suspend")) { m_showText = tr("suspend"); } } void NotificationDialog::paintEvent(QPaintEvent *) { QStyleOption option; option.init(this); QPainter painter(this); painter.setRenderHint(QPainter::Antialiasing); painter.setPen(Qt::NoPen); painter.setBrush(option.palette.color(QPalette::Base)); QPainterPath painterPath; QRect rect = this->rect(); painterPath.addRoundedRect(rect, 12, 12); painter.drawRoundedRect(rect, 12, 12); style()->drawPrimitive(QStyle::PE_Widget, &option, &painter, this); } bool NotificationDialog::eventFilter(QObject *watched, QEvent *event) { if (watched == m_tipsLabel) { if (event->type() == QEvent::Enter) { QFontMetricsF fm(this->font()); if (fm.boundingRect(m_warningText).width() > 450) { QToolTip::showText(QCursor::pos(), m_warningText); } } } return false; } ukui-power-manager-4.0.0.1/ukui-power-manager-tray/fullscreenmask.cpp0000664000175000017500000000370114601232446024234 0ustar fengfeng/* * Copyright (C) 2023, KylinSoft Co., Ltd. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . * */ #include #include #include #include #include #include #include #include "fullscreenmask.h" FullScreenMask::FullScreenMask(QWidget *parent) : QWidget(parent) { setWindowFlags(Qt::FramelessWindowHint | Qt::X11BypassWindowManagerHint); //无边框、禁止拖动、禁止改变大小、不受窗管管理 setAttribute(Qt::WA_TranslucentBackground); //透明背景 setFixedSize(QApplication::desktop()->width(), QApplication::desktop()->height()); move(QGuiApplication::primaryScreen()->geometry().x(), QGuiApplication::primaryScreen()->geometry().y()); } void FullScreenMask::paintEvent(QPaintEvent *event) { //绘制背景 QStyleOption opt; opt.init(this); QPainter p(this); QBrush brush(QColor(165,165,165,255*0.8)); p.setBrush(brush); p.setOpacity(0.3); p.setPen(Qt::NoPen); QPainterPath path; QRect mainRect(0, 0, this->width(), this->height()); path.addRoundedRect(mainRect, 0, 0); p.setRenderHint(QPainter::Antialiasing); p.drawRoundedRect(mainRect, 0, 0); style()->drawPrimitive(QStyle::PE_Widget, &opt, &p, this); QWidget::paintEvent(event); } ukui-power-manager-4.0.0.1/ukui-power-manager-tray/kylable.h0000664000175000017500000000253414601232446022311 0ustar fengfeng/* * Copyright (C) 2023, KylinSoft Co., Ltd. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . * */ #ifndef KYLABLE_H #define KYLABLE_H #include #include #include class KyLable : public QLabel { Q_OBJECT public: explicit KyLable(QWidget *parent = nullptr); ~KyLable() = default; protected: void paintEvent(QPaintEvent *event); void enterEvent(QEvent *event); void leaveEvent(QEvent *event); void mousePressEvent(QMouseEvent *event); void mouseReleaseEvent(QMouseEvent *event); private: QColor m_foregroundColor; QGSettings *m_styleSettings; void setPressColor(); void setHoverColor(); void setNormalColor(); private Q_SLOTS: void onPaletteChanged(); }; #endif // KYLABLE_H ukui-power-manager-4.0.0.1/man/0000775000175000017500000000000014601232446014570 5ustar fengfengukui-power-manager-4.0.0.1/man/ukui-powermanagement.10000664000175000017500000000137414601232446021023 0ustar fengfeng.TH ukui-powermanagement .SH NAME ukui-powermanagement \- The power-manager Daemon for the UKUI Desktop Environment .SH DESCRIPTION This module show power-manager Daemon This program is a background process of power management, which is mainly responsible for controlling the idle operation, closing operation, and low power operation of the operating system. And monitor the action of plugging and unplugging the power cord and perform corresponding operations. .SH "REPORTING BUGS" Report bugs to http://gitlab2.kylin.com/ukui/ukui-power-manager/issues .SH "SEE ALSO" .SS Ukui PowerManager documentation can be found under "Help" by right-clicking on \fBukui-power-manager\fR. Further information may also be available at: http://wiki.ukui-desktop.org/docs .P ukui-power-manager-4.0.0.1/man/ukui-power-manager-tray.10000664000175000017500000000143014601232446021344 0ustar fengfeng.TH ukui-power-manager-tray .SH NAME ukui-power-manager-tray \- The power-manager UI for the UKUI Desktop Environment .SH DESCRIPTION This module show power-manager widget This process is mainly for displaying the power management tray and the main interface after opening the tray icon. Currently, the main interface will show the user the current remaining power and remaining charging time. And provide users with an interface to enter the control panel to set related power operations. .SH "REPORTING BUGS" Report bugs to http://gitlab2.kylin.com/ukui/ukui-power-manager/issues .SH "SEE ALSO" .SS Ukui PowerManager documentation can be found under "Help" by right-clicking on \fBukui-power-manager\fR. Further information may also be available at: http://wiki.ukui-desktop.org/docs .P ukui-power-manager-4.0.0.1/man/ukui-powermanagement-service.10000664000175000017500000000136514601232446022461 0ustar fengfeng.TH ukui-power-management-server .SH NAME ukui-power-management-server \- The power-manager Dbus Server for the UKUI Desktop Environment .SH DESCRIPTION This module show power-manager Dbus Server This service provides corresponding interfaces for the power management background process, such as shutdown, hibernation, sleep, etc. The main corresponding interface is the corresponding interface provided by systemd. The service is treated as a SystemBus. .SH "REPORTING BUGS" Report bugs to http://gitlab2.kylin.com/ukui/ukui-power-manager/issues .SH "SEE ALSO" .SS Ukui PowerManager documentation can be found under "Help" by right-clicking on \fBukui-power-manager\fR. Further information may also be available at: http://wiki.ukui-desktop.org/docs .P ukui-power-manager-4.0.0.1/readme.md0000664000175000017500000000036414601232446015577 0ustar fengfeng## dbus 服务 ``` 用于提权 使用方法: mkdir build make -j8 sudo make install //这样会讲service文件安装到系统目录下 调用exitService接口退出 //或者重启,否则修改无法生效(注销也不生效) ``` ukui-power-manager-4.0.0.1/powermanagement.pro0000664000175000017500000000023214601232446017725 0ustar fengfengTEMPLATE = subdirs CONFIG += ordered SUBDIRS = \ registeredQDbus \ PowerManagementDaemon \ ukui-power-manager-tray \ plugin-power \ ukui-power-manager-4.0.0.1/registeredQDbus/0000775000175000017500000000000014601232446017111 5ustar fengfengukui-power-manager-4.0.0.1/registeredQDbus/sysdbusregister.cpp0000664000175000017500000002160414601232446023061 0ustar fengfeng/* * Copyright 2023 KylinSoft Co., Ltd. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ #include "sysdbusregister.h" #include SysdbusRegister::SysdbusRegister() { getCpuInfo(); m_powerConfig = new PowerConfig(this); int brightnessPercent = -1; if (false == m_powerConfig->isFirstRun()) { brightnessPercent = m_powerConfig->getPowerConfig(GSETTINGS_KEY_BRIGHTNESS_AC).toInt(); } m_brightnessNode = new BrightnessNode(brightnessPercent, this); if (-1 == brightnessPercent) { m_powerConfig->updatePowerConfig(GSETTINGS_KEY_BRIGHTNESS_AC, QString::number(m_brightnessNode->getBrightnessPercent())); } m_susThenHibSet = new QSettings(QString("/etc/systemd/sleep.conf"), QSettings::IniFormat, this); m_susThenHibSet->setIniCodec("UTF-8"); m_devPowerControl = new DevPowerControl(this); } SysdbusRegister::~SysdbusRegister() { delete m_susThenHibSet; } void SysdbusRegister::getCpuInfo() { m_cpuCoreNum = executeLinuxCmd("grep -c 'processor' /proc/cpuinfo").toInt(); QString result = executeLinuxCmd("cat /sys/devices/system/cpu/cpu0/cpufreq/scaling_available_governors"); if (result.contains("schedutil")) { m_cpuFreqMode[Balance] = "schedutil"; } else if (result.contains("ondemand")) { m_cpuFreqMode[Balance] = "ondemand"; } else { m_cpuFreqMode[Balance] = "powersave"; } } QString SysdbusRegister::executeLinuxCmd(QString strCmd) { QProcess process; //调用linux终端命令 process.start("bash", QStringList() << "-c" << strCmd); process.waitForFinished(); QString strResult = process.readAllStandardOutput() + process.readAllStandardError(); return strResult; } QString SysdbusRegister::canControl(const QString control) { QDBusInterface interface( "org.freedesktop.login1", "/org/freedesktop/login1", "org.freedesktop.login1.Manager", QDBusConnection::systemBus()); QDBusReply reply = interface.call(control); if (reply.isValid()) { if ("yes" == reply.value()) { return reply; } else { QDBusMessage message = QDBusMessage::createSignal("/", "org.ukui.powermanagement.interface", "CanControl"); message << reply.value(); QDBusConnection::systemBus().send(message); return reply; } } else { return "error"; } } void SysdbusRegister::controlLogin1Connection(QString type) { bool ctrl = 1; QDBusInterface interface( "org.freedesktop.login1", "/org/freedesktop/login1", "org.freedesktop.login1.Manager", QDBusConnection::systemBus()); interface.call(type, ctrl); } void SysdbusRegister::blockLidAction() { QDBusInterface interface( QStringLiteral("org.freedesktop.login1"), QStringLiteral("/org/freedesktop/login1"), QStringLiteral("org.freedesktop.login1.Manager"), QDBusConnection::systemBus()); QDBusReply reply = interface.call( QStringLiteral("Inhibit"), QStringLiteral("handle-lid-switch"), QStringLiteral("powermanagment"), QStringLiteral("ukui-powermanagement blocked LidSwitch!"), QStringLiteral("block")); if (reply.isValid()) { m_login1Lock = reply.value(); m_blockLidAction = true; qDebug() << "Inhibit got:" << m_login1Lock.fileDescriptor(); } else { qDebug() << "Error from inhibit:" << reply.error(); } } void SysdbusRegister::releaseLidAction() { m_blockLidAction = false; } void SysdbusRegister::UserLogin(const QString userName) { if (false == m_userMap.contains(userName)) { m_userMap.insert(userName, true); } if (false == m_blockLidAction) { blockLidAction(); } UserActive(userName); } void SysdbusRegister::UserLogout(const QString userName) { if (true == m_userMap.contains(userName)) { m_userMap.remove(userName); if (0 == m_userMap.size()) { if (true == m_blockLidAction) { releaseLidAction(); } } } } void SysdbusRegister::UserActive(const QString userName) { QList keys = m_userMap.keys(); for (int i = 0; i < keys.size(); ++i) { QString key = keys.at(i); if (key == userName) { m_userMap.insert(key, true); } else { m_userMap.insert(key, false); } } emit ActiveUserChanged(userName); } bool SysdbusRegister::CanSetBrightness() { return m_brightnessNode->canSetBrightness(); } void SysdbusRegister::SetBrightnessPercent(const int percent) { m_brightnessNode->setBrightnessPercent(percent); } int SysdbusRegister::GetBrightnessPercent() { return m_brightnessNode->getBrightnessPercent(); } int SysdbusRegister::GetMaxBrightness() { return m_brightnessNode->getMaxBrightness(); } void SysdbusRegister::SetReduceBacklightSwitch(const bool value) { m_brightnessNode->setReduceMaxBrightness(value); } void SysdbusRegister::SetPcPolicy(const int policy) { SetCpuPolicy(policy); SetGpuPolicy(policy); SetAudioPolicy(policy); SetAspmPolicy(policy); if (Performance == policy) { m_devPowerControl->setAllDevicePerformance(); } else if (EnergySaving == policy) { m_devPowerControl->setAllDeviceSave(); } else { m_devPowerControl->setAllDeviceBalance(); } } void SysdbusRegister::SetCpuPolicy(const int policy) { if (policy < Performance || policy > EnergySaving) { return ; } for (int var = 0; var < m_cpuCoreNum; ++var) { executeLinuxCmd( QString("echo %1 | tee /sys/devices/system/cpu/cpu%2/cpufreq/scaling_governor") .arg(m_cpuFreqMode[policy]).arg(var)); } } void SysdbusRegister::SetGpuPolicy(const int policy) { if (policy < Performance || policy > EnergySaving) { return ; } QFile radeonFile("/sys/class/drm/card0/device/power_dpm_state"); QFile amdgpuFile("/sys/class/drm/card0/device/power_dpm_force_performance_level"); QStringList radeonPolicy = {"performance", "balanced", "battery"}; QStringList amdGpuPolicy = {"high", "auto", "low"}; QString cmd; if (radeonFile.exists()) { cmd = QString("echo %1 | tee /sys/class/drm/card0/device/power_dpm_state").arg(radeonPolicy[policy]); executeLinuxCmd(cmd); } if (amdgpuFile.exists()) { cmd = QString("echo %1 | tee /sys/class/drm/card0/device/power_dpm_force_performance_level").arg(amdGpuPolicy[policy]); executeLinuxCmd(cmd); } } void SysdbusRegister::SetAudioPolicy(const int policy) { if (Performance == policy) { executeLinuxCmd(QString("echo 0 | tee /sys/module/snd_hda_intel/parameters/power_save")); } else { executeLinuxCmd(QString("echo 1 | tee /sys/module/snd_hda_intel/parameters/power_save")); } } void SysdbusRegister::SetAspmPolicy(const int policy) { if (Performance == policy) { executeLinuxCmd(QString("echo default | tee /sys/module/pcie_aspm/parameters/policy")); } else { executeLinuxCmd(QString("echo powersave | tee /sys/module/pcie_aspm/parameters/policy")); } } void SysdbusRegister::LockScreen() { //锁屏目前由后台处理 } void SysdbusRegister::Hibernate() { if ("yes" == canControl("CanHibernate")) { controlLogin1Connection("Hibernate"); } } void SysdbusRegister::Suspend() { if ("yes" == canControl("CanSuspend")) { controlLogin1Connection("Suspend"); } } void SysdbusRegister::PowerOff() { if ("yes" == canControl("CanPowerOff")) { controlLogin1Connection("PowerOff"); } } void SysdbusRegister::SuspendThenHibernate() { if ("yes" == canControl("CanSuspendThenHibernate")) { m_susThenHibSet->beginGroup("Sleep"); m_susThenHibSet->setValue("HibernateDelaySec", 7200); m_susThenHibSet->endGroup(); m_susThenHibSet->sync(); controlLogin1Connection("SuspendThenHibernate"); } } void SysdbusRegister::SetSystemConfig(const QString userName, const QString key, const QString value) { m_powerConfig->updatePowerConfig(key, value); if (m_userMap.size() > 1) { emit SystemConfigChanged(userName, key, value); } } QString SysdbusRegister::GetSystemConfig(const QString key) { return m_powerConfig->getPowerConfig(key); } ukui-power-manager-4.0.0.1/registeredQDbus/brightness-control/0000775000175000017500000000000014601232446022737 5ustar fengfengukui-power-manager-4.0.0.1/registeredQDbus/brightness-control/brightnessnode.cpp0000664000175000017500000001306314601232446026464 0ustar fengfeng/* * Copyright 2023 KylinSoft Co., Ltd. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ #include #include #include #include #include "brightnessnode.h" BrightnessNode::BrightnessNode(int percent, QObject *parent) : QObject(parent) { qDebug() << "init brightness node info"; m_hasEffectiveNode = false; m_maxbrightness = 0; UpmPreprocessor upp; QString brightnessNode = upp.getBrightnessNode(); qDebug() << "get brightness node:" << brightnessNode; if (brightnessNode.isNull()) { qDebug() << "brightness node is null"; m_effectiveNodePath = QString(); initBrightnessNodeInfo(); } else { m_effectiveNodePath = BRIGHTNESS_NODE_PATH + brightnessNode; QDir brightnessDir(m_effectiveNodePath); if (brightnessDir.exists()) { qDebug() << "brightness dir :" << m_effectiveNodePath; m_maxbrightness = getBrightnessNodeFileContent(m_effectiveNodePath, "/max_brightness").toInt(); m_hasEffectiveNode = true; } else { qDebug() << "brightness dir no exists"; m_effectiveNodePath = QString(); initBrightnessNodeInfo(); } } initBrightnessPercent(percent); m_effectiveMaxbrightness = m_maxbrightness; qDebug() << "node path :" << m_effectiveNodePath; } BrightnessNode::~BrightnessNode() {} void BrightnessNode::initBrightnessNodeInfo() { QDir brightnessNodeDir(BRIGHTNESS_NODE_PATH); m_nodeDirs = brightnessNodeDir.entryList(QDir::Dirs | QDir::NoDotAndDotDot); int i = 0; QStringList allNodesType; for (i = 0; i < m_nodeDirs.size(); ++i) { allNodesType << getBrightnessNodeFileContent(BRIGHTNESS_NODE_PATH + m_nodeDirs.at(i), "/type"); } QStringList nodeTypes = {"firmware", "platform", "raw"}; for (i = 0; i < nodeTypes.size(); ++i) { if (true == getEffectiveBrightnessNode(allNodesType, nodeTypes.at(i))) { m_hasEffectiveNode = true; m_maxbrightness = getBrightnessNodeFileContent(m_effectiveNodePath, "/max_brightness").toInt(); break; } } } void BrightnessNode::initBrightnessPercent(int percent) { if (false == m_hasEffectiveNode) { m_brightnessPercent = 0; return ; } if (-1 == percent) { m_brightnessPercent = getCurrentBrightness() / m_maxbrightness * 100; } else { m_brightnessPercent = percent; } } bool BrightnessNode::getEffectiveBrightnessNode(const QStringList &nodesType, const QString &type) { int nodesNum = 0; int nodeIndex = 0; for (int i = 0; i < nodesType.size(); ++i) { if (type == nodesType.at(i)) { nodesNum++; nodeIndex = i; } } if (1 == nodesNum) { m_effectiveNodePath = BRIGHTNESS_NODE_PATH + m_nodeDirs.at(nodeIndex); return true; } return false; } QString BrightnessNode::getBrightnessNodeFileContent(const QString &strNodePath, const QString &strNodeFile) { QFile nodeFile(strNodePath + strNodeFile); if (!nodeFile.open(QIODevice::ReadOnly | QIODevice::Text)) { qDebug() << "open file error :" << strNodePath + strNodeFile; return ""; } QString fileContent = nodeFile.readLine(); nodeFile.close(); return fileContent.remove('\n'); } bool BrightnessNode::canSetBrightness() { return m_hasEffectiveNode; } int BrightnessNode::getCurrentBrightness() { return getBrightnessNodeFileContent(m_effectiveNodePath, "/brightness").toInt(); } void BrightnessNode::setCurrentBrightness(int brightness) { if (false == m_hasEffectiveNode) { return ; } QFile brightnessFile(m_effectiveNodePath + "/brightness"); if (!brightnessFile.open(QIODevice::WriteOnly | QIODevice::Text)) { return ; } QTextStream in(&brightnessFile); in << brightness << endl; brightnessFile.close(); } void BrightnessNode::setBrightnessPercent(int percent) { if (percent < RESERVE_BRIGHTNESS_PERCENT) { setCurrentBrightness(m_effectiveMaxbrightness * 0.02); m_brightnessPercent = percent; qDebug() << "BrightnessNode percent < 2:" << percent; } else { if (percent > 100) { setCurrentBrightness(m_effectiveMaxbrightness); m_brightnessPercent = 100; qDebug() << "BrightnessNode percent > 100:" << percent; } else { setCurrentBrightness(m_effectiveMaxbrightness * percent * 0.01); m_brightnessPercent = percent; qDebug() << "BrightnessNode 0 < percent < 100:" << percent; } } } int BrightnessNode::getBrightnessPercent() { return m_brightnessPercent; } int BrightnessNode::getMaxBrightness() { return m_maxbrightness; } void BrightnessNode::setReduceMaxBrightness(bool value) { if (true == value) { m_effectiveMaxbrightness = m_maxbrightness * 0.7; } else { m_effectiveMaxbrightness = m_maxbrightness; } setBrightnessPercent(m_brightnessPercent); } ukui-power-manager-4.0.0.1/registeredQDbus/brightness-control/brightnessnode.h0000664000175000017500000000343414601232446026132 0ustar fengfeng/* * Copyright 2023 KylinSoft Co., Ltd. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ #ifndef BRIGHTNESSNODE_H #define BRIGHTNESSNODE_H #include #include "upmpreprocessor.h" #define BRIGHTNESS_NODE_PATH "/sys/class/backlight/" #define RESERVE_BRIGHTNESS_PERCENT 3 class BrightnessNode : public QObject { Q_OBJECT public: explicit BrightnessNode(int percent, QObject *parent = nullptr); ~BrightnessNode(); private: bool m_hasEffectiveNode; int m_maxbrightness; int m_effectiveMaxbrightness; int m_brightnessPercent; QStringList m_nodeDirs; QString m_effectiveNodePath; void initBrightnessNodeInfo(); void initBrightnessPercent(int percent); QString getBrightnessNodeFileContent(const QString &strNodePath, const QString &strNodeFile); bool getEffectiveBrightnessNode(const QStringList &nodesType, const QString &type); bool compatibleBrightnessNode(); void setCurrentBrightness(int brightness); int getCurrentBrightness(); public: bool canSetBrightness(); void setBrightnessPercent(int); int getBrightnessPercent(); int getMaxBrightness(); void setReduceMaxBrightness(bool); }; #endif // BRIGHTNESSNODE_H ukui-power-manager-4.0.0.1/registeredQDbus/conf/0000775000175000017500000000000014601232446020036 5ustar fengfengukui-power-manager-4.0.0.1/registeredQDbus/conf/org.ukui.powermanagement.service0000664000175000017500000000014314601232446026351 0ustar fengfeng[D-BUS Service] Name=org.ukui.powermanagement Exec=/usr/bin/ukui-powermanagement-service User=root ukui-power-manager-4.0.0.1/registeredQDbus/conf/org.ukui.powermanagement.conf0000664000175000017500000000162514601232446025644 0ustar fengfeng ukui-power-manager-4.0.0.1/registeredQDbus/powerconfig.h0000664000175000017500000000525014601232446021606 0ustar fengfeng/* * Copyright (C) 2023, KylinSoft Co., Ltd. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . * */ #ifndef POWERCONFIG_H #define POWERCONFIG_H #include #include #include #define POWER_MANAGER_CONF_PATH "/etc/power/power-manager.conf" #define CONFIG_GROUP_CONFIG "config" #define POWER_MANAGER_FIRST_RUN "powerManagerFirstRun" //电源策略(0:节能 1:平衡 2:性能) #define GSETTINGS_KEY_POWER_POLICY_AC "powerPolicyAc" #define GSETTINGS_KEY_POWER_POLICY_BATTERY "powerPolicyBattery" #define GSETTINGS_KEY_POWER_POLICY_BATTERY_BACKUP "powerPolicyBatteryBackup" //空闲关闭显示器 #define GSETTINGS_KEY_SLEEP_DISPLAY_AC "sleepDisplayAc" #define GSETTINGS_KEY_SLEEP_DISPLAY_BATTERY "sleepDisplayBattery" //空闲睡眠 #define GSETTINGS_KEY_SLEEP_COMPUTER_AC "sleepComputerAc" #define GSETTINGS_KEY_SLEEP_COMPUTER_BATTERY "sleepComputerBattery" //盒盖事件触发操作 #define GSETTINGS_KEY_BUTTON_LID_AC "buttonLidAc" #define GSETTINGS_KEY_BUTTON_LID_BATTERY "buttonLidBattery" //低电量百分百通知 #define GSETTINGS_KEY_PERCENTAGE_LOW "percentageLow" //极低电量 #define GSETTINGS_KEY_PERCENTAGE_ACTION "percentageAction" //极低电量时执行 #define GSETTINGS_KEY_ACTION_CRITICAL_BATTERY "actionCriticalBattery" //低电量时自动开启节能模式 #define GSETTINGS_KEY_BATTERY_SAVE_SWITCH "batterySaveSwitch" //低电量时自动开启节能模式 #define GSETTINGS_KEY_LOW_BATTERY_AUTO_SAVE "lowBatteryAutoSave" //节能模式降低亮度 #define GSETTINGS_KEY_BATTERY_SAVE_REDUCE_BRIGHTNESS "batterySaveReduceBrightness" //亮度值 #define GSETTINGS_KEY_BRIGHTNESS_AC "brightnessAc" class PowerConfig : public QObject { Q_OBJECT public: explicit PowerConfig(QObject *parent = nullptr); ~PowerConfig(); bool isFirstRun(); void updatePowerConfig(const QString &key, const QString &value); QString getPowerConfig(const QString &key); private: bool m_isFirstRun; QSettings *m_qsettings; signals: }; #endif // POWERCONFIG_H ukui-power-manager-4.0.0.1/registeredQDbus/registeredQDbus.pro0000664000175000017500000000232414601232446022730 0ustar fengfengQT += core dbus x11extras QT -= gui greaterThan(QT_MAJOR_VERSION, 4): QT += widgets include($$PWD/../common/common.pri) TARGET = ukui-powermanagement-service TEMPLATE = app CONFIG += console c++11 link_pkgconfig CONFIG -= app_bundle LIBS += -lpci DESTDIR = . INCLUDEPATH += . DEFINES += MODULE_NAME=\\\"pm\\\" inst1.files += conf/org.ukui.powermanagement.service inst1.path = /usr/share/dbus-1/system-services/ inst2.files += conf/org.ukui.powermanagement.conf inst2.path = /usr/share/dbus-1/system.d/ target.source += $$TARGET target.path = /usr/bin INSTALLS += \ target \ inst1 \ inst2 \ HEADERS += \ brightness-control/brightnessnode.h \ dev-power-control/devpowercontrol.h \ powerconfig.h \ sysdbusregister.h \ dev-power-control/devicepowerinfo.h \ dev-power-control/i2cdevice.h \ dev-power-control/pcidevice.h \ dev-power-control/satadevice.h \ SOURCES += \ brightness-control/brightnessnode.cpp \ dev-power-control/devpowercontrol.cpp \ main.cpp \ powerconfig.cpp \ sysdbusregister.cpp \ dev-power-control/devicepowerinfo.cpp \ dev-power-control/i2cdevice.cpp \ dev-power-control/pcidevice.cpp \ dev-power-control/satadevice.cpp \ ukui-power-manager-4.0.0.1/registeredQDbus/dev-power-control/0000775000175000017500000000000014601232446022477 5ustar fengfengukui-power-manager-4.0.0.1/registeredQDbus/dev-power-control/pcidevice.cpp0000664000175000017500000001401314601232446025135 0ustar fengfeng/* * Copyright 2023 KylinSoft Co., Ltd. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ #include #include #include #include #include #include "pcidevice.h" static struct pci_access *g_pciAccess = NULL; PciDevice::PciDevice(QObject *parent) : QObject(parent) { m_controlFile = QString("/power/control"); getPCIDevicePowerInfo(); getBlockDevicePowerInfo(); } void PciDevice::getAtaDevicePowerInfo(const QString &parentDir) { QDir ataDeviceDir(parentDir); if(!ataDeviceDir.exists()) { return; } QStringList ataDeviceDirs = ataDeviceDir.entryList(QDir::Dirs).filter("ata"); for (int i = 0; i < ataDeviceDirs.size(); ++i) { QString devicePath = parentDir + '/' + ataDeviceDirs.at(i); if (true == deviceHasRuntimePM(devicePath)) { QString devName = lookupPciDeviceName(devicePath); m_devicePowerInfo.push_back(new DevicePowerInfo("pci-ata", devicePath, devName, m_controlFile, this)); } } } void PciDevice::getPCIDevicePowerInfo() { QDir deviceDir(PCI_DEVICE_PATH); if(!deviceDir.exists()) { return; } QStringList deviceDirs = deviceDir.entryList(QDir::Dirs | QDir::NoDotAndDotDot); for (int i = 0; i < deviceDirs.size(); ++i) { QString devicePath = PCI_DEVICE_PATH + deviceDirs.at(i); if (true == deviceHasRuntimePM(devicePath)) { QString devName = lookupPciDeviceName(devicePath); m_devicePowerInfo.push_back(new DevicePowerInfo("pci", devicePath, devName, m_controlFile, this)); } getAtaDevicePowerInfo(devicePath); } } void PciDevice::getBlockDevicePowerInfo() { QDir blockDeviceDir(PCI_BLOCK_DEVICE_PATH); if(!blockDeviceDir.exists()) { return; } QStringList blockDeviceDirs = blockDeviceDir.entryList(QDir::Dirs).filter("sd"); for (int i = 0; i < blockDeviceDirs.size(); ++i) { QString controlFilePath = PCI_BLOCK_DEVICE_PATH + blockDeviceDirs.at(i) + "/device"; if (true == deviceHasRuntimePM(controlFilePath)) { m_devicePowerInfo.push_back(new DevicePowerInfo("pci-block", controlFilePath, blockDeviceDirs.at(i), m_controlFile, this)); } } } bool PciDevice::deviceHasRuntimePM(const QString &devPath) { QFile pmFile(devPath + m_controlFile); if (!pmFile.exists()) { return false; } pmFile.setFileName(devPath + "/power/runtime_suspended_time"); if (!pmFile.open(QIODevice::ReadOnly | QIODevice::Text)) { qCritical() << "open file error:" << pmFile.fileName(); return false; } ulong value = pmFile.readLine().toULong(); pmFile.close(); if (value) { return true; } pmFile.setFileName(devPath + "/power/runtime_active_time"); if (!pmFile.open(QIODevice::ReadOnly | QIODevice::Text)) { qCritical() << "open file error:" << pmFile.fileName(); return false; } value = pmFile.readLine().toULong(); pmFile.close(); if (value) { return true; } return false; } QString PciDevice::lookupPciDeviceName(const QString &devPath) { ulong vendorId = 0; ulong deviceId = 0; bool ok; QFile file(devPath + "/vendor"); if (file.open(QIODevice::ReadOnly | QIODevice::Text)) { vendorId = file.readLine().toULong(&ok, 16); file.close(); } file.setFileName(devPath + "/device"); if (file.open(QIODevice::ReadOnly | QIODevice::Text)) { deviceId = file.readLine().toULong(&ok, 16); file.close(); } char devName[512] = {0}; char *pDevName = NULL; if (NULL == g_pciAccess) { g_pciAccess = pci_alloc(); pci_init(g_pciAccess); } pDevName = pci_lookup_name(g_pciAccess, devName, 512, PCI_LOOKUP_VENDOR | PCI_LOOKUP_DEVICE, vendorId, deviceId); return QString(pDevName); } int PciDevice::getPCIDeviceNum() { return m_devicePowerInfo.count(); } QString PciDevice::getDeviceName(int deviceIndex) { if (deviceIndex < m_devicePowerInfo.count()) { return m_devicePowerInfo[deviceIndex]->getDeviceName(); } return "False"; } QString PciDevice::getCurrentPowerStat(int deviceIndex) { if (deviceIndex < m_devicePowerInfo.count()) { return m_devicePowerInfo[deviceIndex]->getCurrentPowerStat(); } return "False"; } QString PciDevice::getDefaultPowerStat(int deviceIndex) { if (deviceIndex < m_devicePowerInfo.count()) { return m_devicePowerInfo[deviceIndex]->getDefaultPowerStat(); } return "False"; } bool PciDevice::setPowerStat(int deviceIndex, const QString &stat) { if (stat == "auto" || stat == "on" || stat == "default") { if (deviceIndex < m_devicePowerInfo.count()) { return m_devicePowerInfo[deviceIndex]->setDevicePowerStat(stat); } } return false; } bool PciDevice::setAllDevicePowerStat(const QString &stat) { if (stat == "auto" || stat == "on" || stat == "default") { for (int i = 0; i < m_devicePowerInfo.count(); ++i) { m_devicePowerInfo[i]->setDevicePowerStat(stat); } return true; } return false; } void PciDevice::printAllDeviceInfo() { qDebug() << "pci device"; for (int i = 0; i < m_devicePowerInfo.count(); ++i) { qDebug() << "name:" << m_devicePowerInfo[i]->getDeviceName() << "path:" << m_devicePowerInfo[i]->getDevicePath() << "stat:" << m_devicePowerInfo[i]->getDefaultPowerStat(); } } ukui-power-manager-4.0.0.1/registeredQDbus/dev-power-control/pcidevice.h0000664000175000017500000000330214601232446024601 0ustar fengfeng/* * Copyright 2023 KylinSoft Co., Ltd. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ #ifndef PCIDEVICE_H #define PCIDEVICE_H #include #include #include "devicepowerinfo.h" extern "C"{ #include "pci/pci.h" } #define PCI_DEVICE_PATH "/sys/bus/pci/devices/" #define PCI_BLOCK_DEVICE_PATH "/sys/block/" class PciDevice : public QObject { Q_OBJECT public: explicit PciDevice(QObject *parent = nullptr); signals: private: QVector m_devicePowerInfo; QString m_controlFile; void getPCIDevicePowerInfo(); void getAtaDevicePowerInfo(const QString &parentDir); void getBlockDevicePowerInfo(); bool deviceHasRuntimePM(const QString &devPath); QString lookupPciDeviceName(const QString &devPath); public: int getPCIDeviceNum(); QString getDeviceName(int deviceIndex); QString getCurrentPowerStat(int deviceIndex); QString getDefaultPowerStat(int deviceIndex); bool setPowerStat(int deviceIndex, const QString &stat); bool setAllDevicePowerStat(const QString &stat); void printAllDeviceInfo(); }; #endif // PCIDEVICE_H ukui-power-manager-4.0.0.1/registeredQDbus/dev-power-control/devicepowerinfo.h0000664000175000017500000000307214601232446026042 0ustar fengfeng/* * Copyright 2023 KylinSoft Co., Ltd. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ #ifndef DEVICEPOWERINFO_H #define DEVICEPOWERINFO_H #include class DevicePowerInfo : public QObject { Q_OBJECT public: explicit DevicePowerInfo(const QString &devType, const QString &devPath, const QString &devName, const QString &controlFile, QObject *parent = nullptr); signals: private: QString m_devType; QString m_devPath; QString m_powerControlFilePath; QString m_devName; QString m_defaultPowerValue; QString m_currentPowerValue; bool ignoreDeviceList(); public: QString getDevicePath(); QString getDeviceName(); QString getCurrentPowerStat(); QString getDefaultPowerStat(); void setDevName(const QString &devName); bool setDevicePowerStat(const QString &stat); }; #endif // DEVICEPOWERINFO_H ukui-power-manager-4.0.0.1/registeredQDbus/dev-power-control/satadevice.h0000664000175000017500000000303514601232446024761 0ustar fengfeng/* * Copyright 2023 KylinSoft Co., Ltd. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ #ifndef SATADEVICE_H #define SATADEVICE_H #include #include #include "devicepowerinfo.h" #define SATA_DEVICE_PATH "/sys/class/scsi_host/" class SataDevice : public QObject { Q_OBJECT public: explicit SataDevice(QObject *parent = nullptr); signals: private: QVector m_devicePowerInfo; QString m_controlFile; void getDevicePowerInfo(); bool checkUsbSupportAutosuspend(const QString &devPath); QString getSataDeviceName(const QString &devPath); public: int getPCIDeviceNum(); QString getDeviceName(int deviceIndex); QString getCurrentPowerStat(int deviceIndex); QString getDefaultPowerStat(int deviceIndex); bool setPowerStat(int deviceIndex, const QString &stat); bool setAllDevicePowerStat(const QString &stat); void printAllDeviceInfo(); }; #endif // SATADEVICE_H ukui-power-manager-4.0.0.1/registeredQDbus/dev-power-control/devpowercontrol.cpp0000664000175000017500000000342314601232446026441 0ustar fengfeng/* * Copyright 2023 KylinSoft Co., Ltd. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ #include "devpowercontrol.h" DevPowerControl::DevPowerControl(QObject *parent) : QObject(parent) { UpmPreprocessor upp; if (upp.pciEnable()) { m_pci = new PciDevice(this); } if (upp.i2cEnable()) { m_i2c = new I2cDevice(this); } if (upp.sataEnable()) { m_sata = new SataDevice(this); } } DevPowerControl::~DevPowerControl() {} void DevPowerControl::setAllDevicePerformance() { setAllDevice("on"); } void DevPowerControl::setAllDeviceBalance() { setAllDevice("default"); } void DevPowerControl::setAllDeviceSave() { setAllDevice("auto"); } void DevPowerControl::setAllDevice(QString mode) { if (m_pci != nullptr) { m_pci->setAllDevicePowerStat(mode); } if (m_i2c != nullptr) { m_i2c->setAllDevicePowerStat(mode); } if (m_sata != nullptr) { if (mode == "on") { m_sata->setAllDevicePowerStat("max_performance"); } else if (mode == "auto") { m_sata->setAllDevicePowerStat("min_power"); } else { m_sata->setAllDevicePowerStat(mode); } } } ukui-power-manager-4.0.0.1/registeredQDbus/dev-power-control/devicepowerinfo.cpp0000664000175000017500000000613714601232446026402 0ustar fengfeng/* * Copyright 2023 KylinSoft Co., Ltd. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ #include #include #include #include #include "devicepowerinfo.h" DevicePowerInfo::DevicePowerInfo(const QString &devType, const QString &devPath, const QString &devName, const QString &controlFile, QObject *parent) : QObject(parent), m_devType(devType), m_devPath(devPath), m_devName(devName) { m_powerControlFilePath = devPath + controlFile; QFile file(m_powerControlFilePath); if (file.open(QIODevice::ReadOnly | QIODevice::Text)) { QTextStream textStream(&file); m_defaultPowerValue = textStream.readLine(); m_currentPowerValue = m_defaultPowerValue; file.close(); } } QString DevicePowerInfo::getDevicePath() { return m_devPath; } QString DevicePowerInfo::getDeviceName() { return m_devName; } QString DevicePowerInfo::getCurrentPowerStat() { return m_currentPowerValue; } QString DevicePowerInfo::getDefaultPowerStat() { return m_defaultPowerValue; } bool DevicePowerInfo::ignoreDeviceList() { if (m_devType == "pci") { if (m_devName.contains("Ethernet", Qt::CaseInsensitive)) { return true; } if (m_devName.contains("usb", Qt::CaseInsensitive)) { return true; } } return false; } bool DevicePowerInfo::setDevicePowerStat(const QString &stat) { bool ret = false; if (true == ignoreDeviceList()) { return false; } QFile controlFile(m_powerControlFilePath); if (!controlFile.open(QIODevice::WriteOnly | QIODevice::Text)) { return false; } QTextStream in(&controlFile); if (stat == "default") { in << m_defaultPowerValue << endl; m_currentPowerValue = m_defaultPowerValue; ret = true; } else { if (m_devType == "sata") { if (stat == "min_power" || stat == "max_performance") { in << stat << endl; m_currentPowerValue = stat; ret = true; } else { ret = false; } } else { if (stat == "auto" || stat == "on") { in << stat << endl; m_currentPowerValue = stat; ret = true; } else { ret = false; } } } controlFile.close(); return ret; } ukui-power-manager-4.0.0.1/registeredQDbus/dev-power-control/i2cdevice.h0000664000175000017500000000301514601232446024504 0ustar fengfeng/* * Copyright 2023 KylinSoft Co., Ltd. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ #ifndef I2CDEVICE_H #define I2CDEVICE_H #include #include #include "devicepowerinfo.h" #define I2C_DEVICE_PATH "/sys/bus/i2c/devices/" class I2cDevice : public QObject { Q_OBJECT public: explicit I2cDevice(QObject *parent = nullptr); signals: private: QVector m_devicePowerInfo; QString m_controlFile; void getDevicePowerInfo(); bool deviceHasRuntimePM(const QString &devPath); QString getI2cDeviceName(const QString &devPath); public: int getPCIDeviceNum(); QString getDeviceName(int deviceIndex); QString getCurrentPowerStat(int deviceIndex); QString getDefaultPowerStat(int deviceIndex); bool setPowerStat(int deviceIndex, const QString &stat); bool setAllDevicePowerStat(const QString &stat); void printAllDeviceInfo(); }; #endif // I2CDEVICE_H ukui-power-manager-4.0.0.1/registeredQDbus/dev-power-control/i2cdevice.cpp0000664000175000017500000001062414601232446025043 0ustar fengfeng/* * Copyright 2023 KylinSoft Co., Ltd. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ #include #include #include #include "i2cdevice.h" I2cDevice::I2cDevice(QObject *parent) : QObject(parent) { m_controlFile = QString("/power/control"); getDevicePowerInfo(); } void I2cDevice::getDevicePowerInfo() { QDir deviceDir(I2C_DEVICE_PATH); if(!deviceDir.exists()) { return; } QStringList deviceDirs = deviceDir.entryList(QDir::Dirs | QDir::NoDotAndDotDot); QString devicePath; for (int i = 0; i < deviceDirs.size(); ++i) { devicePath = I2C_DEVICE_PATH + deviceDirs.at(i); QString devName = getI2cDeviceName(devicePath); QFile pmControlFile(devicePath + "/new_device"); if (pmControlFile.exists()) { devicePath.append("/device"); } if (true == deviceHasRuntimePM(devicePath)) { m_devicePowerInfo.push_back(new DevicePowerInfo("i2c", devicePath, devName, m_controlFile, this)); } } } bool I2cDevice::deviceHasRuntimePM(const QString &devPath) { QFile pmFile(devPath + m_controlFile); if (!pmFile.exists()) { return false; } pmFile.setFileName(devPath + "/power/runtime_suspended_time"); if (!pmFile.open(QIODevice::ReadOnly | QIODevice::Text)) { qCritical() << "open file error:" << pmFile.fileName(); return false; } ulong value = pmFile.readLine().toULong(); pmFile.close(); if (value) { return true; } pmFile.setFileName(devPath + "/power/runtime_active_time"); if (!pmFile.open(QIODevice::ReadOnly | QIODevice::Text)) { qCritical() << "open file error:" << pmFile.fileName(); return false; } value = pmFile.readLine().toULong(); pmFile.close(); if (value) { return true; } return false; } QString I2cDevice::getI2cDeviceName(const QString &devPath) { QString deviceName; QFile file(devPath + "/name"); if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) { qCritical() << "open file error:" << file.fileName(); return "unknown"; } deviceName = file.readLine(); file.close(); return deviceName.remove('\n'); } int I2cDevice::getPCIDeviceNum() { return m_devicePowerInfo.count(); } QString I2cDevice::getDeviceName(int deviceIndex) { if (deviceIndex < m_devicePowerInfo.count()) { return m_devicePowerInfo[deviceIndex]->getDeviceName(); } return "False"; } QString I2cDevice::getCurrentPowerStat(int deviceIndex) { if (deviceIndex < m_devicePowerInfo.count()) { return m_devicePowerInfo[deviceIndex]->getCurrentPowerStat(); } return "False"; } QString I2cDevice::getDefaultPowerStat(int deviceIndex) { if (deviceIndex < m_devicePowerInfo.count()) { return m_devicePowerInfo[deviceIndex]->getDefaultPowerStat(); } return "False"; } bool I2cDevice::setPowerStat(int deviceIndex, const QString &stat) { if (stat == "auto" || stat == "on" || stat == "default") { if (deviceIndex < m_devicePowerInfo.count()) { return m_devicePowerInfo[deviceIndex]->setDevicePowerStat(stat); } } return false; } bool I2cDevice::setAllDevicePowerStat(const QString &stat) { if (stat == "auto" || stat == "on" || stat == "default") { for (int i = 0; i < m_devicePowerInfo.count(); ++i) { m_devicePowerInfo[i]->setDevicePowerStat(stat); } return true; } return false; } void I2cDevice::printAllDeviceInfo() { qDebug() << "i2c device"; for (int i = 0; i < m_devicePowerInfo.count(); ++i) { qDebug() << "name:" << m_devicePowerInfo[i]->getDeviceName() << "path:" << m_devicePowerInfo[i]->getDevicePath() << "stat:" << m_devicePowerInfo[i]->getDefaultPowerStat(); } } ukui-power-manager-4.0.0.1/registeredQDbus/dev-power-control/satadevice.cpp0000664000175000017500000000633214601232446025317 0ustar fengfeng/* * Copyright 2023 KylinSoft Co., Ltd. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ #include #include #include "satadevice.h" SataDevice::SataDevice(QObject *parent) : QObject(parent) { m_controlFile = QString("/link_power_management_policy"); getDevicePowerInfo(); } void SataDevice::getDevicePowerInfo() { QDir deviceDir(SATA_DEVICE_PATH); if(!deviceDir.exists()) { return; } QStringList deviceDirs = deviceDir.entryList(QDir::Dirs | QDir::NoDotAndDotDot); QString devicePath; QFile pmControlFile; for (int i = 0; i < deviceDirs.size(); ++i) { devicePath = SATA_DEVICE_PATH + deviceDirs.at(i); pmControlFile.setFileName(devicePath + m_controlFile); if (!pmControlFile.exists()) { continue; } QString devName = QString("STAT link PM " + deviceDirs.at(i)); m_devicePowerInfo.push_back(new DevicePowerInfo("sata", devicePath, devName, m_controlFile, this)); } } int SataDevice::getPCIDeviceNum() { return m_devicePowerInfo.count(); } QString SataDevice::getDeviceName(int deviceIndex) { if (deviceIndex < m_devicePowerInfo.count()) { return m_devicePowerInfo[deviceIndex]->getDeviceName(); } return "False"; } QString SataDevice::getCurrentPowerStat(int deviceIndex) { if (deviceIndex < m_devicePowerInfo.count()) { return m_devicePowerInfo[deviceIndex]->getCurrentPowerStat(); } return "False"; } QString SataDevice::getDefaultPowerStat(int deviceIndex) { if (deviceIndex < m_devicePowerInfo.count()) { return m_devicePowerInfo[deviceIndex]->getDefaultPowerStat(); } return "False"; } bool SataDevice::setPowerStat(int deviceIndex, const QString &stat) { if (stat == "min_power" || stat == "max_performance" || stat == "default") { if (deviceIndex < m_devicePowerInfo.count()) { return m_devicePowerInfo[deviceIndex]->setDevicePowerStat(stat); } } return false; } bool SataDevice::setAllDevicePowerStat(const QString &stat) { if (stat == "min_power" || stat == "max_performance" || stat == "default") { for (int i = 0; i < m_devicePowerInfo.count(); ++i) { m_devicePowerInfo[i]->setDevicePowerStat(stat); } return true; } return false; } void SataDevice::printAllDeviceInfo() { qDebug() << "stat device"; for (int i = 0; i < m_devicePowerInfo.count(); ++i) { qDebug() << "name:" << m_devicePowerInfo[i]->getDeviceName() << "path:" << m_devicePowerInfo[i]->getDevicePath() << "stat:" << m_devicePowerInfo[i]->getDefaultPowerStat(); } } ukui-power-manager-4.0.0.1/registeredQDbus/dev-power-control/devpowercontrol.h0000664000175000017500000000241714601232446026110 0ustar fengfeng/* * Copyright 2023 KylinSoft Co., Ltd. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ #ifndef DEVPOWERCONTROL_H #define DEVPOWERCONTROL_H #include #include "pcidevice.h" #include "i2cdevice.h" #include "satadevice.h" #include "upmpreprocessor.h" class DevPowerControl : public QObject { Q_OBJECT public: explicit DevPowerControl(QObject *parent = nullptr); ~DevPowerControl(); void setAllDevicePerformance(); void setAllDeviceBalance(); void setAllDeviceSave(); private: void setAllDevice(QString mode); private: PciDevice *m_pci = nullptr; I2cDevice *m_i2c = nullptr; SataDevice *m_sata = nullptr; }; #endif // DEVPOWERCONTROL_H ukui-power-manager-4.0.0.1/registeredQDbus/sysdbusregister.h0000664000175000017500000000610314601232446022523 0ustar fengfeng/* * Copyright 2023 KylinSoft Co., Ltd. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ #ifndef SYSDBUSREGISTER_H #define SYSDBUSREGISTER_H #include #include #include #include #include #include #include #include #include #include #include #include "dev-power-control/devpowercontrol.h" #include "brightness-control/brightnessnode.h" #include "powerconfig.h" class SysdbusRegister : public QObject { Q_OBJECT Q_CLASSINFO("D-Bus Interface", "org.ukui.powermanagement.interface") public: explicit SysdbusRegister(); ~SysdbusRegister(); private: int m_cpuCoreNum; PowerConfig *m_powerConfig; QStringList m_cpuFreqMode = {"performance", "powersave", "powersave"}; BrightnessNode *m_brightnessNode; DevPowerControl *m_devPowerControl; QSettings *m_susThenHibSet; QMap m_userMap; QDBusUnixFileDescriptor m_login1Lock; bool m_blockLidAction = false; void getCpuInfo(); void controlLogin1Connection(QString); void blockLidAction(); void releaseLidAction(); QString canControl(const QString); QString executeLinuxCmd(QString); enum policy { Performance = 0, Balance, EnergySaving, }; public slots: Q_SCRIPTABLE void UserLogin(const QString); Q_SCRIPTABLE void UserLogout(const QString); Q_SCRIPTABLE void UserActive(const QString); Q_SCRIPTABLE bool CanSetBrightness(); Q_SCRIPTABLE void SetBrightnessPercent(const int); Q_SCRIPTABLE int GetBrightnessPercent(); Q_SCRIPTABLE int GetMaxBrightness(); Q_SCRIPTABLE void SetReduceBacklightSwitch(const bool); Q_SCRIPTABLE void SetPcPolicy(const int); Q_SCRIPTABLE void SetCpuPolicy(const int); Q_SCRIPTABLE void SetGpuPolicy(const int); Q_SCRIPTABLE void SetAudioPolicy(const int); Q_SCRIPTABLE void SetAspmPolicy(const int); Q_SCRIPTABLE void LockScreen(); Q_SCRIPTABLE void PowerOff(); Q_SCRIPTABLE void Suspend(); Q_SCRIPTABLE void Hibernate(); Q_SCRIPTABLE void SuspendThenHibernate(); Q_SCRIPTABLE void SetSystemConfig(const QString, const QString, const QString); Q_SCRIPTABLE QString GetSystemConfig(const QString); signals: Q_SCRIPTABLE void SystemConfigChanged(const QString, const QString, const QString); Q_SCRIPTABLE void ActiveUserChanged(const QString); }; #endif // SYSDBUSREGISTER_H ukui-power-manager-4.0.0.1/registeredQDbus/main.cpp0000664000175000017500000000317014601232446020542 0ustar fengfeng/* * Copyright 2023 KylinSoft Co., Ltd. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ #include #include #include #include #include #include "sysdbusregister.h" int main(int argc, char *argv[]) { // initUkuiLog4qt("ukui-powermanagement-service"); QCoreApplication app(argc, argv); app.setOrganizationName("Kylin Team"); app.setApplicationName("ukui-powermanagement-service"); QDBusConnection systemBus = QDBusConnection::systemBus(); if (!systemBus.registerService("org.ukui.powermanagement")) { qCritical() << "QDbus register service failed reason:" << systemBus.lastError(); exit(1); } if (!systemBus.registerObject("/", new SysdbusRegister(), QDBusConnection::ExportAllSlots | QDBusConnection::ExportAllSignals)) { qCritical() << "QDbus register object failed reason:" << systemBus.lastError(); exit(2); } return app.exec(); } ukui-power-manager-4.0.0.1/registeredQDbus/powerconfig.cpp0000664000175000017500000000312214601232446022135 0ustar fengfeng/* * Copyright (C) 2023, KylinSoft Co., Ltd. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . * */ #include "powerconfig.h" #include PowerConfig::PowerConfig(QObject *parent) : QObject(parent) { QFile configFile(POWER_MANAGER_CONF_PATH); if (configFile.exists()) { m_isFirstRun = false; } else { m_isFirstRun = true; } m_qsettings = new QSettings(POWER_MANAGER_CONF_PATH, QSettings::NativeFormat); } PowerConfig::~PowerConfig() {} bool PowerConfig::isFirstRun() { return m_isFirstRun; } void PowerConfig::updatePowerConfig(const QString &key, const QString &value) { m_qsettings->sync(); m_qsettings->beginGroup(CONFIG_GROUP_CONFIG); m_qsettings->setValue(key, value); m_qsettings->endGroup(); m_qsettings->sync(); } QString PowerConfig::getPowerConfig(const QString &key) { m_qsettings->beginGroup(CONFIG_GROUP_CONFIG); QString value = m_qsettings->value(key, "error").toString(); m_qsettings->endGroup(); return value; } ukui-power-manager-4.0.0.1/COPYING0000664000175000017500000001674414601232446015064 0ustar fengfeng GNU LESSER GENERAL PUBLIC LICENSE Version 3, 29 June 2007 Copyright (C) 2007 Free Software Foundation, Inc. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. This version of the GNU Lesser General Public License incorporates the terms and conditions of version 3 of the GNU General Public License, supplemented by the additional permissions listed below. 0. Additional Definitions. As used herein, "this License" refers to version 3 of the GNU Lesser General Public License, and the "GNU GPL" refers to version 3 of the GNU General Public License. "The Library" refers to a covered work governed by this License, other than an Application or a Combined Work as defined below. An "Application" is any work that makes use of an interface provided by the Library, but which is not otherwise based on the Library. Defining a subclass of a class defined by the Library is deemed a mode of using an interface provided by the Library. A "Combined Work" is a work produced by combining or linking an Application with the Library. The particular version of the Library with which the Combined Work was made is also called the "Linked Version". The "Minimal Corresponding Source" for a Combined Work means the Corresponding Source for the Combined Work, excluding any source code for portions of the Combined Work that, considered in isolation, are based on the Application, and not on the Linked Version. The "Corresponding Application Code" for a Combined Work means the object code and/or source code for the Application, including any data and utility programs needed for reproducing the Combined Work from the Application, but excluding the System Libraries of the Combined Work. 1. Exception to Section 3 of the GNU GPL. You may convey a covered work under sections 3 and 4 of this License without being bound by section 3 of the GNU GPL. 2. Conveying Modified Versions. If you modify a copy of the Library, and, in your modifications, a facility refers to a function or data to be supplied by an Application that uses the facility (other than as an argument passed when the facility is invoked), then you may convey a copy of the modified version: a) under this License, provided that you make a good faith effort to ensure that, in the event an Application does not supply the function or data, the facility still operates, and performs whatever part of its purpose remains meaningful, or b) under the GNU GPL, with none of the additional permissions of this License applicable to that copy. 3. Object Code Incorporating Material from Library Header Files. The object code form of an Application may incorporate material from a header file that is part of the Library. You may convey such object code under terms of your choice, provided that, if the incorporated material is not limited to numerical parameters, data structure layouts and accessors, or small macros, inline functions and templates (ten or fewer lines in length), you do both of the following: a) Give prominent notice with each copy of the object code that the Library is used in it and that the Library and its use are covered by this License. b) Accompany the object code with a copy of the GNU GPL and this license document. 4. Combined Works. You may convey a Combined Work under terms of your choice that, taken together, effectively do not restrict modification of the portions of the Library contained in the Combined Work and reverse engineering for debugging such modifications, if you also do each of the following: a) Give prominent notice with each copy of the Combined Work that the Library is used in it and that the Library and its use are covered by this License. b) Accompany the Combined Work with a copy of the GNU GPL and this license document. c) For a Combined Work that displays copyright notices during execution, include the copyright notice for the Library among these notices, as well as a reference directing the user to the copies of the GNU GPL and this license document. d) Do one of the following: 0) Convey the Minimal Corresponding Source under the terms of this License, and the Corresponding Application Code in a form suitable for, and under terms that permit, the user to recombine or relink the Application with a modified version of the Linked Version to produce a modified Combined Work, in the manner specified by section 6 of the GNU GPL for conveying Corresponding Source. 1) Use a suitable shared library mechanism for linking with the Library. A suitable mechanism is one that (a) uses at run time a copy of the Library already present on the user's computer system, and (b) will operate properly with a modified version of the Library that is interface-compatible with the Linked Version. e) Provide Installation Information, but only if you would otherwise be required to provide such information under section 6 of the GNU GPL, and only to the extent that such information is necessary to install and execute a modified version of the Combined Work produced by recombining or relinking the Application with a modified version of the Linked Version. (If you use option 4d0, the Installation Information must accompany the Minimal Corresponding Source and Corresponding Application Code. If you use option 4d1, you must provide the Installation Information in the manner specified by section 6 of the GNU GPL for conveying Corresponding Source.) 5. Combined Libraries. You may place library facilities that are a work based on the Library side by side in a single library together with other library facilities that are not Applications and are not covered by this License, and convey such a combined library under terms of your choice, if you do both of the following: a) Accompany the combined library with a copy of the same work based on the Library, uncombined with any other library facilities, conveyed under the terms of this License. b) Give prominent notice with the combined library that part of it is a work based on the Library, and explaining where to find the accompanying uncombined form of the same work. 6. Revised Versions of the GNU Lesser General Public License. The Free Software Foundation may publish revised and/or new versions of the GNU Lesser General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Library as you received it specifies that a certain numbered version of the GNU Lesser General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that published version or of any later version published by the Free Software Foundation. If the Library as you received it does not specify a version number of the GNU Lesser General Public License, you may choose any version of the GNU Lesser General Public License ever published by the Free Software Foundation. If the Library as you received it specifies that a proxy can decide whether future versions of the GNU Lesser General Public License shall apply, that proxy's public statement of acceptance of any version is permanent authorization for you to choose that version for the Library. ukui-power-manager-4.0.0.1/data/0000775000175000017500000000000014601232446014726 5ustar fengfengukui-power-manager-4.0.0.1/data/ukui-power-manager0000664000175000017500000000016514601232446020372 0ustar fengfeng/tmp/ukui-power-manager.log { daily rotate 7 compress notifempty maxsize 10M copytruncate } ukui-power-manager-4.0.0.1/data/gpm-prefs.ui0000664000175000017500000016745714601232446017211 0ustar fengfeng 1 1 61 1 5 23 1 61 1 5 41 100 1 5 1 1 61 1 5 23 1 61 1 5 1 1 61 1 5 23 1 61 1 5 5 Power Management Preferences False center-on-parent dialog True vertical 2 True True 6 True 12 vertical 12 True vertical 6 True 0 <b>Actions</b> True False False 0 True 12 True vertical 6 True 12 True True 0 Put computer to _sleep when inactive for: True False 0 True 1 False False 0 True 12 True True 0 When laptop lid is cl_osed: True False 0 True 1 1 False 1 False 0 True vertical 6 True 0 <b>Display</b> True False False 0 True 12 True vertical 5 True 12 True True 0 Put _display to sleep when inactive for: True False 0 True 1 0 True 12 True True 0 Set display _brightness to: True hscale_ac_brightness False 0 True True adjustment3 0 bottom 1 1 Di_m display when idle True True False True True False False 2 1 False 1 True On AC Power False True 12 vertical 12 True vertical 6 True 0 <b>Actions</b> True False False 0 True 12 True vertical 6 True 12 True True 0 Put computer to _sleep when inactive for: True False 0 True 1 False False 0 True 12 True True 0 When laptop lid is cl_osed: True False 0 True 1 1 True 12 True True 0 When battery po_wer is critically low: True False 0 True 1 2 False 1 False 0 True vertical 6 True 0 <b>Display</b> True False False 0 True 12 True vertical 5 True 12 True True 0 Put _display to sleep when inactive for: True False 0 True 1 0 _Reduce backlight brightness True True False True True False False 1 Di_m display when idle True True False True True False False 2 1 False 1 1 True On Battery Power 1 False True 12 vertical 12 True vertical 6 True 0 <b>Actions</b> True False False 0 True 12 True vertical 6 True 12 True True 0 Put computer to _sleep when inactive for: True False 0 True 1 False False 0 True 12 True True 0 When UPS power is l_ow: True False 0 True 1 1 True 12 True True 0 When UPS power is _critically low: True False 0 True 1 2 False 1 False 0 True vertical 6 True 0 <b>Display</b> True False False 0 True 12 True vertical 5 True 12 True True 0 Put _display to sleep when inactive for: True False 0 True 1 0 1 False 1 2 True On UPS Power 2 False True 12 vertical 12 True vertical 6 True 0 <b>Actions</b> True False False 0 True 12 True vertical 6 True 12 True True 0 When the power _button is pressed: True False 0 True 1 False False 0 True 12 True True 0 When the _suspend button is pressed: True False 0 True 1 1 False 1 False 0 True vertical 6 True 0 <b>Notification Area</b> True False False 0 True 12 True vertical 6 _Never display an icon True True False True True False False 0 _Only display an icon when battery power is low True True False True True radiobutton_notification_never False False 1 Only display an icon when charging or _discharging True True False True True radiobutton_notification_never False False 2 Only display an icon when a battery is p_resent True True False True True radiobutton_notification_never False False 3 _Always display an icon True True False True True radiobutton_notification_never False False 4 1 False 1 3 True General 3 False False 1 True end gtk-help True True True False Provides help about this program True False False 0 True Make Default True True True Sets this policy to be used by all users False False 1 gtk-close True True True True False Closes the program True False False 2 False end 0 button_help button_defaults button_close ukui-power-manager-4.0.0.1/data/ukui-power-preferences.10000664000175000017500000000106114601232446021414 0ustar fengfeng.TH "UKUI-POWER-PREFERENCES" "1" "11 July, 2005" "" "" .SH NAME ukui-power-preferences \- UKUI power preferences GUI .SH SYNOPSIS \fBukui-power-preferences\fR [ \fB\-\-verbose\fR ] [ \fB\-\-help\fR ] .SH "DESCRIPTION" \fBukui-power-preferences\fR is the gui program for the ukui power management infrastructure .SH "OPTIONS" .TP \fB\-\-help\fR Show summary of options. .TP \fB\-\-verbose\fR Show extra debugging. .SH "SEE ALSO" .PP ukui-power-manager (1). .SH "AUTHOR" .PP This manual page was written by Oliver Grawert for the Debian system. ukui-power-manager-4.0.0.1/data/ukui-power-manager-tray.10000664000175000017500000000146314601232446021510 0ustar fengfeng.TH "UKUI-POWER-MANAGER-TRAY" "1" "29 March,2006" "" "" .SH NAME ukui-power-manager-tray \- UKUI power manager system tray .SH SYNOPSIS \fBukui-power-manager-tray\fR [ \fB\-\-verbose\fR ] [ \fB\-\-debug\fR ] [ \fB\-\-help\fR ] .SH "DESCRIPTION" \fBukui-power-manager-tray\fR is the panel applet of the UKUI power management. .PP It supports features such as suspending, hibernating, screen blanking, cpu frequency switching and more. .SH "OPTIONS" .TP \fB\-\-help\fR Show summary of options. .TP \fB\-\-verbose\fR Show extra debugging. .TP \fB\-\-debug\fR Only show specific debugging options. Useful for developers only. .SH "SEE ALSO" .PP ukui-power-preferences (1). .SH "AUTHOR" .PP This manual page was written by Oliver Grawert for the Debian system and updated by Ow Mun Heng ukui-power-manager-4.0.0.1/data/Makefile.am0000664000175000017500000000323414601232446016764 0ustar fengfeng#SUBDIRS = icons @INTLTOOL_DESKTOP_RULE@ desktopdir = $(datadir)/applications desktop_in_files = ukui-power-preferences.desktop.in \ ukui-power-statistics.desktop.in desktop_DATA = $(desktop_in_files:.desktop.in=.desktop) @INTLTOOL_DESKTOP_RULE@ autostartdir = $(sysconfdir)/xdg/autostart autostart_in_files = ukui-power-manager.desktop.in \ ukui-power-manager-tray.desktop.in autostart_DATA = $(autostart_in_files:.desktop.in=.desktop) servicedir = $(DBUS_SERVICES_DIR) service_in_files = org.ukui.PowerManager.service.in service_DATA = $(service_in_files:.service.in=.service) $(service_DATA): $(service_in_files) Makefile @sed -e "s|\@servicedir\@|$(bindir)|" $< > $@ @GSETTINGS_RULES@ @INTLTOOL_XML_NOMERGE_RULE@ gsettings_schemas_in_files = org.ukui.power-manager.gschema.xml.in gsettings_SCHEMAS = $(gsettings_schemas_in_files:.xml.in=.xml) #kobe #confdir = $(sysconfdir)/polkit-1/localauthority/50-local.d #conf_DATA = com.ubuntu.enable-hibernate.pkla pkgdata_DATA = \ gpm-statistics.ui \ gpm-feedback-widget.ui \ gpm-prefs.ui \ acme.ui man_MANS = \ ukui-power-manager.1 \ ukui-power-manager-tray.1 \ ukui-power-backlight-helper.1 \ ukui-power-statistics.1 \ ukui-power-preferences.1 EXTRA_DIST = \ $(service_in_files) \ $(autostart_in_files) \ $(desktop_in_files) \ $(gsettings_schemas_in_files) \ $(pkgdata_DATA) \ $(man_MANS) # $(conf_DATA) clean-local : rm -f *~ DISTCLEANFILES = \ ukui-power-manager.desktop \ ukui-power-manager-tray.desktop \ ukui-power-preferences.desktop \ ukui-power-statistics.desktop \ org.ukui.PowerManager.service \ $(gsettings_SCHEMAS) ukui-power-manager-4.0.0.1/data/ukui-power-manager-tray.desktop.in.in0000664000175000017500000000064314601232446024032 0ustar fengfeng[Desktop Entry] _Name=Power Manager Tray Name[zh_CN]=电源管理程序 _Comment=Power management tray Icon=ukui-power-manager Exec=ukui-power-manager-tray Terminal=false Type=Application NoDisplay=true Categories= OnlyShowIn=UKUI; X-UKUI-Bugzilla-Bugzilla=UKUI X-UKUI-Bugzilla-Product=ukui-power-manager-tray X-UKUI-Bugzilla-Component=ukui-power-manager-tray X-UKUI-Bugzilla-Version=@VERSION@ X-UKUI-AutoRestart=true ukui-power-manager-4.0.0.1/data/ukui.power.policy.conf0000775000175000017500000000114314601232446021205 0ustar fengfeng ukui-power-manager-4.0.0.1/data/gpm-statistics.ui0000664000175000017500000007532314601232446020252 0ustar fengfeng False 6 Power Statistics center-on-parent dialog True False vertical 2 True False end gtk-help True True True False False True False False 0 True gtk-close True True True False False True False False 1 True False 6 6 True True never automatic in True True False False True 0 True True True True 9 automatic automatic in True True True False Details False True False 9 9 True False 12 True False 6 True False Graph type: False 0 True False 0 True True 1 True True 0 True False 6 True False Data length: False True 0 True False 0 True True 1 True True 1 False True 0 True False True False 6 True False y-axis 90 False True 0 True False There is no data to display. True True 1 True True 0 True False x-axis False True 1 True True 1 True False 6 True Use smoothed line True True False False True False True 0 Show data points True True False False True False True 1 False True 2 1 True False History 1 False True False 9 9 True False 6 True False Graph type: False True 0 True False 0 True True 1 False True 0 True False True False 6 True False y-axis 90 False True 0 True False There is no data to display. True True 1 True True 0 True False x-axis False True 1 True True 3 1 True False 6 True Use smoothed line True True False False True False True 0 Show data points True True False False True False True 1 False True 2 2 True False Statistics 2 False True False 9 9 True False 3 True False Processor wakeups per second: False True 0 True False 0 False True 1 False True 0 True True automatic automatic in True True True True 1 3 True False Wakeups 3 False True True 1 True True 1 button_help button_close ukui-power-manager-4.0.0.1/data/gpm-feedback-widget.ui0000664000175000017500000000315414601232446021056 0ustar fengfeng Brightness notification True 0 out True 12 6 True 6 0 True 0.10000000149 False False 1 ukui-power-manager-4.0.0.1/data/ukui-power-manager.desktop.in.in0000664000175000017500000000054014601232446023051 0ustar fengfeng[Desktop Entry] _Name=Power Manager _Comment=Power management daemon Icon=ukui-power-manager Exec= Terminal=false Type=Application NoDisplay=true Categories= OnlyShowIn=UKUI; X-UKUI-Bugzilla-Bugzilla=UKUI X-UKUI-Bugzilla-Product=ukui-power-manager X-UKUI-Bugzilla-Component=ukui-power-manager X-UKUI-Bugzilla-Version=@VERSION@ X-UKUI-AutoRestart=true ukui-power-manager-4.0.0.1/data/ukui-power-statistics.10000664000175000017500000000120314601232446021303 0ustar fengfeng.TH "UKUI-POWER-STATISTICS" "1" "11 December, 2007" "" "" .SH NAME ukui-power-statistics \- UKUI power statistics GUI .SH SYNOPSIS \fBukui-power-statistics\fR [ \fB\-\-verbose\fR ] [ \fB\-\-help\fR ] .SH "DESCRIPTION" \fBukui-power-statistics\fR is the gui program for the ukui power management infrastructure. .PP It allows users to visualize the power consumption of laptop hardware. .SH "OPTIONS" .TP \fB\-\-help\fR Show summary of options. .TP \fB\-\-verbose\fR Show extra debugging. .SH "SEE ALSO" .PP ukui-power-manager (1), ukui-power-preferences (1). .SH "AUTHOR" .PP This manual page was written by Simon Zheng . ukui-power-manager-4.0.0.1/data/org.ukui.power-manager.gschema.xml.in0000664000175000017500000005000014601232446023764 0ustar fengfeng 'suspend' Whether to hibernate, suspend or do nothing when inactive The type of sleeping that should be performed when the computer is inactive. 'suspend' Battery critical low action The action to take when the battery is critically low. true If the battery event should occur when the lid is shut and the power disconnected If the battery lid close event should occur (for example 'Suspend when lid closed on battery') when the lid is previously shut and the AC power disconnected at a later time. 'suspend' Whether to hibernate, suspend or do nothing when inactive The type of sleeping that should be performed when the computer is inactive. 'shutdown' UPS critical low action The action to take when the UPS is critically low. 'hibernate' UPS low power action The action to take when the UPS is low. true Allow backlight brightness adjustment If the screen brightness should be changed when switching between AC and battery power. true Reduce the backlight brightness when on battery power If the screen should be reduced in brightness when the computer is on battery power. true Reduce the keyboard backlight when on battery power If the keyboard backlight brightness should be reduced when the computer is on battery power 100 Keyboard backlight brightness when on AC power. Percent brightness to set keyboard backlight at when on AC power. Legal values are between 0 and 100. 50 Percent to reduce keyboard backlight by when on battery power. The percentage to reduce the keyboard backlight by when on battery power. For example, if set to '60', the backlight will be cut by 40% on battery power. Legal values are between 0 and 100. 75 Percent to reduce keyboard backlight by when idle. The percentage to reduce the keyboard backlight by when idle. For example, if set to '60', the backlight will be cut by 40% when idle. Legal values are between 0 and 100. 100 The brightness of the screen when idle This is the laptop panel screen brightness used when the session is idle. Only valid when use-time-for-policy is true. true Dim the screen after a period of inactivity when on battery power If the screen should be dimmed to save power when the computer is idle when on battery power. 60 The default amount of time to dim the screen after idle The default amount of time to dim the screen after idle. 50 LCD dimming amount when on battery The amount to dim the brightness of the display when on battery power. Possible values are between 0 and 100. false Dim the screen after a period of inactivity when on AC power If the screen should be dimmed to save power when the computer is idle when on AC power. 'off' Method used to blank screen on AC The DPMS method used to blank the screen when on AC power. 'off' Method used to blank screen on battery The DPMS method used to blank the screen when on battery power. 100.0 LCD brightness when on AC The brightness of the display when on AC power. Possible values are between 0.0 and 100.0. 100.0 LCD brightness when on BAT The brightness of the display when on BAT power. Possible values are between 0.0 and 100.0. 'suspend' Suspend button action The action to take when the system suspend button is pressed. 'hibernate' Hibernate button action The action to take when the system hibernate button is pressed. 'interactive' Power button action The action to take when the system power button is pressed. 'suspend' Laptop lid close action on battery The action to take when the laptop lid is closed and the laptop is on battery power. 'suspend' Laptop lid close action when on AC The action to take when the laptop lid is closed and the laptop is on AC power. true Whether to use time-based notifications If time based notifications should be used. If set to false, then the percentage change is used instead, which may fix a broken ACPI BIOS. false Check CPU load before sleeping If the CPU load should be checked before doing the idle action. false Whether NetworkManager should be connected and disconnected on sleep. Whether NetworkManager should disconnect before suspending or hibernating and connect on resume. true Use ukui-screensaver lock setting Whether to use the screen lock setting of ukui-screensaver to decide if the screen is locked after a hibernate, suspend or blank screen. true Lock screen when blanked Whether the screen is locked when the screen is turned off. Only used if lock-use-screensaver is false. true Lock screen on suspend Whether the screen is locked when the computer wakes up from a suspend. Only used if lock-use-screensaver is false. true Lock screen on hibernate Whether the screen is locked when the computer wakes up from a hibernate. Only used if lock-use-screensaver is false. false Lock GNOME keyring on sleep Whether the GNOME keyring is locked before the computer enters suspend. This means the keyring will have to be unlocked on resume. true Lock GNOME keyring on sleep Whether the GNOME keyring is locked before the computer enters hibernate. This means the keyring will have to be unlocked on resume. true If we should show the low capacity warning for a broken battery If we should show the low capacity warning for a broken battery. true Notify when AC adapter is disconnected If the user should be notified when the AC adapter is disconnected. false Notify when fully charged If a notification message should be displayed when the battery is fully charged. true Notify on a sleep failure If a notification message should be displayed after suspend or hibernate failed. '' The URI to show to the user on sleep failure When sleep fails we can show the user a button to help fix the situation. Leave this blank if the button should not be shown. true Notify on a low power If a notification message should be displayed when the battery is getting low. true Whether we should show the history data points Whether we should show the history data points in the statistics window. true Whether we should smooth the history data Whether we should smooth the history data in the graph. 'power' The default graph type to show for history The default graph type to show in the history window. 21600 The maximum time displayed for history The maximum duration of time displayed on the x-axis of the history graph. true Whether we should show the stats data points Whether we should show the stats data points in the statistics window. true Whether we should smooth the stats data Whether we should smooth the stats data in the graph. 'power' The default graph type to show for stats The default graph type to show in the stats window. 0 The index of the page number to show by default The index of the page number to show by default which is used to return focus to the correct page. '' The ID of the last device selected The identifier of the last device which is used to return focus to the correct device. 20 Percentage considered low The percentage of the battery when it is considered low. Only valid when use-time-for-policy is false. 10 Percentage considered critical The percentage of the battery when it is considered critical. Only valid when use-time-for-policy is false. 5 Percentage action is taken The percentage of the battery when the critical action is performed. Only valid when use-time-for-policy is false. 1200 The time remaining when low The time remaining in seconds of the battery when it is considered low. Only valid when use-time-for-policy is true. 300 The time remaining when critical The time remaining in seconds of the battery when it is considered critical. Only valid when use-time-for-policy is true. 120 The time remaining when action is taken The time remaining in seconds of the battery when critical action is taken. Only valid when use-time-for-policy is true. 900 Sleep timeout computer when on battery The amount of time in seconds the computer on battery power needs to be inactive before it goes to sleep. 900 Sleep timeout computer when on AC The amount of time in seconds the computer on AC power needs to be inactive before it goes to sleep. 0 Sleep timeout computer when on UPS The amount of time in seconds the computer on UPS power needs to be inactive before it goes to sleep. 600 Sleep timeout display when on AC The amount of time in seconds before the display goes to sleep when the computer is on AC power. 600 Sleep timeout display when on battery The amount of time in seconds the computer on battery power needs to be inactive before the display goes to sleep. 600 Sleep timeout display when on UPS The amount of time in seconds the computer on UPS power needs to be inactive before the display goes to sleep. true If sounds should be used If sounds should be used when the power is critically low, or inhibit requests have stopped the policy action. true If preferences and statistics items should be shown in the context menu false If power policy mode should be auto switched when plugged in and out false If power policy mode should be auto switched when plugged in and out 2 power policy mode 1 power policy current 2 power policy current 1 power policy current 1 power policy current 1 power policy current 1 power policy current 'present' When to show the notification icon Display options for the notification icon. ukui-power-manager-4.0.0.1/data/ukui-power-backlight-helper.10000664000175000017500000000201014601232446022313 0ustar fengfeng.TH "UKUI-POWER-BACKLIGHT-HELPER" "1" "21 April, 2014" "" "" .SH NAME ukui-power-backlight-helper \- helper application for UKUI's power management backlight control .SH SYNOPSIS \fBukui-power-backlight-helper\fR [ \fB\-\-help\fR ] [ \fB\-\-set-brightness\fR ] [ \fB\-\-get-brightness\fR ] [ \fB\-\-get-max-brightness\fR ] .SH "DESCRIPTION" \fBukui-power-backlight-helper\fR is a helper utility for controlling the backlight of TFT displays via the UKUI power manager userspace daemon. .PP The \fBukui-power-backlight-helper\fR requires to be run with root privileges. .SH "OPTIONS" .TP \fB\-\-help\fR Show summary of options. .TP \fB\-\-set-brightness BRIGHTNESS_LEVEL\fR Set the given brightness. .TP \fB\-\-get-brightness\fR Get the current brightness. .TP \fB\-\-get-max-brightness\fR Get the number of brightness levels supported. .SH "SEE ALSO" .PP ukui-power-manager (1). .SH "AUTHOR" .PP This manual page has been written by Mike Gabriel for the Debian system (but may be used by others). ukui-power-manager-4.0.0.1/data/99-upower-wake-up-usb-device.rules0000664000175000017500000000022514601232446023154 0ustar fengfengSUBSYSTEMS=="usb", ATTRS{product}=="*Mouse",ATTR{power/wakeup}="enabled" SUBSYSTEMS=="usb", ATTRS{product}=="*Keyboard",ATTR{power/wakeup}="enabled" ukui-power-manager-4.0.0.1/data/ukui-power-preferences.desktop.in.in0000664000175000017500000000067214601232446023746 0ustar fengfeng[Desktop Entry] _Name=Power Management _Comment=Configure power management Icon=ukui-power-manager Exec=ukui-power-preferences Terminal=false Type=Application Categories=Settings;HardwareSettings; Keywords=UKUI;power;management;preferences;settings; OnlyShowIn=UKUI; StartupNotify=true X-UKUI-Bugzilla-Bugzilla=UKUI X-UKUI-Bugzilla-Product=ukui-power-manager X-UKUI-Bugzilla-Component=ukui-power-preferences X-UKUI-Bugzilla-Version=@VERSION@ ukui-power-manager-4.0.0.1/data/ukui-power-policy.service0000664000175000017500000000032714601232446021716 0ustar fengfeng[Unit] Description=UKUI Power Policy daemon After=upower.service [Service] Type=dbus Restart=always RestartSec=0 BusName=ukui.power.policy ExecStart=/usr/bin/ukui-power-policy [Install] WantedBy=multi-user.target ukui-power-manager-4.0.0.1/data/org.ukui.PowerManager.service.in0000664000175000017500000000012014601232446023037 0ustar fengfeng[D-BUS Service] Name=org.ukui.PowerManager Exec=@servicedir@/ukui-power-manager ukui-power-manager-4.0.0.1/data/acme.ui0000664000175000017500000000213614601232446016174 0ustar fengfeng True 6 True audio-volume-high 6 0 True False False 1 ukui-power-manager-4.0.0.1/data/power-ignore.conf0000664000175000017500000000003614601232446020211 0ustar fengfeng[Login] HandlePowerKey=ignore ukui-power-manager-4.0.0.1/data/ukui-power-manager.10000664000175000017500000000207414601232446020532 0ustar fengfeng.TH "UKUI-POWER-MANAGER" "1" "29 March,2006" "" "" .SH NAME ukui-power-manager \- UKUI power manager userspace daemon .SH SYNOPSIS \fBukui-power-manager\fR [ \fB\-\-verbose\fR ] [ \fB\-\-debug\fR ] [ \fB\-\-help\fR ] .SH "DESCRIPTION" \fBukui-power-manager\fR is the backend program of the UKUI power management infrastructure providing a complete and integrated solution to power management under the UKUI desktop environment. .PP It supports features such as suspending, hibernating, screen blanking, cpu frequency switching and more in one small neat package. .SH "OPTIONS" .TP \fB\-\-help\fR Show summary of options. .TP \fB\-\-verbose\fR Show extra debugging. .TP \fB\-\-no-daemon\fR Do not detach \fBukui-power-manager\fR into the background so that error messages will be displayed on console. .TP \fB\-\-debug\fR Only show specific debugging options. Useful for developers only. .SH "SEE ALSO" .PP ukui-power-preferences (1). .SH "AUTHOR" .PP This manual page was written by Oliver Grawert for the Debian system and updated by Ow Mun Heng ukui-power-manager-4.0.0.1/data/ukui-power-statistics.desktop.in.in0000664000175000017500000000066114601232446023635 0ustar fengfeng[Desktop Entry] _Name=Power Statistics _Comment=Observe power management Icon=ukui-power-statistics Exec=ukui-power-statistics Terminal=false Type=Application Categories=GTK;System;Monitor; OnlyShowIn=UKUI; NoDisplay=false StartupNotify=true X-UKUI-Bugzilla-Bugzilla=UKUI X-UKUI-Bugzilla-Product=ukui-power-manager X-UKUI-Bugzilla-Component=ukui-power-statistics X-UKUI-Bugzilla-Version=@VERSION@ X-Desktop-File-Install-Version=0.10 ukui-power-manager-4.0.0.1/.github/0000755000175000017500000000000014554615633015365 5ustar fengfengukui-power-manager-4.0.0.1/.github/workflows/0000755000175000017500000000000014554615633017422 5ustar fengfengukui-power-manager-4.0.0.1/.github/workflows/build.yml0000644000175000017500000000660614554615633021254 0ustar fengfengname: Check build on: push: branches: - master pull_request: branches: - master schedule: - cron: '0 0 * * *' jobs: archlinux: name: on Archlinux runs-on: ubuntu-20.04 container: docker.io/library/archlinux:latest steps: - name: Checkout ukui-power-manager source code uses: actions/checkout@v2 - name: Refresh pacman repository run: pacman -Sy - name: Install build dependencies run: pacman -S --noconfirm base-devel qt5-tools dbus-glib gtk3 libgnome-keyring libnotify upower intltool mate-common yelp-tools libxrandr libx11 libxext xorgproto glib2 - name: Configure & Make run: | ./autogen.sh; make -j$(nproc); debian: name: on Debian Sid runs-on: ubuntu-20.04 container: docker.io/library/debian:sid env: DEBIAN_FRONTEND: noninteractive steps: - name: Checkout ukui-power-manager source code uses: actions/checkout@v2 - name: Update apt repository run: apt-get update -y - name: Install build dependcies run: apt-get install -y build-essential qt5-default qttools5-dev-tools debhelper-compat qtbase5-dev intltool libcanberra-gtk3-dev libdbus-glib-1-dev libgcrypt20-dev libglib2.0-dev libgtk-3-dev libnotify-dev libtool-bin libupower-glib-dev libwnck-3-dev libx11-dev libxext-dev libxml-parser-perl libxrandr-dev mate-common pkg-config xmlto yelp-tools libqt5charts5-dev libqt5x11extras5-dev libgsettings-qt-dev - name: Configure & Make run: | ./autogen.sh --without-keyring; make -j$(nproc); fedora: name: on Fedora 32 runs-on: ubuntu-20.04 container: docker.io/library/fedora:32 steps: - name: Checkout ukui-power-manager source code uses: actions/checkout@v2 - name: Install build dependencies run: dnf install -y which gcc gcc-c++ make cmake cmake-rpm-macros autoconf automake intltool rpm-build qt5-rpm-macros gtk3-devel libwnck3-devel qt5-qtbase-devel intltool libcanberra-devel libcanberra-gtk3 glib2-devel dbus-glib-devel libnotify-devel libtool libgcrypt-devel upower-devel libX11-devel libXext-devel libXrandr-devel perl-XML-Parser qt5-qtx11extras-devel gsettings-qt-devel mate-common mate-desktop-devel qt5-qtcharts-devel xmlto yelp-tools libgnome-keyring-devel - name: Configure & Make run: | ln -sf /usr/bin/lrelease-qt5 /usr/bin/lrelease; ln -sf /usr/bin/qmake-qt5 /usr/bin/qmake; ./autogen.sh; make -j$(nproc); ubuntu: name: on Ubuntu 20.04 runs-on: ubuntu-20.04 container: docker.io/library/ubuntu:focal env: DEBIAN_FRONTEND: noninteractive steps: - name: Checkout ukui-power-manager source code uses: actions/checkout@v2 - name: Update apt repository run: apt-get update -y - name: Install build dependcies run: apt-get install -y build-essential qt5-default qttools5-dev-tools debhelper-compat qtbase5-dev intltool libcanberra-gtk3-dev libdbus-glib-1-dev libgcrypt20-dev libglib2.0-dev libgtk-3-dev libnotify-dev libtool-bin libupower-glib-dev libwnck-3-dev libx11-dev libxext-dev libxml-parser-perl libxrandr-dev mate-common pkg-config xmlto yelp-tools libqt5charts5-dev libqt5x11extras5-dev libgsettings-qt-dev - name: Configure & Make run: | ./autogen.sh --without-keyring; make -j$(nproc); ukui-power-manager-4.0.0.1/common/0000775000175000017500000000000014601232446015305 5ustar fengfengukui-power-manager-4.0.0.1/common/upmpreprocessor.h0000664000175000017500000000267014601232446020733 0ustar fengfeng/* * Copyright 2023 KylinSoft Co., Ltd. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ #ifndef UPMPREPROCESSOR_H #define UPMPREPROCESSOR_H #include #include #include #include #include #include #include class UpmPreprocessor : public QObject { Q_OBJECT public: UpmPreprocessor(QObject *parent = nullptr); ~UpmPreprocessor(); void start(); bool i2cEnable(); bool pciEnable(); bool sataEnable(); QString getBrightnessNode(); private: void preprocessPowerMode(); void readModalias(); void readCpuType(); bool checkConf(QString file, QString group, QString key); QVariant readConfig(QString file, QString group, QString key); private: QString m_modalias = ""; QString m_cpuType = ""; }; #endif // UPMPREPROCESSOR_H ukui-power-manager-4.0.0.1/common/upmpreprocessor.cpp0000664000175000017500000001104314601232446021260 0ustar fengfeng/* * Copyright 2023 KylinSoft Co., Ltd. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ #include "upmpreprocessor.h" /** 没有配置文件,即为新用户,按照主板配置列表进行恢复。 */ #include "global-define.h" UpmPreprocessor::UpmPreprocessor(QObject *parent) { readModalias(); readCpuType(); } UpmPreprocessor::~UpmPreprocessor() { } void UpmPreprocessor::start() { preprocessPowerMode(); } bool UpmPreprocessor::i2cEnable() { static int ret = -1; if (ret > -1) { return ret; } ret = checkConf(UPM_GLOBAL_CONFIG, UPM_POWER_IIC_SCHEMA, UPM_POWER_MODE_BALANCE_KEY); return ret; } bool UpmPreprocessor::pciEnable() { static int ret = -1; if (ret > -1) { return ret; } ret = checkConf(UPM_GLOBAL_CONFIG, UPM_POWER_PCI_SCHEMA, UPM_POWER_MODE_BALANCE_KEY); return ret; } bool UpmPreprocessor::sataEnable() { static int ret = -1; if (ret > -1) { return ret; } ret = checkConf(UPM_GLOBAL_CONFIG, UPM_POWER_SATA_SCHEMA, UPM_POWER_MODE_BALANCE_KEY); return ret; } void UpmPreprocessor::preprocessPowerMode() { QGSettings settings(POWER_MANAGER_SETTINGS); if (settings.get(PRE_POWER_MODE).toBool()) { return; } QString filePath = QStandardPaths::locate(QStandardPaths::ConfigLocation, QStringLiteral("ukui-power-manager.conf")); settings.set(PRE_POWER_MODE, true); QFileInfo fileInfo(filePath); if (fileInfo.isFile()) { return; } QStringList boards = readConfig(UPM_GLOBAL_CONFIG, UPM_POWER_MODE_BALANCE_SCHEMA, UPM_POWER_MODE_BALANCE_KEY).toString().split(","); Q_FOREACH (const QString &str, boards) { if (m_modalias.contains(str) && !str.isEmpty()) { settings.set(POWER_POLICY_AC, Upm::powerMode::Balance); settings.set(POWER_POLICY_BATTERY, Upm::powerMode::Balance); break; } } } bool UpmPreprocessor::checkConf(QString file, QString group, QString key) { QStringList boards = readConfig(file, group, key).toString().split(","); Q_FOREACH (const QString &str, boards) { if (m_modalias.contains(str) && !str.isEmpty()) { return true; } } return false; } void UpmPreprocessor::readModalias() { QFile file; QString filePath = UPM_MODALIAS_PATH; file.setFileName(filePath); if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) return; QTextStream pstream(&file); m_modalias = pstream.readAll(); file.close(); } void UpmPreprocessor::readCpuType() { QFile file; QString filePath = UPM_CPU_INFO_PATH; file.setFileName(filePath); if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) return; QTextStream pstream(&file); m_cpuType = pstream.readAll(); file.close(); } QVariant UpmPreprocessor::readConfig(QString file, QString group, QString key) { QVariant ret; QSettings settings(file, QSettings::IniFormat); settings.beginGroup(group); ret = settings.value(key); settings.endGroup(); settings.sync(); return ret; } QString UpmPreprocessor::getBrightnessNode() { QStringList boardNames = readConfig( UPM_GLOBAL_CONFIG, UPM_LENOVO_BACKLIGHT, UPM_LENOVO_BOARD_NAME_KEY).toString().split(","); Q_FOREACH (const QString &str, boardNames) { if (m_modalias.contains(str) && !str.isEmpty()) { return UPM_LENOVO_BACKLIGHT; } } QStringList cpuAndNodes = {"ZHAOXIN:acpi_video0", "loongson:loongson-gpu", "Phytium:ec_bl"}; Q_FOREACH (const QString &str, cpuAndNodes) { QStringList cpuAndNode = str.split(":"); if (m_cpuType.contains(cpuAndNode[0], Qt::CaseInsensitive)) { return cpuAndNode[1]; } } return QString(); } ukui-power-manager-4.0.0.1/common/common.pri0000664000175000017500000000025414601232446017312 0ustar fengfengINCLUDEPATH += -I $$PWD/ HEADERS += \ $$PWD/global-define.h \ $$PWD/upmpreprocessor.h \ SOURCES += \ $$PWD/upmpreprocessor.cpp PKGCONFIG += gsettings-qt \ ukui-power-manager-4.0.0.1/common/global-define.h0000664000175000017500000000350514601232446020151 0ustar fengfeng/* * Copyright 2023 KylinSoft Co., Ltd. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ #include namespace Upm { #define UPM_MODALIAS_PATH QStringLiteral("/sys/class/dmi/id/modalias") #define UPM_CPU_INFO_PATH QStringLiteral("/proc/cpuinfo") #define UPM_GLOBAL_CONFIG QStringLiteral("/etc/ukui/ukui-power-manager/upm-global.conf") #define UPM_POWER_MODE_BALANCE_SCHEMA QStringLiteral("power-mode-default-balance") #define UPM_LENOVO_BACKLIGHT QStringLiteral("lenovo_backlight") #define UPM_POWER_IIC_SCHEMA QStringLiteral("iic-white-list") #define UPM_POWER_PCI_SCHEMA QStringLiteral("pci-white-list") #define UPM_POWER_SATA_SCHEMA QStringLiteral("sata-white-list") #define UPM_POWER_MODE_BALANCE_KEY QStringLiteral("boardName") #define UPM_LENOVO_BOARD_NAME_KEY QStringLiteral("boardName") #define POWER_MANAGER_SETTINGS ("org.ukui.power-manager") #define POWER_POLICY_AC QStringLiteral("powerPolicyAc") //电源策略(0:性能 1:平衡 2:节能) #define POWER_POLICY_BATTERY QStringLiteral("powerPolicyBattery") //电源策略(0:性能 1:平衡 2:节能) #define PRE_POWER_MODE QStringLiteral("preprocessPowerMode") enum powerMode{ Performance = 0, Balance, EnergySaving, }; } ukui-power-manager-4.0.0.1/.clang-format0000644000175000017500000001771014554615633016406 0ustar fengfeng--- # 语言: None, Cpp, Java, JavaScript, ObjC, Proto, TableGen, TextProto Language: Cpp # BasedOnStyle: WebKit # 访问说明符(public、private等)的偏移 AccessModifierOffset: -4 # 开括号(开圆括号、开尖括号、开方括号)后的对齐: Align, DontAlign, AlwaysBreak(总是在开括号后换行) AlignAfterOpenBracket: AlwaysBreak # 连续赋值时,对齐所有等号 AlignConsecutiveAssignments: false # 连续声明时,对齐所有声明的变量名 AlignConsecutiveDeclarations: false # 左对齐逃脱换行(使用反斜杠换行)的反斜杠 AlignEscapedNewlines: Right # 水平对齐二元和三元表达式的操作数 AlignOperands: true # 对齐连续的尾随的注释 AlignTrailingComments: true # 允许函数声明的所有参数在放在下一行 AllowAllParametersOfDeclarationOnNextLine: true # 允许短的块放在同一行 AllowShortBlocksOnASingleLine: false # 允许短的case标签放在同一行 AllowShortCaseLabelsOnASingleLine: false # 允许短的函数放在同一行: None, InlineOnly(定义在类中), Empty(空函数), Inline(定义在类中,空函数), All AllowShortFunctionsOnASingleLine: Empty # 允许短的if语句保持在同一行 AllowShortIfStatementsOnASingleLine: false # 允许短的循环保持在同一行 AllowShortLoopsOnASingleLine: false # 总是在定义返回类型后换行(deprecated) AlwaysBreakAfterDefinitionReturnType: None # 总是在返回类型后换行: None, All, TopLevel(顶级函数,不包括在类中的函数), # AllDefinitions(所有的定义,不包括声明), TopLevelDefinitions(所有的顶级函数的定义) AlwaysBreakAfterReturnType: None # 总是在多行string字面量前换行 AlwaysBreakBeforeMultilineStrings: false # 总是在template声明后换行 AlwaysBreakTemplateDeclarations: true # false表示函数实参要么都在同一行,要么都各自一行 BinPackArguments: false # false表示所有形参要么都在同一行,要么都各自一行 BinPackParameters: false # 大括号换行,只有当BreakBeforeBraces设置为Custom时才有效 BraceWrapping: # class定义后面 AfterClass: true # 控制语句后面 AfterControlStatement: false # enum定义后面 AfterEnum: true # 函数定义后面 AfterFunction: true # 命名空间定义后面 AfterNamespace: true # ObjC定义后面 AfterObjCDeclaration: false # struct定义后面 AfterStruct: true # union定义后面 AfterUnion: true # extern 定义后面 AfterExternBlock: true # catch之前 BeforeCatch: false # else 之前 BeforeElse: false # 缩进大括号 IndentBraces: false SplitEmptyFunction: true SplitEmptyRecord: true SplitEmptyNamespace: true # 在二元运算符前换行: None(在操作符后换行), NonAssignment(在非赋值的操作符前换行), All(在操作符前换行) BreakBeforeBinaryOperators: All # 在大括号前换行: Attach(始终将大括号附加到周围的上下文), Linux(除函数、命名空间和类定义,与Attach类似), # Mozilla(除枚举、函数、记录定义,与Attach类似), Stroustrup(除函数定义、catch、else,与Attach类似), # Allman(总是在大括号前换行), GNU(总是在大括号前换行,并对于控制语句的大括号增加额外的缩进), WebKit(在函数前换行), Custom # 注:这里认为语句块也属于函数 BreakBeforeBraces: Custom # 继承列表的逗号前换行 BreakBeforeInheritanceComma: false # 在三元运算符前换行 BreakBeforeTernaryOperators: true # 在构造函数的初始化列表的逗号前换行 BreakConstructorInitializersBeforeComma: false # 初始化列表前换行 BreakConstructorInitializers: BeforeComma # Java注解后换行 BreakAfterJavaFieldAnnotations: false BreakStringLiterals: true # 每行字符的限制,0表示没有限制 ColumnLimit: 120 # 描述具有特殊意义的注释的正则表达式,它不应该被分割为多行或以其它方式改变 CommentPragmas: '^ IWYU pragma:' # 紧凑 命名空间 CompactNamespaces: false # 构造函数的初始化列表要么都在同一行,要么都各自一行 ConstructorInitializerAllOnOneLineOrOnePerLine: true # 构造函数的初始化列表的缩进宽度 ConstructorInitializerIndentWidth: 4 # 延续的行的缩进宽度 ContinuationIndentWidth: 4 # 去除C++11的列表初始化的大括号{后和}前的空格 Cpp11BracedListStyle: false # 继承最常用的指针和引用的对齐方式 DerivePointerAlignment: false # 关闭格式化 DisableFormat: false # 自动检测函数的调用和定义是否被格式为每行一个参数(Experimental) ExperimentalAutoDetectBinPacking: false # 固定命名空间注释 FixNamespaceComments: true # 需要被解读为foreach循环而不是函数调用的宏 ForEachMacros: - foreach - Q_FOREACH - BOOST_FOREACH IncludeBlocks: Preserve # 对#include进行排序,匹配了某正则表达式的#include拥有对应的优先级,匹配不到的则默认优先级为INT_MAX(优先级越小排序越靠前), # 可以定义负数优先级从而保证某些#include永远在最前面 IncludeCategories: - Regex: '^"(llvm|llvm-c|clang|clang-c)/' Priority: 2 - Regex: '^(<|"(gtest|gmock|isl|json)/)' Priority: 3 - Regex: '.*' Priority: 1 IncludeIsMainRegex: '(Test)?$' # 缩进case标签 IndentCaseLabels: true IndentPPDirectives: None # 缩进宽度 IndentWidth: 4 # 函数返回类型换行时,缩进函数声明或函数定义的函数名 IndentWrappedFunctionNames: false JavaScriptQuotes: Leave JavaScriptWrapImports: true # 保留在块开始处的空行 KeepEmptyLinesAtTheStartOfBlocks: true # 开始一个块的宏的正则表达式 MacroBlockBegin: '' # 结束一个块的宏的正则表达式 MacroBlockEnd: '' # 连续空行的最大数量 MaxEmptyLinesToKeep: 1 # 命名空间的缩进: None, Inner(缩进嵌套的命名空间中的内容), All NamespaceIndentation: Inner # 使用ObjC块时缩进宽度 ObjCBlockIndentWidth: 4 # 在ObjC的@property后添加一个空格 ObjCSpaceAfterProperty: true # 在ObjC的protocol列表前添加一个空格 ObjCSpaceBeforeProtocolList: true PenaltyBreakAssignment: 2 PenaltyBreakBeforeFirstCallParameter: 19 # 在一个注释中引入换行的penalty PenaltyBreakComment: 300 # 第一次在<<前换行的penalty PenaltyBreakFirstLessLess: 120 # 在一个字符串字面量中引入换行的penalty PenaltyBreakString: 1000 # 对于每个在行字符数限制之外的字符的penalty PenaltyExcessCharacter: 1000000 # 将函数的返回类型放到它自己的行的penalty PenaltyReturnTypeOnItsOwnLine: 60 # 指针和引用的对齐: Left, Right, Middle PointerAlignment: Right #RawStringFormats: # - Delimiter: pb # Language: TextProto # BasedOnStyle: google # 允许重新排版注释 ReflowComments: true # 允许排序#include SortIncludes: false SortUsingDeclarations: true # 在C风格类型转换后添加空格 SpaceAfterCStyleCast: false # 模板关键字后面添加空格 SpaceAfterTemplateKeyword: true # 在赋值运算符之前添加空格 SpaceBeforeAssignmentOperators: true # 开圆括号之前添加一个空格: Never, ControlStatements, Always SpaceBeforeParens: ControlStatements # 在空的圆括号中添加空格 SpaceInEmptyParentheses: false # 在尾随的评论前添加的空格数(只适用于//) SpacesBeforeTrailingComments: 1 # 在尖括号的<后和>前添加空格 SpacesInAngles: false # 在容器(ObjC和JavaScript的数组和字典等)字面量中添加空格 SpacesInContainerLiterals: true # 在C风格类型转换的括号中添加空格 SpacesInCStyleCastParentheses: false # 在圆括号的(后和)前添加空格 SpacesInParentheses: false # 在方括号的[后和]前添加空格,lamda表达式和未指明大小的数组的声明不受影响 SpacesInSquareBrackets: false # 标准: Cpp03, Cpp11, Auto Standard: Cpp11 # tab宽度 TabWidth: 4 # 使用tab字符: Never, ForIndentation, ForContinuationAndIndentation, Always UseTab: Never ...