ukui-power-manager-4.0.0.1/ 0000755 0001750 0001750 00000000000 14601232446 014013 5 ustar feng feng ukui-power-manager-4.0.0.1/doc/ 0000775 0001750 0001750 00000000000 14601232446 014562 5 ustar feng feng ukui-power-manager-4.0.0.1/doc/schedules.md 0000664 0001750 0001750 00000004040 14601232446 017061 0 ustar feng feng ## 计划表
```
计划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/电源管理需求文档.md 0000664 0001750 0001750 00000003515 14601232446 025525 0 ustar feng feng # 电源管理需求文档
### 目录
```
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/性能测试注意事项.md 0000664 0001750 0001750 00000001126 14601232446 025640 0 ustar feng feng # 性能测试注意事项
```
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/设计文档.md 0000664 0001750 0001750 00000000033 14601232446 021447 0 ustar feng feng # 电源管理设计文档
ukui-power-manager-4.0.0.1/PowerManagementDaemon/ 0000775 0001750 0001750 00000000000 14601232446 020232 5 ustar feng feng ukui-power-manager-4.0.0.1/PowerManagementDaemon/upm-upower-dbus/ 0000775 0001750 0001750 00000000000 14601232446 023305 5 ustar feng feng ukui-power-manager-4.0.0.1/PowerManagementDaemon/upm-upower-dbus/upowerbatterydbus.cpp 0000664 0001750 0001750 00000012355 14601232446 027611 0 ustar feng feng /*
* 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.h 0000664 0001750 0001750 00000004046 14601232446 025661 0 ustar feng feng /*
* 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.h 0000664 0001750 0001750 00000003647 14601232446 027262 0 ustar feng feng /*
* 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.h 0000664 0001750 0001750 00000002446 14601232446 027610 0 ustar feng feng /*
* 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.h 0000664 0001750 0001750 00000004720 14601232446 026541 0 ustar feng feng /*
* 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.cpp 0000664 0001750 0001750 00000017246 14601232446 027103 0 ustar feng feng /*
* 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.cpp 0000664 0001750 0001750 00000011672 14601232446 026217 0 ustar feng feng /*
* 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.cpp 0000664 0001750 0001750 00000004651 14601232446 030143 0 ustar feng feng /*
* 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.h 0000664 0001750 0001750 00000002165 14601232446 023440 0 ustar feng feng /*
* 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/ 0000775 0001750 0001750 00000000000 14601232446 023040 5 ustar feng feng ukui-power-manager-4.0.0.1/PowerManagementDaemon/upm-gsettings/upm_gsettings.h 0000664 0001750 0001750 00000007503 14601232446 026106 0 ustar feng feng /*
* 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.cpp 0000664 0001750 0001750 00000012730 14601232446 026437 0 ustar feng feng /*
* 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.cpp 0000664 0001750 0001750 00000004615 14601232446 024273 0 ustar feng feng /*
* 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.h 0000664 0001750 0001750 00000003154 14601232446 023451 0 ustar feng feng /*
* 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/ 0000775 0001750 0001750 00000000000 14601232446 023444 5 ustar feng feng ukui-power-manager-4.0.0.1/PowerManagementDaemon/upm-control-dbus/upm_controldbus.cpp 0000664 0001750 0001750 00000012215 14601232446 027370 0 ustar feng feng /*
* 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.h 0000664 0001750 0001750 00000006174 14601232446 027044 0 ustar feng feng /*
* 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/ 0000775 0001750 0001750 00000000000 14601232446 023254 5 ustar feng feng ukui-power-manager-4.0.0.1/PowerManagementDaemon/upm-common-dbus/upm_commondbus.cpp 0000664 0001750 0001750 00000011115 14601232446 027006 0 ustar feng feng /*
* 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.h 0000664 0001750 0001750 00000003430 14601232446 026454 0 ustar feng feng /*
* 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.cpp 0000664 0001750 0001750 00000013650 14601232446 024067 0 ustar feng feng /*
* 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.h 0000664 0001750 0001750 00000002574 14601232446 024777 0 ustar feng feng /*
* 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/ 0000775 0001750 0001750 00000000000 14601232446 022753 5 ustar feng feng ukui-power-manager-4.0.0.1/PowerManagementDaemon/translations/ukui-power-manager-daemon_zh_CN.ts 0000664 0001750 0001750 00000001646 14601232446 031373 0 ustar feng feng
UpmCommonDBusPower Manager电源管理器UpmLowPowerLow battery notification低电量消息通知The system enters a low battery state系统进入低电量状态
ukui-power-manager-4.0.0.1/PowerManagementDaemon/translations/ukui-power-manager-daemon_tr.ts 0000664 0001750 0001750 00000001635 14601232446 031015 0 ustar feng feng
UpmCommonDBusPower ManagerUpmLowPowerLow battery notificationThe system enters a low battery state
ukui-power-manager-4.0.0.1/PowerManagementDaemon/translations/ukui-power-manager-daemon_bo_CN.ts 0000664 0001750 0001750 00000002127 14601232446 031345 0 ustar feng feng
UpmCommonDBusPower Managerགློག་ཁུངས་དོ་དམ་ཆས་UpmLowPowerLow battery notificationདམའ་གློག་ཚད་གནས་ཚུལ་བརྡ་སྦྱོར།The system enters a low battery stateམ་ལག་སླེབས་པ་དམའ་གློག་ཚད་རྣམ་པ།
ukui-power-manager-4.0.0.1/PowerManagementDaemon/upm_brightness.cpp 0000664 0001750 0001750 00000004762 14601232446 024000 0 ustar feng feng /*
* 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.h 0000664 0001750 0001750 00000003677 14601232446 023157 0 ustar feng feng /*
* 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.h 0000664 0001750 0001750 00000003210 14601232446 021667 0 ustar feng feng /*
* 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.cpp 0000664 0001750 0001750 00000010746 14601232446 022377 0 ustar feng feng /*
* 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/ 0000775 0001750 0001750 00000000000 14601232446 022244 5 ustar feng feng ukui-power-manager-4.0.0.1/PowerManagementDaemon/resources/10-monitor.conf 0000664 0001750 0001750 00000000237 14601232446 025022 0 ustar feng feng Section "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.desktop 0000664 0001750 0001750 00000000655 14601232446 031252 0 ustar feng feng [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.conf 0000664 0001750 0001750 00000000424 14601232446 025152 0 ustar feng feng [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.xml 0000664 0001750 0001750 00000051140 14601232446 030703 0 ustar feng feng 'suspend'Whether to hibernate, suspend or do nothing when inactiveThe type of sleeping that should be performed when the computer is inactive.'suspend'Battery critical low actionThe action to take when the battery is critically low.trueIf the battery event should occur when the lid is shut and the power disconnectedIf 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 inactiveThe type of sleeping that should be performed when the computer is inactive.'shutdown'UPS critical low actionThe action to take when the UPS is critically low.'hibernate'UPS low power actionThe action to take when the UPS is low.trueAllow backlight brightness adjustmentIf the screen brightness should be changed when switching between AC and battery power.trueReduce the backlight brightness when on battery powerIf the screen should be reduced in brightness when the computer is on battery power.trueReduce the keyboard backlight when on battery powerIf the keyboard backlight brightness should be reduced when the computer is on battery power100Keyboard backlight brightness when on AC power.Percent brightness to set keyboard backlight at when on AC power. Legal values are between 0 and 100.50Percent 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.75Percent 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.100The brightness of the screen when idleThis is the laptop panel screen brightness used when the session is idle. Only valid when use-time-for-policy is true.trueDim the screen after a period of inactivity when on battery powerIf the screen should be dimmed to save power when the computer is idle when on battery power.60The default amount of time to dim the screen after idleThe default amount of time to dim the screen after idle.50LCD dimming amount when on batteryThe amount to dim the brightness of the display when on battery power. Possible values are between 0 and 100.falseDim the screen after a period of inactivity when on AC powerIf the screen should be dimmed to save power when the computer is idle when on AC power.'off'Method used to blank screen on ACThe DPMS method used to blank the screen when on AC power.'off'Method used to blank screen on batteryThe DPMS method used to blank the screen when on battery power.-1.0LCD brightness when on ACThe brightness of the display when on AC power. Possible values are between 0.0 and 100.0.100.0LCD brightness when on BATThe brightness of the display when on BAT power. Possible values are between 0.0 and 100.0.'suspend'Suspend button actionThe action to take when the system suspend button is pressed.'hibernate'Hibernate button actionThe action to take when the system hibernate button is pressed.'interactive'Power button actionThe action to take when the system power button is pressed.'suspend'Laptop lid close action on batteryThe action to take when the laptop lid is closed and the laptop is on battery power.'suspend'Laptop lid close action when on ACThe action to take when the laptop lid is closed and the laptop is on AC power.trueWhether to use time-based notificationsIf time based notifications should be used. If set to false, then the percentage change is used instead, which may fix a broken ACPI BIOS.falseCheck CPU load before sleepingIf the CPU load should be checked before doing the idle action.falseWhether NetworkManager should be connected and disconnected on sleep.Whether NetworkManager should disconnect before suspending or hibernating and connect on resume.trueUse ukui-screensaver lock settingWhether to use the screen lock setting of ukui-screensaver to decide if the screen is locked after a hibernate, suspend or blank screen.trueLock screen when blankedWhether the screen is locked when the screen is turned off. Only used if lock-use-screensaver is false.trueLock screen on suspendWhether the screen is locked when the computer wakes up from a suspend. Only used if lock-use-screensaver is false.trueLock screen on hibernateWhether the screen is locked when the computer wakes up from a hibernate. Only used if lock-use-screensaver is false.falseLock GNOME keyring on sleepWhether the GNOME keyring is locked before the computer enters suspend. This means the keyring will have to be unlocked on resume.trueLock GNOME keyring on sleepWhether the GNOME keyring is locked before the computer enters hibernate. This means the keyring will have to be unlocked on resume.trueIf we should show the low capacity warning for a broken batteryIf we should show the low capacity warning for a broken battery.trueNotify when AC adapter is disconnectedIf the user should be notified when the AC adapter is disconnected.falseNotify when fully chargedIf a notification message should be displayed when the battery is fully charged.trueNotify on a sleep failureIf a notification message should be displayed after suspend or hibernate failed.''The URI to show to the user on sleep failureWhen sleep fails we can show the user a button to help fix the situation. Leave this blank if the button should not be shown.trueNotify on a low powerIf a notification message should be displayed when the battery is getting low.trueWhether we should show the history data pointsWhether we should show the history data points in the statistics window.trueWhether we should smooth the history dataWhether we should smooth the history data in the graph.'power'The default graph type to show for historyThe default graph type to show in the history window.21600The maximum time displayed for historyThe maximum duration of time displayed on the x-axis of the history graph.trueWhether we should show the stats data pointsWhether we should show the stats data points in the statistics window.trueWhether we should smooth the stats dataWhether we should smooth the stats data in the graph.'power'The default graph type to show for statsThe default graph type to show in the stats window.0The index of the page number to show by defaultThe 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 selectedThe identifier of the last device which is used to return focus to the correct device.20Percentage considered lowThe percentage of the battery when it is considered low. Only valid when use-time-for-policy is false.10Percentage considered criticalThe percentage of the battery when it is considered critical. Only valid when use-time-for-policy is false.5Percentage action is takenThe percentage of the battery when the critical action is performed. Only valid when use-time-for-policy is false.1200The time remaining when lowThe time remaining in seconds of the battery when it is considered low. Only valid when use-time-for-policy is true.300The time remaining when criticalThe time remaining in seconds of the battery when it is considered critical. Only valid when use-time-for-policy is true.120The time remaining when action is takenThe time remaining in seconds of the battery when critical action is taken. Only valid when use-time-for-policy is true.900Sleep timeout computer when on batteryThe amount of time in seconds the computer on battery power needs to be inactive before it goes to sleep.900Sleep timeout computer when on ACThe amount of time in seconds the computer on AC power needs to be inactive before it goes to sleep.0Sleep timeout computer when on UPSThe amount of time in seconds the computer on UPS power needs to be inactive before it goes to sleep.600Sleep timeout display when on ACThe amount of time in seconds before the display goes to sleep when the computer is on AC power.600Sleep timeout display when on batteryThe amount of time in seconds the computer on battery power needs to be inactive before the display goes to sleep.600Sleep timeout display when on UPSThe amount of time in seconds the computer on UPS power needs to be inactive before the display goes to sleep.trueIf sounds should be usedIf sounds should be used when the power is critically low, or inhibit requests have stopped the policy action.trueIf preferences and statistics items should be shown in the context menufalseIf power policy mode should be auto switched when plugged in and outfalseIf power policy mode should be auto switched when plugged in and out2power policy mode0power policy current0power policy current3power policy currentfalsebattery save switchfalsepower policy currentfalsepower policy current1power policy current1power policy current'present'When to show the notification iconDisplay options for the notification icon.falseinit power manager configfalseAdjust the power mode strategy based on local mainline information
ukui-power-manager-4.0.0.1/PowerManagementDaemon/upm_powerchanged.h 0000664 0001750 0001750 00000002077 14601232446 023740 0 ustar feng feng /*
* 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.cpp 0000664 0001750 0001750 00000020366 14601232446 024010 0 ustar feng feng /*
* 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.h 0000664 0001750 0001750 00000002746 14601232446 022045 0 ustar feng feng /*
* 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.h 0000664 0001750 0001750 00000003443 14601232446 022533 0 ustar feng feng /*
* 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.h 0000664 0001750 0001750 00000002501 14601232446 023525 0 ustar feng feng /*
* 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.cpp 0000664 0001750 0001750 00000002351 14601232446 021663 0 ustar feng feng /*
* 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.pro 0000664 0001750 0001750 00000006603 14601232446 025176 0 ustar feng feng QT += 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.cpp 0000664 0001750 0001750 00000004173 14601232446 025327 0 ustar feng feng /*
* 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.cpp 0000664 0001750 0001750 00000024245 14601232446 023504 0 ustar feng feng /*
* 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.cpp 0000664 0001750 0001750 00000020247 14601232446 023067 0 ustar feng feng /*
* 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/ 0000775 0001750 0001750 00000000000 14607363245 016455 5 ustar feng feng ukui-power-manager-4.0.0.1/plugin-power/translations/ 0000775 0001750 0001750 00000000000 14601232446 021166 5 ustar feng feng ukui-power-manager-4.0.0.1/plugin-power/translations/en_US.ts 0000664 0001750 0001750 00000021401 14601232446 022545 0 ustar feng feng
PowerPowerGeneral/Power/GeneralSelect power plan/Power/Select power planBattery saving plan/Power/Battery saving planReduce the occupation of backend running program resources and ensure smooth operation of key and focus applications.Require password when sleep/hibernateRequire password when hibernateRequire password when sleepPassword required when waking up the screenPress the power buttonTime to close displayTime to sleepNotebook coverDynamic resource schedulingUsing powerUsing batteryOpen battery savingAutomatically run saving mode when low batteryAuto display brightness levelLow battery notificationBattery level is lower thanRuninteractiveshutdownsuspendhibernate5min10min15min30min1h2hnever3hnothingblankBalanceEnergy EfficiencyPerformance
ukui-power-manager-4.0.0.1/plugin-power/translations/bo_CN.ts 0000664 0001750 0001750 00000027702 14601232446 022526 0 ustar feng feng
PowerPowerསྟོབས་ཤུགས།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/GeneralSelect power planསྒུལ་ཤུགས་འཆར་གཞི་བདམས་པ།/Power/Select power planBattery saving planགློག་གཡིས་གྲོན་ཆུང་གི་འཆར་/Power/Battery saving plannothingཅི་ཡང་མ་རེད།blankསྟོང་ཆ།shutdownཁ་རྒྱགOpen battery savingསྒོ་ཕྱེ་བའི་གློག་སྨན་གྲོན་ཆུངAuto display brightness levelརང་འགུལ་གྱིས་མངོན་པའི་གསལ་ཚད་ཀྱི་ཆུ་suspendགཉིད་hibernateམངལ་གནས་སུ་སྦས་པ།interactiveཕན་ཚུན་སྐུལ་འདེད་5min5སྐར་མ་10min10སྐར་མ་15min15སྐར་མ་30min30སྐར་མ་1h1ཆུ་ཚོད།2h2ཆུ་ཚོད།neverགཏན་ནས་བྱེད་མི་3h3ཆུ་ཚོད།Balanceདོ་མཉམ།Energy Efficiencyཕན་འབྲས་ལེགས་ཤོས་Performanceམཆོག་གྱུར་གཤིས་ནུས།
ukui-power-manager-4.0.0.1/plugin-power/translations/zh_CN.ts 0000664 0001750 0001750 00000022742 14601232446 022546 0 ustar feng feng
PowerPower电源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/GeneralSelect power plan电源计划/Power/Select power planBattery saving plan电池节电计划/Power/Battery saving plannothing无操作blank关闭显示器shutdown关机Open battery saving开启节电计划Auto display brightness level节电模式下自动降低屏幕亮度suspend睡眠hibernate休眠interactive询问5min5 分钟10min10 分钟15min15 分钟30min30 分钟1h1 小时2h2 小时never从不3h3 小时Balance平衡Energy Efficiency最佳能效Performance最佳性能
ukui-power-manager-4.0.0.1/plugin-power/powermacrodata.h 0000664 0001750 0001750 00000005312 14601232446 021627 0 ustar feng feng /* -*- 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.pro 0000664 0001750 0001750 00000001620 14601232446 021616 0 ustar feng feng QT += 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.sh 0000775 0001750 0001750 00000000522 14601232446 023213 0 ustar feng feng #!/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.h 0000664 0001750 0001750 00000013303 14601232446 017752 0 ustar feng feng /*
* 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.cpp 0000664 0001750 0001750 00000142453 14607363245 020326 0 ustar feng feng /*
* 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/ 0000775 0001750 0001750 00000000000 14607363245 020521 5 ustar feng feng ukui-power-manager-4.0.0.1/ukui-power-manager-tray/powertray.h 0000664 0001750 0001750 00000004250 14601232446 022717 0 ustar feng feng /*
* 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.h 0000664 0001750 0001750 00000020124 14601232446 023254 0 ustar feng feng /*
* 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.h 0000664 0001750 0001750 00000003527 14601232446 024537 0 ustar feng feng /*
* 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.cpp 0000664 0001750 0001750 00000006427 14601232446 022651 0 ustar feng feng /*
* 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.h 0000664 0001750 0001750 00000003275 14601232446 025717 0 ustar feng feng /*
* 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.pro 0000664 0001750 0001750 00000005701 14601232446 025732 0 ustar feng feng #-------------------------------------------------
#
# 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.cpp 0000664 0001750 0001750 00000013746 14601232446 023635 0 ustar feng feng /*
* 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.cpp 0000664 0001750 0001750 00000017043 14601232446 024332 0 ustar feng feng /*
* 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/ 0000775 0001750 0001750 00000000000 14601232446 022765 5 ustar feng feng ukui-power-manager-4.0.0.1/ukui-power-manager-tray/upower-dbus/upowerbatterydbus.cpp 0000664 0001750 0001750 00000012335 14601232446 027267 0 ustar feng feng /*
* 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.h 0000664 0001750 0001750 00000004045 14601232446 025340 0 ustar feng feng /*
* 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.h 0000664 0001750 0001750 00000003654 14601232446 026740 0 ustar feng feng /*
* 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.h 0000664 0001750 0001750 00000002454 14601232446 027267 0 ustar feng feng /*
* 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.cpp 0000664 0001750 0001750 00000011640 14601232446 025672 0 ustar feng feng /*
* 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.cpp 0000664 0001750 0001750 00000005042 14601232446 027616 0 ustar feng feng /*
* 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.cpp 0000664 0001750 0001750 00000012433 14601232446 026246 0 ustar feng feng /*
* 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.h 0000664 0001750 0001750 00000006243 14601232446 023274 0 ustar feng feng /*
* 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/ 0000775 0001750 0001750 00000000000 14601232446 023232 5 ustar feng feng ukui-power-manager-4.0.0.1/ukui-power-manager-tray/translations/ukui-power-manager-tray_tr.ts 0000664 0001750 0001750 00000021610 14601232446 031003 0 ustar feng feng
NotificationDialogThe system will %1 in 60 seconds as the battery is about to run out.I knowThe system will %1 in %2 seconds as the battery is about to run out.shutdownhibernatesuspendPowerTraySetPower设置电源和睡眠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%)powerwindowCharging正在充电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.ts 0000664 0001750 0001750 00000022014 14601232446 031356 0 ustar feng feng
NotificationDialogThe 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睡眠PowerTraySetPower设置电源和睡眠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%)powerwindowCharging正在充电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.ts 0000664 0001750 0001750 00000026475 14601232446 031354 0 ustar feng feng
NotificationDialogThe 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གཉིད་PowerTraySetPowerབཀོད་སྒྲིག།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%)powerwindowChargingགློག་གསོག་པའི་ནང།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དང་སྐར་མ་%2fully chargedགློག་གསོག་ཚད་ཚང་མ་Better enduranceགློག་སྨན།Better performanceདོ་མཉམ།Best performanceཆེས་ལེགས་པའི་ནུས་པ།
ukui-power-manager-4.0.0.1/ukui-power-manager-tray/powersupplydev.h 0000664 0001750 0001750 00000005343 14601232446 023777 0 ustar feng feng /*
* 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.h 0000664 0001750 0001750 00000001657 14601232446 022321 0 ustar feng feng /*
* 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/ 0000775 0001750 0001750 00000000000 14601232446 022523 5 ustar feng feng ukui-power-manager-4.0.0.1/ukui-power-manager-tray/resources/ukui-power-manager-tray.desktop 0000664 0001750 0001750 00000000643 14601232446 030615 0 ustar feng feng [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.cpp 0000664 0001750 0001750 00000002226 14601232446 022645 0 ustar feng feng /*
* 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.h 0000664 0001750 0001750 00000002025 14601232446 023677 0 ustar feng feng /*
* 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.cpp 0000664 0001750 0001750 00000004241 14601232446 022142 0 ustar feng feng /*
* 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.cpp 0000664 0001750 0001750 00000023312 14601232446 023252 0 ustar feng feng /*
* 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.cpp 0000664 0001750 0001750 00000052204 14607363245 023614 0 ustar feng feng /*
* 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.cpp 0000664 0001750 0001750 00000051700 14601232446 023613 0 ustar feng feng /*
* 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.h 0000664 0001750 0001750 00000007567 14601232446 023265 0 ustar feng feng /*
* 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.cpp 0000664 0001750 0001750 00000012345 14601232446 025070 0 ustar feng feng /*
* 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.cpp 0000664 0001750 0001750 00000003701 14601232446 024234 0 ustar feng feng /*
* 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.h 0000664 0001750 0001750 00000002534 14601232446 022311 0 ustar feng feng /*
* 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/ 0000775 0001750 0001750 00000000000 14601232446 014570 5 ustar feng feng ukui-power-manager-4.0.0.1/man/ukui-powermanagement.1 0000664 0001750 0001750 00000001374 14601232446 021023 0 ustar feng feng .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.1 0000664 0001750 0001750 00000001430 14601232446 021344 0 ustar feng feng .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.1 0000664 0001750 0001750 00000001365 14601232446 022461 0 ustar feng feng .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.md 0000664 0001750 0001750 00000000364 14601232446 015577 0 ustar feng feng ## dbus 服务
```
用于提权
使用方法:
mkdir build
make -j8
sudo make install //这样会讲service文件安装到系统目录下
调用exitService接口退出 //或者重启,否则修改无法生效(注销也不生效)
```
ukui-power-manager-4.0.0.1/powermanagement.pro 0000664 0001750 0001750 00000000232 14601232446 017725 0 ustar feng feng TEMPLATE = subdirs
CONFIG += ordered
SUBDIRS = \
registeredQDbus \
PowerManagementDaemon \
ukui-power-manager-tray \
plugin-power \
ukui-power-manager-4.0.0.1/registeredQDbus/ 0000775 0001750 0001750 00000000000 14601232446 017111 5 ustar feng feng ukui-power-manager-4.0.0.1/registeredQDbus/sysdbusregister.cpp 0000664 0001750 0001750 00000021604 14601232446 023061 0 ustar feng feng /*
* 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/ 0000775 0001750 0001750 00000000000 14601232446 022737 5 ustar feng feng ukui-power-manager-4.0.0.1/registeredQDbus/brightness-control/brightnessnode.cpp 0000664 0001750 0001750 00000013063 14601232446 026464 0 ustar feng feng /*
* 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.h 0000664 0001750 0001750 00000003434 14601232446 026132 0 ustar feng feng /*
* 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/ 0000775 0001750 0001750 00000000000 14601232446 020036 5 ustar feng feng ukui-power-manager-4.0.0.1/registeredQDbus/conf/org.ukui.powermanagement.service 0000664 0001750 0001750 00000000143 14601232446 026351 0 ustar feng feng [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.conf 0000664 0001750 0001750 00000001625 14601232446 025644 0 ustar feng feng
ukui-power-manager-4.0.0.1/registeredQDbus/powerconfig.h 0000664 0001750 0001750 00000005250 14601232446 021606 0 ustar feng feng /*
* 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.pro 0000664 0001750 0001750 00000002324 14601232446 022730 0 ustar feng feng QT += 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/ 0000775 0001750 0001750 00000000000 14601232446 022477 5 ustar feng feng ukui-power-manager-4.0.0.1/registeredQDbus/dev-power-control/pcidevice.cpp 0000664 0001750 0001750 00000014013 14601232446 025135 0 ustar feng feng /*
* 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.h 0000664 0001750 0001750 00000003302 14601232446 024601 0 ustar feng feng /*
* 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.h 0000664 0001750 0001750 00000003072 14601232446 026042 0 ustar feng feng /*
* 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.h 0000664 0001750 0001750 00000003035 14601232446 024761 0 ustar feng feng /*
* 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.cpp 0000664 0001750 0001750 00000003423 14601232446 026441 0 ustar feng feng /*
* 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.cpp 0000664 0001750 0001750 00000006137 14601232446 026402 0 ustar feng feng /*
* 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.h 0000664 0001750 0001750 00000003015 14601232446 024504 0 ustar feng feng /*
* 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