New upstream version 4.1.0.0

This commit is contained in:
dengtuo 2023-11-23 16:31:57 +08:00
parent eb7008be90
commit 73ccf92832
134 changed files with 13215 additions and 15469 deletions

30
LICENSE Normal file
View File

@ -0,0 +1,30 @@
BSD 3-Clause License
Copyright (c) 2022, dengtuo
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of the copyright holder nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

View File

@ -1,175 +0,0 @@
#!/usr/bin/python3
#
import dbus
import dbus.service
import dbus.mainloop.glib
from gi.repository import GLib
#dbus调用封装
class MyDbusCall:
def __init__(self, servername, objectpath, type = 0) -> None:
self.__servername = servername
self.__path = objectpath
self.__dbus = None
if 0 == type:
self.__dbus = dbus.SessionBus()
else:
self.__dbus = dbus.SystemBus()
self.__proxy = self.__dbus.get_object(servername, objectpath)
def getdbus(self):
return self.__dbus
#调用服务提供接口
#params ---- type(list)
def callmethod(self, dbus_interface, function, params):
res = None
try:
res = self.__proxy.get_dbus_method(function, dbus_interface=dbus_interface)(*params)
except Exception as e:
res = e
return res
def getAttr(self, attr_interface, dbus_interface, function):
res = None
try:
interface = dbus.Interface(self.__proxy, attr_interface)
res = interface.Get(dbus_interface, function)
except Exception as e:
res = e
return res
def addSignal(self, path, dbus_interface, signal_name, callback):
self.__dbus.add_signal_receiver(callback, dbus_interface = dbus_interface,
signal_name = signal_name, bus_name=self.__servername,
path = path)
ServiceName = "org.freedesktop.login1"
ObjectName = "/org/freedesktop/login1"
InterfaceName = ServiceName + ".Manager"
InterfaceName1 = "org.freedesktop.DBus.Properties"
InterfaceName2 = ServiceName + ".Session"
methed_ListSession = "ListSessions"
s = None
class Sess():
def __init__(self, sid, uid, user, seat, objectpath) -> None:
self.sid = sid
self.uid = uid
self.user = user
self.seat = seat
self.objectpath = objectpath
self.__dbus = MyDbusCall(ServiceName, self.objectpath, 1)
self.Remote = self.__dbus.getAttr(InterfaceName1, InterfaceName2, "Remote")
self.Active = self.__dbus.getAttr(InterfaceName1, InterfaceName2, "Active")
self.Service = self.__dbus.getAttr(InterfaceName1, InterfaceName2, "Service")
if user is None:
self.user = self.__dbus.getAttr(InterfaceName1, InterfaceName2, "Name")
self.__dbus.addSignal(self.objectpath, InterfaceName1, "PropertiesChanged", self.PropertiesChanged)
print("sess[{}]: user<{}> Remote<{}> Active<{}> Service<{}>".format(
self.sid, self.user, self.Remote, self.Active, self.Service))
def PropertiesChanged(self, v1, v2, v3):
if "Active" in v2:
self.Active = v2['Active']
print("sess[{}]: user<{}> Remote<{}> Active<{}> Service<{}>".format(
self.sid, self.user, self.Remote, self.Active, self.Service))
s.UpdateActiveUser()
def CalcValue(self):
if self.Active != True:
return False
if self.Remote:
return False
if self.sid.isdigit() != True:
return False
return True
class SessMng(dbus.service.Object):
def __init__(self, bus) -> None:
self.__sesses = dict()
self.activeUser = None
self.path = '/com/ukui/test'
bus_name = dbus.service.BusName("org.ukui.test", bus)
dbus.service.Object.__init__(self, bus_name, self.path)
def createSess(self, sid, uid, user, seat, objectpath):
print("createSess : ", sid)
if sid in self.__sesses:
return False
self.__sesses[sid] = Sess(sid, uid, user, seat, objectpath)
print("sess num : ", len(self.__sesses))
return True
def delSess(self, sid):
print("del: ", sid)
if sid in self.__sesses:
self.__sesses.pop(sid)
print("sess num : ", len(self.__sesses))
def getSess(self, sid):
return self.__sesses(sid, None)
def UpdateActiveUser(self):
last = None
for sess in self.__sesses.values():
if sess.CalcValue() is True:
last = sess
break
if last is not None and self.activeUser != last.user:
self.activeUser = last.user
self.ActiveUserChange(self.activeUser)
print("emit ActiveUserChange signal")
print("activeUser : ", self.activeUser)
@dbus.service.signal('com.ukui.test', signature='s')
def ActiveUserChange(self, activeUser):
# nothing else to do so...
pass
@dbus.service.method("com.ukui.test",
in_signature='',
out_signature='s',
sender_keyword='sender')
def GetActiveUser(self, sender):
print("caller: ", sender)
return self.activeUser
def SessNew(sid, objectpath):
s.createSess(sid, None, None, None, objectpath)
s.UpdateActiveUser()
def SessRemove(sid, objectpath):
s.delSess(sid)
s.UpdateActiveUser()
if __name__ == '__main__':
dbus.mainloop.glib.DBusGMainLoop(set_as_default=True)
mydbus = MyDbusCall(ServiceName, ObjectName, 1)
sesses = mydbus.callmethod(InterfaceName, methed_ListSession, [])
s = SessMng(mydbus.getdbus())
for sess in sesses:
#print(sess)
if len(sess) != 5:
continue
s.createSess(*sess)
print(mydbus.getdbus().get_unique_name())
mydbus.addSignal(ObjectName, InterfaceName, "SessionNew", SessNew)
mydbus.addSignal(ObjectName, InterfaceName, "SessionRemoved", SessRemove)
s.UpdateActiveUser()
mainloop = GLib.MainLoop()
mainloop.run()

View File

@ -1,11 +0,0 @@
[Unit]
Description=active user service
After=systemd-logind.service
[Service]
Type=idle
ExecStart=python3 -u /usr/bin/activeuser.py
Restart=always
[Install]
WantedBy=multi-user.target

View File

@ -0,0 +1,22 @@
<?xml version="1.0" encoding="UTF-8"?> <!-- -*- XML -*- -->
<!DOCTYPE busconfig PUBLIC
"-//freedesktop//DTD D-BUS Bus Configuration 1.0//EN"
"http://www.freedesktop.org/standards/dbus/1.0/busconfig.dtd">
<busconfig>
<!-- Only root can own the service -->
<policy user="root">
<allow own="com.bluetooth.systemdbus"/>
<allow send_interface="com.bluetooth.interface"/>
</policy>
<!-- Allow anyone to invoke methods on the interfaces -->
<policy context="default">
<allow send_destination="com.bluetooth.systemdbus"
send_interface="com.bluetooth.interface"/>
<allow send_destination="com.bluetooth.systemdbus"
send_interface="org.freedesktop.DBus.Introspectable"/>
<allow send_destination="com.bluetooth.systemdbus"
send_interface="org.freedesktop.DBus.Properties"/>
</policy>
</busconfig>

View File

@ -0,0 +1,18 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE policyconfig PUBLIC
"-//freedesktop//DTD PolicyKit Policy Configuration 1.0//EN"
"http://www.freedesktop.org/standards/PolicyKit/1.0/policyconfig.dtd">
<policyconfig>
<vendor>kylin os</vendor>
<vendor_url>http://github.com/ukui/</vendor_url>
<action id="com.bluetooth.systemdbus.service">
<description>ukui bluetooth</description>
<message>system policy bluetooth</message>
<defaults>
<allow_any>auth_admin</allow_any>
<allow_inactive>auth_admin</allow_inactive>
<allow_active>auth_admin_keep</allow_active>
</defaults>
</action>
</policyconfig>

View File

@ -0,0 +1,4 @@
[D-BUS Service]
Name=com.bluetooth.systemdbus
Exec=/usr/bin/profileDaemon
User=root

View File

@ -1,20 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE busconfig PUBLIC
"-//freedesktop//DTD D-BUS Bus Configuration 1.0//EN"
"http://www.freedesktop.org/standards/dbus/1.0/busconfig.dtd">
<busconfig>
<policy user="root">
<allow own="com.ukui.bluetooth"/>
<allow send_destination="com.ukui.bluetooth"/>
</policy>
<!-- Allow anyone to invoke methods on the interfaces -->
<policy context="default">
<allow send_destination="com.ukui.bluetooth"
send_interface="com.ukui.bluetooth"/>
<allow send_destination="com.ukui.bluetooth"
send_interface="org.freedesktop.DBus.Introspectable"/>
<allow send_destination="com.ukui.bluetooth"
send_interface="org.freedesktop.DBus.Properties"/>
</policy>
</busconfig>

View File

@ -1,18 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE busconfig PUBLIC
"-//freedesktop//DTD D-BUS Bus Configuration 1.0//EN"
"http://www.freedesktop.org/standards/dbus/1.0/busconfig.dtd">
<busconfig>
<policy user="root">
<allow own="org.ukui.test"/>
<allow send_destination="org.ukui.test"/>
</policy>
<!-- Allow anyone to invoke methods on the interfaces -->
<policy context="default">
<allow send_destination="org.ukui.test"
send_interface="com.ukui.test"/>
<allow send_destination="org.ukui.test"
send_interface="org.freedesktop.DBus.Introspectable"/>
</policy>
</busconfig>

View File

@ -1,20 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE busconfig PUBLIC
"-//freedesktop//DTD D-BUS Bus Configuration 1.0//EN"
"http://www.freedesktop.org/standards/dbus/1.0/busconfig.dtd">
<busconfig>
<policy user="root">
<allow own="org.bluez.obex"/>
<allow send_destination="org.bluez.obex"/>
</policy>
<!-- Allow anyone to invoke methods on the interfaces -->
<policy context="default">
<allow send_destination="org.bluez.obex"
send_interface="org.bluez.obex"/>
<allow send_destination="org.bluez.obex"
send_interface="org.freedesktop.DBus.Introspectable"/>
<allow send_destination="org.bluez.obex"
send_interface="org.freedesktop.DBus.Properties"/>
</policy>
</busconfig>

View File

@ -5,10 +5,9 @@ Name=Bluetooth
Name[zh_CN]=蓝牙
Name[bo_CN]=སོ་སྔོན།
Name[zh_HK]=藍牙
Name[mn]=ᠯᠠᠨᠶᠠ
Comment=Simple bluetooth tool for ukui desktop environment
Comment[zh_CN]=UKUI桌面环境简单的蓝牙工具
Exec=/usr/bin/ukui-bluetooth
Exec=/usr/bin/bluetoothService -o
Icon=bluetooth
StartupNotify=false
OnlyShowIn=UKUI;

View File

@ -1,13 +0,0 @@
[Unit]
Description=UKUI Bluetooth service
After=dbus.service
[Service]
Environment="DBUS_SESSION_BUS_ADDRESS=unix:path=/run/dbus/system_bus_socket"
Type=simple
ExecStart=/usr/bin/bluetoothService
Restart=always
RestartSec=5s
[Install]
WantedBy=multi-user.target

32
profileDaemon/main.cpp Normal file
View File

@ -0,0 +1,32 @@
#include <QCoreApplication>
#include <QtSingleCoreApplication>
#include <QDBusConnection>
#include <QDebug>
#include "sysdbusregister.h"
int main(int argc, char *argv[])
{
QtSingleCoreApplication a(argc, argv);
a.setOrganizationName("Kylin Team");
a.setApplicationName("system-bus-bluetooth-service");
if (a.isRunning()) {
qDebug() << "system-bus-bluetooth-service is Already running ! ! !";
return EXIT_SUCCESS;
} else {
QDBusConnection systemBus = QDBusConnection::systemBus();
if (!systemBus.registerService("com.bluetooth.systemdbus")){
qCritical() << "QDbus register service failed reason:" << systemBus.lastError();
//exit(1);
}
if (!systemBus.registerObject("/", "com.bluetooth.interface", new SysDbusRegister(), QDBusConnection::ExportAllSlots)){
qCritical() << "QDbus register object failed reason:" << systemBus.lastError();
//exit(2);
}
// qDebug() << "ok";
return a.exec();
}
}

View File

@ -0,0 +1,53 @@
######################################################################
# Automatically generated by qmake (3.1) Thu Mar 4 18:08:23 2021
######################################################################
TEMPLATE = app
TARGET = profileDaemon
INCLUDEPATH += .
include(../qtsingleapplication/qtsinglecoreapplication.pri)
include(../environment.pri)
QT += core dbus
QT -= gui
CONFIG += c++11 link_pkgconfig
PKGCONFIG += gio-2.0
LIBS += -lglib-2.0
QMAKE_LFLAGS += -D_FORTIFY_SOURCE=2 -O2
ins1.files += ../data/com.bluetooth.systemdbus.conf
ins1.path = $$CONF_INSTALL_DIR
ins2.files += ../data/com.bluetooth.systemdbus.service
ins2.path = $$SERVICE_INSTALL_DIR
ins3.files += ../data/com.bluetooth.systemdbus.policy
ins3.path = $$ACTIONS_INSTALL_DIR
target.source += $$TARGET
target.path = $$BIN_INSTALL_DIR
INSTALLS += ins1 \
ins2 \
ins3 \
target
# The following define makes your compiler warn you 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
# Input
#HEADERS +=
SOURCES += main.cpp \
sysdbusregister.cpp
HEADERS += \
sysdbusregister.h

View File

@ -0,0 +1,138 @@
#include "sysdbusregister.h"
extern "C" {
#include <string>
#include <glib.h>
#include <glib/gprintf.h>
}
#include <QSettings>
SysDbusRegister::SysDbusRegister()
{
qInfo() << Q_FUNC_INFO ;
if (InterfaceAlreadyExists()) {
QDBusConnection systemBus = QDBusConnection::systemBus();
if (!systemBus.registerService("com.bluetooth.systemdbus")) {
qCritical() << "QDbus register service failed reason:" << systemBus.lastError();
}
if (!systemBus.registerObject("/", "com.bluetooth.interface", this, QDBusConnection::ExportAllSlots)){
qCritical() << "QDbus register object failed reason:" << systemBus.lastError();
}
}
}
SysDbusRegister::~SysDbusRegister()
{
}
int SysDbusRegister::exitService()
{
qApp->exit(0);
return 0;
}
QString SysDbusRegister::writeKeyFile(QString devAddress, QString devName, qint32 type)
{
qDebug() << Q_FUNC_INFO ;
if(devAddress.isNull())
return QString("Address can not be empty ! ! !");
if(devName.isNull())
return QString("Name can not be empty ! ! !");
if(devAddress.at(2) != ":" ||
devAddress.at(5) != ":" ||
devAddress.at(8) != ":" ||
devAddress.at(11) != ":" ||
devAddress.at(14) != ":")
return QString("arg0 is not an address ! ! !");
qDebug() << Q_FUNC_INFO << QFile::exists(LIST_PATH);
if(!QFile::exists(LIST_PATH)){
QFile file(LIST_PATH);
file.open(QIODevice::WriteOnly|QIODevice::Text);
file.close();
}
GKeyFile *key_file = nullptr;
key_file = g_key_file_new();
char *data;
gsize length = 0;
g_key_file_load_from_file(key_file,QString(LIST_PATH).toStdString().c_str(),G_KEY_FILE_NONE,NULL);
g_key_file_set_string(key_file,devAddress.toStdString().c_str(),"Name",devName.toStdString().c_str());
g_key_file_set_string(key_file,devAddress.toStdString().c_str(),"Type",QString("%1").arg(type).toStdString().c_str());
g_key_file_set_string(key_file,devAddress.toStdString().c_str(),"ConnectTime",QString::number(QDateTime::currentMSecsSinceEpoch() / 1000).toStdString().c_str());
data = g_key_file_to_data(key_file,&length,NULL);
g_file_set_contents(QString(LIST_PATH).toStdString().c_str(),data,length,NULL);
g_free(data);
g_key_file_free(key_file);
return QString("Key write ok!!!");
}
QString SysDbusRegister::removeKeyFile(QString devAddress)
{
qDebug() << Q_FUNC_INFO ;
if(devAddress.isNull())
return QString("Address can not be empty ! ! !");
if(devAddress.at(2) != ":" ||
devAddress.at(5) != ":" ||
devAddress.at(8) != ":" ||
devAddress.at(11) != ":" ||
devAddress.at(14) != ":")
return QString("arg0 is not an address ! ! !");
if(!QFile::exists(LIST_PATH)){
QFile file(LIST_PATH);
file.open(QIODevice::WriteOnly|QIODevice::Text);
file.close();
}
GKeyFile *key_file = nullptr;
char *data;
gsize length = 0;
GError *error;
key_file = g_key_file_new();
g_key_file_load_from_file(key_file,QString(LIST_PATH).toStdString().c_str(),G_KEY_FILE_NONE,NULL);
if(g_key_file_has_group(key_file,devAddress.toStdString().c_str())){
g_key_file_remove_group(key_file,devAddress.toStdString().c_str(),&error);
data = g_key_file_to_data(key_file,&length,NULL);
g_file_set_contents(QString(LIST_PATH).toStdString().c_str(),data,length,NULL);
g_free(data);
}
g_key_file_free(key_file);
return QString("Key remove ok!!!");
}
QString SysDbusRegister::getKeyFilePath()
{
return QString(LIST_PATH);
}
int SysDbusRegister::writeNewConf(QMap<QString, QVariant> attrs)
{
QSettings settings("/etc/bluetooth/ukui-bluetooth.conf", QSettings::IniFormat);
settings.beginGroup("conf");
for(auto iter : attrs.toStdMap())
{
settings.setValue(iter.first, iter.second);
}
settings.endGroup();
return 0;
}
bool SysDbusRegister::InterfaceAlreadyExists()
{
QDBusConnection conn = QDBusConnection::systemBus();
if (!conn.isConnected())
return 0;
QDBusReply<QString> reply = conn.interface()->call("GetNameOwner", "com.ukui.bluetooth");
return reply.value() == "";
}

View File

@ -0,0 +1,36 @@
#ifndef SYSDBUSREGISTER_H
#define SYSDBUSREGISTER_H
#include <QObject>
#include <QCoreApplication>
#include <QFile>
#include <QDateTime>
#include <QDebug>
#include <QtDBus/QDBusContext>
#include <QDBusConnection>
#include <QDBusReply>
#include <QDBusConnectionInterface>
#define LIST_PATH "/etc/pairDevice.list"
class SysDbusRegister : public QObject, protected QDBusContext
{
Q_OBJECT
Q_CLASSINFO("D-Bus Interface", "com.bluetooth.interface")
public:
SysDbusRegister();
~SysDbusRegister();
private:
bool InterfaceAlreadyExists();
public slots:
Q_SCRIPTABLE int exitService();
Q_SCRIPTABLE QString writeKeyFile(QString,QString,qint32);
Q_SCRIPTABLE QString removeKeyFile(QString);
Q_SCRIPTABLE QString getKeyFilePath();
//同步更新新版本配置文件,解决后期大版本升级相关问题
Q_SCRIPTABLE int writeNewConf(QMap<QString, QVariant>);
};
#endif // SYSDBUSREGISTER_H

View File

@ -1,46 +0,0 @@
#ifndef CSINGLETON_H
#define CSINGLETON_H
template <typename T>
class SingleTon
{
public:
// 创建单例实例
template<typename... Args>
static T* instance(Args&&... args)
{
if (m_pInstance == nullptr)
{
m_pInstance = new T(std::forward<Args>(args)...);
}
return m_pInstance;
}
// 获取单例
static T* getInstance()
{
return m_pInstance;
}
// 删除单例
static void destroyInstance()
{
delete m_pInstance;
m_pInstance = nullptr;
}
private:
SingleTon();
virtual ~SingleTon();
private:
static T* m_pInstance;
};
template <class T>
T* SingleTon<T>::m_pInstance = nullptr;
#endif

File diff suppressed because it is too large Load Diff

View File

@ -1,203 +0,0 @@
#ifndef ADAPTER_H
#define ADAPTER_H
#include <QObject>
#include <QMap>
#include <QString>
#include <QDebug>
#include <QSharedPointer>
#include <QTimer>
#include <KF5/BluezQt/bluezqt/adapter.h>
#include <KF5/BluezQt/bluezqt/device.h>
#include <KF5/BluezQt/bluezqt/pendingcall.h>
#include "ukui-log4qt.h"
#include "CSingleton.h"
#include "common.h"
class KylinDevice;
typedef QSharedPointer<KylinDevice> KylinDevicePtr;
class KylinAdapter : public QObject
{
Q_OBJECT
public:
explicit KylinAdapter(BluezQt::AdapterPtr adapter);
~KylinAdapter();
int start(void);
int stop(void);
int bluetooth_block(void);
void set_need_reconnect(bool v){ m_need_reconnect = v; }
int reconnect_dev(void);
public:
QStringList getAllDev(void);
QStringList getPairedDev(void);
QString addr(void) { return m_adapter->address(); }
bool setDiscoverable(bool);
bool setPower(bool);
bool setActiveConnection(bool);
bool setName(QString);
bool trayShow(bool);
QMap<QString, QVariant> getAdapterAttr(QString);
KylinDevicePtr getDevPtr(QString);
bool devIsAudioType(QString);
/*
**** type
* 0
* 1
*/
int devConnect(QString addr, int type = 0);
int devDisconnect(QString);
int devRemove(QStringList);
int updateDiscovering(void);
int devDisconnectAll(void);
QString connected_audio_device(void){ return m_connected_audio_device; }
void connected_audio_device(QString v);
int activeConnectionReply(QString, bool);
void clearPinCode(void);
protected slots:
void nameChanged(const QString &name);
void poweredChanged(bool powered);
void discoverableChanged(bool discoverable);
void discoveringChanged(bool discovering);
void deviceAdded(BluezQt::DevicePtr device);
void deviceRemoved(BluezQt::DevicePtr device);
void uuidsChanged(const QStringList &uuids);
protected:
int add(BluezQt::DevicePtr adapter);
int remove(BluezQt::DevicePtr adapter);
bool deal_active_connection(QString, int);
bool __setDiscoverable();
bool __setPower();
bool __setActiveConnection();
bool __setDiscovering();
void __sendAttr(enum_send_type stype = enum_send_type_delay);
void __sendAdd();
void __reconnectFunc();
void __clear_timers();
int __devRemove(QString);
virtual void timerEvent( QTimerEvent *event);
void wait_for_finish(BluezQt::PendingCall *call);
void __init_uuid();
void __init_devattr(QMap<QString, QVariant> &);
protected:
//正在使用的蓝牙适配器标志,仅有一个
bool m_is_start = false;
BluezQt::AdapterPtr m_adapter = nullptr;
QMap<QString, KylinDevicePtr> m_devices;
bool m_connectProgress = false;
bool m_need_reconnect = true;
bool m_reconnectProgress = false;
bool m_powerProgress = false;
bool m_set_power = false;
bool m_set_discoverable = false;
bool m_set_Discovering = false;
bool m_set_activeConnection = false;
QString m_connected_audio_device;
QMap<QString, QVariant> m_attr_send;
int m_set_TimerID = 0;
int m_autoclean_TimerID = 0;
int m_attrsignal_TimerID= 0;
int m_activeConnection_TimerID = 0;
int m_reconnect_TimerId = 0;
QString m_active_dev;
QSet<QString> m_black_activeconn_dev;
QStringList m_uuids;
bool m_support_ad2p_sink = false;
bool m_support_a2dp_source = false;
bool m_support_hfphsp_ag = false;
bool m_support_hfphsp_hf = false;
bool m_support_filetransport = false;
bool m_cleanProgress = false;
friend class KylinDevice;
};
typedef QSharedPointer<KylinAdapter> KylinAdapterPtr;
class AdapterMng : public QObject
{
Q_OBJECT
public:
AdapterMng();
~AdapterMng();
int add(BluezQt::AdapterPtr adapter);
int remove(BluezQt::AdapterPtr adapter);
QStringList getAllAdapterAddress(void);
QStringList getDefaultAdapterAllDev(void);
QStringList getDefaultAdapterPairedDev(void);
int setDefaultAdapter(QString);
QMap<QString, QVariant> getAdapterAttr(QString, QString);
KylinAdapterPtr getDefaultAdapter(void){ return m_default_adapter; }
void bluetooth_block(bool);
bool isDefaultAdapter(QString);
protected:
int update_adapter(void);
protected:
KylinAdapterPtr m_default_adapter = nullptr;
QMap<QString, KylinAdapterPtr> m_adapters;
bool m_bluetooth_block = false;
friend class SingleTon<AdapterMng>;
};
typedef SingleTon<AdapterMng> ADAPTERMNG;
#endif // ADAPTER_H

View File

@ -1,117 +0,0 @@
#include "app.h"
#include <QDBusConnection>
#include "adapter.h"
#include "common.h"
#include "config.h"
Application::Application(QString dbusid, QString username, int type)
{
m_dbusid = dbusid;
m_username = username;
m_type = type;
KyInfo() << "dbusid: " << m_dbusid <<", username: " << m_username
<< ", type: " << m_type;
}
Application::~Application()
{
KyInfo() << "dbusid: " << m_dbusid;
}
ApplicationMng::ApplicationMng()
{
m_watch = new QDBusServiceWatcher("",QDBusConnection::systemBus(),
QDBusServiceWatcher::WatchForUnregistration, nullptr);
connect(m_watch, &QDBusServiceWatcher::serviceUnregistered, this, &ApplicationMng::serviceUnregistered);
}
ApplicationMng::~ApplicationMng()
{
m_watch->disconnect(this);
m_watch->deleteLater();
}
int ApplicationMng::add(QString dbusid, QString username, int type)
{
KyInfo() << dbusid << username << type;
if(m_apps.contains(dbusid))
{
return 0;
}
else
{
Application * mem = new Application(dbusid, username, type);
m_apps[dbusid] = mem;
m_watch->addWatchedService(dbusid);
}
this->update();
return 1;
}
int ApplicationMng::remove(QString dbusid)
{
KyInfo() << dbusid;
if(m_apps.contains(dbusid))
{
delete m_apps[dbusid];
m_apps.remove(dbusid);
this->update();
}
return 1;
}
int ApplicationMng::getControlNum()
{
int num = 0;
for(auto item : m_apps.toStdMap())
{
//控制面板
if(item.second->type() == enum_app_type_bluetooth_controlPanel)
{
//仅计算活跃用户的控制面板数量
if(item.second->username() == CONFIG::getInstance()->active_user())
{
num++;
}
}
}
return num;
}
bool ApplicationMng::existDbusid(QString id)
{
return m_apps.contains(id);
}
QStringList ApplicationMng::getRegisterClient()
{
QStringList apps;
for(auto item : m_apps.toStdMap())
{
apps.append(item.first);
}
return apps;
}
void ApplicationMng::update()
{
KylinAdapterPtr ptr = ADAPTERMNG::getInstance()->getDefaultAdapter();
if(ptr)
{
ptr->updateDiscovering();
}
}
void ApplicationMng::serviceUnregistered(const QString &service)
{
KyInfo() << service;
this->remove(service);
}

View File

@ -1,63 +0,0 @@
#ifndef APP_H
#define APP_H
#include <QObject>
#include <QMap>
#include <QString>
#include <QDebug>
#include <QDBusServiceWatcher>
#include "ukui-log4qt.h"
#include "CSingleton.h"
class Application
{
public:
explicit Application(QString, QString, int);
~Application();
QString dbusid(){ return m_dbusid; }
QString username(){ return m_username; }
int type(){ return m_type; }
protected:
QString m_dbusid;
QString m_username;
int m_type = 0;
};
class ApplicationMng: public QObject
{
public:
ApplicationMng();
~ApplicationMng();
public:
int add(QString, QString, int);
int remove(QString);
int getControlNum(void);
int getAllNum(void) { return m_apps.size(); }
bool existDbusid(QString);
QStringList getRegisterClient(void);
//int unknownDbusid(QString, );
private:
void update(void);
protected slots:
void serviceUnregistered(const QString &service);
protected:
QMap<QString, Application *> m_apps;
QDBusServiceWatcher * m_watch = nullptr;
friend class SingleTon<ApplicationMng>;
};
typedef SingleTon<ApplicationMng> APPMNG;
#endif // APP_H

View File

@ -1,155 +1,191 @@
#include "bluetoothagent.h"
#include "adapter.h"
#include "device.h"
#include "globalsize.h"
//取消发送蓝牙设备状态信号,在SessionDbusRegister定义
extern int cancelEmitDevStatus(QString addr);
extern void addDelay(BluezQt::DevicePtr dev);
BluetoothAgent::BluetoothAgent(QObject *parent)
: Agent(parent)
, m_pinRequested(false)
, m_passkeyRequested(false)
, m_authorizationRequested(false)
, m_cancelCalled(false)
, m_releaseCalled(false)
, m_hasClosePinCode(false)
{
KyInfo();
qDebug() << Q_FUNC_INFO;
if(daemonIsNotRunning()){
//QDBusConnection bus = QDBusConnection::systemBus();
// 在session bus上注册名为"org.bluez.Agent1"的service
//if (!bus.registerService("org.bluez.Agent1")) { //注意命名规则-和_
// qDebug() << bus.lastError().message();
// exit(1);
//}
// "QDBusConnection::ExportAllSlots"表示把类Hotel的所有Slot都导出为这个Object的method
//bus.registerObject("/", this ,QDBusConnection::ExportAllContents);
}
QDBusConnection::sessionBus().connect("com.ukui.bluetooth",
"/com/ukui/bluetooth",
"com.ukui.bluetooth",
"replyRequestConfirmation",
this,
SLOT(replyRequestConfirmationFunc(bool)));
}
void BluetoothAgent::emitRemoveSignal(BluezQt::DevicePtr device) {
if (device.data()->isPaired()) {
QTimer::singleShot(100,this,[=]{
emit agentRemoveDevice(device);
});
}
}
void BluetoothAgent::replyRequestConfirmationFunc(bool v)
{
qDebug() << Q_FUNC_INFO << v;
//if (tmpRequestConfirmation == NULL)
// qDebug() << "BluetoothAgent::replyRequestConfirmationFunc--qk-0";
//qDebug() << "BluetoothAgent::replyRequestConfirmationFunc--qk-01";
if (v)
tmpRequestConfirmation.accept();
else
tmpRequestConfirmation.reject();
//发送蓝牙连接信号
//条件:蓝牙设备未配对,蓝牙适配器配对,且蓝牙设备主动连接
//约束条件: 点击确定、被动连接、连接成功、配对
if(v && nullptr != m_device && !GlobalSize::IsBlueDevActive(m_device->address()) &&
m_device->isConnected() && m_device->isPaired())
{
//若对端拒绝、超时等,会出现蓝牙设备状态发送异常情况,暂时无法避免
addDelay(m_device);
}
qDebug() << "BluetoothAgent::replyRequestConfirmationFunc--qk";
}
QDBusObjectPath BluetoothAgent::objectPath() const
{
return QDBusObjectPath(QStringLiteral("/org/bluez/agent"));
return QDBusObjectPath(QStringLiteral("/BluetoothAgent"));
}
void BluetoothAgent::requestPinCode(BluezQt::DevicePtr device, const BluezQt::Request<QString> &request)
{
KyInfo();
KylinAdapterPtr ptr = ADAPTERMNG::getInstance()->getDefaultAdapter();
KylinDevicePtr d = nullptr;
if(device && ptr)
{
d = ptr->getDevPtr(device->address());
}
qDebug() << Q_FUNC_INFO;
m_device = device;
m_pinRequested = true;
request.accept(QString());
if(d)
{
d->requestPinCode(request);
}
else
{
request.reject();
}
}
void BluetoothAgent::displayPinCode(BluezQt::DevicePtr device, const QString &pinCode)
{
KyInfo();
KylinAdapterPtr ptr = ADAPTERMNG::getInstance()->getDefaultAdapter();
KylinDevicePtr d = nullptr;
if(device && ptr)
{
d = ptr->getDevPtr(device->address());
}
if(d)
{
d->displayPinCode(pinCode);
}
qDebug() << Q_FUNC_INFO;
//m_device = device;
//m_displayedPinCode = pinCode;
QString entered;
this->displayPasskey(device, pinCode, entered);
}
void BluetoothAgent::requestPasskey(BluezQt::DevicePtr device, const BluezQt::Request<quint32> &request)
{
KyInfo();
KylinAdapterPtr ptr = ADAPTERMNG::getInstance()->getDefaultAdapter();
KylinDevicePtr d = nullptr;
if(device && ptr)
{
d = ptr->getDevPtr(device->address());
}
qDebug() << Q_FUNC_INFO;
m_device = device;
m_passkeyRequested = true;
if(d)
{
d->requestPasskey(request);
}
else
{
request.reject();
}
request.accept(0);
}
void BluetoothAgent::displayPasskey(BluezQt::DevicePtr device, const QString &passkey, const QString &entered)
{
KyInfo();
this->displayPinCode(device, passkey);
qDebug() << Q_FUNC_INFO << ( m_device.isNull() ? "NULL" : m_device.data()->address() ) << entered << passkey;
cancelEmitDevStatus(device->address());
if(m_displayedPasskey == passkey)
return;
QDBusMessage displayPasskeySignal = QDBusMessage::createSignal("/com/ukui/bluetooth",
"com.ukui.bluetooth",
"displayPasskey");
displayPasskeySignal << device.data()->name() << passkey;
QDBusConnection::sessionBus().send(displayPasskeySignal);
}
void BluetoothAgent::requestConfirmation(BluezQt::DevicePtr device, const QString &passkey, const BluezQt::Request<> &request)
{
KyInfo() << device->name() << passkey << device->isConnected() << device->isPaired();
KylinAdapterPtr ptr = ADAPTERMNG::getInstance()->getDefaultAdapter();
KylinDevicePtr d = nullptr;
if(device && ptr)
{
d = ptr->getDevPtr(device->address());
}
qDebug() << Q_FUNC_INFO << device->name() << passkey << device->isConnected() << device->isPaired();
if(d)
cancelEmitDevStatus(device->address());
m_device = device;
//规避设备类型为耳机、音响设备时还会弹出pin窗口的问题
if ((nullptr != m_device) &&
(m_device.data()->type() == BluezQt::Device::AudioVideo ||
m_device.data()->type() == BluezQt::Device::Headphones ||
m_device.data()->type() == BluezQt::Device::Headset ))
{
d->requestConfirmation(passkey, request);
request.accept();
}
else
{
request.reject();
QDBusMessage displayPasskeySignal = QDBusMessage::createSignal("/com/ukui/bluetooth",
"com.ukui.bluetooth",
"requestConfirmation");
displayPasskeySignal << device.data()->name() << passkey;
QDBusConnection::sessionBus().send(displayPasskeySignal);
tmpRequestConfirmation = request;
}
}
void BluetoothAgent::requestAuthorization(BluezQt::DevicePtr device, const BluezQt::Request<> &request)
{
KyInfo() << device->name();
KylinAdapterPtr ptr = ADAPTERMNG::getInstance()->getDefaultAdapter();
KylinDevicePtr d = nullptr;
if(device && ptr)
{
d = ptr->getDevPtr(device->address());
}
qDebug() << Q_FUNC_INFO << device->name();
m_device = device;
m_authorizationRequested = true;
if(d)
{
d->requestAuthorization(request);
}
else
{
request.reject();
}
request.accept();
}
void BluetoothAgent::authorizeService(BluezQt::DevicePtr device, const QString &uuid, const BluezQt::Request<> &request)
{
KyInfo() << device->name();
KylinAdapterPtr ptr = ADAPTERMNG::getInstance()->getDefaultAdapter();
KylinDevicePtr d = nullptr;
if(device && ptr)
{
d = ptr->getDevPtr(device->address());
}
qDebug() << Q_FUNC_INFO << device->name();
m_device = device;
m_authorizedUuid = uuid;
if(d)
{
d->authorizeService(uuid, request);
}
else
{
request.reject();
}
request.accept();
}
void BluetoothAgent::cancel()
{
KyInfo();
KylinAdapterPtr ptr = ADAPTERMNG::getInstance()->getDefaultAdapter();
if(ptr)
{
ptr->clearPinCode();
}
qDebug() << Q_FUNC_INFO;
if (m_cancelCalled)
return;
QDBusMessage pairAgentCanceled = QDBusMessage::createSignal("/com/ukui/bluetooth",
"com.ukui.bluetooth",
"pairAgentCanceled");
QDBusConnection::sessionBus().send(pairAgentCanceled);
}
void BluetoothAgent::release()
{
KyInfo();
qDebug() << Q_FUNC_INFO;
m_releaseCalled = true;
}
int BluetoothAgent::daemonIsNotRunning()
{
QDBusConnection conn = QDBusConnection::systemBus();
if (!conn.isConnected())
return 0;
QDBusReply<QString> reply = conn.interface()->call("GetNameOwner", "org.bluez.Agent1");
return reply.value() == "";
}

View File

@ -1,6 +1,8 @@
#ifndef BLUETOOTHAGENT_H
#define BLUETOOTHAGENT_H
#include "../ukui-bluetooth/pin/pincodewidget.h"
#include <unistd.h>
#include <KF5/BluezQt/bluezqt/agent.h>
#include <KF5/BluezQt/bluezqt/adapter.h>
@ -14,12 +16,10 @@
#include <QtDBus/QDBusInterface>
#include <QtDBus/QDBusReply>
#include <QtDBus/QDBusConnectionInterface>
//#include <QMessageBox>
#include <QDebug>
#include <QTimer>
#include "ukui-log4qt.h"
#include "CSingleton.h"
class BluetoothAgent : public BluezQt::Agent
{
Q_OBJECT
@ -39,10 +39,47 @@ public:
void cancel() override;
void release() override;
int daemonIsNotRunning();
void emitRemoveSignal(BluezQt::DevicePtr device);
private slots:
void replyRequestConfirmationFunc(bool);
Q_SIGNALS:
void requestAccept();
void requestReject();
void stopNotifyTimer(BluezQt::DevicePtr);
void startNotifyTimer(BluezQt::DevicePtr);
void agentRemoveDevice(BluezQt::DevicePtr);
private:
friend class SingleTon<BluetoothAgent>;
BluezQt::DevicePtr m_device;
// requestPinCode
bool m_pinRequested;
// displayPinCode
QString m_displayedPinCode;
// requestPasskey
bool m_passkeyRequested;
// displayPasskey
QString m_displayedPasskey;
QString m_enteredPasskey;
// requestConfirmation
QString m_requestedPasskey;
// requestAuthorization
bool m_authorizationRequested;
// authorizeService
QString m_authorizedUuid;
// cancel
bool m_cancelCalled;
// release
bool m_releaseCalled;
bool m_hasClosePinCode;
BluezQt::Request<> tmpRequestConfirmation;
PinCodeWidget *pincodewidget = nullptr;
PinCodeWidget *Keypincodewidget = nullptr;
};
typedef SingleTon<BluetoothAgent> BLUETOOTHAGENT;
#endif // BLUETOOTHAGENT_H

View File

@ -1,43 +1,189 @@
#include "bluetoothobexagent.h"
#include "filesess.h"
BluetoothObexAgent::BluetoothObexAgent(QObject *parent):ObexAgent(parent)
{
KyInfo();
if(daemonIsNotRunning())
{
qDebug() << Q_FUNC_INFO << __LINE__;
QDBusConnection bus = QDBusConnection::sessionBus();
if (!bus.registerService("com.ukui.bluetooth")) { //注意命名规则-和_
qDebug() << bus.lastError().message();
exit(1);
}
// "QDBusConnection::ExportAllSlots"表示把类Hotel的所有Slot都导出为这个Object的method
//qDebug() << Q_FUNC_INFO << bus.registerObject("/", "org.bluez.obex.Agent1", this, QDBusConnection::ExportAllContents);
bus.registerObject("/", "org.bluez.obex.Agent1", this, QDBusConnection::ExportAllContents);
}
QDBusConnection::sessionBus().connect("com.ukui.bluetooth",
"/com/ukui/bluetooth",
"com.ukui.bluetooth",
"clearOldSession",
this,
SLOT(clearOldSession()));
QDBusConnection::sessionBus().connect("com.ukui.bluetooth",
"/com/ukui/bluetooth",
"com.ukui.bluetooth",
"replyFileReceivingSignal",
this,
SLOT(replyFileReceivingSignalFunc(bool)));
QDBusConnection::sessionBus().connect("com.ukui.bluetooth",
"/com/ukui/bluetooth",
"com.ukui.bluetooth",
"cancelFileReceivingSignal",
this,
SLOT(cancelFileReceivingSignalFunc()));
QDBusConnection::sessionBus().connect("com.ukui.bluetooth",
"/com/ukui/bluetooth",
"com.ukui.bluetooth",
"continueRecieveFilesSignal",
this,
SLOT(continueRecieveFiles()));
}
BluetoothObexAgent::~BluetoothObexAgent()
{
KyInfo();
}
QDBusObjectPath BluetoothObexAgent::objectPath() const
{
return QDBusObjectPath(QStringLiteral("/org/bluez/obex/Agent1"));
}
void BluetoothObexAgent::authorizePush(BluezQt::ObexTransferPtr transfer, BluezQt::ObexSessionPtr session, const BluezQt::Request<QString> &request)
{
KyInfo();
if(nullptr == transfer || nullptr == session)
{
request.reject();
qDebug() << Q_FUNC_INFO << transfer->status() << transfer->fileName() << transfer->name() <<transfer->objectPath().path() << transfer->transferred() << transfer->objectName();
qDebug() << session->source() << session->destination();
if (oldSession == session && transfer->status() != BluezQt::ObexTransfer::Error) {
qDebug() << Q_FUNC_INFO << __LINE__;
QDBusMessage fileReviceMore = QDBusMessage::createSignal("/com/ukui/bluetooth",
"com.ukui.bluetooth",
"fileReceiveMore");
fileReviceMore << transfer->name() << transfer->size() << transfer->type();
QDBusConnection::sessionBus().send(fileReviceMore);
_Mtransfer = transfer;
_Mrequest = &request;
qDebug() << Q_FUNC_INFO << __LINE__;
return;
}
m_session = session;
FILESESSMNG::getInstance()->receiveFiles(transfer, session, request);
qDebug() << Q_FUNC_INFO << __LINE__;
if(transfer->status() == BluezQt::ObexTransfer::Queued ){//|| transfer->status() == BluezQt::ObexTransfer::Complete
QDBusMessage statusChanged = QDBusMessage::createSignal("/com/ukui/bluetooth",
"com.ukui.bluetooth",
"statusChanged");
QMetaEnum metaEnum = QMetaEnum::fromType<BluezQt::ObexTransfer::Status>();
statusChanged << metaEnum.valueToKey(transfer->status()) << session.data()->destination() << transfer.data()->objectPath().path();
QDBusConnection::sessionBus().send(statusChanged);
QDBusMessage fileReceivingSignal = QDBusMessage::createSignal("/com/ukui/bluetooth",
"com.ukui.bluetooth",
"fileReceivingSignal");
fileReceivingSignal << session->destination() << transfer->name() << transfer->type() << session->source() << transfer.data()->size();
QDBusConnection::sessionBus().send(fileReceivingSignal);
qDebug() << Q_FUNC_INFO << __LINE__;
_Mtransfer = transfer;
_Mrequest = &request;
_Msession = session;
}
qDebug() << Q_FUNC_INFO << transfer->status() << transfer->type() << transfer->fileName() << transfer->transferred();
}
QDBusObjectPath BluetoothObexAgent::objectPath() const
{
qDebug() << Q_FUNC_INFO;
return QDBusObjectPath(QStringLiteral("/org/bluez/obex/Agent1"));
}
void BluetoothObexAgent::cancel()
{
FILESESSMNG::getInstance()->sessionCanceled(m_session);
KyInfo();
qDebug() << Q_FUNC_INFO;
statusChangedSlot(BluezQt::ObexTransfer::Error);
QDBusMessage obexAgentCanceled = QDBusMessage::createSignal("/com/ukui/bluetooth",
"com.ukui.bluetooth",
"obexAgentCanceled");
QDBusConnection::sessionBus().send(obexAgentCanceled);
oldSession = nullptr;
}
void BluetoothObexAgent::release()
{
KyInfo();
qDebug() << Q_FUNC_INFO;
}
int BluetoothObexAgent::daemonIsNotRunning()
{
QDBusConnection conn = QDBusConnection::sessionBus();
if (!conn.isConnected())
return 0;
QDBusReply<QString> reply = conn.interface()->call("GetNameOwner", "org.bluez.obex.Agent1");
return reply.value() == "";
}
void BluetoothObexAgent::continueRecieveFiles() {
qDebug() << Q_FUNC_INFO << __LINE__;
connect(_Mtransfer.data(), &BluezQt::ObexTransfer::transferredChanged, this, &BluetoothObexAgent::transferredChangedSlot);
connect(_Mtransfer.data(), &BluezQt::ObexTransfer::statusChanged, this, &BluetoothObexAgent::statusChangedSlot);
_Mrequest->accept(_Mtransfer.data()->name());
}
void BluetoothObexAgent::receiveDisConnectSignal(QString address)
{
qDebug() << Q_FUNC_INFO << address << __LINE__;
QDBusMessage m = QDBusMessage::createMethodCall("org.ukui.bluetooth","/org/ukui/bluetooth","org.ukui.bluetooth","disConnectToDevice");
m << address;
qDebug() << Q_FUNC_INFO << m.arguments().at(0).value<QString>() <<__LINE__;
// 发送Message
QDBusMessage response = QDBusConnection::sessionBus().call(m);
}
void BluetoothObexAgent::replyFileReceivingSignalFunc(bool value)
{
qDebug() << Q_FUNC_INFO << __LINE__;
if (value) {
qDebug() << Q_FUNC_INFO << __LINE__;
_Mrequest->accept(_Mtransfer.data()->name());
oldSession = _Msession;
qDebug() << Q_FUNC_INFO << __LINE__;
QDBusMessage initTransferPath = QDBusMessage::createSignal("/com/ukui/bluetooth",
"com.ukui.bluetooth",
"initTransferPath");
initTransferPath << _Mtransfer.data()->objectPath().path() << false;
QDBusConnection::sessionBus().send(initTransferPath);
connect(_Mtransfer.data(), &BluezQt::ObexTransfer::transferredChanged, this, &BluetoothObexAgent::transferredChangedSlot);
connect(_Mtransfer.data(), &BluezQt::ObexTransfer::statusChanged, this, &BluetoothObexAgent::statusChangedSlot);
} else {
statusChangedSlot(BluezQt::ObexTransfer::Error);
_Mrequest->reject();
clearOldSession();
}
}
void BluetoothObexAgent::cancelFileReceivingSignalFunc() {
_Mtransfer.data()->cancel();
qDebug() << Q_FUNC_INFO << __LINE__;
}
void BluetoothObexAgent::transferredChangedSlot(quint64 size) {
QDBusMessage transferredChanged = QDBusMessage::createSignal("/com/ukui/bluetooth",
"com.ukui.bluetooth",
"transferredChanged");
transferredChanged << QVariant::fromValue(size) << _Mtransfer.data()->objectPath().path();
QDBusConnection::sessionBus().send(transferredChanged);
}
void BluetoothObexAgent::statusChangedSlot(BluezQt::ObexTransfer::Status status) {
QDBusMessage statusChanged = QDBusMessage::createSignal("/com/ukui/bluetooth",
"com.ukui.bluetooth",
"statusChanged");
QMetaEnum metaEnum = QMetaEnum::fromType<BluezQt::ObexTransfer::Status>();
statusChanged << metaEnum.valueToKey(status) << _Msession.data()->destination() << _Mtransfer.data()->objectPath().path();
QDBusConnection::sessionBus().send(statusChanged);
}
void BluetoothObexAgent::clearOldSession() {
oldSession = nullptr;
}

View File

@ -16,30 +16,38 @@
#include <QtDBus/QDBusInterface>
#include <QtDBus/QDBusReply>
#include <QtDBus/QDBusConnectionInterface>
//#include <QMessageBox>
#include <QDebug>
#include <QMetaEnum>
#include "ukui-log4qt.h"
#include "CSingleton.h"
class BluetoothObexAgent : public BluezQt::ObexAgent
{
Q_OBJECT
public:
explicit BluetoothObexAgent(QObject *parent = nullptr);
~BluetoothObexAgent();
void authorizePush (BluezQt::ObexTransferPtr transfer,BluezQt::ObexSessionPtr session, const BluezQt::Request<QString> &request);
QDBusObjectPath objectPath() const override;
void cancel ();
void release ();
private:
BluezQt::ObexSessionPtr m_session = nullptr;
int daemonIsNotRunning();
QString getTansferDev();
void receiveDisConnectSignal(QString address);
friend class SingleTon<BluetoothObexAgent>;
private slots:
void replyFileReceivingSignalFunc(bool);
void clearOldSession();
void continueRecieveFiles();
void cancelFileReceivingSignalFunc();
void transferredChangedSlot(quint64 size);
void statusChangedSlot(BluezQt::ObexTransfer::Status status);
private:
BluezQt::ObexTransferPtr _Mtransfer;
const BluezQt::Request<QString> *_Mrequest;
BluezQt::ObexSessionPtr _Msession;
BluezQt::ObexSessionPtr oldSession;
};
typedef SingleTon<BluetoothObexAgent> BLUETOOTHOBEXAGENT;
#endif // BLUETOOTHOBEXAGENT_H

View File

@ -3,17 +3,13 @@
BuriedPointData::BuriedPointData(QObject *parent)
:QObject(parent)
{
KyInfo();
m_Thread = new QThread(this);
moveToThread(m_Thread);
qDebug() << __FUNCTION__ << __LINE__;
connect(this,&BuriedPointData::writeInData,this,&BuriedPointData::writeInDataSlot);
m_Thread->start();
}
bool BuriedPointData::buriedSettings(QString pluginName, QString settingsName, QString action, QString value)
{
KyInfo();
//QThread::sleep(5);
qDebug() << __FUNCTION__ << __LINE__;
#ifdef EXISTS_KYSDK_DIAGNOSTICS
// 埋点数据
char appName[] = "ukui-bluetooth";
@ -44,7 +40,7 @@ bool BuriedPointData::buriedSettings(QString pluginName, QString settingsName, Q
}
catch(std::exception &e)
{
KyWarning() << e.what();
qWarning() << Q_FUNC_INFO << e.what() << __LINE__;
return false;
}
#endif
@ -53,11 +49,11 @@ bool BuriedPointData::buriedSettings(QString pluginName, QString settingsName, Q
void BuriedPointData::writeInDataSlot(QString pluginName, QString settingsName, QString action, QString value)
{
KyDebug() << settingsName << action;
qDebug() << __FUNCTION__ << settingsName << action << __LINE__;
if(buriedSettings(pluginName,settingsName,action,value))
KyDebug() << "write data successful";
qDebug() << __FUNCTION__ << "write data successful" << __LINE__;
else
KyDebug() << "write data fail" ;
qDebug() << __FUNCTION__ << "write data fail" << __LINE__;
}

View File

@ -5,11 +5,6 @@
#include <QString>
#include <QTimer>
#include <QDebug>
#include <QThread>
#include <QEventLoop>
#include <ukui-log4qt.h>
#include "CSingleton.h"
#ifdef EXISTS_KYSDK_DIAGNOSTICS
//埋点
@ -22,19 +17,18 @@ class BuriedPointData : public QObject
public:
BuriedPointData(QObject *parent = nullptr);
//void sendWriteInDataSignal(QString,QString);
static bool buriedSettings(QString, QString, QString, QString);
Q_SIGNALS:
void writeInData(QString, QString, QString, QString);
public slots:
void writeInDataSlot(QString , QString , QString , QString);
protected:
bool buriedSettings(QString, QString, QString, QString);
QThread * m_Thread = nullptr;
friend class SingleTon<BuriedPointData>;
private:
bool run_timer_flag = true;
QTimer * m_data_reprot_timer = nullptr;
};
typedef SingleTon<BuriedPointData> BPDMNG;
#endif // BURIEDPOINTDATA_H

View File

@ -1,223 +0,0 @@
#include "common.h"
#include "ukui-log4qt.h"
QStringList list_errmsg =
{
"",
"br-connection-already-connected", //1
"br-connection-page-timeout",
"br-connection-profile-unavailable",
"br-connection-sdp-search",
"br-connection-create-socket",
"br-connection-invalid-argument",
"br-connection-adapter-not-powered",
"br-connection-not-suuported",
"br-connection-bad-socket",
"br-connection-memory-allocation",
"br-connection-busy",
"br-connection-concurrent-connection-limit",
"br-connection-timeout",
"br-connection-refused",
"br-connection-aborted-by-remote",
"br-connection-aborted-by-local",
"br-connection-lmp-protocol-error",
"br-connection-canceled",
"br-connection-unknown",
/////////////////////////////////
"le-connection-invalid-arguments", //20
"le-connection-adapter-not-powered",
"le-connection-not-supported",
"le-connection-already-connected",
"le-connection-bad-socket",
"le-connection-memory-allocation",
"le-connection-busy",
"le-connection-refused",
"le-connection-create-socket",
"le-connection-timeout",
"le-connection-concurrent-connection-limit",
"le-connection-abort-by-remote",
"le-connection-abort-by-local",
"le-connection-link-layer-protocol-error",
"le-connection-gatt-browsing",
"le-connection-unknown",
////////////////////////////////////////////
"Invalid arguments in method call", //36
"Operation already in progress",
"Already Exists",
"Operation is not supported",
"Already Connected",
"Operation currently not available",
"Does Not Exist",
"Not Connected",
"In Progress",
"Operation Not Authorized",
"No such adapter",
"Agent Not Available",
"Resource Not Ready",
////////////////////////////////////////////////
"Did not receive a reply. Possible causes include: "\
"the remote application did not send a reply, "\
"the message bus security policy blocked the reply, "\
"the reply timeout expired, or the network connection was broken.",
/************上面错误码为bluez返回错误码****************/
"ERR_BREDR_INTERNAL_NO_Default_Adapter",
"ERR_BREDR_INTERNAL_Operation_Progress",
"ERR_BREDR_INTERNAL_Already_Connected",
"ERR_BREDR_INTERNAL_Dev_Not_Exist",
"ERR_BREDR_UNKNOWN_Other",
/////////////////////////////////////////////////
};
QStringList Adapter_attr
{
"Pairing",
"Connecting",
"Powered",
"Discoverable",
"Pairable",
"Discovering",
"Name",
"Block",
"Addr",
"ActiveConnection",
"DefaultAdapter",
"trayShow",
"FileTransportSupport",
"ClearPinCode",
};
QStringList Device_attr
{
"Paired",
"Trusted",
"Blocked",
"Connected",
"Name",
"Type",
"TypeName",
"Pairing",
"Connecting",
"Battery",
"ConnectFailedId",
"ConnectFailedDisc",
"Rssi",
"Addr",
"FileTransportSupport",
"ShowName",
"Adapter",
};
QStringList app_attr
{
"dbusid",
"username",
"type",
"pid",
};
QStringList startpair_attr
{
"dev",
"name",
"pincode",
"type",
};
QStringList filestatus_attr
{
"status",
"progress",
"filename",
"allfilenum",
"fileseq",
"dev",
"fileFailedDisc",
"filetype",
"transportType",
"savepath",
"filesize",
};
QStringList receivefile_attr
{
"dev",
"name",
"filetype",
"filename",
"filesize",
};
bool support_a2dp_sink(const QStringList & uuids)
{
if(-1 != uuids.indexOf(A2DP_SINK_UUID) || -1 != uuids.indexOf(QString(A2DP_SINK_UUID).toUpper()))
{
return true;
}
return false;
}
bool support_a2dp_source(const QStringList & uuids)
{
if(-1 != uuids.indexOf(A2DP_SOURCE_UUID) || -1 != uuids.indexOf(QString(A2DP_SOURCE_UUID).toUpper()))
{
return true;
}
return false;
}
bool support_hfphsp_ag(const QStringList & uuids)
{
if(-1 != uuids.indexOf(HFP_AG_UUID) || -1 != uuids.indexOf(QString(HFP_AG_UUID).toUpper()) ||
-1 != uuids.indexOf(HSP_AG_UUID) || -1 != uuids.indexOf(QString(HSP_AG_UUID).toUpper()))
{
return true;
}
return false;
}
bool support_hfphsp_hf(const QStringList & uuids)
{
if(-1 != uuids.indexOf(HFP_HS_UUID) || -1 != uuids.indexOf(QString(HFP_HS_UUID).toUpper()) ||
-1 != uuids.indexOf(HSP_HS_UUID) || -1 != uuids.indexOf(QString(HSP_HS_UUID).toUpper()))
{
return true;
}
return false;
}
static QStringList static_filetransport_uuids
{
//OBEX_SYNC_UUID,
OBEX_OPP_UUID,
OBEX_FTP_UUID,
/*
OBEX_PCE_UUID,
OBEX_PSE_UUID,
OBEX_PBAP_UUID,
OBEX_MAS_UUID,
OBEX_MNS_UUID,
OBEX_MAP_UUID,
*/
};
bool support_filetransport(const QStringList & uuids)
{
for(auto key : static_filetransport_uuids)
{
if(-1 != uuids.indexOf(key) || -1 != uuids.indexOf(key.toUpper()))
{
return true;
}
}
return false;
}

View File

@ -1,262 +0,0 @@
#ifndef COMMON_H
#define COMMON_H
#include <QString>
#include <QStringList>
#include <QMap>
#include <QMetaEnum>
#define A2DP_SOURCE_UUID "0000110a-0000-1000-8000-00805f9b34fb"
#define A2DP_SINK_UUID "0000110b-0000-1000-8000-00805f9b34fb"
#define HSP_HS_UUID "00001108-0000-1000-8000-00805f9b34fb"
#define HSP_AG_UUID "00001112-0000-1000-8000-00805f9b34fb"
#define HFP_HS_UUID "0000111e-0000-1000-8000-00805f9b34fb"
#define HFP_AG_UUID "0000111f-0000-1000-8000-00805f9b34fb"
//#define OBEX_SYNC_UUID "00001104-0000-1000-8000-00805f9b34fb"
#define OBEX_OPP_UUID "00001105-0000-1000-8000-00805f9b34fb"
#define OBEX_FTP_UUID "00001106-0000-1000-8000-00805f9b34fb"
//#define OBEX_PCE_UUID "0000112e-0000-1000-8000-00805f9b34fb"
//#define OBEX_PSE_UUID "0000112f-0000-1000-8000-00805f9b34fb"
//#define OBEX_PBAP_UUID "00001130-0000-1000-8000-00805f9b34fb"
//#define OBEX_MAS_UUID "00001132-0000-1000-8000-00805f9b34fb"
//#define OBEX_MNS_UUID "00001133-0000-1000-8000-00805f9b34fb"
//#define OBEX_MAP_UUID "00001134-0000-1000-8000-00805f9b34fb"
#define GREATERINDEX "greater index"
enum enum_connect_errmsg
{
ERR_BREDR_CONN_SUC,
ERR_BREDR_CONN_ALREADY_CONNECTED = 1,
ERR_BREDR_CONN_PAGE_TIMEOUT,
ERR_BREDR_CONN_PROFILE_UNAVAILABLE,
ERR_BREDR_CONN_SDP_SEARCH,
ERR_BREDR_CONN_CREATE_SOCKET,
ERR_BREDR_CONN_INVALID_ARGUMENTS,
ERR_BREDR_CONN_ADAPTER_NOT_POWERED,
ERR_BREDR_CONN_NOT_SUPPORTED,
ERR_BREDR_CONN_BAD_SOCKET,
ERR_BREDR_CONN_MEMORY_ALLOC,
ERR_BREDR_CONN_BUSY,
ERR_BREDR_CONN_CNCR_CONNECT_LIMIT,
ERR_BREDR_CONN_TIMEOUT,
ERR_BREDR_CONN_REFUSED,
ERR_BREDR_CONN_ABORT_BY_REMOTE,
ERR_BREDR_CONN_ABORT_BY_LOCAL,
ERR_BREDR_CONN_LMP_PROTO_ERROR,
ERR_BREDR_CONN_CANCELED,
ERR_BREDR_CONN_UNKNOWN,
////////////////////////////////////////////
ERR_LE_CONN_INVALID_ARGUMENTS = 20,
ERR_LE_CONN_ADAPTER_NOT_POWERED,
ERR_LE_CONN_NOT_SUPPORTED,
ERR_LE_CONN_ALREADY_CONNECTED,
ERR_LE_CONN_BAD_SOCKET,
ERR_LE_CONN_MEMORY_ALLOC,
ERR_LE_CONN_BUSY,
ERR_LE_CONN_REFUSED,
ERR_LE_CONN_CREATE_SOCKET,
ERR_LE_CONN_TIMEOUT,
ERR_LE_CONN_SYNC_CONNECT_LIMIT,
ERR_LE_CONN_ABORT_BY_REMOTE,
ERR_LE_CONN_ABORT_BY_LOCAL,
ERR_LE_CONN_LL_PROTO_ERROR,
ERR_LE_CONN_GATT_BROWSE,
ERR_LE_CONN_UNKNOWN,
////////////////////////////////////////////////////
ERR_BREDR_Invalid_Arguments = 36,
ERR_BREDR_Operation_Progress,
ERR_BREDR_Already_Exists,
ERR_BREDR_Operation_Not_Supported,
ERR_BREDR_Already_Connected,
ERR_BREDR_Operation_Not_Available,
ERR_BREDR_Does_Not_Exist,
ERR_BREDR_Does_Not_Connected,
ERR_BREDR_Does_In_Progress,
ERR_BREDR_Operation_Not_Authorized,
ERR_BREDR_No_Such_Adapter,
ERR_BREDR_Agent_Not_Available,
ERR_BREDR_Resource_Not_Ready,
/************上面错误码为bluez返回错误码****************/
ERR_BREDR_Bluezqt_DidNot_ReceiveReply,
/////////////////////////////////////////////////
ERR_BREDR_INTERNAL_NO_Default_Adapter,
ERR_BREDR_INTERNAL_Operation_Progress,
ERR_BREDR_INTERNAL_Already_Connected,
ERR_BREDR_INTERNAL_Dev_Not_Exist,
ERR_BREDR_UNKNOWN_Other,
};
enum enum_Adapter_attr
{
enum_Adapter_attr_Pairing = 0,
enum_Adapter_attr_Connecting,
enum_Adapter_attr_Powered,
enum_Adapter_attr_Discoverable,
enum_Adapter_attr_Pairable,
enum_Adapter_attr_Discovering,
enum_Adapter_attr_Name,
enum_Adapter_attr_Block,
enum_Adapter_attr_Addr,
enum_Adapter_attr_ActiveConnection,
enum_Adapter_attr_DefaultAdapter,
enum_Adapter_attr_TrayShow,
enum_Adapter_attr_FileTransportSupport,
enum_Adapter_attr_ClearPinCode,
};
enum enum_device_attr
{
enum_device_attr_Paired = 0,
enum_device_attr_Trusted,
enum_device_attr_Blocked,
enum_device_attr_Connected,
enum_device_attr_Name,
enum_device_attr_Type,
enum_device_attr_TypeName,
enum_device_attr_Pairing,
enum_device_attr_Connecting,
enum_device_attr_Battery,
enum_device_attr_ConnectFailedId,
enum_device_attr_ConnectFailedDisc,
enum_device_attr_Rssi,
enum_device_attr_Addr,
enum_device_attr_FileTransportSupport,
enum_device_attr_ShowName,
enum_device_attr_Adapter,
};
enum enum_app_attr
{
enum_app_attr_dbusid = 0,
enum_app_attr_username,
enum_app_attr_type,
enum_app_attr_pid,
};
enum enum_app_type_bluetooth
{
enum_app_type_bluetooth_controlPanel = 0, //蓝牙控制面板
enum_app_type_bluetooth_tray, //蓝牙托盘
enum_app_type_bluetooth_other = 0xff,
};
enum enum_start_pair
{
enum_start_pair_dev = 0,
enum_start_pair_name,
enum_start_pair_pincode,
enum_start_pair_type,
};
enum enum_pair_pincode_type
{
enum_pair_pincode_type_request = 0,
enum_pair_pincode_type_display,
};
/**
* @brief
*
*/
enum enum_send_type
{
enum_send_type_delay = 0,
enum_send_type_immediately,
};
enum enum_filestatus
{
enum_filestatus_status = 0,
enum_filestatus_progress,
enum_filestatus_filename,
enum_filestatus_allfilenum,
enum_filestatus_fileseq,
enum_filestatus_dev,
enum_filestatus_fileFailedDisc,
enum_filestatus_filetype,
enum_filestatus_transportType,
enum_filestatus_savepath,
enum_filestatus_filesize,
};
enum enum_filetransport_Type
{
enum_filetransport_Type_send = 0,
enum_filetransport_Type_receive,
enum_filetransport_Type_other,
};
enum enum_receivefile
{
enum_receivefile_dev = 0,
enum_receivefile_name,
enum_receivefile_filetype,
enum_receivefile_filename,
enum_receivefile_filesize,
};
extern QStringList Adapter_attr;
#define AdapterAttr(i) (((Adapter_attr.size()>i))?Adapter_attr[i]:GREATERINDEX)
#define AdapterAttrIndex(str) (Adapter_attr.indexOf(str))
extern QStringList Device_attr;
#define DeviceAttr(i) (((Device_attr.size()>i))?Device_attr[i]:GREATERINDEX)
#define DeviceAttrIndex(str) (Device_attr.indexOf(str))
extern QStringList list_errmsg;
#define get_enum_errmsg(str) (list_errmsg.indexOf(str))
#define get_enum_errmsg_str(i) (((list_errmsg.size()>i))?list_errmsg[i]:GREATERINDEX)
extern QStringList app_attr;
#define AppAttr(i) (((app_attr.size()>i))?app_attr[i]:GREATERINDEX)
#define AppAttrIndex(str) (app_attr.indexOf(str))
extern QStringList startpair_attr;
#define PairAttr(i) (((startpair_attr.size()>i))?startpair_attr[i]:GREATERINDEX)
#define PairAttrIndex(str) (startpair_attr.indexOf(str))
extern QStringList filestatus_attr;
#define FileStatusAttr(i) (((filestatus_attr.size()>i))?filestatus_attr[i]:GREATERINDEX)
#define FileStatusAttrIndex(str) (filestatus_attr.indexOf(str))
extern QStringList receivefile_attr;
#define ReceiveFileAttr(i) (((receivefile_attr.size()>i))?receivefile_attr[i]:GREATERINDEX)
#define ReceiveFileAttrIndex(str) (receivefile_attr.indexOf(str))
/**
* @brief
*
* @param
* @return true or false
*/
bool support_a2dp_sink(const QStringList &);
bool support_a2dp_source(const QStringList &);
bool support_hfphsp_ag(const QStringList &);
bool support_hfphsp_hf(const QStringList &);
bool support_filetransport(const QStringList &);
#endif // COMMON_H

View File

@ -1,290 +1,179 @@
#include "config.h"
#include <QDBusContext>
#include <QDBusConnection>
#include <QDBusConnectionInterface>
#include <QDBusReply>
Environment envPC = Environment::NOMAL;
#define CONF_FILE_FULLPATH "/etc/bluetooth/ukui-bluetooth.conf"
#define CONF_STR_BLUETOOTH_POWER_SWTICH "switch"
#define CONF_STR_BLUETOOTH_DISCOVERABLE_SWTICH "bluetoothDiscoverableSwitch"
#define CONF_STR_FINALLY_CONNECT_THE_DEVICE "finallyConnectTheDevice"
#define CONF_STR_ADAPTER_ADDRESS "adapterAddress"
#define CONF_STR_FILE_SAVE_PATH "fileSavePath"
#define CONF_STR_ADAPTER_ADDRESS_LIST "adapterAddressList"
#define CONF_STR_ACTIVE_CONNECTION "activeConnection"
#define CONF_STR_TRAY_SHOW "trayShow"
#define CONF_LOG_LEVEL "loglevel"
const QString UIExe = "/usr/bin/ukui-bluetooth";
QProcess *process = nullptr;
QGSettings* Config::gsetting = new QGSettings(GSETTING_SCHEMA_UKUIBLUETOOH);
QGSettings* Config::ukccGsetting = new QGSettings(GSETTING_SCHEMA_UKCC,GSETTING_PACH_UKCC);
Config::Config(QObject *parent)
:QObject(parent)
{
m_ukui_bluetooth = new QSettings(CONF_FILE_FULLPATH, QSettings::IniFormat);
QStringList groups = m_ukui_bluetooth->childGroups();
KyInfo() << groups;
if(groups.indexOf("conf") == -1)
{
KyInfo() << "create and init conf";
m_ukui_bluetooth->beginGroup("conf");
this->init_conf();
}
else
{
m_ukui_bluetooth->beginGroup("conf");
this->init_conf();
}
}
Config::~Config()
{
delete m_ukui_bluetooth;
m_ukui_bluetooth = nullptr;
delete gsetting;
}
void Config::init_conf()
void Config::SendNotifyMessage(QString message)
{
if(!m_ukui_bluetooth->contains(CONF_STR_BLUETOOTH_POWER_SWTICH))
{
KyInfo() << "add conf: " << CONF_STR_BLUETOOTH_POWER_SWTICH;
m_ukui_bluetooth->setValue(CONF_STR_BLUETOOTH_POWER_SWTICH, false);
}
QDBusInterface iface("org.freedesktop.Notifications",
"/org/freedesktop/Notifications",
"org.freedesktop.Notifications",
QDBusConnection::sessionBus());
QList<QVariant> args;
args<<tr("Bluetooth")
<<((unsigned int) 0)
<<"bluetooth"
<<tr("Bluetooth message") //显示的是什么类型的信息
<<message //显示的具体信息
<<QStringList()
<<QVariantMap()
<<(int)-1;
QDBusMessage msg = iface.callWithArgumentList(QDBus::AutoDetect,"Notify",args);
qDebug() << Q_FUNC_INFO << msg.errorMessage();
}
if(!m_ukui_bluetooth->contains(CONF_STR_BLUETOOTH_DISCOVERABLE_SWTICH))
{
KyInfo() << "add conf: " << CONF_STR_BLUETOOTH_DISCOVERABLE_SWTICH;
m_ukui_bluetooth->setValue(CONF_STR_BLUETOOTH_DISCOVERABLE_SWTICH, true);
}
void Config::OpenBluetoothSettings()
{
qDebug() << Q_FUNC_INFO << __LINE__;
//mavis 需要区分
if (Environment::MAVIS == envPC){
if(!m_ukui_bluetooth->contains(CONF_STR_FINALLY_CONNECT_THE_DEVICE))
{
KyInfo() << "add conf: " << CONF_STR_FINALLY_CONNECT_THE_DEVICE;
m_ukui_bluetooth->setValue(CONF_STR_FINALLY_CONNECT_THE_DEVICE, "");
}
QDBusInterface *m_statusSessionDbus = new QDBusInterface("com.kylin.statusmanager.interface",
"/",
"com.kylin.statusmanager.interface",
QDBusConnection::sessionBus());
if(!m_ukui_bluetooth->contains(CONF_STR_ADAPTER_ADDRESS))
{
KyInfo() << "add conf: " << CONF_STR_ADAPTER_ADDRESS;
m_ukui_bluetooth->setValue(CONF_STR_ADAPTER_ADDRESS, "");
}
if (m_statusSessionDbus->isValid())
{
qInfo() << Q_FUNC_INFO << "is_tabletmode" << __LINE__;
if(!m_ukui_bluetooth->contains(CONF_STR_FILE_SAVE_PATH))
{
KyInfo() << "add conf: " << CONF_STR_FILE_SAVE_PATH;
m_ukui_bluetooth->setValue(CONF_STR_FILE_SAVE_PATH, "");
QDBusReply<bool> is_tabletmode = m_statusSessionDbus->call("get_current_tabletmode");
if (is_tabletmode)
AppManagerToOpenBluetoothSettings();
else
CommandToOpenBluetoothSettings();
}
else
CommandToOpenBluetoothSettings();
}
else
CommandToOpenBluetoothSettings();
}
if(!m_ukui_bluetooth->contains(CONF_STR_ADAPTER_ADDRESS_LIST))
{
KyInfo() << "add conf: " << CONF_STR_ADAPTER_ADDRESS_LIST;
QStringList t;
t.append("null");
m_ukui_bluetooth->setValue(CONF_STR_ADAPTER_ADDRESS_LIST, t);
}
void Config::AppManagerToOpenBluetoothSettings()
{
qInfo () << Q_FUNC_INFO << "" << __LINE__;
if(!m_ukui_bluetooth->contains(CONF_STR_ACTIVE_CONNECTION))
{
KyInfo() << "add conf: " << CONF_STR_ACTIVE_CONNECTION;
m_ukui_bluetooth->setValue(CONF_STR_ACTIVE_CONNECTION, true);
}
QDBusMessage m = QDBusMessage::createMethodCall("com.kylin.AppManager",
"/com/kylin/AppManager",
"com.kylin.AppManager",
"LaunchAppWithArguments");
m<< QString("ukui-control-center.desktop") << QStringList{"-m","Bluetooth"};
// qDebug() << Q_FUNC_INFO << m.arguments().at(0).value<QString>() <<__LINE__;
// 发送Message
QDBusConnection::sessionBus().call(m, QDBus::NoBlock);
if(!m_ukui_bluetooth->contains(CONF_STR_TRAY_SHOW))
}
void Config::CommandToOpenBluetoothSettings()
{
qInfo () << Q_FUNC_INFO << "" << __LINE__;
QProcess *process = new QProcess();
QString cmd = "ukui-control-center";
QStringList arg;
arg.clear();
arg << "-m";
arg << "Bluetooth";
qDebug() << Q_FUNC_INFO << arg;
process->startDetached(cmd,arg);
}
void Config::LaunchUI()
{
if(nullptr == process)
{
KyInfo() << "add conf: " << CONF_STR_TRAY_SHOW;
m_ukui_bluetooth->setValue(CONF_STR_TRAY_SHOW, true);
process = new QProcess();
QString cmd = UIExe;
qDebug() << Q_FUNC_INFO;
QTimer::singleShot(700, process, [=]{
process->startDetached(cmd);
});
}
}
int Config::init()
QStringList Config::getDeviceConnectTimeList(QString path)
{
if(m_ukui_bluetooth->contains(CONF_STR_BLUETOOTH_POWER_SWTICH))
{
m_power_switch = m_ukui_bluetooth->value(CONF_STR_BLUETOOTH_POWER_SWTICH).toBool();
KyInfo() << CONF_STR_BLUETOOTH_POWER_SWTICH << m_power_switch;
QStringList pair_device_list;
pair_device_list.clear();
if(!QFile::exists(path))
return pair_device_list;
QVector<int> pair_device_time_list;
pair_device_time_list.clear();
GKeyFile *key_file = nullptr;
key_file = g_key_file_new();
g_key_file_load_from_file(key_file,QString(path).toStdString().c_str(),G_KEY_FILE_NONE,NULL);
gchar **list;
bool ok;
list = g_key_file_get_groups(key_file,NULL);
for(int i = 0; list[i] != NULL; i++){
pair_device_list.append(QString::fromUtf8(list[i]));
pair_device_time_list.append(QString::fromUtf8(g_key_file_get_string(key_file,list[i],"ConnectTime",NULL)).toInt(&ok,10));
}
if(m_ukui_bluetooth->contains(CONF_STR_BLUETOOTH_DISCOVERABLE_SWTICH))
{
m_discoverable_switch = m_ukui_bluetooth->value(CONF_STR_BLUETOOTH_DISCOVERABLE_SWTICH).toBool();
KyInfo() << CONF_STR_BLUETOOTH_DISCOVERABLE_SWTICH << m_discoverable_switch;
//*****************给从配置文件中得到的设备列表和设备对应的最后连接时间列表排序***********START**************
for(int i = 0; i < pair_device_time_list.length(); i++){
for(int j = 0; j < pair_device_time_list.length()-i-1; j++){
if(pair_device_time_list.at(j) < pair_device_time_list.at(j+1)){
int max = pair_device_time_list.at(j);
pair_device_time_list.replace(j,pair_device_time_list.at(j+1));
pair_device_time_list.replace(j+1,max);
QString target = pair_device_list.at(j);
pair_device_list.removeAt(j);
pair_device_list.insert(j+1,target);
}
}
}
//************************************ END ******************************************************
if(m_ukui_bluetooth->contains(CONF_STR_FINALLY_CONNECT_THE_DEVICE))
{
m_finally_audiodevice = m_ukui_bluetooth->value(CONF_STR_FINALLY_CONNECT_THE_DEVICE).toString();
KyInfo() << CONF_STR_FINALLY_CONNECT_THE_DEVICE << m_finally_audiodevice;
}
g_key_file_free(key_file);
if(m_ukui_bluetooth->contains(CONF_STR_ADAPTER_ADDRESS))
{
m_adapter_addr = m_ukui_bluetooth->value(CONF_STR_ADAPTER_ADDRESS).toString();
KyInfo() << CONF_STR_ADAPTER_ADDRESS << m_adapter_addr;
}
return pair_device_list;
}
if(m_ukui_bluetooth->contains(CONF_STR_FILE_SAVE_PATH))
{
m_file_save_path = m_ukui_bluetooth->value(CONF_STR_FILE_SAVE_PATH).toString();
KyInfo() << CONF_STR_FILE_SAVE_PATH << m_file_save_path;
}
void Config::writeKeyFile(QString addr, QString name, qint32 type)
{
qDebug() << Q_FUNC_INFO << addr << name << type;
QDBusMessage m = QDBusMessage::createMethodCall("com.bluetooth.systemdbus", "/", "com.bluetooth.interface", "writeKeyFile");
m << addr << name << type;
QDBusMessage response = QDBusConnection::systemBus().call(m);
qDebug() << Q_FUNC_INFO << addr << name << type << response.errorMessage();
}
if(m_ukui_bluetooth->contains(CONF_STR_ACTIVE_CONNECTION))
{
m_activeconnection = m_ukui_bluetooth->value(CONF_STR_ACTIVE_CONNECTION).toBool();
KyInfo() << CONF_STR_ACTIVE_CONNECTION << m_activeconnection;
}
void Config::removeKey(QString addr)
{
qDebug() << Q_FUNC_INFO << addr;
QDBusMessage m = QDBusMessage::createMethodCall("com.bluetooth.systemdbus", "/", "com.bluetooth.interface", "removeKeyFile");
m << addr;
QDBusMessage response = QDBusConnection::systemBus().call(m);
qDebug() << Q_FUNC_INFO << addr << response.errorMessage();
if(m_ukui_bluetooth->contains(CONF_STR_TRAY_SHOW))
{
m_tray_show = m_ukui_bluetooth->value(CONF_STR_TRAY_SHOW).toBool();
KyInfo() << CONF_STR_TRAY_SHOW << m_tray_show;
}
}
if(m_ukui_bluetooth->contains(CONF_LOG_LEVEL))
{
m_loglevel = m_ukui_bluetooth->value(CONF_LOG_LEVEL).toString();
KyInfo() << CONF_LOG_LEVEL << m_loglevel;
}
m_active_user = this->getActiveUser();
KyInfo()<< "active user: "<< m_active_user;
//m_file_watch = new QFileSystemWatcher(QStringList(CONF_FILE_FULLPATH));
//connect(m_file_watch, &QFileSystemWatcher::fileChanged, this, &Config::fileChanged);
//KyInfo() << "monistor: "<< m_file_watch->files();
this->init_rename();
int Config::writeNewConf(QMap<QString, QVariant> attrs)
{
qDebug() << Q_FUNC_INFO << attrs;
QDBusMessage m = QDBusMessage::createMethodCall("com.bluetooth.systemdbus", "/", "com.bluetooth.interface", "writeNewConf");
m << attrs;
QDBusMessage response = QDBusConnection::systemBus().call(m);
return 0;
}
void Config::power_switch(bool v)
{
m_power_switch = v;
m_ukui_bluetooth->setValue(CONF_STR_BLUETOOTH_POWER_SWTICH, v);
}
void Config::discoverable_switch(bool v)
{
m_discoverable_switch = v;
m_ukui_bluetooth->setValue(CONF_STR_BLUETOOTH_DISCOVERABLE_SWTICH, v);
}
void Config::finally_audiodevice(QString v)
{
m_finally_audiodevice = v;
m_ukui_bluetooth->setValue(CONF_STR_FINALLY_CONNECT_THE_DEVICE, v);
}
void Config::adapter_addr(QString v)
{
m_adapter_addr = v;
m_ukui_bluetooth->setValue(CONF_STR_ADAPTER_ADDRESS, v);
}
void Config::file_save_path(QString v)
{
m_file_save_path = v;
m_ukui_bluetooth->setValue(CONF_STR_FILE_SAVE_PATH, v);
}
void Config::activeconnection(bool v)
{
m_activeconnection = v;
m_ukui_bluetooth->setValue(CONF_STR_ACTIVE_CONNECTION, v);
}
void Config::trayShow(bool v)
{
m_tray_show = v;
m_ukui_bluetooth->setValue(CONF_STR_TRAY_SHOW, v);
}
void Config::loglevel(QString v)
{
m_loglevel = v;
m_ukui_bluetooth->setValue(CONF_LOG_LEVEL, v);
}
void Config::set_rename(QString addr, QString name)
{
m_rename[addr] = name;
QSettings s(CONF_FILE_FULLPATH, QSettings::IniFormat);
s.beginGroup("rename");
s.setValue(addr, name);
s.endGroup();
}
QString Config::get_rename(QString v)
{
if(m_rename.contains(v))
{
return m_rename[v];
}
return "";
}
void Config::delete_rename(QString addr)
{
if(m_rename.contains(addr))
{
QSettings s(CONF_FILE_FULLPATH, QSettings::IniFormat);
s.beginGroup("rename");
s.remove(addr);
s.endGroup();
m_rename.remove(addr);
}
}
void Config::init_rename()
{
QSettings s(CONF_FILE_FULLPATH, QSettings::IniFormat);
s.beginGroup("rename");
QStringList keys = s.allKeys();
for(auto iter : keys)
{
m_rename[iter] = s.value(iter).toString();
}
KyDebug() << m_rename;
s.endGroup();
}
QString Config::getActiveUser()
{
QString user;
QDBusInterface iface("org.ukui.test",
"/com/ukui/test",
"com.ukui.test",
QDBusConnection::systemBus());
QDBusPendingCall pcall = iface.asyncCall("GetActiveUser");
pcall.waitForFinished();
QDBusMessage res = pcall.reply();
if(res.type() == QDBusMessage::ReplyMessage)
{
if(res.arguments().size() > 0)
{
user = res.arguments().takeFirst().toString();
}
}
else
{
qWarning()<< res.errorName() << ": "<< res.errorMessage();
}
return user;
}

View File

@ -2,6 +2,7 @@
#define CONFIG_H
#include <QObject>
#include <QGSettings>
#include <QString>
#include <QByteArray>
#include <QDBusInterface>
@ -11,8 +12,6 @@
#include <QFile>
#include <QTimer>
#include <QDBusReply>
#include <QSettings>
#include <QFileSystemWatcher>
extern "C"
{
@ -20,8 +19,6 @@ extern "C"
#include <glib.h>
#include <glib/gprintf.h>
}
#include "ukui-log4qt.h"
#include "CSingleton.h"
//全局变量,是否是华为机器, 默认false, 在config.cpp文件定义
enum Environment
@ -34,13 +31,20 @@ enum Environment
//gsetting name define
//名称请勿随意改动会导致升级时获取的gsetting值不一致
#define GSETTING_STR_BLUETOOTH_POWER_SWTICH "switch"
#define GSETTING_STR_BLUETOOTH_DISCOVERABLE_SWTICH "bluetooth-discoverable-switch"
#define GSETTING_STR_FINALLY_CONNECT_THE_DEVICE "finally-connect-the-device"
#define GSETTING_STR_ADAPTER_ADDRESS "adapter-address"
#define GSETTING_STR_FILE_SAVE_PATH "file-save-path"
#define GSETTING_STR_ADAPTER_ADDRESS_LIST "adapter-address-list"
#define GSETTING_STR_ACTIVE_CONNECTION "active-connection"
#define GSETTING_STR_ACTIVE_CONNECTION_TRAN "activeConnection"
#define GSETTING_SCHEMA_UKUIBLUETOOH "org.ukui.bluetooth"
#define GSETTING_SCHEMA_UKCC "org.ukui.control-center.plugins"
#define GSETTING_PACH_UKCC "/org/ukui/control-center/plugins/Bluetooth/"
extern Environment envPC;
class Config : public QObject
@ -49,97 +53,21 @@ public:
Config(QObject *parent = nullptr);
~Config();
int init(void);
bool power_switch(void){ return m_power_switch; }
void power_switch(bool);
bool discoverable_switch(void){ return m_discoverable_switch; }
void discoverable_switch(bool);
QString finally_audiodevice(void){ return m_finally_audiodevice; }
void finally_audiodevice(QString);
QString adapter_addr(void){ return m_adapter_addr; }
void adapter_addr(QString);
QString file_save_path(void){ return m_file_save_path; }
void file_save_path(QString);
bool activeconnection(void){ return m_activeconnection; }
void activeconnection(bool);
bool trayShow(void){ return m_tray_show; }
void trayShow(bool);
QString loglevel(void){ return m_loglevel; }
void loglevel(QString);
/////////////////////////////////////////////////////////
bool bluetooth_block(void){ return m_bluetooth_block; }
void bluetooth_block(bool v){ m_bluetooth_block = v; }
bool systemSleepFlag(void){ return m_systemSleepFlag; }
void systemSleepFlag(bool v){ m_systemSleepFlag = v; }
bool showBluetooth(void){ return m_showBluetooth; }
void showBluetooth(bool v){ m_showBluetooth = v; }
QString active_user(void){ return m_active_user; }
void active_user(QString v){ m_active_user = v; }
void set_rename(QString, QString);
QString get_rename(QString);
void delete_rename(QString);
protected slots:
void fileChanged(const QString &path);
static QGSettings *gsetting;
static QGSettings *ukccGsetting;
static void SendNotifyMessage(QString);
static void OpenBluetoothSettings();
static void CommandToOpenBluetoothSettings();
static void AppManagerToOpenBluetoothSettings();
static void LaunchUI();
static QStringList getDeviceConnectTimeList(QString);
static void writeKeyFile(QString,QString,qint32);
static void removeKey(QString);
static int writeNewConf(QMap<QString, QVariant>);
private:
void init_rename(void);
void init_conf(void);
protected:
QString getActiveUser(void);
QSettings * m_ukui_bluetooth = nullptr;
QFileSystemWatcher * m_file_watch = nullptr;
private:
bool m_power_switch = false;
bool m_discoverable_switch = true;
QString m_finally_audiodevice;
QString m_adapter_addr;
QString m_file_save_path;
bool m_activeconnection = false;
bool m_tray_show = true;
QString m_loglevel;
//内部属性
bool m_bluetooth_block = false;
bool m_systemSleepFlag = false;
bool m_showBluetooth = false;
QString m_active_user;
//别名
QMap<QString, QString> m_rename;
friend class SingleTon<Config>;
QString setting_name;
};
typedef SingleTon<Config> CONFIG;
#endif // CONFIG_H

File diff suppressed because it is too large Load Diff

View File

@ -4,6 +4,7 @@
#include "bluetoothagent.h"
#include "bluetoothobexagent.h"
#include "config.h"
#include "rfkill.h"
#include "buriedpointdata.h"
#ifdef BATTERY
@ -39,8 +40,17 @@
#include <QDBusConnection>
#include <QThread>
#include <QEventLoop>
#include "ukui-log4qt.h"
#include "CSingleton.h"
enum DevOperate {
PAIR = 0,
CONNECT,
DISCONNECT,
REMOVE,
TRUST,
ERROR,
};
class Daemon : public QObject
{
@ -49,47 +59,78 @@ public:
explicit Daemon(QObject *parent = nullptr);
~Daemon();
int start(void);
static BluezQt::AdapterPtr _DefualtAdapter;
static BluezQt::Manager *_BluezManager;
int stop(void);
static void setBluetoothBlock(bool);
// static void devOperateFunc(const QString,const DevOperate,const bool value = false);
// static void sendDevSignal(DevOperate,QString);
static QDBusMessage createCustomSignalMsg(QString);
static void reconnectFunc();
static void devConnectSignalDbus(QString);
int unblock_bluetooth(void);
static void sendWriteInData(QString,QString,QString,QString);
protected:
int init_bluez(void);
public:
void setDefaultDiscoverble();
int init_obex(void);
void launchDefaultBluetooth(void);
int init_sys_monistor(void);
private:
int __init_bluez_adapter(void);
Q_SIGNALS:
void startThread();
void writeInData(QString,QString,QString,QString);
protected slots:
//bluez
void operationalChanged(bool operational);
void bluetoothOperationalChanged(bool operational);
void bluetoothBlockedChanged(bool blocked);
void adapterAdded(BluezQt::AdapterPtr adapter);
void adapterRemoved(BluezQt::AdapterPtr adapter);
void usableAdapterChanged(BluezQt::AdapterPtr adapter);
void allAdaptersRemoved();
//sleep
private slots:
void gsettingsChangedSlot(const QString &);
void rfkillStatusChange(int);
void sendFile(QString,QString);
void closeSession();
void continueSendFiles(QString filename);
void monitorSleepSlot(bool);
void activeUserChange(QString);
private:
void __unblock_sleep(int);
void initGSettingInfo();
int initBluezManager();
void registerBluezAgent();
void fileTransferSessionCreator(QString,QString);
void initObexManager();
void registerObexAgent();
void launchTrayUI();
BluezQt::AdapterPtr getDefualtAdapter();
// void connectDefualtSignal();
void monitorDbusSignal();
void launchDbusSignal();
void wait_for_finish(BluezQt::PendingCall *call);
protected:
BluezQt::Manager * m_bluez = nullptr;
void __launch_bluetooth(void);
friend class SingleTon<Daemon>;
QString getFileName();
Rfkill *_rfkill = nullptr;
QThread *_rfkillThread = nullptr;
Config *_mConfig = nullptr;
QMap<QString,QVariant> _mGsetting;
BuriedPointData *_buriedPointData = nullptr;
QThread *_buriedPointDataThread = nullptr;
// QDBusMessage devScanSignal;
// QDBusMessage adapterPowerSignal;
// QDBusMessage adapterDiscoverableSignal;
// QDBusMessage adapterScanStatusSignal;
QString selected_file;
QDBusObjectPath pre_session;
quint64 transfer_file_size = 0;
BluezQt::ObexObjectPush *opp = nullptr;
BluezQt::ObexTransferPtr filePtr = nullptr;
BluezQt::ObexManager *_ObexManager = nullptr;
BluetoothAgent *_BluezAgent = nullptr;
BluetoothObexAgent *_ObexAgent = nullptr;
QString transferDev;
// BluetoothFileTransferWidget *transfer_widget = nullptr;
};
typedef SingleTon<Daemon> DAEMON;
#endif // DAEMON_H

View File

@ -1,840 +0,0 @@
#include "device.h"
#include <QThread>
#include <QEventLoop>
#include <QTimerEvent>
#include "sessiondbusregister.h"
#include "adapter.h"
#include "config.h"
class BluezQt::MediaTransport{};
KylinDevice::KylinDevice(BluezQt::DevicePtr device, QString adapter)
{
m_device = device;
m_adapter = adapter;
connect(m_device.data(), &BluezQt::Device::nameChanged, this, &KylinDevice::nameChanged);
connect(m_device.data(), &BluezQt::Device::pairedChanged, this, &KylinDevice::pairedChanged);
connect(m_device.data(), &BluezQt::Device::trustedChanged, this, &KylinDevice::trustedChanged);
connect(m_device.data(), &BluezQt::Device::blockedChanged, this, &KylinDevice::blockedChanged);
connect(m_device.data(), &BluezQt::Device::rssiChanged, this, &KylinDevice::rssiChanged);
connect(m_device.data(), &BluezQt::Device::connectedChanged, this, &KylinDevice::connectedChanged);
connect(m_device.data(), &BluezQt::Device::batteryChanged, this, &KylinDevice::batteryChanged);
connect(m_device.data(), &BluezQt::Device::typeChanged, this, &KylinDevice::typeChanged);
connect(m_device.data(), &BluezQt::Device::uuidsChanged, this, &KylinDevice::uuidsChanged);
connect(m_device.data(), &BluezQt::Device::mediaTransportChanged, this, &KylinDevice::mediaTransportChanged);
m_a2dp_connect =m_device->mediaTransport() ? true : false;
KyDebug() << m_device->address() << " a2dp_connect : " << m_a2dp_connect;
m_paired = m_device->isPaired();
if(m_paired)
{
m_connect = m_device->isConnected();
}
m_uuids = m_device->uuids();
m_showName = CONFIG::getInstance()->get_rename(m_device->address());
this->__send_add();
this->__init_uuid();
}
KylinDevice::~KylinDevice()
{
KyDebug() << m_device->address();
m_device->disconnect(this);
if(0 != m_attrsignal_TimerID)
{
this->killTimer(m_attrsignal_TimerID);
m_attrsignal_TimerID = 0;
}
this->__kill_reconnect_a2dp_timer();
}
int KylinDevice::start()
{
this->deal_active_connection();
return 0;
}
int KylinDevice::devConnect(int type /*= 0*/)
{
KyInfo()<< m_device->address();
m_need_clean = 0;
m_lastConnectError = "";
m_connect_type = type;
if(m_connectProgress)
{
return ERR_BREDR_INTERNAL_Operation_Progress;
}
m_connectProgress = true;
m_attr_send[DeviceAttr(enum_device_attr_Connecting)] = m_connectProgress;
this->__send_attr(enum_send_type_immediately);
this->__kill_reconnect_a2dp_timer();
int ret = ERR_BREDR_CONN_SUC;
if(m_device->isPaired())
{
if(Environment::HUAWEI == envPC)
{
if(m_device->type() != BluezQt::Device::Computer && m_device->type() != BluezQt::Device::Phone)
{
ret = this->connectToDevice();
}
}
else
{
ret = this->connectToDevice();
}
}
else
{
ret = this->pair();
if(ERR_BREDR_CONN_SUC == ret)
{
if(Environment::HUAWEI == envPC)
{
if(m_device->type() != BluezQt::Device::Computer && m_device->type() != BluezQt::Device::Phone)
{
ret = this->connectToDevice();
}
}
else
{
ret = this->connectToDevice();
}
}
}
m_connectProgress = false;
m_attr_send[DeviceAttr(enum_device_attr_Connecting)] = m_connectProgress;
this->__send_attr(enum_send_type_immediately);
return ret;
}
int KylinDevice::devDisconnect()
{
KyInfo()<< m_device->address();
m_need_clean = 0;
this->__kill_reconnect_a2dp_timer();
if((m_device->isPaired() && m_device->isConnected()) || m_connect)
{
BluezQt::PendingCall *call = m_device->disconnectFromDevice();
//this->wait_for_finish(call);
}
return ERR_BREDR_CONN_SUC;
}
int KylinDevice::pairFuncReply(bool v)
{
KyInfo()<< m_device->address() << v;
if(v)
{
m_request.accept();
}
else
{
m_request.reject();
}
return 0;
}
void KylinDevice::requestPinCode(const BluezQt::Request<QString> &request)
{
KyInfo()<< m_device->address();
request.accept(QString());
}
void KylinDevice::requestPasskey(const BluezQt::Request<quint32> &request)
{
KyInfo()<< m_device->address();
request.accept(0);
}
void KylinDevice::requestConfirmation(const QString &passkey, const BluezQt::Request<> &request)
{
KyInfo()<< m_device->address();
if(this->isAudioType())
{
request.accept();
}
else
{
m_request = request;
QMap<QString, QVariant> attrs;
attrs[PairAttr(enum_start_pair_dev)] = m_device->address();
attrs[PairAttr(enum_start_pair_name)] = m_device->name();
attrs[PairAttr(enum_start_pair_pincode)] = passkey;
attrs[PairAttr(enum_start_pair_type)] = enum_pair_pincode_type_request;
emit SYSDBUSMNG::getInstance()->startPair(attrs);
//request.accept();
}
}
void KylinDevice::requestAuthorization(const BluezQt::Request<> &request)
{
KyInfo()<< m_device->address();
request.accept();
}
void KylinDevice::authorizeService(const QString &uuid, const BluezQt::Request<> &request)
{
KyInfo()<< m_device->address() << uuid;
if(this->isAudioType())
{
//主动连接, 信任状态
if(m_device->isTrusted())
{
request.accept();
}
//本机移除后再连接
else
{
request.reject();
}
}
else
{
request.accept();
m_connect = true;
m_attr_send[DeviceAttr(enum_device_attr_Connected)] = m_connect;
this->__send_attr();
}
}
void KylinDevice::displayPinCode(const QString &pinCode)
{
KyInfo()<< m_device->address();
//if(m_connectProgress)
{
QMap<QString, QVariant> attrs;
attrs[PairAttr(enum_start_pair_dev)] = m_device->address();
attrs[PairAttr(enum_start_pair_name)] = m_device->name();
attrs[PairAttr(enum_start_pair_pincode)] = pinCode;
attrs[PairAttr(enum_start_pair_type)] = enum_pair_pincode_type_display;
emit SYSDBUSMNG::getInstance()->startPair(attrs);
}
}
bool KylinDevice::needClean()
{
if(m_connect || m_paired || m_connectProgress || m_pairProgress || m_device->isPaired() || m_device->isConnected())
{
return false;
}
if(m_need_clean > 3)
{
KyDebug() << m_device->address() << "need delete";
return true;
}
m_need_clean++;
return false;
}
bool KylinDevice::isAudioType()
{
if(m_device->type() == BluezQt::Device::AudioVideo ||
m_device->type() == BluezQt::Device::Headphones ||
m_device->type() == BluezQt::Device::Headset)
{
return true;
}
return false;
}
int KylinDevice::reset()
{
m_need_clean = 0;
return 0;
}
void KylinDevice::setSendfileStatus()
{
if(!m_connect)
{
m_connect = true;
m_attr_send[DeviceAttr(enum_device_attr_Connected)] = m_connect;
this->__send_attr();
}
}
void KylinDevice::nameChanged(const QString &name)
{
m_need_clean = 0;
m_attr_send[DeviceAttr(enum_device_attr_Name)] = name;
this->__send_attr();
}
void KylinDevice::pairedChanged(bool paired)
{
m_need_clean = 0;
KyInfo() << m_device->address() <<", paired: "<< paired;
if(this->isAudioType())
{
if(m_pairProgress || m_paired)
{
m_paired = paired;
m_attr_send[DeviceAttr(enum_device_attr_Paired)] = paired;
this->__send_attr();
}
else
{
//移除设备
KylinAdapterPtr adapterPtr = ADAPTERMNG::getInstance()->getDefaultAdapter();
if(adapterPtr)
{
KyInfo() << m_device->address() << "active connect, delete dev";
adapterPtr->__devRemove(m_device->address());
}
}
}
else
{
m_paired = paired;
m_attr_send[DeviceAttr(enum_device_attr_Paired)] = paired;
this->__send_attr();
}
}
void KylinDevice::trustedChanged(bool trusted)
{
m_need_clean = 0;
m_attr_send[DeviceAttr(enum_device_attr_Trusted)] = trusted;
this->__send_attr();
}
void KylinDevice::blockedChanged(bool blocked)
{
m_need_clean = 0;
}
void KylinDevice::rssiChanged(qint16 rssi)
{
m_need_clean = 0;
if(-rssi > 0 && -rssi < 100 )
{
//this->deal_active_connection();
m_attr_send[DeviceAttr(enum_device_attr_Rssi)] = rssi;
this->__send_attr();
}
}
void KylinDevice::connectedChanged(bool connected)
{
m_need_clean = 0;
KyInfo() << m_device->address() << connected;
if(Environment::HUAWEI == envPC)
{
if(BluezQt::Device::Computer == m_device->type() ||
BluezQt::Device::Phone == m_device->type() )
{
if(connected && m_device->isPaired())
{
KyInfo() << m_device->address() << " disconnect, HUAWEI";
m_device->disconnectFromDevice();
return;
}
}
}
// 底层状态断开 && 当前保存状态 不等于 底层状态
if(!connected && m_connect != connected)
{
m_connect = connected;
m_attr_send[DeviceAttr(enum_device_attr_Connected)] = m_connect;
this->__send_attr();
this->updateAudioDevice();
this->__kill_reconnect_a2dp_timer();
}
//未主动连接 && 底层状态变为已连接 && 设备信任(以前主动连接的设备)
else if(!m_connectProgress && connected && m_device->isTrusted())
{
m_connect = connected;
m_attr_send[DeviceAttr(enum_device_attr_Connected)] = m_connect;
this->__send_attr();
this->updateAudioDevice();
}
}
void KylinDevice::batteryChanged(BluezQt::BatteryPtr battery)
{
m_need_clean = 0;
if(battery)
{
m_attr_send[DeviceAttr(enum_device_attr_Battery)] = battery->percentage();
this->__send_attr();
}
}
void KylinDevice::typeChanged(BluezQt::Device::Type Type)
{
m_need_clean = 0;
if(Environment::HUAWEI == envPC)
{
if(Type == BluezQt::Device::Type::AudioVideo)
{
m_attr_send[DeviceAttr(enum_device_attr_Type)] = BluezQt::Device::Type::Headphones;
}
else
{
m_attr_send[DeviceAttr(enum_device_attr_Type)] = Type;
}
}
else
{
m_attr_send[DeviceAttr(enum_device_attr_Type)] = Type;
}
m_attr_send[DeviceAttr(enum_device_attr_TypeName)] = BluezQt::Device::typeToString(Type);
this->__send_attr();
}
void KylinDevice::uuidsChanged(const QStringList &uuids)
{
m_uuids = uuids;
this->__init_uuid();;
}
void KylinDevice::mediaTransportChanged(BluezQt::MediaTransportPtr mediaTransport)
{
KyInfo() << m_device->address();
if(mediaTransport)
{
KyInfo() << m_device->address() << " a2dp connect suc";
this->__kill_reconnect_a2dp_timer();
m_a2dp_connect = true;
}
else
{
KyInfo() << m_device->address() << " a2dp disconnect";
if(m_a2dp_connect)
{
this->__kill_reconnect_a2dp_timer();
m_a2dp_reconnect_TimerID = this->startTimer(5000);
KyInfo() << m_device->address() << "start a2dp reconnect timer";
}
m_a2dp_connect = false;
}
}
void KylinDevice::pairfinished(BluezQt::PendingCall *call)
{
if(call->error() != 0)
{
KyWarning()<< m_device->address() <<" paired error, code: "
<<call->error() << ", msg: "<< call->errorText();
m_lastConnectError = call->errorText();
m_attr_send[DeviceAttr(enum_device_attr_ConnectFailedDisc)] = m_lastConnectError;
m_attr_send[DeviceAttr(enum_device_attr_ConnectFailedId)] = get_enum_errmsg(m_lastConnectError);
this->__send_attr();
}
//配对成功
else
{
m_paired = true;
KyInfo() << m_device->address() << " pair suc";
BluezQt::PendingCall * p = m_device->setTrusted(true);
this->wait_for_finish(p);
}
}
void KylinDevice::connectfinished(BluezQt::PendingCall *call)
{
if(call->error() != 0)
{
m_connect = false;
KyWarning()<< m_device->address() <<" connect error, code: "
<<call->error() << ", msg: "<< call->errorText();
//回连失败不发送错误信号
if(0 == m_connect_type)
{
m_lastConnectError = call->errorText();
m_attr_send[DeviceAttr(enum_device_attr_ConnectFailedDisc)] = m_lastConnectError;
m_attr_send[DeviceAttr(enum_device_attr_ConnectFailedId)] = get_enum_errmsg(m_lastConnectError);
this->__send_attr();
}
}
else
{
KyInfo() << m_device->address() << " connect suc";
m_connect = true;
m_attr_send[DeviceAttr(enum_device_attr_Connected)] = m_connect;
this->__send_attr();
this->updateAudioDevice();
}
}
int KylinDevice::pair()
{
m_pairProgress = true;
KyInfo()<< m_device->address();
BluezQt::PendingCall *call = m_device->pair();
connect(call, &BluezQt::PendingCall::finished, this, &KylinDevice::pairfinished);
this->wait_for_finish(call);
m_pairProgress = false;
if(m_lastConnectError.isEmpty())
{
return 0;
}
return get_enum_errmsg(m_lastConnectError);
}
int KylinDevice::connectToDevice()
{
KyInfo() << m_device->address();
BluezQt::PendingCall *call = m_device->connectToDevice();
connect(call, &BluezQt::PendingCall::finished, this, &KylinDevice::connectfinished);
this->wait_for_finish(call);
if(m_lastConnectError.isEmpty())
{
return 0;
}
return get_enum_errmsg(m_lastConnectError);
}
int KylinDevice::updateAudioDevice()
{
//音频设备
if(this->isAudioType())
{
QString old_connected_audio_device;
//移除设备
KylinAdapterPtr adapterPtr = ADAPTERMNG::getInstance()->getDefaultAdapter();
if(adapterPtr)
{
old_connected_audio_device = adapterPtr->connected_audio_device();
if(m_connect)
{
if(old_connected_audio_device != m_device->address())
{
adapterPtr->connected_audio_device(m_device->address());
}
//判断a2dp是否连接
m_a2dp_connect = m_device->mediaTransport() ? true : false;
if(!m_a2dp_connect)
{
if(0 != m_a2dp_reconnect_TimerID)
{
this->__kill_reconnect_a2dp_timer();
}
m_a2dp_reconnect_TimerID = this->startTimer(5000);
KyInfo() << m_device->address() << "start a2dp reconnect timer";
}
}
else
{
if(old_connected_audio_device == m_device->address())
{
adapterPtr->connected_audio_device("");
}
}
}
}
return 0;
}
void KylinDevice::deal_active_connection()
{
if(CONFIG::getInstance()->activeconnection())
{
if(!this->isAudioType() || m_device->isPaired())
{
return;
}
int timeout = 15;
int v= m_device->rssi();
if(abs(v) <= 60)
{
//移除设备
KylinAdapterPtr adapterPtr = ADAPTERMNG::getInstance()->getDefaultAdapter();
if(adapterPtr && adapterPtr->deal_active_connection(m_device->address(), timeout))
{
emit SYSDBUSMNG::getInstance()->ActiveConnection(m_device->address(), m_device->name(),
BluezQt::Device::typeToString(m_device->type()), v, timeout);
KyInfo() << "start active conection" << m_device->address()
<<" rssi: "<< m_device->rssi() << " timeout:" << timeout
<<" type: " << BluezQt::Device::typeToString(m_device->type())
<<" name: " << m_device->name();
}
}
}
}
void KylinDevice::timerEvent(QTimerEvent *event)
{
if(event->timerId() == m_attrsignal_TimerID)
{
KyDebug() << m_device->address() <<" send attrs" << m_attr_send;
this->killTimer(m_attrsignal_TimerID);
m_attrsignal_TimerID = 0;
emit SYSDBUSMNG::getInstance()->deviceAttrChanged(m_device->address(), m_attr_send);
m_attr_send.clear();
}
else if(event->timerId() == m_a2dp_reconnect_TimerID)
{
KyInfo() << m_device->address() <<" a2dp_reconnect_TimerID";
if(m_device->isConnected())
{
m_a2dp_reconnect_count += 1;
if(m_a2dp_reconnect_count > 2)
{
KyInfo() << m_device->address() <<" a2dp sink connect failed, disconnect";
this->devDisconnect();
return;
}
KyInfo() << m_device->address() <<" reconnect a2dp sink";
m_device->connectProfile(A2DP_SINK_UUID);
}
else
{
// 蓝牙连接断开,移删除定时器
this->__kill_reconnect_a2dp_timer();
KyInfo() << m_device->address() <<" already disconnected";
}
}
else
{
KyDebug() << m_device->address() << "other timer, delete";
this->killTimer(event->timerId());
}
}
void KylinDevice::wait_for_finish(BluezQt::PendingCall *call)
{
QEventLoop eventloop;
connect(call, &BluezQt::PendingCall::finished, this, [&](BluezQt::PendingCall *callReturn)
{
eventloop.exit();
});
eventloop.exec();
}
void KylinDevice::__send_attr(enum_send_type stype /*= enum_send_type_delay*/)
{
if(enum_send_type_delay == stype)
{
if(0 == m_attrsignal_TimerID)
{
m_attrsignal_TimerID = this->startTimer(500);
}
}
else
{
if(0 != m_attrsignal_TimerID)
{
this->killTimer(m_attrsignal_TimerID);
m_attrsignal_TimerID = 0;
}
KyDebug() << m_device->address() << " attrs: "<< m_attr_send;
emit SYSDBUSMNG::getInstance()->deviceAttrChanged(m_device->address(), m_attr_send);
m_attr_send.clear();
}
}
void KylinDevice::__send_remove()
{
QMap<QString, QVariant> attrs;
attrs[DeviceAttr(enum_device_attr_Adapter)] = m_adapter;
emit SYSDBUSMNG::getInstance()->deviceRemoveSignal(m_device->address(), attrs);
}
void KylinDevice::__init_uuid()
{
if(support_a2dp_sink(m_uuids))
{
if(!m_support_ad2p_sink)
{
m_support_ad2p_sink = true;
//KyDebug() << m_device->address() <<" support_a2dp_sink";
}
}
else
{
if(m_support_ad2p_sink)
{
m_support_ad2p_sink = false;
//KyDebug() << m_device->address() << "not support_a2dp_sink";
}
}
if(support_a2dp_source(m_uuids))
{
if(!m_support_a2dp_source)
{
m_support_a2dp_source = true;
//KyDebug()<< m_device->address() << "support_a2dp_source";
}
}
else
{
if(m_support_a2dp_source)
{
m_support_a2dp_source = false;
//KyDebug()<< m_device->address() << "not support_a2dp_source";
}
}
if(support_hfphsp_ag(m_uuids))
{
if(!m_support_hfphsp_ag)
{
m_support_hfphsp_ag = true;
//KyDebug()<< m_device->address() << "support_hfphsp_ag";
}
}
else
{
if(m_support_hfphsp_ag)
{
m_support_hfphsp_ag = false;
//KyDebug()<< m_device->address() << "not support_hfphsp_ag";
}
}
if(support_hfphsp_hf(m_uuids))
{
if(!m_support_hfphsp_hf)
{
m_support_hfphsp_hf = true;
//KyDebug() << m_device->address() << "support_hfphsp_hf";
}
}
else
{
if(m_support_hfphsp_hf)
{
m_support_hfphsp_hf = false;
//KyDebug()<< m_device->address() << "not support_hfphsp_hf";
}
}
if(support_filetransport(m_uuids))
{
if(!m_support_filetransport)
{
m_support_filetransport = true;
m_attr_send[DeviceAttr(enum_device_attr_FileTransportSupport)] = m_support_filetransport;
this->__send_attr();
//KyDebug()<< m_device->address() << "support_filetransport";
}
}
else
{
if(m_support_filetransport)
{
m_support_filetransport = false;
m_attr_send[DeviceAttr(enum_device_attr_FileTransportSupport)] = m_support_filetransport;
this->__send_attr();
//KyDebug()<< m_device->address() << "not support_filetransport";
}
}
}
void KylinDevice::__init_devattr(QMap<QString, QVariant> & attrs)
{
attrs.clear();
attrs[DeviceAttr(enum_device_attr_Adapter)] = m_adapter;
attrs[DeviceAttr(enum_device_attr_Paired)] = m_device->isPaired();
attrs[DeviceAttr(enum_device_attr_Trusted)] = m_device->isTrusted();
attrs[DeviceAttr(enum_device_attr_Connected)] = m_connect;
attrs[DeviceAttr(enum_device_attr_Name)] = m_device->name();
if(Environment::HUAWEI == envPC)
{
if(m_device->type() == BluezQt::Device::Type::AudioVideo)
{
attrs[DeviceAttr(enum_device_attr_Type)] = BluezQt::Device::Type::Headphones;
}
else
{
attrs[DeviceAttr(enum_device_attr_Type)] = m_device->type();
}
}
else
{
attrs[DeviceAttr(enum_device_attr_Type)] = m_device->type();
}
attrs[DeviceAttr(enum_device_attr_TypeName)] = BluezQt::Device::typeToString(m_device->type());
attrs[DeviceAttr(enum_device_attr_Connecting)] = m_connectProgress;
if(m_device->type() == BluezQt::Device::Type::Phone || m_device->type() == BluezQt::Device::Type::Computer)
{
attrs[DeviceAttr(enum_device_attr_FileTransportSupport)] = m_support_filetransport;
}
if(m_device->battery())
{
attrs[DeviceAttr(enum_device_attr_Battery)] = m_device->battery()->percentage();
}
attrs[DeviceAttr(enum_device_attr_Addr)] = m_device->address();
attrs[DeviceAttr(enum_device_attr_Rssi)] = m_device->rssi();
attrs[DeviceAttr(enum_device_attr_ShowName)] = m_showName;
}
void KylinDevice::__kill_reconnect_a2dp_timer()
{
if(0 != m_a2dp_reconnect_TimerID)
{
KyInfo() << m_device->address() << "stop a2dp reconnect timer";
this->killTimer(m_a2dp_reconnect_TimerID);
m_a2dp_reconnect_TimerID = 0;
m_a2dp_reconnect_count = 0;
}
}
QMap<QString, QVariant> KylinDevice::getDevAttr()
{
QMap<QString, QVariant> attrs;
this->__init_devattr(attrs);
return attrs;
}
int KylinDevice::setDevAttr(QMap<QString, QVariant> attrs)
{
QString key = DeviceAttr(enum_device_attr_Name);
if(attrs.contains(key) && this->ispaired())
{
m_showName = attrs[key].toString();
if(m_showName.length() == 0)
{
m_showName = m_device->name();
}
CONFIG::getInstance()->set_rename(m_device->address(), m_showName);
m_attr_send[DeviceAttr(enum_device_attr_ShowName)] = m_showName;
this->__send_attr();
}
return 0;
}
void KylinDevice::__send_add()
{
QMap<QString, QVariant> attrs;
this->__init_devattr(attrs);
KyDebug() << m_device->address() << attrs;
emit SYSDBUSMNG::getInstance()->deviceAddSignal(attrs);
}

View File

@ -1,130 +0,0 @@
#ifndef DEVICE_H
#define DEVICE_H
#include <QObject>
#include <QMap>
#include <QString>
#include <QDebug>
#include <KF5/BluezQt/bluezqt/adapter.h>
#include <KF5/BluezQt/bluezqt/device.h>
#include <KF5/BluezQt/bluezqt/pendingcall.h>
#include <KF5/BluezQt/bluezqt/request.h>
#ifdef BATTERY
#include <KF5/BluezQt/bluezqt/battery.h>
#endif
#include "ukui-log4qt.h"
#include "common.h"
class KylinAdapter;
class KylinDevice: public QObject
{
public:
explicit KylinDevice(BluezQt::DevicePtr device, QString adapter);
~KylinDevice();
int start(void);
int devConnect(int type = 0);
int devDisconnect(void);
QMap<QString, QVariant> getDevAttr(void);
int setDevAttr(QMap<QString, QVariant>);
int pairFuncReply(bool);
void requestPinCode(const BluezQt::Request<QString> &request);
void requestPasskey(const BluezQt::Request<quint32> &request);
void requestConfirmation(const QString &passkey, const BluezQt::Request<> &request);
void requestAuthorization(const BluezQt::Request<> &request);
void authorizeService(const QString &uuid, const BluezQt::Request<> &request);
void displayPinCode(const QString &pinCode);
bool needClean(void);
bool isAudioType(void);
int reset(void);
QString Name(void) { return m_device->name(); }
bool ispaired(void) { return m_paired; }
void setSendfileStatus(void);
protected slots:
void nameChanged(const QString &name);
void pairedChanged(bool paired);
void trustedChanged(bool trusted);
void blockedChanged(bool blocked);
void rssiChanged(qint16 rssi);
void connectedChanged(bool connected);
void batteryChanged(BluezQt::BatteryPtr battery);
void typeChanged(BluezQt::Device::Type type);
void uuidsChanged(const QStringList &uuids);
void mediaTransportChanged(BluezQt::MediaTransportPtr mediaTransport);
//////////////////////////////////////////////
void pairfinished(BluezQt::PendingCall *call);
void connectfinished(BluezQt::PendingCall *call);
protected:
int pair();
int connectToDevice();
int updateAudioDevice(void);
void deal_active_connection(void);
virtual void timerEvent( QTimerEvent *event);
void wait_for_finish(BluezQt::PendingCall *call);
private:
void __send_attr(enum_send_type stype = enum_send_type_delay);
void __send_add(void);
void __send_remove(void);
void __init_uuid();
void __init_devattr(QMap<QString, QVariant> &);
void __kill_reconnect_a2dp_timer(void);
protected:
QString m_adapter;
int m_need_clean = 0;
BluezQt::DevicePtr m_device = nullptr;
bool m_connectProgress = false;
bool m_pairProgress = false;
bool m_connect = false;
bool m_paired = false;
QString m_showName;
BluezQt::Request<> m_request;
QStringList m_uuids;
bool m_support_ad2p_sink = false;
bool m_support_a2dp_source = false;
bool m_support_hfphsp_ag = false;
bool m_support_hfphsp_hf = false;
bool m_support_filetransport = false;
QMap<QString, QVariant> m_attr_send;
int m_attrsignal_TimerID= 0;
/**
* @brief m_connect_type
* 0 :
* 1 :
*/
int m_connect_type = 0;
QString m_lastConnectError;
bool m_a2dp_connect = false;
int m_a2dp_reconnect_TimerID = 0;
int m_a2dp_reconnect_count = 0;
friend class KylinAdapter;
};
#endif // DEVICE_H

View File

@ -1,681 +0,0 @@
#include "filesess.h"
#include <QFileInfo>
#include <QDir>
#include <QTimerEvent>
#include "adapter.h"
#include "bluetoothobexagent.h"
#include "sessiondbusregister.h"
#include "device.h"
#include "config.h"
#include <file-utils.h>
KylinFileSess::KylinFileSess(QString addr, QStringList files)
{
KyInfo() << addr << files;
m_dest = addr;
m_files = files;
m_type = enum_filetransport_Type_send;
m_user = CONFIG::getInstance()->active_user();
//设置文件传输状态
this->setSendfileStatus();
}
KylinFileSess::KylinFileSess(BluezQt::ObexTransferPtr transfer, BluezQt::ObexSessionPtr session, const BluezQt::Request<QString> &request)
{
m_type = enum_filetransport_Type_receive;
m_filePtr = transfer;
m_sess = session;
m_request = request;
m_user = CONFIG::getInstance()->active_user();
m_dest = session->destination();
m_object_path = session->objectPath();
KyInfo() << m_object_path.path() << session->destination();
this->__init_Transfer();
this->send_reveivesignal();
//设置文件传输状态
this->setSendfileStatus();
}
KylinFileSess::~KylinFileSess()
{
KyInfo() << m_dest;
if(m_opp)
{
delete m_opp;
m_opp = nullptr;
}
if(0 != m_remove_Timer)
{
this->killTimer(m_remove_Timer);
m_remove_Timer = 0;
}
//接收异常
if(enum_filetransport_Type_receive == m_type)
{
}
m_attr[FileStatusAttr(enum_filestatus_dev)] = m_dest;
m_attr[FileStatusAttr(enum_filestatus_status)] = 0xff;
m_attr[FileStatusAttr(enum_filestatus_transportType)] = m_type;
this->__send_statuschanged();
}
void KylinFileSess::receiveUpdate(BluezQt::ObexTransferPtr transfer, BluezQt::ObexSessionPtr session, const BluezQt::Request<QString> &request)
{
m_filetype = "";
m_filePtr = transfer;
m_request = request;
this->__init_Transfer();
if(session->objectPath() != m_sess->objectPath())
{
KyInfo() << session->destination() << " sess changed, " << session->objectPath().path();
m_sess = session;
m_object_path = m_sess->objectPath();
this->send_reveivesignal();
}
else
{
m_fileIndex++;
m_request.accept(m_filePtr->name());
}
if(0 != m_remove_Timer)
{
this->killTimer(m_remove_Timer);
m_remove_Timer = 0;
}
}
void KylinFileSess::stop()
{
KyInfo();
if(nullptr != m_filePtr && BluezQt::ObexTransfer::Status::Active == m_filePtr->status())
{
m_filePtr->cancel();
}
m_running = false;
}
int KylinFileSess::replyFileReceiving(bool v, QString path)
{
KyInfo() << v;
if(v)
{
if(!path.isEmpty() && this->__isdir_exist(path))
{
m_savePathdir = path;
if(!m_savePathdir.isEmpty() && m_savePathdir[m_savePathdir.length() - 1] != '/')
{
m_savePathdir += '/';
}
}
m_request.accept(m_filePtr->name());
}
else
{
m_request.reject();
}
return 0;
}
void KylinFileSess::CreateSessStart(BluezQt::PendingCall *call)
{
QVariant v = call->value();
m_object_path = v.value<QDBusObjectPath>();
KyInfo() << m_object_path.path();
if(call->error() != 0)
{
KyWarning()<< m_dest <<" CreateSessStart error, code: "
<<call->error() << ", msg: "<< call->errorText();
m_attr[FileStatusAttr(enum_filestatus_dev)] = m_dest;
m_attr[FileStatusAttr(enum_filestatus_fileFailedDisc)] = call->errorText();
this->__send_statuschanged();
FILESESSMNG::getInstance()->removeSession(m_object_path);
return;
}
if(!m_running)
{
KyInfo() << "sendfile stop";
FILESESSMNG::getInstance()->removeSession(m_object_path);
return;
}
m_opp = new BluezQt::ObexObjectPush(m_object_path);
this->sendfile();
}
void KylinFileSess::TransferStart(BluezQt::PendingCall *call)
{
KyInfo();
if(call->error() != 0)
{
KyWarning()<< m_dest <<" TransferStart error, code: "
<<call->error() << ", msg: "<< call->errorText();
m_attr[FileStatusAttr(enum_filestatus_dev)] = m_dest;
m_attr[FileStatusAttr(enum_filestatus_fileFailedDisc)] = call->errorText();
this->__send_statuschanged();
FILESESSMNG::getInstance()->removeSession(m_object_path);
return;
}
QVariant v = call->value();
m_filePtr = v.value<BluezQt::ObexTransferPtr>();
this->__init_Transfer();
}
void KylinFileSess::transferredChanged(quint64 transferred)
{
int percent = transferred * 100.0 / m_transfer_file_size;
if(percent != m_percent)
{
m_attr[FileStatusAttr(enum_filestatus_progress)] = percent;
this->send_statuschanged();
}
m_percent = percent;
}
void KylinFileSess::statusChanged(BluezQt::ObexTransfer::Status status)
{
KyDebug() << status;
if(BluezQt::ObexTransfer::Status::Active == status)
{
if(enum_filetransport_Type_receive == m_type)
{
if(m_filetype.isEmpty())
{
QString src = "/root/.cache/obexd/" + m_filePtr->name();
GError *error;
GFile *file = g_file_new_for_path(src.toStdString().c_str());
if(nullptr != file)
{
GFileInfo *file_info = g_file_query_info(file,"*",G_FILE_QUERY_INFO_NONE,NULL,&error);
if(file_info)
{
m_filetype = g_file_info_get_content_type(file_info);
KyInfo() << m_filePtr->name() << ", filetype: "<<m_filetype;
}
}
}
}
}
else if(BluezQt::ObexTransfer::Status::Queued == status)
{
}
else if(BluezQt::ObexTransfer::Status::Suspended == status)
{
}
else if(BluezQt::ObexTransfer::Status::Complete == status)
{
if(enum_filetransport_Type_send == m_type)
{
m_fileIndex++;
if(m_files.size() > m_fileIndex)
{
this->sendfile();
}
else
{
FILESESSMNG::getInstance()->removeSession(m_object_path);
}
}
//接收文件,改变文件所属
else
{
QString dest;
this->movefile(m_filePtr->name(), dest);
m_attr[FileStatusAttr(enum_filestatus_savepath)] = dest;
//10s内未收到文件传输信号则断开文件连接连接
if(0 == m_remove_Timer)
{
m_remove_Timer = this->startTimer(10 * 1000);
}
}
}
else if(BluezQt::ObexTransfer::Status::Error == status)
{
this->send_statuschanged();
FILESESSMNG::getInstance()->removeSession(m_object_path);
return;
}
else if(BluezQt::ObexTransfer::Status::Unknown == status)
{
this->send_statuschanged();
FILESESSMNG::getInstance()->removeSession(m_object_path);
return;
}
this->send_statuschanged();
}
void KylinFileSess::cancelReceive()
{
m_attr[FileStatusAttr(enum_filestatus_dev)] = m_dest;
m_attr[FileStatusAttr(enum_filestatus_status)] = BluezQt::ObexTransfer::Error;
m_attr[FileStatusAttr(enum_filestatus_transportType)] = m_type;
this->__send_statuschanged();
}
void KylinFileSess::fileNameChanged(const QString &fileName)
{
KyDebug() << fileName;
}
void KylinFileSess::addNewFiles(QStringList files)
{
m_files.append(files);
}
int KylinFileSess::sendfile()
{
int index = m_fileIndex;
QString filename = m_files[index];
BluezQt::PendingCall *transfer = m_opp->sendFile(filename);
connect(transfer, &BluezQt::PendingCall::finished, this, &KylinFileSess::TransferStart);
return 0;
}
QString KylinFileSess::getProperFilePath(QString dir, QString filename)
{
QString dest;
if(dest.isEmpty())
{
dest = "/home/" + m_user + "/" + filename;
}
else
{
dest = dir + filename;
}
KyDebug() << dest;
while (QFile::exists(dest))
{
QStringList newUrl = dest.split("/");
newUrl.pop_back();
newUrl.append(Peony::FileUtils::handleDuplicateName(Peony::FileUtils::urlDecode(dest)));
dest = newUrl.join("/");
KyDebug() << dest << newUrl;
}
return dest;
}
int KylinFileSess::movefile(QString filename, QString & dest)
{
QString src = "/root/.cache/obexd/" + filename;
dest = this->getProperFilePath(m_savePathdir, filename);
GError *error;
GFile *source = g_file_new_for_path(src.toStdString().c_str());
GFile *destination = g_file_new_for_path(dest.toStdString().c_str());
bool flag = g_file_move(source,destination,G_FILE_COPY_BACKUP,NULL,NULL,NULL,&error);
KyInfo() << "move file" << "target_path =" << dest << " source_path =" << src << "flag =" << flag;
if(flag)
{
QString cmd;
cmd = "chgrp " + m_user + " \"" + dest + "\"";
KyInfo() << cmd;
system(cmd.toStdString().c_str());
cmd = "chown " + m_user + " \"" + dest + "\"";;
KyInfo() << cmd;
system(cmd.toStdString().c_str());
}
return 0;
}
void KylinFileSess::timerEvent(QTimerEvent *event)
{
if(event->timerId() == m_remove_Timer)
{
KyInfo() << "remove filesess";
this->killTimer(event->timerId());
m_remove_Timer = 0;
FILESESSMNG::getInstance()->removeSession(m_object_path);
}
else
{
KyInfo() << "other timer, delete";
this->killTimer(event->timerId());
}
}
void KylinFileSess::setSendfileStatus()
{
KylinAdapterPtr ptr = ADAPTERMNG::getInstance()->getDefaultAdapter();
KylinDevicePtr d = nullptr;
if(ptr)
{
d = ptr->getDevPtr(m_dest);
}
if(d)
{
d->setSendfileStatus();
}
}
int KylinFileSess::send_statuschanged()
{
if(enum_filetransport_Type_send == m_type)
{
m_attr[FileStatusAttr(enum_filestatus_allfilenum)] = m_files.size();
}
else
{
if(m_filetype.isEmpty())
{
m_attr[FileStatusAttr(enum_filestatus_filetype)] = m_filePtr->type();
}
else
{
m_attr[FileStatusAttr(enum_filestatus_filetype)] = m_filetype;
}
m_attr[FileStatusAttr(enum_filestatus_filesize)] = m_filePtr->size();
}
m_attr[FileStatusAttr(enum_filestatus_filename)] = m_filePtr->name();
m_attr[FileStatusAttr(enum_filestatus_fileseq)] = m_fileIndex;
m_attr[FileStatusAttr(enum_filestatus_dev)] = m_dest;
m_attr[FileStatusAttr(enum_filestatus_status)] = m_filePtr->status();
m_attr[FileStatusAttr(enum_filestatus_transportType)] = m_type;
this->__send_statuschanged();
return 0;
}
int KylinFileSess::__send_statuschanged()
{
Q_EMIT SYSDBUSMNG::getInstance()->fileStatusChanged(m_attr);
m_attr.clear();
return 0;
}
bool KylinFileSess::__isdir_exist(QString dirpath)
{
QDir dir(dirpath);
return dir.exists();
}
bool KylinFileSess::__isfile_exit(QString filefullpath)
{
QFile file(filefullpath);
return file.exists();
}
int KylinFileSess::send_reveivesignal()
{
KylinAdapterPtr ptr = ADAPTERMNG::getInstance()->getDefaultAdapter();
KylinDevicePtr d = nullptr;
if(!ptr)
{
KyWarning() << "getDefaultAdapter nullptr";
return -1;
}
d = ptr->getDevPtr(m_dest);
if(!d)
{
KyWarning() << "getDevPtr nullptr";
return -1;
}
QMap<QString, QVariant> attrs;
attrs[ReceiveFileAttr(enum_receivefile_dev)] = m_dest;
attrs[ReceiveFileAttr(enum_receivefile_name)] = d->Name();
attrs[ReceiveFileAttr(enum_receivefile_filetype)] = m_filePtr->type();
attrs[ReceiveFileAttr(enum_receivefile_filename)] = m_filePtr->name();
attrs[ReceiveFileAttr(enum_receivefile_filesize)] = m_filePtr->size();
Q_EMIT SYSDBUSMNG::getInstance()->fileReceiveSignal(attrs);
//m_request.accept(m_filePtr->name());
return 0;
}
int KylinFileSess::__init_Transfer()
{
m_transfer_file_size = m_filePtr->size();
m_transferPath = m_filePtr->objectPath().path();
KyInfo() << m_transferPath << m_transfer_file_size << m_filePtr->name() << m_filePtr->fileName()
<< m_filePtr->type() << m_filePtr->status();
connect(m_filePtr.data(), &BluezQt::ObexTransfer::transferredChanged, this, &KylinFileSess::transferredChanged);
connect(m_filePtr.data(), &BluezQt::ObexTransfer::statusChanged, this, &KylinFileSess::statusChanged);
connect(m_filePtr.data(), &BluezQt::ObexTransfer::fileNameChanged, this, &KylinFileSess::fileNameChanged);
m_percent = 0;
m_attr[FileStatusAttr(enum_filestatus_progress)] = m_percent;
this->send_statuschanged();
return 0;
}
////////////////////////////////////////////////////
FileSessMng::FileSessMng()
{
KyInfo();
}
int FileSessMng::init()
{
m_obex = new BluezQt::ObexManager(this);
BluezQt::InitObexManagerJob *obex_job = m_obex->init();
obex_job->exec();
connect(m_obex, &BluezQt::ObexManager::operationalChanged, this, &FileSessMng::operationalChanged);
connect(m_obex, &BluezQt::ObexManager::sessionAdded, this, &FileSessMng::sessionAdded);
connect(m_obex, &BluezQt::ObexManager::sessionRemoved, this, &FileSessMng::sessionRemoved);
if(!m_obex->isOperational())
{
this->start_obexservice();
}
else
{
Q_EMIT m_obex->operationalChanged(m_obex->isOperational());
}
return 0;
}
int FileSessMng::sendFiles(QString addr, QStringList files)
{
KyInfo() << addr << files;
KylinAdapterPtr ptr = ADAPTERMNG::getInstance()->getDefaultAdapter();
if(!ptr || !m_obex->isOperational() || addr.isEmpty() || files.size() == 0)
{
return -1;
}
if (m_sess.contains(addr))
{
m_sess[addr]->addNewFiles(files);
return 0;
}
KylinFileSessPtr s(new KylinFileSess(addr, files));
m_sess[addr] = s;
QMap<QString,QVariant> map;
map["Source"] = ptr->addr();
map["Target"] = "OPP";
BluezQt::PendingCall *target = m_obex->createSession(addr,map);
connect(target, &BluezQt::PendingCall::finished, s.data(), &KylinFileSess::CreateSessStart);
this->wait_for_finish(target);
if(0 != target->error())
{
m_sess.remove(addr);
}
return target->error();
}
int FileSessMng::receiveFiles(BluezQt::ObexTransferPtr transfer, BluezQt::ObexSessionPtr session, const BluezQt::Request<QString> &request)
{
if(m_sess_recv.contains(session->destination()))
{
m_sess_recv[session->destination()]->receiveUpdate(transfer, session, request);
return 0;
}
KylinFileSessPtr s(new KylinFileSess(transfer, session, request));
m_sess_recv[session->destination()] = s;
return 0;
}
int FileSessMng::removeSession(const QDBusObjectPath &session)
{
KyInfo() << session.path();
m_obex->removeSession(session);
return 0;
}
int FileSessMng::stopFiles(QString addr, int type)
{
KyInfo() << addr << type;
if(enum_filetransport_Type_send == type)
{
if(m_sess.contains(addr))
{
m_sess[addr]->stop();
if(!m_sess[addr]->object_path().path().isEmpty())
{
this->removeSession(m_sess[addr]->object_path());
}
}
}
else if(enum_filetransport_Type_receive == type)
{
if(m_sess_recv.contains(addr))
{
m_sess_recv[addr]->stop();
this->removeSession(m_sess_recv[addr]->object_path());
}
}
return 0;
}
int FileSessMng::replyFileReceiving(QString addr, bool v, QString path)
{
KyInfo() << addr << v;
if(m_sess_recv.contains(addr))
{
return m_sess_recv[addr]->replyFileReceiving(v, path);
}
return 0;
}
void FileSessMng::operationalChanged(bool operational)
{
if(operational)
{
if(!BLUETOOTHOBEXAGENT::getInstance())
{
BLUETOOTHOBEXAGENT::instance(this);
BluezQt::PendingCall * call = m_obex->registerAgent(BLUETOOTHOBEXAGENT::getInstance());
this->wait_for_finish(call);
}
}
else
{
if(BLUETOOTHOBEXAGENT::getInstance())
{
BluezQt::PendingCall * call = m_obex->unregisterAgent(BLUETOOTHOBEXAGENT::getInstance());
this->wait_for_finish(call);
BLUETOOTHOBEXAGENT::destroyInstance();
}
QTimer::singleShot(5 * 1000,this,[=]{
KyInfo() << "restart obex";
this->start_obexservice();
});
}
}
void FileSessMng::sessionAdded(BluezQt::ObexSessionPtr session)
{
KyInfo();
if(session && m_sess.contains(session->destination()))
{
m_sess[session->destination()]->ObexSessionPtr(session);
}
}
void FileSessMng::sessionRemoved(BluezQt::ObexSessionPtr session)
{
KyInfo() << ((nullptr == session) ? "null session" : session->destination())
<< ((nullptr == session) ? "null session" : session->objectPath().path());
if(session && m_sess.contains(session->destination()))
{
BluezQt::ObexSessionPtr ptr = m_sess[session->destination()]->ObexSessionPtr();
if(ptr && ptr->objectPath() == session->objectPath())
{
m_sess.remove(session->destination());
}
}
if(session && m_sess_recv.contains(session->destination()))
{
BluezQt::ObexSessionPtr ptr = m_sess_recv[session->destination()]->ObexSessionPtr();
if(ptr && ptr->objectPath() == session->objectPath())
{
m_sess_recv.remove(session->destination());
}
}
}
void FileSessMng::sessionCanceled(BluezQt::ObexSessionPtr session)
{
if (!m_sess_recv.contains(session->destination()))
return;
m_sess_recv[session->destination()]->cancelReceive();
}
void FileSessMng::wait_for_finish(BluezQt::PendingCall *call)
{
QEventLoop eventloop;
connect(call, &BluezQt::PendingCall::finished, this, [&](BluezQt::PendingCall *callReturn)
{
eventloop.exit();
});
eventloop.exec();
}
void FileSessMng::start_obexservice()
{
KyInfo() << "start obex";
if(nullptr == m_process)
{
m_process = new QProcess;
m_process->setProgram("/usr/lib/bluetooth/obexd");
m_process->setArguments(QStringList{"-d"});
m_process->startDetached();
}
else
{
m_process->setProgram("/usr/lib/bluetooth/obexd");
m_process->setArguments(QStringList{"-d"});
m_process->startDetached();
}
}

View File

@ -1,166 +0,0 @@
#ifndef FILESESS_H
#define FILESESS_H
#include <QObject>
#ifdef BATTERY
#include <KF5/BluezQt/bluezqt/battery.h>
#endif
#include <KF5/BluezQt/bluezqt/adapter.h>
#include <KF5/BluezQt/bluezqt/manager.h>
#include <KF5/BluezQt/bluezqt/initmanagerjob.h>
#include <KF5/BluezQt/bluezqt/device.h>
#include <KF5/BluezQt/bluezqt/agent.h>
#include <KF5/BluezQt/bluezqt/pendingcall.h>
#include <KF5/BluezQt/bluezqt/obexmanager.h>
#include <KF5/BluezQt/bluezqt/initobexmanagerjob.h>
#include <KF5/BluezQt/bluezqt/obexobjectpush.h>
#include <KF5/BluezQt/bluezqt/obexsession.h>
#include <KF5/BluezQt/bluezqt/obextransfer.h>
#include <QDBusObjectPath>
#include <QThread>
#include <QEventLoop>
#include <QProcess>
#include "common.h"
#include "ukui-log4qt.h"
#include "CSingleton.h"
class KylinFileSess : public QObject
{
Q_OBJECT
public:
explicit KylinFileSess(QString, QStringList);
explicit KylinFileSess(BluezQt::ObexTransferPtr transfer,BluezQt::ObexSessionPtr session, const BluezQt::Request<QString> &request);
~KylinFileSess();
void ObexSessionPtr(BluezQt::ObexSessionPtr p){ m_sess = p; }
BluezQt::ObexSessionPtr ObexSessionPtr(void) { return m_sess; }
enum_filetransport_Type type(void){ return m_type; }
void receiveUpdate(BluezQt::ObexTransferPtr transfer,BluezQt::ObexSessionPtr session, const BluezQt::Request<QString> &request);
QDBusObjectPath object_path(void){ return m_object_path; }
void stop(void);
int replyFileReceiving(bool, QString);
void addNewFiles(QStringList files);
void cancelReceive();
public slots:
void CreateSessStart(BluezQt::PendingCall *call);
protected slots:
void TransferStart(BluezQt::PendingCall *call);
void transferredChanged(quint64 transferred);
void statusChanged(BluezQt::ObexTransfer::Status status);
void fileNameChanged(const QString &fileName);
protected:
int sendfile(void);
QString getProperFilePath(QString, QString);
int movefile(QString, QString &);
virtual void timerEvent( QTimerEvent *event);
void setSendfileStatus(void);
private:
int send_statuschanged(void);
int send_reveivesignal(void);
int __init_Transfer();
int __send_statuschanged(void);
bool __isdir_exist(QString);
bool __isfile_exit(QString);
protected:
bool m_running = true;
QString m_dest;
QStringList m_files;
int m_fileIndex = 0;
QDBusObjectPath m_object_path;
quint64 m_transfer_file_size = 0;
QString m_transferPath;
int m_percent = 0;
BluezQt::ObexTransferPtr m_filePtr = nullptr;
BluezQt::ObexSessionPtr m_sess = nullptr;
BluezQt::ObexObjectPush * m_opp = nullptr;
BluezQt::Request<QString> m_request;
QMap<QString, QVariant> m_attr;
QString m_savePathdir;
QString m_user;
QString m_filetype;
int m_remove_Timer = 0;
enum_filetransport_Type m_type = enum_filetransport_Type_send;
};
typedef QSharedPointer<KylinFileSess> KylinFileSessPtr;
////////////////////////////////////////
class FileSessMng : public QObject
{
Q_OBJECT
public:
explicit FileSessMng();
int init(void);
int sendFiles(QString, QStringList);
int receiveFiles(BluezQt::ObexTransferPtr transfer,BluezQt::ObexSessionPtr session, const BluezQt::Request<QString> &request);
int removeSession(const QDBusObjectPath &session);
int stopFiles(QString, int);
int replyFileReceiving(QString, bool, QString);
void sessionCanceled(BluezQt::ObexSessionPtr session);
protected slots:
//obex
void operationalChanged(bool operational);
void sessionAdded(BluezQt::ObexSessionPtr session);
void sessionRemoved(BluezQt::ObexSessionPtr session);
private:
void wait_for_finish(BluezQt::PendingCall *call);
void start_obexservice();
protected:
QMap<QString, KylinFileSessPtr> m_sess;
QMap<QString, KylinFileSessPtr> m_sess_recv;
BluezQt::ObexManager * m_obex = nullptr;
QProcess * m_process = nullptr;
friend class SingleTon<FileSessMng>;
};
typedef SingleTon<FileSessMng> FILESESSMNG;
#endif // FILESESS_H

42
service/globalsize.cpp Normal file
View File

@ -0,0 +1,42 @@
#include "globalsize.h"
QMap<QString, int> GlobalSize::m_static_devconnectcount;
int GlobalSize::refBlueDevActive(QString key)
{
if(m_static_devconnectcount.contains(key))
{
m_static_devconnectcount[key] = m_static_devconnectcount[key] + 1;
}
else
{
m_static_devconnectcount[key] = 1;
}
return m_static_devconnectcount[key];
}
int GlobalSize::unrefBlueDevActive(QString key)
{
if(m_static_devconnectcount.contains(key))
{
m_static_devconnectcount[key] = m_static_devconnectcount[key] -1;
if(0 == m_static_devconnectcount[key])
{
m_static_devconnectcount.remove(key);
return 0;
}
return m_static_devconnectcount[key];
}
return 0;
}
bool GlobalSize::IsBlueDevActive(QString key)
{
return m_static_devconnectcount.contains(key);
}
int GlobalSize::BlueDevActiveSize(void)
{
return m_static_devconnectcount.size();
}

26
service/globalsize.h Normal file
View File

@ -0,0 +1,26 @@
#ifndef GLOBALSIZE_H
#define GLOBALSIZE_H
#include <QObject>
#include <QString>
#include <QMap>
class GlobalSize
{
public:
static int refBlueDevActive(QString key);
static int unrefBlueDevActive(QString key);
static bool IsBlueDevActive(QString key);
static int BlueDevActiveSize(void);
protected:
//主动连接标志
static QMap<QString, int> m_static_devconnectcount;
};
#endif // GLOBALSIZE_H

View File

@ -4,18 +4,11 @@
#include <QCommandLineParser>
#include <QDebug>
#include <QFile>
#include <QTranslator>
#include <QLibraryInfo>
#include <ukui-log4qt.h>
#include "daemon.h"
#include "sessiondbusregister.h"
#include "systemadapter.h"
#include "app.h"
#include "adapter.h"
#include "device.h"
#include "common.h"
#include "filesess.h"
extern "C" {
@ -23,7 +16,7 @@ extern "C" {
#include <signal.h>
}
#include "kysdk/kysdk-system/libkysysinfo.h"
#include "kysdk/kysdk-system/libkysysinfo.h"
void signalHandlerFunc(int signal) {
@ -53,7 +46,7 @@ static void setEnvPCValue()
envPC = Environment::NOMAL;
QString str = executeLinuxCmd("cat /proc/cpuinfo | grep -i hardware");
QString str = executeLinuxCmd("cat /proc/cpuinfo | grep Hardware");
if(str.length() == 0)
{
goto FuncEnd;
@ -62,17 +55,7 @@ static void setEnvPCValue()
if(str.indexOf("huawei") != -1 || str.indexOf("pangu") != -1 ||
str.indexOf("kirin") != -1)
{
QString str1 = executeLinuxCmd("dmidecode |grep \"String 4\"");
//M900公版无需采用CBG方案可跟随主线方案
if(str.indexOf("m900") != -1 && (str1.isEmpty() || str1.indexOf("pwc30") == -1))
{
envPC = Environment::NOMAL;
}
else
{
envPC = Environment::HUAWEI;
}
envPC = Environment::HUAWEI;
}
FuncEnd:
@ -84,110 +67,62 @@ FuncEnd:
envPC = Environment::MAVIS;
}
KyInfo () << envPC;
qInfo () << Q_FUNC_INFO << envPC <<__LINE__;
}
static bool InterfaceAlreadyExists()
{
QDBusConnection conn = QDBusConnection::systemBus();
if (!conn.isConnected())
return 0;
QDBusReply<QString> reply = conn.interface()->call("GetNameOwner", "com.ukui.bluetooth");
return reply.value() == "";
}
static int init(void)
{
if (InterfaceAlreadyExists())
{
CONFIG::instance();
CONFIG::getInstance()->init();
QDBusConnection conn = QDBusConnection::systemBus();
if (!conn.registerService("com.ukui.bluetooth")) {
KyWarning() << "QDbus register service failed reason:" << conn.lastError();
return -1;
}
SYSDBUSMNG::instance();
SYSDBUSMNG::getInstance()->start();
if(!conn.registerObject("/com/ukui/bluetooth", "com.ukui.bluetooth",
SYSDBUSMNG::getInstance()->get_sys_adapter(),
QDBusConnection::ExportAllSlots|QDBusConnection::ExportAllSignals))
{
KyWarning() << "QDbus register object failed reason:" << conn.lastError();
return -1;
}
BPDMNG::instance();
APPMNG::instance();
ADAPTERMNG::instance();
Q_EMIT SYSDBUSMNG::getInstance()->updateClient();
DAEMON::instance();
DAEMON::getInstance()->start();
if(envPC != HUAWEI)
{
FILESESSMNG::instance();
FILESESSMNG::getInstance()->init();
}
}
else
{
KyInfo() << "already running";
return -1;
}
return 0;
}
static int fini(void)
{
return 0;
}
int main(int argc, char *argv[])
{
fprintf(stdout,"Program running.....\n");
initUkuiLog4qt(QString("bluetoothserver"));
setEnvPCValue();
KyDebug() << "envPC: "<< envPC;
qDebug() << "envPC: "<< envPC;
QCoreApplication a(argc, argv);
QCommandLineParser parser;
parser.addHelpOption();
parser.addVersionOption();
parser.addOptions({{{"o","obex"},QCoreApplication::translate("main","Load the Bluetooth file transfer agent")}});
parser.setApplicationDescription(QCoreApplication::translate("main","UKUI bluetooth daemon"));
parser.process(a);
QtSingleCoreApplication a(argc, argv);
a.setOrganizationName("Kylin Team");
a.setApplicationName("dbus-bluetooth-service");
a.setApplicationVersion("1.0.0");
QTranslator *t = new QTranslator();
t->load("/usr/share/libpeony-qt/libpeony-qt_"+QLocale::system().name() + ".qm");
QCoreApplication::installTranslator(t);
if (a.isRunning()) {
qDebug() << "bus-bluetooth-service is Already running ! ! !";
return EXIT_SUCCESS;
} else {
// signal(SIGKILL,signalHandlerFunc);
// signal(SIGQUIT,signalHandlerFunc);
int ret = init();
if(0 != ret)
{
return ret;
QCommandLineParser parser;
parser.addHelpOption();
parser.addVersionOption();
parser.addOptions({{{"o","obex"},QCoreApplication::translate("main","Load the Bluetooth file transfer agent")}});
parser.setApplicationDescription(QCoreApplication::translate("main","UKUI bluetooth daemon"));
parser.process(a);
// QDBusConnection systemBus = QDBusConnection::systemBus();
// if (!systemBus.registerService("com.bluetooth.systemdbus")){
// qCritical() << "QDbus register service failed reason:" << systemBus.lastError();
// //exit(1);
// }
// if (!systemBus.registerObject("/", "com.bluetooth.interface", new SysDbusRegister(), QDBusConnection::ExportAllSlots)){
// qCritical() << "QDbus register object failed reason:" << systemBus.lastError();
// //exit(2);
// }
// qDebug() << "ok";
SessionDbusRegister *sessionDbus = new SessionDbusRegister();
Q_UNUSED(sessionDbus);
Daemon *daemon = new Daemon();
Q_UNUSED(daemon);
int quitValue = a.exec();
delete sessionDbus;
delete daemon;
qInfo() << Q_FUNC_INFO << "Daemon program exit!!!!";
return quitValue;
}
KyInfo() << "QCoreApplication exec";
int quitValue = a.exec();
fini();
KyInfo() << "Daemon program exit!!!!";
return quitValue;
}

224
service/rfkill.cpp Normal file
View File

@ -0,0 +1,224 @@
#include "rfkill.h"
enum rfkill_type {
RFKILL_TYPE_ALL = 0,
RFKILL_TYPE_WLAN,
RFKILL_TYPE_BLUETOOTH,
RFKILL_TYPE_UWB,
RFKILL_TYPE_WIMAX,
RFKILL_TYPE_WWAN
};
enum rfkill_operation {
RFKILL_OP_ADD = 0,
RFKILL_OP_DEL,
RFKILL_OP_CHANGE,
RFKILL_OP_CHANGE_ALL,
RFKILL_OP_OFF
};
struct rfkill_event {
quint32 idx;
quint8 type;
quint8 op;
quint8 soft;
quint8 hard;
};
Rfkill::Rfkill(QObject *parent) :
QObject(parent),
_mReadFd(-1),
_mWriteFd(-1),
_mState(Unknown)
{
// init();
}
Rfkill::~Rfkill()
{
if (_mReadFd != -1) {
close(_mReadFd);
}
if (_mWriteFd != -1) {
close(_mWriteFd);
}
}
Rfkill::State Rfkill::state() const
{
return _mState;
}
bool Rfkill::block()
{
if (_mState == SoftBlocked || _mState == HardBlocked) {
return true;
}
if (_mState != Unblocked) {
return false;
}
return setSoftBlock(1);
}
bool Rfkill::unblock()
{
if (_mState == Unblocked) {
return true;
}
if (_mState != SoftBlocked) {
return false;
}
return setSoftBlock(0);
}
size_t Rfkill::bluetooth_size(void)
{
return _mDevices.size();
}
void Rfkill::init()
{
_mReadFd = open("/dev/rfkill", O_RDONLY | O_CLOEXEC);
if (_mReadFd == -1) {
qDebug() << Q_FUNC_INFO << "Cannot open /dev/rfkill for reading!";
return;
}
if (fcntl(_mReadFd, F_SETFL, O_NONBLOCK) < 0) {
close(_mReadFd);
_mReadFd = -1;
return;
}
updateRfkillDevices();
// add 不存在蓝牙节点情况下,发送初始化信号
if(_mDevices.size() == 0)
{
emit rfkillStatusChanged(RFKILL_OP_OFF);
}
QSocketNotifier *notifier = new QSocketNotifier(_mReadFd, QSocketNotifier::Read, this);
connect(notifier, &QSocketNotifier::activated, this, &Rfkill::devReadyRead);
}
void Rfkill::devReadyRead()
{
State oldState = _mState;
updateRfkillDevices();
if (_mState != oldState) {
emit stateChanged(_mState);
}
}
static Rfkill::State getState(rfkill_event event)
{
if (event.hard) {
return Rfkill::HardBlocked;
} else if (event.soft) {
return Rfkill::SoftBlocked;
}
return Rfkill::Unblocked;
}
void Rfkill::updateRfkillDevices()
{
if (_mReadFd == -1) {
return;
}
rfkill_event event;
while (read(_mReadFd, &event, sizeof(event)) == sizeof(event)) {
qDebug() << Q_FUNC_INFO << QString("idx %1 type %2 op %3 soft %4 hard %5").arg(event.idx).arg(event.type).arg(event.op).arg(event.soft).arg(event.hard);
if (event.type != RFKILL_TYPE_BLUETOOTH) {
continue;
}
switch (event.op) {
case RFKILL_OP_ADD:
_mDevices[event.idx] = getState(event);
emit rfkillStatusChanged(RFKILL_OP_ADD);
break;
case RFKILL_OP_CHANGE:
_mDevices[event.idx] = getState(event);
break;
case RFKILL_OP_DEL:
_mDevices.remove(event.idx);
emit rfkillStatusChanged(RFKILL_OP_DEL);
break;
case RFKILL_OP_CHANGE_ALL:
for (auto it = _mDevices.begin(); it != _mDevices.end(); ++it) {
it.value() = getState(event);
}
break;
default:
break;
}
}
// Update global state
_mState = Unknown;
for (State state : qAsConst(_mDevices)) {
Q_ASSERT(state != Unknown);
if (_mState == Unknown) {
_mState = state;
} else if (state > _mState) {
_mState = state;
}
}
qDebug() << "Rfkill global state changed:" << _mState;
qDebug() << "Rfkill currentThreadId :" << QThread::currentThreadId();
}
bool Rfkill::openForWriting()
{
if (_mWriteFd != -1) {
return true;
}
_mWriteFd = open("/dev/rfkill", O_WRONLY | O_CLOEXEC);
if (_mWriteFd == -1) {
qDebug() << "Cannot open /dev/rfkill for writing!";
return false;
}
if (fcntl(_mWriteFd, F_SETFL, O_NONBLOCK) < 0) {
close(_mWriteFd);
_mWriteFd = -1;
return false;
}
return true;
}
bool Rfkill::setSoftBlock(quint8 soft)
{
if (!openForWriting()) {
return false;
}
rfkill_event event;
memset(&event, 0, sizeof(event));
event.op = RFKILL_OP_CHANGE_ALL;
event.type = RFKILL_TYPE_BLUETOOTH;
event.soft = soft;
bool ret = write(_mWriteFd, &event, sizeof(event)) == sizeof(event);
qDebug() << "Setting Rfkill soft block succeeded:" << ret;
return ret;
}

50
service/rfkill.h Normal file
View File

@ -0,0 +1,50 @@
#ifndef RFKILL_H
#define RFKILL_H
#include <QObject>
#include <QDebug>
#include <QThread>
#include <QSocketNotifier>
extern "C" {
#include <unistd.h>
#include <fcntl.h>
}
class Rfkill : public QObject
{
Q_OBJECT
public:
enum State {
Unblocked = 0,
SoftBlocked = 1,
HardBlocked = 2,
Unknown = 3
};
explicit Rfkill(QObject *parent = nullptr);
~Rfkill();
State state() const;
bool block();
bool unblock();
size_t bluetooth_size(void);
public slots:
void init();
private:
void devReadyRead();
void updateRfkillDevices();
bool openForWriting();
bool setSoftBlock(quint8);
signals:
void stateChanged(State);
void rfkillStatusChanged(quint64);
private:
State _mState;
int _mReadFd;
int _mWriteFd;
QHash<quint32, State> _mDevices;
};
#endif // RFKILL_H

View File

@ -14,12 +14,12 @@ QT += core gui dbus
greaterThan(QT_MAJOR_VERSION, 4): QT += widgets
CONFIG += c++11 \
exception \
link_pkgconfig
PKGCONFIG += gsettings-qt \
gio-2.0 \
kysdk-sysinfo \
peony
kysdk-sysinfo
#exists(/usr/include/kysdk/kysdk-base/libkydiagnostics.h)
#{
# PKGCONFIG += kysdk-diagnostics
@ -45,9 +45,6 @@ INSTALLS += target
# 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
DEFINES += QT_NO_INFO_OUTPUT
DEFINES += QT_NO_DEBUG_OUTPUT
exists(/usr/include/KF5/BluezQt/bluezqt/battery.h){DEFINES += BATTERY}
# You can also make your code fail to compile if you use deprecated APIs.
@ -55,36 +52,28 @@ exists(/usr/include/KF5/BluezQt/bluezqt/battery.h){DEFINES += BATTERY}
# 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
SOURCES += main.cpp \
adapter.cpp \
app.cpp \
bluetoothagent.cpp \
bluetoothobexagent.cpp \
buriedpointdata.cpp \
common.cpp \
config.cpp \
daemon.cpp \
device.cpp \
filesess.cpp \
globalsize.cpp \
rfkill.cpp \
sessiondbusregister.cpp\
systemadapter.cpp
tmpdevclear.cpp
HEADERS += \
CSingleton.h \
adapter.h \
app.h \
bluetoothagent.h \
bluetoothobexagent.h \
buriedpointdata.h \
common.h \
config.h \
daemon.h \
device.h \
filesess.h \
globalsize.h \
rfkill.h \
sessiondbusregister.h \
systemadapter.h
tmpdevclear.h
TRANSLATIONS += ../translations/ukui-bluetooth_zh_CN.ts
OBJECTS_DIR = ./obj/
MOC_DIR = ./moc/
CONFIG+=force_debug_info

File diff suppressed because it is too large Load Diff

View File

@ -1,76 +1,276 @@
#ifndef SESSIONDBUSREGISTER_H
#define SESSIONDBUSREGISTER_H
#include "daemon.h"
#include "config.h"
#include <KF5/BluezQt/bluezqt/adapter.h>
#include <KF5/BluezQt/bluezqt/manager.h>
#include <KF5/BluezQt/bluezqt/types.h>
#include <KF5/BluezQt/bluezqt/device.h>
#ifdef BATTERY
#include <KF5/BluezQt/bluezqt/battery.h>
#endif
#include <QObject>
#include <QString>
#include <QStringList>
#include <QDebug>
#include <QDBusContext>
#include <QDBusConnection>
#include <QDBusConnectionInterface>
#include <QDBusReply>
#include "ukui-log4qt.h"
#include "CSingleton.h"
#include <QDebug>
#include <QString>
#include <QStringList>
#include <QTimer>
class SystemAdapter;
class SysDbusMng : public QObject
class DelayStruct : public QObject
{
Q_OBJECT
protected:
explicit SysDbusMng(QObject *parent = nullptr);
~SysDbusMng();
public:
int start(void);
DelayStruct(BluezQt::DevicePtr dev, QObject *parent = nullptr);
~DelayStruct();
int stop(void);
void close(void); //关闭并销毁函数
SystemAdapter *get_sys_adapter(){ return m_sys_adapter; }
public:
bool registerClient(QMap<QString, QVariant>, QString);
bool unregisterClient(QString);
QString bluetoothKeyValue(unsigned int,QString);
signals:
void adapterAddSignal(QMap<QString, QVariant>);
void adapterAttrChanged(QString, QMap<QString, QVariant>);
void adapterRemoveSignal(QString);
void deviceAddSignal(QMap<QString, QVariant>);
void deviceAttrChanged(QString, QMap<QString, QVariant>);
void deviceRemoveSignal(QString, QMap<QString, QVariant>);
void ActiveConnection(QString, QString, QString, int, int);
void updateClient(void);
void startPair(QMap<QString, QVariant>);
void fileStatusChanged(QMap<QString, QVariant>);
void fileReceiveSignal(QMap<QString, QVariant>);
void clearBluetoothDev(QStringList);
//音频控制信号
void VolumeDown();
void VolumeUp();
void Next();
void PlayPause();
void Previous();
void Stop();
void Play();
void Pause();
protected:
void sendMultimediaControlButtonSignal(unsigned int);
virtual void timerEvent( QTimerEvent *event);
private:
SystemAdapter * m_sys_adapter = nullptr;
QMap<unsigned int, long long> m_pressTimeMap; //记录键值按下的时间
QMap<unsigned int, long long> m_releaseTimeMap; //记录键值释放的时间
friend class SingleTon<SysDbusMng>;
int m_TimerID = 0;
BluezQt::DevicePtr m_dev = nullptr;
};
typedef SingleTon<SysDbusMng> SYSDBUSMNG;
class SessionDbusRegister : public QObject, protected QDBusContext
{
Q_OBJECT
Q_CLASSINFO("D-Bus Interface", "com.ukui.bluetooth")
public:
explicit SessionDbusRegister(QObject *parent = nullptr);
~SessionDbusRegister();
private:
QMap<QString,QMap<QString,QString>> sessionList;
int scanOnCount = 0;
QTimer * scanOnTimer = nullptr;
bool huawei_scan_interval_flag = false;
QString tmpDevCord = QString("");
bool InterfaceAlreadyExists();
void AudioDevConnectFunc(BluezQt::DevicePtr);
void clearDeviceScanList(BluezQt::DevicePtr);
bool deviceMacAddressContrast(QString,QString,int);
bool deviceMacAddressChanged(BluezQt::DevicePtr);
void deviceConnectAgain(BluezQt::DevicePtr,bool);
void deal_active_connection(BluezQt::DevicePtr);
private slots:
void dealStatusChanged(QString status, QString dev, QString path);
public slots:
//客户端id + 类型 + 用户名
//客户端id: dbus唯一名称
//类型 0 控制面板, 1托盘
bool registerClient(QString, int, QString);
bool unregisterClient(QString);
// 蓝牙默认适配器信息处理dbus
bool getBluetoothBlock();
QString getDefaultAdapterAddress();
bool getDefaultAdapterPower();
bool getDefaultAdapterScanStatus();
bool getDefaultAdapterDiscoverable();
QString getAdapterNameByAddr(QString);
QStringList getDefaultAdapterPairedDevAddress();
QStringList getDefaultAdapterTrustedDevAddress();
QStringList getDefaultAdapterCacheDevAddress();
QStringList getAdapterDevAddressList();
void setDefaultAdapterPower(bool);
void setDefaultAdapterScanOn(bool);
void setDefaultAdapter(QString);
void setDefaultAdapterDiscoverable(bool);
void setBluetoothBlock(bool);
void setDefaultAdapterName(QString);
void clearNonViableDevice(QStringList);
//蓝牙设备处理dbus
void devPair(const QString);
void devConnect(const QString);
void devDisconnect(const QString);
void devRemove(const QString);
void devTrust(const QString,const bool);
bool getDevPairStatus(const QString);
bool getDevConnectStatus(const QString);
QString getDevName(const QString);
QString getDevType(const QString);
void clearAllUnPairedDevicelist();
void setSendTransferDeviceMesg(QString);
void setSendTransferFileMesg(QStringList files);
void setclearOldSession();
void continueSendFiles(QString filename);
void cancelFileReceiving();
//#ifdef BATTERY
qint64 getDevBattery(const QString);
//#endif
//设备是否支持文件发送
bool getDevSupportFileSend(const QString);
qint16 getDevRssi(const QString);
//文件传输dbus
void sendFiles(QString,QString);//test
void exit();
//其他dbus
void sendNotifyMessage(QString);
void openBluetoothSettings();
void connectSignal();
void showTrayWidgetUI();
bool getTransferDevAndStatus(QString dev);
//test
void sendContinueRecieveFilesSignal();
void sendReplyRequestConfirmation(bool);
void sendReplyFileReceivingSignal(bool v);
void sendCloseSession();
//主动连接请求, v 接受/拒绝
void activeConnectionReply(QString dev, bool v);
signals:
//适配器相关信号
void defaultAdapterPowerChanged(bool);
void defaultAdapterChanged(QString);
void defaultScanStatusChanged(bool);
void defaultDiscoverableChanged(bool);
void adapterAddSignal(QString);
void adapterRemoveSignal(QString);
void defaultAdapterNameChanged(QString);
//设备相关信号
void deviceScanResult(QString,QString,QString,bool,qint16);
void devPairSignal(QString,bool);
void devTypeChangedSignal(QString,QString);
void devBatteryChangedSignal(QString, QString);
void devNameChangedSignal(QString,QString);
void devConnectStatusSignal(QString,bool);
void devRemoveSignal(QString);
void devLaunchConnecting(QString);
void devOperateErrorSignal(QString,int,QString);
void devMacAddressChangedSignal(QString,QString);
void devRssiChangedSignal(QString,qint16);
//代理相关信号
void sendFile(QString,QString);
void continueSendFilesSignal(QString);
void displayPasskey(QString,QString);
// void replyDisplayPasskey(bool);
void requestConfirmation(QString,QString);
void replyRequestConfirmation(bool);
void transferredChanged(quint64,QString);
void statusChanged(QString,QString,QString);
void fileReceivingSignal(QString,QString,QString,QString,quint64);
void replyFileReceivingSignal(bool);
void continueRecieveFilesSignal();
void closeSessionSignal();
void pairAgentCanceled();
void obexAgentCanceled();
void propertyChanged(quint64);
void sendTransferDeviceMesg(QString);
void sendTransferFilesMesg(QStringList);
void clearOldSession();
void cancelFileReceivingSignal();
void showTrayWidgetUISignal();
void initTransferPath(QString, bool);
void powerProgress(bool);
void clearBluetoothDev(QStringList);
//id, name , type, rssi, timeout
void ActiveConnection(QString, QString, QString, int, int);
};
#endif // SESSIONDBUSREGISTER_H

View File

@ -1,375 +0,0 @@
#include "systemadapter.h"
#include "sessiondbusregister.h"
#include "adapter.h"
#include "device.h"
#include "config.h"
#include "app.h"
#include "filesess.h"
#include "common.h"
#include "buriedpointdata.h"
SystemAdapter::SystemAdapter(QObject *parent): QObject(parent)
{
KyDebug();
}
SystemAdapter::~SystemAdapter()
{
KyDebug();
}
QMap<QString, QVariant> SystemAdapter::registerClient(QMap<QString, QVariant> params)
{
QString dbusid = this->getCallerDebus();
KyInfo() << params << " dbusid: "<< dbusid;
QMap<QString, QVariant> res;
res["result"] = SYSDBUSMNG::getInstance()->registerClient(params, dbusid);
res["envPC"] = envPC;
return res;
}
bool SystemAdapter::unregisterClient(QString id)
{
KyInfo() << id << " dbusid: "<<this->getCallerDebus();
return SYSDBUSMNG::getInstance()->unregisterClient(id);
}
QStringList SystemAdapter::getRegisterClient()
{
KyInfo() << " dbusid: "<<this->getCallerDebus();
return APPMNG::getInstance()->getRegisterClient();
}
QStringList SystemAdapter::getAllAdapterAddress()
{
KyInfo() << " dbusid: "<<this->getCallerDebus();
return ADAPTERMNG::getInstance()->getAllAdapterAddress();
}
QMap<QString, QVariant> SystemAdapter::getAdapterAttr(QString addr, QString key)
{
KyInfo() << " dbusid: "<<this->getCallerDebus();
return ADAPTERMNG::getInstance()->getAdapterAttr(addr.toUpper(), key);
}
QStringList SystemAdapter::getDefaultAdapterAllDev()
{
KyInfo() << " dbusid: "<<this->getCallerDebus();
return ADAPTERMNG::getInstance()->getDefaultAdapterAllDev();
}
QStringList SystemAdapter::getDefaultAdapterPairedDev()
{
KyInfo() << " dbusid: "<<this->getCallerDebus();
return ADAPTERMNG::getInstance()->getDefaultAdapterPairedDev();
}
QMap<QString, QVariant> SystemAdapter::getDevAttr(QString addr)
{
addr = addr.toUpper();
KyInfo() << addr << " dbusid: "<<this->getCallerDebus();
KylinAdapterPtr ptr = ADAPTERMNG::getInstance()->getDefaultAdapter();
KylinDevicePtr d = nullptr;
if(ptr)
{
d = ptr->getDevPtr(addr);
}
if(d)
{
return d->getDevAttr();
}
return QMap<QString, QVariant>();
}
bool SystemAdapter::setDevAttr(QString dev, QMap<QString, QVariant> attrs)
{
KyInfo() << dev << attrs << " dbusid: "<<this->getCallerDebus();
dev = dev.toUpper();
KyInfo() << dev << attrs << " dbusid: "<<this->getCallerDebus();
KylinAdapterPtr ptr = ADAPTERMNG::getInstance()->getDefaultAdapter();
KylinDevicePtr d = nullptr;
if(ptr)
{
d = ptr->getDevPtr(dev);
}
if(d)
{
d->setDevAttr(attrs);
}
return true;
}
bool SystemAdapter::setDefaultAdapterAttr(QMap<QString, QVariant> attrs)
{
KyInfo() << attrs << " dbusid: "<<this->getCallerDebus();
KylinAdapterPtr ptr = ADAPTERMNG::getInstance()->getDefaultAdapter();
if(ptr)
{
QString key;
key = AdapterAttr(enum_Adapter_attr_Powered);
if(attrs.contains(key) && attrs[key].type() == QVariant::Bool)
{
bool v = attrs[key].toBool();
CONFIG::getInstance()->power_switch(v);
ptr->setPower(v);
}
key = AdapterAttr(enum_Adapter_attr_Discoverable);
if(attrs.contains(key) && attrs[key].type() == QVariant::Bool)
{
bool v = attrs[key].toBool();
CONFIG::getInstance()->discoverable_switch(v);
ptr->setDiscoverable(v);
}
key = AdapterAttr(enum_Adapter_attr_Name);
if(attrs.contains(key) && attrs[key].type() == QVariant::String)
{
QString v = attrs[key].toString();
ptr->setName(v);
}
key = AdapterAttr(enum_Adapter_attr_ActiveConnection);
if(attrs.contains(key) && attrs[key].type() == QVariant::Bool)
{
bool v = attrs[key].toBool();
CONFIG::getInstance()->activeconnection(v);
ptr->setActiveConnection(v);
}
key = AdapterAttr(enum_Adapter_attr_TrayShow);
if(attrs.contains(key) && attrs[key].type() == QVariant::Bool)
{
bool v = attrs[key].toBool();
CONFIG::getInstance()->trayShow(v);
ptr->trayShow(v);
}
return true;
}
return false;
}
int SystemAdapter::setDefaultAdapter(QString addr)
{
qInfo() << Q_FUNC_INFO << addr << " dbusid: "<<this->getCallerDebus();
return ADAPTERMNG::getInstance()->setDefaultAdapter(addr);
}
int SystemAdapter::devConnect(QString addr)
{
addr = addr.toUpper();
KyInfo() << addr << " dbusid: "<<this->getCallerDebus();
int ret = ERR_BREDR_INTERNAL_NO_Default_Adapter;
KylinAdapterPtr ptr = ADAPTERMNG::getInstance()->getDefaultAdapter();
if(ptr)
{
ret = ptr->devConnect(addr);
if(ERR_BREDR_CONN_SUC == ret && ptr->devIsAudioType(addr))
{
CONFIG::getInstance()->finally_audiodevice(addr);
}
}
return ret;
}
int SystemAdapter::devDisconnect(QString addr)
{
addr = addr.toUpper();
KyInfo() << addr << " dbusid: "<<this->getCallerDebus();
int ret = ERR_BREDR_INTERNAL_NO_Default_Adapter;
KylinAdapterPtr ptr = ADAPTERMNG::getInstance()->getDefaultAdapter();
if(ptr)
{
ret = ptr->devDisconnect(addr);
if(addr == CONFIG::getInstance()->finally_audiodevice())
{
CONFIG::getInstance()->finally_audiodevice("");
}
}
return ret;
}
int SystemAdapter::devRemove(QStringList devlist)
{
KyInfo() << devlist << " dbusid: "<<this->getCallerDebus();
KylinAdapterPtr ptr = ADAPTERMNG::getInstance()->getDefaultAdapter();
if(ptr)
{
ptr->devRemove(devlist);
for(auto iter : devlist)
{
CONFIG::getInstance()->delete_rename(iter.toUpper());
}
}
return 0;
}
int SystemAdapter::activeConnectionReply(QString addr, bool v)
{
addr = addr.toUpper();
KyInfo() << addr << v << " dbusid: "<<this->getCallerDebus();
KylinAdapterPtr ptr = ADAPTERMNG::getInstance()->getDefaultAdapter();
if(ptr)
{
ptr->activeConnectionReply(addr, v);
}
return 0;
}
int SystemAdapter::pairFuncReply(QString addr, bool v)
{
addr = addr.toUpper();
KyInfo() << addr << v << " dbusid: "<<this->getCallerDebus();
KylinAdapterPtr ptr = ADAPTERMNG::getInstance()->getDefaultAdapter();
KylinDevicePtr d = nullptr;
if(ptr)
{
d = ptr->getDevPtr(addr);
}
if(d)
{
return d->pairFuncReply(v);
}
return -1;
}
int SystemAdapter::sendFiles(QString user, QString addr, QStringList files)
{
addr = addr.toUpper();
KyInfo() << addr << files << " dbusid: "<<this->getCallerDebus();
if(HUAWEI == envPC)
{
KyInfo() << "not support";
return -1;
}
return FILESESSMNG::getInstance()->sendFiles(addr, files);
}
int SystemAdapter::stopFiles(QMap<QString, QVariant> params)
{
KyInfo() << params << " dbusid: "<<this->getCallerDebus();
if(HUAWEI == envPC)
{
KyInfo() << "not support";
return -1;
}
QString addr;
int transportType = enum_filetransport_Type_other;
QString key;
key = "dev";
if(params.contains(key) && params[key].type() == QVariant::String)
{
addr = params[key].toString();
addr = addr.toUpper();
}
key = "transportType";
if(params.contains(key) && (params[key].type() == QVariant::Int || params[key].type() == QVariant::UInt))
{
transportType = params[key].toInt();
}
if(addr.isEmpty() || enum_filetransport_Type_other == transportType)
{
qWarning() << Q_FUNC_INFO << "error";
return -1;
}
return FILESESSMNG::getInstance()->stopFiles(addr, transportType);
}
int SystemAdapter::replyFileReceiving(QMap<QString, QVariant> params)
{
KyInfo() << params << " dbusid: "<<this->getCallerDebus();
if(HUAWEI == envPC)
{
KyInfo() << "not support";
return -1;
}
QString addr;
bool v = false;
QString savePathdir;
QString user;
QString key;
key = "dev";
if(params.contains(key) && params[key].type() == QVariant::String)
{
addr = params[key].toString();
addr = addr.toUpper();
}
key = "receive";
if(params.contains(key) && params[key].type() == QVariant::Bool)
{
v = params[key].toBool();
}
key = "savePathdir";
if(params.contains(key) && params[key].type() == QVariant::String)
{
savePathdir = params[key].toString();
}
key = "user";
if(params.contains(key) && params[key].type() == QVariant::String)
{
user = params[key].toString();
}
if(addr.isEmpty())
{
qWarning() << "addr error";
return -1;
}
return FILESESSMNG::getInstance()->replyFileReceiving(addr, v, savePathdir);
}
void SystemAdapter::writeBuriedPointData(QString pluginName, QString settingsName, QString action, QString value)
{
KyInfo() << pluginName << settingsName << action << value << " dbusid: "<<this->getCallerDebus();
emit BPDMNG::getInstance()->writeInData(pluginName, settingsName, action, value);
}
QString SystemAdapter::bluetoothKeyValue(unsigned int key, QString str)
{
KyInfo() << key << str << " dbusid: "<<this->getCallerDebus();
return SYSDBUSMNG::getInstance()->bluetoothKeyValue(key, str);
}
QString SystemAdapter::getCallerDebus()
{
QDBusConnection conn = connection();
QDBusMessage msg = message();
QString dbusid = conn.interface()->serviceOwner(msg.service()).value();
if(APPMNG::getInstance()->existDbusid(dbusid))
{
return dbusid;
}
int uid = conn.interface()->serviceUid(msg.service()).value();
int64_t pid = conn.interface()->servicePid(msg.service()).value();
KyInfo() << "unknown dbusid: "<< dbusid << " uid: "<< uid << " pid: " << pid;
return dbusid;
}

View File

@ -1,78 +0,0 @@
#ifndef SYSTEMADAPTER_H
#define SYSTEMADAPTER_H
#include <QObject>
#include <QDBusContext>
#include <QDBusConnection>
#include <QDBusConnectionInterface>
#include <QDBusReply>
#include <QDebug>
#include <QString>
#include <QStringList>
#include <QTimer>
#include "ukui-log4qt.h"
class SystemAdapter : public QObject, protected QDBusContext
{
Q_OBJECT
Q_CLASSINFO("D-Bus Interface", "com.ukui.bluetooth")
public:
explicit SystemAdapter(QObject *parent = nullptr);
virtual ~SystemAdapter();
public slots:
QMap<QString, QVariant> registerClient(QMap<QString, QVariant>);
bool unregisterClient(QString);
QStringList getRegisterClient(void);
QStringList getAllAdapterAddress(void);
QMap<QString, QVariant> getAdapterAttr(QString, QString);
QStringList getDefaultAdapterAllDev(void);
QStringList getDefaultAdapterPairedDev(void);
QMap<QString, QVariant> getDevAttr(QString);
bool setDevAttr(QString, QMap<QString, QVariant>);
bool setDefaultAdapterAttr(QMap<QString, QVariant>);
int setDefaultAdapter(QString);
int devConnect(QString);
int devDisconnect(QString);
int devRemove(QStringList);
int activeConnectionReply(QString, bool);
int pairFuncReply(QString, bool);
int sendFiles(QString, QString, QStringList);
int stopFiles(QMap<QString, QVariant>);
int replyFileReceiving(QMap<QString, QVariant>);
void writeBuriedPointData(QString, QString, QString, QString);
QString bluetoothKeyValue(unsigned int,QString);
signals:
void adapterAddSignal(QMap<QString, QVariant>);
void adapterAttrChanged(QString, QMap<QString, QVariant>);
void adapterRemoveSignal(QString);
void deviceAddSignal(QMap<QString, QVariant>);
void deviceAttrChanged(QString, QMap<QString, QVariant>);
void deviceRemoveSignal(QString, QMap<QString, QVariant>);
void ActiveConnection(QString, QString, QString, int, int);
void updateClient(void);
void startPair(QMap<QString, QVariant>);
void fileStatusChanged(QMap<QString, QVariant>);
void fileReceiveSignal(QMap<QString, QVariant>);
void clearBluetoothDev(QStringList);
//音频控制信号
void VolumeDown();
void VolumeUp();
void Next();
void PlayPause();
void Previous();
void Stop();
void Play();
void Pause();
private:
QString getCallerDebus(void);
};
#endif // SYSTEMADAPTER_H

157
service/tmpdevclear.cpp Normal file
View File

@ -0,0 +1,157 @@
#include "tmpdevclear.h"
#include "daemon.h"
#include "sessiondbusregister.h"
#include <functional>
#include <algorithm>
#include <QDateTime>
#include <QTimer>
#include <QDebug>
#include <QMutexLocker>
#include <KF5/BluezQt/bluezqt/device.h>
extern QString global_active_connection_dev;
extern SessionDbusRegister * global_sess;
//间隔清理不可见设备时间
const qint64 interval = 30*1000;
TmpDevClear* TmpDevClear::_instant = nullptr;
TmpDevClear *TmpDevClear::getInstant()
{
if (nullptr == _instant) {
_instant = new TmpDevClear();
}
return _instant;
}
void TmpDevClear::init()
{
if (!baseTime) {
baseTime = new QTimer(this);
baseTime->setInterval(interval / 6);
connect(baseTime,&QTimer::timeout,this,&TmpDevClear::removeConnectionFromMap);
}
qDebug() << "TmpDevClear currentThreadId :" << QThread::currentThreadId();
for (auto dev : Daemon::_DefualtAdapter.data()->devices()) {
qDebug() << Q_FUNC_INFO <<dev.data()->address() << dev.data()->name();
if (connections.end() != connections.find(dev.data()->address())) {
QObject::disconnect(connections[dev.data()->address()]);
}
devUpdates[dev.data()->address()] = QDateTime::currentMSecsSinceEpoch();
connections[dev.data()->address()] = connect(dev.data(),&BluezQt::Device::deviceChanged,this,&TmpDevClear::rssiChanaged);
}
Daemon::_DefualtAdapter->disconnect(this);
connect(Daemon::_DefualtAdapter.data(),&BluezQt::Adapter::deviceAdded,this,[=](BluezQt::DevicePtr devAdd){
if (connections.end() != connections.find(devAdd.data()->address())) {
QObject::disconnect(connections[devAdd.data()->address()]);
}
devUpdates[devAdd.data()->address()] = QDateTime::currentMSecsSinceEpoch();
connections[devAdd.data()->address()] = connect(devAdd.data(),&BluezQt::Device::deviceChanged,this,&TmpDevClear::rssiChanaged);
});
baseTime->start();
}
void TmpDevClear::fini(void)
{
Daemon::_DefualtAdapter->disconnect(this);
devUpdates.clear();
//蓝牙设备删除,关联的信号也会删除
connections.clear();
}
TmpDevClear::TmpDevClear(QObject *parent): QObject(parent)
{
}
void TmpDevClear::removeConnectionFromMap()
{
if (Daemon::_DefualtAdapter.isNull() || !Daemon::_DefualtAdapter->isPowered())
return;
qDebug() << Q_FUNC_INFO << "start" << devUpdates.size() << connections.size();
for(QString iter : m_cleardev)
{
BluezQt::DevicePtr devptr = Daemon::_DefualtAdapter.data()->deviceForAddress(iter);
//能够搜索到设备,且处于未配对未连接状态,从底层移除设备
if(!devptr.isNull() && !devptr.data()->isPaired() && !devptr.data()->isConnected()
&& devptr->address() != global_active_connection_dev)
{
qDebug() << "clear dev: " << iter;
Daemon::_DefualtAdapter.data()->removeDevice(devptr);
}
//能够搜索到设备,且设备处于配对或者连接状态,加入列表
else if(!devptr.isNull() && (devptr->isPaired() || devptr->isConnected()))
{
qDebug() << "add dev: " << iter;
devUpdates[devptr->address()] = QDateTime::currentMSecsSinceEpoch();
connections[devptr->address()] = connect(devptr.data(),&BluezQt::Device::deviceChanged,this,&TmpDevClear::rssiChanaged);
}
//搜索不到设备,说明已经被移除了
}
m_cleardev.clear();
for (QMap<QString,qint64>::iterator iter = devUpdates.begin(); iter != devUpdates.end();) {
if ((iter.value()+interval) <= QDateTime::currentMSecsSinceEpoch()) {
BluezQt::DevicePtr devptr = Daemon::_DefualtAdapter.data()->deviceForAddress(iter.key());
//发起配对时设备非pair状态但是是连接状态
if (!devptr.isNull() && !devptr.data()->isPaired() && !devptr.data()->isConnected()
&& devptr->address() != global_active_connection_dev) {
disconnect(connections[iter.key()]);
connections.remove(iter.key());
iter = devUpdates.erase(iter);
m_cleardev.append(devptr->address());
}
//设备已被移除
else if(devptr.isNull())
{
disconnect(connections[iter.key()]);
connections.remove(iter.key());
iter = devUpdates.erase(iter);
}
else {
iter++;
}
} else {
iter++;
}
}
if(m_cleardev.size() > 0)
{
qDebug() << "clear dev: " << m_cleardev;
global_sess->clearBluetoothDev(m_cleardev);
}
}
void TmpDevClear::rssiChanaged(BluezQt::DevicePtr dev)
{
Q_UNUSED(dev);
devUpdates[dev.data()->address()] = QDateTime::currentMSecsSinceEpoch();
}
void TmpDevClear::updateTime(const QString & addr)
{
if(devUpdates.contains(addr))
{
devUpdates[addr] = QDateTime::currentMSecsSinceEpoch();
}
}
TmpDevClear::~TmpDevClear()
{
}

48
service/tmpdevclear.h Normal file
View File

@ -0,0 +1,48 @@
#ifndef TMPDEVCLEAR_H
#define TMPDEVCLEAR_H
#include <QObject>
#include <QMap>
#include <QMutex>
#include <QStringList>
#include <KF5/BluezQt/bluezqt/adapter.h>
class QTimer;
class TmpDevClear final : public QObject
{
Q_OBJECT
public:
static TmpDevClear* getInstant();
void init();
void fini(void);
TmpDevClear(TmpDevClear&&) = delete;
TmpDevClear(const TmpDevClear&) = delete;
TmpDevClear& operator =(TmpDevClear&) = delete;
~TmpDevClear();
//更新时间戳
void updateTime(const QString & addr);
private:
explicit TmpDevClear(QObject *parent = nullptr);
void removeConnectionFromMap();
static TmpDevClear*_instant;
QMap<QString,QMetaObject::Connection> connections;
QMap<QString,qint64> devUpdates;
QTimer* baseTime = nullptr;
private:
QStringList m_cleardev;
public slots:
void rssiChanaged(BluezQt::DevicePtr);
};
#endif // TMPDEVCLEAR_H

View File

@ -4,14 +4,9 @@ Environment envPC = Environment::NOMAL;
Bluetooth::Bluetooth() : mFirstLoad(true) {
KyDebug() << "start" << "++ukccBluetooth========================";
QStringList addrList = BlueToothDBusService::getAllAdapterAddress();
if (!addrList.size())
ukccbluetoothconfig::ukccGsetting->set("show",QVariant(false));
else
ukccbluetoothconfig::ukccGsetting->set("show",QVariant(true));
KyDebug() << envPC ;
qDebug() << Q_FUNC_INFO << "start" << "++ukccBluetooth========================" << __LINE__;
ukccbluetoothconfig::setEnvPCValue();
qDebug() << Q_FUNC_INFO << envPC << __LINE__;
QTranslator * translator = new QTranslator(this);;
translator->load("/usr/share/ukui-bluetooth/translations/ukcc-bluetooth_" + QLocale::system().name() + ".qm");
@ -19,11 +14,46 @@ Bluetooth::Bluetooth() : mFirstLoad(true) {
pluginName = tr("Bluetooth");
pluginType = DEVICES;
QList <quint64> btServiceProcessId;
bool m_bluetooth_service_process_flag = ukccbluetoothconfig::checkProcessRunning(BluetoothServiceExePath/*"bluetoothService"*/,btServiceProcessId);
for(quint64 tempId : btServiceProcessId)
{
qDebug () << Q_FUNC_INFO << "========================" << tempId;
}
if (m_bluetooth_service_process_flag)
{
qDebug () << Q_FUNC_INFO << BluetoothServiceExePath << "is Running" ;
}
else
{
qDebug () << Q_FUNC_INFO << BluetoothServiceExePath << "is not Running" ;
QList <quint64> btTrayProcessId;
bool m_ukui_bluetooth_process_flag = ukccbluetoothconfig::checkProcessRunning(BluetoothTrayExePath,btTrayProcessId);
if (m_ukui_bluetooth_process_flag)
{
qDebug () << Q_FUNC_INFO << BluetoothTrayExePath << "is Running" ;
for (quint64 processId:btTrayProcessId)
{
qDebug () << Q_FUNC_INFO << "ProcessId:" << btTrayProcessId << "is Running" ;
ukccbluetoothconfig::killAppProcess(processId);
}
}
else
{
qDebug () << Q_FUNC_INFO << BluetoothTrayExePath << "is not Running" ;
}
ukccbluetoothconfig::launchBluetoothServiceStart(BluetoothServiceExePath);
}
}
Bluetooth::~Bluetooth() {
if (!mFirstLoad) {
pluginWidget->deleteLater();
// delete pluginWidget;
}
}
@ -39,12 +69,15 @@ QWidget *Bluetooth::pluginUi() {
if (mFirstLoad) {
mFirstLoad = false;
pluginWidget = new BlueToothMainWindow;
pluginWidget = new BlueToothMain;
// pluginWidget = new BlueToothMainWindow;
}
if (!mFirstLoad && (nullptr != pluginWidget))
{
BlueToothDBusService::registerClient();
QTimer::singleShot(2000,this,[=]
{
pluginWidget->setbluetoothAdapterDiscoveringStatus(true);
});
}
return pluginWidget;
@ -64,27 +97,25 @@ QIcon Bluetooth::icon() const
return QIcon::fromTheme("bluetooth-active-symbolic");
}
bool Bluetooth::isEnable() const
{
QStringList addrList = BlueToothDBusService::getAllAdapterAddress();
KyDebug() << addrList ;
if (addrList.size())
QString m_defaultAdapterAddr = BlueToothDBusService::getDefaultAdapterAddr();
if (m_defaultAdapterAddr.isEmpty() || 6 != m_defaultAdapterAddr.split(":").size())
{
KyDebug() << "Bluetooth::isEnable is true";
return true;
}
else
{
KyDebug() << "Bluetooth::isEnable is false";
qInfo() << Q_FUNC_INFO << m_defaultAdapterAddr << endl;
return false;
}
else
return true;
}
void Bluetooth::plugin_leave()
{
if (nullptr != pluginWidget)
{
//界面切出时注销控制面板注册
BlueToothDBusService::unregisterClient();
pluginWidget->setbluetoothAdapterDiscoveringStatus(false);
//pluginWidget->update();
}
}

View File

@ -7,9 +7,9 @@
#include <QWidget>
#include <QTranslator>
#include <QApplication>
#include <ukui-log4qt.h>
#include <ukcc/interface/interface.h>
#include "bluetoothmain.h"
#include "bluetoothmainwindow.h"
#include "ukccbluetoothconfig.h"
@ -41,7 +41,8 @@ public:
private:
QString pluginName;
int pluginType;
BlueToothMainWindow *pluginWidget;
BlueToothMain * pluginWidget;
// BlueToothMainWindow *pluginWidget;
bool mFirstLoad;
};

File diff suppressed because it is too large Load Diff

View File

@ -1,186 +1,44 @@
#ifndef BLUETOOTHDBUSSERVICE_H
#define BLUETOOTHDBUSSERVICE_H
#include <QList>
#include <QDebug>
#include <QTimer>
#include <QObject>
#include <QDBusReply>
#include <QDBusMessage>
#include <ukui-log4qt.h>
#include <QStandardPaths>
#include <QDBusInterface>
#include <QDBusConnection>
#include "config.h"
#include "devicebase.h"
#include "ukccbluetoothconfig.h"
/**
* @brief
*
*/
#define DBUSSERVICE "com.ukui.bluetooth"
#define DBUSPATH "/com/ukui/bluetooth"
#define DBUSINTERFACE "com.ukui.bluetooth"
class BlueToothDBusService : public QObject
{
Q_OBJECT
public:
/**
* @brief
*
* @param parent
*/
BlueToothDBusService(QObject *parent = nullptr);
/**
* @brief
*
*/
~BlueToothDBusService();
int initBluetoothServer();
static QDBusInterface interface; /**< TODO: systemd dbus */
static QDBusInterface interface;
static bool getDefaultAdapterPower();
static bool getBluetoothBlock();
static bool getAdapterDiscoverable();
static QStringList getAdapterList();
static QString getDefaultAdapterAddr();
static QString getAdapterNameByAddr(QString);
static bool m_taskbar_show_mark ; /**< TODO: default bt adapter */
static QStringList m_bluetooth_adapter_address_list ; /**< TODO: default bt adapter */
static QStringList m_bluetooth_adapter_name_list ; /**< TODO: default bt adapter */
static void setAdapterPower(bool);
static void setAdapterDiscoverable(bool);
static QStringList m_bluetooth_Paired_Device_address_list ; /**< TODO: default bt adapter */
static QStringList m_bluetooth_All_Device_address_list ; /**< TODO: default bt adapter */
static bluetoothadapter * m_default_bluetooth_adapter ; /**< TODO: default bt adapter */
QList<bluetoothadapter *> m_bluetooth_adapter_list ; /**< TODO: bt adapter list*/
static bool getDevPairedByAddr(QString);
static QString getDevTypeByAddr(QString);
static QString getDevNameByAddr(QString);
static int checkAddrList(QStringList &);
static QMap<QString, QVariant> registerClient();
static QMap<QString, QVariant> registerClient(QMap<QString, QVariant>);
static bool unregisterClient();
//Function operation
static int devConnect(QString address);
static bool devRename(QString address,QString reanme_str);
static bool setDevTrusted(QString address,bool isTrusted);
static int devDisconnect(QString address);
static int devRemove(QString address);
static int devRemove(QStringList addressList);
static int sendFiles(QString address);
//get adapter data
static QMap<QString, QVariant> defaultAdapterDataAttr;
static QStringList getAllAdapterAddress();
QMap<QString ,QVariant> getAdapterAttr(QString,QString);
static bool setDefaultAdapterAttr(QMap<QString, QVariant>);
int getAdapterAllData(QString);
void bluetoothAdapterDataAnalysis(QMap<QString ,QVariant> value,
QString &dev_name,
QString &dev_address,
bool &dev_block ,
bool &dev_power,
bool &dev_pairing ,
bool &dev_pairable ,
bool &dev_connecting ,
bool &dev_discovering ,
bool &dev_discoverable,
bool &dev_activeConnection,
bool &dev_defaultAdapterMark,
bool &dev_trayShow);
//set default adapter
static void setDefaultAdapterName(QString);
static void setDefaultAdapterSwitchStatus(bool);
static int setDefaultAdapter(QString);
static void setTrayIconShowStatus(bool);
static void setDefaultAdapterDiscoverableStatus(bool);
static void setAutoConnectAudioDevStatus(bool);
//get device data
static QMap<QString, QVariant> deviceDataAttr;
static QStringList getDefaultAdapterPairedDev();
static QStringList getDefaultAdapterAllDev();
static QMap<QString,QVariant> getDevAttr(QString);
static bool setDevAttr(QString,QMap<QString,QVariant>);
void bluetoothDeviceDataAnalysis(QMap<QString ,QVariant> value,
QString &dev_address ,
QString &dev_name ,
QString &dev_showName ,
bluetoothdevice::DEVICE_TYPE &dev_type ,
bool &dev_paired ,
bool &dev_trusted ,
bool &dev_blocked ,
bool &dev_connected ,
bool &dev_pairing ,
bool &dev_connecting ,
int &dev_battery ,
int &dev_connectFailedId ,
QString &dev_connectFailedDisc ,
qint16 &dev_rssi ,
bool &dev_sendFileMark ,
QString &adapter_addr );
bluetoothdevice * createOneBleutoothDeviceForAddress(QString address);
//set device data
/**
* @brief
*
* @param dev
* @return bool
*/
static bool getDevSupportFileSend(QString);
static bool getTransferInfo(QString dev);
/**
* @brief setDefaultAdapterScanOn
*
* @param bool
*/
static void setDefaultAdapterScanOn(bool);
//report data
signals:
void adapterAddSignal(QString);
void adapterRemoveSignal(int);
void defaultAdapterChangedSignal(int);
void adapterNameChanged(QString);
void adapterPoweredChanged(bool);
void adapterTrayIconChanged(bool);
void adapterDiscoverableChanged(bool);
void adapterActiveConnectionChanged(bool);
void adapterDiscoveringChanged(bool);
void deviceAddSignal(QString);
void deviceRemoveSignal(QString);
void btServiceRestart();
void btServiceRestartComplete(bool);
private Q_SLOTS:
void reportAdapterAddSignal(QMap<QString ,QVariant>);
void reportAdapterAttrChanged(QString,QMap<QString ,QVariant>);
void reportAdapterRemoveSignal(QString address);
void reportDeviceAddSignal(QMap<QString ,QVariant>);
void reportDeviceAttrChanged(QString,QMap<QString ,QVariant>);
int reportDeviceRemoveSignal(QString devAddr , QMap<QString ,QVariant> );
void reportClearBluetoothDev(QStringList);
void reportUpdateClient();
void devLoadingTimeoutSlot();
private:
/**
* @brief
*
*/
// int getDevListIndex(QString address);
void bindServiceReportData();
void bindDefaultAdapterReportData();
void serviceChangedDefaultAdapter(int);
void getDefaultAdapterDevices();
QStringList m_remainder_loaded_bluetooth_device_address_list ;
QTimer * m_loading_dev_timer = nullptr;
};
#endif // BLUETOOTHDBUSSERVICE_H

View File

@ -1,275 +0,0 @@
#include "bluetoothdevicefunc.h"
#define RADIUS 6.0
bluetoothdevicefunc::bluetoothdevicefunc(QWidget *parent ,QString dev_address):
QPushButton(parent),
_MDev_addr(dev_address)
{
initGsettings();
initInterface();
}
bluetoothdevicefunc::~bluetoothdevicefunc()
{
KyDebug() <<_MDev_addr ;
_mStyle_GSettings->deleteLater();
}
void bluetoothdevicefunc::initGsettings()
{
if (QGSettings::isSchemaInstalled(GSETTING_UKUI_STYLE))
{
_mStyle_GSettings = new QGSettings(GSETTING_UKUI_STYLE);
if(_mStyle_GSettings->get("styleName").toString() == "ukui-default" ||
_mStyle_GSettings->get("style-name").toString() == "ukui-light")
_themeIsBlack = false;
else
_themeIsBlack = true;
_mIconThemeName = _mStyle_GSettings->get("iconThemeName").toString();
}
connect(_mStyle_GSettings,&QGSettings::changed,this,&bluetoothdevicefunc::mStyle_GSettingsSlot);
}
void bluetoothdevicefunc::initBackground()
{
this->setIcon(QIcon::fromTheme("view-more-horizontal-symbolic"));
this->setProperty("useButtonPalette", true);
this->setFlat(true);
}
void bluetoothdevicefunc::initInterface()
{
KyDebug();
this->setFixedSize(36,36);
// if (_themeIsBlack)
initBackground();
devMenuFunc = new QMenu(this);
devMenuFunc->setMinimumWidth(160);
//devMenuFunc->setMaximumWidth(160);
connect(devMenuFunc,&QMenu::triggered,this,&bluetoothdevicefunc::MenuSignalDeviceFunction);
connect(devMenuFunc,&QMenu::aboutToHide,this,&bluetoothdevicefunc::MenuSignalAboutToHide);
}
void bluetoothdevicefunc::MenuSignalDeviceFunction(QAction *action)
{
KyDebug() << action->text();
if (!BlueToothDBusService::m_default_bluetooth_adapter->m_bt_dev_list.contains(_MDev_addr))
{
KyWarning() << " bluetooth device is null";
return;
}
if(action->text() == tr("sendFile"))
{
BlueToothDBusService::sendFiles(_MDev_addr);
}
else if(action->text() == tr("remove"))
{
DevRemoveDialog::REMOVE_INTERFACE_TYPE mode ;
if (bluetoothdevice::DEVICE_TYPE::phone == BlueToothDBusService::m_default_bluetooth_adapter->m_bt_dev_list[_MDev_addr]->getDevType() ||
bluetoothdevice::DEVICE_TYPE::computer == BlueToothDBusService::m_default_bluetooth_adapter->m_bt_dev_list[_MDev_addr]->getDevType())
mode = DevRemoveDialog::REMOVE_HAS_PIN_DEV;
else
mode = DevRemoveDialog::REMOVE_NO_PIN_DEV;
showDeviceRemoveWidget(mode);
}
else if (action->text() == tr("connect"))
{
KyDebug() << "To :" << _MDev_addr << "connect" ;
if (BlueToothDBusService::m_default_bluetooth_adapter->m_bt_dev_list.contains(_MDev_addr))
{
BlueToothDBusService::m_default_bluetooth_adapter->m_bt_dev_list[_MDev_addr]->setDevConnecting(true);
}
BlueToothDBusService::devConnect(_MDev_addr);
}
else if(action->text() == tr("disconnect"))
{
KyDebug() << "To :" <<_MDev_addr << "disconnect" ;
BlueToothDBusService::devDisconnect(_MDev_addr);
}
else if(action->text() == tr("rename"))
{
KyDebug() << "To :" << _MDev_addr << "disconnect" ;
showDeviceRenameWidget();
}
// emit devFuncOpertionSignal();
}
void bluetoothdevicefunc::MenuSignalAboutToHide()
{
//KyWarning();
}
void bluetoothdevicefunc::showDeviceRemoveWidget(DevRemoveDialog::REMOVE_INTERFACE_TYPE mode)
{
DevRemoveDialog *mesgBox = new DevRemoveDialog(mode);
mesgBox->setModal(true);
mesgBox->setDialogText(BlueToothDBusService::m_default_bluetooth_adapter->m_bt_dev_list[_MDev_addr]->getDevInterfaceShowName());
connect(mesgBox,&DevRemoveDialog::accepted,this,[=]{
KyDebug() << "To :" << _MDev_addr << "Remove" ;
BlueToothDBusService::devRemove(_MDev_addr);
Q_EMIT devFuncOpertionRemoveSignal(_MDev_addr);
});
QDBusInterface iface("org.ukui.panel",
"/panel/position",
"org.ukui.panel",
QDBusConnection::sessionBus());
if (iface.isValid()) {
QDBusReply<QVariantList> reply=iface.call("GetPrimaryScreenGeometry");
kdk::WindowManager::setGeometry(mesgBox->windowHandle(),
QRect((reply.value().at(2).toInt()-mesgBox->width())/2,
(reply.value().at(3).toInt()-mesgBox->height())/2,
mesgBox->width(), mesgBox->height()));
}
mesgBox->exec();
}
void bluetoothdevicefunc::showDeviceRenameWidget()
{
KyDebug();
DevRenameDialog *renameMesgBox = new DevRenameDialog();
renameMesgBox->setDevName(BlueToothDBusService::m_default_bluetooth_adapter->m_bt_dev_list[_MDev_addr]->getDevInterfaceShowName());
renameMesgBox->setRenameInterface(DevRenameDialog::DEVRENAMEDIALOG_BT_DEVICE);
connect(renameMesgBox,&DevRenameDialog::nameChanged,this,[=](QString name){
BlueToothDBusService::devRename(BlueToothDBusService::m_default_bluetooth_adapter->m_bt_dev_list[_MDev_addr]->getDevAddress(),name);
});
renameMesgBox->exec();
KyDebug() << "end" ;
}
void bluetoothdevicefunc::mStyle_GSettingsSlot(const QString &key)
{
KyDebug() << key;
if ("iconThemeName" == key || "icon-theme-name" == key)
{
_mIconThemeName = _mStyle_GSettings->get("iconThemeName").toString();
}
else if ("styleName" == key || "style-name" == key)
{
if(_mStyle_GSettings->get("style-name").toString() == "ukui-default" ||
_mStyle_GSettings->get("style-name").toString() == "ukui-light")
{
_themeIsBlack = false;
}
else
{
_themeIsBlack = true;
}
}
// initBackground();
this->update();
}
void bluetoothdevicefunc::paintEvent(QPaintEvent *event)
{
QPainter painter(this);
painter.setRenderHint(QPainter:: Antialiasing, true); //设置渲染,启动反锯齿
painter.setPen(Qt::NoPen);
painter.setBrush(this->palette().base().color());
QPalette pal = qApp->palette();
QColor color = pal.color(QPalette::Button);
color.setAlphaF(0.6);
pal.setColor(QPalette::Button, color);
this->setPalette(pal);
QPushButton::paintEvent(event);
}
void bluetoothdevicefunc::mousePressEvent(QMouseEvent *event)
{
// KyWarning();
//获取当前时间
_pressCurrentTime = QDateTime::currentDateTime().toMSecsSinceEpoch();
QPushButton::mousePressEvent(event);
}
void bluetoothdevicefunc:: mouseReleaseEvent(QMouseEvent *event)
{
// KyWarning();
if (!BlueToothDBusService::m_default_bluetooth_adapter->m_bt_dev_list.contains(_MDev_addr))
return;
long long _releaseCurrentTime = QDateTime::currentDateTime().toMSecsSinceEpoch();
//KyDebug() << "_releaseCurrentTime" << _releaseCurrentTime << "_pressCurrentTime:" << _pressCurrentTime;
//点击超时取消操作
if((_releaseCurrentTime - _pressCurrentTime) <= 300)
{
// 显示顺序
/*
*
*
*
*
*/
devMenuFunc->clear();
if (!BlueToothDBusService::m_default_bluetooth_adapter->m_bt_dev_list[_MDev_addr]->isConnected())
{
QAction * connAction = new QAction(devMenuFunc);
connAction->setText(tr("connect"));
devMenuFunc->addAction(connAction);
}
else
{
QAction * disconnAction = new QAction(devMenuFunc);
disconnAction->setText(tr("disconnect"));
devMenuFunc->addAction(disconnAction);
}
if ((bluetoothdevice::DEVICE_TYPE::phone == BlueToothDBusService::m_default_bluetooth_adapter->m_bt_dev_list[_MDev_addr]->getDevType() ||
bluetoothdevice::DEVICE_TYPE::computer == BlueToothDBusService::m_default_bluetooth_adapter->m_bt_dev_list[_MDev_addr]->getDevType()) &&
BlueToothDBusService::m_default_bluetooth_adapter->m_bt_dev_list[_MDev_addr]->getDevSendFileMark() &&
HUAWEI != envPC)
{
QAction * sendFileAction = new QAction(devMenuFunc);
sendFileAction->setText(tr("sendFile"));
devMenuFunc->addAction(sendFileAction);
}
QAction * renameAction = new QAction(devMenuFunc);
renameAction->setText(tr("rename"));
devMenuFunc->addAction(renameAction);
renameAction->setEnabled(BlueToothDBusService::m_default_bluetooth_adapter->m_bt_dev_list[_MDev_addr]->isConnected());
QAction * removeAction = new QAction(devMenuFunc);
removeAction->setText(tr("remove"));
devMenuFunc->addAction(removeAction);
//计算显示位置
QPoint currentWPoint = this->pos();
QPoint sreenPoint = QWidget::mapFromGlobal(currentWPoint);
// qInfo() << this->x() << this->y() << "======x ======y";
// qInfo() << sreenPoint.x() << sreenPoint.y() << "======sreenPoint.x ======sreenPoint.y";
// qInfo() << devMenuFunc->width() << this->width() << this->height() << "======devMenuFunc->width ======this->width ======this->height";
// qInfo() << (-1)*sreenPoint.x()+devMenuFunc->width()+this->width()+4<<(-1)*sreenPoint.y()+this->height();
//devMenuFunc->move( this->x()+devMenuFunc->width()+this->width(),this->y()+devMenuFunc->height()+this->height());
devMenuFunc->move((-1)*sreenPoint.x()+this->x()-2,(-1)*sreenPoint.y()+this->height()+2);
// devMenuFunc->setFocus();
devMenuFunc->exec();
}
QPushButton::mouseReleaseEvent(event);
emit devBtnReleaseSignal();
}

View File

@ -1,65 +0,0 @@
#ifndef BLUETOOTHDEVICEFUNC_H
#define BLUETOOTHDEVICEFUNC_H
#include <QIcon>
#include <QMenu>
#include <QTimer>
#include <QDebug>
#include <QObject>
#include <QPalette>
#include <QDateTime>
#include <QMessageBox>
#include <QPushButton>
#include <QApplication>
#include <QGSettings/QGSettings>
#include "devicebase.h"
#include "devrenamedialog.h"
#include "devremovedialog.h"
//#include "bluetoothmainwindow.h"
#include "bluetoothdbusservice.h"
#include "windowmanager/windowmanager.h"
#define ICON_PATH_NAME "view-more-horizontal-symbolic"
class bluetoothdevicefunc : public QPushButton
{
Q_OBJECT
public:
bluetoothdevicefunc(QWidget *parent ,QString dev_address);
~bluetoothdevicefunc();
void initGsettings();
void initInterface();
void initBackground();
signals:
void devFuncOpertionSignal();
void devFuncOpertionRemoveSignal(QString);
void devBtnReleaseSignal();
private slots:
void MenuSignalDeviceFunction(QAction *action);
void mStyle_GSettingsSlot(const QString &key);
void MenuSignalAboutToHide();
protected:
void paintEvent(QPaintEvent *event);
void mousePressEvent(QMouseEvent *event);
void mouseReleaseEvent(QMouseEvent *event);
private:
QMenu * devMenuFunc = nullptr;
QGSettings * _mStyle_GSettings = nullptr;
QString _MDev_addr ;
bool _themeIsBlack = false;
QString _mIconThemeName;
long long _pressCurrentTime;
void showDeviceRenameWidget();
void showDeviceRemoveWidget(DevRemoveDialog::REMOVE_INTERFACE_TYPE mode);
};
#endif // BLUETOOTHDEVICEFUNC_H

View File

@ -1,679 +0,0 @@
#include "bluetoothdeviceitem.h"
//#define RADIUS 6.0
#define DEFAULT_FONT_WIDTH 400
/**
* @brief
*
* @param parent
* @param dev
*/
bluetoothdeviceitem::bluetoothdeviceitem(QWidget *parent , QString dev_address):
QPushButton(parent),
_MDev_addr(dev_address)
{
KyDebug() << dev_address ;
if (!BlueToothDBusService::m_default_bluetooth_adapter->m_bt_dev_list.contains(dev_address))
{
KyDebug() << dev_address << "not exist";
return;
}
this->setObjectName(dev_address);
devConnectiontimer = new QTimer(this);
devConnectiontimer->setInterval(CONNECT_DEVICE_TIMING);
connect(devConnectiontimer,&QTimer::timeout,this,[=]
{
devConnOperationTimeoutSlot();
});
devConnectionFail_timer = new QTimer(this);
devConnectionFail_timer->setInterval(CONNECT_ERROR_TIMER_CLEAR);
connect(devConnectionFail_timer,&QTimer::timeout,this,[=]
{
_mConnFailCount = 0 ;
devConnectionFail_timer->stop();
});
bindDeviceChangedSignals();
initGsettings();
initInterface();
refreshInterface();
}
/**
* @brief
*
*/
bluetoothdeviceitem::~bluetoothdeviceitem()
{
KyDebug() << _MDev_addr ;
devFuncBtn->deleteLater();
devloadingLabel->deleteLater();
_mStyle_GSettings->deleteLater();
devConnectiontimer->deleteLater();
devConnectionFail_timer->deleteLater();
}
void bluetoothdeviceitem::initGsettings()
{
if (QGSettings::isSchemaInstalled(GSETTING_UKUI_STYLE))
{
_mStyle_GSettings = new QGSettings(GSETTING_UKUI_STYLE);
if(_mStyle_GSettings->get("styleName").toString() == "ukui-default" ||
_mStyle_GSettings->get("style-name").toString() == "ukui-light")
_themeIsBlack = false;
else
_themeIsBlack = true;
_mIconThemeName = _mStyle_GSettings->get("iconThemeName").toString();
}
connect(_mStyle_GSettings,&QGSettings::changed,this,&bluetoothdeviceitem::mStyle_GSettingsSlot);
}
void bluetoothdeviceitem::devStatusLoading()
{
if (devStatusLabel->isVisible())
devStatusLabel->hide();
if (!devConnectiontimer->isActive())
devConnectiontimer->start();
if (devloadingLabel->isHidden())
devloadingLabel->show();
devloadingLabel->setTimerStart();
}
void bluetoothdeviceitem::devFuncOperationSlot()
{
// KyDebug() << str_opt ;
this->clearFocus();
// if ("connect" == str_opt || "disconnect" == str_opt)
// {
// devStatusLoading();
// }
}
void bluetoothdeviceitem::devBtnPressedSlot()
{
this->update();
}
void bluetoothdeviceitem::devFuncOpertionRemoveSlot(QString address)
{
Q_EMIT bluetoothDeviceItemRemove(address);
}
void bluetoothdeviceitem::devConnOperationTimeoutSlot()
{
devloadingLabel->hide();
devloadingLabel->setTimerStop();
refreshDevCurrentStatus();
}
void bluetoothdeviceitem::initBackground()
{
this->setProperty("useButtonPalette", true);
this->setFlat(true);
}
/**
* @brief
*
*/
void bluetoothdeviceitem::initInterface()
{
KyDebug() ;
this->setMinimumSize(580, 56);
initBackground();
devItemHLayout = new QHBoxLayout(this);
devItemHLayout->setContentsMargins(16,0,16,0);
devItemHLayout->setSpacing(16);
devIconLabel = new QLabel(this);
devIconLabel->setPixmap(getDevTypeIcon());
devItemHLayout->addWidget(devIconLabel);
devNameLabel = new QLabel(this);
devNameLabel->resize(DEFAULT_FONT_WIDTH,this->height());
devNameLabel->setText(getDevName());
devItemHLayout->addWidget(devNameLabel);
devItemHLayout->addStretch(50);
devloadingLabel = new LoadingLabel(this);
devloadingLabel->setFixedSize(16,16);
devloadingLabel->setTimerStart();
devItemHLayout->addWidget(devloadingLabel, 1, Qt::AlignRight);
devloadingLabel->hide();//默认隐藏
devStatusLabel = new QLabel(this);
devStatusLabel->setText(getDevStatus());
devItemHLayout->addWidget(devStatusLabel,Qt::AlignRight);
devStatusLabel->hide();//默认隐藏
devFuncBtn = new bluetoothdevicefunc(this,_MDev_addr);
devItemHLayout->addWidget(devFuncBtn);
bindInInterfaceUISignals();
}
/**
* @brief
*
*/
void bluetoothdeviceitem::bindInInterfaceUISignals()
{
connect(devFuncBtn,SIGNAL(devFuncOpertionSignal()),this,SLOT(devFuncOperationSlot()));
connect(devFuncBtn,SIGNAL(devBtnReleaseSignal()),this,SLOT(devBtnPressedSlot()));
connect(devFuncBtn,SIGNAL(devFuncOpertionRemoveSignal(QString)),this,SLOT(devFuncOpertionRemoveSlot(QString)));
}
/**
* @brief
*
*/
void bluetoothdeviceitem::refreshInterface()
{
KyDebug() << __LINE__;
//优先级状态判断
//if(_MDev->getDevPairing() || _MDev->getDevConnecting())
if(BlueToothDBusService::m_default_bluetooth_adapter->m_bt_dev_list[_MDev_addr]->getDevConnecting())
{
devStatusLabel->hide();
devConnectiontimer->start();
devloadingLabel->show();
devloadingLabel->setTimerStart();
}
else if(BlueToothDBusService::m_default_bluetooth_adapter->m_bt_dev_list[_MDev_addr]->isPaired() ||
BlueToothDBusService::m_default_bluetooth_adapter->m_bt_dev_list[_MDev_addr]->isConnected())
{
devStatusLabel->show();
devloadingLabel->hide();
}
else
{
devStatusLabel->hide();
devloadingLabel->hide();
}
devFuncBtn->setVisible(BlueToothDBusService::m_default_bluetooth_adapter->m_bt_dev_list[_MDev_addr]->isPaired());
}
void bluetoothdeviceitem::devItemNameChanged(const QString &name)
{
KyDebug() << name << __LINE__;
if (devNameLabel)
{
QFontMetrics fontWidth(devNameLabel->font());//得到QLabel字符的度量
int font_w = fontWidth.width(name);
QString elidedNote = name ;
if (font_w > DEFAULT_FONT_WIDTH)
elidedNote = fontWidth.elidedText(name, Qt::ElideMiddle, DEFAULT_FONT_WIDTH);//获取处理后的文本
if(elidedNote != name)
{
devNameLabel->setToolTip(name);
}
else
{
devNameLabel->setToolTip("");
}
devNameLabel->setText(elidedNote);
}
KyDebug() << "end" << __LINE__;
}
void bluetoothdeviceitem::devItemTypeChanged(const bluetoothdevice::DEVICE_TYPE &type)
{
KyDebug() << type << __LINE__;
if (devIconLabel)
devIconLabel->setPixmap(getDevTypeIcon());
KyDebug() << "end" << __LINE__;
}
void bluetoothdeviceitem::devItemStatusChanged(const QString &status)
{
KyDebug() << status << __LINE__;
if (devStatusLabel)
devStatusLabel->setText(status);
KyDebug() << "end" << __LINE__;
}
/**
* @brief
*
*/
void bluetoothdeviceitem::bindDeviceChangedSignals()
{
KyDebug();
if (BlueToothDBusService::m_default_bluetooth_adapter && BlueToothDBusService::m_default_bluetooth_adapter->m_bt_dev_list.contains(_MDev_addr))
{
KyDebug() << "connect dev item";
connect(BlueToothDBusService::m_default_bluetooth_adapter->m_bt_dev_list[_MDev_addr],&bluetoothdevice::nameChanged,this,[=](const QString &name)
{
KyDebug()<< BlueToothDBusService::m_default_bluetooth_adapter->m_bt_dev_list[_MDev_addr]->getDevName()
<< BlueToothDBusService::m_default_bluetooth_adapter->m_bt_dev_list[_MDev_addr]->getDevAddress()
<<"nameChanged:" << name ;
if (BlueToothDBusService::m_default_bluetooth_adapter->m_bt_dev_list[_MDev_addr]->getDevShowName().isEmpty())
devItemNameChanged(name);
});
connect(BlueToothDBusService::m_default_bluetooth_adapter->m_bt_dev_list[_MDev_addr],&bluetoothdevice::showNameChanged,this,[=](const QString &name)
{
KyDebug()<< BlueToothDBusService::m_default_bluetooth_adapter->m_bt_dev_list[_MDev_addr]->getDevName()
<< BlueToothDBusService::m_default_bluetooth_adapter->m_bt_dev_list[_MDev_addr]->getDevAddress()
<< "showNameChanged:" << name ;
devItemNameChanged(name);
});
connect(BlueToothDBusService::m_default_bluetooth_adapter->m_bt_dev_list[_MDev_addr],&bluetoothdevice::typeChanged,this,[=](bluetoothdevice::DEVICE_TYPE type)
{
KyDebug()<< BlueToothDBusService::m_default_bluetooth_adapter->m_bt_dev_list[_MDev_addr]->getDevName()
<< BlueToothDBusService::m_default_bluetooth_adapter->m_bt_dev_list[_MDev_addr]->getDevAddress()
<< "typeChanged:" << type ;
devItemTypeChanged(type);
});
connect(BlueToothDBusService::m_default_bluetooth_adapter->m_bt_dev_list[_MDev_addr],&bluetoothdevice::pairedChanged,this,[=](bool paired)
{
KyDebug()<< BlueToothDBusService::m_default_bluetooth_adapter->m_bt_dev_list[_MDev_addr]->getDevName()
<< BlueToothDBusService::m_default_bluetooth_adapter->m_bt_dev_list[_MDev_addr]->getDevAddress()
<< "pairedChanged:" << paired ;
if (paired)
{
emit devPairedSuccess(BlueToothDBusService::m_default_bluetooth_adapter->m_bt_dev_list[_MDev_addr]->getDevAddress());
}
refreshDevCurrentStatus();
});
connect(BlueToothDBusService::m_default_bluetooth_adapter->m_bt_dev_list[_MDev_addr],&bluetoothdevice::connectedChanged,this,[=](bool connected)
{
KyDebug()<< BlueToothDBusService::m_default_bluetooth_adapter->m_bt_dev_list[_MDev_addr]->getDevName()
<< BlueToothDBusService::m_default_bluetooth_adapter->m_bt_dev_list[_MDev_addr]->getDevAddress()
<< "connectedChanged:" << connected ;
if (BlueToothDBusService::m_default_bluetooth_adapter->m_bt_dev_list[_MDev_addr]->isPaired())
{
emit devPairedSuccess(BlueToothDBusService::m_default_bluetooth_adapter->m_bt_dev_list[_MDev_addr]->getDevAddress());
}
refreshDevCurrentStatus();
});
connect(BlueToothDBusService::m_default_bluetooth_adapter->m_bt_dev_list[_MDev_addr],&bluetoothdevice::connectingChanged,this,[=](bool connecting)
{
KyDebug()<< BlueToothDBusService::m_default_bluetooth_adapter->m_bt_dev_list[_MDev_addr]->getDevName()
<< BlueToothDBusService::m_default_bluetooth_adapter->m_bt_dev_list[_MDev_addr]->getDevAddress()
<< "connectingChanged:" << connecting ;
refreshDevCurrentStatus();
if(connecting)
{
BlueToothMainWindow::m_device_operating = true ;
}
else
{
BlueToothMainWindow::m_device_operating = false;
}
devFuncBtn->setEnabled(!connecting);
});
connect(BlueToothDBusService::m_default_bluetooth_adapter->m_bt_dev_list[_MDev_addr],&bluetoothdevice::errorInfoRefresh,this,[=](int errorId , QString errorText)
{
KyDebug()<< BlueToothDBusService::m_default_bluetooth_adapter->m_bt_dev_list[_MDev_addr]->getDevName()
<< BlueToothDBusService::m_default_bluetooth_adapter->m_bt_dev_list[_MDev_addr]->getDevAddress()
<<"error:" << errorId << errorText ;
refreshDevCurrentStatus();
if (errorId && BlueToothDBusService::m_default_bluetooth_adapter->m_bt_dev_list[_MDev_addr]->isPaired())
devConnectionFail();
});
connect(BlueToothDBusService::m_default_bluetooth_adapter->m_bt_dev_list[_MDev_addr],&bluetoothdevice::rssiChanged,this,[=](qint16 value)
{
KyDebug()<< BlueToothDBusService::m_default_bluetooth_adapter->m_bt_dev_list[_MDev_addr]->getDevName()
<< BlueToothDBusService::m_default_bluetooth_adapter->m_bt_dev_list[_MDev_addr]->getDevAddress()
<< "rssiChanged:" << value ;
if (!BlueToothDBusService::m_default_bluetooth_adapter->m_bt_dev_list[_MDev_addr]->isPaired())
emit devRssiChanged(value);
});
}
}
/************************************************
* @brief getDevTypeIcon
* @param null
* @return QPixmap
*************************************************/
QPixmap bluetoothdeviceitem::getDevTypeIcon()
{
KyDebug();
QPixmap icon;
QString iconName;
if (BlueToothDBusService::m_default_bluetooth_adapter->m_bt_dev_list.contains(_MDev_addr)) {
switch (BlueToothDBusService::m_default_bluetooth_adapter->m_bt_dev_list[_MDev_addr]->getDevType()) {
case bluetoothdevice::DEVICE_TYPE::phone:
iconName = "phone-symbolic";
break;
case bluetoothdevice::DEVICE_TYPE::computer:
iconName = "video-display-symbolic";
break;
case bluetoothdevice::DEVICE_TYPE::headset:
case bluetoothdevice::DEVICE_TYPE::headphones:
iconName = "audio-headphones-symbolic";
break;
case bluetoothdevice::DEVICE_TYPE::audiovideo:
iconName = "audio-speakers-symbolic";
break;
case bluetoothdevice::DEVICE_TYPE::keyboard:
iconName = "input-keyboard-symbolic";
break;
case bluetoothdevice::DEVICE_TYPE::mouse:
iconName = "input-mouse-symbolic";
break;
default:
iconName = "bluetooth-symbolic";
break;
}
}
else
{
iconName = "bluetooth-symbolic";
}
if (_themeIsBlack)
{
icon = ukccbluetoothconfig::loadSvg(QIcon::fromTheme(iconName).pixmap(DEV_ICON_WH),ukccbluetoothconfig::WHITE);
}
else
{
icon = QIcon::fromTheme(iconName).pixmap(DEV_ICON_WH);
}
return icon;
}
/************************************************
* @brief getDevName
* @param null
* @return QString
*************************************************/
QString bluetoothdeviceitem::getDevName()
{
KyDebug() ;
QString name;
if (BlueToothDBusService::m_default_bluetooth_adapter->m_bt_dev_list.contains(_MDev_addr))
name = BlueToothDBusService::m_default_bluetooth_adapter->m_bt_dev_list[_MDev_addr]->getDevInterfaceShowName();
else
name = "Bluetooth Test Name";
if(devNameLabel)
{
QFontMetrics fontWidth(devNameLabel->font());//得到QLabel字符的度量
int font_w = fontWidth.width(name);
QString elidedNote = name ;
if (font_w > DEFAULT_FONT_WIDTH)
elidedNote = fontWidth.elidedText(name, Qt::ElideMiddle, DEFAULT_FONT_WIDTH);//获取处理后的文本
if(elidedNote != name)
{
devNameLabel->setToolTip(name);
return elidedNote;
}
else
{
devNameLabel->setToolTip("");
}
}
return name;
}
/**
* @brief
*
* @return QString
*/
QString bluetoothdeviceitem::getDevStatus()
{
KyDebug();
QString strStatus;
if (BlueToothDBusService::m_default_bluetooth_adapter->m_bt_dev_list.contains(_MDev_addr))
{
//注意判断优先级
//if (_MDev->getDevPairing() || _MDev->getDevConnecting())
if (BlueToothDBusService::m_default_bluetooth_adapter->m_bt_dev_list[_MDev_addr]->getDevConnecting())
{
strStatus = m_str_connecting;
}
else if (!BlueToothDBusService::m_default_bluetooth_adapter->m_bt_dev_list[_MDev_addr]->isPaired() && 0 != BlueToothDBusService::m_default_bluetooth_adapter->m_bt_dev_list[_MDev_addr]->getErrorId())
{
strStatus = m_str_connectionfail;
}
else if (BlueToothDBusService::m_default_bluetooth_adapter->m_bt_dev_list[_MDev_addr]->isPaired() && !BlueToothDBusService::m_default_bluetooth_adapter->m_bt_dev_list[_MDev_addr]->isConnected())
{
strStatus = m_str_notconnected;
}
else if (BlueToothDBusService::m_default_bluetooth_adapter->m_bt_dev_list[_MDev_addr]->isPaired() && BlueToothDBusService::m_default_bluetooth_adapter->m_bt_dev_list[_MDev_addr]->isConnected())
{
strStatus = m_str_connected;
}
else
{
strStatus = m_str_notpaired;
}
}
else
strStatus = m_str_notpaired;
return strStatus;
}
void bluetoothdeviceitem::refreshDevCurrentStatus()
{
KyDebug() ;
if (BlueToothDBusService::m_default_bluetooth_adapter->m_bt_dev_list[_MDev_addr]->getDevConnecting())
{
devStatusLoading();
}
else if (BlueToothDBusService::m_default_bluetooth_adapter->m_bt_dev_list[_MDev_addr]->isPaired() && !BlueToothDBusService::m_default_bluetooth_adapter->m_bt_dev_list[_MDev_addr]->isConnected())
{
devItemStatusChanged(getDevStatus());
if (devStatusLabel->isHidden())
{
devStatusLabel->show();
}
// devStatusLabel->setEnabled(false);
//if (devloadingLabel->isVisible())
{
devloadingLabel->hide();
devloadingLabel->setTimerStop();
}
// if (devFuncFrame->isHidden())
// devFuncFrame->show();
if (devFuncBtn->isHidden())
devFuncBtn->show();
if (devConnectiontimer->isActive())
devConnectiontimer->stop();
}
else if (BlueToothDBusService::m_default_bluetooth_adapter->m_bt_dev_list[_MDev_addr]->isPaired() && BlueToothDBusService::m_default_bluetooth_adapter->m_bt_dev_list[_MDev_addr]->isConnected())
{
devItemStatusChanged(getDevStatus());
if (devStatusLabel->isHidden())
{
devStatusLabel->show();
}
// devStatusLabel->setEnabled(true);
//KyWarning() << "devloadingLabel->isVisible()" << "devFuncFrame->isHidden()" << "devFuncFrame->isVisible()";
//KyWarning() << devloadingLabel->isVisible() << devloadingLabel->isHidden() << devFuncFrame->isHidden() << devFuncFrame->isVisible();
//if (devloadingLabel->isHidden())
{
devloadingLabel->hide();
devloadingLabel->setTimerStop();
}
//KyWarning() << devFuncFrame->isHidden() << devFuncFrame->isVisible();
// if (devFuncFrame->isHidden())
// devFuncFrame->show();
if (devFuncBtn->isHidden())
devFuncBtn->show();
if (devConnectiontimer->isActive())
devConnectiontimer->stop();
}
else if (0 != BlueToothDBusService::m_default_bluetooth_adapter->m_bt_dev_list[_MDev_addr]->getErrorId())
{
devItemStatusChanged(getDevStatus());
if (devStatusLabel->isHidden())
devStatusLabel->show();
//if (devloadingLabel->isVisible())
{
devloadingLabel->hide();
devloadingLabel->setTimerStop();
}
if(devConnectiontimer->isActive())
devConnectiontimer->stop();
}
else
{
if (devStatusLabel->isVisible())
devStatusLabel->hide();
if (devloadingLabel->isVisible())
{
devloadingLabel->hide();
devloadingLabel->setTimerStop();
}
if (devConnectiontimer->isActive())
devConnectiontimer->stop();
}
}
void bluetoothdeviceitem::devConnectionFail()
{
KyDebug() << "_mConnFailCount :" << _mConnFailCount << "devConnectionFail_timer->isActive():" << devConnectionFail_timer->isActive();
if ((0 == _mConnFailCount) && !devConnectionFail_timer->isActive())
devConnectionFail_timer->start();
_mConnFailCount++;
if (_mConnFailCount > CONNECT_ERROR_COUNT)
{
_mConnFailCount = 0;
devConnectionFail_timer->stop();
showDeviceRemoveWidget(DevRemoveDialog::REMOVE_MANY_TIMES_CONN_FAIL_DEV);
}
}
void bluetoothdeviceitem::showDeviceRemoveWidget(DevRemoveDialog::REMOVE_INTERFACE_TYPE mode)
{
DevRemoveDialog *mesgBox = new DevRemoveDialog(mode);
mesgBox->setModal(true);
mesgBox->setDialogText(BlueToothDBusService::m_default_bluetooth_adapter->m_bt_dev_list[_MDev_addr]->getDevInterfaceShowName());
//rejected
connect(mesgBox,&DevRemoveDialog::rejected,this,[=]{
_mConnFailCount = 0;
devConnectionFail_timer->stop();
});
//accepted
connect(mesgBox,&DevRemoveDialog::accepted,this,[=]{
KyDebug() << "To :" << BlueToothDBusService::m_default_bluetooth_adapter->m_bt_dev_list[_MDev_addr]->getDevName() << "Remove" ;
BlueToothDBusService::devRemove(BlueToothDBusService::m_default_bluetooth_adapter->m_bt_dev_list[_MDev_addr]->getDevAddress());
});
mesgBox->exec();
}
void bluetoothdeviceitem::mStyle_GSettingsSlot(const QString &key)
{
KyDebug() << key;
if ("iconThemeName" == key || "icon-theme-name" == key)
{
_mIconThemeName = _mStyle_GSettings->get("iconThemeName").toString();
if (devIconLabel)
devIconLabel->setPixmap(getDevTypeIcon());
}
else if ("styleName" == key || "style-name" == key)
{
if(_mStyle_GSettings->get("style-name").toString() == "ukui-default" ||
_mStyle_GSettings->get("style-name").toString() == "ukui-light")
{
_themeIsBlack = false;
}
else
{
_themeIsBlack = true;
}
if (devIconLabel)
devIconLabel->setPixmap(getDevTypeIcon());
}
// initBackground();
this->update();
}
void bluetoothdeviceitem::paintEvent(QPaintEvent *event)
{
QPainter painter(this);
painter.setRenderHint(QPainter:: Antialiasing, true); //设置渲染,启动反锯齿
painter.setPen(Qt::NoPen);
painter.setBrush(this->palette().base().color());
QPalette pal = qApp->palette();
QColor color = pal.color(QPalette::Button);
color.setAlphaF(0.5);
pal.setColor(QPalette::Button, color);
this->setPalette(pal);
QPushButton::paintEvent(event);
}
void bluetoothdeviceitem::mousePressEvent(QMouseEvent *event)
{
KyWarning();
//获取当前时间
_pressCurrentTime = QDateTime::currentDateTime().toMSecsSinceEpoch();
QPushButton::mousePressEvent(event);
}
void bluetoothdeviceitem::mouseReleaseEvent(QMouseEvent *event)
{
KyWarning();
long long _releaseCurrentTime = QDateTime::currentDateTime().toMSecsSinceEpoch();
KyDebug() << "_releaseCurrentTime" << _releaseCurrentTime << "_pressCurrentTime:" << _pressCurrentTime;
if(BlueToothDBusService::m_default_bluetooth_adapter->m_bt_dev_list.contains(_MDev_addr) && (_releaseCurrentTime - _pressCurrentTime) <= 300)
{//点击超时取消操作
if (!BlueToothDBusService::m_default_bluetooth_adapter->m_bt_dev_list[_MDev_addr]->isConnected() && !BlueToothMainWindow::m_device_operating)
{
devStatusLoading();
BlueToothDBusService::m_default_bluetooth_adapter->m_bt_dev_list[_MDev_addr]->setDevConnecting(true);
BlueToothDBusService::devConnect(BlueToothDBusService::m_default_bluetooth_adapter->m_bt_dev_list[_MDev_addr]->getDevAddress());
}
}
QPushButton::mouseReleaseEvent(event);
}
void bluetoothdeviceitem::mouseMoveEvent(QMouseEvent *e)
{
KyWarning();
}

View File

@ -1,130 +0,0 @@
#ifndef BLUETOOTHDEVICEITEM_H
#define BLUETOOTHDEVICEITEM_H
#include "devicebase.h"
#include "loadinglabel.h"
#include "devremovedialog.h"
#include "bluetoothdevicefunc.h"
#include "bluetoothmainwindow.h"
#include "bluetoothdbusservice.h"
#include <QChar>
#include <QIcon>
#include <QMenu>
#include <QFont>
#include <QFrame>
#include <QLabel>
#include <QColor>
#include <QTimer>
#include <QDebug>
#include <QStyle>
#include <QObject>
#include <QString>
#include <QPainter>
#include <QDateTime>
#include <QPushButton>
#include <QMouseEvent>
#include <QMessageBox>
#include <QFontMetrics>
#include <QApplication>
#include <QAbstractButton>
#include <QGSettings/QGSettings>
#include "windowmanager/windowmanager.h"
#define CONNECT_ERROR_COUNT (3)
#define CONNECT_DEVICE_TIMING (35*1000)
#define CONNECT_ERROR_TIMER_CLEAR (3*60*1000) //3分钟内用户来连接失败超过3次提示用户是否移除后重新配对连接
#define DEV_ICON_WH 16,16
class bluetoothdeviceitem : public QPushButton
{
Q_OBJECT
public:
enum _DEV_STATUS {
Dev_Connecting,
Dev_Disconnecting,
Dev_NotPaired,
Dev_NotConnected,
Dev_ConnectionFail,
Dev_DisconnectionFail
};//(_DEV_STATUS);
bluetoothdeviceitem(QWidget *parent = nullptr , QString dev_address="");
~bluetoothdeviceitem();
QString m_str_unknown = tr("unknown");
QString m_str_connecting = tr("Connecting");
QString m_str_disconnecting = tr("Disconnecting");
QString m_str_notpaired = tr("Not Paired");
QString m_str_notconnected = tr("Not Connected");
QString m_str_connected = tr("Connected");
QString m_str_connectionfail = tr("Connect fail,Please try again");
QString m_str_disconnectionfail = tr("Disconnection Fail");
private:
QHBoxLayout * devItemHLayout = nullptr;
QHBoxLayout * devFuncHLayout = nullptr;
QLabel * devIconLabel = nullptr;
QLabel * devNameLabel = nullptr;
QLabel * devStatusLabel = nullptr;
// QFrame * devFuncFrame = nullptr;
bluetoothdevicefunc * devFuncBtn = nullptr;
LoadingLabel * devloadingLabel = nullptr;
QTimer * devConnectiontimer = nullptr;
QTimer * devConnectionFail_timer = nullptr;
QString getDevName();
QString getDevStatus();
QPixmap getDevTypeIcon();
void initGsettings();
void initBackground();
void initInterface();
void refreshInterface();
void devStatusLoading();
void bindInInterfaceUISignals();
void bindDeviceChangedSignals();
void refreshDevCurrentStatus();
void devConnectionFail();
void showDeviceRemoveWidget(DevRemoveDialog::REMOVE_INTERFACE_TYPE);
uint _mConnFailCount = 0;
bool _themeIsBlack = false;
QString _mIconThemeName;
long long _pressCurrentTime;
QString _MDev_addr ;
QGSettings * _mStyle_GSettings = nullptr;
protected:
void paintEvent(QPaintEvent *event);
void mousePressEvent(QMouseEvent *event);
void mouseReleaseEvent(QMouseEvent *event);
void mouseMoveEvent(QMouseEvent *e);
private Q_SLOTS:
void devFuncOperationSlot();
void devConnOperationTimeoutSlot();
void devItemNameChanged(const QString &);
void devItemTypeChanged(const bluetoothdevice::DEVICE_TYPE &);
void devItemStatusChanged(const QString &);
void mStyle_GSettingsSlot(const QString &key);
void devBtnPressedSlot();
void devFuncOpertionRemoveSlot(QString);
signals:
void devFuncOptSignals();
void devPairedSuccess(QString);
void devRssiChanged(qint64);
void bluetoothDeviceItemRemove(QString);
};
#endif // BLUETOOTHDEVICEITEM_H

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,326 @@
#ifndef BLUETOOTHMAIN_H
#define BLUETOOTHMAIN_H
#include <QQueue>
#include <QVector>
#include <QList>
#include <QMainWindow>
#include <QVBoxLayout>
#include <QHBoxLayout>
#include <QGridLayout>
#include <QString>
#include <QDebug>
#include <QLabel>
#include <QFrame>
#include <QSystemTrayIcon>
#include <QFont>
#include <QMetaType>
#include <QSizePolicy>
#include <QWidget>
#include <QScrollArea>
#include <QMenu>
#include <QTimer>
#include <QVariant>
#include <QProcess>
#include <QComboBox>
#include <QMetaEnum>
#include <QVector>
#include <QStringView>
#include <QLayoutItem>
#include <QMouseEvent>
#include <QStackedWidget>
#include <QDBusObjectPath>
#include <QtDBus/QDBusReply>
#include <QtDBus/QDBusInterface>
#include <QtDBus/QDBusConnection>
#include <QtDBus/QDBusAbstractAdaptor>
#include <QtDBus/QDBusConnectionInterface>
#include <polkit-qt5-1/PolkitQt1/Authority>
#include <QGSettings/QGSettings>
#include <QMetaEnum>
#include <QTranslator>
#include <QApplication>
#include <QDBusMessage>
#include <QMessageLogger>
#include <QStandardPaths>
//#include <ukcc/widgets/switchbutton.h>
//#include <ukcc/widgets/titlelabel.h>
//#include <ukcc/widgets/imageutil.h>
#include "config.h"
#include "devicebase.h"
#include "deviceinfoitem.h"
#include "bluetoothnamelabel.h"
#include "ukccbluetoothconfig.h"
#include "bluetoothdbusservice.h"
#include "kswitchbutton.h"
using namespace kdk;
#define GSETTING_STR_ACTIVE_CONNECTION "active-connection"
#define GSETTING_STR_ACTIVE_CONNECTION_TRAN "activeConnection"
class BlueToothMain : public QMainWindow
{
Q_OBJECT
public:
enum DevTypeShow {
All = 0,
Audio,
Peripherals,
PC,
Phone,
Other,
};
Q_ENUM(DevTypeShow)
BlueToothMain(QWidget *parent = nullptr);
~BlueToothMain();
protected:
void leaveEvent(QEvent *event);
//dev-3.1 界面服务分离
public:
static bool m_device_operating ; //有设备正在操作
static QString m_device_operating_address ;//正在操作设备的mac地址
static bool m_device_pin_flag ;
void setbluetoothAdapterDiscoveringStatus(bool);
signals:
void sendAdapterNameChangeSignal(const QString &value);
void defaultAdapterNameChanged(const QString &name);
private slots:
//report
void reportDefaultAdapterChanged(QString);
void reportDefaultAdapterNameChanged(QString);
void reportAdapterAddSignal(QString );
void reportAdapterRemoveSignal(QString);
void reportPowerProgress(bool);
void reportDefaultAdapterPowerChanged(bool);
void reportDefaultDiscoverableChanged(bool);
void reportDefaultScanStatusChanged(bool);
void reportDeviceScanResult(QString,QString,QString,bool,qint16);
void reportDevRemoveSignal(QString);
void reportDevPairSignal(QString,bool);
void reportDevConnectStatusSignal(QString,bool);
void reportDevNameChangedSignal(QString,QString);
void reportDevTypeChangedSignal(QString,QString);
void reportRequestConfirmation(QString,QString);
void reportDisplayPasskey(QString,QString);
void reportReplyRequestConfirmation(bool);
void reportDevOperateErrorSignal(QString,int,QString);
void reportDevMacAddressChangedSignal(QString,QString);
void reportClearBluetoothDev(QStringList);
void reportDevRssiChangedSignal(QString,qint16);
void reportDevLaunchConnecting(QString);
//receive
void receiveConnectsignal(QString);
void receiveDisConnectSignal(QString);
void receiveRemoveSignal(QString);
//gsetting
void setTrayVisible(bool);
void onClick_Open_Bluetooth(bool);
void changeDeviceParentWindow(const QString &address);
void refreshLoadLabelIcon();
void refreshWaitLabelIcon();
void monitorSleepSlot(bool value);
void changeListOfDiscoveredDevices(int);
void receiveSendFileSignal(QString);
void gSettingsChanged(const QString &);
void adapterPoweredChanged(bool value);
void adapterComboxChanged(int i);
void adapterListComboxEnabledState(bool);
void gSettingsBluetoothChanged(const QString &);
void longTimeNoDevAddSlots();
private:
QStackedWidget * _MCentralWidget = nullptr;
QWidget * frame_top = nullptr;
QFrame *line_frame1 = nullptr;
QFrame *frame_2 = nullptr;
QFrame *line_frame2 = nullptr;
QFrame *frame_3 = nullptr;
QFrame *line_frame3 = nullptr;
QFrame *frame_4 = nullptr;
QFrame *line_frame4 = nullptr;
QFrame *frame_5 = nullptr;
QWidget * frame_middle = nullptr;
QWidget * frame_bottom = nullptr;
QWidget * m_normal_main_widget = nullptr;
QWidget * m_error_main_widget = nullptr;
QWidget *_MAdapterLoadingWidget = nullptr;
QVBoxLayout * errorWidgetLayout = nullptr;
QLabel * errorWidgetIcon = nullptr;
QLabel * errorWidgetTip0 = nullptr;
QFrame * mDev_frame = nullptr;
QFrame * device_list = nullptr;
QVBoxLayout * device_list_layout = nullptr;
BluetoothNameLabel * bluetooth_name = nullptr;
QVBoxLayout * paired_dev_layout = nullptr;
QVBoxLayout * main_layout = nullptr;
QComboBox * cacheDevTypeList = nullptr;
QLabel * label_2 = nullptr;
QLabel * loadLabel = nullptr;
QLabel * waitLabel = nullptr;
//QString Default_Adapter;
QGSettings * m_settings = nullptr;
QGSettings * styleSettings = nullptr;
int i = 7;
int cnt = 7;
bool sleep_status = false;
bool m_myDev_show_flag = false;
bool isblack = false;
bool m_service_dbus_adapter_power_change_flag = false;
bool m_service_dbus_adapter_discovery_change_flag = false;
bool m_current_adapter_power_swtich;
bool m_current_adapter_disconvery_swtich;
bool m_current_bluetooth_block_status;
bool m_current_adapter_scan_status; //正在扫描true否则false
bool m_current_active_connection_status = false;
QString m_default_adapter_name;
QString m_default_adapter_address;
QStringList m_adapter_name_list;
QStringList m_adapter_address_list;
//QStringList last_discovery_device_address;
QStringList m_default_adapter_paired_device_address_list; //默认适配器的配对列表
QStringList m_discovery_device_address_all_list; //所有device mac list
QStringList m_load_device_address_list; //加载的所有的device list
KSwitchButton * m_open_bluetooth_btn = nullptr;
KSwitchButton * m_show_panel_btn = nullptr;
KSwitchButton * m_discover_switch_btn = nullptr;
KSwitchButton * m_active_scan_switch_btn = nullptr;
QComboBox * m_adapter_list_cmbox = nullptr;
QComboBox * m_cache_dev_type_list_cmbox = nullptr;
bluetoothadapter * m_default_bluetooth_adapter = nullptr ;
QList <bluetoothadapter *> m_bluetooth_adapter_list;
//QList <bluetoothdevice *> m_bluetooth_device_list;
DevTypeShow discoverDevFlag = DevTypeShow::All;
QTimer * m_timer = nullptr;
QTimer * w_timer = nullptr;
QTimer * delayStartDiscover_timer = nullptr;
//用于实时监控蓝牙适配器状态的计时器
//长时间未收到新增设备时检测当前适配器是否处于扫描状态
//若不处于扫描状态则开启
QTimer * longTimeNoDevAddSignal_timer = nullptr;
// QQueue <bluetoothdevice *> devPreShowQue;
QTimer * devPreShow_timer = nullptr;
QTimer * adapterListCmbox_timer = nullptr;
int m_loadingWindx = 0;
QTimer * m_loadingWIcontimer = nullptr;
QTimer * m_loadingWBTAdapterTimer = nullptr;
QTimer * m_loadingWBTServiceTimer = nullptr;
private:
void mDevFrameAddLineFrame(int ,QString,QString);
void removeMDevFrameLineFrame(QString);
void monitorBluetoothDbusConnection();
void removeDeviceItemUI(QString address);
void addMyDeviceItemUI(bluetoothdevice *);
void monitorSleepSignal();
void cleanPairDevices();
void addDiscoverDevListByFlag(DevTypeShow);
//get adapter data
void connectBluetoothServiceSignal();
void initTimerLoadDevFunction();
void getAllAdapterData();
void getDefaultAdapterData(QString);
QStringList getAdapterDevAddressList();
QStringList getAdapterDevNameList();
QString getDefaultAdapterAddress();
QString getAdapterName(QString);
bool getBluetoothBlock();
bool getDefaultAdapterPower();
bool getDefaultAdapterDiscoverable();
bool getDefaultAdapterScanStatus();
QStringList getDefaultAdapterPairedDevAddress();
QStringList getDefaultAdapterCacheDevAddress();
QString getDevName(QString);
bluetoothdevice::DEVICE_TYPE getDeviceType(QString,QString);
QString getDevType(QString);
bool getDevPairStatus(QString);
bool getDevConnectStatus(QString);
bool getDevSupportFileSend(QString);
qint16 getDevRssi(QString);
int getDevAddressItemIndex(QString);
int getDevRssiItemInsertIndex(qint16);
void clearAllUnPairedDevicelist();
void clearNonViableDevice(QStringList);
//QStringList getAdapterNameList();
void setBluetoothBlock(bool);
void setDefaultAdapterPower(bool);
void setDefaultAdapter(QString);
void setDefaultAdapterName(QString);
void setDefaultAdapterDiscoverable(bool);
void setDefaultAdapterScanOn(bool);
// Dbus注册
bool registerClient();
bool unregisterClient();
//
void showBluetoothNormalMainWindow();
void initMainWindowTopUI();
void initMainWindowMiddleUI();
void initMainWindowbottomUI();
void initMainWindowParameters();
void showBluetoothErrorMainWindow();
void showBluetoothloadingMainWindow();
void refreshUIWhenAdapterChanged();
void refreshBluetoothAdapterInterfaceUI();
bool isInvalidDevice(QString , bluetoothdevice::DEVICE_TYPE);
bluetoothdevice * createOneBluetoothDeviceFromMacAddress(QString);
bluetoothdevice * createOneBluetoothDeviceFromBluetoothService(QString,QString,QString,bool,qint16);
bluetoothadapter * createOneBluetoothAdapter(QString);
bool whetherToAddCurrentInterface(bluetoothdevice *);
void addOneBluetoothDeviceItemUi(bluetoothdevice *);
void addAdapterDataList(QString);
void removeAdapterDataList(QString);
void stopAllTimer();
void setGSettingsActiveConnectionStatus(bool);
void RefreshMyDeviceInterface();
};
#endif // BLUETOOTHMAIN_H

File diff suppressed because it is too large Load Diff

View File

@ -1,186 +1,77 @@
#ifndef BLUETOOTHMAINWINDOW_H
#define BLUETOOTHMAINWINDOW_H
#include <QIcon>
#include <QTimer>
#include <QLabel>
#include <QFrame>
#include <QDebug>
#include <QObject>
#include <QString>
#include <ukcc/widgets/switchbutton.h>
#include "bluetoothnamelabel.h"
#include "loadinglabel.h"
#include <QMainWindow>
#include <QWidget>
#include <QStackedWidget>
#include <QWidget>
#include <QComboBox>
#include <QMetaEnum>
#include <QMainWindow>
#include <QStringList>
#include <QVBoxLayout>
#include <QHBoxLayout>
#include <QStackedWidget>
#include "loadinglabel.h"
#include <QLabel>
#include <QString>
#include <QFrame>
#include <QStringList>
#include <QDebug>
#include <QIcon>
#include <QMetaEnum>
#include "kswitchbutton.h"
#include "bluetoothnamelabel.h"
#include "bluetoothdeviceitem.h"
#define MAINWINDOW_ERROR_ABNORMAL_DRIVE 0
#define MAINWINDOW_ERROR_ADAPTER_NOT_DETECTED 1
#define MAINWINDOW_LOADING_INTERFACE 2
#define MAINWINDOW_NORMAL_INTERFACE 3
using namespace kdk;
class BlueToothMainWindow : public QMainWindow
{
Q_OBJECT
public:
enum _DEV_TYPE {
BT_All = 0,
BT_Audio,
BT_Peripherals,
BT_Computer,
BT_Phone,
BT_Other,
enum DEVTYPESHOW {
All = 0,
Audio,
Peripherals,
Computer,
Phone,
Other,
};
Q_ENUM(_DEV_TYPE);
//记录当前是否蓝牙界面是否在操作状态
static bool m_device_operating; //有设备正在操作
//
const QStringList devTypeSelectStrList = {tr("All"), \
tr("Audio"), \
tr("Peripherals"), \
tr("Computer"), \
tr("Phone"), \
tr("Other")};
Q_ENUM(DEVTYPESHOW);
explicit BlueToothMainWindow(QWidget *parent = nullptr);
~BlueToothMainWindow();
void InitInterfaceUIStatus();
protected:
void InitMainWindow();
void InitAbnormalErrorWidget();
void InitNoAdapterErrorWidget();
void InitAdapterLoadingWidget();
void setAdapterLoadingWidget(int m_mode);
void InitError0Widget();
void InitError1Widget();
void InitNormalWidget();
void InitNormalWidgetTop();
void InitNormalWidgetMiddle();
void InitNormalWidgetBottom();
void InitBluetoothServiceSignalBinding();
void InitInterfaceUISignalBinding();
public slots:
void addMyDeviceItemUI(QString);
void addOneBluetoothDeviceItemUi(QString);
private slots:
//界面槽
void setDefaultAdapterNameSlot(QString);
void _BtSwitchBtnSlot(bool status);
void adapterPowerStatusChangedSlot(bool);
void adapterNameChangedSlot(QString);
void _BtTrayIconShowSlot(bool status);
void adapterTrayIconSlot(bool status);
void _BtDiscoverableSlot(bool status);
void adapterDiscoverableSlot(bool status);
void _BtAutoAudioConnBtnSlot(bool status);
void adapterActiveConnectionSlot(bool status);
void adapterDiscoveringSlot(bool status);
void _AdapterListSelectComboBoxSlot(int indx);
void _DevTypeSelectComboBoxSlot(int indx);
//dev slot
void adapterAddSlot(QString adapter_name);
void adapterRemoveSlot(int indx);
void defaultAdapterChangedSlot(int);
void deviceAddSlot(QString);
void deviceRemoveSlot(QString);
void btServiceRestartSlot();
void btServiceRestartCompleteSlot(bool);
void InitInterfaceUIStatus();
private:
QStackedWidget *_MCentralWidget = nullptr;
QWidget *_MAbnormalErrorWidget = nullptr;
QWidget *_MNoAdapterErrorWidget = nullptr;
QWidget *_MAdapterLoadingWidget = nullptr;
QWidget *_MError0Widget = nullptr;
QWidget *_MError1Widget = nullptr;
QWidget *_MNormalWidget = nullptr;
QVBoxLayout *_NormalWidgetMainLayout = nullptr;
QVBoxLayout *_NormalWidgetMainLayout = nullptr;
QVBoxLayout *_NormalWidgetPairedDevLayout = nullptr;
QVBoxLayout *_NormalWidgetCacheDevLayout = nullptr;
QVBoxLayout *_NormalWidgetCacheDevLayout = nullptr;
QWidget *_MNormalWidgetTop = nullptr;
QWidget *_MNormalWidgetMiddle = nullptr;
QWidget *_MNormalWidgetBottom = nullptr;
QWidget *_MNormalWidgetTop = nullptr;
QWidget *_MNormalWidgetTopMiddle = nullptr;
QWidget *_MNormalWidgetTopBottom = nullptr;
QWidget *_CacheDevWidget = nullptr;
QFrame *_MNormalFrameTop = nullptr;
QFrame *_MNormalFrameMiddle = nullptr;
QFrame *_MNormalFrameBottom = nullptr;
QFrame *BtSwitchLineFrame = nullptr;
QFrame *BtAdapterListFrame = nullptr;
QFrame *BtAdapterListLineFrame = nullptr;
QFrame *BtTrayIconShowFrame= nullptr;
QFrame *BtTrayIconShowLineFrame = nullptr;
QFrame *BtDiscoverableFrame= nullptr;
QFrame *BtDiscoverableLineFrame= nullptr;
QFrame *BtAutomaticAudioConnectionFrame= nullptr;
KSwitchButton *_BtSwitchBtn = nullptr;
KSwitchButton *_BtTrayIconShow = nullptr;
KSwitchButton *_BtDiscoverable = nullptr;
KSwitchButton *_BtAutoAudioConnBtn = nullptr;
LoadingLabel *_LoadIcon = nullptr;
BluetoothNameLabel *_BtNameLabel = nullptr;
QComboBox *_AdapterListSelectComboBox = nullptr;
QComboBox *_DevTypeSelectComboBox = nullptr;
QMap <QString, QString> adapterDataMap;
QList <QString> adapterAddressList;
QList <QString> adapterNameList;
int m_loadingWindx = 0;
QTimer * m_loadingWBTAdapterTimer = nullptr;
QTimer * m_loadingWBTServiceTimer = nullptr;
// QTimer * m_loadingWIcontimer = nullptr;
BlueToothDBusService * btServer = nullptr;
_DEV_TYPE currentShowTypeFlag = _DEV_TYPE::BT_All;
bool _MyDevicesInterfaceShowFlags = false;
bool _BTServiceReportPowerSwitchFlag = false; //服务上报的蓝牙开关状态
bool _BTServiceReportTrayIconSwitchFlag = false; //服务上报的蓝牙托盘显示开关状态
bool _BTServiceReportDiscoverableSwtichFlag = false; //服务上报的可被发现状态
bool _BTServiceReportAutoAudioConnSwtichFlag = false; //服务上报的自动音频状态
// bool _BTServiceReportDiscoveringSwtichFlag = false; //服务上报的扫描状态
bool isEffectiveDevice(QString, bluetoothdevice::DEVICE_TYPE);
bool whetherToDisplayInTheCurrentInterface(bluetoothdevice::DEVICE_TYPE devType);
void reloadDeviceListItem(_DEV_TYPE flag);
void frameAddLineFrame(int,QString,QString);
void removeBluetoothDeviceItemUi(QString);
void removeMDevFrameLineFrame(QString);
void adjustDeviceDisplayPosition(QString ,quint16);
int getDevRssiItemInsertIndex(qint16 currDevRssi);
void changeDeviceParentWindow(const QString &address);
void adapterChangedRefreshInterface(int indx);
void clearMyDevicesUI();
void clearOtherDevicesUI();
SwitchButton *_BtSwitchBtn = nullptr;
SwitchButton *_BtTrayIconShow = nullptr;
LoadingLabel *_LoadIcon = nullptr;
SwitchButton *_BtDiscoverable = nullptr;
BluetoothNameLabel *_BtNameLabel = nullptr;
QComboBox *_AdapterListSelect = nullptr;
QComboBox *_DevTypeSelect = nullptr;
};
#endif // BLUETOOTHMAINWINDOW_H

View File

@ -48,9 +48,10 @@ BluetoothNameLabel::~BluetoothNameLabel()
{
delete settings;
settings = nullptr;
if(nullptr != renameDialog)
if (nullptr != renameDialog)
{
renameDialog->deleteLater();
delete renameDialog ;
renameDialog = nullptr;
}
}
@ -68,15 +69,15 @@ void BluetoothNameLabel::set_dev_name(const QString &dev_name)
void BluetoothNameLabel::showDevRenameDialog()
{
if(nullptr != renameDialog)
if (nullptr != renameDialog)
{
renameDialog->disconnect();
delete renameDialog;
renameDialog = nullptr;
}
renameDialog = new DevRenameDialog();
renameDialog = new DevRenameDialog(this);
renameDialog->setDevName(device_name);
renameDialog->setRenameInterface(DevRenameDialog::DEVRENAMEDIALOG_ADAPTER);
connect(renameDialog,&DevRenameDialog::nameChanged,this,[=](QString name){
m_label->setText(name);
@ -146,6 +147,16 @@ void BluetoothNameLabel::resizeEvent(QResizeEvent *event)
}
}
void BluetoothNameLabel::setLabelText(const QString &value)
{
setMyNameLabelText(value);
// QFontMetrics fm(m_label->font());
// QString text = fm.elidedText(value, Qt::ElideMiddle, m_label->width());
// m_label->setText(text);
// m_label->setToolTip(tr("Can now be found as \"%1\"").arg(device_name));
// m_label->update();
}
void BluetoothNameLabel::settings_changed(const QString &key)
{
qDebug() << Q_FUNC_INFO <<key;

View File

@ -47,6 +47,7 @@ signals:
void sendAdapterName(const QString &value);
public slots:
void setLabelText(const QString &value);
void settings_changed(const QString &key);
private:
@ -62,7 +63,7 @@ private:
QMessageBox *messagebox = nullptr;
QHBoxLayout *hLayout = nullptr;
DevRenameDialog *renameDialog = nullptr;
DevRenameDialog *renameDialog = nullptr;
void showDevRenameDialog();
void setMyNameLabelText(QString);
};

View File

@ -8,10 +8,11 @@
#define BluetoothServiceName "bluetoothService"
#define BluetoothTrayName "ukui-bluetooth"
#define SYSTEMSTYLESCHEMA "org.ukui.style"
#define SYSTEMSTYLENAME "styleName"
#define SYSTEMFONTSIZE "systemFontSize"
#define SYSTEMFONT "systemFont"
#define GSETTING_ORG_UKUI_STYLE "org.ukui.style"
#define SYSTEMSTYLENAME "styleName"
#define SYSTEMFONTSIZE "systemFontSize"
#define SYSTEMFONT "systemFont"
#define ICONTHEMENAME "iconThemeName"
#define MAX_DEVICE_CONECTIONS_TIMES 3
@ -23,17 +24,8 @@
#define TRANSPARENCY_SETTINGS "org.ukui.control-center.personalise"
#define TRANSPARENCY_KEY "transparency"
#define GSETTING_UKUI_STYLE "org.ukui.style"
#define GSETTING_SCHEMA_UKCC "org.ukui.control-center.plugins"
#define GSETTING_PACH_UKCC "/org/ukui/control-center/plugins/Bluetooth/"
#define DBUSSERVICE "com.ukui.bluetooth"
#define DBUSPATH "/com/ukui/bluetooth"
#define DBUSINTERFACE "com.ukui.bluetooth"
#define TITLE_ICON_BLUETOOTH "bluetooth"
const QString SERVICE = "com.ukui.bluetooth";
const QString PATH = "/com/ukui/bluetooth";
const QString INTERFACE = "com.ukui.bluetooth";
@ -45,6 +37,5 @@ enum Environment
LAIKA,
MAVIS
};
extern Environment envPC;
#endif // CONFIG_H

View File

@ -8,403 +8,108 @@ devicebase::devicebase()
//devicebase end
//bluetoothadapter
bluetoothadapter::bluetoothadapter(QString dev_name ,
const QString dev_address ,
bool dev_block ,
bool dev_power ,
bool dev_pairing ,
bool dev_pairable ,
bool dev_connecting ,
bluetoothadapter::bluetoothadapter(QString dev_name ,
const QString dev_address ,
bool dev_power ,
bool dev_discovering ,
bool dev_discoverable,
bool dev_activeConnection,
bool dev_defaultAdapterMark,
bool dev_trayShow)
:m_dev_name(dev_name),
m_dev_address(dev_address) ,
m_dev_block(dev_block) ,
m_dev_power(dev_power) ,
m_dev_pairing(dev_pairing) ,
m_dev_pairable(dev_pairable) ,
m_dev_connecting(dev_connecting) ,
m_dev_discovering(dev_discovering) ,
m_dev_discoverable(dev_discoverable),
m_dev_activeConnection(dev_activeConnection),
m_dev_defaultAdapterMark(dev_defaultAdapterMark),
m_dev_trayShow(dev_trayShow)
bool dev_discoverable)
:m_dev_name(dev_name)
,m_dev_address(dev_address)
,m_dev_power(dev_power)
,m_dev_discovering(dev_discovering)
,m_dev_discoverable(dev_discoverable)
{
KyDebug();
qDebug() << Q_FUNC_INFO << __LINE__;
this->setObjectName(dev_address);
}
bluetoothadapter::bluetoothadapter(QMap<QString ,QVariant> value)
{
bluetoothAdapterDataAnalysis(value);
}
void bluetoothadapter::bluetoothAdapterDataAnalysis(QMap<QString ,QVariant> value)
{
//解析adpater数据
QString key = "Name";
if(value.contains(key))
this->m_dev_name = value[key].toString();
key = "Addr";
if(value.contains(key))
this->m_dev_address = value[key].toString();
key = "Block";
if(value.contains(key))
this->m_dev_block = value[key].toBool();
key = "Powered";
if(value.contains(key))
this->m_dev_power = value[key].toBool();
key = "Pairing";
if(value.contains(key))
this->m_dev_pairing = value[key].toBool();
key = "Pairable";
if(value.contains(key))
this->m_dev_pairable = value[key].toBool();
key = "Connecting";
if(value.contains(key))
this->m_dev_connecting = value[key].toBool();
key = "Discovering";
if(value.contains(key))
this->m_dev_discovering = value[key].toBool();
key = "Discoverable";
if(value.contains(key))
this->m_dev_discoverable = value[key].toBool();
key = "ActiveConnection";
if(value.contains(key))
this->m_dev_activeConnection = value[key].toBool();
key = "DefaultAdapter";
if(value.contains(key))
this->m_dev_defaultAdapterMark = value[key].toBool();
key = "trayShow";
if(value.contains(key))
this->m_dev_trayShow = value[key].toBool();
}
void bluetoothadapter::resetDeviceName(QString new_dev_name)
{
KyDebug();
if (new_dev_name != this->m_dev_name)
{
this->m_dev_name = new_dev_name;
Q_EMIT adapterNameChanged(this->m_dev_name);
}
qDebug() << Q_FUNC_INFO << __LINE__;
this->m_dev_name = new_dev_name;
}
QString bluetoothadapter::getDevName()
{
KyDebug();
qDebug() << Q_FUNC_INFO << __LINE__;
return this->m_dev_name;
}
QString bluetoothadapter::getDevAddress()
{
KyDebug();
qDebug() << Q_FUNC_INFO << __LINE__;
return this->m_dev_address;
}
void bluetoothadapter::setAdapterPower(bool value)
void bluetoothadapter::setDevPower(bool value)
{
KyDebug() << value;
if (value != this->m_dev_power)
{
this->m_dev_power = value;
Q_EMIT adapterPoweredChanged(this->m_dev_power);
}
qDebug() << Q_FUNC_INFO << __LINE__;
this->m_dev_power = value;
}
bool bluetoothadapter::getAdapterPower()
bool bluetoothadapter::getDevPower()
{
KyDebug();
qDebug() << Q_FUNC_INFO << __LINE__;
return this->m_dev_power;
}
void bluetoothadapter::setAdapterPairing(bool value)
void bluetoothadapter::setDevDiscovering(bool value)
{
KyDebug() << value ;
if (value != this->m_dev_pairing)
{
this->m_dev_pairing = value;
Q_EMIT adapterPairingChanged(this->m_dev_pairing);
}
}
bool bluetoothadapter::getAdapterPairing()
{
return this->m_dev_pairing;
qDebug() << Q_FUNC_INFO << __LINE__;
this->m_dev_discovering = value;
}
void bluetoothadapter::setAdapterConnecting(bool value)
bool bluetoothadapter::getDevDiscovering()
{
KyDebug() << value ;
if (value != this->m_dev_connecting)
{
this->m_dev_connecting = value;
Q_EMIT adapterConnectingChanged(this->m_dev_connecting);
}
}
bool bluetoothadapter::getAdapterConnecting()
{
return this->m_dev_connecting;
}
void bluetoothadapter::setAdapterPairable(bool value)
{
if (value != this->m_dev_pairable)
{
this->m_dev_pairable = value;
Q_EMIT adapterPairableChanged(this->m_dev_pairable);
}
}
bool bluetoothadapter::getAdapterPairable()
{
return this->m_dev_pairable;
}
void bluetoothadapter::setAdapterDiscovering(bool value)
{
KyDebug() << value ;
if (value != this->m_dev_discovering)
{
this->m_dev_discovering = value;
Q_EMIT adapterDiscoveringChanged(this->m_dev_discovering);
}
}
bool bluetoothadapter::getAdapterDiscovering()
{
KyDebug() ;
qDebug() << Q_FUNC_INFO << __LINE__;
return this->m_dev_discovering;
}
void bluetoothadapter::setAdapterDiscoverable(bool value)
void bluetoothadapter::setDevDiscoverable(bool value)
{
KyDebug() ;
if (value != this->m_dev_discoverable)
{
this->m_dev_discoverable = value;
Q_EMIT adapterDiscoverableChanged(this->m_dev_discoverable);
}
qDebug() << Q_FUNC_INFO << __LINE__;
this->m_dev_discoverable = value;
}
bool bluetoothadapter::getAdapterDiscoverable()
bool bluetoothadapter::getDevDiscoverable()
{
KyDebug();
qDebug() << Q_FUNC_INFO << __LINE__;
return this->m_dev_discoverable;
}
void bluetoothadapter::setAdapterAutoConn(bool value)
{
KyDebug();
if (value != this->m_dev_activeConnection)
{
this->m_dev_activeConnection = value;
Q_EMIT adapterAutoConnStatuChanged(this->m_dev_activeConnection);
}
}
bool bluetoothadapter::getAdapterAutoConn()
{
return this->m_dev_activeConnection;
}
void bluetoothadapter::setAdapterDefaultMark(bool mark)
{
KyDebug();
if (mark != this->m_dev_defaultAdapterMark)
{
this->m_dev_defaultAdapterMark = mark;
if (mark)
Q_EMIT defaultAdapterChanged(this->m_dev_address);
}
}
bool bluetoothadapter::getAdapterDefaultMark()
{
KyDebug();
return this->m_dev_defaultAdapterMark;
}
void bluetoothadapter::setAdapterTrayShow(bool trayShow)
{
KyDebug();
if (trayShow != this->m_dev_trayShow)
{
this->m_dev_trayShow = trayShow;
Q_EMIT adapterTrayIconChanged(this->m_dev_trayShow);
}
}
bool bluetoothadapter::getAdapterTrayShow()
{
KyDebug();
return this->m_dev_trayShow;
}
//bluetoothadapter end
//bluetoothdevice
bluetoothdevice::bluetoothdevice(QString dev_address ,
QString dev_name ,
QString dev_showName ,
DEVICE_TYPE dev_type ,
bool dev_paired ,
bool dev_trusted ,
bool dev_blocked ,
bool dev_connected ,
bool dev_pairing ,
bool dev_connecting ,
int dev_battery ,
int dev_connectFailedId ,
QString dev_connectFailedDisc ,
qint16 dev_rssi ,
bool dev_sendFileMark ,
QString adapter_address
bluetoothdevice::bluetoothdevice(QString dev_name ,
QString dev_address ,
DEVICE_TYPE dev_type ,
bool dev_paired_status ,
bool dev_connected_status ,
//DEVICE_STATUS dev_status ,
bool dev_trust,
qint16 dev_rssi
)
:m_dev_address ( dev_address )
,m_dev_name ( dev_name )
,m_dev_showName ( dev_showName )
,m_dev_type ( dev_type )
,m_dev_paired ( dev_paired )
,m_dev_trusted ( dev_trusted )
,m_dev_blocked ( dev_blocked )
,m_dev_connected ( dev_connected )
,m_dev_pairing ( dev_pairing )
,m_dev_connecting ( dev_connecting )
,m_dev_battery ( dev_battery )
,m_dev_connectFailedId ( dev_connectFailedId )
,m_dev_connectFailedDisc ( dev_connectFailedDisc )
,m_dev_rssi ( dev_rssi )
,m_dev_sendFileMark ( dev_sendFileMark )
,m_adapter_address ( adapter_address )
:m_dev_name(dev_name)
,m_dev_address(dev_address)
,m_dev_type(dev_type)
,m_dev_isPaired(dev_paired_status)
,m_dev_isConnected(dev_connected_status)
//,m_dev_status(dev_status)
,m_dev_trust(dev_trust)
,m_dev_rssi(dev_rssi)
{
this->setObjectName(dev_address);
}
bluetoothdevice::bluetoothdevice(QMap<QString ,QVariant> value)
{
bluetoothDeviceDataAnalysis(value);
}
void bluetoothdevice::bluetoothDeviceDataAnalysis(QMap<QString ,QVariant> value)
{
//解析bluetooth device数据
QString key = "Paired";
if(value.contains(key))
this->m_dev_paired = value[key].toBool();
key = "Trusted";
if(value.contains(key))
this->m_dev_trusted = value[key].toBool();
key = "Blocked";
if(value.contains(key))
this->m_dev_blocked = value[key].toBool();
key = "Connected";
if(value.contains(key))
this->m_dev_connected = value[key].toBool();
key = "Name";
if(value.contains(key))
this->m_dev_name = value[key].toString();
key = "ShowName";
if(value.contains(key))
this->m_dev_showName = value[key].toString();
key = "Addr";
if(value.contains(key))
this->m_dev_address = value[key].toString();
key = "Type";
if(value.contains(key))
this->m_dev_type = bluetoothdevice::DEVICE_TYPE(value[key].toInt());
key = "Pairing";
if(value.contains(key))
this->m_dev_pairing = value[key].toBool();
key = "Connecting";
if(value.contains(key))
this->m_dev_connecting = value[key].toBool();
key = "Battery";
if(value.contains(key))
this->m_dev_battery = value[key].toInt();
key = "ConnectFailedId";
if(value.contains(key))
this->m_dev_connectFailedId = value[key].toInt();
key = "ConnectFailedDisc";
if(value.contains(key))
this->m_dev_connectFailedDisc = value[key].toString();
key = "Rssi";
if(value.contains(key))
this->m_dev_rssi = value[key].toInt();
key = "FileTransportSupport";
if(value.contains(key))
this->m_dev_sendFileMark = value[key].toBool();
key = "Adapter";
if(value.contains(key))
this->m_adapter_address = value[key].toString();
clearErrorInfo();
}
void bluetoothdevice::resetDeviceName(QString new_dev_name)
{
//KyDebug();
if(new_dev_name != this->m_dev_name)
{
this->m_dev_name = new_dev_name;
Q_EMIT nameChanged(new_dev_name);
}
}
void bluetoothdevice::setDevShowName(QString new_dev_showName)
{
//KyDebug() << this->m_dev_showName << new_dev_showName ;
if(new_dev_showName != this->m_dev_showName)
{
this->m_dev_showName = new_dev_showName;
Q_EMIT showNameChanged(new_dev_showName);
}
}
QString bluetoothdevice::getDevShowName()
{
return this->m_dev_showName;
}
QString bluetoothdevice::getDevInterfaceShowName()
{
if(this->m_dev_showName.isEmpty())
return this->m_dev_name;
else
return this->m_dev_showName;
//qDebug() << Q_FUNC_INFO << __LINE__;
this->m_dev_name = new_dev_name;
emit nameChanged(new_dev_name);
}
void bluetoothdevice::devMacAddressChanged(QString macAddress)
@ -418,122 +123,104 @@ void bluetoothdevice::devMacAddressChanged(QString macAddress)
QString bluetoothdevice::getDevName()
{
//KyDebug();
//qDebug() << Q_FUNC_INFO << __LINE__;
return this->m_dev_name;
}
QString bluetoothdevice::getDevAddress()
{
//KyDebug();
//qDebug() << Q_FUNC_INFO << __LINE__;
return this->m_dev_address;
}
void bluetoothdevice::setDevType(DEVICE_TYPE type)
{
//KyDebug();
if (this->m_dev_type != type)
{
this->m_dev_type = type;
Q_EMIT typeChanged(type);
}
//qDebug() << Q_FUNC_INFO << __LINE__;
this->m_dev_type = type;
emit typeChanged(type);
}
bluetoothdevice::DEVICE_TYPE bluetoothdevice::getDevType()
{
//KyDebug();
//qDebug() << Q_FUNC_INFO << __LINE__;
return this->m_dev_type;
}
void bluetoothdevice::setDevPairing(bool value)
{
if (value != this->m_dev_pairing)
{
this->m_dev_pairing = value;
Q_EMIT pairingChanged(value);
}
}
bool bluetoothdevice::getDevPairing()
{
return this->m_dev_pairing;
}
void bluetoothdevice::setDevConnecting(bool value)
{
KyWarning() << value << this->m_dev_connecting ;
if (value != this->m_dev_connecting)
{
this->m_dev_connecting = value;
Q_EMIT connectingChanged(value);
}
}
bool bluetoothdevice::getDevConnecting()
{
return this->m_dev_connecting;
}
//void bluetoothdevice::setDevStatus(DEVICE_STATUS status)
//{
// //qDebug() << Q_FUNC_INFO << __LINE__;
//}
//bluetoothdevice::DEVICE_STATUS bluetoothdevice::getDevStatus()
//{
// //qDebug() << Q_FUNC_INFO << __LINE__;
//}
void bluetoothdevice::setDevTrust(bool value)
{
//KyDebug();
if (value != this->m_dev_trusted)
{
this->m_dev_trusted = value;
Q_EMIT trustChanged(value);
}
//qDebug() << Q_FUNC_INFO << __LINE__;
this->m_dev_trust = value;
emit trustChanged(value);
}
bool bluetoothdevice::getDevTrust()
{
//KyDebug();
return this->m_dev_trusted;
//qDebug() << Q_FUNC_INFO << __LINE__;
}
bool bluetoothdevice::isPaired()
{
//KyDebug();
return m_dev_paired;
//qDebug() << Q_FUNC_INFO << __LINE__;
return m_dev_isPaired;
}
void bluetoothdevice::devPairedChanged(bool value)
{
qDebug() << Q_FUNC_INFO << value << this->m_dev_paired << __LINE__;
if(value != this->m_dev_paired )
qDebug() << Q_FUNC_INFO << value << __LINE__;
if(this->m_dev_isPaired != value)
{
this->m_dev_paired = value;
Q_EMIT pairedChanged(value);
this->m_dev_isPaired = value;
emit pairedChanged(value);
}
}
bool bluetoothdevice::isConnected()
{
//KyDebug();
return m_dev_connected;
//qDebug() << Q_FUNC_INFO << __LINE__;
return m_dev_isConnected;
}
void bluetoothdevice::devConnectedChanged(bool value)
{
if(value != this->m_dev_connected)
if(this->m_dev_isConnected != value)
{
this->m_dev_connected = value;
Q_EMIT connectedChanged(value);
this->m_dev_isConnected = value;
emit connectedChanged(value);
}
}
void bluetoothdevice::setDevSendFileMark(bool mark)
void bluetoothdevice::setErrorInfo(int errorId,QString errorText)
{
if (mark != this->m_dev_sendFileMark)
this->m_dev_sendFileMark = mark;
this->m_errorId = errorId;
this->m_errorText = errorText;
emit errorInfoRefresh(errorId,errorText);
}
void bluetoothdevice::clearErrorInfo()
{
this->m_errorId = 0;
this->m_errorText = "";
}
void bluetoothdevice::setDevSendFileMark(bool isSupport)
{
this->m_dev_support_sendFile = isSupport;
}
bool bluetoothdevice::getDevSendFileMark()
{
return this->m_dev_sendFileMark;
return this->m_dev_support_sendFile;
}
void bluetoothdevice::setDevRssi(qint16 rssi)
{
if (m_dev_rssi != rssi)
{
this->m_dev_rssi = rssi;
Q_EMIT this->rssiChanged(rssi);
}
this->m_dev_rssi = rssi;
}
qint16 bluetoothdevice::getDevRssi()
@ -541,31 +228,5 @@ qint16 bluetoothdevice::getDevRssi()
return this->m_dev_rssi;
}
void bluetoothdevice::setDevConnFailedInfo(int errId,QString errInfo)
{
//if(errId != this->m_dev_connectFailedId)
{
this->m_dev_connectFailedId = errId;
}
//if(errInfo != this->m_dev_connectFailedDisc)
{
this->m_dev_connectFailedDisc = errInfo;
}
//收到一次转发一下
Q_EMIT errorInfoRefresh(errId,errInfo);
}
int bluetoothdevice::getErrorId()
{
return this->m_dev_connectFailedId;
}
//bluetoothdevice end
//

View File

@ -1,15 +1,13 @@
#ifndef DEVICEBASE_H
#define DEVICEBASE_H
#include <QList>
#include <QDebug>
#include <QObject>
#include <QVector>
#include <QList>
#include <QString>
#include <ukui-log4qt.h>
#include <QDebug>
#include "config.h"
#include <config.h>
class devicebase;
class bluetoothadapter;
@ -27,9 +25,9 @@ public:
virtual QString getDevName() = 0;
virtual QString getDevAddress() = 0;
private:
QString m_dev_name;
QString m_dev_address;
//signals:
// void deviceNameChanged();
};
//devicebase end
@ -39,92 +37,36 @@ class bluetoothadapter : public devicebase
{
Q_OBJECT
public:
bluetoothadapter(QString dev_name ,
const QString dev_address ,
bool dev_block ,
bool dev_power ,
bool dev_pairing ,
bool dev_pairable ,
bool dev_connecting ,
bool dev_discovering ,
bool dev_discoverable,
bool dev_activeConnection,
bool dev_defaultAdapterMark,
bool dev_trayShow);
bluetoothadapter(QString dev_name ,
QString dev_address,
bool dev_power ,
bool dev_discovering,
bool dev_discoverable);
bluetoothadapter(QMap<QString ,QVariant> value);
~bluetoothadapter(){
//KyDebug() << "======" << m_dev_name << m_dev_address;
}
~bluetoothadapter(){}
void resetDeviceName(QString) Q_DECL_OVERRIDE ;
QString getDevName() Q_DECL_OVERRIDE ;
QString getDevAddress() Q_DECL_OVERRIDE ;
void setAdapterPower(bool);
bool getAdapterPower();
void setDevPower(bool);
bool getDevPower();
void setDevDiscovering(bool);
bool getDevDiscovering();
void setDevDiscoverable(bool);
bool getDevDiscoverable();
void setAdapterPairing(bool);
bool getAdapterPairing();
void setAdapterConnecting(bool);
bool getAdapterConnecting();
void setAdapterPairable(bool);
bool getAdapterPairable();
void setAdapterDiscovering(bool);
bool getAdapterDiscovering();
void setAdapterDiscoverable(bool);
bool getAdapterDiscoverable();
void setAdapterAutoConn(bool);
bool getAdapterAutoConn();
void setAdapterDefaultMark(bool);
bool getAdapterDefaultMark();
void setAdapterTrayShow(bool);
bool getAdapterTrayShow();
QMap <QString,bluetoothdevice *> m_bt_dev_list;
// QList<bluetoothdevice *> m_bluetooth_device_list;
QMap <QString,bluetoothdevice *> m_bt_dev_paired_list;
// QList<bluetoothdevice *> m_bluetooth_device_paired_list;
signals:
void adapterNameChanged(const QString &name);
void adapterPoweredChanged(bool powered);
void adapterPairingChanged(bool pairing);
void adapterPairableChanged(bool pairable);
void adapterConnectingChanged(bool connecting);
void adapterTrayIconChanged(bool status);
void adapterDiscoverableChanged(bool discoverable);
void adapterDiscoveringChanged(bool discovering);
void adapterAutoConnStatuChanged(bool status);
void adapterDeviceAdded(bluetoothdevice * &device);
void adapterDeviceRemoved(bluetoothdevice * &device);
void defaultAdapterChanged(const QString &address);
QList<bluetoothdevice *> m_bluetooth_device_list;
QList<bluetoothdevice *> m_bluetooth_device_paired_list;
private:
QString m_dev_name ;
QString m_dev_address ;
QString m_dev_name;
QString m_dev_address;
bool m_dev_power;
bool m_dev_discovering;
bool m_dev_discoverable;
bool m_dev_block ;
bool m_dev_power ;
bool m_dev_pairing ;
bool m_dev_pairable ;
bool m_dev_connecting ;
bool m_dev_discovering ;
bool m_dev_discoverable ;
bool m_dev_activeConnection ;
bool m_dev_defaultAdapterMark ;
bool m_dev_trayShow ;
void bluetoothAdapterDataAnalysis(QMap<QString ,QVariant> value);
};
//bluetoothadapter end
@ -231,101 +173,64 @@ public:
};
Q_ENUM(Error)
bluetoothdevice(QString dev_address ,
QString dev_name ,
QString dev_showName ,
DEVICE_TYPE dev_type ,
bool dev_paired ,
bool dev_trusted ,
bool dev_blocked ,
bool dev_connected ,
bool dev_pairing ,
bool dev_connecting ,
int dev_battery ,
int dev_connectFailedId ,
QString dev_connectFailedDisc ,
qint16 dev_rssi ,
bool dev_sendFileMark ,
QString adapter_address);
bluetoothdevice(QMap<QString ,QVariant> value);
~bluetoothdevice(){
//KyDebug() << "======" << m_dev_name << m_dev_address;
}
bluetoothdevice(QString device_name ,
QString device_address ,
DEVICE_TYPE dev_type ,
bool dev_paired_status ,
bool dev_connected_status ,
//DEVICE_STATUS dev_status ,
bool dev_trust,
qint16 dev_rssi
);
~bluetoothdevice(){}
void resetDeviceName(QString) Q_DECL_OVERRIDE ;
QString getDevName() Q_DECL_OVERRIDE ;
QString getDevAddress() Q_DECL_OVERRIDE ;
void setDevShowName(QString);
QString getDevShowName();
QString getDevInterfaceShowName();
void setDevType(DEVICE_TYPE);
DEVICE_TYPE getDevType();
//void setDevStatus(DEVICE_STATUS);
//DEVICE_STATUS getDevStatus();
bool isPaired();
void devPairedChanged(bool);
bool isConnected();
void devConnectedChanged(bool);
void setDevPairing(bool);
bool getDevPairing();//暂时不使用
void setDevConnecting(bool);
bool getDevConnecting();
void devMacAddressChanged(QString);
void setDevTrust(bool);
bool getDevTrust();
void setDevConnFailedInfo(int,QString);
void setErrorInfo(int,QString);
void clearErrorInfo();
void setDevSendFileMark(bool);
bool getDevSendFileMark();
qint16 getDevRssi();
void setDevRssi(qint16);
int getErrorId();
signals:
void nameChanged(QString);
void showNameChanged(QString);
void rssiChanged(qint16);
void typeChanged(DEVICE_TYPE);
void pairedChanged(bool);
void connectedChanged(bool);
void pairingChanged(bool);
void connectingChanged(bool);
void trustChanged(bool);
void errorInfoRefresh(int,QString);
void devConnectingSignal();
private:
QString m_dev_address ;
QString m_dev_name ;
QString m_dev_showName ;
DEVICE_TYPE m_dev_type ;
bool m_dev_paired = false ;
bool m_dev_trusted = false ;
bool m_dev_blocked = false ;
bool m_dev_connected = false ;
bool m_dev_pairing = false ;//暂时不使用
bool m_dev_connecting = false ;
int m_dev_battery ;
int m_dev_connectFailedId ;
QString m_dev_connectFailedDisc ;
qint16 m_dev_rssi ;
bool m_dev_sendFileMark ;
QString m_adapter_address ;//暂时不使用
void bluetoothDeviceDataAnalysis(QMap<QString ,QVariant> value);
QString m_dev_name;
QString m_dev_address;
DEVICE_TYPE m_dev_type;
qint16 m_dev_rssi;
//DEVICE_STATUS m_dev_status;
bool m_dev_trust ;
bool m_dev_isPaired;
bool m_dev_isConnected;
bool m_dev_support_sendFile;
int m_errorId;
QString m_errorText;
};
//bluetoothdevice end

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,177 @@
#ifndef DEVICEINFOITEM_H
#define DEVICEINFOITEM_H
#include "devicebase.h"
#include "devremovedialog.h"
#include "bluetoothmain.h"
#include "bluetoothdbusservice.h"
#include <QChar>
#include <QIcon>
#include <QMenu>
#include <QFont>
#include <QFrame>
#include <QLabel>
#include <QColor>
#include <QTimer>
#include <QDebug>
#include <QStyle>
#include <QString>
#include <QPainter>
#include <QDateTime>
#include <QPushButton>
#include <QMouseEvent>
#include <QMessageBox>
#include <QFontMetrics>
#include <QAbstractButton>
#include <QGSettings/QGSettings>
//#include <ukcc/widgets/imageutil.h>
#include "windowmanager/windowmanager.h"
#define CONNECT_ERROR_COUNT (3)
#define CONNECT_DEVICE_TIMING (35*1000)
#define CONNECT_ERROR_TIMER_CLEAR (3*60*1000) //3分钟内用户来连接失败超过3次提示用户是否移除后重新配对连接
class DeviceInfoItem : public QFrame
{
Q_OBJECT
public:
DeviceInfoItem(QWidget *parent = nullptr,bluetoothdevice * dev = nullptr);
~DeviceInfoItem();
void refresh_device_icon(bluetoothdevice::DEVICE_TYPE changeType);
void setDeviceCurrentStatus();
enum Status{
Hover = 0,
Nomal,
Check,
};
Q_ENUM(Status)
enum DEVSTATUS{
None,
Connected,
Connecting,
DisConnecting,
ConnectFailed,
DisConnectFailed,
NoPaired,
Paired,
Error
};
Q_ENUM(DEVSTATUS)
void InitMemberVariables();
void startDevConnectTiming();
protected:
void enterEvent(QEvent *);
void leaveEvent(QEvent *);
void mousePressEvent(QMouseEvent *);
void mouseReleaseEvent(QMouseEvent *);
void mouseMoveEvent(QMouseEvent *);
void paintEvent(QPaintEvent *);
private slots:
void GSettingsChanges(const QString &key);
void tranGSettingsChanges(const QString &key);
void MenuSignalDeviceFunction(QAction *action);
void DevSetConnectingFunc();
signals:
void devPaired(QString);
void devConnect(QString);
void devDisconnect(QString);
void devRemove(QString);
void devSendFiles(QString);
void devConnectionComplete();
private:
QColor getPainterBrushColor();
QColor getDevStatusColor();
QPixmap getDevTypeIcon();
void DrawBackground(QPainter &);
void DrawStatusIcon(QPainter &);
void DrawText(QPainter &);
void DrawStatusText(QPainter &);
void DrawFuncBtn(QPainter &);
void DrawLoadingIcon(QPainter &);
void MouseClickedFunc();
void MouseClickedDevFunc();
bool mouseEventIntargetAera(QPoint);
void DevConnectFunc();
void setDeviceConnectSignals();
QRect getStatusTextRect(QRect);
QRect getLoadIconRect();
QRect getStatusIconRect(QRect);
QRect getFontPixelQPoint(QString);
//int NameTextWidthMax();
QString getDeviceName(QString);
int ShowNameTextNumberMax();
// int NameTextCoordinate_Y_offset();
void TimedRestoreConnectionErrorDisplay();
void showDeviceRemoveWidget(DevRemoveDialog::REMOVE_INTERFACE_TYPE);
//bool isDisplayPINCodeWidget();
bool toptipflag = false;
int iconFlag = 7;
int m_devConnect_error_count = 0;
DEVSTATUS _DevStatus;
Status _MStatus;
Status _MBtnStatus;
QString devName;
QString _fontFamily;
QString _iconThemeName;
int _fontSize;
bool _inBtn = false;
bool _clicked;
bool _pressFlag ;
bool _connDevTimeOutFlag ;
bool _rightFlag ;
bool _removeDevFlag ;
bool _pressBtnFlag = false;
bool _themeIsBlack = false;
long long _pressCurrentTime;
double tran =1;
bool _userCheckdevConnecting = false;//用户点击界面的连接操作
QMenu *dev_Menu = nullptr;
QTimer *_iconTimer = nullptr;
QTimer *_devConnTimer = nullptr;
QTimer *_devConnErrorClearTimer = nullptr;
bluetoothdevice * _MDev = nullptr;
QGSettings *item_gsettings = nullptr;
QGSettings *transparency_gsettings = nullptr;
//#define DEV_CONNECTING_TEXT "Connecting"
QString m_str_dev_connecting ;
//#define DEV_DISCONNECTING_TEXT "Disconnecting"
QString m_str_dev_disconnecting ;
//#define DEV_CONNECTED_TEXT "Connected"
QString m_str_dev_connected ;
//#define DEV_UNUNITED_TEXT "Ununited"
QString m_str_dev_ununited ;
//#define DEV_CONNECTION_FAIL_TEXT "Connect fail"
QString m_str_dev_conn_fail;
QString m_str_dev_disconn_fail;
QBrush btnhoverBrush;
QBrush btnclickBrush;
QBrush getPainterBtnBrush();
QBrush hoverBrush;
QBrush clickBrush;
QBrush getPainterBackgroundBrush();
};
#endif // DEVICEINFOITEM_H

View File

@ -9,12 +9,11 @@ DevRemoveDialog::DevRemoveDialog(REMOVE_INTERFACE_TYPE mode,QWidget *parent):QDi
this->setAttribute(Qt::WA_TranslucentBackground);
initUI();
initGsettings();
}
DevRemoveDialog::~DevRemoveDialog()
{
gsettings->deleteLater();
}
void DevRemoveDialog::initUI()
@ -22,6 +21,7 @@ void DevRemoveDialog::initUI()
if(REMOVE_MANY_TIMES_CONN_FAIL_DEV == this->m_mode)
{
title_icon = new QLabel(this);
//title_icon->setPixmap(QIcon::fromTheme("preferences-system-bluetooth").pixmap(20,22));
title_icon->setPixmap(QIcon::fromTheme(TITLE_ICON_BLUETOOTH).pixmap(20,22));
title_icon->setGeometry(8,8,20,22);
@ -47,7 +47,7 @@ void DevRemoveDialog::initUI()
txtLabel->setPalette(txtPal);
QString txtStr = tr("After it is removed, the PIN code must be matched for the next connection.");
QString newTxtStr = QFontMetrics(this->font()).elidedText(txtStr,Qt::ElideMiddle,txtLabel->width());
QString newTxtStr = QFontMetrics(this->font()).elidedText(txtStr,Qt::ElideRight,txtLabel->width());
QFont txtFont ;
txtFont.setPointSize(this->fontInfo().pointSize());
txtLabel->setFont(txtFont);
@ -109,7 +109,7 @@ void DevRemoveDialog::setDialogText(const QString &str)
else
txtStr = QString(tr("Are you sure to remove %1 ?")).arg(str);
QString newTxtStr = QFontMetrics(this->font()).elidedText(txtStr,Qt::ElideMiddle,tipLabel->width());
QString newTxtStr = QFontMetrics(this->font()).elidedText(txtStr,Qt::ElideRight,tipLabel->width());
QFont tipFont ;
tipFont.setPointSize(this->fontInfo().pointSize());
tipLabel->setFont(tipFont);
@ -159,3 +159,21 @@ void DevRemoveDialog::paintEvent(QPaintEvent *event)
painter.drawRoundedRect(this->rect(),12,12);
}
void DevRemoveDialog::keyPressEvent(QKeyEvent * event)
{
Q_UNUSED(event)
switch(event->key())
{
case Qt::Key_Return:
case Qt::Key_Enter:
//if(acceptBtn->isEnabled())//setEnable状态后emit click 信号不相应,无需判断
emit acceptBtn->click();
break;
case Qt::Key_Escape:
//if(rejectBtn->isEnabled())//setEnable状态后emit click 信号不相应,无需判断
this->close();
break;
}
}

View File

@ -13,6 +13,7 @@
#include <QDebug>
#include <QIcon>
#include <QFont>
#include <QKeyEvent>
#include "config.h"
@ -43,6 +44,7 @@ private slots:
protected:
void paintEvent(QPaintEvent *);
void keyPressEvent(QKeyEvent *);
private:
bool isblack = false;

View File

@ -13,34 +13,16 @@ DevRenameDialog::DevRenameDialog(QWidget *parent):QDialog(parent)
DevRenameDialog::~DevRenameDialog()
{
gsettings->deleteLater();
}
void DevRenameDialog::setRenameInterface(DEV_RENAME_DIALOG_TYPE mode)
{
this->_mMode = mode;
if (DEVRENAMEDIALOG_ADAPTER == mode)
{
textLabel->setVisible(true);
titleLabel->setText(tr("Rename"));
}
else if (DEVRENAMEDIALOG_BT_DEVICE == mode)
{
textLabel->setVisible(false);
lineEdit->setGeometry(25,55,435,36);
tipLabel->setGeometry(20,94,435,25);
titleLabel->setFixedSize(300,30);
titleLabel->setText(tr("Rename device"));
}
}
void DevRenameDialog::setDevName(const QString &str)
{
lineEdit->setText(str);
adapterOldName = str;
//test name
//lineEdit->setText("strdddd123456788991111000000");
//adapterOldName = "strdddd123456788991111000000";
}
void DevRenameDialog::initGsettings()
@ -80,6 +62,7 @@ void DevRenameDialog::gsettingsSlot(const QString &key)
isblack = true;
}
this->setPalette(palette);
}
}
@ -87,24 +70,27 @@ void DevRenameDialog::gsettingsSlot(const QString &key)
void DevRenameDialog::initUI()
{
QLabel *iconLabel = new QLabel(this);
iconLabel->setGeometry(10,11,20,20);
iconLabel->setGeometry(10,6,20,20);
iconLabel->setPixmap(QIcon::fromTheme(TITLE_ICON_BLUETOOTH).pixmap(20,20));
titleLabel = new QLabel(this);
titleLabel->setGeometry(36,5,120,30);
QLabel *titleLabel = new QLabel(this);
titleLabel->setGeometry(36,5,100,20);
titleLabel->setAlignment(Qt::AlignVCenter | Qt::AlignLeft);
titleLabel->setText(tr("Rename"));
closeBtn = new QPushButton(this);
closeBtn->setGeometry(453,8,20,20);
//closeBtn->setIcon(QIcon::fromTheme("application-exit-symbolic"));
closeBtn->setIcon(QIcon::fromTheme("window-close-symbolic"));
closeBtn->setFlat(true);
//closeBtn->setFixedSize(QSize(20,20));
closeBtn->setProperty("isWindowButton",0x2);
closeBtn->setProperty("useIconHighlihtEffect",0x8);
connect(closeBtn,&QPushButton::clicked,this,[=]{
this->close();
});
textLabel = new QLabel(this);
QLabel *textLabel = new QLabel(this);
textLabel->setGeometry(24,64,60,20);
textLabel->setText(tr("Name"));
textLabel->setAlignment(Qt::AlignHCenter|Qt::AlignRight);
@ -119,9 +105,8 @@ void DevRenameDialog::initUI()
//输入变化时进行长度提示
connect(lineEdit,&QLineEdit::textEdited,this,&DevRenameDialog::lineEditSlot);
tipLabel = new QLabel(this);
tipLabel->setGeometry(96 + wigth,94,400,25);
//tipLabel->setText(tr("Cannot be null"));
tipLabel = new TitleLabel(this);
tipLabel->setGeometry(96 + wigth,94,300,25);
tipLabel->setText(tr("The value contains 1 to 32 characters"));
tipLabel->setVisible(false);
tipLabel->setStyleSheet("color: rgba(255, 0, 0, 0.85);\
@ -131,10 +116,10 @@ void DevRenameDialog::initUI()
acceptBtn->setGeometry(359,130,96,36);
connect(acceptBtn,&QPushButton::clicked,this,[=]{
qWarning()<< Q_FUNC_INFO << "acceptBtn clicked !" << __LINE__;
if ((lineEdit->text().length() >= INPUT_STRNAME_MIN) &&
(lineEdit->text().length() <= INPUT_STRNAME_MAX) &&
(lineEdit->text() != adapterOldName))
emit nameChanged(lineEdit->text());
this->close();

View File

@ -1,19 +1,17 @@
#ifndef DEVRENAMEDIALOG_H
#define DEVRENAMEDIALOG_H
#include <QIcon>
#include <QLabel>
#include <QDebug>
#include <QDialog>
#include <QVariant>
#include <QPalette>
#include <QPainter>
#include <QLineEdit>
#include <QKeyEvent>
#include <QGSettings>
#include <QIcon>
#include <QPushButton>
#include <QLabel>
#include <QHBoxLayout>
#include <QGSettings>
#include <QVariant>
#include <QPalette>
#include <QKeyEvent>
#include <ukcc/widgets/titlelabel.h>
#include "config.h"
@ -25,25 +23,14 @@ class DevRenameDialog : public QDialog
{
Q_OBJECT
public:
enum DEV_RENAME_DIALOG_TYPE
{
DEVRENAMEDIALOG_ADAPTER = 0,
DEVRENAMEDIALOG_BT_DEVICE = 1
};
Q_ENUM(DEV_RENAME_DIALOG_TYPE)
explicit DevRenameDialog(QWidget *parent = nullptr);
~DevRenameDialog();
void setDevName(const QString &);
void setRenameInterface(DEV_RENAME_DIALOG_TYPE mode);
void initGsettings();
QLabel * titleLabel = nullptr;
QLabel * textLabel = nullptr;
DEV_RENAME_DIALOG_TYPE _mMode = DEVRENAMEDIALOG_ADAPTER;
private slots:
void gsettingsSlot(const QString &);

View File

@ -5,12 +5,11 @@ LoadingLabel::LoadingLabel(QObject *parent)
m_timer = new QTimer(this);
m_timer->setInterval(100);
connect(m_timer,&QTimer::timeout,this,&LoadingLabel::refreshIconNum);
initGsettings();
}
LoadingLabel::~LoadingLabel()
{
m_timer->deleteLater();
// delete m_timer;
}
void LoadingLabel::setTimerStop()
@ -20,8 +19,7 @@ void LoadingLabel::setTimerStop()
void LoadingLabel::setTimerStart()
{
if (!m_timer->isActive())
m_timer->start();
m_timer->start();
}
void LoadingLabel::setTimeReresh(int m)
@ -35,62 +33,14 @@ void LoadingLabel::paintEvent(QPaintEvent *e)
painter.setRenderHint(QPainter::SmoothPixmapTransform);
painter.setPen(Qt::transparent);
// ukccbluetoothconfig::loadSvg(QIcon::fromTheme("ukui-loading-"+QString("%1").arg(index)+"-symbolic").pixmap(this->width(),this->height()),
// ukccbluetoothconfig::WHITE)
// qWarning()<< Q_FUNC_INFO << "_themeIsBlack:" << _themeIsBlack << __LINE__;
if (_themeIsBlack)
painter.drawImage(0,0,
ukccbluetoothconfig::loadSvgImage(QIcon::fromTheme("ukui-loading-"+QString("%1").arg(index)+"-symbolic").pixmap(this->width(),this->height()),ukccbluetoothconfig::WHITE),
0,0,-1,-1,Qt::ColorMode_Mask);
else
painter.drawPixmap(0,0,this->width(),this->height(),QIcon::fromTheme("ukui-loading-"+QString("%1").arg(index)+"-symbolic").pixmap(this->width(),this->height()));
painter.drawPixmap(0,0,this->width(),this->height(),QIcon::fromTheme("ukui-loading-"+QString("%1").arg(i)+"-symbolic").pixmap(this->width(),this->height()));
}
void LoadingLabel::refreshIconNum()
{
// KyDebug() << QString::number(i,10);
// qDebug() << Q_FUNC_INFO << QString::number(i,10);
this->update();
index++;
if(index > 7 || index < 0)
index = 0;
}
void LoadingLabel::initGsettings()
{
// qWarning()<< Q_FUNC_INFO << __LINE__;
if (QGSettings::isSchemaInstalled(GSETTING_UKUI_STYLE))
{
_mStyle_GSettings = new QGSettings(GSETTING_UKUI_STYLE);
if(_mStyle_GSettings->get("styleName").toString() == "ukui-default" ||
_mStyle_GSettings->get("style-name").toString() == "ukui-light")
_themeIsBlack = false;
else
_themeIsBlack = true;
//_mIconThemeName = _mStyle_GSettings->get("iconThemeName").toString();
}
connect(_mStyle_GSettings,&QGSettings::changed,this,&LoadingLabel::mStyle_GSettingsSlot);
}
void LoadingLabel::mStyle_GSettingsSlot(const QString &key)
{
// qWarning()<< Q_FUNC_INFO << key << __LINE__;
if ("styleName" == key || "style-name" == key)
{
if(_mStyle_GSettings->get("style-name").toString() == "ukui-default" ||
_mStyle_GSettings->get("style-name").toString() == "ukui-light")
{
_themeIsBlack = false;
}
else
{
_themeIsBlack = true;
}
}
if(i == 0)
i = 8;
i--;
}

View File

@ -1,16 +1,12 @@
#ifndef LOADINGLABEL_H
#define LOADINGLABEL_H
#include <QWidget>
#include <QTimer>
#include <QIcon>
#include <QDebug>
#include <QTimer>
#include <QWidget>
#include <QPainter>
#include <QGSettings>
#include <QPaintEvent>
#include "config.h"
#include "ukccbluetoothconfig.h"
#include <QPainter>
class LoadingLabel : public QWidget
{
@ -24,18 +20,13 @@ public:
private Q_SLOTS:
void refreshIconNum();
void mStyle_GSettingsSlot(const QString &key);
protected:
void paintEvent(QPaintEvent *e);
private:
int index = 0;
QTimer *m_timer;
bool _themeIsBlack = false;
QGSettings * _mStyle_GSettings = nullptr;
void initGsettings();
int i = 8;
};
#endif // LOADINGLABEL_H

View File

@ -2,75 +2,115 @@
<!DOCTYPE TS>
<TS version="2.1" language="bo_CN">
<context>
<name>BlueToothMainWindow</name>
<name>BlueToothMain</name>
<message>
<source>Bluetooth adapter is abnormal !</source>
<translation></translation>
<source>Show icon on taskbar</source>
<translation></translation>
<extra-contents_path>/Bluetooth/Show icon on taskbar</extra-contents_path>
</message>
<message>
<source>Discoverable by nearby Bluetooth devices</source>
<translation></translation>
<extra-contents_path>/Bluetooth/Discoverable</extra-contents_path>
</message>
<message>
<source>My Devices</source>
<translation></translation>
</message>
<message>
<source>Bluetooth</source>
<translation></translation>
</message>
<message>
<source>Turn on :</source>
<translation></translation>
<extra-contents_path>/Bluetooth/Turn on :</extra-contents_path>
<source>Other Devices</source>
<translation></translation>
<extra-contents_path>/Bluetooth/Other Devices</extra-contents_path>
</message>
<message>
<source>Show icon on taskbar</source>
<translation></translation>
<extra-contents_path>/Bluetooth/Show icon on taskbar</extra-contents_path>
<source>Bluetooth adapter</source>
<translation></translation>
<extra-contents_path>/Bluetooth/Bluetooth adapter</extra-contents_path>
</message>
<message>
<source>Discoverable by nearby Bluetooth devices</source>
<translation></translation>
<extra-contents_path>/Bluetooth/Discoverable by nearby Bluetooth devices</extra-contents_path>
</message>
<message>
<source>My Devices</source>
<translation></translation>
</message>
<message>
<source>Audio</source>
<translation></translation>
</message>
<message>
<source>Other</source>
<translation></translation>
</message>
<message>
<source>Bluetooth adapter not detected !</source>
<translation></translation>
</message>
<message>
<source>Adapter List</source>
<translation></translation>
<extra-contents_path>/Bluetooth/Adapter List</extra-contents_path>
</message>
<message>
<source>Auto discover Bluetooth audio devices</source>
<translation></translation>
<extra-contents_path>/Bluetooth/Auto discover Bluetooth audio devices</extra-contents_path>
<source>Turn on</source>
<translation></translation>
<extra-contents_path>/Bluetooth/Turn on</extra-contents_path>
</message>
<message>
<source>All</source>
<translation></translation>
</message>
<message>
<source>Audio</source>
<translation></translation>
</message>
<message>
<source>Peripherals</source>
<translation></translation>
</message>
<message>
<source>Computer</source>
<translation></translation>
<source>PC</source>
<translation></translation>
</message>
<message>
<source>Phone</source>
<translation></translation>
</message>
<message>
<source>Bluetooth Devices</source>
<translation> </translation>
<source>Other</source>
<translation></translation>
</message>
<message>
<source>Bluetooth driver abnormal</source>
<translation type="vanished"></translation>
</message>
<message>
<source>Auto discover Bluetooth audio devices</source>
<translation></translation>
<extra-contents_path>/Bluetooth/Automatically discover Bluetooth audio devices</extra-contents_path>
</message>
<message>
<source>The Bluetooth adapter is not detected!</source>
<translation></translation>
</message>
</context>
<context>
<name>BlueToothMainWindow</name>
<message>
<source>Bluetooth adapter is abnormal !</source>
<translation type="obsolete"></translation>
</message>
<message>
<source>Bluetooth</source>
<translation type="obsolete"></translation>
</message>
<message>
<source>Turn on :</source>
<translation type="obsolete"></translation>
</message>
<message>
<source>Show icon on taskbar</source>
<translation type="obsolete"></translation>
</message>
<message>
<source>Discoverable by nearby Bluetooth devices</source>
<translation type="obsolete"></translation>
</message>
<message>
<source>My Devices</source>
<translation type="obsolete"></translation>
</message>
<message>
<source>Other Devices</source>
<translation type="obsolete"></translation>
</message>
<message>
<source>Audio</source>
<translation type="obsolete"></translation>
</message>
<message>
<source>Other</source>
<translation type="obsolete"></translation>
</message>
</context>
<context>
@ -82,6 +122,18 @@
</context>
<context>
<name>BluetoothNameLabel</name>
<message>
<source>Tip</source>
<translation type="vanished"></translation>
</message>
<message>
<source>Double-click to change the device name</source>
<translation type="vanished"></translation>
</message>
<message>
<source>The length of the device name does not exceed %1 characters !</source>
<translation type="vanished">%1 </translation>
</message>
<message>
<source>Can now be found as &quot;%1&quot;</source>
<translation>&quot;%1&quot;</translation>
@ -140,47 +192,9 @@
<source>The value contains 1 to 32 characters</source>
<translation>132</translation>
</message>
<message>
<source>Rename device</source>
<translation></translation>
</message>
</context>
<context>
<name>MainWidget</name>
<message>
<source></source>
<translation> </translation>
</message>
</context>
<context>
<name>bluetoothdevicefunc</name>
<message>
<source>connect</source>
<translation></translation>
</message>
<message>
<source>disconnect</source>
<translation></translation>
</message>
<message>
<source>remove</source>
<translation></translation>
</message>
<message>
<source>rename</source>
<translation></translation>
</message>
<message>
<source>sendFile</source>
<translation></translation>
</message>
</context>
<context>
<name>bluetoothdeviceitem</name>
<message>
<source>unknown</source>
<translation></translation>
</message>
<name>DeviceInfoItem</name>
<message>
<source>Connecting</source>
<translation></translation>
@ -190,24 +204,43 @@
<translation></translation>
</message>
<message>
<source>Not Paired</source>
<translation></translation>
<source>Connected</source>
<translation></translation>
</message>
<message>
<source>Connect fail</source>
<translation type="vanished"></translation>
</message>
<message>
<source>Disconnect fail</source>
<translation></translation>
</message>
<message>
<source>send file</source>
<translation></translation>
</message>
<message>
<source>remove</source>
<translation></translation>
</message>
<message>
<source>Not Connected</source>
<translation></translation>
</message>
<message>
<source>Connected</source>
<translation></translation>
<source>disconnect</source>
<translation></translation>
</message>
<message>
<source>Connect fail,Please try again</source>
<translation></translation>
</message>
</context>
<context>
<name>MainWidget</name>
<message>
<source>Disconnection Fail</source>
<translation></translation>
<source></source>
<translation> </translation>
</message>
</context>
</TS>

View File

@ -1,98 +1,167 @@
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE TS>
<TS version="2.1" language="en_US" sourcelanguage="en">
<TS version="2.1" language="zh_CN" sourcelanguage="en">
<context>
<name>BlueToothMainWindow</name>
<name>BlueToothMain</name>
<message>
<location filename="../bluetoothmainwindow.cpp" line="97"/>
<source>Bluetooth adapter is abnormal !</source>
<translation>Bluetooth adapter is abnormal !</translation>
</message>
<message>
<location filename="../bluetoothmainwindow.cpp" line="131"/>
<source>Bluetooth adapter not detected !</source>
<translation>Bluetooth adapter not detected !</translation>
</message>
<message>
<location filename="../bluetoothmainwindow.cpp" line="260"/>
<location filename="../bluetoothmain.cpp" line="1824"/>
<source>Bluetooth</source>
<translation>Bluetooth</translation>
</message>
<message>
<location filename="../bluetoothmainwindow.cpp" line="288"/>
<source>Turn on :</source>
<translation>Turn on:</translation>
<extra-contents_path>/Bluetooth/Turn on :</extra-contents_path>
<location filename="../bluetoothmain.cpp" line="1854"/>
<source>Turn on</source>
<oldsource>Turn on :</oldsource>
<translation>Turn on</translation>
<extra-contents_path>/Bluetooth/Turn on</extra-contents_path>
</message>
<message>
<location filename="../bluetoothmainwindow.cpp" line="320"/>
<source>Adapter List</source>
<translation>Adapter List</translation>
<extra-contents_path>/Bluetooth/Adapter List</extra-contents_path>
<location filename="../bluetoothmain.cpp" line="1908"/>
<source>Bluetooth adapter</source>
<translation>Bluetooth adapter</translation>
<extra-contents_path>/Bluetooth/Bluetooth adapter</extra-contents_path>
</message>
<message>
<location filename="../bluetoothmainwindow.cpp" line="350"/>
<location filename="../bluetoothmain.cpp" line="1950"/>
<source>Show icon on taskbar</source>
<translation>Show icon on taskbar</translation>
<extra-contents_path>/Bluetooth/Show icon on taskbar</extra-contents_path>
</message>
<message>
<location filename="../bluetoothmainwindow.cpp" line="378"/>
<location filename="../bluetoothmain.cpp" line="1994"/>
<source>Discoverable by nearby Bluetooth devices</source>
<translation>Discoverable by nearby Bluetooth devices</translation>
<extra-contents_path>/Bluetooth/Discoverable by nearby Bluetooth devices</extra-contents_path>
<extra-contents_path>/Bluetooth/Discoverable</extra-contents_path>
</message>
<message>
<location filename="../bluetoothmainwindow.cpp" line="406"/>
<location filename="../bluetoothmain.cpp" line="2026"/>
<source>Auto discover Bluetooth audio devices</source>
<translation>Auto discover Bluetooth audio devices</translation>
<extra-contents_path>/Bluetooth/Auto discover Bluetooth audio devices</extra-contents_path>
<extra-contents_path>/Bluetooth/Automatically discover Bluetooth audio devices</extra-contents_path>
</message>
<message>
<location filename="../bluetoothmainwindow.cpp" line="428"/>
<location filename="../bluetoothmain.cpp" line="2058"/>
<source>My Devices</source>
<translation>My Devices</translation>
</message>
<message>
<location filename="../bluetoothmainwindow.cpp" line="461"/>
<source>Bluetooth Devices</source>
<translation>Bluetooth Devices</translation>
<location filename="../bluetoothmain.cpp" line="2086"/>
<source>Other Devices</source>
<translation>Other Devices</translation>
<extra-contents_path>/Bluetooth/Other Devices</extra-contents_path>
</message>
<message>
<location filename="../bluetoothmainwindow.h" line="51"/>
<location filename="../bluetoothmain.cpp" line="2188"/>
<source>Bluetooth driver abnormal</source>
<translation>Bluetooth driver abnormal</translation>
</message>
<message>
<source>No Bluetooth adapter detected!</source>
<translation type="vanished"></translation>
</message>
<message>
<location filename="../bluetoothmain.cpp" line="2119"/>
<source>All</source>
<translation>All</translation>
</message>
<message>
<location filename="../bluetoothmainwindow.h" line="52"/>
<location filename="../bluetoothmain.cpp" line="2120"/>
<source>Audio</source>
<translation>Audio</translation>
</message>
<message>
<location filename="../bluetoothmainwindow.h" line="53"/>
<location filename="../bluetoothmain.cpp" line="2121"/>
<source>Peripherals</source>
<translation>Peripherals</translation>
</message>
<message>
<location filename="../bluetoothmainwindow.h" line="54"/>
<source>Computer</source>
<location filename="../bluetoothmain.cpp" line="2122"/>
<source>PC</source>
<translation>Computer</translation>
</message>
<message>
<location filename="../bluetoothmainwindow.h" line="55"/>
<location filename="../bluetoothmain.cpp" line="2123"/>
<source>Phone</source>
<translation>Phone</translation>
</message>
<message>
<location filename="../bluetoothmainwindow.h" line="56"/>
<location filename="../bluetoothmain.cpp" line="2124"/>
<source>Other</source>
<translation>Other</translation>
</message>
<message>
<source>Bluetooth adapter is not detected!</source>
<translation type="vanished"></translation>
</message>
</context>
<context>
<name>BlueToothMainWindow</name>
<message>
<source>Bluetooth adapter is abnormal !</source>
<translation type="vanished"></translation>
</message>
<message>
<source>Bluetooth adapter not detected !</source>
<translation type="vanished"></translation>
</message>
<message>
<source>Bluetooth</source>
<translation type="vanished"></translation>
</message>
<message>
<source>Turn on :</source>
<oldsource>Turn on</oldsource>
<translation type="vanished"></translation>
</message>
<message>
<source>Adapter List</source>
<translation type="vanished"></translation>
</message>
<message>
<source>Show icon on taskbar</source>
<translation type="vanished"></translation>
</message>
<message>
<source>Discoverable by nearby Bluetooth devices</source>
<translation type="vanished"></translation>
</message>
<message>
<source>My Devices</source>
<translation type="vanished"></translation>
</message>
<message>
<source>Other Devices</source>
<translation type="vanished"></translation>
</message>
<message>
<source>All</source>
<translation type="vanished"></translation>
</message>
<message>
<source>Audio</source>
<translation type="vanished"></translation>
</message>
<message>
<source>Peripherals</source>
<translation type="vanished"></translation>
</message>
<message>
<source>PC</source>
<translation type="vanished"></translation>
</message>
<message>
<source>Phone</source>
<translation type="vanished"></translation>
</message>
<message>
<source>Other</source>
<translation type="vanished"></translation>
</message>
</context>
<context>
<name>Bluetooth</name>
<message>
<location filename="../bluetooth.cpp" line="21"/>
<location filename="../bluetooth.cpp" line="15"/>
<source>Bluetooth</source>
<translation>Bluetooth</translation>
</message>
@ -100,47 +169,59 @@
<context>
<name>BluetoothNameLabel</name>
<message>
<location filename="../bluetoothnamelabel.cpp" line="26"/>
<location filename="../bluetoothnamelabel.cpp" line="22"/>
<source>Click to change the device name</source>
<oldsource>Double-click to change the device name</oldsource>
<translation>Click to change the device name</translation>
</message>
<message>
<location filename="../bluetoothnamelabel.cpp" line="197"/>
<location filename="../bluetoothnamelabel.cpp" line="79"/>
<location filename="../bluetoothnamelabel.cpp" line="202"/>
<source>Can now be found as &quot;%1&quot;</source>
<translation>Can now be found as &quot;%1&quot;</translation>
</message>
<message>
<location filename="../bluetoothnamelabel.cpp" line="90"/>
<source>Tip</source>
<translation>Tip</translation>
</message>
<message>
<location filename="../bluetoothnamelabel.cpp" line="91"/>
<source>The length of the device name does not exceed %1 characters !</source>
<translation>The length of the device name does not exceed %1 characters !</translation>
</message>
</context>
<context>
<name>DevRemoveDialog</name>
<message>
<location filename="../devremovedialog.cpp" line="28"/>
<location filename="../devremovedialog.cpp" line="27"/>
<source>Bluetooth Connections</source>
<translation>Bluetooth Connections</translation>
</message>
<message>
<location filename="../devremovedialog.cpp" line="49"/>
<location filename="../devremovedialog.cpp" line="56"/>
<location filename="../devremovedialog.cpp" line="48"/>
<location filename="../devremovedialog.cpp" line="55"/>
<source>After it is removed, the PIN code must be matched for the next connection.</source>
<translation>After it is removed, the PIN code must be matched for the next connection.</translation>
</message>
<message>
<location filename="../devremovedialog.cpp" line="75"/>
<location filename="../devremovedialog.cpp" line="74"/>
<source>Remove</source>
<translation>Remove</translation>
</message>
<message>
<location filename="../devremovedialog.cpp" line="83"/>
<location filename="../devremovedialog.cpp" line="82"/>
<source>Cancel</source>
<translation>Cancel</translation>
</message>
<message>
<location filename="../devremovedialog.cpp" line="108"/>
<location filename="../devremovedialog.cpp" line="107"/>
<source>Connection failed! Please remove it before connecting.</source>
<translation>Connection failed! Please remove it before connecting.</translation>
</message>
<message>
<location filename="../devremovedialog.cpp" line="110"/>
<location filename="../devremovedialog.cpp" line="109"/>
<location filename="../devremovedialog.cpp" line="118"/>
<source>Are you sure to remove %1 ?</source>
<translation>Are you sure to remove %1 ?</translation>
</message>
@ -148,110 +229,112 @@
<context>
<name>DevRenameDialog</name>
<message>
<location filename="../devrenamedialog.cpp" line="26"/>
<location filename="../devrenamedialog.cpp" line="79"/>
<source>Rename</source>
<translation>Rename</translation>
</message>
<message>
<location filename="../devrenamedialog.cpp" line="36"/>
<source>Rename device</source>
<translation>Rename device</translation>
</message>
<message>
<location filename="../devrenamedialog.cpp" line="114"/>
<location filename="../devrenamedialog.cpp" line="95"/>
<source>Name</source>
<translation>Name</translation>
</message>
<message>
<location filename="../devrenamedialog.cpp" line="130"/>
<location filename="../devrenamedialog.cpp" line="109"/>
<source>The value contains 1 to 32 characters</source>
<translation>The value contains 1 to 32 characters</translation>
</message>
<message>
<location filename="../devrenamedialog.cpp" line="135"/>
<source>The input character length exceeds the limit</source>
<translation type="vanished"></translation>
</message>
<message>
<location filename="../devrenamedialog.cpp" line="114"/>
<source>OK</source>
<translation>OK</translation>
</message>
<message>
<location filename="../devrenamedialog.cpp" line="148"/>
<location filename="../devrenamedialog.cpp" line="127"/>
<source>Cancel</source>
<translation>Cancel</translation>
</message>
</context>
<context>
<name>bluetoothdevicefunc</name>
<name>DeviceInfoItem</name>
<message>
<location filename="../bluetoothdevicefunc.cpp" line="82"/>
<location filename="../bluetoothdevicefunc.cpp" line="222"/>
<source>connect</source>
<translation>connect</translation>
</message>
<message>
<location filename="../bluetoothdevicefunc.cpp" line="92"/>
<location filename="../bluetoothdevicefunc.cpp" line="243"/>
<source>rename</source>
<translation>rename</translation>
</message>
<message>
<location filename="../bluetoothdevicefunc.cpp" line="87"/>
<location filename="../bluetoothdevicefunc.cpp" line="228"/>
<source>disconnect</source>
<translation>disconnect</translation>
</message>
<message>
<location filename="../bluetoothdevicefunc.cpp" line="72"/>
<location filename="../bluetoothdevicefunc.cpp" line="248"/>
<source>remove</source>
<translation>remove</translation>
</message>
<message>
<location filename="../bluetoothdevicefunc.cpp" line="67"/>
<location filename="../bluetoothdevicefunc.cpp" line="238"/>
<source>sendFile</source>
<translation>sendFile</translation>
</message>
</context>
<context>
<name>bluetoothdeviceitem</name>
<message>
<location filename="../bluetoothdeviceitem.h" line="58"/>
<source>unknown</source>
<translation>unknown</translation>
</message>
<message>
<location filename="../bluetoothdeviceitem.h" line="59"/>
<location filename="../deviceinfoitem.cpp" line="21"/>
<source>Connecting</source>
<translation>Connecting</translation>
</message>
<message>
<location filename="../bluetoothdeviceitem.h" line="60"/>
<location filename="../deviceinfoitem.cpp" line="22"/>
<source>Disconnecting</source>
<translation>Disconnecting</translation>
</message>
<message>
<location filename="../bluetoothdeviceitem.h" line="61"/>
<source>Not Paired</source>
<translation>Not Paired</translation>
</message>
<message>
<location filename="../bluetoothdeviceitem.h" line="62"/>
<source>Not Connected</source>
<translation>Not Connected</translation>
</message>
<message>
<location filename="../bluetoothdeviceitem.h" line="63"/>
<location filename="../deviceinfoitem.cpp" line="23"/>
<source>Connected</source>
<translation>Connected</translation>
</message>
<message>
<location filename="../bluetoothdeviceitem.h" line="64"/>
<location filename="../deviceinfoitem.cpp" line="24"/>
<source>Not Connected</source>
<translation>Not Connected</translation>
</message>
<message>
<location filename="../deviceinfoitem.cpp" line="25"/>
<source>Connect fail,Please try again</source>
<translation>Connect fail,Please try again</translation>
</message>
<message>
<location filename="../bluetoothdeviceitem.h" line="65"/>
<source>Disconnection Fail</source>
<translation>Disconnection Fail</translation>
<location filename="../deviceinfoitem.cpp" line="164"/>
<location filename="../deviceinfoitem.cpp" line="538"/>
<source>disconnect</source>
<translation>disconnect</translation>
</message>
<message>
<source>Paired</source>
<translation type="vanished"></translation>
</message>
<message>
<source>Connect fail</source>
<translation type="vanished"></translation>
</message>
<message>
<location filename="../deviceinfoitem.cpp" line="26"/>
<source>Disconnect fail</source>
<translation>Disconnect fail</translation>
</message>
<message>
<source>Send files</source>
<translation type="vanished"></translation>
</message>
<message>
<source>Remove</source>
<translation type="vanished"></translation>
</message>
<message>
<source>cancel</source>
<translation type="vanished"></translation>
</message>
<message>
<location filename="../deviceinfoitem.cpp" line="153"/>
<location filename="../deviceinfoitem.cpp" line="570"/>
<source>remove</source>
<translation>remove</translation>
</message>
<message>
<location filename="../deviceinfoitem.cpp" line="147"/>
<location filename="../deviceinfoitem.cpp" line="562"/>
<source>send file</source>
<translation>send file</translation>
</message>
<message>
<source>Sure to remove,</source>
<translation type="vanished"></translation>
</message>
<message>
<source>After removal, the next connection requires matching PIN code!</source>
<translation type="vanished">PIN码</translation>
</message>
</context>
</TS>

View File

@ -1,213 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE TS>
<TS version="2.1" language="mn">
<context>
<name>BlueToothMainWindow</name>
<message>
<source>Bluetooth adapter is abnormal !</source>
<translation> !</translation>
</message>
<message>
<source>Bluetooth</source>
<translation></translation>
</message>
<message>
<source>Turn on :</source>
<translation>:</translation>
<extra-contents_path>/Bluetooth/Turn on :</extra-contents_path>
</message>
<message>
<source>Show icon on taskbar</source>
<translation> </translation>
<extra-contents_path>/Bluetooth/Show icon on taskbar</extra-contents_path>
</message>
<message>
<source>Discoverable by nearby Bluetooth devices</source>
<translation> </translation>
<extra-contents_path>/Bluetooth/Discoverable by nearby Bluetooth devices</extra-contents_path>
</message>
<message>
<source>My Devices</source>
<translation> </translation>
</message>
<message>
<source>Audio</source>
<translation> </translation>
</message>
<message>
<source>Other</source>
<translation></translation>
</message>
<message>
<source>Bluetooth adapter not detected !</source>
<translation> !</translation>
</message>
<message>
<source>Adapter List</source>
<translation> </translation>
<extra-contents_path>/Bluetooth/Adapter List</extra-contents_path>
</message>
<message>
<source>Auto discover Bluetooth audio devices</source>
<translation> </translation>
<extra-contents_path>/Bluetooth/Auto discover Bluetooth audio devices</extra-contents_path>
</message>
<message>
<source>All</source>
<translation></translation>
</message>
<message>
<source>Peripherals</source>
<translation> </translation>
</message>
<message>
<source>Computer</source>
<translation></translation>
</message>
<message>
<source>Phone</source>
<translation> </translation>
</message>
<message>
<source>Bluetooth Devices</source>
<translation> </translation>
</message>
</context>
<context>
<name>Bluetooth</name>
<message>
<source>Bluetooth</source>
<translation></translation>
</message>
</context>
<context>
<name>BluetoothNameLabel</name>
<message>
<source>Can now be found as &quot;%1&quot;</source>
<translation> &quot;%1&quot;</translation>
</message>
<message>
<source>Click to change the device name</source>
<translation> </translation>
</message>
</context>
<context>
<name>DevRemoveDialog</name>
<message>
<source>After it is removed, the PIN code must be matched for the next connection.</source>
<translation> PIN .</translation>
</message>
<message>
<source>Remove</source>
<translation></translation>
</message>
<message>
<source>Cancel</source>
<translation></translation>
</message>
<message>
<source>Are you sure to remove %1 ?</source>
<translation>%1 / ?</translation>
</message>
<message>
<source>Connection failed! Please remove it before connecting.</source>
<translation> .</translation>
</message>
<message>
<source>Bluetooth Connections</source>
<translation> </translation>
</message>
</context>
<context>
<name>DevRenameDialog</name>
<message>
<source>Rename</source>
<translation> </translation>
</message>
<message>
<source>Name</source>
<translation> </translation>
</message>
<message>
<source>OK</source>
<translation>OK</translation>
</message>
<message>
<source>Cancel</source>
<translation></translation>
</message>
<message>
<source>The value contains 1 to 32 characters</source>
<translation> 1-32 </translation>
</message>
<message>
<source>Rename device</source>
<translation> </translation>
</message>
</context>
<context>
<name>MainWidget</name>
<message>
<source></source>
<translation></translation>
</message>
</context>
<context>
<name>bluetoothdevicefunc</name>
<message>
<source>sendFile</source>
<translation> </translation>
</message>
<message>
<source>remove</source>
<translation></translation>
</message>
<message>
<source>connect</source>
<translation></translation>
</message>
<message>
<source>disconnect</source>
<translation> </translation>
</message>
<message>
<source>rename</source>
<translation> </translation>
</message>
</context>
<context>
<name>bluetoothdeviceitem</name>
<message>
<source>unknown</source>
<translation> </translation>
</message>
<message>
<source>Connecting</source>
<translation> </translation>
</message>
<message>
<source>Disconnecting</source>
<translation> </translation>
</message>
<message>
<source>Not Paired</source>
<translation> </translation>
</message>
<message>
<source>Not Connected</source>
<translation> </translation>
</message>
<message>
<source>Connected</source>
<translation> </translation>
</message>
<message>
<source>Connect fail,Please try again</source>
<translation> </translation>
</message>
<message>
<source>Disconnection Fail</source>
<translation> </translation>
</message>
</context>
</TS>

View File

@ -2,98 +2,170 @@
<!DOCTYPE TS>
<TS version="2.1" language="zh_CN" sourcelanguage="en">
<context>
<name>BlueToothMainWindow</name>
<name>BlueToothMain</name>
<message>
<location filename="../bluetoothmainwindow.cpp" line="97"/>
<source>Bluetooth adapter is abnormal !</source>
<translation></translation>
</message>
<message>
<location filename="../bluetoothmainwindow.cpp" line="131"/>
<source>Bluetooth adapter not detected !</source>
<translation></translation>
</message>
<message>
<location filename="../bluetoothmainwindow.cpp" line="260"/>
<location filename="../bluetoothmain.cpp" line="1850"/>
<source>Bluetooth</source>
<translation></translation>
</message>
<message>
<location filename="../bluetoothmainwindow.cpp" line="288"/>
<source>Turn on :</source>
<oldsource>Turn on</oldsource>
<translation></translation>
<extra-contents_path>/Bluetooth/Turn on :</extra-contents_path>
<location filename="../bluetoothmain.cpp" line="1880"/>
<source>Turn on</source>
<oldsource>Turn on :</oldsource>
<translation></translation>
<extra-contents_path>/Bluetooth/Turn on</extra-contents_path>
</message>
<message>
<location filename="../bluetoothmainwindow.cpp" line="320"/>
<source>Adapter List</source>
<location filename="../bluetoothmain.cpp" line="1934"/>
<source>Bluetooth adapter</source>
<translation></translation>
<extra-contents_path>/Bluetooth/Adapter List</extra-contents_path>
<extra-contents_path>/Bluetooth/Bluetooth adapter</extra-contents_path>
</message>
<message>
<location filename="../bluetoothmainwindow.cpp" line="350"/>
<location filename="../bluetoothmain.cpp" line="1976"/>
<source>Show icon on taskbar</source>
<translation></translation>
<extra-contents_path>/Bluetooth/Show icon on taskbar</extra-contents_path>
</message>
<message>
<location filename="../bluetoothmainwindow.cpp" line="378"/>
<location filename="../bluetoothmain.cpp" line="2020"/>
<source>Discoverable by nearby Bluetooth devices</source>
<translation></translation>
<extra-contents_path>/Bluetooth/Discoverable by nearby Bluetooth devices</extra-contents_path>
<extra-contents_path>/Bluetooth/Discoverable</extra-contents_path>
</message>
<message>
<location filename="../bluetoothmainwindow.cpp" line="406"/>
<location filename="../bluetoothmain.cpp" line="2051"/>
<source>Auto discover Bluetooth audio devices</source>
<translation></translation>
<extra-contents_path>/Bluetooth/Auto discover Bluetooth audio devices</extra-contents_path>
<extra-contents_path>/Bluetooth/Automatically discover Bluetooth audio devices</extra-contents_path>
</message>
<message>
<location filename="../bluetoothmainwindow.cpp" line="428"/>
<location filename="../bluetoothmain.cpp" line="2083"/>
<source>My Devices</source>
<translation></translation>
</message>
<message>
<location filename="../bluetoothmainwindow.cpp" line="461"/>
<source>Bluetooth Devices</source>
<translation></translation>
<location filename="../bluetoothmain.cpp" line="2111"/>
<source>Other Devices</source>
<translation></translation>
<extra-contents_path>/Bluetooth/Other Devices</extra-contents_path>
</message>
<message>
<location filename="../bluetoothmainwindow.h" line="51"/>
<location filename="../bluetoothmain.cpp" line="2214"/>
<source>The Bluetooth adapter is not detected!</source>
<translation></translation>
</message>
<message>
<source>Bluetooth driver abnormal</source>
<translation type="vanished"></translation>
</message>
<message>
<source>No Bluetooth adapter detected!</source>
<translation type="vanished"></translation>
</message>
<message>
<location filename="../bluetoothmain.cpp" line="2144"/>
<source>All</source>
<translation></translation>
</message>
<message>
<location filename="../bluetoothmainwindow.h" line="52"/>
<location filename="../bluetoothmain.cpp" line="2145"/>
<source>Audio</source>
<translation></translation>
</message>
<message>
<location filename="../bluetoothmainwindow.h" line="53"/>
<location filename="../bluetoothmain.cpp" line="2146"/>
<source>Peripherals</source>
<translation></translation>
</message>
<message>
<location filename="../bluetoothmainwindow.h" line="54"/>
<source>Computer</source>
<location filename="../bluetoothmain.cpp" line="2147"/>
<source>PC</source>
<translation></translation>
</message>
<message>
<location filename="../bluetoothmainwindow.h" line="55"/>
<location filename="../bluetoothmain.cpp" line="2148"/>
<source>Phone</source>
<translation></translation>
</message>
<message>
<location filename="../bluetoothmainwindow.h" line="56"/>
<location filename="../bluetoothmain.cpp" line="2149"/>
<source>Other</source>
<translation></translation>
</message>
<message>
<source>Bluetooth adapter is not detected!</source>
<translation type="vanished"></translation>
</message>
</context>
<context>
<name>BlueToothMainWindow</name>
<message>
<source>Bluetooth adapter is abnormal !</source>
<translation type="vanished"></translation>
</message>
<message>
<source>Bluetooth adapter not detected !</source>
<translation type="vanished"></translation>
</message>
<message>
<source>Bluetooth</source>
<translation type="vanished"></translation>
</message>
<message>
<source>Turn on :</source>
<oldsource>Turn on</oldsource>
<translation type="vanished"></translation>
</message>
<message>
<source>Adapter List</source>
<translation type="vanished"></translation>
</message>
<message>
<source>Show icon on taskbar</source>
<translation type="vanished"></translation>
</message>
<message>
<source>Discoverable by nearby Bluetooth devices</source>
<translation type="vanished"></translation>
</message>
<message>
<source>My Devices</source>
<translation type="vanished"></translation>
</message>
<message>
<source>Other Devices</source>
<translation type="vanished"></translation>
</message>
<message>
<source>All</source>
<translation type="vanished"></translation>
</message>
<message>
<source>Audio</source>
<translation type="vanished"></translation>
</message>
<message>
<source>Peripherals</source>
<translation type="vanished"></translation>
</message>
<message>
<source>PC</source>
<translation type="vanished"></translation>
</message>
<message>
<source>Phone</source>
<translation type="vanished"></translation>
</message>
<message>
<source>Other</source>
<translation type="vanished"></translation>
</message>
</context>
<context>
<name>Bluetooth</name>
<message>
<location filename="../bluetooth.cpp" line="21"/>
<location filename="../bluetooth.cpp" line="15"/>
<source>Bluetooth</source>
<translation></translation>
</message>
@ -107,10 +179,18 @@
<translation></translation>
</message>
<message>
<location filename="../bluetoothnamelabel.cpp" line="197"/>
<location filename="../bluetoothnamelabel.cpp" line="208"/>
<source>Can now be found as &quot;%1&quot;</source>
<translation>&quot;%1&quot;</translation>
</message>
<message>
<source>Tip</source>
<translation type="vanished"></translation>
</message>
<message>
<source>The length of the device name does not exceed %1 characters !</source>
<translation type="vanished"> %1 </translation>
</message>
</context>
<context>
<name>DevRemoveDialog</name>
@ -149,110 +229,112 @@
<context>
<name>DevRenameDialog</name>
<message>
<location filename="../devrenamedialog.cpp" line="26"/>
<location filename="../devrenamedialog.cpp" line="79"/>
<source>Rename</source>
<translation></translation>
<translation></translation>
</message>
<message>
<location filename="../devrenamedialog.cpp" line="36"/>
<source>Rename device</source>
<translation></translation>
</message>
<message>
<location filename="../devrenamedialog.cpp" line="114"/>
<location filename="../devrenamedialog.cpp" line="95"/>
<source>Name</source>
<translation></translation>
<translation></translation>
</message>
<message>
<location filename="../devrenamedialog.cpp" line="130"/>
<location filename="../devrenamedialog.cpp" line="109"/>
<source>The value contains 1 to 32 characters</source>
<translation> 1-32 </translation>
</message>
<message>
<location filename="../devrenamedialog.cpp" line="135"/>
<source>The input character length exceeds the limit</source>
<translation type="vanished"></translation>
</message>
<message>
<location filename="../devrenamedialog.cpp" line="114"/>
<source>OK</source>
<translation></translation>
</message>
<message>
<location filename="../devrenamedialog.cpp" line="148"/>
<location filename="../devrenamedialog.cpp" line="127"/>
<source>Cancel</source>
<translation></translation>
</message>
</context>
<context>
<name>bluetoothdevicefunc</name>
<name>DeviceInfoItem</name>
<message>
<location filename="../bluetoothdevicefunc.cpp" line="82"/>
<location filename="../bluetoothdevicefunc.cpp" line="222"/>
<source>connect</source>
<translation></translation>
</message>
<message>
<location filename="../bluetoothdevicefunc.cpp" line="92"/>
<location filename="../bluetoothdevicefunc.cpp" line="243"/>
<source>rename</source>
<translation></translation>
</message>
<message>
<location filename="../bluetoothdevicefunc.cpp" line="87"/>
<location filename="../bluetoothdevicefunc.cpp" line="228"/>
<source>disconnect</source>
<translation></translation>
</message>
<message>
<location filename="../bluetoothdevicefunc.cpp" line="72"/>
<location filename="../bluetoothdevicefunc.cpp" line="248"/>
<source>remove</source>
<translation></translation>
</message>
<message>
<location filename="../bluetoothdevicefunc.cpp" line="67"/>
<location filename="../bluetoothdevicefunc.cpp" line="238"/>
<source>sendFile</source>
<translation></translation>
</message>
</context>
<context>
<name>bluetoothdeviceitem</name>
<message>
<location filename="../bluetoothdeviceitem.h" line="58"/>
<source>unknown</source>
<translation></translation>
</message>
<message>
<location filename="../bluetoothdeviceitem.h" line="59"/>
<location filename="../deviceinfoitem.cpp" line="46"/>
<source>Connecting</source>
<translation></translation>
</message>
<message>
<location filename="../bluetoothdeviceitem.h" line="60"/>
<location filename="../deviceinfoitem.cpp" line="47"/>
<source>Disconnecting</source>
<translation></translation>
</message>
<message>
<location filename="../bluetoothdeviceitem.h" line="61"/>
<source>Not Paired</source>
<translation></translation>
</message>
<message>
<location filename="../bluetoothdeviceitem.h" line="62"/>
<source>Not Connected</source>
<translation></translation>
</message>
<message>
<location filename="../bluetoothdeviceitem.h" line="63"/>
<location filename="../deviceinfoitem.cpp" line="48"/>
<source>Connected</source>
<translation></translation>
</message>
<message>
<location filename="../bluetoothdeviceitem.h" line="64"/>
<location filename="../deviceinfoitem.cpp" line="49"/>
<source>Not Connected</source>
<translation></translation>
</message>
<message>
<location filename="../deviceinfoitem.cpp" line="50"/>
<source>Connect fail,Please try again</source>
<translation></translation>
</message>
<message>
<location filename="../bluetoothdeviceitem.h" line="65"/>
<source>Disconnection Fail</source>
<location filename="../deviceinfoitem.cpp" line="211"/>
<location filename="../deviceinfoitem.cpp" line="614"/>
<source>disconnect</source>
<translation></translation>
</message>
<message>
<source>Paired</source>
<translation type="vanished"></translation>
</message>
<message>
<source>Connect fail</source>
<translation type="vanished"></translation>
</message>
<message>
<location filename="../deviceinfoitem.cpp" line="51"/>
<source>Disconnect fail</source>
<translation></translation>
</message>
<message>
<source>Send files</source>
<translation type="vanished"></translation>
</message>
<message>
<source>Remove</source>
<translation type="vanished"></translation>
</message>
<message>
<source>cancel</source>
<translation type="vanished"></translation>
</message>
<message>
<location filename="../deviceinfoitem.cpp" line="200"/>
<location filename="../deviceinfoitem.cpp" line="646"/>
<source>remove</source>
<translation></translation>
</message>
<message>
<location filename="../deviceinfoitem.cpp" line="194"/>
<location filename="../deviceinfoitem.cpp" line="638"/>
<source>send file</source>
<translation></translation>
</message>
<message>
<source>Sure to remove,</source>
<translation type="vanished"></translation>
</message>
<message>
<source>After removal, the next connection requires matching PIN code!</source>
<translation type="vanished">PIN码</translation>
</message>
</context>
</TS>

View File

@ -2,98 +2,170 @@
<!DOCTYPE TS>
<TS version="2.1" language="zh_CN" sourcelanguage="en">
<context>
<name>BlueToothMainWindow</name>
<name>BlueToothMain</name>
<message>
<location filename="../bluetoothmainwindow.cpp" line="97"/>
<source>Bluetooth adapter is abnormal !</source>
<translation></translation>
</message>
<message>
<location filename="../bluetoothmainwindow.cpp" line="131"/>
<source>Bluetooth adapter not detected !</source>
<translation></translation>
</message>
<message>
<location filename="../bluetoothmainwindow.cpp" line="260"/>
<location filename="../bluetoothmain.cpp" line="1850"/>
<source>Bluetooth</source>
<translation></translation>
<translation></translation>
</message>
<message>
<location filename="../bluetoothmainwindow.cpp" line="288"/>
<source>Turn on :</source>
<oldsource>Turn on</oldsource>
<translation></translation>
<extra-contents_path>/Bluetooth/Turn on :</extra-contents_path>
<location filename="../bluetoothmain.cpp" line="1880"/>
<source>Turn on</source>
<oldsource>Turn on :</oldsource>
<translation></translation>
<extra-contents_path>/Bluetooth/Turn on</extra-contents_path>
</message>
<message>
<location filename="../bluetoothmainwindow.cpp" line="320"/>
<source>Adapter List</source>
<translation></translation>
<extra-contents_path>/Bluetooth/Adapter List</extra-contents_path>
<location filename="../bluetoothmain.cpp" line="1934"/>
<source>Bluetooth adapter</source>
<translation></translation>
<extra-contents_path>/Bluetooth/Bluetooth adapter</extra-contents_path>
</message>
<message>
<location filename="../bluetoothmainwindow.cpp" line="350"/>
<location filename="../bluetoothmain.cpp" line="1976"/>
<source>Show icon on taskbar</source>
<translation></translation>
<translation></translation>
<extra-contents_path>/Bluetooth/Show icon on taskbar</extra-contents_path>
</message>
<message>
<location filename="../bluetoothmainwindow.cpp" line="378"/>
<location filename="../bluetoothmain.cpp" line="2020"/>
<source>Discoverable by nearby Bluetooth devices</source>
<translation></translation>
<extra-contents_path>/Bluetooth/Discoverable by nearby Bluetooth devices</extra-contents_path>
<translation></translation>
<extra-contents_path>/Bluetooth/Discoverable</extra-contents_path>
</message>
<message>
<location filename="../bluetoothmainwindow.cpp" line="406"/>
<location filename="../bluetoothmain.cpp" line="2051"/>
<source>Auto discover Bluetooth audio devices</source>
<translation></translation>
<extra-contents_path>/Bluetooth/Auto discover Bluetooth audio devices</extra-contents_path>
<extra-contents_path>/Bluetooth/Automatically discover Bluetooth audio devices</extra-contents_path>
</message>
<message>
<location filename="../bluetoothmainwindow.cpp" line="428"/>
<location filename="../bluetoothmain.cpp" line="2083"/>
<source>My Devices</source>
<translation></translation>
<translation></translation>
</message>
<message>
<location filename="../bluetoothmainwindow.cpp" line="461"/>
<source>Bluetooth Devices</source>
<translation></translation>
<location filename="../bluetoothmain.cpp" line="2111"/>
<source>Other Devices</source>
<translation></translation>
<extra-contents_path>/Bluetooth/Other Devices</extra-contents_path>
</message>
<message>
<location filename="../bluetoothmainwindow.h" line="51"/>
<location filename="../bluetoothmain.cpp" line="2214"/>
<source>The Bluetooth adapter is not detected!</source>
<translation></translation>
</message>
<message>
<source>Bluetooth driver abnormal</source>
<translation type="vanished"></translation>
</message>
<message>
<source>No Bluetooth adapter detected!</source>
<translation type="vanished"></translation>
</message>
<message>
<location filename="../bluetoothmain.cpp" line="2144"/>
<source>All</source>
<translation></translation>
</message>
<message>
<location filename="../bluetoothmainwindow.h" line="52"/>
<location filename="../bluetoothmain.cpp" line="2145"/>
<source>Audio</source>
<translation></translation>
<translation></translation>
</message>
<message>
<location filename="../bluetoothmainwindow.h" line="53"/>
<location filename="../bluetoothmain.cpp" line="2146"/>
<source>Peripherals</source>
<translation></translation>
<translation></translation>
</message>
<message>
<location filename="../bluetoothmainwindow.h" line="54"/>
<source>Computer</source>
<location filename="../bluetoothmain.cpp" line="2147"/>
<source>PC</source>
<translation></translation>
</message>
<message>
<location filename="../bluetoothmainwindow.h" line="55"/>
<location filename="../bluetoothmain.cpp" line="2148"/>
<source>Phone</source>
<translation></translation>
<translation></translation>
</message>
<message>
<location filename="../bluetoothmainwindow.h" line="56"/>
<location filename="../bluetoothmain.cpp" line="2149"/>
<source>Other</source>
<translation></translation>
</message>
<message>
<source>Bluetooth adapter is not detected!</source>
<translation type="vanished"></translation>
</message>
</context>
<context>
<name>BlueToothMainWindow</name>
<message>
<source>Bluetooth adapter is abnormal !</source>
<translation type="vanished"></translation>
</message>
<message>
<source>Bluetooth adapter not detected !</source>
<translation type="vanished"></translation>
</message>
<message>
<source>Bluetooth</source>
<translation type="vanished"></translation>
</message>
<message>
<source>Turn on :</source>
<oldsource>Turn on</oldsource>
<translation type="vanished"></translation>
</message>
<message>
<source>Adapter List</source>
<translation type="vanished"></translation>
</message>
<message>
<source>Show icon on taskbar</source>
<translation type="vanished"></translation>
</message>
<message>
<source>Discoverable by nearby Bluetooth devices</source>
<translation type="vanished"></translation>
</message>
<message>
<source>My Devices</source>
<translation type="vanished"></translation>
</message>
<message>
<source>Other Devices</source>
<translation type="vanished"></translation>
</message>
<message>
<source>All</source>
<translation type="vanished"></translation>
</message>
<message>
<source>Audio</source>
<translation type="vanished"></translation>
</message>
<message>
<source>Peripherals</source>
<translation type="vanished"></translation>
</message>
<message>
<source>PC</source>
<translation type="vanished"></translation>
</message>
<message>
<source>Phone</source>
<translation type="vanished"></translation>
</message>
<message>
<source>Other</source>
<translation type="vanished"></translation>
</message>
</context>
<context>
<name>Bluetooth</name>
<message>
<location filename="../bluetooth.cpp" line="21"/>
<location filename="../bluetooth.cpp" line="15"/>
<source>Bluetooth</source>
<translation></translation>
</message>
@ -107,10 +179,18 @@
<translation></translation>
</message>
<message>
<location filename="../bluetoothnamelabel.cpp" line="197"/>
<location filename="../bluetoothnamelabel.cpp" line="208"/>
<source>Can now be found as &quot;%1&quot;</source>
<translation>%1</translation>
</message>
<message>
<source>Tip</source>
<translation type="vanished"></translation>
</message>
<message>
<source>The length of the device name does not exceed %1 characters !</source>
<translation type="vanished">%1</translation>
</message>
</context>
<context>
<name>DevRemoveDialog</name>
@ -149,110 +229,112 @@
<context>
<name>DevRenameDialog</name>
<message>
<location filename="../devrenamedialog.cpp" line="26"/>
<location filename="../devrenamedialog.cpp" line="79"/>
<source>Rename</source>
<translation></translation>
</message>
<message>
<location filename="../devrenamedialog.cpp" line="36"/>
<source>Rename device</source>
<translation></translation>
</message>
<message>
<location filename="../devrenamedialog.cpp" line="114"/>
<location filename="../devrenamedialog.cpp" line="95"/>
<source>Name</source>
<translation></translation>
</message>
<message>
<location filename="../devrenamedialog.cpp" line="130"/>
<location filename="../devrenamedialog.cpp" line="109"/>
<source>The value contains 1 to 32 characters</source>
<translation>1-32</translation>
</message>
<message>
<location filename="../devrenamedialog.cpp" line="135"/>
<source>The input character length exceeds the limit</source>
<translation type="vanished"></translation>
</message>
<message>
<location filename="../devrenamedialog.cpp" line="114"/>
<source>OK</source>
<translation></translation>
</message>
<message>
<location filename="../devrenamedialog.cpp" line="148"/>
<location filename="../devrenamedialog.cpp" line="127"/>
<source>Cancel</source>
<translation></translation>
</message>
</context>
<context>
<name>bluetoothdevicefunc</name>
<name>DeviceInfoItem</name>
<message>
<location filename="../bluetoothdevicefunc.cpp" line="82"/>
<location filename="../bluetoothdevicefunc.cpp" line="222"/>
<source>connect</source>
<translation></translation>
</message>
<message>
<location filename="../bluetoothdevicefunc.cpp" line="92"/>
<location filename="../bluetoothdevicefunc.cpp" line="243"/>
<source>rename</source>
<translation></translation>
</message>
<message>
<location filename="../bluetoothdevicefunc.cpp" line="87"/>
<location filename="../bluetoothdevicefunc.cpp" line="228"/>
<source>disconnect</source>
<translation></translation>
</message>
<message>
<location filename="../bluetoothdevicefunc.cpp" line="72"/>
<location filename="../bluetoothdevicefunc.cpp" line="248"/>
<source>remove</source>
<translation></translation>
</message>
<message>
<location filename="../bluetoothdevicefunc.cpp" line="67"/>
<location filename="../bluetoothdevicefunc.cpp" line="238"/>
<source>sendFile</source>
<translation></translation>
</message>
</context>
<context>
<name>bluetoothdeviceitem</name>
<message>
<location filename="../bluetoothdeviceitem.h" line="58"/>
<source>unknown</source>
<translation></translation>
</message>
<message>
<location filename="../bluetoothdeviceitem.h" line="59"/>
<location filename="../deviceinfoitem.cpp" line="46"/>
<source>Connecting</source>
<translation></translation>
</message>
<message>
<location filename="../bluetoothdeviceitem.h" line="60"/>
<location filename="../deviceinfoitem.cpp" line="47"/>
<source>Disconnecting</source>
<translation></translation>
</message>
<message>
<location filename="../bluetoothdeviceitem.h" line="61"/>
<source>Not Paired</source>
<translation></translation>
</message>
<message>
<location filename="../bluetoothdeviceitem.h" line="62"/>
<source>Not Connected</source>
<translation></translation>
</message>
<message>
<location filename="../bluetoothdeviceitem.h" line="63"/>
<location filename="../deviceinfoitem.cpp" line="48"/>
<source>Connected</source>
<translation></translation>
</message>
<message>
<location filename="../bluetoothdeviceitem.h" line="64"/>
<location filename="../deviceinfoitem.cpp" line="49"/>
<source>Not Connected</source>
<translation></translation>
</message>
<message>
<location filename="../deviceinfoitem.cpp" line="50"/>
<source>Connect fail,Please try again</source>
<translation></translation>
</message>
<message>
<location filename="../bluetoothdeviceitem.h" line="65"/>
<source>Disconnection Fail</source>
<location filename="../deviceinfoitem.cpp" line="211"/>
<location filename="../deviceinfoitem.cpp" line="614"/>
<source>disconnect</source>
<translation></translation>
</message>
<message>
<source>Paired</source>
<translation type="vanished"></translation>
</message>
<message>
<source>Connect fail</source>
<translation type="vanished"></translation>
</message>
<message>
<location filename="../deviceinfoitem.cpp" line="51"/>
<source>Disconnect fail</source>
<translation></translation>
</message>
<message>
<source>Send files</source>
<translation type="vanished"></translation>
</message>
<message>
<source>Remove</source>
<translation type="vanished"></translation>
</message>
<message>
<source>cancel</source>
<translation type="vanished"></translation>
</message>
<message>
<location filename="../deviceinfoitem.cpp" line="200"/>
<location filename="../deviceinfoitem.cpp" line="646"/>
<source>remove</source>
<translation></translation>
</message>
<message>
<location filename="../deviceinfoitem.cpp" line="194"/>
<location filename="../deviceinfoitem.cpp" line="638"/>
<source>send file</source>
<translation></translation>
</message>
<message>
<source>Sure to remove,</source>
<translation type="vanished"></translation>
</message>
<message>
<source>After removal, the next connection requires matching PIN code!</source>
<translation type="vanished">PIN码</translation>
</message>
</context>
</TS>

View File

@ -0,0 +1,3 @@
{
"Keys" : [ ]
}

View File

@ -20,10 +20,7 @@ LIBS += -lukcc
# 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
DEFINES += UKCC_BLUETOOTH_DATA_BURIAL_POINT
DEFINES += QT_NO_INFO_OUTPUT
DEFINES += QT_NO_DEBUG_OUTPUT
DEFINES += QT_DEPRECATED_WARNINGS
#exists(/etc/apt/ota_version)
#{
# DEFINES += DEVICE_IS_INTEL
@ -37,11 +34,11 @@ DEFINES += QT_NO_DEBUG_OUTPUT
SOURCES += \
bluetooth.cpp \
bluetoothdbusservice.cpp \
bluetoothdevicefunc.cpp \
bluetoothdeviceitem.cpp \
bluetoothmainwindow.cpp \
bluetoothmain.cpp \
#bluetoothmainwindow.cpp \
bluetoothnamelabel.cpp \
devicebase.cpp \
deviceinfoitem.cpp \
devremovedialog.cpp \
devrenamedialog.cpp \
loadinglabel.cpp \
@ -50,12 +47,12 @@ SOURCES += \
HEADERS += \
bluetooth.h \
bluetoothdbusservice.h \
bluetoothdevicefunc.h \
bluetoothdeviceitem.h \
bluetoothmainwindow.h \
bluetoothmain.h \
#bluetoothmainwindow.h \
bluetoothnamelabel.h \
config.h \
devicebase.h \
deviceinfoitem.h \
devremovedialog.h \
devrenamedialog.h \
loadinglabel.h \
@ -66,9 +63,7 @@ DISTFILES += ukcc-bluetooth.json
TRANSLATIONS += \
translations/ukcc-bluetooth_zh_CN.ts \
translations/ukcc-bluetooth_bo_CN.ts \
translations/ukcc-bluetooth_zh_HK.ts \
translations/ukcc-bluetooth_en_US.ts \
translations/ukcc-bluetooth_mn.ts
translations/ukcc-bluetooth_zh_HK.ts
system("lrelease translations/*.ts")
@ -91,5 +86,3 @@ INSTALLS += qm_files \
RESOURCES += \
ukcc-bluetooth.qrc
OBJECTS_DIR = ./obj/
MOC_DIR = ./moc/

View File

@ -1,39 +1,37 @@
#include "ukccbluetoothconfig.h"
QGSettings* ukccbluetoothconfig::ukccGsetting = new QGSettings(GSETTING_SCHEMA_UKCC,GSETTING_PACH_UKCC);
ukccbluetoothconfig::ukccbluetoothconfig()
{
}
ukccbluetoothconfig::~ukccbluetoothconfig()
{
ukccGsetting->deleteLater();
}
void ukccbluetoothconfig::launchBluetoothServiceStart(const QString &processName)
{
KyDebug();
qDebug () << Q_FUNC_INFO << __LINE__;
QProcess *process = new QProcess();
QString cmd = processName;
//cmd.append(" -o");
KyDebug() << cmd ;
qDebug () << Q_FUNC_INFO << cmd << __LINE__;
process->startDetached(cmd);
}
void ukccbluetoothconfig::killAppProcess(const quint64 &processId)
{
KyDebug() << "========================" << processId;
// QString strCommand = "ps -ef|grep " + processName + " |grep -v grep |awk '{print $2}'";
// QList <quint64> processId;
// checkProcessRunning(processName,processId);
// for(quint64 tempId : processId)
// {
qDebug () << Q_FUNC_INFO << "========================" << processId;
QProcess *process = new QProcess();
QString cmd = QString("kill -9 %1").arg(processId);
process->startDetached(cmd);
// }
}
bool ukccbluetoothconfig::checkProcessRunning(const QString &processName, QList<quint64> &listProcessId)
{
KyDebug() ;
qDebug() << Q_FUNC_INFO << __LINE__;
bool res(false);
QString strCommand;
@ -41,7 +39,7 @@ bool ukccbluetoothconfig::checkProcessRunning(const QString &processName, QList<
// strCommand = "ps -ef|grep '" + processName + " -o' |grep -v grep |awk '{print $2}'";
//else
strCommand = "ps -ef|grep '" + processName + "' |grep -v grep |awk '{print $2}'";
KyDebug() << strCommand ;
qDebug() << Q_FUNC_INFO << strCommand << __LINE__;
QByteArray ba = strCommand.toLatin1();
const char* strFind_ComName = ba.data();
@ -81,7 +79,7 @@ static QString executeLinuxCmd(QString strCmd)
void ukccbluetoothconfig::setEnvPCValue()
{
KyDebug();
qDebug() << Q_FUNC_INFO <<__LINE__;
unsigned int productFeatures = 0;
char * projectName = "";
char * projectSubName = "";
@ -113,7 +111,7 @@ FuncEnd:
envPC = Environment::MAVIS;
}
KyInfo() << envPC ;
qInfo () << Q_FUNC_INFO << envPC <<__LINE__;
}
const QImage ukccbluetoothconfig::loadSvgImage(const QPixmap &source, const PixmapColor &cgColor)
@ -199,20 +197,3 @@ const QPixmap ukccbluetoothconfig::loadSvg(const QPixmap &source, const PixmapCo
}
return QPixmap::fromImage(img);
}
bool ukccbluetoothconfig::ukccBtBuriedSettings(QString pluginName, QString settingsName, QString action, QString value)
{
#ifdef UKCC_BLUETOOTH_DATA_BURIAL_POINT
try
{
bool res = ukcc::UkccCommon::buriedSettings(pluginName,settingsName,action,value);
return res;
}
catch(std::exception &e)
{
KyWarning() << e.what();
return false;
}
#endif
return false;
}

View File

@ -5,13 +5,8 @@
#include <QDebug>
#include <QPixmap>
#include <QProcess>
#include <QGSettings>
#include <ukui-log4qt.h>
#ifdef UKCC_BLUETOOTH_DATA_BURIAL_POINT
#include <ukcc/interface/ukcccommon.h>
#endif
#include "kysdk/kysdk-system/libkysysinfo.h"
#include "config.h"
@ -20,7 +15,6 @@ class ukccbluetoothconfig
{
public:
ukccbluetoothconfig();
~ukccbluetoothconfig();
enum PixmapColor {
WHITE = 0,
BLACK,
@ -28,9 +22,7 @@ public:
BLUE,
DEFAULT
};
static QGSettings *ukccGsetting;
static bool ukccBtBuriedSettings(QString pluginName, QString settingsName, QString action, QString value = nullptr);
static void launchBluetoothServiceStart(const QString &processName);
static void killAppProcess(const quint64 &processId);
static bool checkProcessRunning(const QString &processName, QList<quint64> &listProcessId);

View File

@ -7,6 +7,7 @@ INCLUDEPATH += .
SUBDIRS += ukui-bluetooth \
ukcc-bluetooth \
profileDaemon \
service
# The following define makes your compiler warn you if you use any

View File

@ -0,0 +1,205 @@
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: dunto; c-basic-offset: 4 -*-
*
* Copyright (C) 2019 Tianjin KYLIN Information Technology 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.
*
*/
#include "activeconnectionwidget.h"
#include "config/xatom-helper.h"
#include "config/config.h"
#include <QPainterPath>
ActiveConnectionWidget::ActiveConnectionWidget(QString address, QString name, QString type, int rssi) :
devAddr(address),
devName(name),
devType(type),
devRSSI(rssi)
{
if(QGSettings::isSchemaInstalled("org.ukui.style")){
settings = new QGSettings("org.ukui.style");
connect(settings,&QGSettings::changed,this,&ActiveConnectionWidget::GSettingsChanges);
}
const QByteArray transparency_id(TRANSPARENCY_SETTINGS);
if(QGSettings::isSchemaInstalled(transparency_id)) {
transparency = new QGSettings(transparency_id);
}
if(QGSettings::isSchemaInstalled(transparency_id)) {
getTransparency();
connect(transparency,&QGSettings::changed,this,&ActiveConnectionWidget::GSettingsChanges);
}
setProperty("useStyleWindowManager", false);
setProperty("useSystemStyleBlur", true);
this->setAttribute(Qt::WA_TranslucentBackground);
//窗管协议
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);
this->setWindowIcon(QIcon::fromTheme("bluetooth"));
this->setWindowTitle(tr("Bluetooth Connection"));
this->setAttribute(Qt::WA_DeleteOnClose);
this->setFixedSize(420, 154);
window_icon = new QLabel(this);
window_icon->setPixmap(QIcon::fromTheme("preferences-system-bluetooth").pixmap(22,22));
window_title = new QLabel(tr("Bluetooth Connections"),this);
window_title->setFixedSize(300,20);
window_close = new QPushButton(this);
window_close->setIcon(QIcon::fromTheme("window-close-symbolic"));
window_close->setProperty("isWindowButton", 0x2);
window_close->setProperty("useIconHighlightEffect", 0x8);
window_close->setFlat(true);
connect(window_close, &QPushButton::clicked, this, &ActiveConnectionWidget::onClick_close_btn);
tip_txt = new QLabel(this);
tip_txt->setFixedWidth(380);
QFontMetrics fontMetrics(tip_txt->font());
QString tip = QString(tr("Found audio device \"") + devName + tr("\", connect it or not?"));
QString _tip = fontMetrics.elidedText(tip,
Qt::ElideMiddle,
tip_txt->width());
if (tip != _tip)
tip_txt->setToolTip(tip);
tip_txt->setText(_tip);
connect_btn = new QPushButton(tr("Connect"),this);
connect_btn->setFocusPolicy(Qt::NoFocus);
connect(connect_btn, &QPushButton::clicked, this, &ActiveConnectionWidget::onClick_connect_btn);
cancel_btn = new QPushButton(tr("Cancel"),this);
cancel_btn->setFocusPolicy(Qt::NoFocus);
connect(cancel_btn, &QPushButton::clicked, this, &ActiveConnectionWidget::onClick_cancel_btn);
window_icon->setGeometry(8,8,24,24);
window_title->setGeometry(36, 10, 300, 20);
window_close->setGeometry(388,8,24,24);
tip_txt->setGeometry(24,48,380,28);
cancel_btn->setGeometry(188,94,96,36);
connect_btn->setGeometry(300,94,96,36);
Config::setKdkGeometry(this->windowHandle(), this->width(),this->height(),false);
}
ActiveConnectionWidget::~ActiveConnectionWidget()
{
qDebug() << Q_FUNC_INFO;
}
void ActiveConnectionWidget::getTransparency() {
double proportion = transparency->get(TRANSPARENCY_KEY).toDouble();
proportion = ((proportion > 0.85) ? 1 : (proportion + 0.15));
qDebug() << Q_FUNC_INFO << proportion;
tran = proportion * 255;
}
void ActiveConnectionWidget::onClick_close_btn()
{
qDebug() << Q_FUNC_INFO << "close";
onClick_cancel_btn();
}
void ActiveConnectionWidget::onClick_connect_btn()
{
qDebug() << Q_FUNC_INFO << "accpet";
emit replyActiveConnection(devAddr, true);
this->hide();
this->deleteLater();
}
void ActiveConnectionWidget::onClick_cancel_btn()
{
qDebug() << Q_FUNC_INFO << "cancel";
emit replyActiveConnection(devAddr, false);
this->hide();
this->deleteLater();
}
void ActiveConnectionWidget::GSettingsChanges(const QString &key)
{
qDebug() << Q_FUNC_INFO << key;
if(key == "styleName"){
this->update();
}
if (key == "systemFontSize") {
QFontMetrics fontMetrics(tip_txt->font());
QString tip = fontMetrics.elidedText(QString(tr("Found audio device \"") + devName + tr("\", connect it or not?")),
Qt::ElideMiddle,
tip_txt->width());
tip_txt->setText(tip);
}
}
QPushButton* ActiveConnectionWidget::getButton() {
switch (pressCnt) {
case 1:
return connect_btn;
case 2:
return cancel_btn;
case 3:
return window_close;
default:
return nullptr;
}
}
void ActiveConnectionWidget::paintEvent(QPaintEvent *event) {
QPainter pt(this);
QColor color = QColor("#818181");
pt.setPen(color);
selectedBtn = getButton();
if (selectedBtn == nullptr) {
QWidget::paintEvent(event);
return;
}
QRect rect = selectedBtn->geometry();
pt.setRenderHint(QPainter::Antialiasing);
pt.drawRect(rect);
QWidget::paintEvent(event);
}
void ActiveConnectionWidget::keyPressEvent(QKeyEvent *event) {
switch (event->key()) {
case Qt::Key_Tab:
qDebug() << "press Tab";
++pressCnt;
if (pressCnt == 4)
pressCnt = 1;
this->update();
break;
case Qt::Key_Enter:
case Qt::Key_Return:
qDebug() << "press Enter";
if (selectedBtn == nullptr)
return;
selectedBtn->clicked();
break;
case Qt::Key_Escape:
qDebug() << "press Esc";
if (pressCnt == 0)
this->close();
pressCnt = 0;
this->update();
break;
default:
break;
}
}

View File

@ -1,3 +1,23 @@
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: dunto; c-basic-offset: 4 -*-
*
* Copyright (C) 2019 Tianjin KYLIN Information Technology 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 ACTIVECONNECTIONWIDGET_H
#define ACTIVECONNECTIONWIDGET_H
@ -7,7 +27,6 @@
#include <QObject>
#include <QWidget>
#include <QPainter>
#include <QCheckBox>
#include <QGSettings>
#include <QPushButton>
#include <QApplication>
@ -30,8 +49,6 @@ private:
int pressCnt = 0;
double tran =1;
bool mutex = false;
QString devAddr;
QString devName;
QString devType;
@ -42,15 +59,12 @@ private:
QLabel *window_icon = nullptr;
QLabel *window_title = nullptr;
QLabel *tip_txt = nullptr;
QLabel *checkBox_txt = nullptr;
QPushButton *window_close = nullptr;
QPushButton *connect_btn = nullptr;
QPushButton *cancel_btn = nullptr;
QPushButton *selectedBtn = nullptr;
QCheckBox *actCnt_box = nullptr;
QPushButton *getButton();
void defaultStyleInit();
void getTransparency();
@ -61,18 +75,12 @@ private slots:
void onClick_cancel_btn();
void GSettingsChanges(const QString &key);
public slots:
void autoConnChanged(bool activate);
signals:
void replyActiveConnection(QString,bool);
protected:
void paintEvent(QPaintEvent *event);
void keyPressEvent(QKeyEvent *event);
void focusOutEvent(QFocusEvent *event);
void focusInEvent(QFocusEvent *event);
void dragEnterEvent(QDragEnterEvent *event);
};
#endif // ACTIVECONNECTIONWIDGET_H

View File

@ -1,3 +1,23 @@
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: dunto; c-basic-offset: 4 -*-
*
* Copyright (C) 2019 Tianjin KYLIN Information Technology 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.
*
*/
#include "bluetoothsettinglabel.h"
BluetoothSettingLabel::BluetoothSettingLabel(QWidget *parent) : QLabel(parent)
@ -32,10 +52,7 @@ QColor BluetoothSettingLabel::getPainterBrushColor()
QColor color;
switch (_MStatus) {
case Status::Normal:
if (StyleSettings->get("style-name").toString() == "ukui-default")
color = QColor(217,217,217);
else
color = this->palette().color(QPalette::Active, QPalette::ButtonText);
color = this->palette().color(QPalette::Active, QPalette::ButtonText);
break;
case Status::Hover:
color = this->palette().color(QPalette::Active, QPalette::Highlight);

View File

@ -1,3 +1,23 @@
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: dunto; c-basic-offset: 4 -*-
*
* Copyright (C) 2019 Tianjin KYLIN Information Technology 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 BLUETOOTHSETTINGLABEL_H
#define BLUETOOTHSETTINGLABEL_H

View File

@ -1,3 +1,23 @@
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: dunto; c-basic-offset: 4 -*-
*
* Copyright (C) 2019 Tianjin KYLIN Information Technology 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.
*
*/
#include "kyfiledialog.h"
//被注释部分主要用于文件夹的选择,用于目录传输功能,暂不深度开发

View File

@ -1,3 +1,23 @@
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: dunto; c-basic-offset: 4 -*-
*
* Copyright (C) 2019 Tianjin KYLIN Information Technology 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 KYFILEDIALOG_H
#define KYFILEDIALOG_H

View File

@ -1,3 +1,23 @@
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: dunto; c-basic-offset: 4 -*-
*
* Copyright (C) 2019 Tianjin KYLIN Information Technology 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.
*
*/
#include "kyhline.h"
KyHLine::KyHLine(QWidget *parent) : QFrame(parent)
@ -15,11 +35,7 @@ KyHLine::KyHLine(QWidget *parent) : QFrame(parent)
void KyHLine::paintEvent(QPaintEvent * e)
{
QPainter p(this);
QColor color;
if(StyleSettings->get("style-name").toString() == "ukui-default"){
color = QColor(217, 217, 217);
} else
color = qApp->palette().color(QPalette::Active, QPalette::BrightText);
QColor color = qApp->palette().color(QPalette::BrightText);
color.setAlphaF(0.08);
p.save();
p.setBrush(color);

View File

@ -1,3 +1,23 @@
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: dunto; c-basic-offset: 4 -*-
*
* Copyright (C) 2019 Tianjin KYLIN Information Technology 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 KYHLINE_H
#define KYHLINE_H
#include <QFrame>

View File

@ -1,9 +1,35 @@
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: dunto; c-basic-offset: 4 -*-
*
* Copyright (C) 2019 Tianjin KYLIN Information Technology 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.
*
*/
#include "qdevitem.h"
QDevItem::QDevItem(QString address, QMap<QString, QVariant> devAttr, QWidget *parent):
QFrame(parent)
QDevItem::QDevItem(QString address, QStringList deviceinfo, bool connected, QWidget *parent):
QFrame(parent),
_Address(address),
_Connected(connected),
_Name(deviceinfo.at(0)),
_Battery(deviceinfo.at(2)),
_MType(deviceinfo.at(1))
{
initMap();
qDebug() << " get dev Battery : " << deviceinfo.at(0) << _Battery;
if(QGSettings::isSchemaInstalled("org.ukui.style")) {
StyleSettings = new QGSettings("org.ukui.style");
@ -25,7 +51,6 @@ QDevItem::QDevItem(QString address, QMap<QString, QVariant> devAttr, QWidget *pa
_clicked = false;
_pressFlag = false;
_MDev = devAttr;
InitMemberVariables();
}
@ -35,25 +60,40 @@ QDevItem::~QDevItem()
}
void QDevItem::initMap() {
typeMap = new QMap<int, QString>();
typeMap->insert(Type::Phone, QString("phone-symbolic"));
typeMap->insert(Type::Computer, QString("video-display-symbolic"));
typeMap->insert(Type::Headset, QString("audio-headphones-symbolic")); // typeMap->insert(Type::Headset, QString("audio-headset-symbolic"));
typeMap->insert(Type::Headphones, QString("audio-headphones-symbolic"));
typeMap->insert(Type::AudioVideo, QString("audio-speakers-symbolic"));
typeMap->insert(Type::Keyboard, QString("input-keyboard-symbolic"));
typeMap->insert(Type::Mouse, QString("input-mouse-symbolic"));
typeMap->insert(Type::Tablet, QString("tablet-symbolic"));
typeMap = new QMap<QString, QIcon>();
typeMap->insert(QString("phone"), QIcon::fromTheme("phone-symbolic"));
typeMap->insert(QString("computer"), QIcon::fromTheme("video-display-symbolic"));
typeMap->insert(QString("headset"), QIcon::fromTheme("audio-headset-symbolic"));
typeMap->insert(QString("headphones"), QIcon::fromTheme("audio-headphones-symbolic"));
typeMap->insert(QString("audiovideo"), QIcon::fromTheme("audio-speakers-symbolic"));
typeMap->insert(QString("keyboard"), QIcon::fromTheme("input-keyboard-symbolic"));
typeMap->insert(QString("mouse"), QIcon::fromTheme("input-mouse-symbolic"));
}
void QDevItem::attrChangedSlot(QMap<QString, QVariant> devAttr) {
if (_MDev.value("Connected").toBool() != devAttr.value("Connected").toBool()) {
void QDevItem::SendMessage(bool connected)
{
QString text;
if (connected) {
text = QString(tr("The connection with the Bluetooth device “%1” is successful!").arg(_Name));
} else {
text = QString(tr("Bluetooth device “%1” disconnected!").arg(_Name));
}
Config::SendNotifyMessage(text);
}
void QDevItem::connectedChangedSlot(bool connected) {
qDebug() << Q_FUNC_INFO << connected;
if (_clicked) {
_iconTimer->stop();
_clicked = false;
}
_MDev = devAttr;
update();
if (_Connected == connected)
return;
_Connected = connected;
qDebug() << Q_FUNC_INFO << __LINE__;
update();
SendMessage(connected);
}
void QDevItem::InitMemberVariables()
@ -116,9 +156,6 @@ void QDevItem::mousePressEvent(QMouseEvent *event)
void QDevItem::mouseReleaseEvent(QMouseEvent *event)
{
qDebug() << Q_FUNC_INFO << __LINE__;
if (_MStatus != Status::Click)
return;
if (event->button() == Qt::LeftButton && _pressFlag) {
if (_leaved)
_MStatus = Status::Nomal;
@ -163,31 +200,32 @@ QColor QDevItem::getPainterBrushColor()
QColor color;
switch (_MStatus) {
case Status::Nomal:
if(StyleSettings->get("style-name").toString() != "ukui-light"){
if(StyleSettings->get("style-name").toString() == "ukui-light" || StyleSettings->get("style-name").toString() == "ukui-default")
color = QColor(255,255,255,0);
else {
color = QColor(QPalette::Base);
color.setAlpha(0);
}
else
color = QColor(255,255,255,0);
break;
case Status::Hover:
if(StyleSettings->get("style-name").toString() != "ukui-light")
color = QColor(55, 55, 59, tran);
else
if(StyleSettings->get("style-name").toString() != "ukui-dark")
color = QColor(217,217,217,tran);
else
color = QColor(55, 55, 59, tran);
break;
case Status::Click:
if(StyleSettings->get("style-name").toString() != "ukui-light")
color = QColor(102, 102, 102, tran);
else
if(StyleSettings->get("style-name").toString() != "ukui-dark")
color = QColor(209, 209, 209,tran);
else
color = QColor(102, 102, 102, tran);
break;
default:
if(StyleSettings->get("style-name").toString() != "ukui-light"){
if(StyleSettings->get("style-name").toString() != "ukui-dark")
color = QColor(223,223,223,tran);
else{
color = QColor(QPalette::Base);
color.setAlpha(0);
} else
color = QColor(223,223,223,tran);
}
break;
}
@ -202,22 +240,22 @@ QColor QDevItem::getPainterBrushColor()
QColor QDevItem::getDevStatusColor()
{
QColor color;
if (_MDev.value("Connected").toBool()) {
if (_Connected) {
if (_MStatus == Status::Click)
color = this->palette().color(QPalette::Active, QPalette::Highlight).darker(105);
else
color = this->palette().color(QPalette::Active, QPalette::Highlight);
} else {
if(StyleSettings->get("style-name").toString() != "ukui-light") {
if (_MStatus == Status::Click)
color = QColor("#444444");
else
color = QColor("#666666");
} else {
if(StyleSettings->get("style-name").toString() != "ukui-dark") {
if (_MStatus == Status::Click)
color = QColor("#E0E0E0");
else
color = QColor("#DFDFDF");
} else {
if (_MStatus == Status::Click)
color = QColor("#444444");
else
color = QColor("#666666");
}
color.setAlpha(tran);
}
@ -236,8 +274,8 @@ QPixmap QDevItem::getDevTypeIcon()
if (_clicked) {
icon = QIcon::fromTheme("ukui-loading-" + QString::number(iconFlag) + "-symbolic");
} else {
if (_MDev.contains("Type") && typeMap->contains(_MDev.value("Type").toInt()))
icon = QIcon::fromTheme(typeMap->value(_MDev.value("Type").toInt()));
if (typeMap->keys().contains(_MType))
icon = typeMap->value(_MType);
else
icon = QIcon::fromTheme("bluetooth-symbolic");
}
@ -271,15 +309,19 @@ void QDevItem::DrawStatusIcon(QPainter &painter)
painter.drawEllipse(16,7,36,36);
painter.setRenderHint(QPainter::SmoothPixmapTransform);
if(StyleSettings->get("style-name").toString() != "ukui-light") {
painter.setPen(QColor(Qt::white));
devpixmap = Config::loadSvg(getDevTypeIcon(), Config::PixmapColor::WHITE);
} else {
if(StyleSettings->get("style-name").toString() != "ukui-dark") {
painter.setPen(QColor(Qt::black));
if (_MDev.value("Connected").toBool())
if (_Connected)
devpixmap = Config::loadSvg(getDevTypeIcon(), Config::PixmapColor::WHITE);
else
devpixmap = getDevTypeIcon();
} else {
if (StyleSettings->get("icon-theme-name").toString() == "ukui-icon-theme-classical")
devpixmap = getDevTypeIcon();
else {
painter.setPen(QColor(Qt::white));
devpixmap = Config::loadSvg(getDevTypeIcon(), Config::PixmapColor::WHITE);
}
}
style()->drawItemPixmap(&painter, QRect(25, 16, 18, 18), Qt::AlignCenter, devpixmap);
@ -294,29 +336,24 @@ void QDevItem::DrawStatusIcon(QPainter &painter)
void QDevItem::DrawText(QPainter &painter)
{
painter.save();
if(StyleSettings->get("style-name").toString() != "ukui-light")
painter.setPen(QColor(Qt::white));
else
if(StyleSettings->get("style-name").toString() != "ukui-dark")
painter.setPen(QColor(Qt::black));
else
painter.setPen(QColor(Qt::white));
QString newName;
QString nName;
double fontSize = StyleSettings->get("system-font-size").toDouble() - 11;
QFont ft;
ft.setPixelSize(18 + fontSize);
QFontMetrics fontMetrics(ft);
QString name;
name = _MDev.value("Name").toString();
if (_MDev.contains("ShowName"))
if (_MDev.value("ShowName").toString() != QString(""))
name = _MDev.value("ShowName").toString();
newName = fontMetrics.elidedText(name, Qt::ElideRight, 280);
if (name.size() != newName.size())
this->setToolTip(name);
nName = fontMetrics.elidedText(_Name, Qt::ElideRight, 280);
if (_Name.size() != nName.size())
this->setToolTip(_Name);
if (fontSize >= 14)
painter.drawText(62,8,280,30,Qt::AlignLeft|Qt::AlignVCenter, newName);
painter.drawText(62,8,280,30,Qt::AlignLeft|Qt::AlignVCenter, nName);
else
painter.drawText(62,12,280,28,Qt::AlignLeft|Qt::AlignVCenter, newName);
painter.drawText(62,12,280,28,Qt::AlignLeft|Qt::AlignVCenter, nName);
painter.restore();
}
@ -328,21 +365,21 @@ void QDevItem::DrawText(QPainter &painter)
*************************************************/
void QDevItem::DrawBattery(QPainter &painter)
{
int battery = _MDev.value("Battery").toInt();
if (battery == -1 || !_MDev.value("Connected").toBool())
int battery = _Battery.toInt();
if (battery == -1 || !_Connected)
return;
painter.save();
QString batteryIcon = QString("battery-level-") + QString::number(battery / 10 * 10) + QString("-symbolic");
QString batteryString = QString::number(battery) + QString("%");
QString batteryString = _Battery + QString("%");
QPixmap batteryPixmap;
if(StyleSettings->get("style-name").toString() != "ukui-light") {
painter.setPen(QColor(Qt::white));
batteryPixmap = Config::loadSvg(QIcon::fromTheme(batteryIcon).pixmap(20,20), Config::PixmapColor::WHITE);
} else {
if(StyleSettings->get("style-name").toString() != "ukui-dark") {
painter.setPen(QColor(Qt::black));
batteryPixmap = Config::loadSvg(QIcon::fromTheme(batteryIcon).pixmap(20,20), Config::PixmapColor::BLACK);
} else {
painter.setPen(QColor(Qt::white));
batteryPixmap = Config::loadSvg(QIcon::fromTheme(batteryIcon).pixmap(20,20), Config::PixmapColor::WHITE);
}
if (StyleSettings->get("system-font-size").toDouble() >= 14)
@ -360,7 +397,7 @@ void QDevItem::DrawBattery(QPainter &painter)
*************************************************/
void QDevItem::MouseClickedFunc()
{
emit devConnect(!_MDev.value("Connected").toBool());
emit devConnect(!_Connected);
startIconTimer();
}
@ -383,5 +420,5 @@ void QDevItem::startIconTimer() {
}
bool QDevItem::isConnected() {
return _MDev.value("Connected").toBool();
return _Connected;
}

View File

@ -1,3 +1,23 @@
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: dunto; c-basic-offset: 4 -*-
*
* Copyright (C) 2019 Tianjin KYLIN Information Technology 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 QDEVITEM_H
#define QDEVITEM_H
@ -30,7 +50,7 @@ public:
int FontTable[6] = {32, 30, 26, 24, 23, 22};
QDevItem(QString address, QMap<QString, QVariant> devAttr, QWidget *parent = nullptr);
QDevItem(QString address, QStringList deviceinfo, bool connected, QWidget *parent = nullptr);
~QDevItem();
void setFocusStyle(bool val);
void pressEnterCallback();
@ -50,7 +70,7 @@ protected:
void paintEvent(QPaintEvent *);
private:
QMap<int, QString> *typeMap = nullptr;
QMap<QString, QIcon> *typeMap = nullptr;
QColor getPainterBrushColor();
QColor getDevStatusColor();
QPixmap getDevTypeIcon();
@ -61,23 +81,28 @@ private:
void DrawText(QPainter &);
void MouseClickedFunc();
void DevConnectFunc();
void SendMessage(bool connected);
Status _MStatus;
double tran =1;
bool _clicked;
bool _pressFlag;
int iconFlag = 7;
bool _Connected;
bool _leaved = false;
bool _focused = false;
bool _clickEnabled = true;
QMap<QString, QVariant> _MDev;
QTimer *_iconTimer = nullptr;
BluezQt::DevicePtr _MDev = nullptr;
QString _Address;
QString _Name;
QString _Battery;
QGSettings *StyleSettings = nullptr;
QGSettings *transparency_gsettings = nullptr;
QString _MType;
public slots:
void attrChangedSlot(QMap<QString, QVariant> devAttr);
void connectedChangedSlot(bool connected);
};
#endif // QDEVITEM_H

View File

@ -1,6 +1,26 @@
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: dunto; c-basic-offset: 4 -*-
*
* Copyright (C) 2019 Tianjin KYLIN Information Technology 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.
*
*/
#include "config.h"
int envPC = 0;
Environment envPC = Environment::NOMAL;
//全局变量,判定机型架构
Config::Config(QObject *parent, QString name)
:QObject(parent)
@ -16,22 +36,20 @@ Config::~Config()
delete gsetting;
}
void Config::SendNotifyMessage(QString title, QString message, QString soundeffects)
void Config::SendNotifyMessage(QString message)
{
QDBusInterface iface("org.freedesktop.Notifications",
"/org/freedesktop/Notifications",
"org.freedesktop.Notifications",
QDBusConnection::sessionBus());
QList<QVariant> args;
QMap<QString, QVariant> vmap;
vmap.insert("sound-name", QVariant(soundeffects));
args<<tr("Bluetooth")
<<((unsigned int) 0)
<<"bluetooth"
<<title //显示的是什么类型的信息
<<tr("Bluetooth Message") //显示的是什么类型的信息
<<message //显示的具体信息
<<QStringList()
<<vmap
<<QVariantMap()
<<(int)-1;
QDBusMessage msg = iface.callWithArgumentList(QDBus::AutoDetect,"Notify",args);
qDebug() << Q_FUNC_INFO << msg.errorMessage();
@ -116,265 +134,12 @@ void Config::setKdkGeometry(QWindow *windowHandle, int width, int height, bool c
}
}
void Config::AppManagerToOpenBluetoothSettings()
{
qInfo () << Q_FUNC_INFO << "" << __LINE__;
QDBusMessage m = QDBusMessage::createMethodCall("com.kylin.AppManager",
"/com/kylin/AppManager",
"com.kylin.AppManager",
"LaunchAppWithArguments");
m<< QString("ukui-control-center.desktop") << QStringList{"-m","Bluetooth"};
QDBusConnection::sessionBus().call(m, QDBus::NoBlock);
}
void Config::CommandToOpenBluetoothSettings()
{
qInfo () << Q_FUNC_INFO << "" << __LINE__;
QProcess *process = new QProcess();
QString cmd = "ukui-control-center";
QStringList arg;
arg.clear();
arg << "-m";
arg << "Bluetooth";
qDebug() << Q_FUNC_INFO << arg;
process->startDetached(cmd,arg);
}
void Config::OpenBluetoothSettings()
{
if (Environment::MAVIS == envPC){
QDBusInterface *m_statusSessionDbus = new QDBusInterface("com.kylin.statusmanager.interface",
"/",
"com.kylin.statusmanager.interface",
QDBusConnection::sessionBus());
if (m_statusSessionDbus->isValid())
{
qInfo() << Q_FUNC_INFO << "is_tabletmode" << __LINE__;
QDBusReply<bool> is_tabletmode = m_statusSessionDbus->call("get_current_tabletmode");
if (is_tabletmode)
AppManagerToOpenBluetoothSettings();
else
CommandToOpenBluetoothSettings();
}
else
CommandToOpenBluetoothSettings();
}
else
CommandToOpenBluetoothSettings();
QProcess *process = new QProcess();
QString cmd = "ukui-control-center";
QStringList arg;
arg.clear();
arg << "-m";
arg << "Bluetooth";
qDebug() << Q_FUNC_INFO << arg;
process->startDetached(cmd,arg);
}
int Config::devConnect(QString address) {
QDBusMessage dbusMsg = CREATE_SYSTEM_METHOD_CALL("devConnect");
dbusMsg << address;
QDBusMessage response = QDBusConnection::systemBus().call(dbusMsg, QDBus::NoBlock);
if (response.type() == QDBusMessage::ReplyMessage)
{
int res = response.arguments().takeFirst().toInt();
switch (res) {
case 0:
DEBUG_PRINT("Connect Succeed");
break;
case -1:
DEBUG_PRINT("Address Error");
break;
case -2:
DEBUG_PRINT("Devices doesn't Exist");
break;
case -3:
DEBUG_PRINT("Adapter doesn't Exist");
break;
case -4:
DEBUG_PRINT("Pair Failed");
break;
case -5:
DEBUG_PRINT("Paring");
break;
}
return res;
} else {
DEBUG_PRINT("Method Call Error");
return -6;
}
}
int Config::devDisconnect(QString address) {
QDBusMessage dbusMsg = CREATE_SYSTEM_METHOD_CALL("devDisconnect");
dbusMsg << address;
QDBusMessage response = QDBusConnection::systemBus().call(dbusMsg, QDBus::NoBlock);
if (response.type() == QDBusMessage::ReplyMessage)
{
int res = response.arguments().takeFirst().toInt();
switch (res) {
case 0:
DEBUG_PRINT("Disconnect Succeed");
break;
case -1:
DEBUG_PRINT("Address Error");
break;
case -2:
DEBUG_PRINT("Devices doesn't Exist");
break;
}
return res;
} else {
DEBUG_PRINT("Method Call Error");
return -3;
}
}
int Config::devRemove(QString address, QString adapter) {
QDBusMessage dbusMsg = CREATE_SYSTEM_METHOD_CALL("devRemove");
dbusMsg << address << adapter;
QDBusMessage response = QDBusConnection::systemBus().call(dbusMsg, QDBus::NoBlock);
if (response.type() == QDBusMessage::ReplyMessage)
{
int res = response.arguments().takeFirst().toInt();
switch (res) {
case 0:
DEBUG_PRINT("Remove Succeed");
break;
case -1:
DEBUG_PRINT("Address Error");
break;
case -2:
DEBUG_PRINT("Devices doesn't Exist");
break;
}
return res;
} else {
DEBUG_PRINT("Method Call Error");
return -3;
}
}
int Config::activeConnectionReply(QString address, bool accept) {
QDBusMessage dbusMsg = CREATE_SYSTEM_METHOD_CALL("activeConnectionReply");
dbusMsg << address << accept;
QDBusMessage response = QDBusConnection::systemBus().call(dbusMsg, QDBus::NoBlock);
if (response.type() == QDBusMessage::ReplyMessage)
{
int res = response.arguments().takeFirst().toInt();
switch (res) {
case 0:
DEBUG_PRINT("Remove Succeed");
break;
case -1:
DEBUG_PRINT("Address Error");
break;
case -2:
DEBUG_PRINT("Devices doesn't Exist");
break;
}
return res;
} else {
DEBUG_PRINT("Method Call Error");
return -3;
}
}
int Config::pairFuncReply(QString address, bool accept) {
QDBusMessage dbusMsg = CREATE_SYSTEM_METHOD_CALL("pairFuncReply");
dbusMsg << address << accept;
QDBusMessage response = QDBusConnection::systemBus().call(dbusMsg, QDBus::NoBlock);
if (response.type() == QDBusMessage::ReplyMessage)
{
int res = response.arguments().takeFirst().toInt();
switch (res) {
case 0:
DEBUG_PRINT("Remove Succeed");
break;
case -1:
DEBUG_PRINT("Address Error");
break;
case -2:
DEBUG_PRINT("Devices doesn't Exist");
break;
}
return res;
} else {
DEBUG_PRINT("Method Call Error");
return -3;
}
}
int Config::replyFileReceiving(QString address, bool accept, QString savePathdir, QString user) {
QMap<QString, QVariant> sendMsg;
sendMsg.insert("dev", QVariant(address));
sendMsg.insert("receive", QVariant(accept));
sendMsg.insert("savePathdir", QVariant(savePathdir));
sendMsg.insert("user", user);
QDBusMessage dbusMsg = CREATE_SYSTEM_METHOD_CALL("replyFileReceiving");
dbusMsg << sendMsg;
QDBusMessage response = QDBusConnection::systemBus().call(dbusMsg, QDBus::NoBlock);
if (response.type() == QDBusMessage::ReplyMessage)
{
int res = response.arguments().takeFirst().toInt();
switch (res) {
case 0:
DEBUG_PRINT("Remove Succeed");
break;
case -1:
DEBUG_PRINT("Address Error");
break;
case -2:
DEBUG_PRINT("Devices doesn't Exist");
break;
}
return res;
} else {
DEBUG_PRINT("Method Call Error");
return -3;
}
}
bool Config::setDefaultAdapterAttr(QMap<QString, QVariant> adpAttr) {
qDebug() << adpAttr;
QDBusMessage dbusMsg = CREATE_SYSTEM_METHOD_CALL("setDefaultAdapterAttr");
dbusMsg << adpAttr;
QDBusMessage response = QDBusConnection::systemBus().call(dbusMsg);
if (response.type() == QDBusMessage::ReplyMessage)
{
return response.arguments().takeFirst().toBool();
} else
return false;
}
void Config::soundComplete() {
QDBusMessage m = QDBusMessage::createMethodCall("org.ukui.sound.theme.player",
"/org/ukui/sound/theme/player",
"org.ukui.sound.theme.player",
"playAlertSound");
m<< QString("complete");
QDBusConnection::sessionBus().call(m, QDBus::NoBlock);
}
void Config::soundWarning() {
QDBusMessage m = QDBusMessage::createMethodCall("org.ukui.sound.theme.player",
"/org/ukui/sound/theme/player",
"org.ukui.sound.theme.player",
"playAlertSound");
m<< QString("dialog-error");
QDBusConnection::sessionBus().call(m, QDBus::NoBlock);
qDebug() << Q_FUNC_INFO;
arg << "--bluetooth";
process->start(cmd,arg);
}

View File

@ -1,7 +1,26 @@
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: dunto; c-basic-offset: 4 -*-
*
* Copyright (C) 2019 Tianjin KYLIN Information Technology 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 CONFIG_H
#define CONFIG_H
#include <QDir>
#include <QGSettings>
#include <QString>
#include <QByteArray>
@ -10,97 +29,12 @@
#include <QProcess>
#include <QStyle>
#include <QPixmap>
#include <KWindowSystem>
#include <QtDBus/QDBusConnection>
#include <QtDBus/QDBusAbstractAdaptor>
#include <QtDBus/QDBusInterface>
#include <QtDBus/QDBusReply>
#include <QtDBus/QDBusConnectionInterface>
#include "windowmanager/windowmanager.h"
#define INFO_PRINT(info) qInfo() << Q_FUNC_INFO << info << "in line :" << __LINE__
#define DEBUG_PRINT(info) qInfo() << Q_FUNC_INFO << info << "in line :" << __LINE__
#define MEDIA_BATTERY_SERVICE "org.ukui.media"
#define MEDIA_BATTERY_PATH "/org/ukui/media/bluetooth"
#define MEDIA_BATTERY_INTERFACE MEDIA_BATTERY_SERVICE
#define SYSTEMD_SERVICE "com.ukui.bluetooth"
#define SYSTEMD_PATH "/com/ukui/bluetooth"
#define SYSTEMD_INTERFACE SYSTEMD_SERVICE
#define SESSION_SERVICE "com.ukui.bluetooth"
#define SESSION_PATH "/com/ukui/bluetooth"
#define SESSION_INTERFACE SESSION_SERVICE
#define SYSTEM_ACTIVE_USER_DBUS "org.ukui.test"
#define SYSTEM_ACTIVE_USER_PATH "/com/ukui/test"
#define SYSTEM_ACTIVE_USER_INTERFACE "com.ukui.test"
//org.freedesktop.DBus
#define SESSION_DBUS_FREEDESKTOP_SERVICE "org.freedesktop.DBus"
#define SESSION_DBUS_FREEDESKTOP_PATH "/org/freedesktop/DBus"
#define SESSION_DBUS_FREEDESKTOP_INTERFACE "org.freedesktop.DBus"
//音视频session dbus
#define SESSION_DBUS_NAME_STR_FIELD "org.mpris.MediaPlayer2"
#define SESSION_DBUS_PLAYER_PATH "/org/mpris/MediaPlayer2"
#define SESSION_DBUS_PLAYER_INTERFACE "org.mpris.MediaPlayer2.Player"
#define GSETTING_SCHEMA_UKUIBLUETOOH "org.ukui.bluetooth"
#define GSETTING_SCHEMA_UKCC "org.ukui.control-center.plugins"
#define GSETTING_PACH_UKCC "/org/ukui/control-center/plugins/Bluetooth/"
#define SESSION_DBUS_CONNECT QDBusConnection::sessionBus().connect
#define SYSTEM_DBUS_CONNECT QDBusConnection::systemBus().connect
#define CONNECT_DBUS_SIGNAL(signame, func) \
SESSION_DBUS_CONNECT(SESSION_SERVICE, \
SESSION_PATH, \
SESSION_INTERFACE, \
signame, \
this,\
SLOT(func))
#define TRANSFER_DBUS_SIGNAL(signame, func) \
SESSION_DBUS_CONNECT(SESSION_SERVICE, \
SESSION_PATH, \
SESSION_INTERFACE, \
signame, \
this,\
SIGNAL(func))
#define CREATE_METHOD_CALL(funcName) \
QDBusMessage::createMethodCall(SESSION_SERVICE, \
SESSION_PATH, \
SESSION_INTERFACE, \
funcName)
#define CONNECT_SYSTEM_DBUS_SIGNAL(signame, func) \
SYSTEM_DBUS_CONNECT(SYSTEMD_SERVICE, \
SYSTEMD_PATH, \
SYSTEMD_INTERFACE, \
signame, \
this,\
SLOT(func))
#define TRANSFER_SYSTEM_DBUS_SIGNAL(signame, func) \
SYSTEM_DBUS_CONNECT(SYSTEMD_SERVICE, \
SYSTEMD_PATH, \
SYSTEMD_INTERFACE, \
signame, \
this,\
SIGNAL(func))
#define CREATE_SYSTEM_METHOD_CALL(funcName) \
QDBusMessage::createMethodCall(SYSTEMD_SERVICE, \
SYSTEMD_PATH, \
SYSTEMD_INTERFACE, \
funcName)
#define CALL_METHOD(dbusmsg) QDBusConnection::sessionBus().call(dbusmsg);
#define SYSTEM_CALL_METHOD(dbusmsg) QDBusConnection::systemBus().call(dbusmsg);
enum Environment
{
NOMAL = 0,
@ -108,136 +42,7 @@ enum Environment
LAIKA,
MAVIS
};
extern int envPC;
typedef enum Status {
/** Indicates that the transfer is queued. */
Queued,
/** Indicates that the transfer is active. */
Active,
/** Indicates that the transfer is suspended. */
Suspended,
/** Indicates that the transfer have completed successfully. */
Complete,
/** Indicates that the transfer have failed with error. */
Error,
/** Indicates that the transfer status is unknown. */
Unknown,
/** Indicates that the transfer status is static. */
Static = 0xff
} SendStatus;
enum Type {
/** The device is a phone. */
Phone = 0,
/** The device is a modem. */
Modem,
/** The device is a computer. */
Computer,
/** The device is a network. */
Network,
/** The device is a headset. */
Headset,
/** The device is a headphones. */
Headphones,
/** The device is an uncategorized audio video device. */
AudioVideo,
/** The device is a keyboard. */
Keyboard,
/** The device is a mouse. */
Mouse,
/** The device is a joypad. */
Joypad,
/** The device is a graphics tablet (input device). */
Tablet,
/** The deivce is an uncategorized peripheral device. */
Peripheral,
/** The device is a camera. */
Camera,
/** The device is a printer. */
Printer,
/** The device is an uncategorized imaging device. */
Imaging,
/** The device is a wearable device. */
Wearable,
/** The device is a toy. */
Toy,
/** The device is a health device. */
Health,
/** The device is not of any of the known types. */
Uncategorized
};
enum ConnectionErrMsg
{
ERR_BREDR_CONN_SUC,
ERR_BREDR_CONN_ALREADY_CONNECTED = 1,
ERR_BREDR_CONN_PAGE_TIMEOUT,
ERR_BREDR_CONN_PROFILE_UNAVAILABLE,
ERR_BREDR_CONN_SDP_SEARCH,
ERR_BREDR_CONN_CREATE_SOCKET,
ERR_BREDR_CONN_INVALID_ARGUMENTS,
ERR_BREDR_CONN_ADAPTER_NOT_POWERED,
ERR_BREDR_CONN_NOT_SUPPORTED,
ERR_BREDR_CONN_BAD_SOCKET,
ERR_BREDR_CONN_MEMORY_ALLOC,
ERR_BREDR_CONN_BUSY,
ERR_BREDR_CONN_CNCR_CONNECT_LIMIT,
ERR_BREDR_CONN_TIMEOUT,
ERR_BREDR_CONN_REFUSED,
ERR_BREDR_CONN_ABORT_BY_REMOTE,
ERR_BREDR_CONN_ABORT_BY_LOCAL,
ERR_BREDR_CONN_LMP_PROTO_ERROR,
ERR_BREDR_CONN_CANCELED,
ERR_BREDR_CONN_UNKNOWN,
////////////////////////////////////////////
ERR_LE_CONN_INVALID_ARGUMENTS = 20,
ERR_LE_CONN_ADAPTER_NOT_POWERED,
ERR_LE_CONN_NOT_SUPPORTED,
ERR_LE_CONN_ALREADY_CONNECTED,
ERR_LE_CONN_BAD_SOCKET,
ERR_LE_CONN_MEMORY_ALLOC,
ERR_LE_CONN_BUSY,
ERR_LE_CONN_REFUSED,
ERR_LE_CONN_CREATE_SOCKET,
ERR_LE_CONN_TIMEOUT,
ERR_LE_CONN_SYNC_CONNECT_LIMIT,
ERR_LE_CONN_ABORT_BY_REMOTE,
ERR_LE_CONN_ABORT_BY_LOCAL,
ERR_LE_CONN_LL_PROTO_ERROR,
ERR_LE_CONN_GATT_BROWSE,
ERR_LE_CONN_UNKNOWN,
////////////////////////////////////////////////////
ERR_BREDR_Invalid_Arguments = 36,
ERR_BREDR_Operation_Progress,
ERR_BREDR_Already_Exists,
ERR_BREDR_Operation_Not_Supported,
ERR_BREDR_Already_Connected,
ERR_BREDR_Operation_Not_Available,
ERR_BREDR_Does_Not_Exist,
ERR_BREDR_Does_Not_Connected,
ERR_BREDR_Does_In_Progress,
ERR_BREDR_Operation_Not_Authorized,
ERR_BREDR_No_Such_Adapter,
ERR_BREDR_Agent_Not_Available,
ERR_BREDR_Resource_Not_Ready,
/************上面错误码为bluez返回错误码****************/
ERR_BREDR_Bluezqt_DidNot_ReceiveReply,
/////////////////////////////////////////////////
ERR_BREDR_INTERNAL_NO_Default_Adapter,
ERR_BREDR_INTERNAL_Operation_Progress,
ERR_BREDR_INTERNAL_Already_Connected,
ERR_BREDR_INTERNAL_Dev_Not_Exist,
ERR_BREDR_UNKNOWN_Other,
};
extern Environment envPC;
class Config : public QObject
{
@ -252,23 +57,11 @@ public:
};
Q_ENUM(PixmapColor)
Config(QObject *parent = nullptr,QString name = GSETTING_SCHEMA_UKUIBLUETOOH);
Config(QObject *parent = nullptr,QString name = "org.ukui.bluetooth");
~Config();
static int pairFuncReply(QString, bool);
static int replyFileReceiving(QString, bool, QString, QString);
static int activeConnectionReply(QString, bool);
static int devConnect(QString);
static int devDisconnect(QString);
static int devRemove(QString, QString);
static bool setDefaultAdapterAttr(QMap<QString, QVariant> adpAttr);
static void soundWarning();
static void soundComplete();
static void SendNotifyMessage(QString title, QString, QString soundeffects);
static void SendNotifyMessage(QString);
static void OpenBluetoothSettings();
static void CommandToOpenBluetoothSettings();
static void AppManagerToOpenBluetoothSettings();
static const QPixmap loadSvg(const QPixmap &source, const PixmapColor &color);
static void setKdkGeometry(QWindow *windowHandle, int width, int height, bool center);

Some files were not shown because too many files have changed in this diff Show More