commit 776de990753d00796fe28aad70009793f99dbeb2 Author: 谢炜 Date: Wed Jun 8 13:42:09 2022 +0800 Import Upstream version 3.1.4.0.0k0 diff --git a/CJsonObject.cpp b/CJsonObject.cpp new file mode 100644 index 0000000..40ce708 --- /dev/null +++ b/CJsonObject.cpp @@ -0,0 +1,4343 @@ +/* +* Copyright (C) 2020, 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 3, or (at your option) +* any later version. +* +* This program is distributed in the hope that it will be useful, +* but WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +* GNU General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, see ToString()); + } +} + +CJsonObject::CJsonObject(const CJsonObject& oJsonObject) + : m_pJsonData(NULL), m_pExternJsonDataRef(NULL), m_pKeyTravers(NULL) +{ + m_array_iter = m_mapJsonArrayRef.end(); + m_object_iter = m_mapJsonObjectRef.end(); + Parse(oJsonObject.ToString()); +} + +#if __cplusplus >= 201101L +CJsonObject::CJsonObject(CJsonObject&& oJsonObject) + : m_pJsonData(oJsonObject.m_pJsonData), + m_pExternJsonDataRef(oJsonObject.m_pExternJsonDataRef), + m_pKeyTravers(oJsonObject.m_pKeyTravers), + mc_pError(oJsonObject.mc_pError) +{ + oJsonObject.m_pJsonData = NULL; + oJsonObject.m_pExternJsonDataRef = NULL; + oJsonObject.m_pKeyTravers = NULL; + oJsonObject.mc_pError = NULL; + m_strErrMsg = std::move(oJsonObject.m_strErrMsg); + m_mapJsonArrayRef = std::move(oJsonObject.m_mapJsonArrayRef); + m_mapJsonObjectRef = std::move(oJsonObject.m_mapJsonObjectRef); + m_array_iter = m_mapJsonArrayRef.end(); + m_object_iter = m_mapJsonObjectRef.end(); +} +#endif + +CJsonObject::~CJsonObject() +{ + Clear(); +} + +CJsonObject& CJsonObject::operator=(const CJsonObject& oJsonObject) +{ + Parse(oJsonObject.ToString().c_str()); + return(*this); +} + +#if __cplusplus >= 201101L +CJsonObject& CJsonObject::operator=(CJsonObject&& oJsonObject) +{ + m_pJsonData = oJsonObject.m_pJsonData; + oJsonObject.m_pJsonData = NULL; + m_pExternJsonDataRef = oJsonObject.m_pExternJsonDataRef; + oJsonObject.m_pExternJsonDataRef = NULL; + m_pKeyTravers = oJsonObject.m_pKeyTravers; + oJsonObject.m_pKeyTravers = NULL; + mc_pError = oJsonObject.mc_pError; + oJsonObject.mc_pError = NULL; + m_strErrMsg = std::move(oJsonObject.m_strErrMsg); + m_mapJsonArrayRef = std::move(oJsonObject.m_mapJsonArrayRef); + m_mapJsonObjectRef = std::move(oJsonObject.m_mapJsonObjectRef); + m_array_iter = m_mapJsonArrayRef.end(); + m_object_iter = m_mapJsonObjectRef.end(); + return(*this); +} +#endif + +bool CJsonObject::operator==(const CJsonObject& oJsonObject) const +{ + return(this->ToString() == oJsonObject.ToString()); +} + +bool CJsonObject::AddEmptySubObject(const std::string& strKey) +{ + cJSON* pFocusData = NULL; + if (m_pJsonData != NULL) + { + pFocusData = m_pJsonData; + } + else if (m_pExternJsonDataRef != NULL) + { + pFocusData = m_pExternJsonDataRef; + } + else + { + m_pJsonData = cJSON_CreateObject(); + m_pKeyTravers = m_pJsonData; + pFocusData = m_pJsonData; + } + + if (pFocusData == NULL) + { + m_strErrMsg = "json data is null!"; + return(false); + } + if (pFocusData->type != cJSON_Object) + { + m_strErrMsg = "not a json object! json array?"; + return(false); + } + if (cJSON_GetObjectItem(pFocusData, strKey.c_str()) != NULL) + { + m_strErrMsg = "key exists!"; + return(false); + } + cJSON* pJsonStruct = cJSON_CreateObject(); + if (pJsonStruct == NULL) + { + m_strErrMsg = std::string("create sub empty object error!"); + return(false); + } + cJSON_AddItemToObject(pFocusData, strKey.c_str(), pJsonStruct); + m_pKeyTravers = pFocusData; + return(true); +} + +bool CJsonObject::AddEmptySubArray(const std::string& strKey) +{ + cJSON* pFocusData = NULL; + if (m_pJsonData != NULL) + { + pFocusData = m_pJsonData; + } + else if (m_pExternJsonDataRef != NULL) + { + pFocusData = m_pExternJsonDataRef; + } + else + { + m_pJsonData = cJSON_CreateObject(); + m_pKeyTravers = m_pJsonData; + pFocusData = m_pJsonData; + } + + if (pFocusData == NULL) + { + m_strErrMsg = "json data is null!"; + return(false); + } + if (pFocusData->type != cJSON_Object) + { + m_strErrMsg = "not a json object! json array?"; + return(false); + } + if (cJSON_GetObjectItem(pFocusData, strKey.c_str()) != NULL) + { + m_strErrMsg = "key exists!"; + return(false); + } + cJSON* pJsonStruct = cJSON_CreateArray(); + if (pJsonStruct == NULL) + { + m_strErrMsg = std::string("create sub empty array error!"); + return(false); + } + cJSON_AddItemToObject(pFocusData, strKey.c_str(), pJsonStruct); + m_pKeyTravers = pFocusData; + return(true); +} + +bool CJsonObject::GetKey(std::string& strKey) +{ + if (IsArray()) + { + return(false); + } + if (m_pKeyTravers == NULL) + { + if (m_pJsonData != NULL) + { + m_pKeyTravers = m_pJsonData; + } + else if (m_pExternJsonDataRef != NULL) + { + m_pKeyTravers = m_pExternJsonDataRef; + } + return(false); + } + else if (m_pKeyTravers == m_pJsonData || m_pKeyTravers == m_pExternJsonDataRef) + { + cJSON *c = m_pKeyTravers->child; + if (c) + { + strKey = c->string; + m_pKeyTravers = c->next; + return(true); + } + else + { + return(false); + } + } + else + { + strKey = m_pKeyTravers->string; + m_pKeyTravers = m_pKeyTravers->next; + return(true); + } +} + +void CJsonObject::ResetTraversing() +{ + if (m_pJsonData != NULL) + { + m_pKeyTravers = m_pJsonData; + } + else + { + m_pKeyTravers = m_pExternJsonDataRef; + } +} + +CJsonObject& CJsonObject::operator[](const std::string& strKey) +{ +#if __cplusplus < 201101L + std::map::iterator iter = m_mapJsonObjectRef.find(strKey); +#else + auto iter = m_mapJsonObjectRef.find(strKey); +#endif + if (iter == m_mapJsonObjectRef.end()) + { + cJSON* pJsonStruct = NULL; + if (m_pJsonData != NULL) + { + if (m_pJsonData->type == cJSON_Object) + { + pJsonStruct = cJSON_GetObjectItem(m_pJsonData, strKey.c_str()); + } + } + else if (m_pExternJsonDataRef != NULL) + { + if (m_pExternJsonDataRef->type == cJSON_Object) + { + pJsonStruct = cJSON_GetObjectItem(m_pExternJsonDataRef, strKey.c_str()); + } + } + if (pJsonStruct == NULL) + { + CJsonObject* pJsonObject = new CJsonObject(); + m_mapJsonObjectRef.insert(std::pair(strKey, pJsonObject)); + return(*pJsonObject); + } + else + { + CJsonObject* pJsonObject = new CJsonObject(pJsonStruct); + m_mapJsonObjectRef.insert(std::pair(strKey, pJsonObject)); + return(*pJsonObject); + } + } + else + { + return(*(iter->second)); + } +} + +CJsonObject& CJsonObject::operator[](unsigned int uiWhich) +{ +#if __cplusplus < 201101L + std::map::iterator iter = m_mapJsonArrayRef.find(uiWhich); +#else + auto iter = m_mapJsonArrayRef.find(uiWhich); +#endif + if (iter == m_mapJsonArrayRef.end()) + { + cJSON* pJsonStruct = NULL; + if (m_pJsonData != NULL) + { + if (m_pJsonData->type == cJSON_Array) + { + pJsonStruct = cJSON_GetArrayItem(m_pJsonData, uiWhich); + } + } + else if (m_pExternJsonDataRef != NULL) + { + if (m_pExternJsonDataRef->type == cJSON_Array) + { + pJsonStruct = cJSON_GetArrayItem(m_pExternJsonDataRef, uiWhich); + } + } + if (pJsonStruct == NULL) + { + CJsonObject* pJsonObject = new CJsonObject(); + m_mapJsonArrayRef.insert(std::pair(uiWhich, pJsonObject)); + return(*pJsonObject); + } + else + { + CJsonObject* pJsonObject = new CJsonObject(pJsonStruct); + m_mapJsonArrayRef.insert(std::pair(uiWhich, pJsonObject)); + return(*pJsonObject); + } + } + else + { + return(*(iter->second)); + } +} + +std::string CJsonObject::operator()(const std::string& strKey) const +{ + cJSON* pJsonStruct = NULL; + if (m_pJsonData != NULL) + { + if (m_pJsonData->type == cJSON_Object) + { + pJsonStruct = cJSON_GetObjectItem(m_pJsonData, strKey.c_str()); + } + } + else if (m_pExternJsonDataRef != NULL) + { + if(m_pExternJsonDataRef->type == cJSON_Object) + { + pJsonStruct = cJSON_GetObjectItem(m_pExternJsonDataRef, strKey.c_str()); + } + } + if (pJsonStruct == NULL) + { + return(std::string("")); + } + if (pJsonStruct->type == cJSON_String) + { + return(pJsonStruct->valuestring); + } + else if (pJsonStruct->type == cJSON_Int) + { + char szNumber[128] = {0}; + if (pJsonStruct->sign == -1) + { + if (pJsonStruct->valueint <= (int64)INT_MAX && (int64)pJsonStruct->valueint >= (int64)INT_MIN) + { + snprintf(szNumber, sizeof(szNumber), "%d", (int32)pJsonStruct->valueint); + } + else + { +#if LLONG_MAX==LLONG_MAX + snprintf(szNumber, sizeof(szNumber), "%ld", (int64)pJsonStruct->valueint); +#else + snprintf(szNumber, sizeof(szNumber), "%lld", (int64)pJsonStruct->valueint); +#endif + } + } + else + { + if ((uint64)pJsonStruct->valueint <= (uint64)UINT_MAX) + { + snprintf(szNumber, sizeof(szNumber), "%u", (uint32)pJsonStruct->valueint); + } + else + { +#if LLONG_MAX==LLONG_MAX + snprintf(szNumber, sizeof(szNumber), "%lu", pJsonStruct->valueint); +#else + snprintf(szNumber, sizeof(szNumber), "%llu", pJsonStruct->valueint); +#endif + } + } + return(std::string(szNumber)); + } + else if (pJsonStruct->type == cJSON_Double) + { + char szNumber[128] = {0}; + if (fabs(pJsonStruct->valuedouble) < 1.0e-6 || fabs(pJsonStruct->valuedouble) > 1.0e9) + { + snprintf(szNumber, sizeof(szNumber), "%e", pJsonStruct->valuedouble); + } + else + { + snprintf(szNumber, sizeof(szNumber), "%f", pJsonStruct->valuedouble); + } + return(std::string(szNumber)); + } + else if (pJsonStruct->type == cJSON_False) + { + return(std::string("false")); + } + else if (pJsonStruct->type == cJSON_True) + { + return(std::string("true")); + } + return(std::string("")); +} + +std::string CJsonObject::operator()(unsigned int uiWhich) const +{ + cJSON* pJsonStruct = NULL; + if (m_pJsonData != NULL) + { + if (m_pJsonData->type == cJSON_Array) + { + pJsonStruct = cJSON_GetArrayItem(m_pJsonData, uiWhich); + } + } + else if (m_pExternJsonDataRef != NULL) + { + if(m_pExternJsonDataRef->type == cJSON_Array) + { + pJsonStruct = cJSON_GetArrayItem(m_pExternJsonDataRef, uiWhich); + } + } + if (pJsonStruct == NULL) + { + return(std::string("")); + } + if (pJsonStruct->type == cJSON_String) + { + return(pJsonStruct->valuestring); + } + else if (pJsonStruct->type == cJSON_Int) + { + char szNumber[128] = {0}; + if (pJsonStruct->sign == -1) + { + if (pJsonStruct->valueint <= (int64)INT_MAX && (int64)pJsonStruct->valueint >= (int64)INT_MIN) + { + snprintf(szNumber, sizeof(szNumber), "%d", (int32)pJsonStruct->valueint); + } + else + { +#if LLONG_MAX==LLONG_MAX + snprintf(szNumber, sizeof(szNumber), "%ld", (int64)pJsonStruct->valueint); +#else + snprintf(szNumber, sizeof(szNumber), "%lld", (int64)pJsonStruct->valueint); +#endif + } + } + else + { + if ((uint64)pJsonStruct->valueint <= (uint64)UINT_MAX) + { + snprintf(szNumber, sizeof(szNumber), "%u", (uint32)pJsonStruct->valueint); + } + else + { +#if LLONG_MAX==LLONG_MAX + snprintf(szNumber, sizeof(szNumber), "%lu", pJsonStruct->valueint); +#else + snprintf(szNumber, sizeof(szNumber), "%llu", pJsonStruct->valueint); +#endif + } + } + return(std::string(szNumber)); + } + else if (pJsonStruct->type == cJSON_Double) + { + char szNumber[128] = {0}; + if (fabs(pJsonStruct->valuedouble) < 1.0e-6 || fabs(pJsonStruct->valuedouble) > 1.0e9) + { + snprintf(szNumber, sizeof(szNumber), "%e", pJsonStruct->valuedouble); + } + else + { + snprintf(szNumber, sizeof(szNumber), "%f", pJsonStruct->valuedouble); + } + return(std::string(szNumber)); + } + else if (pJsonStruct->type == cJSON_False) + { + return(std::string("false")); + } + else if (pJsonStruct->type == cJSON_True) + { + return(std::string("true")); + } + return(std::string("")); +} + +bool CJsonObject::Parse(const std::string& strJson) +{ + Clear(); + m_pJsonData = cJSON_Parse(strJson.c_str(), &mc_pError); + m_pKeyTravers = m_pJsonData; + if (m_pJsonData == NULL) + { + m_strErrMsg = std::string("prase json string error at ") + mc_pError; + return(false); + } + return(true); +} + +void CJsonObject::Clear() +{ + m_pExternJsonDataRef = NULL; + m_pKeyTravers = NULL; + if (m_pJsonData != NULL) + { + cJSON_Delete(m_pJsonData); + m_pJsonData = NULL; + } +#if __cplusplus < 201101L + for (std::map::iterator iter = m_mapJsonArrayRef.begin(); + iter != m_mapJsonArrayRef.end(); ++iter) +#else + for (auto iter = m_mapJsonArrayRef.begin(); iter != m_mapJsonArrayRef.end(); ++iter) +#endif + { + if (iter->second != NULL) + { + delete (iter->second); + iter->second = NULL; + } + } + m_mapJsonArrayRef.clear(); + m_array_iter = m_mapJsonArrayRef.end(); +#if __cplusplus < 201101L + for (std::map::iterator iter = m_mapJsonObjectRef.begin(); + iter != m_mapJsonObjectRef.end(); ++iter) +#else + for (auto iter = m_mapJsonObjectRef.begin(); iter != m_mapJsonObjectRef.end(); ++iter) +#endif + { + if (iter->second != NULL) + { + delete (iter->second); + iter->second = NULL; + } + } + m_mapJsonObjectRef.clear(); + m_object_iter = m_mapJsonObjectRef.end(); +} + +bool CJsonObject::IsEmpty() const +{ + if (m_pJsonData != NULL) + { + return(false); + } + else if (m_pExternJsonDataRef != NULL) + { + return(false); + } + return(true); +} + +bool CJsonObject::IsArray() const +{ + cJSON* pFocusData = NULL; + if (m_pJsonData != NULL) + { + pFocusData = m_pJsonData; + } + else if (m_pExternJsonDataRef != NULL) + { + pFocusData = m_pExternJsonDataRef; + } + + if (pFocusData == NULL) + { + return(false); + } + + if (pFocusData->type == cJSON_Array) + { + return(true); + } + else + { + return(false); + } +} + +std::string CJsonObject::ToString() const +{ + char* pJsonString = NULL; + std::string strJsonData = ""; + if (m_pJsonData != NULL) + { + pJsonString = cJSON_PrintUnformatted(m_pJsonData); + } + else if (m_pExternJsonDataRef != NULL) + { + pJsonString = cJSON_PrintUnformatted(m_pExternJsonDataRef); + } + if (pJsonString != NULL) + { + strJsonData = pJsonString; + free(pJsonString); + } + return(strJsonData); +} + +std::string CJsonObject::ToFormattedString() const +{ + char* pJsonString = NULL; + std::string strJsonData = ""; + if (m_pJsonData != NULL) + { + pJsonString = cJSON_Print(m_pJsonData); + } + else if (m_pExternJsonDataRef != NULL) + { + pJsonString = cJSON_Print(m_pExternJsonDataRef); + } + if (pJsonString != NULL) + { + strJsonData = pJsonString; + free(pJsonString); + } + return(strJsonData); +} + +bool CJsonObject::KeyExist(const std::string& strKey) const +{ + cJSON* pJsonStruct = NULL; + if (m_pJsonData != NULL) + { + if (m_pJsonData->type == cJSON_Object) + { + pJsonStruct = cJSON_GetObjectItem(m_pJsonData, strKey.c_str()); + } + } + else if (m_pExternJsonDataRef != NULL) + { + if(m_pExternJsonDataRef->type == cJSON_Object) + { + pJsonStruct = cJSON_GetObjectItem(m_pExternJsonDataRef, strKey.c_str()); + } + } + if (pJsonStruct == NULL) + { + return(false); + } + return(true); +} + +bool CJsonObject::Get(const std::string& strKey, CJsonObject& oJsonObject) const +{ + cJSON* pJsonStruct = NULL; + if (m_pJsonData != NULL) + { + if (m_pJsonData->type == cJSON_Object) + { + pJsonStruct = cJSON_GetObjectItem(m_pJsonData, strKey.c_str()); + } + } + else if (m_pExternJsonDataRef != NULL) + { + if(m_pExternJsonDataRef->type == cJSON_Object) + { + pJsonStruct = cJSON_GetObjectItem(m_pExternJsonDataRef, strKey.c_str()); + } + } + if (pJsonStruct == NULL) + { + return(false); + } + char* pJsonString = cJSON_Print(pJsonStruct); + std::string strJsonData = pJsonString; + free(pJsonString); + if (oJsonObject.Parse(strJsonData)) + { + return(true); + } + else + { + return(false); + } +} + +bool CJsonObject::Get(const std::string& strKey, std::string& strValue) const +{ + cJSON* pJsonStruct = NULL; + if (m_pJsonData != NULL) + { + if (m_pJsonData->type == cJSON_Object) + { + pJsonStruct = cJSON_GetObjectItem(m_pJsonData, strKey.c_str()); + } + } + else if (m_pExternJsonDataRef != NULL) + { + if(m_pExternJsonDataRef->type == cJSON_Object) + { + pJsonStruct = cJSON_GetObjectItem(m_pExternJsonDataRef, strKey.c_str()); + } + } + if (pJsonStruct == NULL) + { + return(false); + } + if (pJsonStruct->type != cJSON_String) + { + return(false); + } + strValue = pJsonStruct->valuestring; + return(true); +} + +bool CJsonObject::Get(const std::string& strKey, int32& iValue) const +{ + cJSON* pJsonStruct = NULL; + if (m_pJsonData != NULL) + { + if (m_pJsonData->type == cJSON_Object) + { + pJsonStruct = cJSON_GetObjectItem(m_pJsonData, strKey.c_str()); + } + } + else if (m_pExternJsonDataRef != NULL) + { + if(m_pExternJsonDataRef->type == cJSON_Object) + { + pJsonStruct = cJSON_GetObjectItem(m_pExternJsonDataRef, strKey.c_str()); + } + } + if (pJsonStruct == NULL) + { + return(false); + } + if (pJsonStruct->type == cJSON_Int) + { + iValue = (int32)(pJsonStruct->valueint); + return(true); + } + else if (pJsonStruct->type == cJSON_Double) + { + iValue = (int32)(pJsonStruct->valuedouble); + return(true); + } + return(false); +} + +bool CJsonObject::Get(const std::string& strKey, uint32& uiValue) const +{ + cJSON* pJsonStruct = NULL; + if (m_pJsonData != NULL) + { + if (m_pJsonData->type == cJSON_Object) + { + pJsonStruct = cJSON_GetObjectItem(m_pJsonData, strKey.c_str()); + } + } + else if (m_pExternJsonDataRef != NULL) + { + if(m_pExternJsonDataRef->type == cJSON_Object) + { + pJsonStruct = cJSON_GetObjectItem(m_pExternJsonDataRef, strKey.c_str()); + } + } + if (pJsonStruct == NULL) + { + return(false); + } + if (pJsonStruct->type == cJSON_Int) + { + uiValue = (uint32)(pJsonStruct->valueint); + return(true); + } + else if (pJsonStruct->type == cJSON_Double) + { + uiValue = (uint32)(pJsonStruct->valuedouble); + return(true); + } + return(false); +} + +bool CJsonObject::Get(const std::string& strKey, int64& llValue) const +{ + cJSON* pJsonStruct = NULL; + if (m_pJsonData != NULL) + { + if (m_pJsonData->type == cJSON_Object) + { + pJsonStruct = cJSON_GetObjectItem(m_pJsonData, strKey.c_str()); + } + } + else if (m_pExternJsonDataRef != NULL) + { + if(m_pExternJsonDataRef->type == cJSON_Object) + { + pJsonStruct = cJSON_GetObjectItem(m_pExternJsonDataRef, strKey.c_str()); + } + } + if (pJsonStruct == NULL) + { + return(false); + } + if (pJsonStruct->type == cJSON_Int) + { + llValue = (int64)(pJsonStruct->valueint); + return(true); + } + else if (pJsonStruct->type == cJSON_Double) + { + llValue = (int64)(pJsonStruct->valuedouble); + return(true); + } + return(false); +} + +bool CJsonObject::Get(const std::string& strKey, uint64& ullValue) const +{ + cJSON* pJsonStruct = NULL; + if (m_pJsonData != NULL) + { + if (m_pJsonData->type == cJSON_Object) + { + pJsonStruct = cJSON_GetObjectItem(m_pJsonData, strKey.c_str()); + } + } + else if (m_pExternJsonDataRef != NULL) + { + if(m_pExternJsonDataRef->type == cJSON_Object) + { + pJsonStruct = cJSON_GetObjectItem(m_pExternJsonDataRef, strKey.c_str()); + } + } + if (pJsonStruct == NULL) + { + return(false); + } + if (pJsonStruct->type == cJSON_Int) + { + ullValue = (uint64)(pJsonStruct->valueint); + return(true); + } + else if (pJsonStruct->type == cJSON_Double) + { + ullValue = (uint64)(pJsonStruct->valuedouble); + return(true); + } + return(false); +} + +bool CJsonObject::Get(const std::string& strKey, bool& bValue) const +{ + cJSON* pJsonStruct = NULL; + if (m_pJsonData != NULL) + { + if (m_pJsonData->type == cJSON_Object) + { + pJsonStruct = cJSON_GetObjectItem(m_pJsonData, strKey.c_str()); + } + } + else if (m_pExternJsonDataRef != NULL) + { + if(m_pExternJsonDataRef->type == cJSON_Object) + { + pJsonStruct = cJSON_GetObjectItem(m_pExternJsonDataRef, strKey.c_str()); + } + } + if (pJsonStruct == NULL) + { + return(false); + } + if (pJsonStruct->type > cJSON_True) + { + return(false); + } + bValue = pJsonStruct->type; + return(true); +} + +bool CJsonObject::Get(const std::string& strKey, float& fValue) const +{ + cJSON* pJsonStruct = NULL; + if (m_pJsonData != NULL) + { + if (m_pJsonData->type == cJSON_Object) + { + pJsonStruct = cJSON_GetObjectItem(m_pJsonData, strKey.c_str()); + } + } + else if (m_pExternJsonDataRef != NULL) + { + if(m_pExternJsonDataRef->type == cJSON_Object) + { + pJsonStruct = cJSON_GetObjectItem(m_pExternJsonDataRef, strKey.c_str()); + } + } + if (pJsonStruct == NULL) + { + return(false); + } + if (pJsonStruct->type == cJSON_Double || pJsonStruct->type == cJSON_Int) + { + fValue = (float)(pJsonStruct->valuedouble); + return(true); + } + return(false); +} + +bool CJsonObject::Get(const std::string& strKey, double& dValue) const +{ + cJSON* pJsonStruct = NULL; + if (m_pJsonData != NULL) + { + if (m_pJsonData->type == cJSON_Object) + { + pJsonStruct = cJSON_GetObjectItem(m_pJsonData, strKey.c_str()); + } + } + else if (m_pExternJsonDataRef != NULL) + { + if(m_pExternJsonDataRef->type == cJSON_Object) + { + pJsonStruct = cJSON_GetObjectItem(m_pExternJsonDataRef, strKey.c_str()); + } + } + if (pJsonStruct == NULL) + { + return(false); + } + if (pJsonStruct->type == cJSON_Double || pJsonStruct->type == cJSON_Int) + { + dValue = pJsonStruct->valuedouble; + return(true); + } + return(false); +} + +int CJsonObject::GetValueType(const std::string& strKey) const +{ + cJSON* pJsonStruct = NULL; + if (m_pJsonData != NULL) + { + if (m_pJsonData->type == cJSON_Object) + { + pJsonStruct = cJSON_GetObjectItem(m_pJsonData, strKey.c_str()); + } + } + else if (m_pExternJsonDataRef != NULL) + { + if(m_pExternJsonDataRef->type == cJSON_Object) + { + pJsonStruct = cJSON_GetObjectItem(m_pExternJsonDataRef, strKey.c_str()); + } + } + if (pJsonStruct == NULL) + { + return(false); + } + return(pJsonStruct->type); +} + +bool CJsonObject::IsNull(const std::string& strKey) const +{ + cJSON* pJsonStruct = NULL; + if (m_pJsonData != NULL) + { + if (m_pJsonData->type == cJSON_Object) + { + pJsonStruct = cJSON_GetObjectItem(m_pJsonData, strKey.c_str()); + } + } + else if (m_pExternJsonDataRef != NULL) + { + if(m_pExternJsonDataRef->type == cJSON_Object) + { + pJsonStruct = cJSON_GetObjectItem(m_pExternJsonDataRef, strKey.c_str()); + } + } + if (pJsonStruct == NULL) + { + return(false); + } + if (pJsonStruct->type != cJSON_NULL) + { + return(false); + } + return(true); +} + +bool CJsonObject::Add(const std::string& strKey, const CJsonObject& oJsonObject) +{ + cJSON* pFocusData = NULL; + if (m_pJsonData != NULL) + { + pFocusData = m_pJsonData; + } + else if (m_pExternJsonDataRef != NULL) + { + pFocusData = m_pExternJsonDataRef; + } + else + { + m_pJsonData = cJSON_CreateObject(); + m_pKeyTravers = m_pJsonData; + pFocusData = m_pJsonData; + } + + if (pFocusData == NULL) + { + m_strErrMsg = "json data is null!"; + return(false); + } + if (pFocusData->type != cJSON_Object) + { + m_strErrMsg = "not a json object! json array?"; + return(false); + } + if (cJSON_GetObjectItem(pFocusData, strKey.c_str()) != NULL) + { + m_strErrMsg = "key exists!"; + return(false); + } + cJSON* pJsonStruct = cJSON_Parse(oJsonObject.ToString().c_str(), &mc_pError) ; + if (pJsonStruct == NULL) + { + m_strErrMsg = std::string("prase json string error at ") + mc_pError; + return(false); + } + cJSON_AddItemToObject(pFocusData, strKey.c_str(), pJsonStruct); + if (cJSON_GetObjectItem(pFocusData, strKey.c_str()) == NULL) + { + return(false); + } +#if __cplusplus < 201101L + std::map::iterator iter = m_mapJsonObjectRef.find(strKey); +#else + auto iter = m_mapJsonObjectRef.find(strKey); +#endif + if (iter != m_mapJsonObjectRef.end()) + { + if (iter->second != NULL) + { + delete (iter->second); + iter->second = NULL; + } + m_mapJsonObjectRef.erase(iter); + } + m_pKeyTravers = pFocusData; + return(true); +} + +#if __cplusplus < 201101L +bool CJsonObject::AddWithMove(const std::string& strKey, CJsonObject& oJsonObject) +{ + cJSON* pFocusData = NULL; + if (m_pJsonData != NULL) + { + pFocusData = m_pJsonData; + } + else if (m_pExternJsonDataRef != NULL) + { + pFocusData = m_pExternJsonDataRef; + } + else + { + m_pJsonData = cJSON_CreateObject(); + m_pKeyTravers = m_pJsonData; + pFocusData = m_pJsonData; + } + + if (pFocusData == NULL) + { + m_strErrMsg = "json data is null!"; + return(false); + } + if (pFocusData->type != cJSON_Object) + { + m_strErrMsg = "not a json object! json array?"; + return(false); + } + if (cJSON_GetObjectItem(pFocusData, strKey.c_str()) != NULL) + { + m_strErrMsg = "key exists!"; + return(false); + } + cJSON* pJsonStruct = oJsonObject.m_pJsonData; + oJsonObject.m_pJsonData = NULL; + if (pJsonStruct == NULL) + { + m_strErrMsg = "can not move a non-independent(internal) CJsonObject from one to another."; + return(false); + } + cJSON_AddItemToObject(pFocusData, strKey.c_str(), pJsonStruct); + if (cJSON_GetObjectItem(pFocusData, strKey.c_str()) == NULL) + { + return(false); + } + std::map::iterator iter = m_mapJsonObjectRef.find(strKey); + if (iter != m_mapJsonObjectRef.end()) + { + if (iter->second != NULL) + { + delete (iter->second); + iter->second = NULL; + } + m_mapJsonObjectRef.erase(iter); + } + m_pKeyTravers = pFocusData; + return(true); +} +#else +bool CJsonObject::Add(const std::string& strKey, CJsonObject&& oJsonObject) +{ + cJSON* pFocusData = NULL; + if (m_pJsonData != NULL) + { + pFocusData = m_pJsonData; + } + else if (m_pExternJsonDataRef != NULL) + { + pFocusData = m_pExternJsonDataRef; + } + else + { + m_pJsonData = cJSON_CreateObject(); + m_pKeyTravers = m_pJsonData; + pFocusData = m_pJsonData; + } + + if (pFocusData == NULL) + { + m_strErrMsg = "json data is null!"; + return(false); + } + if (pFocusData->type != cJSON_Object) + { + m_strErrMsg = "not a json object! json array?"; + return(false); + } + if (cJSON_GetObjectItem(pFocusData, strKey.c_str()) != NULL) + { + m_strErrMsg = "key exists!"; + return(false); + } + cJSON* pJsonStruct = oJsonObject.m_pJsonData; + oJsonObject.m_pJsonData = NULL; + if (pJsonStruct == NULL) + { + m_strErrMsg = "can not move a non-independent(internal) CJsonObject from one to another."; + return(false); + } + cJSON_AddItemToObject(pFocusData, strKey.c_str(), pJsonStruct); + if (cJSON_GetObjectItem(pFocusData, strKey.c_str()) == NULL) + { + return(false); + } + auto iter = m_mapJsonObjectRef.find(strKey); + if (iter != m_mapJsonObjectRef.end()) + { + if (iter->second != NULL) + { + delete (iter->second); + iter->second = NULL; + } + m_mapJsonObjectRef.erase(iter); + } + m_pKeyTravers = pFocusData; + return(true); +} +#endif + +bool CJsonObject::Add(const std::string& strKey, const std::string& strValue) +{ + cJSON* pFocusData = NULL; + if (m_pJsonData != NULL) + { + pFocusData = m_pJsonData; + } + else if (m_pExternJsonDataRef != NULL) + { + pFocusData = m_pExternJsonDataRef; + } + else + { + m_pJsonData = cJSON_CreateObject(); + m_pKeyTravers = m_pJsonData; + pFocusData = m_pJsonData; + } + + if (pFocusData == NULL) + { + m_strErrMsg = "json data is null!"; + return(false); + } + if (pFocusData->type != cJSON_Object) + { + m_strErrMsg = "not a json object! json array?"; + return(false); + } + if (cJSON_GetObjectItem(pFocusData, strKey.c_str()) != NULL) + { + m_strErrMsg = "key exists!"; + return(false); + } + cJSON* pJsonStruct = cJSON_CreateString(strValue.c_str()); + if (pJsonStruct == NULL) + { + return(false); + } + cJSON_AddItemToObject(pFocusData, strKey.c_str(), pJsonStruct); + if (cJSON_GetObjectItem(pFocusData, strKey.c_str()) == NULL) + { + return(false); + } + m_pKeyTravers = pFocusData; + return(true); +} + +bool CJsonObject::Add(const std::string& strKey, int32 iValue) +{ + cJSON* pFocusData = NULL; + if (m_pJsonData != NULL) + { + pFocusData = m_pJsonData; + } + else if (m_pExternJsonDataRef != NULL) + { + pFocusData = m_pExternJsonDataRef; + } + else + { + m_pJsonData = cJSON_CreateObject(); + m_pKeyTravers = m_pJsonData; + pFocusData = m_pJsonData; + } + + if (pFocusData == NULL) + { + m_strErrMsg = "json data is null!"; + return(false); + } + if (pFocusData->type != cJSON_Object) + { + m_strErrMsg = "not a json object! json array?"; + return(false); + } + if (cJSON_GetObjectItem(pFocusData, strKey.c_str()) != NULL) + { + m_strErrMsg = "key exists!"; + return(false); + } + cJSON* pJsonStruct = cJSON_CreateInt((uint64)iValue, -1); + if (pJsonStruct == NULL) + { + return(false); + } + cJSON_AddItemToObject(pFocusData, strKey.c_str(), pJsonStruct); + if (cJSON_GetObjectItem(pFocusData, strKey.c_str()) == NULL) + { + return(false); + } + m_pKeyTravers = pFocusData; + return(true); +} + +bool CJsonObject::Add(const std::string& strKey, uint32 uiValue) +{ + cJSON* pFocusData = NULL; + if (m_pJsonData != NULL) + { + pFocusData = m_pJsonData; + } + else if (m_pExternJsonDataRef != NULL) + { + pFocusData = m_pExternJsonDataRef; + } + else + { + m_pJsonData = cJSON_CreateObject(); + m_pKeyTravers = m_pJsonData; + pFocusData = m_pJsonData; + } + + if (pFocusData == NULL) + { + m_strErrMsg = "json data is null!"; + return(false); + } + if (pFocusData->type != cJSON_Object) + { + m_strErrMsg = "not a json object! json array?"; + return(false); + } + if (cJSON_GetObjectItem(pFocusData, strKey.c_str()) != NULL) + { + m_strErrMsg = "key exists!"; + return(false); + } + cJSON* pJsonStruct = cJSON_CreateInt((uint64)uiValue, 1); + if (pJsonStruct == NULL) + { + return(false); + } + cJSON_AddItemToObject(pFocusData, strKey.c_str(), pJsonStruct); + if (cJSON_GetObjectItem(pFocusData, strKey.c_str()) == NULL) + { + return(false); + } + m_pKeyTravers = pFocusData; + return(true); +} + +bool CJsonObject::Add(const std::string& strKey, int64 llValue) +{ + cJSON* pFocusData = NULL; + if (m_pJsonData != NULL) + { + pFocusData = m_pJsonData; + } + else if (m_pExternJsonDataRef != NULL) + { + pFocusData = m_pExternJsonDataRef; + } + else + { + m_pJsonData = cJSON_CreateObject(); + m_pKeyTravers = m_pJsonData; + pFocusData = m_pJsonData; + } + + if (pFocusData == NULL) + { + m_strErrMsg = "json data is null!"; + return(false); + } + if (pFocusData->type != cJSON_Object) + { + m_strErrMsg = "not a json object! json array?"; + return(false); + } + if (cJSON_GetObjectItem(pFocusData, strKey.c_str()) != NULL) + { + m_strErrMsg = "key exists!"; + return(false); + } + cJSON* pJsonStruct = cJSON_CreateInt((uint64)llValue, -1); + if (pJsonStruct == NULL) + { + return(false); + } + cJSON_AddItemToObject(pFocusData, strKey.c_str(), pJsonStruct); + if (cJSON_GetObjectItem(pFocusData, strKey.c_str()) == NULL) + { + return(false); + } + m_pKeyTravers = pFocusData; + return(true); +} + +bool CJsonObject::Add(const std::string& strKey, uint64 ullValue) +{ + cJSON* pFocusData = NULL; + if (m_pJsonData != NULL) + { + pFocusData = m_pJsonData; + } + else if (m_pExternJsonDataRef != NULL) + { + pFocusData = m_pExternJsonDataRef; + } + else + { + m_pJsonData = cJSON_CreateObject(); + m_pKeyTravers = m_pJsonData; + pFocusData = m_pJsonData; + } + + if (pFocusData == NULL) + { + m_strErrMsg = "json data is null!"; + return(false); + } + if (pFocusData->type != cJSON_Object) + { + m_strErrMsg = "not a json object! json array?"; + return(false); + } + if (cJSON_GetObjectItem(pFocusData, strKey.c_str()) != NULL) + { + m_strErrMsg = "key exists!"; + return(false); + } + cJSON* pJsonStruct = cJSON_CreateInt(ullValue, 1); + if (pJsonStruct == NULL) + { + return(false); + } + cJSON_AddItemToObject(pFocusData, strKey.c_str(), pJsonStruct); + if (cJSON_GetObjectItem(pFocusData, strKey.c_str()) == NULL) + { + return(false); + } + m_pKeyTravers = pFocusData; + return(true); +} + +bool CJsonObject::Add(const std::string& strKey, bool bValue, bool bValueAgain) +{ + cJSON* pFocusData = NULL; + if (m_pJsonData != NULL) + { + pFocusData = m_pJsonData; + } + else if (m_pExternJsonDataRef != NULL) + { + pFocusData = m_pExternJsonDataRef; + } + else + { + m_pJsonData = cJSON_CreateObject(); + m_pKeyTravers = m_pJsonData; + pFocusData = m_pJsonData; + } + + if (pFocusData == NULL) + { + m_strErrMsg = "json data is null!"; + return(false); + } + if (pFocusData->type != cJSON_Object) + { + m_strErrMsg = "not a json object! json array?"; + return(false); + } + if (cJSON_GetObjectItem(pFocusData, strKey.c_str()) != NULL) + { + m_strErrMsg = "key exists!"; + return(false); + } + cJSON* pJsonStruct = cJSON_CreateBool(bValue); + if (pJsonStruct == NULL) + { + return(false); + } + cJSON_AddItemToObject(pFocusData, strKey.c_str(), pJsonStruct); + if (cJSON_GetObjectItem(pFocusData, strKey.c_str()) == NULL) + { + return(false); + } + m_pKeyTravers = pFocusData; + return(true); +} + +bool CJsonObject::Add(const std::string& strKey, float fValue) +{ + cJSON* pFocusData = NULL; + if (m_pJsonData != NULL) + { + pFocusData = m_pJsonData; + } + else if (m_pExternJsonDataRef != NULL) + { + pFocusData = m_pExternJsonDataRef; + } + else + { + m_pJsonData = cJSON_CreateObject(); + m_pKeyTravers = m_pJsonData; + pFocusData = m_pJsonData; + } + + if (pFocusData == NULL) + { + m_strErrMsg = "json data is null!"; + return(false); + } + if (pFocusData->type != cJSON_Object) + { + m_strErrMsg = "not a json object! json array?"; + return(false); + } + if (cJSON_GetObjectItem(pFocusData, strKey.c_str()) != NULL) + { + m_strErrMsg = "key exists!"; + return(false); + } + cJSON* pJsonStruct = cJSON_CreateDouble((double)fValue, -1); + if (pJsonStruct == NULL) + { + return(false); + } + cJSON_AddItemToObject(pFocusData, strKey.c_str(), pJsonStruct); + if (cJSON_GetObjectItem(pFocusData, strKey.c_str()) == NULL) + { + return(false); + } + m_pKeyTravers = pFocusData; + return(true); +} + +bool CJsonObject::Add(const std::string& strKey, double dValue) +{ + cJSON* pFocusData = NULL; + if (m_pJsonData != NULL) + { + pFocusData = m_pJsonData; + } + else if (m_pExternJsonDataRef != NULL) + { + pFocusData = m_pExternJsonDataRef; + } + else + { + m_pJsonData = cJSON_CreateObject(); + m_pKeyTravers = m_pJsonData; + pFocusData = m_pJsonData; + } + + if (pFocusData == NULL) + { + m_strErrMsg = "json data is null!"; + return(false); + } + if (pFocusData->type != cJSON_Object) + { + m_strErrMsg = "not a json object! json array?"; + return(false); + } + if (cJSON_GetObjectItem(pFocusData, strKey.c_str()) != NULL) + { + m_strErrMsg = "key exists!"; + return(false); + } + cJSON* pJsonStruct = cJSON_CreateDouble((double)dValue, -1); + if (pJsonStruct == NULL) + { + return(false); + } + cJSON_AddItemToObject(pFocusData, strKey.c_str(), pJsonStruct); + if (cJSON_GetObjectItem(pFocusData, strKey.c_str()) == NULL) + { + return(false); + } + m_pKeyTravers = pFocusData; + return(true); +} + +#if __cplusplus < 201101L +bool CJsonObject::ReplaceAdd(const std::string& strKey, const CJsonObject& oJsonObject) +{ + if (KeyExist(strKey)) + { + return(Replace(strKey, oJsonObject)); + } + return(Add(strKey, oJsonObject)); +} + +bool CJsonObject::ReplaceAdd(const std::string& strKey, const std::string& strValue) +{ + if (KeyExist(strKey)) + { + return(Replace(strKey, strValue)); + } + return(Add(strKey, strValue)); +} +#endif + +bool CJsonObject::AddNull(const std::string& strKey) +{ + cJSON* pFocusData = NULL; + if (m_pJsonData != NULL) + { + pFocusData = m_pJsonData; + } + else if (m_pExternJsonDataRef != NULL) + { + pFocusData = m_pExternJsonDataRef; + } + else + { + m_pJsonData = cJSON_CreateObject(); + m_pKeyTravers = m_pJsonData; + pFocusData = m_pJsonData; + } + + if (pFocusData == NULL) + { + m_strErrMsg = "json data is null!"; + return(false); + } + if (pFocusData->type != cJSON_Object) + { + m_strErrMsg = "not a json object! json array?"; + return(false); + } + if (cJSON_GetObjectItem(pFocusData, strKey.c_str()) != NULL) + { + m_strErrMsg = "key exists!"; + return(false); + } + cJSON* pJsonStruct = cJSON_CreateNull(); + if (pJsonStruct == NULL) + { + return(false); + } + cJSON_AddItemToObject(pFocusData, strKey.c_str(), pJsonStruct); + if (cJSON_GetObjectItem(pFocusData, strKey.c_str()) == NULL) + { + return(false); + } + m_pKeyTravers = pFocusData; + return(true); +} + +bool CJsonObject::Delete(const std::string& strKey) +{ + cJSON* pFocusData = NULL; + if (m_pJsonData == NULL) + { + pFocusData = m_pExternJsonDataRef; + } + else + { + pFocusData = m_pJsonData; + } + if (pFocusData == NULL) + { + m_strErrMsg = "json data is null!"; + return(false); + } + if (pFocusData->type != cJSON_Object) + { + m_strErrMsg = "not a json object! json array?"; + return(false); + } + cJSON_DeleteItemFromObject(pFocusData, strKey.c_str()); +#if __cplusplus < 201101L + std::map::iterator iter = m_mapJsonObjectRef.find(strKey); +#else + auto iter = m_mapJsonObjectRef.find(strKey); +#endif + if (iter != m_mapJsonObjectRef.end()) + { + if (iter->second != NULL) + { + delete (iter->second); + iter->second = NULL; + } + m_mapJsonObjectRef.erase(iter); + } + m_pKeyTravers = pFocusData; + return(true); +} + +bool CJsonObject::Replace(const std::string& strKey, const CJsonObject& oJsonObject) +{ + cJSON* pFocusData = NULL; + if (m_pJsonData == NULL) + { + pFocusData = m_pExternJsonDataRef; + } + else + { + pFocusData = m_pJsonData; + } + if (pFocusData == NULL) + { + m_strErrMsg = "json data is null!"; + return(false); + } + if (pFocusData->type != cJSON_Object) + { + m_strErrMsg = "not a json object! json array?"; + return(false); + } + cJSON* pJsonStruct = cJSON_Parse(oJsonObject.ToString().c_str(), &mc_pError); + if (pJsonStruct == NULL) + { + m_strErrMsg = std::string("prase json string error at ") + mc_pError; + return(false); + } + cJSON_ReplaceItemInObject(pFocusData, strKey.c_str(), pJsonStruct); + if (cJSON_GetObjectItem(pFocusData, strKey.c_str()) == NULL) + { + return(false); + } +#if __cplusplus < 201101L + std::map::iterator iter = m_mapJsonObjectRef.find(strKey); +#else + auto iter = m_mapJsonObjectRef.find(strKey); +#endif + if (iter != m_mapJsonObjectRef.end()) + { + if (iter->second != NULL) + { + delete (iter->second); + iter->second = NULL; + } + m_mapJsonObjectRef.erase(iter); + } + return(true); +} + +#if __cplusplus < 201101L +bool CJsonObject::ReplaceWithMove(const std::string& strKey, CJsonObject& oJsonObject) +{ + cJSON* pFocusData = NULL; + if (m_pJsonData == NULL) + { + pFocusData = m_pExternJsonDataRef; + } + else + { + pFocusData = m_pJsonData; + } + if (pFocusData == NULL) + { + m_strErrMsg = "json data is null!"; + return(false); + } + if (pFocusData->type != cJSON_Object) + { + m_strErrMsg = "not a json object! json array?"; + return(false); + } + cJSON* pJsonStruct = oJsonObject.m_pJsonData; + oJsonObject.m_pJsonData = NULL; + if (pJsonStruct == NULL) + { + m_strErrMsg = "can not move a non-independent(internal) CJsonObject from one to another."; + return(false); + } + cJSON_ReplaceItemInObject(pFocusData, strKey.c_str(), pJsonStruct); + if (cJSON_GetObjectItem(pFocusData, strKey.c_str()) == NULL) + { + return(false); + } + std::map::iterator iter = m_mapJsonObjectRef.find(strKey); + if (iter != m_mapJsonObjectRef.end()) + { + if (iter->second != NULL) + { + delete (iter->second); + iter->second = NULL; + } + m_mapJsonObjectRef.erase(iter); + } + return(true); +} +#else +bool CJsonObject::Replace(const std::string& strKey, CJsonObject&& oJsonObject) +{ + cJSON* pFocusData = NULL; + if (m_pJsonData == NULL) + { + pFocusData = m_pExternJsonDataRef; + } + else + { + pFocusData = m_pJsonData; + } + if (pFocusData == NULL) + { + m_strErrMsg = "json data is null!"; + return(false); + } + if (pFocusData->type != cJSON_Object) + { + m_strErrMsg = "not a json object! json array?"; + return(false); + } + cJSON* pJsonStruct = oJsonObject.m_pJsonData; + oJsonObject.m_pJsonData = NULL; + if (pJsonStruct == NULL) + { + m_strErrMsg = "can not move a non-independent(internal) CJsonObject from one to another."; + return(false); + } + cJSON_ReplaceItemInObject(pFocusData, strKey.c_str(), pJsonStruct); + if (cJSON_GetObjectItem(pFocusData, strKey.c_str()) == NULL) + { + return(false); + } + auto iter = m_mapJsonObjectRef.find(strKey); + if (iter != m_mapJsonObjectRef.end()) + { + if (iter->second != NULL) + { + delete (iter->second); + iter->second = NULL; + } + m_mapJsonObjectRef.erase(iter); + } + return(true); +} +#endif + +bool CJsonObject::Replace(const std::string& strKey, const std::string& strValue) +{ + cJSON* pFocusData = NULL; + if (m_pJsonData == NULL) + { + pFocusData = m_pExternJsonDataRef; + } + else + { + pFocusData = m_pJsonData; + } + if (pFocusData == NULL) + { + m_strErrMsg = "json data is null!"; + return(false); + } + if (pFocusData->type != cJSON_Object) + { + m_strErrMsg = "not a json object! json array?"; + return(false); + } + cJSON* pJsonStruct = cJSON_CreateString(strValue.c_str()); + if (pJsonStruct == NULL) + { + return(false); + } +#if __cplusplus < 201101L + std::map::iterator iter = m_mapJsonObjectRef.find(strKey); +#else + auto iter = m_mapJsonObjectRef.find(strKey); +#endif + if (iter != m_mapJsonObjectRef.end()) + { + if (iter->second != NULL) + { + delete (iter->second); + iter->second = NULL; + } + m_mapJsonObjectRef.erase(iter); + } + cJSON_ReplaceItemInObject(pFocusData, strKey.c_str(), pJsonStruct); + if (cJSON_GetObjectItem(pFocusData, strKey.c_str()) == NULL) + { + return(false); + } + return(true); +} + +bool CJsonObject::Replace(const std::string& strKey, int32 iValue) +{ + cJSON* pFocusData = NULL; + if (m_pJsonData == NULL) + { + pFocusData = m_pExternJsonDataRef; + } + else + { + pFocusData = m_pJsonData; + } + if (pFocusData == NULL) + { + m_strErrMsg = "json data is null!"; + return(false); + } + if (pFocusData->type != cJSON_Object) + { + m_strErrMsg = "not a json object! json array?"; + return(false); + } + cJSON* pJsonStruct = cJSON_CreateInt((uint64)iValue, -1); + if (pJsonStruct == NULL) + { + return(false); + } +#if __cplusplus < 201101L + std::map::iterator iter = m_mapJsonObjectRef.find(strKey); +#else + auto iter = m_mapJsonObjectRef.find(strKey); +#endif + if (iter != m_mapJsonObjectRef.end()) + { + if (iter->second != NULL) + { + delete (iter->second); + iter->second = NULL; + } + m_mapJsonObjectRef.erase(iter); + } + cJSON_ReplaceItemInObject(pFocusData, strKey.c_str(), pJsonStruct); + if (cJSON_GetObjectItem(pFocusData, strKey.c_str()) == NULL) + { + return(false); + } + return(true); +} + +bool CJsonObject::Replace(const std::string& strKey, uint32 uiValue) +{ + cJSON* pFocusData = NULL; + if (m_pJsonData == NULL) + { + pFocusData = m_pExternJsonDataRef; + } + else + { + pFocusData = m_pJsonData; + } + if (pFocusData == NULL) + { + m_strErrMsg = "json data is null!"; + return(false); + } + if (pFocusData->type != cJSON_Object) + { + m_strErrMsg = "not a json object! json array?"; + return(false); + } + cJSON* pJsonStruct = cJSON_CreateInt((uint64)uiValue, 1); + if (pJsonStruct == NULL) + { + return(false); + } +#if __cplusplus < 201101L + std::map::iterator iter = m_mapJsonObjectRef.find(strKey); +#else + auto iter = m_mapJsonObjectRef.find(strKey); +#endif + if (iter != m_mapJsonObjectRef.end()) + { + if (iter->second != NULL) + { + delete (iter->second); + iter->second = NULL; + } + m_mapJsonObjectRef.erase(iter); + } + cJSON_ReplaceItemInObject(pFocusData, strKey.c_str(), pJsonStruct); + if (cJSON_GetObjectItem(pFocusData, strKey.c_str()) == NULL) + { + return(false); + } + return(true); +} + +bool CJsonObject::Replace(const std::string& strKey, int64 llValue) +{ + cJSON* pFocusData = NULL; + if (m_pJsonData == NULL) + { + pFocusData = m_pExternJsonDataRef; + } + else + { + pFocusData = m_pJsonData; + } + if (pFocusData == NULL) + { + m_strErrMsg = "json data is null!"; + return(false); + } + if (pFocusData->type != cJSON_Object) + { + m_strErrMsg = "not a json object! json array?"; + return(false); + } + cJSON* pJsonStruct = cJSON_CreateInt((uint64)llValue, -1); + if (pJsonStruct == NULL) + { + return(false); + } +#if __cplusplus < 201101L + std::map::iterator iter = m_mapJsonObjectRef.find(strKey); +#else + auto iter = m_mapJsonObjectRef.find(strKey); +#endif + if (iter != m_mapJsonObjectRef.end()) + { + if (iter->second != NULL) + { + delete (iter->second); + iter->second = NULL; + } + m_mapJsonObjectRef.erase(iter); + } + cJSON_ReplaceItemInObject(pFocusData, strKey.c_str(), pJsonStruct); + if (cJSON_GetObjectItem(pFocusData, strKey.c_str()) == NULL) + { + return(false); + } + return(true); +} + +bool CJsonObject::Replace(const std::string& strKey, uint64 ullValue) +{ + cJSON* pFocusData = NULL; + if (m_pJsonData == NULL) + { + pFocusData = m_pExternJsonDataRef; + } + else + { + pFocusData = m_pJsonData; + } + if (pFocusData == NULL) + { + m_strErrMsg = "json data is null!"; + return(false); + } + if (pFocusData->type != cJSON_Object) + { + m_strErrMsg = "not a json object! json array?"; + return(false); + } + cJSON* pJsonStruct = cJSON_CreateInt((uint64)ullValue, 1); + if (pJsonStruct == NULL) + { + return(false); + } +#if __cplusplus < 201101L + std::map::iterator iter = m_mapJsonObjectRef.find(strKey); +#else + auto iter = m_mapJsonObjectRef.find(strKey); +#endif + if (iter != m_mapJsonObjectRef.end()) + { + if (iter->second != NULL) + { + delete (iter->second); + iter->second = NULL; + } + m_mapJsonObjectRef.erase(iter); + } + cJSON_ReplaceItemInObject(pFocusData, strKey.c_str(), pJsonStruct); + if (cJSON_GetObjectItem(pFocusData, strKey.c_str()) == NULL) + { + return(false); + } + return(true); +} + +bool CJsonObject::Replace(const std::string& strKey, bool bValue, bool bValueAgain) +{ + cJSON* pFocusData = NULL; + if (m_pJsonData == NULL) + { + pFocusData = m_pExternJsonDataRef; + } + else + { + pFocusData = m_pJsonData; + } + if (pFocusData == NULL) + { + m_strErrMsg = "json data is null!"; + return(false); + } + if (pFocusData->type != cJSON_Object) + { + m_strErrMsg = "not a json object! json array?"; + return(false); + } + cJSON* pJsonStruct = cJSON_CreateBool(bValue); + if (pJsonStruct == NULL) + { + return(false); + } +#if __cplusplus < 201101L + std::map::iterator iter = m_mapJsonObjectRef.find(strKey); +#else + auto iter = m_mapJsonObjectRef.find(strKey); +#endif + if (iter != m_mapJsonObjectRef.end()) + { + if (iter->second != NULL) + { + delete (iter->second); + iter->second = NULL; + } + m_mapJsonObjectRef.erase(iter); + } + cJSON_ReplaceItemInObject(pFocusData, strKey.c_str(), pJsonStruct); + if (cJSON_GetObjectItem(pFocusData, strKey.c_str()) == NULL) + { + return(false); + } + return(true); +} + +bool CJsonObject::Replace(const std::string& strKey, float fValue) +{ + cJSON* pFocusData = NULL; + if (m_pJsonData == NULL) + { + pFocusData = m_pExternJsonDataRef; + } + else + { + pFocusData = m_pJsonData; + } + if (pFocusData == NULL) + { + m_strErrMsg = "json data is null!"; + return(false); + } + if (pFocusData->type != cJSON_Object) + { + m_strErrMsg = "not a json object! json array?"; + return(false); + } + cJSON* pJsonStruct = cJSON_CreateDouble((double)fValue, -1); + if (pJsonStruct == NULL) + { + return(false); + } +#if __cplusplus < 201101L + std::map::iterator iter = m_mapJsonObjectRef.find(strKey); +#else + auto iter = m_mapJsonObjectRef.find(strKey); +#endif + if (iter != m_mapJsonObjectRef.end()) + { + if (iter->second != NULL) + { + delete (iter->second); + iter->second = NULL; + } + m_mapJsonObjectRef.erase(iter); + } + cJSON_ReplaceItemInObject(pFocusData, strKey.c_str(), pJsonStruct); + if (cJSON_GetObjectItem(pFocusData, strKey.c_str()) == NULL) + { + return(false); + } + return(true); +} + +bool CJsonObject::Replace(const std::string& strKey, double dValue) +{ + cJSON* pFocusData = NULL; + if (m_pJsonData == NULL) + { + pFocusData = m_pExternJsonDataRef; + } + else + { + pFocusData = m_pJsonData; + } + if (pFocusData == NULL) + { + m_strErrMsg = "json data is null!"; + return(false); + } + if (pFocusData->type != cJSON_Object) + { + m_strErrMsg = "not a json object! json array?"; + return(false); + } + cJSON* pJsonStruct = cJSON_CreateDouble((double)dValue, -1); + if (pJsonStruct == NULL) + { + return(false); + } +#if __cplusplus < 201101L + std::map::iterator iter = m_mapJsonObjectRef.find(strKey); +#else + auto iter = m_mapJsonObjectRef.find(strKey); +#endif + if (iter != m_mapJsonObjectRef.end()) + { + if (iter->second != NULL) + { + delete (iter->second); + iter->second = NULL; + } + m_mapJsonObjectRef.erase(iter); + } + cJSON_ReplaceItemInObject(pFocusData, strKey.c_str(), pJsonStruct); + if (cJSON_GetObjectItem(pFocusData, strKey.c_str()) == NULL) + { + return(false); + } + return(true); +} + +bool CJsonObject::ReplaceWithNull(const std::string& strKey) +{ + cJSON* pFocusData = NULL; + if (m_pJsonData == NULL) + { + pFocusData = m_pExternJsonDataRef; + } + else + { + pFocusData = m_pJsonData; + } + if (pFocusData == NULL) + { + m_strErrMsg = "json data is null!"; + return(false); + } + if (pFocusData->type != cJSON_Object) + { + m_strErrMsg = "not a json object! json array?"; + return(false); + } + cJSON* pJsonStruct = cJSON_CreateNull(); + if (pJsonStruct == NULL) + { + return(false); + } +#if __cplusplus < 201101L + std::map::iterator iter = m_mapJsonObjectRef.find(strKey); +#else + auto iter = m_mapJsonObjectRef.find(strKey); +#endif + if (iter != m_mapJsonObjectRef.end()) + { + if (iter->second != NULL) + { + delete (iter->second); + iter->second = NULL; + } + m_mapJsonObjectRef.erase(iter); + } + cJSON_ReplaceItemInObject(pFocusData, strKey.c_str(), pJsonStruct); + if (cJSON_GetObjectItem(pFocusData, strKey.c_str()) == NULL) + { + return(false); + } + return(true); +} + +int CJsonObject::GetArraySize() const +{ + if (m_pJsonData != NULL) + { + if (m_pJsonData->type == cJSON_Array) + { + return(cJSON_GetArraySize(m_pJsonData)); + } + } + else if (m_pExternJsonDataRef != NULL) + { + if(m_pExternJsonDataRef->type == cJSON_Array) + { + return(cJSON_GetArraySize(m_pExternJsonDataRef)); + } + } + return(0); +} + +bool CJsonObject::Get(int iWhich, CJsonObject& oJsonObject) const +{ + cJSON* pJsonStruct = NULL; + if (m_pJsonData != NULL) + { + if (m_pJsonData->type == cJSON_Array) + { + pJsonStruct = cJSON_GetArrayItem(m_pJsonData, iWhich); + } + } + else if (m_pExternJsonDataRef != NULL) + { + if(m_pExternJsonDataRef->type == cJSON_Array) + { + pJsonStruct = cJSON_GetArrayItem(m_pExternJsonDataRef, iWhich); + } + } + if (pJsonStruct == NULL) + { + return(false); + } + char* pJsonString = cJSON_Print(pJsonStruct); + std::string strJsonData = pJsonString; + free(pJsonString); + if (oJsonObject.Parse(strJsonData)) + { + return(true); + } + else + { + return(false); + } +} + +bool CJsonObject::Get(int iWhich, std::string& strValue) const +{ + cJSON* pJsonStruct = NULL; + if (m_pJsonData != NULL) + { + if (m_pJsonData->type == cJSON_Array) + { + pJsonStruct = cJSON_GetArrayItem(m_pJsonData, iWhich); + } + } + else if (m_pExternJsonDataRef != NULL) + { + if(m_pExternJsonDataRef->type == cJSON_Array) + { + pJsonStruct = cJSON_GetArrayItem(m_pExternJsonDataRef, iWhich); + } + } + if (pJsonStruct == NULL) + { + return(false); + } + if (pJsonStruct->type != cJSON_String) + { + return(false); + } + strValue = pJsonStruct->valuestring; + return(true); +} + +bool CJsonObject::Get(int iWhich, int32& iValue) const +{ + cJSON* pJsonStruct = NULL; + if (m_pJsonData != NULL) + { + if (m_pJsonData->type == cJSON_Array) + { + pJsonStruct = cJSON_GetArrayItem(m_pJsonData, iWhich); + } + } + else if (m_pExternJsonDataRef != NULL) + { + if(m_pExternJsonDataRef->type == cJSON_Array) + { + pJsonStruct = cJSON_GetArrayItem(m_pExternJsonDataRef, iWhich); + } + } + if (pJsonStruct == NULL) + { + return(false); + } + if (pJsonStruct->type == cJSON_Int) + { + iValue = (int32)(pJsonStruct->valueint); + return(true); + } + else if (pJsonStruct->type == cJSON_Double) + { + iValue = (int32)(pJsonStruct->valuedouble); + return(true); + } + return(false); +} + +bool CJsonObject::Get(int iWhich, uint32& uiValue) const +{ + cJSON* pJsonStruct = NULL; + if (m_pJsonData != NULL) + { + if (m_pJsonData->type == cJSON_Array) + { + pJsonStruct = cJSON_GetArrayItem(m_pJsonData, iWhich); + } + } + else if (m_pExternJsonDataRef != NULL) + { + if(m_pExternJsonDataRef->type == cJSON_Array) + { + pJsonStruct = cJSON_GetArrayItem(m_pExternJsonDataRef, iWhich); + } + } + if (pJsonStruct == NULL) + { + return(false); + } + if (pJsonStruct->type == cJSON_Int) + { + uiValue = (uint32)(pJsonStruct->valueint); + return(true); + } + else if (pJsonStruct->type == cJSON_Double) + { + uiValue = (uint32)(pJsonStruct->valuedouble); + return(true); + } + return(false); +} + +bool CJsonObject::Get(int iWhich, int64& llValue) const +{ + cJSON* pJsonStruct = NULL; + if (m_pJsonData != NULL) + { + if (m_pJsonData->type == cJSON_Array) + { + pJsonStruct = cJSON_GetArrayItem(m_pJsonData, iWhich); + } + } + else if (m_pExternJsonDataRef != NULL) + { + if(m_pExternJsonDataRef->type == cJSON_Array) + { + pJsonStruct = cJSON_GetArrayItem(m_pExternJsonDataRef, iWhich); + } + } + if (pJsonStruct == NULL) + { + return(false); + } + if (pJsonStruct->type == cJSON_Int) + { + llValue = (int64)(pJsonStruct->valueint); + return(true); + } + else if (pJsonStruct->type == cJSON_Double) + { + llValue = (int64)(pJsonStruct->valuedouble); + return(true); + } + return(false); +} + +bool CJsonObject::Get(int iWhich, uint64& ullValue) const +{ + cJSON* pJsonStruct = NULL; + if (m_pJsonData != NULL) + { + if (m_pJsonData->type == cJSON_Array) + { + pJsonStruct = cJSON_GetArrayItem(m_pJsonData, iWhich); + } + } + else if (m_pExternJsonDataRef != NULL) + { + if(m_pExternJsonDataRef->type == cJSON_Array) + { + pJsonStruct = cJSON_GetArrayItem(m_pExternJsonDataRef, iWhich); + } + } + if (pJsonStruct == NULL) + { + return(false); + } + if (pJsonStruct->type == cJSON_Int) + { + ullValue = (uint64)(pJsonStruct->valueint); + return(true); + } + else if (pJsonStruct->type == cJSON_Double) + { + ullValue = (uint64)(pJsonStruct->valuedouble); + return(true); + } + return(false); +} + +bool CJsonObject::Get(int iWhich, bool& bValue) const +{ + cJSON* pJsonStruct = NULL; + if (m_pJsonData != NULL) + { + if (m_pJsonData->type == cJSON_Array) + { + pJsonStruct = cJSON_GetArrayItem(m_pJsonData, iWhich); + } + } + else if (m_pExternJsonDataRef != NULL) + { + if(m_pExternJsonDataRef->type == cJSON_Array) + { + pJsonStruct = cJSON_GetArrayItem(m_pExternJsonDataRef, iWhich); + } + } + if (pJsonStruct == NULL) + { + return(false); + } + if (pJsonStruct->type > cJSON_True) + { + return(false); + } + bValue = pJsonStruct->type; + return(true); +} + +bool CJsonObject::Get(int iWhich, float& fValue) const +{ + cJSON* pJsonStruct = NULL; + if (m_pJsonData != NULL) + { + if (m_pJsonData->type == cJSON_Array) + { + pJsonStruct = cJSON_GetArrayItem(m_pJsonData, iWhich); + } + } + else if (m_pExternJsonDataRef != NULL) + { + if(m_pExternJsonDataRef->type == cJSON_Array) + { + pJsonStruct = cJSON_GetArrayItem(m_pExternJsonDataRef, iWhich); + } + } + if (pJsonStruct == NULL) + { + return(false); + } + if (pJsonStruct->type == cJSON_Double || pJsonStruct->type == cJSON_Int) + { + fValue = (float)(pJsonStruct->valuedouble); + return(true); + } + return(false); +} + +bool CJsonObject::Get(int iWhich, double& dValue) const +{ + cJSON* pJsonStruct = NULL; + if (m_pJsonData != NULL) + { + if (m_pJsonData->type == cJSON_Array) + { + pJsonStruct = cJSON_GetArrayItem(m_pJsonData, iWhich); + } + } + else if (m_pExternJsonDataRef != NULL) + { + if(m_pExternJsonDataRef->type == cJSON_Array) + { + pJsonStruct = cJSON_GetArrayItem(m_pExternJsonDataRef, iWhich); + } + } + if (pJsonStruct == NULL) + { + return(false); + } + if (pJsonStruct->type == cJSON_Double || pJsonStruct->type == cJSON_Int) + { + dValue = pJsonStruct->valuedouble; + return(true); + } + return(false); +} + +int CJsonObject::GetValueType(int iWhich) const +{ + cJSON* pJsonStruct = NULL; + if (m_pJsonData != NULL) + { + if (m_pJsonData->type == cJSON_Array) + { + pJsonStruct = cJSON_GetArrayItem(m_pJsonData, iWhich); + } + } + else if (m_pExternJsonDataRef != NULL) + { + if(m_pExternJsonDataRef->type == cJSON_Array) + { + pJsonStruct = cJSON_GetArrayItem(m_pExternJsonDataRef, iWhich); + } + } + if (pJsonStruct == NULL) + { + return(false); + } + return(pJsonStruct->type); +} + +bool CJsonObject::IsNull(int iWhich) const +{ + cJSON* pJsonStruct = NULL; + if (m_pJsonData != NULL) + { + if (m_pJsonData->type == cJSON_Array) + { + pJsonStruct = cJSON_GetArrayItem(m_pJsonData, iWhich); + } + } + else if (m_pExternJsonDataRef != NULL) + { + if(m_pExternJsonDataRef->type == cJSON_Array) + { + pJsonStruct = cJSON_GetArrayItem(m_pExternJsonDataRef, iWhich); + } + } + if (pJsonStruct == NULL) + { + return(false); + } + if (pJsonStruct->type != cJSON_NULL) + { + return(false); + } + return(true); +} + +bool CJsonObject::Add(const CJsonObject& oJsonObject) +{ + cJSON* pFocusData = NULL; + if (m_pJsonData != NULL) + { + pFocusData = m_pJsonData; + } + else if (m_pExternJsonDataRef != NULL) + { + pFocusData = m_pExternJsonDataRef; + } + else + { + m_pJsonData = cJSON_CreateArray(); + pFocusData = m_pJsonData; + } + + if (pFocusData == NULL) + { + m_strErrMsg = "json data is null!"; + return(false); + } + if (pFocusData->type != cJSON_Array) + { + m_strErrMsg = "not a json array! json object?"; + return(false); + } + cJSON* pJsonStruct = cJSON_Parse(oJsonObject.ToString().c_str(), &mc_pError); + if (pJsonStruct == NULL) + { + m_strErrMsg = std::string("prase json string error at ") + mc_pError; + return(false); + } + int iArraySizeBeforeAdd = cJSON_GetArraySize(pFocusData); + cJSON_AddItemToArray(pFocusData, pJsonStruct); + int iArraySizeAfterAdd = cJSON_GetArraySize(pFocusData); + if (iArraySizeAfterAdd == iArraySizeBeforeAdd) + { + return(false); + } + unsigned int uiLastIndex = (unsigned int)cJSON_GetArraySize(pFocusData) - 1; +#if __cplusplus < 201101L + for (std::map::iterator iter = m_mapJsonArrayRef.begin(); + iter != m_mapJsonArrayRef.end(); ) +#else + for (auto iter = m_mapJsonArrayRef.begin(); iter != m_mapJsonArrayRef.end(); ) +#endif + { + if (iter->first >= uiLastIndex) + { + if (iter->second != NULL) + { + delete (iter->second); + iter->second = NULL; + } + m_mapJsonArrayRef.erase(iter++); + } + else + { + iter++; + } + } + return(true); +} + +#if __cplusplus < 201101L +bool CJsonObject::AddWithMove(CJsonObject& oJsonObject) +{ + cJSON* pFocusData = NULL; + if (m_pJsonData != NULL) + { + pFocusData = m_pJsonData; + } + else if (m_pExternJsonDataRef != NULL) + { + pFocusData = m_pExternJsonDataRef; + } + else + { + m_pJsonData = cJSON_CreateArray(); + pFocusData = m_pJsonData; + } + + if (pFocusData == NULL) + { + m_strErrMsg = "json data is null!"; + return(false); + } + if (pFocusData->type != cJSON_Array) + { + m_strErrMsg = "not a json array! json object?"; + return(false); + } + cJSON* pJsonStruct = oJsonObject.m_pJsonData; + oJsonObject.m_pJsonData = NULL; + if (pJsonStruct == NULL) + { + m_strErrMsg = "can not move a non-independent(internal) CJsonObject from one to another."; + return(false); + } + int iArraySizeBeforeAdd = cJSON_GetArraySize(pFocusData); + cJSON_AddItemToArray(pFocusData, pJsonStruct); + int iArraySizeAfterAdd = cJSON_GetArraySize(pFocusData); + if (iArraySizeAfterAdd == iArraySizeBeforeAdd) + { + return(false); + } + unsigned int uiLastIndex = (unsigned int)cJSON_GetArraySize(pFocusData) - 1; + for (std::map::iterator iter = m_mapJsonArrayRef.begin(); iter != m_mapJsonArrayRef.end(); ) + { + if (iter->first >= uiLastIndex) + { + if (iter->second != NULL) + { + delete (iter->second); + iter->second = NULL; + } + m_mapJsonArrayRef.erase(iter++); + } + else + { + iter++; + } + } + return(true); +} +#else +bool CJsonObject::Add(CJsonObject&& oJsonObject) +{ + cJSON* pFocusData = NULL; + if (m_pJsonData != NULL) + { + pFocusData = m_pJsonData; + } + else if (m_pExternJsonDataRef != NULL) + { + pFocusData = m_pExternJsonDataRef; + } + else + { + m_pJsonData = cJSON_CreateArray(); + pFocusData = m_pJsonData; + } + + if (pFocusData == NULL) + { + m_strErrMsg = "json data is null!"; + return(false); + } + if (pFocusData->type != cJSON_Array) + { + m_strErrMsg = "not a json array! json object?"; + return(false); + } + cJSON* pJsonStruct = oJsonObject.m_pJsonData; + oJsonObject.m_pJsonData = NULL; + if (pJsonStruct == NULL) + { + m_strErrMsg = "can not move a non-independent(internal) CJsonObject from one to another."; + return(false); + } + int iArraySizeBeforeAdd = cJSON_GetArraySize(pFocusData); + cJSON_AddItemToArray(pFocusData, pJsonStruct); + int iArraySizeAfterAdd = cJSON_GetArraySize(pFocusData); + if (iArraySizeAfterAdd == iArraySizeBeforeAdd) + { + return(false); + } + unsigned int uiLastIndex = (unsigned int)cJSON_GetArraySize(pFocusData) - 1; + for (auto iter = m_mapJsonArrayRef.begin(); iter != m_mapJsonArrayRef.end(); ) + { + if (iter->first >= uiLastIndex) + { + if (iter->second != NULL) + { + delete (iter->second); + iter->second = NULL; + } + m_mapJsonArrayRef.erase(iter++); + } + else + { + iter++; + } + } + return(true); +} +#endif + +bool CJsonObject::Add(const std::string& strValue) +{ + cJSON* pFocusData = NULL; + if (m_pJsonData != NULL) + { + pFocusData = m_pJsonData; + } + else if (m_pExternJsonDataRef != NULL) + { + pFocusData = m_pExternJsonDataRef; + } + else + { + m_pJsonData = cJSON_CreateArray(); + pFocusData = m_pJsonData; + } + + if (pFocusData == NULL) + { + m_strErrMsg = "json data is null!"; + return(false); + } + if (pFocusData->type != cJSON_Array) + { + m_strErrMsg = "not a json array! json object?"; + return(false); + } + cJSON* pJsonStruct = cJSON_CreateString(strValue.c_str()); + if (pJsonStruct == NULL) + { + return(false); + } + int iArraySizeBeforeAdd = cJSON_GetArraySize(pFocusData); + cJSON_AddItemToArray(pFocusData, pJsonStruct); + int iArraySizeAfterAdd = cJSON_GetArraySize(pFocusData); + if (iArraySizeAfterAdd == iArraySizeBeforeAdd) + { + return(false); + } + return(true); +} + +bool CJsonObject::Add(int32 iValue) +{ + cJSON* pFocusData = NULL; + if (m_pJsonData != NULL) + { + pFocusData = m_pJsonData; + } + else if (m_pExternJsonDataRef != NULL) + { + pFocusData = m_pExternJsonDataRef; + } + else + { + m_pJsonData = cJSON_CreateArray(); + pFocusData = m_pJsonData; + } + + if (pFocusData == NULL) + { + m_strErrMsg = "json data is null!"; + return(false); + } + if (pFocusData->type != cJSON_Array) + { + m_strErrMsg = "not a json array! json object?"; + return(false); + } + cJSON* pJsonStruct = cJSON_CreateInt((uint64)iValue, -1); + if (pJsonStruct == NULL) + { + return(false); + } + int iArraySizeBeforeAdd = cJSON_GetArraySize(pFocusData); + cJSON_AddItemToArray(pFocusData, pJsonStruct); + int iArraySizeAfterAdd = cJSON_GetArraySize(pFocusData); + if (iArraySizeAfterAdd == iArraySizeBeforeAdd) + { + return(false); + } + return(true); +} + +bool CJsonObject::Add(uint32 uiValue) +{ + cJSON* pFocusData = NULL; + if (m_pJsonData != NULL) + { + pFocusData = m_pJsonData; + } + else if (m_pExternJsonDataRef != NULL) + { + pFocusData = m_pExternJsonDataRef; + } + else + { + m_pJsonData = cJSON_CreateArray(); + pFocusData = m_pJsonData; + } + + if (pFocusData == NULL) + { + m_strErrMsg = "json data is null!"; + return(false); + } + if (pFocusData->type != cJSON_Array) + { + m_strErrMsg = "not a json array! json object?"; + return(false); + } + cJSON* pJsonStruct = cJSON_CreateInt((uint64)uiValue, 1); + if (pJsonStruct == NULL) + { + return(false); + } + int iArraySizeBeforeAdd = cJSON_GetArraySize(pFocusData); + cJSON_AddItemToArray(pFocusData, pJsonStruct); + int iArraySizeAfterAdd = cJSON_GetArraySize(pFocusData); + if (iArraySizeAfterAdd == iArraySizeBeforeAdd) + { + return(false); + } + return(true); +} + +bool CJsonObject::Add(int64 llValue) +{ + cJSON* pFocusData = NULL; + if (m_pJsonData != NULL) + { + pFocusData = m_pJsonData; + } + else if (m_pExternJsonDataRef != NULL) + { + pFocusData = m_pExternJsonDataRef; + } + else + { + m_pJsonData = cJSON_CreateArray(); + pFocusData = m_pJsonData; + } + + if (pFocusData == NULL) + { + m_strErrMsg = "json data is null!"; + return(false); + } + if (pFocusData->type != cJSON_Array) + { + m_strErrMsg = "not a json array! json object?"; + return(false); + } + cJSON* pJsonStruct = cJSON_CreateInt((uint64)llValue, -1); + if (pJsonStruct == NULL) + { + return(false); + } + int iArraySizeBeforeAdd = cJSON_GetArraySize(pFocusData); + cJSON_AddItemToArray(pFocusData, pJsonStruct); + int iArraySizeAfterAdd = cJSON_GetArraySize(pFocusData); + if (iArraySizeAfterAdd == iArraySizeBeforeAdd) + { + return(false); + } + return(true); +} + +bool CJsonObject::Add(uint64 ullValue) +{ + cJSON* pFocusData = NULL; + if (m_pJsonData != NULL) + { + pFocusData = m_pJsonData; + } + else if (m_pExternJsonDataRef != NULL) + { + pFocusData = m_pExternJsonDataRef; + } + else + { + m_pJsonData = cJSON_CreateArray(); + pFocusData = m_pJsonData; + } + + if (pFocusData == NULL) + { + m_strErrMsg = "json data is null!"; + return(false); + } + if (pFocusData->type != cJSON_Array) + { + m_strErrMsg = "not a json array! json object?"; + return(false); + } + cJSON* pJsonStruct = cJSON_CreateInt((uint64)ullValue, 1); + if (pJsonStruct == NULL) + { + return(false); + } + int iArraySizeBeforeAdd = cJSON_GetArraySize(pFocusData); + cJSON_AddItemToArray(pFocusData, pJsonStruct); + int iArraySizeAfterAdd = cJSON_GetArraySize(pFocusData); + if (iArraySizeAfterAdd == iArraySizeBeforeAdd) + { + return(false); + } + return(true); +} + +bool CJsonObject::Add(int iAnywhere, bool bValue) +{ + cJSON* pFocusData = NULL; + if (m_pJsonData != NULL) + { + pFocusData = m_pJsonData; + } + else if (m_pExternJsonDataRef != NULL) + { + pFocusData = m_pExternJsonDataRef; + } + else + { + m_pJsonData = cJSON_CreateArray(); + pFocusData = m_pJsonData; + } + + if (pFocusData == NULL) + { + m_strErrMsg = "json data is null!"; + return(false); + } + if (pFocusData->type != cJSON_Array) + { + m_strErrMsg = "not a json array! json object?"; + return(false); + } + cJSON* pJsonStruct = cJSON_CreateBool(bValue); + if (pJsonStruct == NULL) + { + return(false); + } + int iArraySizeBeforeAdd = cJSON_GetArraySize(pFocusData); + cJSON_AddItemToArray(pFocusData, pJsonStruct); + int iArraySizeAfterAdd = cJSON_GetArraySize(pFocusData); + if (iArraySizeAfterAdd == iArraySizeBeforeAdd) + { + return(false); + } + return(true); +} + +bool CJsonObject::Add(float fValue) +{ + cJSON* pFocusData = NULL; + if (m_pJsonData != NULL) + { + pFocusData = m_pJsonData; + } + else if (m_pExternJsonDataRef != NULL) + { + pFocusData = m_pExternJsonDataRef; + } + else + { + m_pJsonData = cJSON_CreateArray(); + pFocusData = m_pJsonData; + } + + if (pFocusData == NULL) + { + m_strErrMsg = "json data is null!"; + return(false); + } + if (pFocusData->type != cJSON_Array) + { + m_strErrMsg = "not a json array! json object?"; + return(false); + } + cJSON* pJsonStruct = cJSON_CreateDouble((double)fValue, -1); + if (pJsonStruct == NULL) + { + return(false); + } + int iArraySizeBeforeAdd = cJSON_GetArraySize(pFocusData); + cJSON_AddItemToArray(pFocusData, pJsonStruct); + int iArraySizeAfterAdd = cJSON_GetArraySize(pFocusData); + if (iArraySizeAfterAdd == iArraySizeBeforeAdd) + { + return(false); + } + return(true); +} + +bool CJsonObject::Add(double dValue) +{ + cJSON* pFocusData = NULL; + if (m_pJsonData != NULL) + { + pFocusData = m_pJsonData; + } + else if (m_pExternJsonDataRef != NULL) + { + pFocusData = m_pExternJsonDataRef; + } + else + { + m_pJsonData = cJSON_CreateArray(); + pFocusData = m_pJsonData; + } + + if (pFocusData == NULL) + { + m_strErrMsg = "json data is null!"; + return(false); + } + if (pFocusData->type != cJSON_Array) + { + m_strErrMsg = "not a json array! json object?"; + return(false); + } + cJSON* pJsonStruct = cJSON_CreateDouble((double)dValue, -1); + if (pJsonStruct == NULL) + { + return(false); + } + int iArraySizeBeforeAdd = cJSON_GetArraySize(pFocusData); + cJSON_AddItemToArray(pFocusData, pJsonStruct); + int iArraySizeAfterAdd = cJSON_GetArraySize(pFocusData); + if (iArraySizeAfterAdd == iArraySizeBeforeAdd) + { + return(false); + } + return(true); +} + +bool CJsonObject::AddNull() +{ + cJSON* pFocusData = NULL; + if (m_pJsonData != NULL) + { + pFocusData = m_pJsonData; + } + else if (m_pExternJsonDataRef != NULL) + { + pFocusData = m_pExternJsonDataRef; + } + else + { + m_pJsonData = cJSON_CreateArray(); + pFocusData = m_pJsonData; + } + + if (pFocusData == NULL) + { + m_strErrMsg = "json data is null!"; + return(false); + } + if (pFocusData->type != cJSON_Array) + { + m_strErrMsg = "not a json array! json object?"; + return(false); + } + cJSON* pJsonStruct = cJSON_CreateNull(); + if (pJsonStruct == NULL) + { + return(false); + } + int iArraySizeBeforeAdd = cJSON_GetArraySize(pFocusData); + cJSON_AddItemToArray(pFocusData, pJsonStruct); + int iArraySizeAfterAdd = cJSON_GetArraySize(pFocusData); + if (iArraySizeAfterAdd == iArraySizeBeforeAdd) + { + return(false); + } + return(true); +} + +bool CJsonObject::AddAsFirst(const CJsonObject& oJsonObject) +{ + cJSON* pFocusData = NULL; + if (m_pJsonData != NULL) + { + pFocusData = m_pJsonData; + } + else if (m_pExternJsonDataRef != NULL) + { + pFocusData = m_pExternJsonDataRef; + } + else + { + m_pJsonData = cJSON_CreateArray(); + pFocusData = m_pJsonData; + } + + if (pFocusData == NULL) + { + m_strErrMsg = "json data is null!"; + return(false); + } + if (pFocusData->type != cJSON_Array) + { + m_strErrMsg = "not a json array! json object?"; + return(false); + } + cJSON* pJsonStruct = cJSON_Parse(oJsonObject.ToString().c_str(), &mc_pError); + if (pJsonStruct == NULL) + { + m_strErrMsg = std::string("prase json string error at ") + mc_pError; + return(false); + } + int iArraySizeBeforeAdd = cJSON_GetArraySize(pFocusData); + cJSON_AddItemToArrayHead(pFocusData, pJsonStruct); + int iArraySizeAfterAdd = cJSON_GetArraySize(pFocusData); + if (iArraySizeAfterAdd == iArraySizeBeforeAdd) + { + return(false); + } +#if __cplusplus < 201101L + for (std::map::iterator iter = m_mapJsonArrayRef.begin(); + iter != m_mapJsonArrayRef.end(); ) +#else + for (auto iter = m_mapJsonArrayRef.begin(); iter != m_mapJsonArrayRef.end(); ) +#endif + { + if (iter->second != NULL) + { + delete (iter->second); + iter->second = NULL; + } + m_mapJsonArrayRef.erase(iter++); + } + return(true); +} + +#if __cplusplus < 201101L +bool CJsonObject::AddAsFirstWithMove(CJsonObject& oJsonObject) +{ + cJSON* pFocusData = NULL; + if (m_pJsonData != NULL) + { + pFocusData = m_pJsonData; + } + else if (m_pExternJsonDataRef != NULL) + { + pFocusData = m_pExternJsonDataRef; + } + else + { + m_pJsonData = cJSON_CreateArray(); + pFocusData = m_pJsonData; + } + + if (pFocusData == NULL) + { + m_strErrMsg = "json data is null!"; + return(false); + } + if (pFocusData->type != cJSON_Array) + { + m_strErrMsg = "not a json array! json object?"; + return(false); + } + cJSON* pJsonStruct = oJsonObject.m_pJsonData; + oJsonObject.m_pJsonData = NULL; + if (pJsonStruct == NULL) + { + m_strErrMsg = "can not move a non-independent(internal) CJsonObject from one to another."; + return(false); + } + int iArraySizeBeforeAdd = cJSON_GetArraySize(pFocusData); + cJSON_AddItemToArrayHead(pFocusData, pJsonStruct); + int iArraySizeAfterAdd = cJSON_GetArraySize(pFocusData); + if (iArraySizeAfterAdd == iArraySizeBeforeAdd) + { + return(false); + } + for (std::map::iterator iter = m_mapJsonArrayRef.begin(); iter != m_mapJsonArrayRef.end(); ) + { + if (iter->second != NULL) + { + delete (iter->second); + iter->second = NULL; + } + m_mapJsonArrayRef.erase(iter++); + } + return(true); +} +#else +bool CJsonObject::AddAsFirst(CJsonObject&& oJsonObject) +{ + cJSON* pFocusData = NULL; + if (m_pJsonData != NULL) + { + pFocusData = m_pJsonData; + } + else if (m_pExternJsonDataRef != NULL) + { + pFocusData = m_pExternJsonDataRef; + } + else + { + m_pJsonData = cJSON_CreateArray(); + pFocusData = m_pJsonData; + } + + if (pFocusData == NULL) + { + m_strErrMsg = "json data is null!"; + return(false); + } + if (pFocusData->type != cJSON_Array) + { + m_strErrMsg = "not a json array! json object?"; + return(false); + } + cJSON* pJsonStruct = oJsonObject.m_pJsonData; + oJsonObject.m_pJsonData = NULL; + if (pJsonStruct == NULL) + { + m_strErrMsg = "can not move a non-independent(internal) CJsonObject from one to another."; + return(false); + } + int iArraySizeBeforeAdd = cJSON_GetArraySize(pFocusData); + cJSON_AddItemToArrayHead(pFocusData, pJsonStruct); + int iArraySizeAfterAdd = cJSON_GetArraySize(pFocusData); + if (iArraySizeAfterAdd == iArraySizeBeforeAdd) + { + return(false); + } + for (auto iter = m_mapJsonArrayRef.begin(); iter != m_mapJsonArrayRef.end(); ) + { + if (iter->second != NULL) + { + delete (iter->second); + iter->second = NULL; + } + m_mapJsonArrayRef.erase(iter++); + } + return(true); +} +#endif + +bool CJsonObject::AddAsFirst(const std::string& strValue) +{ + cJSON* pFocusData = NULL; + if (m_pJsonData != NULL) + { + pFocusData = m_pJsonData; + } + else if (m_pExternJsonDataRef != NULL) + { + pFocusData = m_pExternJsonDataRef; + } + else + { + m_pJsonData = cJSON_CreateArray(); + pFocusData = m_pJsonData; + } + + if (pFocusData == NULL) + { + m_strErrMsg = "json data is null!"; + return(false); + } + if (pFocusData->type != cJSON_Array) + { + m_strErrMsg = "not a json array! json object?"; + return(false); + } + cJSON* pJsonStruct = cJSON_CreateString(strValue.c_str()); + if (pJsonStruct == NULL) + { + return(false); + } + int iArraySizeBeforeAdd = cJSON_GetArraySize(pFocusData); + cJSON_AddItemToArrayHead(pFocusData, pJsonStruct); + int iArraySizeAfterAdd = cJSON_GetArraySize(pFocusData); + if (iArraySizeAfterAdd == iArraySizeBeforeAdd) + { + return(false); + } + return(true); +} + +bool CJsonObject::AddAsFirst(int32 iValue) +{ + cJSON* pFocusData = NULL; + if (m_pJsonData != NULL) + { + pFocusData = m_pJsonData; + } + else if (m_pExternJsonDataRef != NULL) + { + pFocusData = m_pExternJsonDataRef; + } + else + { + m_pJsonData = cJSON_CreateArray(); + pFocusData = m_pJsonData; + } + + if (pFocusData == NULL) + { + m_strErrMsg = "json data is null!"; + return(false); + } + if (pFocusData->type != cJSON_Array) + { + m_strErrMsg = "not a json array! json object?"; + return(false); + } + cJSON* pJsonStruct = cJSON_CreateInt((uint64)iValue, -1); + if (pJsonStruct == NULL) + { + return(false); + } + int iArraySizeBeforeAdd = cJSON_GetArraySize(pFocusData); + cJSON_AddItemToArrayHead(pFocusData, pJsonStruct); + int iArraySizeAfterAdd = cJSON_GetArraySize(pFocusData); + if (iArraySizeAfterAdd == iArraySizeBeforeAdd) + { + return(false); + } + return(true); +} + +bool CJsonObject::AddAsFirst(uint32 uiValue) +{ + cJSON* pFocusData = NULL; + if (m_pJsonData != NULL) + { + pFocusData = m_pJsonData; + } + else if (m_pExternJsonDataRef != NULL) + { + pFocusData = m_pExternJsonDataRef; + } + else + { + m_pJsonData = cJSON_CreateArray(); + pFocusData = m_pJsonData; + } + + if (pFocusData == NULL) + { + m_strErrMsg = "json data is null!"; + return(false); + } + if (pFocusData->type != cJSON_Array) + { + m_strErrMsg = "not a json array! json object?"; + return(false); + } + cJSON* pJsonStruct = cJSON_CreateInt((uint64)uiValue, -1); + if (pJsonStruct == NULL) + { + return(false); + } + int iArraySizeBeforeAdd = cJSON_GetArraySize(pFocusData); + cJSON_AddItemToArrayHead(pFocusData, pJsonStruct); + int iArraySizeAfterAdd = cJSON_GetArraySize(pFocusData); + if (iArraySizeAfterAdd == iArraySizeBeforeAdd) + { + return(false); + } + return(true); +} + +bool CJsonObject::AddAsFirst(int64 llValue) +{ + cJSON* pFocusData = NULL; + if (m_pJsonData != NULL) + { + pFocusData = m_pJsonData; + } + else if (m_pExternJsonDataRef != NULL) + { + pFocusData = m_pExternJsonDataRef; + } + else + { + m_pJsonData = cJSON_CreateArray(); + pFocusData = m_pJsonData; + } + + if (pFocusData == NULL) + { + m_strErrMsg = "json data is null!"; + return(false); + } + if (pFocusData->type != cJSON_Array) + { + m_strErrMsg = "not a json array! json object?"; + return(false); + } + cJSON* pJsonStruct = cJSON_CreateInt((uint64)llValue, -1); + if (pJsonStruct == NULL) + { + return(false); + } + int iArraySizeBeforeAdd = cJSON_GetArraySize(pFocusData); + cJSON_AddItemToArrayHead(pFocusData, pJsonStruct); + int iArraySizeAfterAdd = cJSON_GetArraySize(pFocusData); + if (iArraySizeAfterAdd == iArraySizeBeforeAdd) + { + return(false); + } + return(true); +} + +bool CJsonObject::AddAsFirst(uint64 ullValue) +{ + cJSON* pFocusData = NULL; + if (m_pJsonData != NULL) + { + pFocusData = m_pJsonData; + } + else if (m_pExternJsonDataRef != NULL) + { + pFocusData = m_pExternJsonDataRef; + } + else + { + m_pJsonData = cJSON_CreateArray(); + pFocusData = m_pJsonData; + } + + if (pFocusData == NULL) + { + m_strErrMsg = "json data is null!"; + return(false); + } + if (pFocusData->type != cJSON_Array) + { + m_strErrMsg = "not a json array! json object?"; + return(false); + } + cJSON* pJsonStruct = cJSON_CreateInt((uint64)ullValue, -1); + if (pJsonStruct == NULL) + { + return(false); + } + int iArraySizeBeforeAdd = cJSON_GetArraySize(pFocusData); + cJSON_AddItemToArrayHead(pFocusData, pJsonStruct); + int iArraySizeAfterAdd = cJSON_GetArraySize(pFocusData); + if (iArraySizeAfterAdd == iArraySizeBeforeAdd) + { + return(false); + } + return(true); +} + +bool CJsonObject::AddAsFirst(int iAnywhere, bool bValue) +{ + cJSON* pFocusData = NULL; + if (m_pJsonData != NULL) + { + pFocusData = m_pJsonData; + } + else if (m_pExternJsonDataRef != NULL) + { + pFocusData = m_pExternJsonDataRef; + } + else + { + m_pJsonData = cJSON_CreateArray(); + pFocusData = m_pJsonData; + } + + if (pFocusData == NULL) + { + m_strErrMsg = "json data is null!"; + return(false); + } + if (pFocusData->type != cJSON_Array) + { + m_strErrMsg = "not a json array! json object?"; + return(false); + } + cJSON* pJsonStruct = cJSON_CreateBool(bValue); + if (pJsonStruct == NULL) + { + return(false); + } + int iArraySizeBeforeAdd = cJSON_GetArraySize(pFocusData); + cJSON_AddItemToArrayHead(pFocusData, pJsonStruct); + int iArraySizeAfterAdd = cJSON_GetArraySize(pFocusData); + if (iArraySizeAfterAdd == iArraySizeBeforeAdd) + { + return(false); + } + return(true); +} + +bool CJsonObject::AddAsFirst(float fValue) +{ + cJSON* pFocusData = NULL; + if (m_pJsonData != NULL) + { + pFocusData = m_pJsonData; + } + else if (m_pExternJsonDataRef != NULL) + { + pFocusData = m_pExternJsonDataRef; + } + else + { + m_pJsonData = cJSON_CreateArray(); + pFocusData = m_pJsonData; + } + + if (pFocusData == NULL) + { + m_strErrMsg = "json data is null!"; + return(false); + } + if (pFocusData->type != cJSON_Array) + { + m_strErrMsg = "not a json array! json object?"; + return(false); + } + cJSON* pJsonStruct = cJSON_CreateDouble((double)fValue, -1); + if (pJsonStruct == NULL) + { + return(false); + } + int iArraySizeBeforeAdd = cJSON_GetArraySize(pFocusData); + cJSON_AddItemToArrayHead(pFocusData, pJsonStruct); + int iArraySizeAfterAdd = cJSON_GetArraySize(pFocusData); + if (iArraySizeAfterAdd == iArraySizeBeforeAdd) + { + return(false); + } + return(true); +} + +bool CJsonObject::AddAsFirst(double dValue) +{ + cJSON* pFocusData = NULL; + if (m_pJsonData != NULL) + { + pFocusData = m_pJsonData; + } + else if (m_pExternJsonDataRef != NULL) + { + pFocusData = m_pExternJsonDataRef; + } + else + { + m_pJsonData = cJSON_CreateArray(); + pFocusData = m_pJsonData; + } + + if (pFocusData == NULL) + { + m_strErrMsg = "json data is null!"; + return(false); + } + if (pFocusData->type != cJSON_Array) + { + m_strErrMsg = "not a json array! json object?"; + return(false); + } + cJSON* pJsonStruct = cJSON_CreateDouble((double)dValue, -1); + if (pJsonStruct == NULL) + { + return(false); + } + int iArraySizeBeforeAdd = cJSON_GetArraySize(pFocusData); + cJSON_AddItemToArrayHead(pFocusData, pJsonStruct); + int iArraySizeAfterAdd = cJSON_GetArraySize(pFocusData); + if (iArraySizeAfterAdd == iArraySizeBeforeAdd) + { + return(false); + } + return(true); +} + +bool CJsonObject::AddNullAsFirst() +{ + cJSON* pFocusData = NULL; + if (m_pJsonData != NULL) + { + pFocusData = m_pJsonData; + } + else if (m_pExternJsonDataRef != NULL) + { + pFocusData = m_pExternJsonDataRef; + } + else + { + m_pJsonData = cJSON_CreateArray(); + pFocusData = m_pJsonData; + } + + if (pFocusData == NULL) + { + m_strErrMsg = "json data is null!"; + return(false); + } + if (pFocusData->type != cJSON_Array) + { + m_strErrMsg = "not a json array! json object?"; + return(false); + } + cJSON* pJsonStruct = cJSON_CreateNull(); + if (pJsonStruct == NULL) + { + return(false); + } + int iArraySizeBeforeAdd = cJSON_GetArraySize(pFocusData); + cJSON_AddItemToArrayHead(pFocusData, pJsonStruct); + int iArraySizeAfterAdd = cJSON_GetArraySize(pFocusData); + if (iArraySizeAfterAdd == iArraySizeBeforeAdd) + { + return(false); + } + return(true); +} + +bool CJsonObject::Delete(int iWhich) +{ + cJSON* pFocusData = NULL; + if (m_pJsonData == NULL) + { + pFocusData = m_pExternJsonDataRef; + } + else + { + pFocusData = m_pJsonData; + } + if (pFocusData == NULL) + { + m_strErrMsg = "json data is null!"; + return(false); + } + if (pFocusData->type != cJSON_Array) + { + m_strErrMsg = "not a json array! json object?"; + return(false); + } + cJSON_DeleteItemFromArray(pFocusData, iWhich); +#if __cplusplus < 201101L + for (std::map::iterator iter = m_mapJsonArrayRef.begin(); + iter != m_mapJsonArrayRef.end(); ) +#else + for (auto iter = m_mapJsonArrayRef.begin(); iter != m_mapJsonArrayRef.end(); ) +#endif + { + if (iter->first >= (unsigned int)iWhich) + { + if (iter->second != NULL) + { + delete (iter->second); + iter->second = NULL; + } + m_mapJsonArrayRef.erase(iter++); + } + else + { + iter++; + } + } + return(true); +} + +bool CJsonObject::Replace(int iWhich, const CJsonObject& oJsonObject) +{ + cJSON* pFocusData = NULL; + if (m_pJsonData == NULL) + { + pFocusData = m_pExternJsonDataRef; + } + else + { + pFocusData = m_pJsonData; + } + if (pFocusData == NULL) + { + m_strErrMsg = "json data is null!"; + return(false); + } + if (pFocusData->type != cJSON_Array) + { + m_strErrMsg = "not a json array! json object?"; + return(false); + } + cJSON* pJsonStruct = cJSON_Parse(oJsonObject.ToString().c_str(), &mc_pError); + if (pJsonStruct == NULL) + { + m_strErrMsg = std::string("prase json string error at ") + mc_pError; + return(false); + } + cJSON_ReplaceItemInArray(pFocusData, iWhich, pJsonStruct); + if (cJSON_GetArrayItem(pFocusData, iWhich) == NULL) + { + return(false); + } +#if __cplusplus < 201101L + std::map::iterator iter = m_mapJsonArrayRef.find(iWhich); +#else + auto iter = m_mapJsonArrayRef.find(iWhich); +#endif + if (iter != m_mapJsonArrayRef.end()) + { + if (iter->second != NULL) + { + delete (iter->second); + iter->second = NULL; + } + m_mapJsonArrayRef.erase(iter); + } + return(true); +} + +#if __cplusplus < 201101L +bool CJsonObject::ReplaceWithMove(int iWhich, CJsonObject& oJsonObject) +{ + cJSON* pFocusData = NULL; + if (m_pJsonData == NULL) + { + pFocusData = m_pExternJsonDataRef; + } + else + { + pFocusData = m_pJsonData; + } + if (pFocusData == NULL) + { + m_strErrMsg = "json data is null!"; + return(false); + } + if (pFocusData->type != cJSON_Array) + { + m_strErrMsg = "not a json array! json object?"; + return(false); + } + cJSON* pJsonStruct = oJsonObject.m_pJsonData; + oJsonObject.m_pJsonData = NULL; + if (pJsonStruct == NULL) + { + m_strErrMsg = "can not move a non-independent(internal) CJsonObject from one to another."; + return(false); + } + cJSON_ReplaceItemInArray(pFocusData, iWhich, pJsonStruct); + if (cJSON_GetArrayItem(pFocusData, iWhich) == NULL) + { + return(false); + } + std::map::iterator iter = m_mapJsonArrayRef.find(iWhich); + if (iter != m_mapJsonArrayRef.end()) + { + if (iter->second != NULL) + { + delete (iter->second); + iter->second = NULL; + } + m_mapJsonArrayRef.erase(iter); + } + return(true); +} +#else +bool CJsonObject::Replace(int iWhich, CJsonObject&& oJsonObject) +{ + cJSON* pFocusData = NULL; + if (m_pJsonData == NULL) + { + pFocusData = m_pExternJsonDataRef; + } + else + { + pFocusData = m_pJsonData; + } + if (pFocusData == NULL) + { + m_strErrMsg = "json data is null!"; + return(false); + } + if (pFocusData->type != cJSON_Array) + { + m_strErrMsg = "not a json array! json object?"; + return(false); + } + cJSON* pJsonStruct = oJsonObject.m_pJsonData; + oJsonObject.m_pJsonData = NULL; + if (pJsonStruct == NULL) + { + m_strErrMsg = "can not move a non-independent(internal) CJsonObject from one to another."; + return(false); + } + cJSON_ReplaceItemInArray(pFocusData, iWhich, pJsonStruct); + if (cJSON_GetArrayItem(pFocusData, iWhich) == NULL) + { + return(false); + } + auto iter = m_mapJsonArrayRef.find(iWhich); + if (iter != m_mapJsonArrayRef.end()) + { + if (iter->second != NULL) + { + delete (iter->second); + iter->second = NULL; + } + m_mapJsonArrayRef.erase(iter); + } + return(true); +} +#endif + +bool CJsonObject::Replace(int iWhich, const std::string& strValue) +{ + cJSON* pFocusData = NULL; + if (m_pJsonData == NULL) + { + pFocusData = m_pExternJsonDataRef; + } + else + { + pFocusData = m_pJsonData; + } + if (pFocusData == NULL) + { + m_strErrMsg = "json data is null!"; + return(false); + } + if (pFocusData->type != cJSON_Array) + { + m_strErrMsg = "not a json array! json object?"; + return(false); + } + cJSON* pJsonStruct = cJSON_CreateString(strValue.c_str()); + if (pJsonStruct == NULL) + { + return(false); + } +#if __cplusplus < 201101L + std::map::iterator iter = m_mapJsonArrayRef.find(iWhich); +#else + auto iter = m_mapJsonArrayRef.find(iWhich); +#endif + if (iter != m_mapJsonArrayRef.end()) + { + if (iter->second != NULL) + { + delete (iter->second); + iter->second = NULL; + } + m_mapJsonArrayRef.erase(iter); + } + cJSON_ReplaceItemInArray(pFocusData, iWhich, pJsonStruct); + if (cJSON_GetArrayItem(pFocusData, iWhich) == NULL) + { + return(false); + } + return(true); +} + +bool CJsonObject::Replace(int iWhich, int32 iValue) +{ + cJSON* pFocusData = NULL; + if (m_pJsonData == NULL) + { + pFocusData = m_pExternJsonDataRef; + } + else + { + pFocusData = m_pJsonData; + } + if (pFocusData == NULL) + { + m_strErrMsg = "json data is null!"; + return(false); + } + if (pFocusData->type != cJSON_Array) + { + m_strErrMsg = "not a json array! json object?"; + return(false); + } + cJSON* pJsonStruct = cJSON_CreateInt((uint64)iValue, -1); + if (pJsonStruct == NULL) + { + return(false); + } +#if __cplusplus < 201101L + std::map::iterator iter = m_mapJsonArrayRef.find(iWhich); +#else + auto iter = m_mapJsonArrayRef.find(iWhich); +#endif + if (iter != m_mapJsonArrayRef.end()) + { + if (iter->second != NULL) + { + delete (iter->second); + iter->second = NULL; + } + m_mapJsonArrayRef.erase(iter); + } + cJSON_ReplaceItemInArray(pFocusData, iWhich, pJsonStruct); + if (cJSON_GetArrayItem(pFocusData, iWhich) == NULL) + { + return(false); + } + return(true); +} + +bool CJsonObject::Replace(int iWhich, uint32 uiValue) +{ + cJSON* pFocusData = NULL; + if (m_pJsonData == NULL) + { + pFocusData = m_pExternJsonDataRef; + } + else + { + pFocusData = m_pJsonData; + } + if (pFocusData == NULL) + { + m_strErrMsg = "json data is null!"; + return(false); + } + if (pFocusData->type != cJSON_Array) + { + m_strErrMsg = "not a json array! json object?"; + return(false); + } + cJSON* pJsonStruct = cJSON_CreateInt((uint64)uiValue, 1); + if (pJsonStruct == NULL) + { + return(false); + } +#if __cplusplus < 201101L + std::map::iterator iter = m_mapJsonArrayRef.find(iWhich); +#else + auto iter = m_mapJsonArrayRef.find(iWhich); +#endif + if (iter != m_mapJsonArrayRef.end()) + { + if (iter->second != NULL) + { + delete (iter->second); + iter->second = NULL; + } + m_mapJsonArrayRef.erase(iter); + } + cJSON_ReplaceItemInArray(pFocusData, iWhich, pJsonStruct); + if (cJSON_GetArrayItem(pFocusData, iWhich) == NULL) + { + return(false); + } + return(true); +} + +bool CJsonObject::Replace(int iWhich, int64 llValue) +{ + cJSON* pFocusData = NULL; + if (m_pJsonData == NULL) + { + pFocusData = m_pExternJsonDataRef; + } + else + { + pFocusData = m_pJsonData; + } + if (pFocusData == NULL) + { + m_strErrMsg = "json data is null!"; + return(false); + } + if (pFocusData->type != cJSON_Array) + { + m_strErrMsg = "not a json array! json object?"; + return(false); + } + cJSON* pJsonStruct = cJSON_CreateInt((uint64)((uint64)llValue), -1); + if (pJsonStruct == NULL) + { + return(false); + } +#if __cplusplus < 201101L + std::map::iterator iter = m_mapJsonArrayRef.find(iWhich); +#else + auto iter = m_mapJsonArrayRef.find(iWhich); +#endif + if (iter != m_mapJsonArrayRef.end()) + { + if (iter->second != NULL) + { + delete (iter->second); + iter->second = NULL; + } + m_mapJsonArrayRef.erase(iter); + } + cJSON_ReplaceItemInArray(pFocusData, iWhich, pJsonStruct); + if (cJSON_GetArrayItem(pFocusData, iWhich) == NULL) + { + return(false); + } + return(true); +} + +bool CJsonObject::Replace(int iWhich, uint64 ullValue) +{ + cJSON* pFocusData = NULL; + if (m_pJsonData == NULL) + { + pFocusData = m_pExternJsonDataRef; + } + else + { + pFocusData = m_pJsonData; + } + if (pFocusData == NULL) + { + m_strErrMsg = "json data is null!"; + return(false); + } + if (pFocusData->type != cJSON_Array) + { + m_strErrMsg = "not a json array! json object?"; + return(false); + } + cJSON* pJsonStruct = cJSON_CreateInt((uint64)ullValue, 1); + if (pJsonStruct == NULL) + { + return(false); + } +#if __cplusplus < 201101L + std::map::iterator iter = m_mapJsonArrayRef.find(iWhich); +#else + auto iter = m_mapJsonArrayRef.find(iWhich); +#endif + if (iter != m_mapJsonArrayRef.end()) + { + if (iter->second != NULL) + { + delete (iter->second); + iter->second = NULL; + } + m_mapJsonArrayRef.erase(iter); + } + cJSON_ReplaceItemInArray(pFocusData, iWhich, pJsonStruct); + if (cJSON_GetArrayItem(pFocusData, iWhich) == NULL) + { + return(false); + } + return(true); +} + +bool CJsonObject::Replace(int iWhich, bool bValue, bool bValueAgain) +{ + cJSON* pFocusData = NULL; + if (m_pJsonData == NULL) + { + pFocusData = m_pExternJsonDataRef; + } + else + { + pFocusData = m_pJsonData; + } + if (pFocusData == NULL) + { + m_strErrMsg = "json data is null!"; + return(false); + } + if (pFocusData->type != cJSON_Array) + { + m_strErrMsg = "not a json array! json object?"; + return(false); + } + cJSON* pJsonStruct = cJSON_CreateBool(bValue); + if (pJsonStruct == NULL) + { + return(false); + } +#if __cplusplus < 201101L + std::map::iterator iter = m_mapJsonArrayRef.find(iWhich); +#else + auto iter = m_mapJsonArrayRef.find(iWhich); +#endif + if (iter != m_mapJsonArrayRef.end()) + { + if (iter->second != NULL) + { + delete (iter->second); + iter->second = NULL; + } + m_mapJsonArrayRef.erase(iter); + } + cJSON_ReplaceItemInArray(pFocusData, iWhich, pJsonStruct); + if (cJSON_GetArrayItem(pFocusData, iWhich) == NULL) + { + return(false); + } + return(true); +} + +bool CJsonObject::Replace(int iWhich, float fValue) +{ + cJSON* pFocusData = NULL; + if (m_pJsonData == NULL) + { + pFocusData = m_pExternJsonDataRef; + } + else + { + pFocusData = m_pJsonData; + } + if (pFocusData == NULL) + { + m_strErrMsg = "json data is null!"; + return(false); + } + if (pFocusData->type != cJSON_Array) + { + m_strErrMsg = "not a json array! json object?"; + return(false); + } + cJSON* pJsonStruct = cJSON_CreateDouble((double)fValue, -1); + if (pJsonStruct == NULL) + { + return(false); + } +#if __cplusplus < 201101L + std::map::iterator iter = m_mapJsonArrayRef.find(iWhich); +#else + auto iter = m_mapJsonArrayRef.find(iWhich); +#endif + if (iter != m_mapJsonArrayRef.end()) + { + if (iter->second != NULL) + { + delete (iter->second); + iter->second = NULL; + } + m_mapJsonArrayRef.erase(iter); + } + cJSON_ReplaceItemInArray(pFocusData, iWhich, pJsonStruct); + if (cJSON_GetArrayItem(pFocusData, iWhich) == NULL) + { + return(false); + } + return(true); +} + +bool CJsonObject::Replace(int iWhich, double dValue) +{ + cJSON* pFocusData = NULL; + if (m_pJsonData == NULL) + { + pFocusData = m_pExternJsonDataRef; + } + else + { + pFocusData = m_pJsonData; + } + if (pFocusData == NULL) + { + m_strErrMsg = "json data is null!"; + return(false); + } + if (pFocusData->type != cJSON_Array) + { + m_strErrMsg = "not a json array! json object?"; + return(false); + } + cJSON* pJsonStruct = cJSON_CreateDouble((double)dValue, -1); + if (pJsonStruct == NULL) + { + return(false); + } +#if __cplusplus < 201101L + std::map::iterator iter = m_mapJsonArrayRef.find(iWhich); +#else + auto iter = m_mapJsonArrayRef.find(iWhich); +#endif + if (iter != m_mapJsonArrayRef.end()) + { + if (iter->second != NULL) + { + delete (iter->second); + iter->second = NULL; + } + m_mapJsonArrayRef.erase(iter); + } + cJSON_ReplaceItemInArray(pFocusData, iWhich, pJsonStruct); + if (cJSON_GetArrayItem(pFocusData, iWhich) == NULL) + { + return(false); + } + return(true); +} + +bool CJsonObject::ReplaceWithNull(int iWhich) +{ + cJSON* pFocusData = NULL; + if (m_pJsonData == NULL) + { + pFocusData = m_pExternJsonDataRef; + } + else + { + pFocusData = m_pJsonData; + } + if (pFocusData == NULL) + { + m_strErrMsg = "json data is null!"; + return(false); + } + if (pFocusData->type != cJSON_Array) + { + m_strErrMsg = "not a json array! json object?"; + return(false); + } + cJSON* pJsonStruct = cJSON_CreateNull(); + if (pJsonStruct == NULL) + { + return(false); + } +#if __cplusplus < 201101L + std::map::iterator iter = m_mapJsonArrayRef.find(iWhich); +#else + auto iter = m_mapJsonArrayRef.find(iWhich); +#endif + if (iter != m_mapJsonArrayRef.end()) + { + if (iter->second != NULL) + { + delete (iter->second); + iter->second = NULL; + } + m_mapJsonArrayRef.erase(iter); + } + cJSON_ReplaceItemInArray(pFocusData, iWhich, pJsonStruct); + if (cJSON_GetArrayItem(pFocusData, iWhich) == NULL) + { + return(false); + } + return(true); +} + +CJsonObject::CJsonObject(cJSON* pJsonData) + : m_pJsonData(NULL), m_pExternJsonDataRef(pJsonData), m_pKeyTravers(pJsonData) +{ +} + +} + + diff --git a/CJsonObject.hpp b/CJsonObject.hpp new file mode 100644 index 0000000..8d8e66d --- /dev/null +++ b/CJsonObject.hpp @@ -0,0 +1,235 @@ +/* +* Copyright (C) 2020, 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 3, or (at your option) +* any later version. +* +* This program is distributed in the hope that it will be useful, +* but WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +* GNU General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, see +#include +#include +#include +#include +#include +#include +#include +#if __cplusplus < 201101L +#include +#else +#include +#endif +#ifdef __cplusplus +extern "C" { +#endif +#include "cJSON.h" +#ifdef __cplusplus +} +#endif + + +namespace neb +{ + +class CJsonObject +{ +public: // method of ordinary json object or json array + CJsonObject(); + CJsonObject(const std::string& strJson); + CJsonObject(const CJsonObject* pJsonObject); + CJsonObject(const CJsonObject& oJsonObject); +#if __cplusplus >= 201101L + CJsonObject(CJsonObject&& oJsonObject); +#endif + virtual ~CJsonObject(); + + CJsonObject& operator=(const CJsonObject& oJsonObject); +#if __cplusplus >= 201101L + CJsonObject& operator=(CJsonObject&& oJsonObject); +#endif + bool operator==(const CJsonObject& oJsonObject) const; + bool Parse(const std::string& strJson); + void Clear(); + bool IsEmpty() const; + bool IsArray() const; + std::string ToString() const; + std::string ToFormattedString() const; + const std::string& GetErrMsg() const + { + return(m_strErrMsg); + } + +public: // method of ordinary json object + bool AddEmptySubObject(const std::string& strKey); + bool AddEmptySubArray(const std::string& strKey); + bool GetKey(std::string& strKey); + void ResetTraversing(); + CJsonObject& operator[](const std::string& strKey); + std::string operator()(const std::string& strKey) const; + bool KeyExist(const std::string& strKey) const; + bool Get(const std::string& strKey, CJsonObject& oJsonObject) const; + bool Get(const std::string& strKey, std::string& strValue) const; + bool Get(const std::string& strKey, int32& iValue) const; + bool Get(const std::string& strKey, uint32& uiValue) const; + bool Get(const std::string& strKey, int64& llValue) const; + bool Get(const std::string& strKey, uint64& ullValue) const; + bool Get(const std::string& strKey, bool& bValue) const; + bool Get(const std::string& strKey, float& fValue) const; + bool Get(const std::string& strKey, double& dValue) const; + int GetValueType(const std::string& strKey) const; + bool IsNull(const std::string& strKey) const; + bool Add(const std::string& strKey, const CJsonObject& oJsonObject); +#if __cplusplus < 201101L + bool AddWithMove(const std::string& strKey, CJsonObject& oJsonObject); +#else + bool Add(const std::string& strKey, CJsonObject&& oJsonObject); +#endif + bool Add(const std::string& strKey, const std::string& strValue); + bool Add(const std::string& strKey, int32 iValue); + bool Add(const std::string& strKey, uint32 uiValue); + bool Add(const std::string& strKey, int64 llValue); + bool Add(const std::string& strKey, uint64 ullValue); + bool Add(const std::string& strKey, bool bValue, bool bValueAgain); + bool Add(const std::string& strKey, float fValue); + bool Add(const std::string& strKey, double dValue); + bool AddNull(const std::string& strKey); // add null like this: "key":null + bool Delete(const std::string& strKey); + bool Replace(const std::string& strKey, const CJsonObject& oJsonObject); +#if __cplusplus < 201101L + bool ReplaceWithMove(const std::string& strKey, CJsonObject& oJsonObject); +#else + bool Replace(const std::string& strKey, CJsonObject&& oJsonObject); +#endif + bool Replace(const std::string& strKey, const std::string& strValue); + bool Replace(const std::string& strKey, int32 iValue); + bool Replace(const std::string& strKey, uint32 uiValue); + bool Replace(const std::string& strKey, int64 llValue); + bool Replace(const std::string& strKey, uint64 ullValue); + bool Replace(const std::string& strKey, bool bValue, bool bValueAgain); + bool Replace(const std::string& strKey, float fValue); + bool Replace(const std::string& strKey, double dValue); + bool ReplaceWithNull(const std::string& strKey); // replace value with null +#if __cplusplus < 201101L + bool ReplaceAdd(const std::string& strKey, const CJsonObject& oJsonObject); + bool ReplaceAdd(const std::string& strKey, const std::string& strValue); + template + bool ReplaceAdd(const std::string& strKey, T value) + { + if (KeyExist(strKey)) + { + return(Replace(strKey, value)); + } + return(Add(strKey, value)); + } +#else + template + bool ReplaceAdd(const std::string& strKey, T&& value) + { + if (KeyExist(strKey)) + { + return(Replace(strKey, std::forward(value))); + } + return(Add(strKey, std::forward(value))); + } +#endif + +public: // method of json array + int GetArraySize() const; + CJsonObject& operator[](unsigned int uiWhich); + std::string operator()(unsigned int uiWhich) const; + bool Get(int iWhich, CJsonObject& oJsonObject) const; + bool Get(int iWhich, std::string& strValue) const; + bool Get(int iWhich, int32& iValue) const; + bool Get(int iWhich, uint32& uiValue) const; + bool Get(int iWhich, int64& llValue) const; + bool Get(int iWhich, uint64& ullValue) const; + bool Get(int iWhich, bool& bValue) const; + bool Get(int iWhich, float& fValue) const; + bool Get(int iWhich, double& dValue) const; + int GetValueType(int iWhich) const; + bool IsNull(int iWhich) const; + bool Add(const CJsonObject& oJsonObject); +#if __cplusplus < 201101L + bool AddWithMove(CJsonObject& oJsonObject); +#else + bool Add(CJsonObject&& oJsonObject); +#endif + bool Add(const std::string& strValue); + bool Add(int32 iValue); + bool Add(uint32 uiValue); + bool Add(int64 llValue); + bool Add(uint64 ullValue); + bool Add(int iAnywhere, bool bValue); + bool Add(float fValue); + bool Add(double dValue); + bool AddNull(); // add a null value + bool AddAsFirst(const CJsonObject& oJsonObject); +#if __cplusplus < 201101L + bool AddAsFirstWithMove(CJsonObject& oJsonObject); +#else + bool AddAsFirst(CJsonObject&& oJsonObject); +#endif + bool AddAsFirst(const std::string& strValue); + bool AddAsFirst(int32 iValue); + bool AddAsFirst(uint32 uiValue); + bool AddAsFirst(int64 llValue); + bool AddAsFirst(uint64 ullValue); + bool AddAsFirst(int iAnywhere, bool bValue); + bool AddAsFirst(float fValue); + bool AddAsFirst(double dValue); + bool AddNullAsFirst(); // add a null value + bool Delete(int iWhich); + bool Replace(int iWhich, const CJsonObject& oJsonObject); +#if __cplusplus < 201101L + bool ReplaceWithMove(int iWhich, CJsonObject& oJsonObject); +#else + bool Replace(int iWhich, CJsonObject&& oJsonObject); +#endif + bool Replace(int iWhich, const std::string& strValue); + bool Replace(int iWhich, int32 iValue); + bool Replace(int iWhich, uint32 uiValue); + bool Replace(int iWhich, int64 llValue); + bool Replace(int iWhich, uint64 ullValue); + bool Replace(int iWhich, bool bValue, bool bValueAgain); + bool Replace(int iWhich, float fValue); + bool Replace(int iWhich, double dValue); + bool ReplaceWithNull(int iWhich); // replace with a null value + +private: + CJsonObject(cJSON* pJsonData); + +private: + cJSON* m_pJsonData; + cJSON* m_pExternJsonDataRef; + cJSON* m_pKeyTravers; + const char* mc_pError; + std::string m_strErrMsg; +#if __cplusplus < 201101L + std::map m_mapJsonArrayRef; + std::map::iterator m_array_iter; + std::map m_mapJsonObjectRef; + std::map::iterator m_object_iter; +#else + std::unordered_map m_mapJsonArrayRef; + std::unordered_map::iterator m_object_iter; + std::unordered_map m_mapJsonObjectRef; + std::unordered_map::iterator m_array_iter; +#endif +}; + +} + +#endif /* CJSONHELPER_HPP_ */ diff --git a/Clock.json b/Clock.json new file mode 100644 index 0000000..1e81138 --- /dev/null +++ b/Clock.json @@ -0,0 +1,3 @@ +{ + "Keys" : [ ] +} diff --git a/ClockInterface.h b/ClockInterface.h new file mode 100644 index 0000000..d4e4f93 --- /dev/null +++ b/ClockInterface.h @@ -0,0 +1,44 @@ +/* +* Copyright (C) 2020, 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 3, or (at your option) +* any later version. +* +* This program is distributed in the hope that it will be useful, +* but WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +* GNU General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, see +#include + +#define CLOCK_DBUS_SERVICE_NAME "org.kylin.dbus.ukuiclock" +#define CLOCK_DBUS_SERVICE_PATH "/org/kylin/dbus/ukuiclock" +#define CLOCK_DBUS_UPDATE_CLOCK_BY_ID_PATH "/org/kylin/dbus/ukuiclock/updateClockById" +#define CLOCK_DBUS_SELECT_CLOCK_BY_ID_PATH "/org/kylin/dbus/ukuiclock/selectClockById" +#define CLOCK_DBUS_DELETE_CLOCK_BY_ID_PATH "/org/kylin/dbus/ukuiclock/deleteClockById" +namespace clockInterface { + +struct ReturnMsg{ + unsigned status = 0; + QString msg; +}; +struct RequestParams{ + QString clockName; + unsigned hour = 0; + unsigned minute = 0; +}; +enum STATUS_CODE{ + SUCCESS = 0, + FAIL = 1, +}; +} +#endif // CLOCKINTERFACE_H diff --git a/CustomButton.cpp b/CustomButton.cpp new file mode 100644 index 0000000..2f06bdf --- /dev/null +++ b/CustomButton.cpp @@ -0,0 +1,144 @@ +#include "CustomButton.h" +#include +#include "theme.h" + +CustomButton::CustomButton(QWidget *parent,int width, int height, int status) : QPushButton(parent),m_width(width),m_height(height),position(0),Status(status) +{ + max = qMax(m_width,m_height); + min = m_width>m_height?m_height:m_width; + length = max - min; + init(status); +} + +CustomButton::~CustomButton() +{ +} + +//开 +void CustomButton::openSlot() +{ + //滑动动画 + animation1 = new QPropertyAnimation(myLabel, "geometry"); + animation1->setDuration(100); + animation1->setKeyValueAt(0, QRect(2, 2, 20, 20)); + animation1->setEndValue(QRect(31, 2, 20, 20)); + animation1->start(); + this->setStyleSheet(openBcack); + myLabel->setStyleSheet(openbtn); + Status = 1; +} + +//关 +void CustomButton::closeSlot() +{ + animation1 = new QPropertyAnimation(myLabel, "geometry"); + animation1->setDuration(100); + animation1->setKeyValueAt(0, QRect(31, 2, 20, 20)); + animation1->setEndValue(QRect(2, 2, 20, 20)); + animation1->start(); + this->setStyleSheet(closeBcack); + myLabel->setStyleSheet(closeBtn); + Status = 0; +} + +void CustomButton::colorUpdate() +{ + switch(Status) + { + case 0: + this->setStyleSheet(closeBcack); + myLabel->setStyleSheet(closeBtn); + break; + + case 1: + this->setStyleSheet(openBcack ); + myLabel->setStyleSheet(openbtn); + break; + } +} + +void CustomButton::init(int status) +{ + this->resize(m_width,m_height); + myLabel = new QLabel(this); + myLabel->setObjectName("myLabel"); + myLabel->resize(20,20); + this->setStyleSheet(openBcack); + myLabel->setStyleSheet(openbtn); + this->setFixedSize(m_width,m_height); + settingsStyle(); +} + +void CustomButton::initClose() +{ + this->setStyleSheet(closeBcack); + myLabel->setStyleSheet(closeBtn); + Status = 0; + myLabel->move(2,2); +} + +void CustomButton::initOpen() +{ + Status = 1; + myLabel->move(31,2); + this->setStyleSheet(openBcack); + myLabel->setStyleSheet(openbtn); +} + +/* +*监听主题 +*/ +void CustomButton::settingsStyle() +{ + GsettingSubject * subject = GsettingSubject::getInstance(); + connect(subject,&GsettingSubject::blackStyle, this,[=](){ + this->blackStyle(); + }); + connect(subject,&GsettingSubject::whiteStyle, this,[=](){ + this->whiteStyle(); + }); + subject->iniWidgetStyle(); +} + +QColor BACK_COLOR = QColor(220, 220, 220, 255); +//黑色主题 +void CustomButton::blackStyle() +{ + + closeBcack = QString("CustomButton{background-color:rgba(240, 247, 255, 0.2);border-radius:%1px;}").arg(min/2); + QColor b1 = QColor(70, 70, 70, 255); + QString btnColor=theme::getColorStr(b1); + QColor btnHover=QColor(100, 100, 100, 255); + QString btnHoverColor=theme::getColorStr(btnHover); + closeBcack = QString("CustomButton{background-color:"+btnColor+";border-radius:%1px;}CustomButton:pressed{background-color:"+btnHoverColor+";}CustomButton:hover{background-color:"+btnHoverColor+";}").arg(min/2); + closeBtn = QString("#myLabel{background-color:rgba(235, 244, 255, 0.55);border-radius:%1px}").arg(20/2); + + QColor deepHigh=theme::highLight_Hover(); + QString deepHiColor=theme::getColorStr(deepHigh); + QColor h1 = this->palette().color(QPalette::Inactive,QPalette::Highlight); + QString hiColor=theme::getColorStr(h1); + openBcack = QString("CustomButton{background-color:"+hiColor+";border-radius:%1px;}CustomButton:pressed{background-color:"+deepHiColor+";}CustomButton:hover{background-color:"+deepHiColor+";}").arg(min/2); + openbtn = QString("#myLabel{background-color:rgba(255, 255, 255, 0.88);border-radius:%1px}").arg(20/2); + colorUpdate(); + +} + + +//白色主题 +void CustomButton::whiteStyle() +{ + closeBcack = QString("CustomButton{background-color:rgba(180, 195, 212, 1);border-radius:%1px;}").arg(min/2); + QString btnColor=theme::getColorStr(BACK_COLOR); + QColor btnClick=theme::button_Click(); + QString btnClickColor=theme::getColorStr(btnClick); + closeBcack = QString("CustomButton{background-color:"+btnColor+";border-radius:%1px;}CustomButton:pressed{background-color:"+btnClickColor+";}CustomButton:hover{background-color:"+btnClickColor+";}").arg(min/2); + closeBtn = QString("#myLabel{background-color: rgb(240, 245, 250);border-radius:%1px}").arg(20/2); + + QColor deepHigh=theme::highLight_Click(); + QString deepHiColor=theme::getColorStr(deepHigh); + QColor h1 = this->palette().color(QPalette::Inactive,QPalette::Highlight); + QString hiColor=theme::getColorStr(h1); + openBcack = QString("CustomButton{background-color:"+hiColor+";border-radius:%1px;}CustomButton:pressed{background-color:"+deepHiColor+";}CustomButton:hover{background-color:"+deepHiColor+";}").arg(min/2); + openbtn = QString("#myLabel{background-color: rgba(255, 255, 255, 0.88);border-radius:%1px}").arg(20/2); + colorUpdate(); +} diff --git a/CustomButton.h b/CustomButton.h new file mode 100644 index 0000000..99cc087 --- /dev/null +++ b/CustomButton.h @@ -0,0 +1,72 @@ +/* +* Copyright (C) 2020, 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 3, or (at your option) +* any later version. +* +* This program is distributed in the hope that it will be useful, +* but WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +* GNU General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, see +#include +#include +#include +#include +#include +#include +#include +#include "constant_class.h" +#include "gsettingsubject.h" + + +/** + * @brief 自定义滑动按钮 + */ +class CustomButton : public QPushButton +{ + Q_OBJECT +public: + explicit CustomButton(QWidget *parent = nullptr, int width=50, int height=24, int status = 1); + ~CustomButton(); + +private: + QTimer timer; + int m_width; + int m_height; + int dir; + int position; + int max; + int min; + int length; + int Status; + QString closeBcack; + QString openBcack; + QString closeBtn; + QString openbtn; + QPropertyAnimation *animation1; + QPropertyAnimation *animation2; +public: + void init(int status); + void whiteStyle(); + void blackStyle(); + void settingsStyle(); + void colorUpdate(); + void openSlot(); + void closeSlot(); + void initOpen(); + void initClose(); + QLabel* myLabel; +}; + +#endif // CUSTOMBUTTON_H diff --git a/README.md b/README.md new file mode 100644 index 0000000..74be22e --- /dev/null +++ b/README.md @@ -0,0 +1 @@ +闹钟项目 diff --git a/about.cpp b/about.cpp new file mode 100644 index 0000000..b3c13fb --- /dev/null +++ b/about.cpp @@ -0,0 +1,138 @@ +/* +* Copyright (C) 2020, 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 3, or (at your option) +* any later version. +* +* This program is distributed in the hope that it will be useful, +* but WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +* GNU General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, see +#include "xatom-helper.h" +#include "configutil.h" + +extern void qt_blurImage(QImage &blurImage, qreal radius, bool quality, int transposed); + +About::About(QWidget *parent) : + QDialog(parent), + ui(new Ui::About) +{ + ui->setupUi(this); + + // 添加窗管协议 + XAtomHelper::setStandardWindowHint(this->winId()); + + setWindowTitle(tr("About")); + //当小部件接受了关闭事件时,使Qt删除此小部件(请参阅QWidget :: closeEvent())。 + setAttribute(Qt::WA_DeleteOnClose); + //左上角闹钟图标 + ui->titleIcon->setPixmap(QIcon::fromTheme("kylin-alarm-clock").pixmap(24,24)); + //右上角关闭X + ui->closeBtn->setIcon(QIcon::fromTheme("window-close-symbolic")); + ui->closeBtn->setProperty("isWindowButton", 0x2); + ui->closeBtn->setProperty("useIconHighlightEffect", 0x8); + //按钮边框是否凸起 默认false + ui->closeBtn->setFlat(true); + connect(ui->closeBtn, &QPushButton::clicked, this, [=](){ + this->close(); + }); + //in order to use the same world in English + ui->titlename->setText(tr(CLOCK_TITLE_NAME)); + //麒麟闹钟 + ui->appnameLabel->setText(tr(KYLIN_CLOCK_APP_NAME)); + ui->appnameLabel->setStyleSheet("QLabel{ font-size: 18px; color: palette(windowText);}" + "QLabel{font-family: NotoSansCJKsc-Medium, NotoSansCJKsc;}"); + QString version = ConfigUtil().Get("common","version").toString(); + + ui->versionLabel->setText(tr("Version: ")+version); + settingsStyle(); + //中间大图标 + ui->appiconLabel->setPixmap(QIcon::fromTheme("kylin-alarm-clock").pixmap(96,96)); + //介绍的超链接 url 时text里的a标签 + connect(ui->introduceLabel, &QLabel::linkActivated, this, [=](const QString url){ + QDesktopServices::openUrl(QUrl(url)); + }); + //该窗口小部件不具有上下文菜单,上下文菜单的处理将延迟到该窗口小部件的父级。 + ui->introduceLabel->setContextMenuPolicy(Qt::NoContextMenu); + // 主题框架1.0.6-5kylin2 + + //关闭按钮去掉聚焦状态 + ui->closeBtn->setFocusPolicy(Qt::NoFocus); + +} + +About::~About() +{ + delete ui; +} +#define SYSTEM_FONT_EKY "system-font-size" +/* +*监听主题 +*/ +void About::settingsStyle() +{ + GsettingSubject * subject = GsettingSubject::getInstance();; + connect(subject,&GsettingSubject::blackStyle, this,[=](){ + this->blackStyle(); + }); + connect(subject,&GsettingSubject::whiteStyle, this,[=](){ + this->whiteStyle(); + }); + connect(subject,&GsettingSubject::iconChnaged, this,[=](){ + ui->titleIcon->setPixmap(QIcon::fromTheme("kylin-alarm-clock").pixmap(24,24)); + ui->appiconLabel->setPixmap(QIcon::fromTheme("kylin-alarm-clock").pixmap(96,96)); + }); + connect(subject,&GsettingSubject::fontChanged, this,[=](int size){ + this->CURRENT_FONT_SIZE=size; + this->updateLabelFront(ui->appnameLabel,round(size*1.63)); + }); + subject->iniWidgetStyle(); + subject->iniFontSize(); +} + +void About::paintEvent(QPaintEvent *event) { + Q_UNUSED(event); + QPainter p(this); + p.setRenderHint(QPainter::Antialiasing); // 反锯齿; + //绘制器路径 + QPainterPath rectPath; + rectPath.addRect(this->rect()); + p.fillPath(rectPath,palette().color(QPalette::Base)); +} + +//黑色主题 +void About::blackStyle() +{ + ui->introduceLabel->setText(tr("Service & Support: ") + + "" + "support@kylinos.cn"); +} +//白色主题 +void About::whiteStyle() +{ + ui->introduceLabel->setText(tr("Service & Support: ") + + "" + "support@kylinos.cn"); +} +/** + * @brief 更新麒麟闹钟字体 + */ +void About::updateLabelFront(QLabel *label, int size) +{ + QString styleSheet = "QLabel{ font-size: "; + styleSheet.append(QString::number(size)).append("px;"); + styleSheet.append("color: palette(windowText);}""QLabel{font-family: NotoSansCJKsc-Medium, NotoSansCJKsc;}"); + label->setStyleSheet(styleSheet); +} diff --git a/about.h b/about.h new file mode 100644 index 0000000..41de607 --- /dev/null +++ b/about.h @@ -0,0 +1,62 @@ +/* +* Copyright (C) 2020, 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 3, or (at your option) +* any later version. +* +* This program is distributed in the hope that it will be useful, +* but WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +* GNU General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, see +#include +#include +#include +#include +#include +#include "constant_class.h" + +#include +#include + +#include "gsettingsubject.h" + + + + + +namespace Ui { +class About; +} + +class About : public QDialog +{ + Q_OBJECT + +public: + explicit About(QWidget *parent = nullptr); + ~About(); + +protected: + void paintEvent(QPaintEvent *event) Q_DECL_OVERRIDE; + +private: + void settingsStyle(); //监听主题 + void blackStyle(); //黑色主题 + void whiteStyle(); //白色主题 + void updateLabelFront(QLabel *label, int size); + int CURRENT_FONT_SIZE; + Ui::About *ui; +}; + +#endif // ABOUT_H diff --git a/about.ui b/about.ui new file mode 100644 index 0000000..2b80325 --- /dev/null +++ b/about.ui @@ -0,0 +1,221 @@ + + + About + + + + 0 + 0 + 420 + 334 + + + + Dialog + + + + 0 + + + 0 + + + 0 + + + 0 + + + 0 + + + + + 0 + + + 5 + + + 5 + + + 5 + + + 8 + + + + + + 24 + 24 + + + + + 24 + 24 + + + + + + + + + + + Qt::Horizontal + + + QSizePolicy::Fixed + + + + 5 + 20 + + + + + + + + Alarm + + + + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + + 30 + 30 + + + + + 30 + 30 + + + + + + + + + + + + + 0 + + + + + + 96 + 96 + + + + + 96 + 96 + + + + + + + + + + + + + 16 + + + 16 + + + + + Alarm + + + Qt::AlignCenter + + + + + + + + + + Qt::AlignCenter + + + + + + + + + + Qt::AlignCenter + + + + + + + Qt::Vertical + + + + 20 + 40 + + + + + + + + + + Qt::Vertical + + + + 20 + 12 + + + + + + + + + diff --git a/adaptscreeninfo.cpp b/adaptscreeninfo.cpp new file mode 100644 index 0000000..5969fc9 --- /dev/null +++ b/adaptscreeninfo.cpp @@ -0,0 +1,103 @@ +/* + * Copyright (C) 2020, KylinSoft Co., Ltd. + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +#include "adaptscreeninfo.h" + +adaptScreenInfo::adaptScreenInfo(QObject *parent) : QObject(parent) +{ + //返回桌面小部件(也称为根窗口)。 + //桌面可能由多个屏幕组成,因此尝试在窗口的几何图形中居中某个窗口小部件是不正确的 + m_pDeskWgt = QApplication::desktop(); + //初始化主屏坐标 + InitializeHomeScreenGeometry(); + //初始化屏幕宽高 + initScreenSize(); + //当改变屏幕分辨率时 重新计算 主屏坐标 屏幕宽高 + connect(QApplication::primaryScreen(), &QScreen::geometryChanged, this, &adaptScreenInfo::onResolutionChanged); + //主屏发生变化槽函数 重新计算 主屏坐标 屏幕宽高 + connect(m_pDeskWgt, &QDesktopWidget::primaryScreenChanged, this, &adaptScreenInfo::primaryScreenChangedSlot); + //屏幕数量改变时 重新计算 主屏坐标 屏幕宽高 + connect(m_pDeskWgt, &QDesktopWidget::screenCountChanged, this, &adaptScreenInfo::screenCountChangedSlots); + //屏幕list + m_pListScreen = QGuiApplication::screens(); +} + +/* 当屏幕数量发生改变时,重新赋值m_pListScreen 未发现调用 */ +void adaptScreenInfo::screenNumChange() +{ + m_pListScreen = QGuiApplication::screens(); +} + + +/* 初始化屏幕高度, 宽度 */ +void adaptScreenInfo::initScreenSize() +{ + QList screen = QGuiApplication::screens(); + int count = m_pDeskWgt->screenCount(); + if (count > 1) { + m_screenWidth = screen[0]->geometry().width() + m_nScreen_x; + m_screenHeight = screen[0]->geometry().height() + m_nScreen_y; + } else { + m_screenWidth = m_pDeskWgt->width() + m_nScreen_x; + m_screenHeight = m_pDeskWgt->height() + m_nScreen_y; + } + qDebug() << "屏幕高度m_screenWidth" << m_screenWidth; + qDebug() << "屏幕宽度m_screenHeight" << m_screenHeight; + return; +} + +/* 初始化主屏坐标 */ +void adaptScreenInfo::InitializeHomeScreenGeometry() +{ + QList screen = QGuiApplication::screens(); + int count = m_pDeskWgt->screenCount(); + if (count > 1) { + m_nScreen_x = screen[0]->geometry().x(); + m_nScreen_y = screen[0]->geometry().y(); + } else { + m_nScreen_x = 0; + m_nScreen_y = 0; + } + qDebug() << "偏移的x坐标" << m_nScreen_x; + qDebug() << "偏移的Y坐标" << m_nScreen_y; +} + +//当改变屏幕分辨率时重新获取屏幕分辨率 +void adaptScreenInfo::onResolutionChanged(const QRect argc) +{ + Q_UNUSED(argc); + initScreenSize(); //获取屏幕可用高度区域 + InitializeHomeScreenGeometry(); + return; +} + +/* 主屏发生变化槽函数 */ +void adaptScreenInfo::primaryScreenChangedSlot() +{ + InitializeHomeScreenGeometry(); + initScreenSize(); + return; +} + +/* 屏幕数量改变时对应槽函数 */ +void adaptScreenInfo::screenCountChangedSlots(int count) +{ + Q_UNUSED(count); + InitializeHomeScreenGeometry(); + initScreenSize(); + return; +} diff --git a/adaptscreeninfo.h b/adaptscreeninfo.h new file mode 100644 index 0000000..a74ecc6 --- /dev/null +++ b/adaptscreeninfo.h @@ -0,0 +1,59 @@ +/* + * Copyright (C) 2020, KylinSoft Co., Ltd. + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +#ifndef ADAPTSCREENINFO_H +#define ADAPTSCREENINFO_H + +#include +#include +#include +#include +#include +#include +#include +class adaptScreenInfo : public QObject +{ + Q_OBJECT +public: + explicit adaptScreenInfo(QObject *parent = nullptr); + void screenNumChange(); + void InitializeHomeScreenGeometry(); + + + QDesktopWidget *m_pDeskWgt; // 桌面问题 + int m_screenWidth; // 桌面宽度 + int m_screenHeight; // 桌面高度 + int m_screenNum; // 屏幕数量 + int m_nScreen_x; // 主屏起始坐标X + int m_nScreen_y; // 主屏起始坐标Y + +signals: + +private: + void initScreenSize(); + +private slots: + void primaryScreenChangedSlot(); + void onResolutionChanged(const QRect argc); + void screenCountChangedSlots(int count); + +private: + QList m_pListScreen; + QStringList ScreenName; +}; + +#endif // ADAPTSCREENINFO_H diff --git a/baseverticalscroll.cpp b/baseverticalscroll.cpp new file mode 100644 index 0000000..25f9973 --- /dev/null +++ b/baseverticalscroll.cpp @@ -0,0 +1,203 @@ +/* +* Copyright (C) 2020, 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 3, or (at your option) +* any later version. +* +* This program is distributed in the hope that it will be useful, +* but WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +* GNU General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, see +#include +#include +#include +#include "theme.h" +BaseVerticalScroll::BaseVerticalScroll(int currentValue, int minRange, int maxRange, QWidget *parent) : QWidget(parent), + m_currentValue(currentValue), + m_minRange(minRange), + m_maxRange(maxRange), + isDragging(false), + m_deviation(0), //默认偏移量为0 // The default offset is 0 + m_numSize(TIME_SCROLL_NUM_SIZE), + interval(1), //间隔默认1 // Interval default 1 + devide(4) //默认分成4格 // Divided into 4 grids by default +{ + m_priManager = new PrimaryManager(); + settingsStyle(); +} + +void BaseVerticalScroll::setWheelSpeed(int wheelSpeed) +{ + m_wheelSpeed = wheelSpeed; +} + +void BaseVerticalScroll::settingsStyle() +{ + subject = GsettingSubject::getInstance(); + connect(subject,&GsettingSubject::mouseWheelChanged, this,[=](int speed){ + if(m_priManager->checkWayland()){ + this->setWheelSpeed(speed); + } + }); + + subject->iniMouseWheel(); +} +void BaseVerticalScroll::homing() +{ + if ( m_deviation > height() / 10) { + homingAni->setStartValue( ( height() - 1 ) / 8 - m_deviation); + homingAni->setEndValue(0); + m_currentValue = calculateCurrentValue(m_currentValue,-interval); + } else if ( m_deviation > -height() / 10 ) { + homingAni->setStartValue(m_deviation); + homingAni->setEndValue(0); + } else if ( m_deviation < -height() / 10 ) { + homingAni->setStartValue(-(height() - 1) / 8 - m_deviation); + homingAni->setEndValue(0); + m_currentValue = calculateCurrentValue(m_currentValue,interval); + } + emit currentValueChanged(m_currentValue); + homingAni->start(); +} +int BaseVerticalScroll::calculateCurrentValue(int current,int offsetValue) +{ + if ( current == m_minRange && offsetValue<0 ) { + current = m_maxRange+offsetValue+1; + } else if( current == m_maxRange && offsetValue>0 ) { + current = m_minRange+offsetValue-1; + }else{ + current+=offsetValue; + } + return current; +} +void BaseVerticalScroll::paintNum(QPainter &painter, int num, int deviation) +{ + int Width = width() - 1; + int Height = height() - 1; + int size = (Height - qAbs(deviation)) / (m_numSize*1.5); //偏移量越大,数字越小 + //The larger the offset, the smaller the number + int transparency = Utils::handelColorRange(255 - 255 * qAbs(deviation) / Height); + int height = Height / devide; + int y = Height / 2 + deviation - height / 2; + + QFont font; + font.setPixelSize(size); + painter.setFont(font); + painter.setPen(QColor(255,255,255,transparency)); + + + QStyleOption opt; + opt.init(this); + + //偏移量越大颜色越浅 + if(theme::themetype==0) + { + painter.setPen(QColor(Utils::handelColorRange(34+(qAbs(deviation)*2)), + Utils::handelColorRange(34+(qAbs(deviation)*2)), + Utils::handelColorRange(34+(qAbs(deviation)*2)),transparency)); + }else{ + painter.setPen(QColor(Utils::handelColorRange(255-(qAbs(deviation)*2)), + Utils::handelColorRange(255-(qAbs(deviation)*2)), + Utils::handelColorRange(255-(qAbs(deviation)*2)),transparency)); + } + + QLinearGradient linearGradient(QPointF(5, 10), QPointF(7, 15)); + linearGradient.setColorAt(0.2, Qt::white); + linearGradient.setColorAt(0.6, Qt::green); + linearGradient.setColorAt(1.0, Qt::black); + painter.setBrush(QBrush(linearGradient)); + + if ( y >= 0 && y + height < Height) { + painter.drawText(QRectF(0, y, Width, height), + Qt::AlignCenter, + change_NUM_to_str(num)); + } +} + +QString BaseVerticalScroll::change_NUM_to_str(int alarmHour) +{ + QString str; + if (alarmHour < 10) { + QString hours_str = QString::number(alarmHour); + str = "0"+hours_str; + } else { + str = QString::number(alarmHour); + } + return str; +} +void BaseVerticalScroll::commonCalcValue(int height) +{ + if ( m_deviation >= height / devide ) { + m_mouseSrcPos += height / devide; + m_deviation -= height / devide; + m_currentValue = calculateCurrentValue(m_currentValue,-interval); + } + + if ( m_deviation <= -height / devide ) { + m_mouseSrcPos -= height / devide; + m_deviation += height / devide; + m_currentValue = calculateCurrentValue(m_currentValue,interval); + } +} +//鼠标滑轮滚动,数值滚动 +// Mouse wheel scrolling, numerical scrolling +void BaseVerticalScroll::wheelEvent(QWheelEvent *event) +{ + //wayland下没有初次进入,触发两次wheelEvent问题 + if(m_priManager->checkWayland()){ + m_isFirstFocus=false; + } + if(m_isFirstFocus){ + event->ignore(); + m_isFirstFocus = false; + }else{ + for (int i=0;idelta() > 0){ + if (m_currentValue <= m_minRange) + m_currentValue = m_maxRange; + else + m_currentValue-=1; + } else { + if (m_currentValue >= m_maxRange) + m_currentValue = m_minRange; + else + m_currentValue+=1; + } +// update(); + repaint(); + QThread::msleep(20); + } + event->accept(); + } + +} +void BaseVerticalScroll::mouseMoveEvent(QMouseEvent *e) +{ + if (isDragging) { +// if ( m_currentValue == m_minRange && e->pos().y() >= m_mouseSrcPos ) { +// m_currentValue = m_maxRange; +// } else if( m_currentValue == m_maxRange && e->pos().y() <= m_mouseSrcPos ) { +// m_currentValue = m_minRange; +// } + + m_deviation = e->pos().y() - m_mouseSrcPos; + //若移动速度过快,则进行限制 + // If the movement speed is too fast, limit it + if (m_deviation > (height() - 1) / devide) { + m_deviation = (height() - 1) / devide; + } else if (m_deviation < -(height() - 1) / devide) { + m_deviation = -( height() - 1) / devide; + } + emit deviationChange((int)m_deviation / ((height() - 1) / devide)); + repaint(); + } +} diff --git a/baseverticalscroll.h b/baseverticalscroll.h new file mode 100644 index 0000000..259346f --- /dev/null +++ b/baseverticalscroll.h @@ -0,0 +1,66 @@ +/* +* Copyright (C) 2020, 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 3, or (at your option) +* any later version. +* +* This program is distributed in the hope that it will be useful, +* but WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +* GNU General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, see +#include "gsettingsubject.h" +#include "primarymanager.h" +#include +#include +class BaseVerticalScroll : public QWidget +{ + Q_OBJECT +public: + explicit BaseVerticalScroll(int currentValue,int minRange,int maxRange,QWidget *parent = nullptr); + + void setWheelSpeed(int wheelSpeed); + int m_currentValue=0; + int m_wheelSpeed = 1; + bool m_isFirstFocus = false; + int m_minRange=0; //最小值 // minimum value + int m_maxRange=0; //最大值 // Maximum + void settingsStyle(); + GsettingSubject * subject; + PrimaryManager * m_priManager; + void homing(); + int calculateCurrentValue(int current,int offsetValue); + void commonCalcValue(int height); + bool isDragging; //鼠标是否按下 // Muse down + int m_deviation; //偏移量,记录鼠标按下后移动的垂直距离 // Offset, record the vertical distance after mouse is pressed + int m_mouseSrcPos; + int m_numSize; + QPropertyAnimation *homingAni; + const int interval; //间隔大小 // Interval size + const int devide; //分隔数量 // Number of partitions + void paintNum(QPainter &painter, int num, int deviation); + QString change_NUM_to_str(int alarmHour); + + +signals: + void currentValueChanged(int value); + void deviationChange(int deviation); +protected: + void wheelEvent(QWheelEvent *) override; + void mouseMoveEvent(QMouseEvent *) override; +private: + + +}; + +#endif // BASEVERTICALSCROLL_H diff --git a/btnNew.cpp b/btnNew.cpp new file mode 100644 index 0000000..110da43 --- /dev/null +++ b/btnNew.cpp @@ -0,0 +1,121 @@ +/* +* Copyright (C) 2020, 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 3, or (at your option) +* any later version. +* +* This program is distributed in the hope that it will be useful, +* but WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +* GNU General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, see +#include +#include "clock.h" +#include +#include "theme.h" + + +Btn_new::Btn_new(int num, QString name, Btn_new::BTN_NEW_TYPE btnType, QWidget *parent) : + QPushButton(parent), + clock_num(num), + m_btnType(btnType) +{ + QPixmap pixmap = QPixmap(":/image/go-bottom-symbolic.png"); + nameLabel = new QLabel(this); + textLabel = new QLabel(this); + IconLabel = new QLabel(this); + noName = new QLabel(this); + //num不同,name与text的大小配比不同 + int lineHeight = 22; + int lineMoveHeight = 13; + int nameWidth = 100; + int editWidth = 200; + nameLabel->setFixedSize(nameWidth-num, lineHeight); + textLabel->setFixedSize(editWidth+num, lineHeight); + IconLabel->setFixedSize(27, 36); + noName->setFixedSize(9, 36); + nameLabel->move(20, lineMoveHeight); + textLabel->move(nameWidth-num, lineMoveHeight); + noName->move(244, 0); + IconLabel->move(309, 6); + nameLabel->setText(name); + textLabel->setText(name); + IconLabel->setPixmap(pixmap); + textLabel->setAlignment(Qt::AlignRight | Qt::AlignCenter); + nameLabel->setStyleSheet("font-size:14px;"); + textLabel->setStyleSheet("font-size:14px;"); + this->resize(340,48); + + QPalette palette; + palette.setColor(QPalette::ButtonText,QColor(148, 148, 148, 255)); + textLabel->setPalette(palette); + clockNameLineEdit = new QLineEdit(this); + clockNameLineEdit->move(nameWidth-num, 0); + clockNameLineEdit->setFixedSize(editWidth+num, 48); + clockNameLineEdit->setContextMenuPolicy(Qt::NoContextMenu); + clockNameLineEdit->setAlignment(Qt::AlignRight); + if(m_btnType==SELECT_BTN){ + textLabel->show(); + IconLabel->show(); + clockNameLineEdit->hide(); + }else if(m_btnType==LINE_EDIT){ + textLabel->hide(); + IconLabel->hide(); + clockNameLineEdit->show(); + } + +} + + + +Btn_new::~Btn_new() +{ + +} + +void Btn_new::paintEvent(QPaintEvent *event) +{ + Q_UNUSED(event); + QPainter p(this); + p.setRenderHint(QPainter::Antialiasing); // 反锯齿; + QPainterPath rectPath; + rectPath.addRoundedRect(this->rect(), 10, 10); // 左上右下 + + QPainter painter(this); + QStyleOption opt; + opt.init(this); + painter.setBrush(opt.palette.color(QPalette::Base)); + + QColor mainColor; + mainColor = theme::selectBtnBackColor; + p.fillPath(rectPath,QBrush(mainColor)); +} +void Btn_new::updateWidthForFontChange(int px) +{ + //调整一下,不然放大字体会遮挡 + int wideth =nameLabel->size().width(); + nameLabel->setFixedWidth(wideth+px); +} +/** + * @brief 1 向上 0 向下 + * @param status + */ +void Btn_new::updateIconLabel(int status) +{ + QPixmap pixmap ; + if(status==1){ + pixmap = QPixmap(":/image/go-up-symbolic.png"); + }else{ + pixmap = QPixmap(":/image/go-bottom-symbolic.png"); + } + IconLabel->setPixmap(pixmap); + IconLabel->update(); +} diff --git a/btnNew.h b/btnNew.h new file mode 100644 index 0000000..220f668 --- /dev/null +++ b/btnNew.h @@ -0,0 +1,63 @@ +/* +* Copyright (C) 2020, 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 3, or (at your option) +* any later version. +* +* This program is distributed in the hope that it will be useful, +* but WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +* GNU General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, see +#include +#include +#include +#include + +namespace Ui { +class Btn_new; +} +class Clock; +class Btn_new : public QPushButton +{ + Q_OBJECT + +public: + enum BTN_NEW_TYPE{ + LINE_EDIT=0, + SELECT_BTN=1 + }; + explicit Btn_new(int num, QString name ,BTN_NEW_TYPE btnType= SELECT_BTN,QWidget *parent = nullptr); + ~Btn_new(); + QLabel *nameLabel; + QLabel *textLabel; + QLabel *noName; + QLabel *IconLabel; + QLineEdit * clockNameLineEdit; + + + void paintEvent(QPaintEvent *event); + void updateWidthForFontChange(int px); + void updateIconLabel(int status); +private: + Ui::Btn_new *ui; + Clock * m_pclock; + int clock_num; + int pressflag; + BTN_NEW_TYPE m_btnType; + + +protected: +}; + +#endif // BTN_NEW_H diff --git a/cJSON.c b/cJSON.c new file mode 100644 index 0000000..f75569d --- /dev/null +++ b/cJSON.c @@ -0,0 +1,1101 @@ +/* +* Copyright (C) 2020, 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 3, or (at your option) +* any later version. +* +* This program is distributed in the hope that it will be useful, +* but WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +* GNU General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, see +#include +#include +#include +#include +#include +#include +#include "cJSON.h" + +#ifndef INT_MAX +#define INT_MAX 2147483647 +#define INT_MIN (-INT_MAX - 1) +#define UINT_MAX 4294967295U +#endif + +/* remove global variable for thread safe. --by Bwar on 2020-11-15 +static const char *ep; + +const char *cJSON_GetErrorPtr() +{ + return ep; +} +*/ + +static int cJSON_strcasecmp(const char *s1, const char *s2) +{ + if (!s1) + return (s1 == s2) ? 0 : 1; + if (!s2) + return 1; + for (; tolower(*s1) == tolower(*s2); ++s1, ++s2) + if (*s1 == 0) + return 0; + return tolower(*(const unsigned char *)s1) + - tolower(*(const unsigned char *)s2); +} + +static void *(*cJSON_malloc)(size_t sz) = malloc; +static void (*cJSON_free)(void *ptr) = free; + +static char* cJSON_strdup(const char* str) +{ + size_t len; + char* copy; + + len = strlen(str) + 1; + if (!(copy = (char*) cJSON_malloc(len))) + return 0; + memcpy(copy, str, len); + return copy; +} + +void cJSON_InitHooks(cJSON_Hooks* hooks) +{ + if (!hooks) + { /* Reset hooks */ + cJSON_malloc = malloc; + cJSON_free = free; + return; + } + + cJSON_malloc = (hooks->malloc_fn) ? hooks->malloc_fn : malloc; + cJSON_free = (hooks->free_fn) ? hooks->free_fn : free; +} + +/* Internal constructor. */ +static cJSON *cJSON_New_Item() +{ + cJSON* node = (cJSON*) cJSON_malloc(sizeof(cJSON)); + if (node) + memset(node, 0, sizeof(cJSON)); + return node; +} + +/* Delete a cJSON structure. */ +void cJSON_Delete(cJSON *c) +{ + cJSON *next; + while (c) + { + next = c->next; + if (!(c->type & cJSON_IsReference) && c->child) + cJSON_Delete(c->child); + if (!(c->type & cJSON_IsReference) && c->valuestring) + cJSON_free(c->valuestring); + if (c->string) + cJSON_free(c->string); + cJSON_free(c); + c = next; + } +} + +/* Parse the input text to generate a number, and populate the result into item. */ +static const char *parse_number(cJSON *item, const char *num) +{ + int64 n = 0; + long double d = 0.0; + double base = 0.0; + double point = 0.1; + int scale = 0.0; + int subscale = 0; + int signsubscale = 1; + item->sign = 1; + + /* Could use sscanf for this? */ + if (*num == '-') + item->sign = -1, num++; /* Has sign? */ + if (*num == '0') + num++; /* is zero */ + while (*num >= '0' && *num <= '9') + { + n = (n * 10) + (*num++ - '0'); + } + d = n; + if (*num == '.' && num[1] >= '0' && num[1] <= '9') + { + num++; + base = d; + do + { + d += point * (*num - '0'); + point *= 0.1; + base = (base * 10.0) + (*num - '0'), scale--; + ++num; + } + while (*num >= '0' && *num <= '9'); + } /* Fractional part? */ + if (*num == 'e' || *num == 'E') /* Exponent? */ + { + num++; + if (*num == '+') + num++; + else if (*num == '-') + signsubscale = -1, num++; /* With sign? */ + while (*num >= '0' && *num <= '9') + subscale = (subscale * 10) + (*num++ - '0'); /* Number? */ + } + + if (scale == 0 && subscale == 0) + { + item->valuedouble = item->sign * d; + item->valueint = item->sign * n; + item->type = cJSON_Int; + } + else + { + if (subscale != 0) + { + d = item->sign * base * pow(10.0, (scale + subscale * signsubscale)); /* number = +/- number.fraction * 10^+/- exponent */ + } + item->valuedouble = d; + item->valueint = n; + item->type = cJSON_Double; + } + return num; +} + +/* Render the number nicely from the given item into a string. */ +static char *print_double(cJSON *item) +{ + char *str; + double d = item->valuedouble; + str = (char*) cJSON_malloc(64); /* This is a nice tradeoff. */ + if (str) + { + sprintf(str, "%.15f", d); + } + return str; +} + +static char *print_int(cJSON *item) +{ + char *str; + str = (char*) cJSON_malloc(22); /* 2^64+1 can be represented in 21 chars. */ + if (str) + { + if (item->sign == -1) + { + if ((int64)item->valueint <= (int64)INT_MAX && (int64)item->valueint >= (int64)INT_MIN) + { + sprintf(str, "%d", (int32)item->valueint); + } + else + { + sprintf(str, "%ld", (int64)item->valueint); + } + } + else + { + if (item->valueint <= (uint64)UINT_MAX) + { + sprintf(str, "%u", (uint32)item->valueint); + } + else + { + sprintf(str, "%lu", item->valueint); + } + } + } + return str; +} + +/* Parse the input text into an unescaped cstring, and populate item. */ +static const unsigned char firstByteMark[7] = { 0x00, 0x00, 0xC0, 0xE0, 0xF0, + 0xF8, 0xFC }; +static const char *parse_string(cJSON *item, const char *str, const char **ep) +{ + const char *ptr = str + 1; + char *ptr2; + char *out; + int len = 0; + unsigned uc, uc2; + if (*str != '\"') + { + *ep = str; + return 0; + } /* not a string! */ + + while (*ptr != '\"' && *ptr && ++len) + if (*ptr++ == '\\') + ptr++; /* Skip escaped quotes. */ + + out = (char*) cJSON_malloc(len + 1); /* This is how long we need for the string, roughly. */ + if (!out) + return 0; + + ptr = str + 1; + ptr2 = out; + while (*ptr != '\"' && *ptr) + { + if (*ptr != '\\') + *ptr2++ = *ptr++; + else + { + ptr++; + switch (*ptr) + { + case 'b': + *ptr2++ = '\b'; + break; + case 'f': + *ptr2++ = '\f'; + break; + case 'n': + *ptr2++ = '\n'; + break; + case 'r': + *ptr2++ = '\r'; + break; + case 't': + *ptr2++ = '\t'; + break; + case 'u': /* transcode utf16 to utf8. */ + sscanf(ptr + 1, "%4x", &uc); + ptr += 4; /* get the unicode char. */ + + if ((uc >= 0xDC00 && uc <= 0xDFFF) || uc == 0) + break; // check for invalid. + + if (uc >= 0xD800 && uc <= 0xDBFF) // UTF16 surrogate pairs. + { + if (ptr[1] != '\\' || ptr[2] != 'u') + break; // missing second-half of surrogate. + sscanf(ptr + 3, "%4x", &uc2); + ptr += 6; + if (uc2 < 0xDC00 || uc2 > 0xDFFF) + break; // invalid second-half of surrogate. + uc = 0x10000 | ((uc & 0x3FF) << 10) | (uc2 & 0x3FF); + } + + len = 4; + if (uc < 0x80) + len = 1; + else if (uc < 0x800) + len = 2; + else if (uc < 0x10000) + len = 3; + ptr2 += len; + + switch (len) + { + case 4: + *--ptr2 = ((uc | 0x80) & 0xBF); + uc >>= 6; + case 3: + *--ptr2 = ((uc | 0x80) & 0xBF); + uc >>= 6; + case 2: + *--ptr2 = ((uc | 0x80) & 0xBF); + uc >>= 6; + case 1: + *--ptr2 = (uc | firstByteMark[len]); + } + ptr2 += len; + break; + default: + *ptr2++ = *ptr; + break; + } + ptr++; + } + } + *ptr2 = 0; + if (*ptr == '\"') + ptr++; + item->valuestring = out; + item->type = cJSON_String; + return ptr; +} + +/* Render the cstring provided to an escaped version that can be printed. */ +static char *print_string_ptr(const char *str) +{ + const char *ptr; + char *ptr2, *out; + int len = 0; + unsigned char token; + + if (!str) + return cJSON_strdup(""); + ptr = str; + while ((token = *ptr) && ++len) + { + if (strchr("\"\\\b\f\n\r\t", token)) + len++; + else if (token < 32) + len += 5; + ptr++; + } + + out = (char*) cJSON_malloc(len + 3); + if (!out) + return 0; + + ptr2 = out; + ptr = str; + *ptr2++ = '\"'; + while (*ptr) + { + if ((unsigned char) *ptr > 31 && *ptr != '\"' && *ptr != '\\') + *ptr2++ = *ptr++; + else + { + *ptr2++ = '\\'; + switch (token = *ptr++) + { + case '\\': + *ptr2++ = '\\'; + break; + case '\"': + *ptr2++ = '\"'; + break; + case '\b': + *ptr2++ = 'b'; + break; + case '\f': + *ptr2++ = 'f'; + break; + case '\n': + *ptr2++ = 'n'; + break; + case '\r': + *ptr2++ = 'r'; + break; + case '\t': + *ptr2++ = 't'; + break; + default: + sprintf(ptr2, "u%04x", token); + ptr2 += 5; + break; /* escape and print */ + } + } + } + *ptr2++ = '\"'; + *ptr2++ = 0; + return out; +} +/* Invote print_string_ptr (which is useful) on an item. */ +static char *print_string(cJSON *item) +{ + return print_string_ptr(item->valuestring); +} + +/* Predeclare these prototypes. */ +static const char *parse_value(cJSON *item, const char *value, const char **ep); +static char *print_value(cJSON *item, int depth, int fmt); +static const char *parse_array(cJSON *item, const char *value, const char **ep); +static char *print_array(cJSON *item, int depth, int fmt); +static const char *parse_object(cJSON *item, const char *value, const char **ep); +static char *print_object(cJSON *item, int depth, int fmt); + +/* Utility to jump whitespace and cr/lf */ +static const char *skip(const char *in) +{ + while (in && *in && (unsigned char) *in <= 32) + in++; + return in; +} + +/* Parse an object - create a new root, and populate. */ +cJSON *cJSON_Parse(const char *value, const char **ep) +{ + cJSON *c = cJSON_New_Item(); + *ep = 0; + if (!c) + return 0; /* memory fail */ + + if (!parse_value(c, skip(value), ep)) + { + cJSON_Delete(c); + return 0; + } + return c; +} + +/* Render a cJSON item/entity/structure to text. */ +char *cJSON_Print(cJSON *item) +{ + return print_value(item, 0, 1); +} +char *cJSON_PrintUnformatted(cJSON *item) +{ + return print_value(item, 0, 0); +} + +/* Parser core - when encountering text, process appropriately. */ +static const char *parse_value(cJSON *item, const char *value, const char **ep) +{ + if (!value) + return 0; /* Fail on null. */ + if (!strncmp(value, "null", 4)) + { + item->type = cJSON_NULL; + return value + 4; + } + if (!strncmp(value, "false", 5)) + { + item->type = cJSON_False; + return value + 5; + } + if (!strncmp(value, "true", 4)) + { + item->type = cJSON_True; + item->valueint = 1; + return value + 4; + } + if (*value == '\"') + { + return parse_string(item, value, ep); + } + if (*value == '-' || (*value >= '0' && *value <= '9')) + { + return parse_number(item, value); + } + if (*value == '[') + { + return parse_array(item, value, ep); + } + if (*value == '{') + { + return parse_object(item, value, ep); + } + + *ep = value; + return 0; /* failure. */ +} + +/* Render a value to text. */ +static char *print_value(cJSON *item, int depth, int fmt) +{ + char *out = 0; + if (!item) + return 0; + switch ((item->type) & 255) + { + case cJSON_NULL: + out = cJSON_strdup("null"); + break; + case cJSON_False: + out = cJSON_strdup("false"); + break; + case cJSON_True: + out = cJSON_strdup("true"); + break; + case cJSON_Int: + out = print_int(item); + break; + case cJSON_Double: + out = print_double(item); + break; + case cJSON_String: + out = print_string(item); + break; + case cJSON_Array: + out = print_array(item, depth, fmt); + break; + case cJSON_Object: + out = print_object(item, depth, fmt); + break; + } + return out; +} + +/* Build an array from input text. */ +static const char *parse_array(cJSON *item, const char *value, const char **ep) +{ + cJSON *child; + if (*value != '[') + { + *ep = value; + return 0; + } /* not an array! */ + + item->type = cJSON_Array; + value = skip(value + 1); + if (*value == ']') + return value + 1; /* empty array. */ + + item->child = child = cJSON_New_Item(); + if (!item->child) + return 0; /* memory fail */ + value = skip(parse_value(child, skip(value), ep)); /* skip any spacing, get the value. */ + if (!value) + return 0; + + while (*value == ',') + { + cJSON *new_item; + if (!(new_item = cJSON_New_Item())) + return 0; /* memory fail */ + child->next = new_item; + new_item->prev = child; + child = new_item; + value = skip(parse_value(child, skip(value + 1), ep)); + if (!value) + return 0; /* memory fail */ + } + + if (*value == ']') + return value + 1; /* end of array */ + *ep = value; + return 0; /* malformed. */ +} + +/* Render an array to text */ +static char *print_array(cJSON *item, int depth, int fmt) +{ + char **entries; + char *out = 0, *ptr, *ret; + int len = 5; + cJSON *child = item->child; + int numentries = 0, i = 0, fail = 0; + + /* How many entries in the array? */ + while (child) + numentries++, child = child->next; + /* Allocate an array to hold the values for each */ + entries = (char**) cJSON_malloc(numentries * sizeof(char*)); + if (!entries) + return 0; + memset(entries, 0, numentries * sizeof(char*)); + /* Retrieve all the results: */ + child = item->child; + while (child && !fail) + { + ret = print_value(child, depth + 1, fmt); + entries[i++] = ret; + if (ret) + len += strlen(ret) + 2 + (fmt ? 1 : 0); + else + fail = 1; + child = child->next; + } + + /* If we didn't fail, try to malloc the output string */ + if (!fail) + out = (char*) cJSON_malloc(len); + /* If that fails, we fail. */ + if (!out) + fail = 1; + + /* Handle failure. */ + if (fail) + { + for (i = 0; i < numentries; i++) + if (entries[i]) + cJSON_free(entries[i]); + cJSON_free(entries); + return 0; + } + + /* Compose the output array. */ + *out = '['; + ptr = out + 1; + *ptr = 0; + for (i = 0; i < numentries; i++) + { + strcpy(ptr, entries[i]); + ptr += strlen(entries[i]); + if (i != numentries - 1) + { + *ptr++ = ','; + if (fmt) + *ptr++ = ' '; + *ptr = 0; + } + cJSON_free(entries[i]); + } + cJSON_free(entries); + *ptr++ = ']'; + *ptr++ = 0; + return out; +} + +/* Build an object from the text. */ +static const char *parse_object(cJSON *item, const char *value, const char **ep) +{ + cJSON *child; + if (*value != '{') + { + *ep = value; + return 0; + } /* not an object! */ + + item->type = cJSON_Object; + value = skip(value + 1); + if (*value == '}') + return value + 1; /* empty array. */ + + item->child = child = cJSON_New_Item(); + if (!item->child) + return 0; + value = skip(parse_string(child, skip(value), ep)); + if (!value) + return 0; + child->string = child->valuestring; + child->valuestring = 0; + if (*value != ':') + { + *ep = value; + return 0; + } /* fail! */ + value = skip(parse_value(child, skip(value + 1), ep)); /* skip any spacing, get the value. */ + if (!value) + return 0; + + while (*value == ',') + { + cJSON *new_item; + if (!(new_item = cJSON_New_Item())) + return 0; /* memory fail */ + child->next = new_item; + new_item->prev = child; + child = new_item; + value = skip(parse_string(child, skip(value + 1), ep)); + if (!value) + return 0; + child->string = child->valuestring; + child->valuestring = 0; + if (*value != ':') + { + *ep = value; + return 0; + } /* fail! */ + value = skip(parse_value(child, skip(value + 1), ep)); /* skip any spacing, get the value. */ + if (!value) + return 0; + } + + if (*value == '}') + return value + 1; /* end of array */ + *ep = value; + return 0; /* malformed. */ +} + +/* Render an object to text. */ +static char *print_object(cJSON *item, int depth, int fmt) +{ + char **entries = 0, **names = 0; + char *out = 0, *ptr, *ret, *str; + int len = 7, i = 0, j; + cJSON *child = item->child; + int numentries = 0, fail = 0; + /* Count the number of entries. */ + while (child) + numentries++, child = child->next; + /* Allocate space for the names and the objects */ + entries = (char**) cJSON_malloc(numentries * sizeof(char*)); + if (!entries) + return 0; + names = (char**) cJSON_malloc(numentries * sizeof(char*)); + if (!names) + { + cJSON_free(entries); + return 0; + } + memset(entries, 0, sizeof(char*) * numentries); + memset(names, 0, sizeof(char*) * numentries); + + /* Collect all the results into our arrays: */ + child = item->child; + depth++; + if (fmt) + len += depth; + while (child) + { + names[i] = str = print_string_ptr(child->string); + entries[i++] = ret = print_value(child, depth, fmt); + if (str && ret) + len += strlen(ret) + strlen(str) + 2 + (fmt ? 2 + depth : 0); + else + fail = 1; + child = child->next; + } + + /* Try to allocate the output string */ + if (!fail) + out = (char*) cJSON_malloc(len); + if (!out) + fail = 1; + + /* Handle failure */ + if (fail) + { + for (i = 0; i < numentries; i++) + { + if (names[i]) + cJSON_free(names[i]); + if (entries[i]) + cJSON_free(entries[i]); + } + cJSON_free(names); + cJSON_free(entries); + return 0; + } + + /* Compose the output: */ + *out = '{'; + ptr = out + 1; + if (fmt) + *ptr++ = '\n'; + *ptr = 0; + for (i = 0; i < numentries; i++) + { + if (fmt) + for (j = 0; j < depth; j++) + *ptr++ = '\t'; + strcpy(ptr, names[i]); + ptr += strlen(names[i]); + *ptr++ = ':'; + if (fmt) + *ptr++ = '\t'; + strcpy(ptr, entries[i]); + ptr += strlen(entries[i]); + if (i != numentries - 1) + *ptr++ = ','; + if (fmt) + *ptr++ = '\n'; + *ptr = 0; + cJSON_free(names[i]); + cJSON_free(entries[i]); + } + + cJSON_free(names); + cJSON_free(entries); + if (fmt) + for (i = 0; i < depth - 1; i++) + *ptr++ = '\t'; + *ptr++ = '}'; + *ptr++ = 0; + return out; +} + +/* Get Array size/item / object item. */ +int cJSON_GetArraySize(cJSON *array) +{ + cJSON *c = array->child; + int i = 0; + while (c) + i++, c = c->next; + return i; +} +cJSON *cJSON_GetArrayItem(cJSON *array, int item) +{ + cJSON *c = array->child; + while (c && item > 0) + item--, c = c->next; + return c; +} +cJSON *cJSON_GetObjectItem(cJSON *object, const char *string) +{ + cJSON *c = object->child; + while (c && cJSON_strcasecmp(c->string, string)) + c = c->next; + return c; +} + +/* Utility for array list handling. */ +static void suffix_object(cJSON *prev, cJSON *item) +{ + prev->next = item; + item->prev = prev; +} +/* Utility for handling references. */ +static cJSON *create_reference(cJSON *item) +{ + cJSON *ref = cJSON_New_Item(); + if (!ref) + return 0; + memcpy(ref, item, sizeof(cJSON)); + ref->string = 0; + ref->type |= cJSON_IsReference; + ref->next = ref->prev = 0; + return ref; +} + +/* Add item to array/object. */ +void cJSON_AddItemToArray(cJSON *array, cJSON *item) +{ + cJSON *c = array->child; + if (!item) + return; + if (!c) + { + array->child = item; + } + else + { + while (c && c->next) + c = c->next; + suffix_object(c, item); + } +} + +void cJSON_AddItemToArrayHead(cJSON *array, cJSON *item) +{ + cJSON *c = array->child; + if (!item) + return; + if (!c) + { + array->child = item; + } + else + { + item->prev = c->prev; + item->next = c; + c->prev = item; + array->child = item; + } +} + +void cJSON_AddItemToObject(cJSON *object, const char *string, cJSON *item) +{ + if (!item) + return; + if (item->string) + cJSON_free(item->string); + item->string = cJSON_strdup(string); + cJSON_AddItemToArray(object, item); +} +void cJSON_AddItemReferenceToArray(cJSON *array, cJSON *item) +{ + cJSON_AddItemToArray(array, create_reference(item)); +} +void cJSON_AddItemReferenceToObject(cJSON *object, const char *string, + cJSON *item) +{ + cJSON_AddItemToObject(object, string, create_reference(item)); +} + +cJSON *cJSON_DetachItemFromArray(cJSON *array, int which) +{ + cJSON *c = array->child; + while (c && which > 0) + c = c->next, which--; + if (!c) + return 0; + if (c->prev) + c->prev->next = c->next; + if (c->next) + c->next->prev = c->prev; + if (c == array->child) + array->child = c->next; + c->prev = c->next = 0; + return c; +} +void cJSON_DeleteItemFromArray(cJSON *array, int which) +{ + cJSON_Delete(cJSON_DetachItemFromArray(array, which)); +} +cJSON *cJSON_DetachItemFromObject(cJSON *object, const char *string) +{ + int i = 0; + cJSON *c = object->child; + while (c && cJSON_strcasecmp(c->string, string)) + i++, c = c->next; + if (c) + return cJSON_DetachItemFromArray(object, i); + return 0; +} +void cJSON_DeleteItemFromObject(cJSON *object, const char *string) +{ + cJSON_Delete(cJSON_DetachItemFromObject(object, string)); +} + +/* Replace array/object items with new ones. */ +void cJSON_ReplaceItemInArray(cJSON *array, int which, cJSON *newitem) +{ + cJSON *c = array->child; + while (c && which > 0) + c = c->next, which--; + if (!c) + return; + newitem->next = c->next; + newitem->prev = c->prev; + if (newitem->next) + newitem->next->prev = newitem; + if (c == array->child) + array->child = newitem; + else + newitem->prev->next = newitem; + c->next = c->prev = 0; + cJSON_Delete(c); +} +void cJSON_ReplaceItemInObject(cJSON *object, const char *string, + cJSON *newitem) +{ + int i = 0; + cJSON *c = object->child; + while (c && cJSON_strcasecmp(c->string, string)) + i++, c = c->next; + if (c) + { + newitem->string = cJSON_strdup(string); + cJSON_ReplaceItemInArray(object, i, newitem); + } +} + +/* Create basic types: */ +cJSON *cJSON_CreateNull() +{ + cJSON *item = cJSON_New_Item(); + if (item) + item->type = cJSON_NULL; + return item; +} +cJSON *cJSON_CreateTrue() +{ + cJSON *item = cJSON_New_Item(); + if (item) + item->type = cJSON_True; + return item; +} +cJSON *cJSON_CreateFalse() +{ + cJSON *item = cJSON_New_Item(); + if (item) + item->type = cJSON_False; + return item; +} +cJSON *cJSON_CreateBool(int b) +{ + cJSON *item = cJSON_New_Item(); + if (item) + item->type = b ? cJSON_True : cJSON_False; + return item; +} +cJSON *cJSON_CreateDouble(double num, int sign) +{ + cJSON *item = cJSON_New_Item(); + if (item) + { + item->type = cJSON_Double; + item->valuedouble = num; + item->valueint = (int64)num; + item->sign = sign; + } + return item; +} +cJSON *cJSON_CreateInt(uint64 num, int sign) +{ + cJSON *item = cJSON_New_Item(); + if (item) + { + item->type = cJSON_Int; + item->valuedouble = (double)num; + item->valueint = (int64)num; + item->sign = sign; + } + return item; +} +cJSON *cJSON_CreateString(const char *string) +{ + cJSON *item = cJSON_New_Item(); + if (item) + { + item->type = cJSON_String; + item->valuestring = cJSON_strdup(string); + } + return item; +} +cJSON *cJSON_CreateArray() +{ + cJSON *item = cJSON_New_Item(); + if (item) + item->type = cJSON_Array; + return item; +} +cJSON *cJSON_CreateObject() +{ + cJSON *item = cJSON_New_Item(); + if (item) + item->type = cJSON_Object; + return item; +} + +/* Create Arrays: */ +cJSON *cJSON_CreateIntArray(int *numbers, int sign, int count) +{ + int i; + cJSON *n = 0, *p = 0, *a = cJSON_CreateArray(); + for (i = 0; a && i < count; i++) + { + n = cJSON_CreateDouble((long double)((unsigned int)numbers[i]), sign); + if (!i) + a->child = n; + else + suffix_object(p, n); + p = n; + } + return a; +} +cJSON *cJSON_CreateFloatArray(float *numbers, int count) +{ + int i; + cJSON *n = 0, *p = 0, *a = cJSON_CreateArray(); + for (i = 0; a && i < count; i++) + { + n = cJSON_CreateDouble((long double)numbers[i], -1); + if (!i) + a->child = n; + else + suffix_object(p, n); + p = n; + } + return a; +} +cJSON *cJSON_CreateDoubleArray(double *numbers, int count) +{ + int i; + cJSON *n = 0, *p = 0, *a = cJSON_CreateArray(); + for (i = 0; a && i < count; i++) + { + n = cJSON_CreateDouble((long double)numbers[i], -1); + if (!i) + a->child = n; + else + suffix_object(p, n); + p = n; + } + return a; +} +cJSON *cJSON_CreateStringArray(const char **strings, int count) +{ + int i; + cJSON *n = 0, *p = 0, *a = cJSON_CreateArray(); + for (i = 0; a && i < count; i++) + { + n = cJSON_CreateString(strings[i]); + if (!i) + a->child = n; + else + suffix_object(p, n); + p = n; + } + return a; +} + diff --git a/cJSON.h b/cJSON.h new file mode 100644 index 0000000..beb922c --- /dev/null +++ b/cJSON.h @@ -0,0 +1,141 @@ +/* +* Copyright (C) 2020, 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 3, or (at your option) +* any later version. +* +* This program is distributed in the hope that it will be useful, +* but WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +* GNU General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, see + +typedef int32_t int32; +typedef uint32_t uint32; +typedef int64_t int64; +typedef uint64_t uint64; + + +#ifdef __cplusplus +extern "C" +{ +#endif + +/* cJSON Types: */ +#define cJSON_False 0 +#define cJSON_True 1 +#define cJSON_NULL 2 +#define cJSON_Int 3 +#define cJSON_Double 4 +#define cJSON_String 5 +#define cJSON_Array 6 +#define cJSON_Object 7 + +#define cJSON_IsReference 256 + +/* The cJSON structure: */ +typedef struct cJSON +{ + struct cJSON *next, *prev; /* next/prev allow you to walk array/object chains. Alternatively, use GetArraySize/GetArrayItem/GetObjectItem */ + struct cJSON *child; /* An array or object item will have a child pointer pointing to a chain of the items in the array/object. */ + + int type; /* The type of the item, as above. */ + + char *valuestring; /* The item's string, if type==cJSON_String */ + int64 valueint; /* The item's number, if type==cJSON_Number */ + double valuedouble; /* The item's number, if type==cJSON_Number */ + int sign; /* sign of valueint, 1(unsigned), -1(signed) */ + + char *string; /* The item's name string, if this item is the child of, or is in the list of subitems of an object. */ +} cJSON; + +typedef struct cJSON_Hooks +{ + void *(*malloc_fn)(size_t sz); + void (*free_fn)(void *ptr); +} cJSON_Hooks; + +/* Supply malloc, realloc and free functions to cJSON */ +extern void cJSON_InitHooks(cJSON_Hooks* hooks); + +/* Supply a block of JSON, and this returns a cJSON object you can interrogate. Call cJSON_Delete when finished. */ +extern cJSON *cJSON_Parse(const char *value, const char **ep); +/* Render a cJSON entity to text for transfer/storage. Free the char* when finished. */ +extern char *cJSON_Print(cJSON *item); +/* Render a cJSON entity to text for transfer/storage without any formatting. Free the char* when finished. */ +extern char *cJSON_PrintUnformatted(cJSON *item); +/* Delete a cJSON entity and all subentities. */ +extern void cJSON_Delete(cJSON *c); + +/* Returns the number of items in an array (or object). */ +extern int cJSON_GetArraySize(cJSON *array); +/* Retrieve item number "item" from array "array". Returns NULL if unsuccessful. */ +extern cJSON *cJSON_GetArrayItem(cJSON *array, int item); +/* Get item "string" from object. Case insensitive. */ +extern cJSON *cJSON_GetObjectItem(cJSON *object, const char *string); + +/* remove gloal variable for thread safe. --by Bwar on 2020-11-15 */ +/* For analysing failed parses. This returns a pointer to the parse error. You'll probably need to look a few chars back to make sense of it. Defined when cJSON_Parse() returns 0. 0 when cJSON_Parse() succeeds. */ +/* extern const char *cJSON_GetErrorPtr(); */ + +/* These calls create a cJSON item of the appropriate type. */ +extern cJSON *cJSON_CreateNull(); +extern cJSON *cJSON_CreateTrue(); +extern cJSON *cJSON_CreateFalse(); +extern cJSON *cJSON_CreateBool(int b); +extern cJSON *cJSON_CreateDouble(double num, int sign); +extern cJSON *cJSON_CreateInt(uint64 num, int sign); +extern cJSON *cJSON_CreateString(const char *string); +extern cJSON *cJSON_CreateArray(); +extern cJSON *cJSON_CreateObject(); + +/* These utilities create an Array of count items. */ +extern cJSON *cJSON_CreateIntArray(int *numbers, int sign, int count); +extern cJSON *cJSON_CreateFloatArray(float *numbers, int count); +extern cJSON *cJSON_CreateDoubleArray(double *numbers, int count); +extern cJSON *cJSON_CreateStringArray(const char **strings, int count); + +/* Append item to the specified array/object. */ +extern void cJSON_AddItemToArray(cJSON *array, cJSON *item); +extern void cJSON_AddItemToArrayHead(cJSON *array, cJSON *item); /* add by Bwar on 2015-01-28 */ +extern void cJSON_AddItemToObject(cJSON *object, const char *string, + cJSON *item); +/* Append reference to item to the specified array/object. Use this when you want to add an existing cJSON to a new cJSON, but don't want to corrupt your existing cJSON. */ +extern void cJSON_AddItemReferenceToArray(cJSON *array, cJSON *item); +extern void cJSON_AddItemReferenceToObject(cJSON *object, const char *string, + cJSON *item); + +/* Remove/Detatch items from Arrays/Objects. */ +extern cJSON *cJSON_DetachItemFromArray(cJSON *array, int which); +extern void cJSON_DeleteItemFromArray(cJSON *array, int which); +extern cJSON *cJSON_DetachItemFromObject(cJSON *object, const char *string); +extern void cJSON_DeleteItemFromObject(cJSON *object, const char *string); + +/* Update array items. */ +extern void cJSON_ReplaceItemInArray(cJSON *array, int which, cJSON *newitem); +extern void cJSON_ReplaceItemInObject(cJSON *object, const char *string, + cJSON *newitem); + +#define cJSON_AddNullToObject(object,name) cJSON_AddItemToObject(object, name, cJSON_CreateNull()) +#define cJSON_AddTrueToObject(object,name) cJSON_AddItemToObject(object, name, cJSON_CreateTrue()) +#define cJSON_AddFalseToObject(object,name) cJSON_AddItemToObject(object, name, cJSON_CreateFalse()) +#define cJSON_AddNumberToObject(object,name,n) cJSON_AddItemToObject(object, name, cJSON_CreateNumber(n)) +#define cJSON_AddStringToObject(object,name,s) cJSON_AddItemToObject(object, name, cJSON_CreateString(s)) + + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/clickableLabel.cpp b/clickableLabel.cpp new file mode 100644 index 0000000..d669403 --- /dev/null +++ b/clickableLabel.cpp @@ -0,0 +1,35 @@ +/* +* 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 3, or (at your option) +* any later version. +* +* This program is distributed in the hope that it will be useful, +* but WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +* GNU General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, see + +ClickableLabel::ClickableLabel( QWidget* parent) + : QLabel(parent) +{ +} + +ClickableLabel::~ClickableLabel() +{ + +} +//鼠标事件 +//Mouse events +void ClickableLabel::mousePressEvent(QMouseEvent* event) +{ + emit clicked(); +} diff --git a/clickableLabel.h b/clickableLabel.h new file mode 100644 index 0000000..8d416a4 --- /dev/null +++ b/clickableLabel.h @@ -0,0 +1,37 @@ +/* + +* 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 3, or (at your option) +* any later version. +* +* This program is distributed in the hope that it will be useful, +* but WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +* GNU General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, see + +class ClickableLabel : public QLabel +{ +Q_OBJECT +public: + explicit ClickableLabel( QWidget* parent=0 ); + ~ClickableLabel(); +signals: + void clicked(); +protected: + //鼠标事件 + //Mouse events + void mousePressEvent(QMouseEvent* event);}; + +#endif // CLICKABLELABEL_H diff --git a/clock.cpp b/clock.cpp new file mode 100644 index 0000000..c1342d0 --- /dev/null +++ b/clock.cpp @@ -0,0 +1,3674 @@ +/* +* 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 3, or (at your option) +* any later version. +* +* This program is distributed in the hope that it will be useful, +* but WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +* GNU General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, see +#include "fieldvalidutil.h" +#include +#include "mediaplayerpool.h" +#include +#include "coreplayer/playcontroller.h" + +using std::string; +using clockInterface::ReturnMsg; +using clockInterface::STATUS_CODE; + + +extern void qt_blurImage(QImage &blurImage, qreal radius, bool quality, int transposed); +const double PI=3.141592; + + +#define SWITCH_BTN_HIGHLIGHT_BACK_COLOR 61,107,229,255 + +const static int DIALOG_MOVE_WIDTH = 16; +const static int DIALOG_WIDTH = 340; + +Clock::Clock(QWidget *parent) : + QWidget(parent), + ui(new Ui::Clock) +{ + //异步初始化 +// MediaPlayerPool::getInstance(); + music = new QMediaPlayer(); + //右键菜单,选择”create new translation file“;项目中会添加一个以”.ts“为后缀的文件,例如”testtranslator_zh.ts“; + //使用Qt Linguist打开该文件,就可以为指定的字符串设置译文; + //在相应的“.ts”文件的右键菜单中点击“lupdate”项,才会更新。 + //翻译完成后,点击”文件“菜单下的”发布“项,就会生成.qm文件; + QTranslator *translator = new QTranslator; + // Get system locale + //切换英文 + QLocale en_us = QLocale("en_US"); + QLocale current = QLocale(); + if (translator->load(current, QLatin1String("ukui-clock"), QLatin1String("_"), QLatin1String("/usr/share/ukui-clock/ukui31"))){ + QApplication::installTranslator(translator); + } + else{ + qDebug() << "cannot load translator ukui-clock_" << QLocale::system().name() << ".qm!"; + } + //加载Qt翻译 + + QTranslator * qtTranslator = new QTranslator; + QString translationsPath = QLibraryInfo::location(QLibraryInfo::TranslationsPath); + if(qtTranslator->load(QLocale(), QStringLiteral("qt"), QLatin1String("_"), translationsPath)){ + QApplication::installTranslator(qtTranslator); + }else{ + qDebug()<<"dbq- cannot load qt"<< QLocale::system().name() << ".qm!"; + } + + //ui 构造代码 + ui->setupUi(this); + currentTheme = new theme(); + //创建或打开数据库 + clock_sql::createConnection(); + //in order to use the same world in English + this->setWindowTitle(tr(CLOCK_TITLE_NAME)); + ui->clockTitleLabel->setText(tr(CLOCK_TITLE_NAME)); + + //创建用户手册dbus客户端 + createUserGuideDebusClient(); + mousePressed = 0; + //设置数据库 + model_setup = clock_sql::getSetupTable(this); + model_setup->select(); + //创建数据库 + m_bellQueryModel = clock_sql::getBellTable(this); + bellIni(); + //闹钟按钮图片初始化 + buttonImageInit(); + //倒计时 运行光圈页初始化 + CountdownInit(); + //秒表初始化 + stopwatchInit(); + //闹钟页初始化 + clockInit(); + setupInit(); + this->setFixedSize(390,580); + /*实现鼠标左键滑动效果 + *Realize the sliding effect of left mouse button*/ + ui->alarmListWidget -> setFrameShape(QListWidget::NoFrame); + ui->timeListWidget -> setFrameShape(QListWidget::NoFrame); + QScroller::grabGesture(ui->alarmListWidget,QScroller::LeftMouseButtonGesture); /*设置鼠标左键拖动 Set left mouse drag*/ + QScroller::grabGesture(ui->timeListWidget,QScroller::LeftMouseButtonGesture); /*设置鼠标左键拖动 Set left mouse drag*/ + ui->alarmListWidget -> setVerticalScrollMode(QAbstractItemView::ScrollPerPixel); /*设置像素级滑动 Set pixel level slide*/ + ui->timeListWidget -> setVerticalScrollMode(QAbstractItemView::ScrollPerPixel); /*设置像素级滑动 Set pixel level slide*/ + ui->alarmListWidget->setProperty("contextMenuPolicy", Qt::CustomContextMenu); /*重要:设置QListWidget的contextMenuPolicy属性,不然不能显示右键菜单*/ + ui->alarmListWidget ->setGridSize(QSize(340, 108+15)); + ui->timeListWidget ->setGridSize(QSize(340, 58+10)); + //主屏信息 + primaryManager = new PrimaryManager(); + //闹钟居中 + //move((m_pSreenInfo->m_screenWidth - this->width() + m_pSreenInfo->m_nScreen_x )/2, (m_pSreenInfo->m_screenHeight - this->height())/2); + utils = new Utils(); + utils->centerToScreen(this); + ui->switchClock->setFixedSize(40,40); + navigationBtnStyle(ui->switchClock); + ui->switchClock->setToolTip(tr(CLOCK_TITLE_NAME)); + ui->switchCountdown->setFixedSize(40,40); + navigationBtnStyle(ui->switchCountdown); + ui->switchCountdown->setToolTip(tr("Count down")); + + ui->switchStopwatch->setFixedSize(40,40); + navigationBtnStyle(ui->switchStopwatch); + ui->switchStopwatch->setToolTip(tr("Watch")); + + connect(ui->switchCountdown, SIGNAL(clicked()), this, SLOT( CountdownPageSwitch ())); + connect(ui->switchClock, SIGNAL(clicked()), this, SLOT( AlarmPageSwitch ())); + connect(ui->switchStopwatch, SIGNAL(clicked()), this, SLOT( StopwatchPageSwitch ())); + + AlarmPageSwitch ();/*初始显示闹钟界面 + Initial display alarm interface*/ + + close_or_hide_page = new close_or_hide(this); + + shadow->installEventFilter(this); + ui->alarmListWidget->installEventFilter(this); + //蓝色 + QPalette palette = ui->suspendCountdownBtn->palette(); + QColor ColorPlaceholderText(248,163,76,255); + QBrush brush3; + brush3.setColor(ColorPlaceholderText); + //主题框架1.0.6-5kylin2 + palette.setColor(QPalette::Highlight,QColor(248,163,76,255)); + palette.setColor(QPalette::Button,QColor(248,163,76,255)); + palette.setBrush(QPalette::ButtonText, QBrush(Qt::white)); + ui->suspendCountdownBtn->setPalette(palette); + startCountSingle->setEnabled(false); + ui->countdownStackedW->setCurrentIndex(0); + drawNoAlarmPrompt();//绘制无闹钟提示图标 + onMin_5btnClicked();//倒计时初始时间默认五分钟 + //字体设置 +// QString selfFont = Utils::loadFontFamilyFromTTF(); +// QFont f(selfFont); + QFont f; + f.setFamily("NotoSansCJKsc-Regular"); + f.setWeight(400); + f.setPixelSize(38); + ui->timeShowBig->setFont(f); + //监听主题 + settingsStyle(); + //主题框架1.0.6-5kylin2 + //配置重要按钮 + + //添加 + ui->addAlarmBtn->setProperty("isImportant", true); + //新建闹钟保存 + ui->saveBtnOnEditAlarm->setProperty("isImportant", true); + //倒计时 滚轮页设置页,开始 + startCountSingle->setProperty("isImportant", true); + //倒计时,运行页,开始结束 +// ui->count_stat->setProperty("isImportant", true); + //秒表 开始结束 + ui->startStopwatch->setProperty("isImportant", true); +// 倒计时 暂停继续 + ui->suspendCountdownBtn->setProperty("isImportant", true); + //倒计时 开始结束 + ui->startCountdownBtn->setProperty("useButtonPalette", true); + //闹钟编辑 取消 + ui->cancelbtnOnEditAlarm->setProperty("useButtonPalette", true); + //秒表 计次 + ui->ringBtn->setProperty("useButtonPalette", true); + //迷你窗口 + updateTinyBtn(); + //倒计时上的小闹钟 +// ui->countdownAlarmIcon->setProperty("useButtonPalette", true); + + + + +} + +Clock::~Clock() +{ + delete timer; + delete timer_2; + delete countdown_timer; + delete model; + delete model_setup; + delete dialog_repeat; + delete dialog_music; + delete count_music_sellect; + delete ui->countdownRunPage; + delete ui; + delete utils; + delete primaryManager; + delete alarmNoticeDialog; + delete countdownNoticeDialog; + delete tinycountdownDia; + delete currentTheme; +} +//重写关闭事件 +void Clock::closeEvent(QCloseEvent *event) +{ + closeHandel(); + + if(close_or_hide_page->close_flag==1){ + event->ignore(); + setWindowState(Qt::WindowMinimized); + close_or_hide_page->close_flag = 0; + }else if(close_or_hide_page->close_flag==2){ + event->accept(); + exit(0); + }else{ + event->ignore(); + } +} +void Clock::closeHandel() +{ + QPointF position = this->pos(); + XAtomHelper::setStandardWindowHint(close_or_hide_page->winId()); + close_or_hide_page->move(position.x()+20,position.y()+200); + close_or_hide_page->exec(); +} + +void Clock::enableTrayIcon() +{ + if (m_trayIcon) { + return; + } + QAction *quitAction = new QAction(tr("Quit"), this); + connect(quitAction, &QAction::triggered, qApp, + &QCoreApplication::quit); + QMenu *trayIconMenu = new QMenu(); + trayIconMenu->addAction(quitAction); + m_trayIcon = new QSystemTrayIcon(); + setDefaultTrayIconTooltip(); + m_trayIcon->setContextMenu(trayIconMenu); + QIcon trayicon = QIcon::fromTheme("kylin-alarm-clock"); + m_trayIcon->setIcon(trayicon); + connect(m_trayIcon, &QSystemTrayIcon::activated, this, [=](QSystemTrayIcon::ActivationReason r){ + if (r == QSystemTrayIcon::Trigger) { + this->show(); + } + }); + m_trayIcon->show(); +} +void Clock::updateTrayIconTooltip(QString info) +{ + if (m_trayIcon) { + m_trayIcon->setToolTip(info); + } +} + +void Clock::setDefaultTrayIconTooltip() +{ + if (m_trayIcon) { + if(m_trayIconTooltip!=""){ + m_trayIcon->setToolTip(m_trayIconTooltip); + }else{ + m_trayIcon->setToolTip(tr(CLOCK_TITLE_NAME)); + } + } +} +void Clock::disableTrayIcon() +{ +#if defined(Q_OS_LINUX) || defined(Q_OS_UNIX) + if (m_trayIcon) { + m_trayIcon->deleteLater(); + } +#endif +} +/* +*监听主题 +*/ +void Clock::settingsStyle() +{ + + GsettingSubject * subject = GsettingSubject::getInstance(); + connect(subject,&GsettingSubject::blackStyle, this,[=](){ + this->blackStyle(); + }); + connect(subject,&GsettingSubject::whiteStyle, this,[=](){ + this->whiteStyle(); + }); + connect(subject,&GsettingSubject::iconChnaged, this,[=](){ + ui->titleIcon->setPixmap(QIcon::fromTheme("kylin-alarm-clock").pixmap(24,24)); + }); + + + connect(subject,&GsettingSubject::timeZoneChanged, this,[=](QString timeZone){ + this->m_timeZone =timeZone; + }); + + connect(subject,&GsettingSubject::fontChanged, this,[=](int size){ + this->CURRENT_FONT_SIZE=size; + this->updateFront(size); + }); + + subject->iniWidgetStyle(); + subject->iniFontSize(); + subject->iniTimeZone(); + +} + + +/** + * @brief 闹钟按钮图片初始化 Alarm button picture initialization + */ +void Clock::buttonImageInit() +{ + pixmap4 = QPixmap(":/image/icon-4-16x16.png"); + //“重复”下拉框对号勾选 + repeat_on_Pixmap = QPixmap(":/image/object-select-symbolic.png"); + repeat_off_Pixmap = QPixmap(""); + //启用主题框架不需要代码 +// this->setWindowIcon(QIcon::fromTheme("kylin-alarm-clock",QIcon(":/image/kylin-alarm-clock.svg"))); + //左上角闹钟图标 + ui->titleIcon->setPixmap(QIcon::fromTheme("kylin-alarm-clock").pixmap(24,24)); + //倒计时上的小闹钟图标 + ui->countdownAlarmIcon->setPixmap(pixmap4); + ui->countdownAlarmIcon->setVisible(true); + ui->countdownAlarmIcon->setFocusPolicy(Qt::NoFocus); + + muteBtnStyle(); + minBtnStyle(); + menuBtnStyle(); + closeBtnStyle(); + + + + + //提醒铃声 倒计时设置页 + musicSelectOnCountdownSet = new Btn_new(0, tr(" bell"),Btn_new::SELECT_BTN, ui->countdownSetPage); + //提醒铃声 倒计时页面运行页 + musicSelectOnCountdownRun = new Btn_new( 0,tr(" bell"),Btn_new::SELECT_BTN, ui->countdownRunPage); + int moveHeight = 310; + int moveWidth = DIALOG_MOVE_WIDTH; + updateCountdownSelectBtnStyle(musicSelectOnCountdownSet,moveWidth,moveHeight); + updateCountdownSelectBtnStyle(musicSelectOnCountdownRun,moveWidth,moveHeight); + //闹钟名称 新建闹钟 + clockEditOnClockNew = new Btn_new( 0,tr(" name"),Btn_new::LINE_EDIT, ui->editAlarmPage); + updateCountdownSelectBtnStyle(clockEditOnClockNew,moveWidth,180); + //重复 新建闹钟 + int selectHeight = 240; + int selectGap = 60; + repeatSelectOnClockNew = new Btn_new( 0,tr(" repeat"),Btn_new::SELECT_BTN, ui->addAlarmPage); + updateClockSelectBtnStyle(repeatSelectOnClockNew,selectHeight); + selectHeight+=selectGap; + //提醒铃声 新建闹钟 + musicSelectOnClockNew = new Btn_new( 0,tr(" bell"),Btn_new::SELECT_BTN, ui->addAlarmPage); + updateClockSelectBtnStyle(musicSelectOnClockNew,selectHeight); + selectHeight+=selectGap; + //稍后提醒 新建闹钟 + remindSelectOnClockNew = new Btn_new( 0,tr(" remind"),Btn_new::SELECT_BTN, ui->addAlarmPage); + updateClockSelectBtnStyle(remindSelectOnClockNew,selectHeight); + +} +/* +*倒计时页初始化 +*Countdown page initialization +*/ +void Clock::CountdownInit() +{ + /*初始化定时器 + Initialize timer*/ + countdown_timer = new QTimer(); + /*信号和槽 + Signals and slots*/ + //倒计时开始-结束 + connect(ui->startCountdownBtn, SIGNAL(clicked()), this, SLOT(startbtnCountdown()) ); +// connect(tinycountdownDia, SIGNAL(finishClick()), this, SLOT(tinyCountdownFinish()) ); + //倒计时执行 + connect(countdown_timer, SIGNAL(timeout()), this, SLOT(statCountdownMsec())); + /*设置定时器每个多少毫秒发送一个timeout()信号 + Set the timer to send a timeout () signal every milliseconds*/ + countdown_timer->setInterval(10); + countdown_hour = 0; + countdown_minute = 0; + countdown_second = 9; + countdown_pushflag = 0; + + countdown_isStarted = 0; + countdown_isStarted_2 = 0; + ui->countdownRunPage->countdownRunRoundBar->setRange(0,COUNTDOWN_TIME); + /*初始化倒计时进度圈 + Initialize countdown progress circle*/ + ui->countdownRunPage->countdownRunRoundBar->setValue(COUNTDOWN_TIME); + //父的顶部 + ui->startCountdownBtn->raise(); + //初始化倒计时弹窗 + countdownNoticeDialog = new Natice_alarm(60,-1); + countdownNoticeDialog->timer->stop(); + countdownNoticeDialog->timer_xumhuan->stop(); + countdownNoticeDialog->m_musicPlayer->stop(); + //小型窗体 + if(tinycountdownDia==nullptr){ + tinycountdownDia = new tinyCountdown(); + } + //绑定主窗体操作 + connect(tinycountdownDia,SIGNAL(mainWindowClick()),this,SLOT(activeWindow())); + //结束 + connect(tinycountdownDia, &tinyCountdown::finishClick, this, [=](){ + tinyCountdownFinish(); + } ); + //暂停 + connect(tinycountdownDia, &tinyCountdown::suspendClick, this, [=](int onRun){ + countdown_isStarted_2 = onRun; + onCountPushClicked(); + } ); +} + +/* +*秒表页初始化 +*Stopwatch page initialization +*/ +void Clock::stopwatchInit() +{ + /*初始化定时器 + Initialize timer*/ + timer = new QTimer(); + /*信号和槽 + Signals and slots*/ + connect(timer, SIGNAL(timeout()), this, SLOT(CountDown())); + /*设置定时器每个多少毫秒发送一个timeout()信号 + Set the timer to send a timeout () signal every milliseconds*/ + timer->setInterval(10); + //显示时间大 + ui->timeShowBig->setText("00:00.00"); + //显示时间小 + ui->timeShowSmall->setText("00:00.00"); + isStarted = 0; + hour=0; + minute=0; + second=0; + pushflag=0 ; + /*时间间隔定时器 + Time interval timer*/ + timer_2 = new QTimer(); + //秒表的 每次计次后清零重新计算的时间 + connect(timer_2, SIGNAL(timeout()), this, SLOT(stopwatchJg())); + timer_2->setInterval(10); + stopwatch_hour = 0; + stopwatch_minute = 0; + stopwatch_second = 0; + stopwatch_isStarted = 0; + + ui->timeShowBig->move(90,125); + ui->timeShowSmall->move(90,190); + ui->timeListWidget->move(25,230); + ui->startStopwatch->raise(); + ui->ringBtn->raise(); + //计次间隔时间最长,最短 + timeSepOrderIndex = new QMap(); + hisLongShortIndex = new QList(); +} + +/* +*闹钟页初始化 +*Alarm page initialization +*/ +void Clock::clockInit() +{ +// alarmNoticeDialog = new Natice_alarm(60,-1); + QTimer *timer_clock = new QTimer(this); + //动态监控闹钟与本地时间 + connect(timer_clock, SIGNAL(timeout()), this, SLOT(timerUpdate()) );/*动态获取时间 + Dynamic acquisition time*/ + timer_clock->start(1000); + connect( ui->addAlarmBtn, SIGNAL(clicked()), this, SLOT(setAlarmClock()) );/*添加闹钟 + Add alarm*/ + ui->timeShowBig->setAlignment(Qt::AlignHCenter); + ui->timeShowSmall->setAlignment(Qt::AlignHCenter); + ui->remainTime->setAlignment(Qt::AlignHCenter); + //单个表读取和写入数据库记录的高级接口 + model = new QSqlTableModel(this); + model->setTable("clock"); + model->setEditStrategy(QSqlTableModel::OnManualSubmit); + model->select(); /*选取整个表的所有行 + Select all rows of the entire table*/ + /*初始化一个包含两个Action(Delete和ClearAll)的菜单*/ + popMenu_In_ListWidget_ = new QMenu(this); + action_Delete_In_ListWidget_ = new QAction(tr("Delete"), this); + action_Clear_In_ListWidget_ = new QAction(tr("ClearAll"), this); + action_edit_In_ListWidget_ = new QAction(tr("edit"), this); + popMenu_In_ListWidget_->addAction(action_edit_In_ListWidget_); + popMenu_In_ListWidget_->addAction(action_Delete_In_ListWidget_); + + connect(this->action_Delete_In_ListWidget_, SIGNAL(triggered()), this, SLOT(deleteAlarm())); + //编辑 + connect(this->action_edit_In_ListWidget_, SIGNAL(triggered()), this, SLOT(listdoubleClickslot())); + connect(ui->alarmListWidget,SIGNAL(itemDoubleClicked(QListWidgetItem*)),this,SLOT(listdoubleClickslot())); + connect(ui->saveBtnOnEditAlarm, SIGNAL(clicked()), this, SLOT(setAlarmSave()) ); + connect(ui->startStopwatch, SIGNAL(clicked()), this, SLOT(onPushbuttonStartClicked())); + connect(ui->ringBtn, SIGNAL(clicked()), this, SLOT(onPushbuttonRingClicked())); + connect(ui->cancelbtnOnEditAlarm, SIGNAL(clicked()), this, SLOT(alarmCancelSave()) ); + //与下拉框绑定 + connect(repeatSelectOnClockNew, SIGNAL(clicked()), this, SLOT(alarmRepeat()) ); + connect(musicSelectOnClockNew, SIGNAL(clicked()), this, SLOT(selectAlarmMusic()) ); + connect(remindSelectOnClockNew, SIGNAL(clicked()), this, SLOT(selectRemindLate()) ); + connect(musicSelectOnCountdownSet, SIGNAL(clicked()), this, SLOT(countdownMusicSellect())); + connect(musicSelectOnCountdownRun, SIGNAL(clicked()), this, SLOT(countdownMusicSellect())); + + + //暂停继续按钮 + connect(ui->suspendCountdownBtn, SIGNAL(clicked()), this, SLOT(onCountPushClicked())); + + + connect(ui->tinyWindowBtn, SIGNAL(clicked()), this, SLOT(onTinyClicked())); + /*绑定右键显示菜单:在单击右键之后会执行槽函数, 槽函数中负责弹出右键菜单*/ + connect(ui->alarmListWidget, SIGNAL(customContextMenuRequested(const QPoint &)), + this, SLOT(onCustomContextMenuRequested(const QPoint &))); + + //初始化SystemTimeFlag,不然初始值可能不为0或者1 + iniSystemTimeFlag(); + //绘制闹钟列表 + updateAlarmClock(); + +} + +void Clock::keyPressEvent(QKeyEvent *event) +{ + if(16777264==event->key()){ + callUserGuide(); + } + +} + +void Clock::callUserGuide() +{ + if(userGuideInterface!=nullptr){ + userGuideInterface->call(QString("showGuide"), "ukui-clock"); + } +} + + + +/* +* 事件处理函数 +*/ +void Clock::onCustomContextMenuRequested(const QPoint &pos) +{ + /*弹出右键菜单*/ + if(ui->alarmListWidget->itemAt(pos)!=NULL){ + //右键弹窗与闹钟绑定 + popMenu_In_ListWidget_->exec(QCursor::pos()); + } +} + +/* +* 默认初始设置 +* Default initial settings +*/ +void Clock::setupInit() +{ + countdownSetStartTime();/*倒计时初始化数字转盘 + Countdown initialization digital turntable*/ + + alarmSetStartTime();/*闹钟初始化数字转盘 + Alarm initialization digital turntable*/ + modelSetupSet(); /*设置数据库初始化 + Set database initialization*/ + textTimerupdate(); + clockEditOnClockNew->clockNameLineEdit->setMaxLength(16);/*限制闹钟名字长度为9个字符*/ + + /*设置输入框无视空格,过滤特殊字符*/ + QRegExp rx = QRegExp("^[\u4E00-\u9FA5A-Za-z0-9_]+$"); + QRegExpValidator* validator = new QRegExpValidator(rx); + clockEditOnClockNew->clockNameLineEdit->setValidator(validator); + + //倒计时的铃声 + QString bellId = model_setup->index(0, 1).data().toString(); + QString bellName = m_selectBtnUtil->getBellNameById(bellId); + musicSelectOnCountdownSet->textLabel->setText(bellName); + musicSelectOnCountdownRun->textLabel->setText(bellName); + + //重复下拉框 + int moreWidth = 20; + dialog_repeat = new set_alarm_repeat_Dialog(DIALOG_WIDTH+moreWidth,290,9,ui->editAlarmPage);dialog_repeat->hide(); + //铃声下拉框 + int bellSize = m_selectBtnUtil->getBellListSize(); + dialog_music = new set_alarm_repeat_Dialog(DIALOG_WIDTH+moreWidth,172,bellSize,ui->editAlarmPage);dialog_music->hide(); + //稍后提醒下拉框 + dialog_remind_late = new set_alarm_repeat_Dialog(DIALOG_WIDTH+moreWidth,258,6,ui->editAlarmPage);dialog_remind_late->hide(); + //倒计时铃声选择 + count_music_sellect = new set_alarm_repeat_Dialog(DIALOG_WIDTH+moreWidth,172,bellSize,ui->countdownPage);count_music_sellect->hide(); + + setMusicSelectDialogListById(bellId,count_music_sellect->listWidget); + //存储重复选择的星期,默认清零 + for (int i = 0; i < 9; i++) { + repeat_day[i] = 0; + } + + + connect(dialog_repeat->listWidget,SIGNAL(itemClicked(QListWidgetItem*)),this,SLOT(repeatListclickslot())); + connect(dialog_music->listWidget,SIGNAL(itemClicked(QListWidgetItem*)),this,SLOT(musicListclickslot())); + connect(dialog_remind_late->listWidget,SIGNAL(itemClicked(QListWidgetItem*)),this,SLOT(remindLateListClickSlot())); + connect(count_music_sellect->listWidget,SIGNAL(itemClicked(QListWidgetItem*)),this,SLOT(countMusicListclickslot())); + connect(dialog_repeat,&set_alarm_repeat_Dialog::dialogClose,this,[=](){ + repeatSelectOnClockNew->updateIconLabel(0); + }); + connect(dialog_music,&set_alarm_repeat_Dialog::dialogClose,this,[=](){ + musicSelectOnClockNew->updateIconLabel(0); + }); + connect(dialog_remind_late,&set_alarm_repeat_Dialog::dialogClose,this,[=](){ + remindSelectOnClockNew->updateIconLabel(0); + }); + connect(count_music_sellect,&set_alarm_repeat_Dialog::dialogClose,this,[=](){ + musicSelectOnCountdownSet->updateIconLabel(0); + musicSelectOnCountdownRun->updateIconLabel(0); + }); + indexWeekdayMap = new QHash(); + indexWeekdayMap->insert(0,":monday"); + indexWeekdayMap->insert(1,":tuesday"); + indexWeekdayMap->insert(2,":wednesday"); + indexWeekdayMap->insert(3,":thusday"); + indexWeekdayMap->insert(4,":friday"); + indexWeekdayMap->insert(5,":saturday"); + indexWeekdayMap->insert(6,":sunday"); +} + +void Clock::bellIni() +{ + m_selectBtnUtil = new SelectBtnUtil(); + int rowNum = m_bellQueryModel->rowCount(); + if (rowNum < 1) { + QList * defaultBell = SelectBtnUtil::getDefaultBellList(); + QList * defaultBellTr = SelectBtnUtil::getDefaultBellTrList(); + for (int i=0;isize();i++) { + m_bellQueryModel->insertRow(i); + QString temp = defaultBell->at(i); + QString tempTr = defaultBellTr->at(i); + m_bellQueryModel->setData(m_bellQueryModel->index(i, 0), Utils::getRandomId()); + m_bellQueryModel->setData(m_bellQueryModel->index(i, 1), tempTr); + m_bellQueryModel->setData(m_bellQueryModel->index(i, 2), temp); + QString path = DEFAULT_BELL_SAVE_PATH; + path = path.append(temp).append(".wav"); + m_bellQueryModel->setData(m_bellQueryModel->index(i, 3), path); + QDateTime time = QDateTime::currentDateTime(); //获取当前时间 + qint64 timeT = time.toMSecsSinceEpoch(); + m_bellQueryModel->setData(m_bellQueryModel->index(i, 4), timeT); + m_bellQueryModel->setData(m_bellQueryModel->index(i, 5), 0); + //排序,暂停1ms + QThread::msleep(1); + } + delete defaultBell; + m_bellQueryModel->submitAll(); + m_selectBtnUtil->refreshBellData(); + } +} + +/* + * 时间间隔执行 + * Interval calculation execution callback + */ +void Clock::stopwatchJg() +{ + if (stopwatch_hour < 10) { + QString hours_str = QString::number(stopwatch_hour); + stopwatch_jg_h = "0"+hours_str; + } else { + stopwatch_jg_h = QString::number(stopwatch_hour); + } + + if (stopwatch_minute < 10) { + QString minute_str = QString::number(stopwatch_minute); + stopwatch_jg_m = "0"+minute_str; + }else { + stopwatch_jg_m = QString::number(stopwatch_minute); + } + + if (stopwatch_second < 10) { + QString second_str = QString::number(stopwatch_second); + stopwatch_jg_s = "0"+second_str; + } else { + stopwatch_jg_s = QString::number(stopwatch_second); + } + + ui->timeShowSmall->setText(stopwatch_jg_h+TIME_SEPARATOR+stopwatch_jg_m+"."+stopwatch_jg_s); + + stopwatch_second++; + if (stopwatch_second==100) { + stopwatch_minute++; stopwatch_second=0;} + if (stopwatch_minute==60) { + stopwatch_hour++; stopwatch_minute=0;} +} + +/* + * 秒表执行 + * Stopwatch execution + */ +void Clock::CountDown() +{ + if (hour < 10) { + QString hours_str = QString::number(hour); + stopwatch_h = "0"+hours_str; + } else { + stopwatch_h = QString::number(hour); + } + + if (minute < 10) { + QString minute_str = QString::number(minute); + stopwatch_m = "0"+minute_str; + } else { + stopwatch_m = QString::number(minute); + } + + if (second < 10) { + QString second_str = QString::number(second); + stopwatch_s = "0"+second_str; + } else { + stopwatch_s = QString::number(second); + } + ui->timeShowBig->setText(stopwatch_h+TIME_SEPARATOR+stopwatch_m+"."+stopwatch_s); +// QString selfFont = Utils::loadFontFamilyFromTTF(); +// QFont f(selfFont); + QFont f; + f.setFamily("NotoSansCJKsc-Regular"); + f.setWeight(400); + f.setPixelSize(38); + ui->timeShowBig->setFont(f); + //命名很不友好 + //second单位是10ms + second++; + //minute单位是秒 + if (second==100){ + minute++; second=0; + } + //hour单位是分钟 + if (minute==60){ + hour++; minute=0; + } + +} +/* + * 秒表开始暂停继续 + * Stopwatch start pause continue + */ +void Clock::onPushbuttonStartClicked() +{ + if (!isStarted) { + ui->startStopwatch->setText(tr("suspend")); + QPalette palette = ui->startStopwatch->palette(); + QColor ColorPlaceholderText(248,163,76,255); + QBrush brush2; + brush2.setColor(ColorPlaceholderText); + //主题框架1.0.6-5kylin2 + palette.setColor(QPalette::Highlight,QColor(248,163,76,255)); + palette.setColor(QPalette::Button,QColor(248,163,76,255)); + palette.setBrush(QPalette::ButtonText, QBrush(Qt::white)); + ui->startStopwatch->setPalette(palette); + + if (stopwatch_isStarted == 0) { + timer_2->start(); + stopwatch_isStarted = 1; + } + timer->start(); + isStarted=1; + if (!stopwatch_Animation) { + stopwatchStartAnimation(); + stopwatch_Animation = 1; + } + ui->ringBtn->setText(tr("count")); + } else { + timer->stop(); + /*查询间隔计时器是否启动 + Query whether the interval timer starts*/ + if (stopwatch_isStarted == 1) { + timer_2->stop(); + stopwatch_isStarted = 0; + } + isStarted=0; + ui->startStopwatch->setText(tr("continue")); + + QPalette palette = ui->startStopwatch->palette(); + QColor ColorPlaceholderText(248,163,76,255); + QBrush brush2; + brush2.setColor(ColorPlaceholderText); + //主题框架1.0.6-5kylin2 + palette.setColor(QPalette::Highlight,QColor(69, 173, 110,255)); + palette.setColor(QPalette::Button,QColor(69, 173, 110,255)); + palette.setBrush(QPalette::ButtonText, QBrush(Qt::white)); + ui->startStopwatch->setPalette(palette); + ui->ringBtn->setText(tr("reset")); + } + return; +} + +/* + *倒计时标签动画移动 + *Countdown start animation move + */ +void Clock::stopwatchStartAnimation() +{ + animation1 = new QPropertyAnimation(ui->timeShowBig, "geometry"); + animation1->setDuration(1000); + animation1->setKeyValueAt(0, QRect(90, 125, 210, 70)); + animation1->setEndValue(QRect(90, 4, 210, 70)); + animation1->start(); + + animation2 = new QPropertyAnimation(ui->timeShowSmall, "geometry"); + animation2->setDuration(1000); + animation2->setKeyValueAt(0, QRect(90, 173, 210, 41)); + animation2->setEndValue(QRect(90, 60, 210, 41)); + animation2->start(); + + animation3 = new QPropertyAnimation(ui->timeListWidget, "geometry"); + animation3->setDuration(1000); + animation3->setKeyValueAt(0, QRect(25 ,230, 340, 270)); + animation3->setEndValue(QRect(25, 109, 340, 270)); + animation3->start(); +} +/* + * 倒计时开始动画移动 + * Countdown start animation move + */ +void Clock::stopwatchStopAnimation() +{ + animation1 = new QPropertyAnimation(ui->timeShowBig, "geometry"); + animation1->setDuration(1000); + animation1->setKeyValueAt(0, QRect(90, 4, 210, 70)); + animation1->setEndValue(QRect(90, 125, 210, 70)); + animation1->start(); + + animation2 = new QPropertyAnimation(ui->timeShowSmall, "geometry"); + animation2->setDuration(1000); + animation2->setKeyValueAt(0, QRect(90, 55, 210, 41)); + animation2->setEndValue(QRect(90, 183, 210, 41)); + animation2->start(); + + animation3 = new QPropertyAnimation(ui->timeListWidget, "geometry"); + animation3->setDuration(1000); + animation3->setKeyValueAt(0, QRect(25 ,109, 340, 270)); + animation3->setEndValue(QRect(25, 230, 340, 270)); + animation3->start(); +} + +/* + * 计次 + * times count + */ +void Clock::onPushbuttonRingClicked() +{ + if (!isStarted) { + //复位 + //清空数据 + timeSepOrderIndex->clear(); + hisLongShortIndex->clear(); + if (nullptr != timer) { + timer->stop(); + timer_2->stop(); + ui->timeShowBig->setText("00:00.00"); + ui->timeShowSmall->setText("00:00.00"); + isStarted = 0; + stopwatch_isStarted = 0; + hour = 0; minute = 0;second = 0; + stopwatch_hour = 0; + stopwatch_minute = 0; + stopwatch_second = 0; + ui->startStopwatch->setText(tr("start")); + ui->startStopwatch->setPalette(ui->addAlarmBtn->palette()); + for (int i=0; i < stopwatch_item_flag; i++) { + delete stopwatch_w[i]; + delete stopwatch_aItem[i]; + } + stopwatch_item_flag = 0; + if (stopwatch_Animation) { + stopwatchStopAnimation(); + stopwatch_Animation = 0; + } + } + }else{ + //计次 + if (stopwatch_isStarted == 0) { + timer_2->start(); + stopwatch_isStarted = 1; + } + if (stopwatch_item_flag < 100) { + stopwatch_aItem[stopwatch_item_flag] =new QListWidgetItem; + stopwatch_aItem[stopwatch_item_flag]->setSizeHint(QSize(340,58)); + stopwatch_aItem[stopwatch_item_flag]->setTextColor(QColor(255, 0, 0, 255)); + ui->timeListWidget->insertItem(0,stopwatch_aItem[stopwatch_item_flag]); + + ui->timeListWidget->setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded); + ui->timeListWidget->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); + stopwatch_w[stopwatch_item_flag] = new stopwatch_item(ui->timeListWidget); + + stopwatch_w[stopwatch_item_flag]->stopwatch1->setText(tr("count")+QString::number(stopwatch_item_flag+1)); + stopwatch_w[stopwatch_item_flag]->stopwatch2->setText(tr("interval ")+stopwatch_jg_h+TIME_SEPARATOR+stopwatch_jg_m+"."+stopwatch_jg_s); + //间隔时间存入列表 + long sepTime = stopwatch_hour*3600+stopwatch_minute*60+stopwatch_second; + timeSepOrderIndex->insert(sepTime,stopwatch_item_flag); + //添加标签 + updateLongestShortLabel(); + + stopwatch_w[stopwatch_item_flag]->stopwatch3->setText(stopwatch_h+TIME_SEPARATOR+stopwatch_m+"."+stopwatch_s); +// QString selfFont = Utils::loadFontFamilyFromTTF(); +// QFont f(selfFont); + QFont f; + f.setFamily("NotoSansCJKsc-Regular"); + f.setWeight(400); + f.setPixelSize(24); + stopwatch_w[stopwatch_item_flag]->stopwatch3->setFont(f); + + ui->timeListWidget->setItemWidget(stopwatch_aItem[stopwatch_item_flag],stopwatch_w[stopwatch_item_flag]); + + stopwatch_hour = 0; + stopwatch_minute = 0; + stopwatch_second = 0; + + stopwatch_item_flag++; + + } else if(stopwatch_item_flag >= 100) { + QToolTip::showText(mapToGlobal(ui->timeListWidget->pos()+QPoint(90,340)),tr("up to 100 times"),this); + } + } + + + //秒表页面子项字体更新 + updateStopwatchItemFront(CURRENT_FONT_SIZE); +} + +void Clock::updateLongestShortLabel() +{ + QListIterator iterator(*hisLongShortIndex); + while (iterator.hasNext()) { + int index = iterator.next(); + stopwatch_w[index]->updateTipCommonStyle(); + } + long shortIndex = timeSepOrderIndex->first(); + stopwatch_w[shortIndex]->updateTipShortestStyle(); + int longIndex = timeSepOrderIndex->last(); + stopwatch_w[longIndex]->updateTipLongestStyle(); + //存储到历史 + hisLongShortIndex->clear(); + hisLongShortIndex->append(shortIndex); + hisLongShortIndex->append(longIndex); + + +} + +/* + *复位 + *reset + */ +void Clock::onPushbuttonTimeselectClicked() +{ + if (nullptr != timer) { + if (isStarted) + return; + timer->stop(); + timer_2->stop(); + ui->timeShowBig->setText("00:00.00"); + ui->timeShowSmall->setText("00:00.00"); + isStarted = 0; + stopwatch_isStarted = 0; + hour = 0; minute = 0;second = 0; + stopwatch_hour = 0; + stopwatch_minute = 0; + stopwatch_second = 0; + ui->startStopwatch->setText(tr("start")); + ui->startStopwatch->setPalette(ui->addAlarmBtn->palette()); + + for (int i=0; i < stopwatch_item_flag; i++) { + delete stopwatch_w[i]; + delete stopwatch_aItem[i]; + } + stopwatch_item_flag = 0; + if (stopwatch_Animation) { + stopwatchStopAnimation(); + stopwatch_Animation = 0; + } + } +} + +/* + * 窗口关闭 + * window closing + */ +void Clock::windowClosingClicked() +{ + closeHandel(); + + if(close_or_hide_page->close_flag==1){ +// setWindowState(Qt::WindowMinimized); + this->hide(); + //加入托盘 + enableTrayIcon(); + close_or_hide_page->close_flag = 0; + }else if(close_or_hide_page->close_flag==2){ + exit(0); + } +} + +/* + *窗口最小化 + *window minimizing + */ +void Clock::windowMinimizingClicked() +{ + this->showNormal(); + this->showMinimized(); +} + +void Clock::muteAllBell() +{ + //静音反转 + m_muteOn = !m_muteOn; + QPixmap pixmap = QPixmap(":/image/miniIcon/mute-off.png"); + if(m_muteOn){ + pixmap = QPixmap(":/image/miniIcon/mute-on.png"); + } + ui->muteBtn->setIcon(pixmap); + if(m_muteOn){ + QPoint position = frameGeometry().center(); + int x = position.x()-m_commonToolTip->geometry().width()/2; + int y = position.y()-m_commonToolTip->geometry().height()/2; + m_commonToolTip->move(x,y); + m_commonToolTip->show(); + m_commonToolTipRemainTime = 2; + m_commonToolTipCloseTimer->start(); + //存储静音到数据库 + model_setup->setData(model_setup->index(0, 0), 1);//静音 Mute + }else{ + model_setup->setData(model_setup->index(0, 0), 0);//静音 Mute + } + model_setup->submitAll(); +} + +/* + * 倒计时切换 + * Countdown switch + */ +void Clock:: CountdownPageSwitch () +{ + setSwitchHighlightColor(ui->switchCountdown); + setSwitchDefaultColor(ui->switchClock); + setSwitchDefaultColor(ui->switchStopwatch); + ui->mainWidget->setCurrentIndex(0); +} +void Clock::setBtnIcon(QPushButton *btn, QString imgUrl, QString localUrl) +{ + QIcon icon=Utils::getQIcon(imgUrl,localUrl); + btn->setIcon(QIcon::fromTheme(imgUrl)); + btn->setIconSize(QSize(18, 18)); + QPainter p(btn); +// 表示引擎应尽可能对图元的边缘进行抗锯齿。 + p.setRenderHint(QPainter::Antialiasing); +} +void Clock::setDefaultIcon(QPushButton *btn) +{ + if(btn==ui->switchClock){ + setBtnIcon(ui->switchClock,"ukui-alarm-symbolic",":/image/alarm.png"); + }else if(btn==ui->switchCountdown){ + setBtnIcon(ui->switchCountdown,"ukui-countselect-symbolic",":/image/count.png"); + }else if(btn==ui->switchStopwatch){ + setBtnIcon(ui->switchStopwatch,"ukui-stopwatch-symbolic",":/image/stopwatch.png"); + } + if(theme::themetype==1){ + changeIconHeight(btn); + } +} +QColor Clock::getHighlightActive() +{ + return palette().color(QPalette::Active,QPalette::Highlight); +} + +QColor Clock::getButtonActive() +{ + return palette().color(QPalette::Active,QPalette::Button); +} +void Clock::setSwitchDefaultColor(QPushButton * btn) +{ + auto pa = btn->palette(); + QColor btnAcCol = getButtonActive(); + pa.setColor(QPalette::Active,QPalette::Button,btnAcCol); + btn->setPalette(pa); + setDefaultIcon(btn); +} +void Clock::setSwitchHighlightColor(QPushButton * btn) +{ + + auto pa = btn->palette(); + QColor highAcCol = getHighlightActive(); + pa.setColor(QPalette::Active,QPalette::Button,highAcCol); + btn->setPalette(pa); + //修改图标颜色 + changeIconHeight(btn); + +} +/* + * 闹钟窗口切换 + * Alarm window switchin + */ +void Clock:: AlarmPageSwitch () +{ + setSwitchDefaultColor(ui->switchCountdown); + setSwitchHighlightColor(ui->switchClock); + setSwitchDefaultColor(ui->switchStopwatch); + ui->mainWidget->setCurrentIndex(1); +} +void Clock::changeIconHeight(QPushButton *btn) +{ + QPixmap pix = btn->icon().pixmap(btn->iconSize()); + QPixmap tarPix=theme::changeIconColor(pix,palette().highlightedText().color()); + btn->setIcon(QIcon(tarPix)); +} +/* + * 秒表窗口切换 + * Stopwatch window switch + */ +void Clock:: StopwatchPageSwitch () +{ + setSwitchDefaultColor(ui->switchCountdown); + setSwitchDefaultColor(ui->switchClock); + setSwitchHighlightColor(ui->switchStopwatch); + ui->mainWidget->setCurrentIndex(2); +} + + +/** + * @brief 闹钟列表项 + */ +void Clock::textTimerupdate() +{ + //闹钟表条数 + int rowNum = model->rowCount(); + model_setup->select(); + QTime time = QTime::currentTime(); + int time_H = time.hour(); + int time_M = time.minute(); + int time_S = time.second(); + //Timeformat + //系统24时 + if (checkSystem24()) { + set24ClockItem(time_H,time_M,time_S,rowNum); + } else { + //系统12时制 + set12ClockItem(time_H,time_M,time_S,rowNum); + } +} + +/** + * @brief 设置24时制闹钟 + */ +void Clock::set24ClockItem(int time_H,int time_M,int time_S,int rowNum) +{ + if(system_time_flag == 0){ + system_time_flag = 1; + clearClockItem( rowNum); + } else { + system_time_flag = 1; + } +} +/** + * @brief 设置12时制闹钟 + */ +void Clock::set12ClockItem(int time_H,int time_M,int time_S,int rowNum) +{ + //原来是24时,则重新构建 + if (system_time_flag == 1) { + system_time_flag = 0; + clearClockItem(rowNum); + } else { + system_time_flag = 0; + } +} +/** + * @brief 清理重新构建闹钟列表 + */ +void Clock::clearClockItem(int rowNum) +{ + for(int i=0; iindex(0, 0).data().toInt(); + m_muteOn = mute==1?true:false; + QPixmap pixmap = QPixmap(":/image/miniIcon/mute-off.png"); + if(m_muteOn){ + pixmap = QPixmap(":/image/miniIcon/mute-on.png"); + } + ui->muteBtn->setIcon(pixmap); + ui->muteBtn->setIconSize(QSize(32, 32)); + QPainter p(ui->muteBtn); + //表示引擎应尽可能对图元的边缘进行抗锯齿。 + p.setRenderHint(QPainter::Antialiasing); + ui->muteBtn->setFlat(true); + ui->muteBtn->setVisible(true); + ui->muteBtn->setFocusPolicy(Qt::NoFocus); + ui->muteBtn->setToolTip(tr("mute")); + //弹窗初始化 + m_commonToolTip = new CommonToolTip(this); + m_commonToolTip->hide(); + m_commonToolTip->setMsgText(tr("All bells are off")); + //弹窗定时 + m_commonToolTipCloseTimer = new QTimer(this); + m_commonToolTipCloseTimer->setInterval(1000); + connect(m_commonToolTipCloseTimer, &QTimer::timeout, this, [=](){ + m_commonToolTipRemainTime--; + if(m_commonToolTipRemainTime<=0){ + m_commonToolTipCloseTimer->stop(); + m_commonToolTip->hide(); + } + }); + connect(ui->muteBtn, SIGNAL(clicked()), this, SLOT(muteAllBell())); +} +/** + * @brief 最小化按钮样式 + */ +void Clock::minBtnStyle() +{ + //窗口最小化 + ui->minmizeBtn->setIcon(QIcon::fromTheme("window-minimize-symbolic")); + ui->minmizeBtn->setFlat(true); + ui->minmizeBtn->setVisible(true); + ui->minmizeBtn->setFocusPolicy(Qt::NoFocus); + ui->minmizeBtn->setProperty("useIconHighlightEffect", 0x2); + ui->minmizeBtn->setProperty("isWindowButton", 0x01); + ui->minmizeBtn->setToolTip(tr("Minimize")); + connect(ui->minmizeBtn, SIGNAL(clicked()), this, SLOT(windowMinimizingClicked())); +} +/** + * @brief 关闭按钮样式 + */ +void Clock::closeBtnStyle() +{ + + //窗口关闭 + ui->closeTitleBtn->setIcon(QIcon::fromTheme("window-close-symbolic")); + ui->closeTitleBtn->setFlat(true); + ui->closeTitleBtn->setVisible(true); + ui->closeTitleBtn->setFocusPolicy(Qt::NoFocus); + //主题框架1.0.6-5kylin2 + ui->closeTitleBtn->setProperty("isWindowButton", 0x2); + ui->closeTitleBtn->setProperty("useIconHighlightEffect", 0x8); + ui->closeTitleBtn->setToolTip(tr("Quit")); + connect(ui->closeTitleBtn, SIGNAL(clicked()), this, SLOT(windowClosingClicked())); +} +/** + * @brief 菜单按钮样式 + */ +void Clock::menuBtnStyle() +{ + //菜单项 + ui->menuBtn->setIcon(QIcon::fromTheme("open-menu-symbolic")); + ui->menuBtn->setVisible(true); + ui->menuBtn->setFocusPolicy(Qt::NoFocus); + ui->menuBtn->setToolTip(tr("Menu")); + ui->menuBtn->setProperty("useIconHighlightEffect", 0x2); + ui->menuBtn->setProperty("useButtonPalette", true); + /*设置关于页*/ + ui->menuBtn->setPopupMode(QToolButton::InstantPopup); + m_menu = new QMenu(ui->menuBtn); + m_menu->setProperty("fillIconSymbolicColor", true); +// ui->pushButton_12->setProperty("useButtonPalette", true); + //菜单项的操作 + //帮助 + QAction *m_helpAction = new QAction(m_menu); + //关于 + QAction *m_aboutAction = new QAction(m_menu); + //关闭 + QAction *m_closeAction = new QAction(m_menu); + m_helpAction->setText(tr("Help")); + m_aboutAction->setText(tr("About")); + m_closeAction->setText(tr("Close")); + m_menu->addAction(m_helpAction); + m_menu->addAction(m_aboutAction); + m_menu->addAction(m_closeAction); + ui->menuBtn->setMenu(m_menu); + connect(m_helpAction, &QAction::triggered, this, [=](){ + qDebug() << "help clicked"; + callUserGuide(); + }); + connect(m_aboutAction, &QAction::triggered, this, [=](){ + About *dialog = new About(); + QPointF position = this->pos(); + XAtomHelper::setStandardWindowHint(dialog->winId()); + dialog->move(position.x()-15,position.y()+130); + dialog->exec(); + }); + connect(m_closeAction, SIGNAL(triggered()), this, SLOT(windowClosingClicked())); + + //手动改成透明色 + QPalette pale =ui->menuBtn->palette(); + pale.setColor(QPalette::Active,QPalette::Button,Qt::transparent); + ui->menuBtn->setPalette(pale); +} +/* + * @brief 检查小窗体是否初始化 + */ +bool Clock::checkTinyCountdownDia() +{ + return tinycountdownDia!=nullptr?true:false; +} + +void Clock::navigationBtnStyle(QPushButton * btn) +{ + setDefaultIcon(btn);; + //不使用主题高亮 + btn->setProperty("useIconHighlightEffect", false); + //使用灰按钮 + btn->setProperty("useButtonPalette", true); +} + +void Clock::updateClockSelectBtnStyle(SelectBtn *temp, int moveHeight) +{ + temp->move(25,moveHeight); +} + +void Clock::updateCountdownSelectBtnStyle(SelectBtn *temp, int moveWidth, int moveHeight) +{ + temp->move(moveWidth,moveHeight); +} + +void Clock::updateClockSelectBtnStyle(Btn_new *temp, int moveHeight) +{ + temp->move(DIALOG_MOVE_WIDTH,moveHeight); +} + +void Clock::updateCountdownSelectBtnStyle(Btn_new *temp, int moveWidth, int moveHeight) +{ + temp->move(moveWidth,moveHeight); +} + +void Clock::updateClockSelectBtnLabel(QLabel *temp, int moveHeight, QString text) +{ + temp->setText(text); + temp->setAlignment(Qt::AlignLeft|Qt::AlignVCenter); + temp->setStyleSheet("font-size:14px;"); + int labelLeftSpace = 20; + temp->move(labelLeftSpace, moveHeight); +} + +void Clock::widgetListWhiteStyle(QListWidget *listWidget) +{ + QString listBackColor = getDefaultGreyColor(); + QString selectItemRadius = QString::number(SELECT_ITEM_RADIUS); + listWidget->setStyleSheet("QListWidget{background-color: rgba(0, 0, 0, 0);}\ + QListWidget::Item{background-color:"+listBackColor+";border-radius:"+selectItemRadius+"px;}\ + QListWidget::item::selected{background-color:rgba(233, 233, 233,255);border-radius:"+selectItemRadius+"px;border:1px solid rgba(131, 131, 131,0);}\ + QListWidget::item:hover{background-color:rgba(233, 233, 233,255);border-radius:"+selectItemRadius+"px;}\ + QScrollBar:vertical{width:4px;background:rgba(0, 0, 0, 0);}QScrollBar::handle:vertical{width:4px;background:rgba(186, 193, 201, 1);}\ + QScrollBar::up-arrow:vertical, QScrollBar::down-arrow:vertical{background: white;border: 2px solid transparent;}\ + "); +} + +void Clock::widgetListBlackStyle(QListWidget *listWidget) +{ + QString selectItemRadius = QString::number(SELECT_ITEM_RADIUS); + listWidget->setStyleSheet("QListWidget{background-color: rgba(0, 0, 0, 0);}\ + QListWidget::Item{background-color:rgba(41, 41, 41, 255);border-radius:"+selectItemRadius+"px;}\ + QListWidget::item::selected{background-color:rgba(55, 55, 59, 255);border-radius:"+selectItemRadius+"px;border:1px solid rgba(131, 131, 131,0);}\ + QListWidget::item:hover{background-color:rgba(55, 55, 59, 255);border-radius:"+selectItemRadius+"px;}\ + QScrollBar:vertical{width:4px;background:rgba(0, 0, 0, 0);}QScrollBar::handle:vertical{width:4px;background:rgba(186, 193, 201, 1);}\ + QScrollBar::up-arrow:vertical, QScrollBar::down-arrow:vertical{background: white;border: 2px solid transparent;}\ + "); +} + +/* + * 动态监控闹钟与本地时间 + * Dynamic monitoring alarm clock and local time + */ +void Clock::timerUpdate() +{ + QTime time = QTime::currentTime(); + int timeH = time.hour(); + int timeM = time.minute(); + int timeS = time.second(); + + model_setup->select(); + //更新闹钟列表项 + textTimerupdate(); + + int rowNum = model->rowCount(); + bool hasNextAlarm = false; + QString nextAlarmClock = ""; + //记录最近的闹钟时间差 + int spanTime = 0; + //遍历闹钟 + for (int i = 0; i < rowNum; i++) { + /*判断星期 + Judgment week*/ + QDateTime current_date_time = QDateTime::currentDateTime(); + //今天没提醒闹钟,则continue + //缩写的本地化日期名称 + if (current_date_time.toString("ddd").compare("周一")==0 && model->index(i, 6).data().toInt() == 0) + continue; + if (current_date_time.toString("ddd").compare("周二")==0 && model->index(i, 7).data().toInt() == 0) + continue; + if (current_date_time.toString("ddd").compare("周三")==0 && model->index(i, 8).data().toInt() == 0) + continue; + if (current_date_time.toString("ddd").compare("周四")==0 && model->index(i, 9).data().toInt() == 0) + continue; + if (current_date_time.toString("ddd").compare("周五")==0 && model->index(i, 10).data().toInt() == 0) + continue; + if (current_date_time.toString("ddd").compare("周六")==0 && model->index(i, 11).data().toInt() == 0) + continue; + if (current_date_time.toString("ddd").compare("周日")==0 && model->index(i, 12).data().toInt() == 0) + continue; + + /*判断开关 + Judgment switch*/ + //闹钟关闭 则 continue + if ( model->index(i, 3).data().toInt() == 1) + continue; + //闹钟时间到 + int alarmH = model->index(i, 0).data().toInt(); + int alarmM = model->index(i, 1).data().toInt(); + if (timeH == alarmH + && timeM == alarmM + && timeS == 0) { + double music_time = 30; + if (model->index(i, 13).data().toString().compare(tr("2min"))==0) { + music_time = 2*60; + } else if (model->index(i, 13).data().toString().compare(tr("3min"))==0) { + music_time = 3*60; + } else if (model->index(i, 13).data().toString().compare(tr("4min"))==0) { + music_time = 4*60; + } else if (model->index(i, 13).data().toString().compare(tr("6min"))==0) { + music_time = 6*60; + } else { + music_time = 60; + } + QString id = model->index(i, 14).data().toString(); + noticeDialogShow(music_time, i ,id); + if(model->index(i, 5).data().toString().compare(tr("No repetition"))==0) + offAlarm(i); + }else{ + int tempSpan = (alarmH-timeH)*60+alarmM-timeM; + if(tempSpan>0){ + hasNextAlarm = true; + if(spanTime==0){ + spanTime=tempSpan; + nextAlarmClock = changeNumToStrWithAm(alarmH)+TIME_SEPARATOR+changeNumToStr(alarmM); + }else{ + if(tempSpanselect(); + QScreen *screen=QGuiApplication::primaryScreen (); + //闹钟弹窗 + alarmNoticeDialog = new Natice_alarm(close_time,alarm_num,nullptr,id); + if(countdownNoticeDialog != nullptr) { + if (countdownNoticeDialog->isVisible() == 0) + moveUnderMultiScreen(UP_RIGHT,alarmNoticeDialog,1); + else + moveUnderMultiScreen(UP_RIGHT,alarmNoticeDialog,0); + } + else + moveUnderMultiScreen(UP_RIGHT,alarmNoticeDialog,1); + alarmNoticeDialog->playMusic(); +} + + +/** + * @brief 重绘窗口,更新闹钟 Redraw window, update alarm clock + */ +void Clock::updateAlarmClock() +{ + int rowNum = model->rowCount(); + int hour_now; + int min_now; + if(rowNum){ + ui->noAlarm->hide(); + ui->noAlarmIcon->hide(); + }else{ + ui->noAlarm->show(); + ui->noAlarmIcon->show(); + } + auto sqlQuery = clock_sql::getQSqlQuery(); + sqlQuery.exec("select * from clock order by Hour ASC,Minute ASC"); + int alarmNum = 0; + //实现id补偿,原表设计没有主键,为实现旧数据兼容 +// QList * needIdNumList = new QList(); +// QHash * numToIndex =new QHash(); + while (sqlQuery.next()) { + //窗体 + aItem[alarmNum] =new QListWidgetItem; + aItem[alarmNum]->setSizeHint(QSize(340,108)); + aItem[alarmNum]->setTextColor(QColor(255, 0, 0, 255)); + ui->alarmListWidget->addItem(aItem[alarmNum]); + ui->alarmListWidget->setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded); + ui->alarmListWidget->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); + //闹钟信息 + w1[alarmNum] = new item_new(ui->alarmListWidget); + //信息与展示窗体绑定 + ui->alarmListWidget->setItemWidget(aItem[alarmNum],w1[alarmNum]); + //绑定Id到闹钟子项 + auto hisId = sqlQuery.value(14).toString(); + w1[alarmNum]->setId(hisId); + hour_now =sqlQuery.value( 0).toInt(); + min_now =sqlQuery.value( 1).toInt(); + int onOff = sqlQuery.value(3).toInt(); + if(onOff==1){ + w1[alarmNum]->closeStyle(CURRENT_FONT_SIZE); + }else{ + w1[alarmNum]->openStyle(CURRENT_FONT_SIZE); + } + if (system_time_flag) { + //24时制 + changeTimeNum(hour_now,min_now);//转换int为QString + // Convert int to qstring + w1[alarmNum]->alarmLabel0->setText(alarmHour_str+TIME_SEPARATOR+alarmMinute_str); + QString selfFont = Utils::loadFontFamilyFromTTF(); + QFont f(selfFont); + f.setPixelSize(38); + w1[alarmNum]->alarmLabel0->setFont(f); + + w1[alarmNum]->alarmLabel1->hide(); + } else { + //12时制 + if (hour_now >= 12) { + w1[alarmNum]->alarmLabel1->setText(tr("PM")); + if (hour_now == 12) { + w1[alarmNum]->alarmLabel0->setText(changeNumToStr(hour_now)+" : "+changeNumToStr(min_now)); + } else { + w1[alarmNum]->alarmLabel0->setText(changeNumToStr(hour_now-12)+" : "+changeNumToStr(min_now)); + } + } else { + w1[alarmNum]->alarmLabel1->setText(tr("AM")); + if (hour_now == 0) { + w1[alarmNum]->alarmLabel0->setText(changeNumToStr(12)+" : "+changeNumToStr(min_now)); + } else { + w1[alarmNum]->alarmLabel0->setText(changeNumToStr(hour_now)+" : "+changeNumToStr(min_now)); + } + } + } + /*闹钟开关 + Alarm switch*/ + //onoroff + if (sqlQuery.value( 3).toInt() == 1) { + w1[alarmNum]->alarm_on_off0->setChecked(false); + } else { + w1[alarmNum]->alarm_on_off0->setChecked(true); + } + //Name 闹钟名 + QString clockName = sqlQuery.value( 13).toString(); + int sizeLimit = 8; + if(clockName.length()>sizeLimit){ + w1[alarmNum]->alarmLabel_w0->setToolTip(clockName); + //名字超长 + clockName = clockName.left(sizeLimit); + clockName = clockName+".."; + } + w1[alarmNum]->alarmLabel_w0->setText(clockName); + //repeat 重复 + QString werk_str = sqlQuery.value( 5).toString(); + QString werk_day ; + int werk = 0; + for (int i=0; i<7; i++) { + //从周一到周日开始判断 为1 + if (sqlQuery.value( 6+i).toInt()) { + //拼接werk_day + if(i == 0){ + werk_day = werk_day + tr("Mon")+" "; + }else if(i == 1){ + werk_day = werk_day + tr("Tue")+" "; + }else if(i == 2){ + werk_day = werk_day + tr("Wed")+" "; + }else if(i == 3){ + werk_day = werk_day + tr("Thu")+" "; + }else if(i == 4){ + werk_day = werk_day + tr("Fri")+" "; + }else if(i == 5){ + werk_day = werk_day + tr("Sat")+" "; + }else if(i == 6){ + werk_day = werk_day + tr("Sun")+" "; + } + }else{ + //不是全为1 + werk = 1; + } + } + if(werk){ + w1[alarmNum]->alarmLabel_s0->setText(werk_day); + }else { + if(werk_str == tr("Every day") || werk_str == "每天"){ + w1[alarmNum]->alarmLabel_s0->setText(tr("Every day")); + }else if(werk_str == "Workingday" || werk_str == "工作日"){ + w1[alarmNum]->alarmLabel_s0->setText(tr("Workingday")); + }else if(werk_str == "No repetition" || werk_str == "不重复"){ + w1[alarmNum]->alarmLabel_s0->setText(tr("No repetition")); + } + } + //闹钟开关绑定 +// connect( w1[alarmNum]->alarm_on_off0, SIGNAL(clicked()), this, SLOT(OnOffAlarm()) ); + connect(w1[alarmNum]->alarm_on_off0,SIGNAL(stateChanged()),this, SLOT(OnOffAlarm())); + alarmNum++; + } +// updateClockIdByNum(needIdNumList,numToIndex); + +} + +/* + * 绘制无闹钟提示 + * Draw no alarm prompt + */ +void Clock::drawNoAlarmPrompt() +{ + ui->noAlarmIcon->setPixmap(QPixmap(":/image/noClockWhite.png"));//.pixmap(164,194) + ui->noAlarm->setAlignment(Qt::AlignHCenter); +} + +/* + * 修改时间单数 为两位数 + * Modify time singular to two digits + */ +void Clock::changeTimeNum(int alarmHour, int alarmMinute) +{ + if (alarmHour < 10) { + QString hours_str = QString::number(alarmHour); + alarmHour_str = "0"+hours_str; + } else { + alarmHour_str = QString::number(alarmHour); + } + if (alarmMinute < 10) { + QString minute_str = QString::number(alarmMinute); + alarmMinute_str = "0"+minute_str; + } else { + alarmMinute_str = QString::number(alarmMinute); + } +} + + + + +/* + * 新建闹钟按钮回调 + * New alarm button callback + */ +void Clock::setAlarmClock() +{ + onEditPage = false; + //新建闹钟页 + ui->mainWidget->setCurrentIndex(3); + //取消 + ui->cancelbtnOnEditAlarm->show(); + repeat_new_or_edit_flag = 0; + + model_setup->select();/*调用默认设置 + Call default settings*/ + repeat_str_model = tr("Workingday"); + //工作日默认 + repeatSelectOnClockNew->textLabel->setText(repeat_str_model+tr("(default)")); + //工作日设置的逻辑 + for (int i=0; i<5; i++) { + repeat_day[i] = 1; + } + remind_late_str_model= tr("none"); + //设置新建闹钟默认铃声 + QString defaultBellId = m_selectBtnUtil->getDefaultBellId(); + QString bellName = m_selectBtnUtil->getBellNameById(defaultBellId); + musicSelectOnClockNew->textLabel->setText(bellName); + setMusicSelectDialogListById(defaultBellId,dialog_music->listWidget); + //设置默认稍后提醒 + remindSelectOnClockNew->textLabel->setText(remind_late_str_model); + setRemindLateSelectDialogListByName(remind_late_str_model,dialog_remind_late->listWidget); + clock_name = tr(CLOCK_TITLE_NAME); + clockEditOnClockNew->clockNameLineEdit->setText(clock_name); +} +/** + * @brief 设置新建闹钟的铃声的默认值 + * @param name + */ +void Clock::setMusicSelectDialogListById(QString bellId, QListWidget *temp) +{ + int status = m_selectBtnUtil->getBellIndexById(bellId); + temp->setCurrentRow(status); +} + +void Clock::setRemindLateSelectDialogListByName(QString name, QListWidget *temp) +{ + + int status = getRemindStatusByName(name); + temp->setCurrentRow(status); +} + +int Clock::getRemindStatusByName(QString name) +{ + int status = 0; + if(name.compare("none") == 0 || name.compare("不需要") == 0){ + status = 0; + }else if(name.compare("five mins late") == 0 || name.compare("5分钟后") == 0){ + status = 1; + }else if(name.compare("ten mins late") == 0 || name.compare("10分钟后") == 0){ + status = 2; + }else if(name.compare("twenty mins late") == 0 || name.compare("20分钟后") == 0){ + status = 3; + }else if(name.compare("thirsty mins late") == 0 || name.compare("30分钟后") == 0){ + status = 4; + }else if(name.compare("one hour late") == 0 || name.compare("1小时后") == 0){ + status = 5; + } + return status; +} + +/* + * 闹钟新建界面保存回调 + * Alarm new interface save callback + */ +void Clock::setAlarmSave() +{ + if(onEditPage){ + //编辑页面保存 + QString clockName = clockEditOnClockNew->clockNameLineEdit->text(); + if(clockName.isEmpty()){ + delete_msg *deletemsg = new delete_msg(); + deletemsg->ui->msgInfo->setText(tr("Please set alarm name!")); + QPointF position = this->pos(); + deletemsg->move(position.x()+67,position.y()+250); + deletemsg->exec(); + return ; + } + auto curentId = getClockPkByCurrentNum(); + auto sqlQuery = clock_sql::getQSqlQuery(); + sqlQuery.prepare("update clock set hour=:hour,minute=:minute,bell_id=:music,repeat=:repeat," + "name=:name,monday=:monday,tuesday=:tuesday,wednesday=:wednesday,thursday=:thusday," + "friday=:friday,saturday=:saturday,sunday=:sunday,remind_status=:remind_status where id=:id"); + sqlQuery.bindValue(":id",curentId); + sqlQuery.bindValue(":hour",timer_alarm_start24->m_currentValue); + sqlQuery.bindValue(":minute",timer_alarm_start60->m_currentValue); + QString bellId = getSelectBellId(dialog_music); + sqlQuery.bindValue(":music",bellId); + sqlQuery.bindValue(":repeat",repeat_str_model); + sqlQuery.bindValue(":remind_status",remind_late_str_model); + sqlQuery.bindValue(":name",clockName); + for (int i=0; i<7; i++) { + QString day = indexWeekdayMap->value(i); + if (repeat_day[i]) { + sqlQuery.bindValue(day,1); + } else { + sqlQuery.bindValue(day,0); + } + } + sqlQuery.exec(); + model->submitAll(); + int m = model->rowCount(); + /*每次updateAlarmClock()之前,删除全部闹钟相关控件 + Delete all alarm related controls before updatealrmclock()*/ + for (int i = 0; i < m; i++) { + delete aItem[i]; + delete w1[i]; + } + updateAlarmClock(); + updateAlarmItemFront(CURRENT_FONT_SIZE); + ui->mainWidget->setCurrentIndex(1); + ui->mainWidget->raise();/*将页面放置最前方 + Put the page at the front*/ + ui->minmizeBtn->raise(); + ui->closeTitleBtn->raise(); + ui->menuBtn->raise(); + + if (dialog_repeat) + dialog_repeat->close(); + + if (dialog_music) + dialog_music->close(); + if(dialog_remind_late) + dialog_remind_late->close(); + }else{ + //新建页面保存 + clockEditOnClockNew->clockNameLineEdit->setText(clockEditOnClockNew->clockNameLineEdit->text().remove(QRegExp("\\s")));//去除所以空格 + if(clockEditOnClockNew->clockNameLineEdit->text().isEmpty()){ + delete_msg *deletemsg = new delete_msg(); + deletemsg->ui->msgInfo->setText(tr("Please set alarm name!")); + QPointF position = this->pos(); + deletemsg->move(position.x()+67,position.y()+250); + deletemsg->exec(); + return ; + } + int rowNum; + rowNum = model->rowCount(); + + qDebug() << rowNum << "闹钟数"; + if (rowNum < 20) { + saveClockToDatabase(rowNum); + } else { + QMessageBox::warning(this, tr("warning"), tr("the number of alarms reaches limit!!"), tr("yes")); + } + + ui->mainWidget->setCurrentIndex(1); + ui->mainWidget->raise();//将页面放置最前方 + // Put the page at the front + ui->minmizeBtn->raise(); + ui->closeTitleBtn->raise(); + ui->menuBtn->raise(); + + if (dialog_repeat) + dialog_repeat->close(); + if (dialog_music) + dialog_music->close(); + } + updateAlarmItemFront(CURRENT_FONT_SIZE); +} + +void Clock::saveClockToDatabase(int rowNum) +{ + QString clockName = clockEditOnClockNew->clockNameLineEdit->text(); + model->insertRow(rowNum); + + model->setData(model->index(rowNum, 0), timer_alarm_start24->m_currentValue); + model->setData(model->index(rowNum, 1), timer_alarm_start60->m_currentValue); + QString bellId = getSelectBellId(dialog_music); + model->setData(model->index(rowNum, 2), bellId); + model->setData(model->index(rowNum, 15), remind_late_str_model); + model->setData(model->index(rowNum, 3), int(0)); + model->setData(model->index(rowNum, 4), int(model->index(rowNum-1, 4).data().toInt()+1)); + model->setData(model->index(rowNum, 5), repeat_str_model); + model->setData(model->index(rowNum, 13), clockName); + //主键 + auto id = Utils::getRandomId(); + model->setData(model->index(rowNum, 14), id); + for (int i=0; i<7; i++) { + model->setData(model->index(rowNum, i+6), repeat_day[i]); + } + model->submitAll(); + + for (int i=0; iindex(rowNum, 0).data().toString() + << model->index(rowNum, 1).data().toString() + << QFileInfo( model->index(rowNum, 2).data().toString() ).fileName(); + updateAlarmClock(); +} + +QString Clock::getSelectBellId(set_alarm_repeat_Dialog *tempDialog) +{ + int num=tempDialog->listWidget->currentRow(); + QString id = m_selectBtnUtil->getBellIdByIndex(num); + return id; +} + +QString Clock::addAlarm(clockInterface::RequestParams param) +{ + return addAlarm(param.clockName,param.hour,param.minute); +} + +QString Clock::addAlarmJosn(QString param) +{ + neb::CJsonObject oJson(param.toStdString()); + QString clockName = QString::fromStdString(oJson["clockName"].ToString()); + QString hour = QString::fromStdString(oJson["hour"].ToString()); + QString minute = QString::fromStdString(oJson["minute"].ToString()); + if(FieldValidUtil::isNull(hour)){ + return formatReturnMsg(clockInterface::FAIL,"小时为空"); + } + if(FieldValidUtil::isNull(minute)){ + return formatReturnMsg(clockInterface::FAIL,"分钟为空"); + } + return addAlarm(clockName, hour.toInt(), minute.toInt()); +} + +QString Clock::updateClockByIdJosn(QString param) +{ + neb::CJsonObject oJson(param.toStdString()); + QString id = QString::fromStdString(oJson["id"].ToString()); + if(FieldValidUtil::isNull(id)){ + return formatReturnMsg(clockInterface::FAIL,"主键id为空"); + } + id = FieldValidUtil::QStringFilter(id); + QString clockName = QString::fromStdString(oJson["clockName"].ToString()); + QString hour = QString::fromStdString(oJson["hour"].ToString()); + QString minute = QString::fromStdString(oJson["minute"].ToString()); + if(FieldValidUtil::isNull(clockName)&&FieldValidUtil::isNull(hour)&&FieldValidUtil::isNull(minute)){ + return formatReturnMsg(clockInterface::FAIL,"没有需要修改的数据"); + } + updateClockDatabase(id,clockName,hour,minute,0); + return formatReturnMsg(clockInterface::SUCCESS,"闹钟修改成功"); +} + +QString Clock::selectClockByIdJosn(QString param) +{ + neb::CJsonObject oJson(param.toStdString()); + QString id = QString::fromStdString(oJson["id"].ToString()); + if(FieldValidUtil::isNull(id)){ + return formatReturnMsg(clockInterface::FAIL,"主键id为空"); + } + id = FieldValidUtil::QStringFilter(id); + auto sqlQuery = getClockByPK(id); + QString queryId = sqlQuery.value(14).toString(); + if(FieldValidUtil::isNull(queryId)){ + return formatReturnMsg(clockInterface::FAIL,"查询结果为空"); + } + oJson.Add("name",sqlQuery.value(13).toString().toStdString()); + oJson.Add("hour",sqlQuery.value( 0).toInt()); + oJson.Add("minute",sqlQuery.value( 1).toInt()); + return formatReturnMsg(oJson,clockInterface::SUCCESS,"闹钟查询成功"); +} + +QString Clock::deleteClockByIdJosn(QString param) +{ + neb::CJsonObject oJson(param.toStdString()); + QString id = QString::fromStdString(oJson["id"].ToString()); + if(FieldValidUtil::isNull(id)){ + return formatReturnMsg(clockInterface::FAIL,"主键id为空"); + } + id = FieldValidUtil::QStringFilter(id); + deleteAlarmDatabase(id); + return formatReturnMsg(clockInterface::SUCCESS,"闹钟删除成功"); +} + +QString Clock::addAlarm(QString clockName, int hour, int minute) +{ + //表单验证 + if(FieldValidUtil::isNull(clockName)){ + return formatReturnMsg(clockInterface::FAIL,"闹钟名为空"); + } + QString clockNameQstr = FieldValidUtil::QStringFilter(clockName); + if(clockNameQstr.length()>16){ + return formatReturnMsg(clockInterface::FAIL,"闹钟名超过16个字"); + } + if(!FieldValidUtil::isValueBetweenRange(hour,0,23)){ + return formatReturnMsg(clockInterface::FAIL,"小时位不是0-23之间的整数"); + } + if(!FieldValidUtil::isValueBetweenRange(minute,0,59)){ + return formatReturnMsg(clockInterface::FAIL,"分钟位不是0-59之间的整数"); + } + int rowNum; + rowNum = model->rowCount(); + if(rowNum>=20){ + return formatReturnMsg(clockInterface::FAIL,"闹钟数已达上限"); + } + + //存储到数据库 + model->insertRow(rowNum); + model->setData(model->index(rowNum, 0), hour); + model->setData(model->index(rowNum, 1), minute); + model->setData(model->index(rowNum, 2), tr("glass")); + model->setData(model->index(rowNum, 3), int(0)); + model->setData(model->index(rowNum, 4), int(model->index(rowNum-1, 4).data().toInt()+1)); + model->setData(model->index(rowNum, 5), tr("No repetition")); + model->setData(model->index(rowNum, 13), clockNameQstr); + //主键 + auto id = Utils::getRandomId(); + model->setData(model->index(rowNum, 14), id); + for (int i=0; i<7; i++) { + model->setData(model->index(rowNum, i+6), 1); + } + model->submitAll(); + for (int i=0; imainWidget->setCurrentIndex(1); + ui->mainWidget->raise(); + ui->minmizeBtn->raise(); + ui->closeTitleBtn->raise(); + ui->menuBtn->raise(); +} + +/* + * 双击闹钟打开重编辑页面 + * Double click the alarm clock to open the re edit page + */ +void Clock::listdoubleClickslot() +{ + onEditPage = true; + ui->mainWidget->setCurrentIndex(3); + //以链表序号找寻数据 + auto curentId = getClockPkByCurrentNum(); + //根据id查询数据 + auto sqlQuery = getClockByPK(curentId); + timer_alarm_start24->m_currentValue=sqlQuery.value( 0).toInt(); + timer_alarm_start60->m_currentValue=sqlQuery.value( 1).toInt(); + repeat_new_or_edit_flag = 1; + QString werk_day ; + int werk = 0; + for (int i=0; i<7; i++) { + if (sqlQuery.value( 6+i).toInt()) { + if(i == 0){ + werk_day = werk_day + tr("Mon")+" "; + }else if(i == 1){ + werk_day = werk_day + tr("Tue")+" "; + }else if(i == 2){ + werk_day = werk_day + tr("Wed")+" "; + }else if(i == 3){ + werk_day = werk_day + tr("Thu")+" "; + }else if(i == 4){ + werk_day = werk_day + tr("Fri")+" "; + }else if(i == 5){ + werk_day = werk_day + tr("Sat")+" "; + }else if(i == 6){ + werk_day = werk_day + tr("Sun")+" "; + } + }else{ + werk = 1; + } + } + if(werk){ + repeatSelectOnClockNew->textLabel->setText(werk_day); + }else { + repeatSelectOnClockNew->textLabel->setText(tr("Every day")); + } + if(sqlQuery.value( 5).toString() == tr(" work") || sqlQuery.value( 5).toString() == tr(" 工作日")){ + repeatSelectOnClockNew->textLabel->setText(tr(" work")); + } + if(sqlQuery.value( 5).toString() == tr("No repetition") || sqlQuery.value( 5).toString() == tr("不重复")){ + repeatSelectOnClockNew->textLabel->setText(tr("No repetition")); + } + repeat_str_model = sqlQuery.value( 5).toString(); + + updateRepeatStr(repeatSelectOnClockNew->textLabel); + + QString bellId = sqlQuery.value( 2).toString(); + auto name = m_selectBtnUtil->getBellNameById(bellId); + musicSelectOnClockNew->textLabel->setText(name); + setMusicSelectDialogListById(bellId,dialog_music->listWidget); + + //重复 + remind_late_str_model = sqlQuery.value( 15).toString(); + qDebug()<<"从数据库查稍后"<textLabel->setText(remind_late_str_model); + setRemindLateSelectDialogListByName(remind_late_str_model,dialog_remind_late->listWidget); + + clock_name = sqlQuery.value( 13).toString(); + clockEditOnClockNew->clockNameLineEdit->setText(clock_name); + for (int i=0; i<7; i++) { + if (sqlQuery.value( 6+i).toInt()) { + repeat_day[i] = 1; + } else { + repeat_day[i] = 0; + } + } +} + +QString Clock::getClockPkByCurrentNum() +{ + int num = ui->alarmListWidget->currentRow(); + auto widgetItem = static_cast(ui->alarmListWidget->itemWidget(aItem[num])); + auto curentId = widgetItem->id(); + return curentId; +} + +QSqlQuery Clock::getClockByPK(QString id) +{ + auto sqlQuery = clock_sql::getQSqlQuery(); + sqlQuery.prepare("select * from clock where id=:id"); + sqlQuery.bindValue(":id",id); + sqlQuery.exec(); + sqlQuery.next(); + return sqlQuery; +} + + + +/* + * 闹钟重编辑页面删除闹钟回调 + * Alarm re edit page delete alarm callback + */ +void Clock::deleteAlarm() +{ + int rowNum = model->rowCount(); + + +/* + delete_msg *deletemsg = new delete_msg(); + QPointF position = this->pos(); + deletemsg->move(position.x()+35,position.y()+200); + deletemsg->exec(); +*/ + +/* + * 重新适配QMessageBox控件 + * Refit the qmessagebox control + */ + int ret; + QMessageBox msg(this); + + msg.setIcon(QMessageBox::Question); + msg.setWindowTitle(QObject::tr("Hint")); + msg.setText(QObject::tr("Are you sure to delete?")); + msg.addButton(QObject::tr("sure"), QMessageBox::AcceptRole); + msg.addButton(QObject::tr("cancel"), QMessageBox::RejectRole); + + ret = msg.exec(); + + if (ret == QMessageBox::RejectRole) { + qDebug()<<"dbq-不删除"; + } else { + //删除数据 + auto curentId = getClockPkByCurrentNum(); + deleteAlarmDatabase(curentId); + rowNum = model->rowCount(); + qDebug() << rowNum; + + } + //闹钟页面子项 + updateAlarmItemFront(CURRENT_FONT_SIZE); +} + +void Clock::deleteAlarmDatabase(QString id) +{ + int rowNum = model->rowCount(); + auto sqlQuery = clock_sql::getQSqlQuery(); + sqlQuery.prepare("delete from clock where id=:id"); + sqlQuery.bindValue(":id",id); + sqlQuery.exec(); + for (int i=0; isubmitAll(); + updateAlarmClock(); + updateAlarmItemFront(CURRENT_FONT_SIZE); +} + +void Clock::updateClockDatabase(QString id, QString name, QString hour, QString minute, int onOff) +{ + QString sql = "update clock set "; + if(FieldValidUtil::isNotNull(name)){ + sql = sql.append(" Name=:clockName , "); + } + if(FieldValidUtil::isNotNull(hour)){ + sql = sql.append(" Hour=:hour , "); + } + if(FieldValidUtil::isNotNull(minute)){ + sql = sql.append(" Minute=:minute , "); + } + sql = sql.append(" on_or_off=:onOff , "); + sql = sql.remove(sql.length()-2,2); + sql = sql.append(" where Id=:id"); + int rowNum = model->rowCount(); + auto sqlQuery = clock_sql::getQSqlQuery(); + sqlQuery.prepare(sql); + sqlQuery.bindValue(":id",id); + //绑定数据 + if(FieldValidUtil::isNotNull(name)){ + name = FieldValidUtil::QStringFilter(name); + sqlQuery.bindValue(":clockName",name); + } + if(FieldValidUtil::isNotNull(hour)){ + sqlQuery.bindValue(":hour",hour.toInt()); + } + if(FieldValidUtil::isNotNull(minute)){ + sqlQuery.bindValue(":minute",minute.toInt()); + } + sqlQuery.bindValue(":onOff",onOff); + sqlQuery.exec(); + model->submitAll(); + if(FieldValidUtil::isNotNull(name)||FieldValidUtil::isNotNull(hour)||FieldValidUtil::isNotNull(minute)){ + for (int i=0; i(QObject::sender()); + while (btn != w1[i]->alarm_on_off0) { + i++; + } + QString id = w1[i]->id(); + auto sqlQuery = getClockByPK(id); + if (sqlQuery.value(3).toInt() == 0) { +// btn->closeSlot(); + w1[i]->closeStyle(CURRENT_FONT_SIZE); + updateClockDatabase(id,nullptr,nullptr,nullptr,1); + } else { +// btn->openSlot(); + w1[i]->openStyle(CURRENT_FONT_SIZE); + updateClockDatabase(id,nullptr,nullptr,nullptr,0); + } +} +/* + * 不重复时单独关闭闹钟 + * Turn off the alarm separately if it is not repeated + */ +void Clock::offAlarm(int i) +{ + w1[i]->alarm_on_off0->setChecked(false); + model->setData(model->index(i, 3), int(1)); + model->submitAll(); + + int rowNum = model->rowCount(); + for (int i = 0; i < rowNum; i++) { + delete aItem[i]; + delete w1[i]; + } + updateAlarmClock(); +} + +/* + * 倒计时音乐选择 + * Countdown music selection + */ +void Clock::countdownMusicSellect() +{ + musicSelectOnCountdownSet->updateIconLabel(1); + musicSelectOnCountdownRun->updateIconLabel(1); + QPointF position = this->pos(); + count_music_sellect->move(position.x()+DIALOG_MOVE_WIDTH,position.y()+482); + count_music_sellect->setWindowFlags(Qt::Popup); + refreshMusicSelectList(count_music_sellect); + count_music_sellect->show(); +// connect(count_music_sellect->listWidget,SIGNAL(itemClicked(QListWidgetItem*)),this,SLOT(countMusicListclickslot())); +} +/* + * 倒计时音乐选择单机回调 + * Countdown music selection single callback + */ +void Clock::countMusicListclickslot() +{ + int num=count_music_sellect->listWidget->currentRow(); + int size = count_music_sellect->rowNum_all; + //最后一个自定义铃声 + if(num==(size-1)){ + addDivBell(count_music_sellect,Clock::count_down); + }else{ + QString id = m_selectBtnUtil->getBellIdByIndex(num); + QString path = m_selectBtnUtil->getBellPathById(id); + QString name = m_selectBtnUtil->getBellNameById(id); + musicSelectOnClockNew->textLabel->setText(name); + //排除无 + if(num==0){ + path=""; + } + playMusicFromPath(path); + model_setup->setData(model_setup->index(0, 1), id); + musicSelectOnCountdownSet->textLabel->setText(name); + musicSelectOnCountdownRun->textLabel->setText(name); + model_setup->submitAll(); + } + count_music_sellect->close(); +} + +void Clock::playMusicFromPath(QString path) +{ +// delete musicSelectPlay; +// musicSelectPlay = new QMediaPlayer(this); + //停止上次播放 +// stopHisPlay(); + +// delete music; +// music = new QMediaPlayer(); +// music->setMedia(QUrl::fromLocalFile(path)); +// music->play(); + + playController::getInstance().playSingleSong(path,0); + +} + +void Clock::stopHisPlay() +{ + if(hisPlayer!=nullptr){ + hisPlayer->stop(); + } +} +//TODO 加按钮 +void Clock::addDivBell(set_alarm_repeat_Dialog *tempDialog, btnType type) +{ + QString filePath = m_selectBtnUtil->openAudioFileDialog(tempDialog); + if(FieldValidUtil::isNotNull(filePath)){ + qWarning()<<"dbq-开始复制"<copyAudioFile(filePath); + //存储到数据库 + QString bellId = m_selectBtnUtil->saveToBellTable(toPatn); + QString name = m_selectBtnUtil->getBellNameById(bellId); + + if(type==Clock::count_down){ + musicSelectOnCountdownSet->textLabel->setText(name); + musicSelectOnCountdownRun->textLabel->setText(name); + }else{ + musicSelectOnClockNew->textLabel->setText(name); + } + + playMusicFromPath(toPatn); + //刷新窗体 +// rebuildCountdownMusicDialog(); + //选中新建的铃声 +// setMusicSelectDialogListById(bellId,count_music_sellect->listWidget); + } +} + +//倒计时执行 +// Countdown execution +void Clock::statCountdown(){ + //减1算法 + if(countdown_second>0){ + countdown_second--; + }else if(countdown_second==0&&countdown_minute>=1){ + countdown_minute--; + countdown_second=59; + }else if(countdown_second==0&&countdown_minute==0&&countdown_hour>=1){ + countdown_hour--; + countdown_minute=59; + countdown_second=59; + } + + QString h; QString m; QString s; + if (countdown_hour < 10){ + QString hours_str = QString::number(countdown_hour); + h = "0"+hours_str; + } else { + h = QString::number(countdown_hour); + } + if (countdown_minute < 10) { + QString minute_str = QString::number(countdown_minute); + m = "0"+minute_str; + } else { + m = QString::number(countdown_minute); + } + + if (countdown_second < 10) { + QString second_str = QString::number(countdown_second); + s = "0"+second_str; + }else { + s = QString::number(countdown_second); + } + ui->remainTime->setText(h+TIME_SEPARATOR+m+TIME_SEPARATOR+s); +// QString selfFont = Utils::loadFontFamilyFromTTF(); +// QFont f(selfFont); + QFont f; + f.setFamily("NotoSansCJKsc-Regular"); + f.setWeight(400); + f.setPixelSize(40); + ui->remainTime->setFont(f); + + //设置倒计时托盘tooltip + QString tooltip = tr("Count down"); + tooltip +=TIME_SEPARATOR_CN+h+TIME_SEPARATOR+m+TIME_SEPARATOR+s; + updateTrayIconTooltip(tooltip); + + //小型倒计时 显示倒计时时间 + if(this->m_selectTinyCountdown){ + if(checkTinyCountdownDia()){ + tinycountdownDia->updateTimeInfo(h+TIME_SEPARATOR+m+TIME_SEPARATOR+s); + } + } + //时间归零 + if (countdown_hour==0 && countdown_minute==0 && (countdown_second)==0) { + startbtnCountdown(); + countdown_timer->stop(); + //托盘恢复默认 + setDefaultTrayIconTooltip(); + //倒计时通知弹窗 + countdownNoticeDialogShow(); + } +} + +void Clock::statCountdownMsec() +{ + countdown_msec-=10; + if(countdown_msec<=0){ + //减1算法 + if(countdown_second>0){ + countdown_second--; + }else if(countdown_second==0&&countdown_minute>=1){ + countdown_minute--; + countdown_second=59; + }else if(countdown_second==0&&countdown_minute==0&&countdown_hour>=1){ + countdown_hour--; + countdown_minute=59; + countdown_second=59; + } + countdown_msec=1000; + } + //设置当前时间 + int ringmax = countdown_hour*3600 + countdown_minute*60 + countdown_second; + ui->countdownRunPage->countdownRunRoundBar->setValue(ringmax); + + QString h; QString m; QString s; + if (countdown_hour < 10){ + QString hours_str = QString::number(countdown_hour); + h = "0"+hours_str; + } else { + h = QString::number(countdown_hour); + } + if (countdown_minute < 10) { + QString minute_str = QString::number(countdown_minute); + m = "0"+minute_str; + } else { + m = QString::number(countdown_minute); + } + + if (countdown_second < 10) { + QString second_str = QString::number(countdown_second); + s = "0"+second_str; + }else { + s = QString::number(countdown_second); + } + ui->remainTime->setText(h+TIME_SEPARATOR+m+TIME_SEPARATOR+s); +// QString selfFont = Utils::loadFontFamilyFromTTF(); +// QFont f(selfFont); + QFont f; + f.setFamily("NotoSansCJKsc-Regular"); + f.setWeight(400); + f.setPixelSize(40); + ui->remainTime->setFont(f); + //设置倒计时托盘tooltip + QString tooltip = tr("Count down"); + tooltip +=TIME_SEPARATOR_CN+h+TIME_SEPARATOR+m+TIME_SEPARATOR+s; + updateTrayIconTooltip(tooltip); + + //小型倒计时 显示倒计时时间 + if(this->m_selectTinyCountdown){ + if(checkTinyCountdownDia()){ + tinycountdownDia->updateTimeInfo(h+TIME_SEPARATOR+m+TIME_SEPARATOR+s); + } + } + //时间归零 + if (countdown_hour==0 && countdown_minute==0 && (countdown_second)==0) { + startbtnCountdown(); + countdown_timer->stop(); + //托盘恢复默认 + setDefaultTrayIconTooltip(); + //倒计时通知弹窗 + countdownNoticeDialogShow(); + } +} + +/* + * 倒计时通知弹窗 + * Countdown notification pop-up + */ +void Clock::countdownNoticeDialogShow() +{ + //关闭tiny倒计时 + if(checkTinyCountdownDia()){ + tinycountdownDia->set_dialog_close(); + } + + model_setup->select(); + QScreen *screen=QGuiApplication::primaryScreen (); + QRect mm=screen->availableGeometry() ; + int screen_width = mm.width(); + int screen_height = mm.height(); + model_setup->select(); +// countdownNoticeDialog->timer_value = 59; + //多少秒后自动关闭 + countdownNoticeDialog->ui->autoCloseTime->setText(tr("60 Seconds to close")); + //左上图标 +// countdownNoticeDialog->ui->titleLabel->setText(tr("Alarm")); + //时间到 + if (alarmNoticeDialog != nullptr) { + if (alarmNoticeDialog->isVisible() == 0) + moveUnderMultiScreen(UP_RIGHT,countdownNoticeDialog,1); + else + moveUnderMultiScreen(UP_RIGHT,countdownNoticeDialog,0); + } else + moveUnderMultiScreen(UP_RIGHT,countdownNoticeDialog,1); + countdownNoticeDialog->playMusic(); +} + +/* + * 倒计时开始-结束 + * Countdown start end callback + */ +void Clock::startbtnCountdown(){ + if (!countdown_isStarted) { + + //点击了开始 + if (hourTimerRing->m_currentValue==0 && minuteTimeRing->m_currentValue==0 && secondTimeRing->m_currentValue==0) { + return; + } + //当前剩余时间,单位秒 + int ringmax = hourTimerRing->m_currentValue*3600 + minuteTimeRing->m_currentValue*60 + secondTimeRing->m_currentValue; + //进度圈 + ui->countdownRunPage->countdownRunRoundBar->setRange(0,ringmax); + //切换进度条颜色 + ui->countdownRunPage->countdownRunRoundBar->switchRunRingColor(); + ui->startCountdownBtn->setStyleSheet(""); + countdown_isStarted=1; + //结束 + ui->startCountdownBtn->setText(tr("End")); + //点击开始,刷新数值 + refreshCountdownLabel11Flag = true; + //设置倒计时初始时间label9 中间数字 + setcoutdownNumber(hourTimerRing->m_currentValue, minuteTimeRing->m_currentValue, secondTimeRing->m_currentValue);//获取转轮当前值 + //倒计时页面 + ui->countdownStackedW->setCurrentIndex(1); + countdown_timer->start(); + //光圈的进度值修改定时启动 + + } else { + //点击了结束,或者时间耗尽 + ui->countdownRunPage->countdownRunRoundBar->setRange(0,COUNTDOWN_TIME); + ui->countdownRunPage->countdownRunRoundBar->setValue(COUNTDOWN_TIME);/*初始化倒计时进度圈 + Initialize countdown progress circle*/ + countdown_timer->stop(); + countdown_isStarted=0; + countdown_isStarted_2=0; + hourTimerRing->m_currentValue = 0; + minuteTimeRing->m_currentValue = 0; + secondTimeRing->m_currentValue = 0; + ui->startCountdownBtn->setText(tr("start")); + ui->remainTime->setText("00:00:00"); + //切换到倒计时滚轮页 + ui->countdownStackedW->setCurrentIndex(0); + //暂停 + ui->suspendCountdownBtn->setText(tr("suspend")); + + QPalette palette = ui->suspendCountdownBtn->palette(); + QColor ColorPlaceholderText(248,163,76,255); + QBrush brush2; + brush2.setColor(ColorPlaceholderText); + //主题框架1.0.6-5kylin2 + palette.setColor(QPalette::Highlight,QColor(248,163,76,255)); + palette.setColor(QPalette::Button,QColor(248,163,76,255)); + palette.setBrush(QPalette::ButtonText, QBrush(Qt::white)); + ui->suspendCountdownBtn->setPalette(palette); + //小窗体清零,隐藏 + if(checkTinyCountdownDia()){ + tinycountdownDia->clearData(); + } + //恢复默认托盘 + setDefaultTrayIconTooltip(); + } + return; +} + +void Clock::tinyCountdownFinish() +{ + tinycountdownDia->hide(); + activeWindow(); + startbtnCountdown(); +} + +/* + * 设置倒计时初始时间 + * Set the initial countdown time + */ +void Clock::setcoutdownNumber(int h1, int m1, int s1){ + countdown_hour=h1; countdown_minute=m1 ; countdown_second=s1; + + QString h; QString m; QString s; + + if (countdown_hour < 10){ + QString hours_str = QString::number(countdown_hour); + h = "0"+hours_str; + } else { + h = QString::number(countdown_hour); + } + + if (countdown_minute < 10) { + QString minute_str = QString::number(countdown_minute); + m = "0"+minute_str; + } else { + m = QString::number(countdown_minute); + } + + if (countdown_second < 10) { + QString second_str = QString::number(countdown_second); + s = "0"+second_str; + } else { + s = QString::number(countdown_second); + } + + ui->remainTime->setText(h+TIME_SEPARATOR+m+TIME_SEPARATOR+s); +// QString selfFont = Utils::loadFontFamilyFromTTF(); +// QFont f(selfFont); + QFont f; + f.setFamily("NotoSansCJKsc-Regular"); + f.setWeight(400); + f.setPixelSize(40); + ui->remainTime->setFont(f); + //获取倒计时结束时间 + getCountdownOverTime(); +} + +/* + * 倒计时5分钟 + * Countdown 5 minutes set callback + */ +void Clock::onMin_5btnClicked() +{ + hourTimerRing->m_currentValue = 0; + minuteTimeRing->m_currentValue = 5; + secondTimeRing->m_currentValue = 0; + setcoutdownNumber(0, 5, 0); +} + +/* + * 获取倒计时结束时间 + * Get countdown end time + */ +void Clock::getCountdownOverTime() +{ + QTime time = QTime::currentTime(); + int timeH = time.hour(); + int timeM = time.minute(); + int timeS = time.second(); + if(refreshCountdownLabel11Flag){ + x_h = countdown_hour + timeH; + x_m = countdown_minute + timeM; + //分钟位进1 + if(countdown_second+timeS>=60){ + x_m+=1; + } + refreshCountdownLabel11Flag = false; + if (x_m >= 60) { + x_m = x_m - 60; + x_h ++; + } + } + if (x_h >= 48) { + x_h = x_h - 48; + ui->countdownAlarmTime->setText(tr("after tomorrow")+formatX_h(x_h)+TIME_SEPARATOR+changeNumToStr(x_m)); + } else if (x_h >= 24) { + x_h = x_h - 24; + ui->countdownAlarmTime->setText(tr("Tomorrow")+formatX_h(x_h)+TIME_SEPARATOR+changeNumToStr(x_m)); + } else{ + ui->countdownAlarmTime->setText(formatX_h(x_h)+TIME_SEPARATOR+changeNumToStr(x_m)); + } +} +//上下午格式 +QString Clock::get12hourStr(int x_h) +{ + QString str; + //12时 + if (x_h >= 12) { + x_h = x_h - 12; + str=tr("PM")+" "+changeNumToStr(x_h); + } else { + str=tr("AM")+" "+changeNumToStr(x_h); + } + return str; +} +/** + * @brief 创建用户手册dbus客户端 + */ +void Clock::createUserGuideDebusClient() +{ + // 用户手册 + QString serviceName = "com.kylinUserGuide.hotel" + + QString("%1%2").arg("_").arg(QString::number(getuid())); + //创建dbus-client + userGuideInterface = new QDBusInterface(serviceName, + "/", + "com.guide.hotel", + QDBusConnection::sessionBus()); + qDebug() << "connect to kylinUserGuide" << userGuideInterface->isValid(); + if (!userGuideInterface->isValid()) { + qDebug() << "fail to connect to kylinUserGuide"; + qDebug() << qPrintable(QDBusConnection::sessionBus().lastError().message()); + return; + } +} + +void Clock::onTinyClicked() +{ + this->m_selectTinyCountdown=true; + //主窗体最小化 + setWindowState(Qt::WindowMinimized); + moveUnderMultiScreen(UP_RIGHT,tinycountdownDia,0); + tinycountdownDia->showTop(); +} + +void Clock::activeWindow() +{ + setWindowState(Qt::WindowActive); +} +//刷新时间格式 +QString Clock::formatX_h(int x_h) +{ + QString str; + //跟随系统时间 + if(m_timeZone == "24"){ + str=changeNumToStr(x_h); + }else{ + //12时 + str =get12hourStr(x_h); + } + return str; +} +/* + * 单位变双位 + * Integer to character + */ +QString Clock::changeNumToStr(int alarmHour) +{ + QString str; + if (alarmHour < 10) { + QString hours_str = QString::number(alarmHour); + str = "0"+hours_str; + } else { + str = QString::number(alarmHour); + } + return str; +} +QString Clock::changeNumToStrWithAm(int alarmHour) +{ + QString str; + if (system_time_flag) { + //24时制 + str = changeNumToStr(alarmHour);//转换int为QString + } else { + //12时制 + if (alarmHour >= 12) { + str+=tr("PM")+" "; + if (alarmHour == 12) { + str+=changeNumToStr(alarmHour); + } else { + str+=changeNumToStr(alarmHour-12); + } + } else { + str+=tr("AM")+" "; + if (alarmHour == 0) { + str+=changeNumToStr(12); + } else { + str+=changeNumToStr(alarmHour); + } + } + } + return str; +} +/* + * 倒计时-暂停继续 + * Countdown - pause resume callback + */ +void Clock::onCountPushClicked() +{ + tinycountdownDia->updateOnRunState(countdown_isStarted_2); + if (countdown_isStarted_2){ + //点击了继续 + ui->suspendCountdownBtn->setText(tr("suspend")); + //切换进度条颜色 + ui->countdownRunPage->countdownRunRoundBar->switchRunRingColor(); + + QPalette palette = ui->suspendCountdownBtn->palette(); + QColor ColorPlaceholderText(248,163,76,255); + QBrush brush2; + brush2.setColor(ColorPlaceholderText); + //主题框架1.0.6-5kylin2 + palette.setColor(QPalette::Highlight,QColor(248,163,76,255)); + palette.setColor(QPalette::Button,QColor(248,163,76,255)); + palette.setBrush(QPalette::ButtonText, QBrush(Qt::white)); + ui->suspendCountdownBtn->setPalette(palette); + + countdown_timer->start(); + countdown_isStarted_2=0; + refreshCountdownLabel11Flag = true; + getCountdownOverTime(); + } else { + //点击了暂停 + ui->suspendCountdownBtn->setText(tr("continue")); + //切换进度条颜色 + ui->countdownRunPage->countdownRunRoundBar->switchStopRingColor(); + + QPalette palette = ui->suspendCountdownBtn->palette(); + QColor ColorPlaceholderText(SWITCH_BTN_HIGHLIGHT_BACK_COLOR); + QBrush brush2; + brush2.setColor(ColorPlaceholderText); + //主题框架1.0.6-5kylin2 + palette.setColor(QPalette::Highlight,QColor(69, 173, 110,255)); + palette.setColor(QPalette::Button,QColor(69, 173, 110,255)); + palette.setBrush(QPalette::ButtonText, QBrush(Qt::white)); + ui->suspendCountdownBtn->setPalette(palette); + + countdown_timer->stop(); + countdown_isStarted_2=1; + } + + return; +} + +/* + * 倒计时初始数字转盘 + * Countdown initial digital dial + */ +void Clock::countdownSetStartTime() +{ + + //倒计时小时滚轮 + hourTimerRing = new VerticalScroll_99(ui->countdownSetPage); + QLabel * h_in_m = new QLabel (ui->countdownSetPage); + //倒计时分钟 + minuteTimeRing = new VerticalScroll_60(ui->countdownSetPage); + QLabel * m_in_s = new QLabel (ui->countdownSetPage); + //倒计时秒 + secondTimeRing = new VerticalScroll_60(ui->countdownSetPage); + QLabel * after_s = new QLabel (ui->countdownSetPage); + + + h_in_m->resize(50,30); + h_in_m->setText(tr("hour")); +// h_in_m->setStyleSheet("font: 30pt 'Sans Serif';"); + m_in_s->resize(50,30); + m_in_s->setText(tr("min")); +// m_in_s->setStyleSheet("font: 30pt 'Sans Serif';"); + after_s->resize(50,30); + after_s->setText(tr("sec")); +// after_s->setStyleSheet("font: 30pt 'Sans Serif';"); + int ringMoveWidth = 73; + int ringMoveHeight = 45; + int timeSep = 100; + int labelSep = 55; + int timeLabelMoveHeight = 130; + hourTimerRing->move(ringMoveWidth, ringMoveHeight); + h_in_m->move(ringMoveWidth+labelSep,timeLabelMoveHeight); + //hour 要比min长 + if(Utils::checkLocalUs()){ + ringMoveWidth+=timeSep+4; + }else{ + ringMoveWidth+=timeSep; + } + minuteTimeRing->move(ringMoveWidth, ringMoveHeight); + m_in_s->move(ringMoveWidth+labelSep,timeLabelMoveHeight); + ringMoveWidth+=timeSep; + secondTimeRing->move(ringMoveWidth, ringMoveHeight); + after_s->move(ringMoveWidth+labelSep,timeLabelMoveHeight); + //配置倒计时页的开始按钮 + startCountSingle = new QPushButton(ui->countdownSetPage); + startCountSingle->resize(120,34); + startCountSingle->move(135,401); + startCountSingle->setText(tr("start")); + connect(startCountSingle, SIGNAL(clicked()), this, SLOT(startbtnCountdown()) ); + + QPalette palette2 = startCountSingle->palette(); + QColor ColorPlaceholderText2(233,233,233,255); + QBrush brush2; + brush2.setColor(ColorPlaceholderText2); + palette2.setColor(QPalette::Button,QColor(233,233,233,255)); + //palette2.setBrush(QPalette::ButtonText, QBrush(Qt::white)); + startCountSingle->setPalette(palette2); + + QTimer *timer_count_start; + timer_count_start = new QTimer(); + connect(timer_count_start, SIGNAL(timeout()), this, SLOT(countStatBtnGray())); + timer_count_start->setInterval(100); + timer_count_start->start(); +} + +/* + * 倒计时页开始键致灰 + * Start button of countdown page grays out + */ +void Clock::countStatBtnGray() +{ + if(hourTimerRing->m_currentValue==0 && minuteTimeRing->m_currentValue==0 && secondTimeRing->m_currentValue==0) { + startCountSingle->setEnabled(false); + QStyleOption opt; + opt.init(this); + + if(theme::themetype==0){ + QPalette palette2 = startCountSingle->palette(); + QColor ColorPlaceholderText2(233,233,233,255); + QBrush brush2; + brush2.setColor(ColorPlaceholderText2); + palette2.setColor(QPalette::Button,QColor(233,233,233,255)); + palette2.setBrush(QPalette::ButtonText, QBrush(QColor(158,158,158,255))); + startCountSingle->setPalette(palette2); + }else{ + QPalette palette2 = startCountSingle->palette(); + QColor ColorPlaceholderText2(45,45,48,255); + QBrush brush2; + brush2.setColor(ColorPlaceholderText2); + palette2.setColor(QPalette::Button,QColor(45,45,48,255)); + palette2.setBrush(QPalette::ButtonText, QBrush(QColor(58,58,58,255))); + startCountSingle->setPalette(palette2); + } + }else{ + startCountSingle->setEnabled(true); + QPalette palette2 = startCountSingle->palette(); + QColor ColorPlaceholderText2(SWITCH_BTN_HIGHLIGHT_BACK_COLOR); + QBrush brush2; + brush2.setColor(ColorPlaceholderText2); + palette2.setColor(QPalette::Button,QColor(SWITCH_BTN_HIGHLIGHT_BACK_COLOR)); + palette2.setBrush(QPalette::ButtonText, QBrush(Qt::white)); + startCountSingle->setPalette(palette2); + } +} + + +void Clock::updateLabelFront(QLabel *label, int size) +{ + QString styleSheet = "font-size:"; + styleSheet.append(QString::number(size)).append("px;"); + label->setStyleSheet(styleSheet); +} + +void Clock::updateQLineEditFront(QLineEdit *lineEdit, int size) +{ + QFont font ; + font.setPixelSize(size); + lineEdit->setFont(font); +} +/** + * @brief 放大闹钟子项字体 + */ +void Clock::updateAlarmItemFront(int size) +{ + QListWidget * alarmList = ui->alarmListWidget; + for (int i=0;icount() ;i++ ) { + QListWidgetItem * varItem = alarmList->item(i); + item_new * varWidget = static_cast(alarmList->itemWidget(varItem)) ; + varWidget->commonStyle(size); + } +} + +void Clock::updateStopwatchItemFront(int size) +{ + QListWidget * stopwatchList = ui->timeListWidget; + for (int i=0;icount() ;i++ ) { + QListWidgetItem * varItem = stopwatchList->item(i); + stopwatch_item * varWidget = static_cast(stopwatchList->itemWidget(varItem)) ; + updateLabelFront(varWidget->stopwatch1,round(1.1*size)); + updateLabelFront(varWidget->stopwatch2,round(1.1*size)); + updateLabelFront(varWidget->stopwatch3,round(2.2*size)); + } +} +void Clock::updateFront(const int size) +{ + + //闹钟页面子项 + updateAlarmItemFront(size); + //秒表页面 两个时间 + updateLabelFront(ui->timeShowBig,round(3.2*size)); + updateLabelFront(ui->timeShowSmall,round(1.73*size)); + //秒表页面子项 + updateStopwatchItemFront(size); + double font = 1.15; + //闹钟编辑页面 + //重复 + updateLabelFront(repeatSelectOnClockNew->nameLabel,round(font*size)); + updateLabelFront(repeatSelectOnClockNew->textLabel,round(font*size)); + //提醒铃声 + updateLabelFront(musicSelectOnClockNew->nameLabel,round(font*size)); + updateLabelFront(musicSelectOnClockNew->textLabel,round(font*size)); + //稍后提醒 + updateLabelFront(remindSelectOnClockNew->nameLabel,round(font*size)); + updateLabelFront(remindSelectOnClockNew->textLabel,round(font*size)); + //倒计时 set 铃声 + updateLabelFront(musicSelectOnCountdownSet->nameLabel,round(font*size)); + updateLabelFront(musicSelectOnCountdownSet->textLabel,round(font*size)); + //倒计时 run 铃声 + updateLabelFront(musicSelectOnCountdownRun->nameLabel,round(font*size)); + updateLabelFront(musicSelectOnCountdownRun->textLabel,round(font*size)); + //闹钟名 + updateLabelFront(clockEditOnClockNew->nameLabel,round(font*size)); + //闹钟编辑 + updateQLineEditFront(clockEditOnClockNew->clockNameLineEdit,round(font*size)); +} +void Clock::updateRepeatStr(QLabel *label){ + if(Utils::checkLocalChina()){ + updateLabelTextByLength(label,16); + } + if(Utils::checkLocalUs()){ + updateLabelTextByLength(label,25); + } +} +void Clock::updateLabelTextByLength(QLabel *label, int limitSize) +{ + QString str = label->text(); + if(str.length()>limitSize){ + label->setToolTip(str); + str = Utils::getOmitStr(str,limitSize); + } + label->setText(str); +} + + +/* + * 闹钟初始化数字转盘 + * Alarm clock initialization digital turntable drawing + */ +void Clock::alarmSetStartTime() +{ + shadow = new QWidget(ui->editAlarmPage); + shadow->move(115,58); + shadow->resize(160,58); + //闹钟小时滚轮 + timer_alarm_start24 = new VerticalScroll_24(ui->editAlarmPage, this); + QLabel * h_in_m = new QLabel (ui->editAlarmPage); + //闹钟分钟滚轮 + timer_alarm_start60 = new VerticalScroll_60(ui->editAlarmPage); + + timer_alarm_start24->resize(63,220); + timer_alarm_start60->resize(63,220); + + QLabel * hour_ring = new QLabel (ui->editAlarmPage); + QLabel * min_ring = new QLabel (ui->editAlarmPage); + + hour_ring->hide(); + min_ring->hide(); + + hour_ring->setAlignment(Qt::AlignHCenter); + min_ring->setAlignment(Qt::AlignHCenter); + + h_in_m->resize(10,40); + h_in_m->setText(TIME_SEPARATOR); + h_in_m->setStyleSheet("font: 25pt;"); + + hour_ring->resize(50,30); + hour_ring->setText(tr("hour")); + hour_ring->setStyleSheet("font: 13pt ;color: rgb(148, 148, 148);"); + min_ring->resize(50,30); + min_ring->setText(tr("min")); + min_ring->setStyleSheet("font: 13pt ;color: rgb(148, 148, 148);"); + int ringMoveHeight = -30; + timer_alarm_start24->move(124, ringMoveHeight); + hour_ring->move(140,7); + h_in_m->move(187,60); + timer_alarm_start60->move(196, ringMoveHeight); + min_ring->move(212,7); +} + +/* + * 闹钟初始化工作日选择界面绘制回调 + * Alarm clock initialization workday selection interface drawing callback + */ +void Clock::alarmRepeat() +{ + repeatSelectOnClockNew->updateIconLabel(1); + int num; + //repeat_new_or_edit_flag 编辑是1 + if(repeat_new_or_edit_flag) + num = ui->alarmListWidget->currentRow(); + else { + num= model->rowCount(); + } + QPointF position = this->pos();//446 + dialog_repeat->move(position.x()+DIALOG_MOVE_WIDTH,position.y()+420); + dialog_repeat->setWindowFlags(Qt::Popup); + dialog_repeat->widget[0]->alarmLabel0->setText(tr("No repetition")); + dialog_repeat->widget[1]->alarmLabel0->setText(tr("Workingday")); + dialog_repeat->widget[2]->alarmLabel0->setText(tr("Mon")); + dialog_repeat->widget[3]->alarmLabel0->setText(tr("Tue")); + dialog_repeat->widget[4]->alarmLabel0->setText(tr("Wed")); + dialog_repeat->widget[5]->alarmLabel0->setText(tr("Thu")); + dialog_repeat->widget[6]->alarmLabel0->setText(tr("Fri")); + dialog_repeat->widget[7]->alarmLabel0->setText(tr("Sat")); + dialog_repeat->widget[8]->alarmLabel0->setText(tr("Sun")); + for (int i=0; i<7; i++) { + if (repeat_day[i]) { + //前两个是不重复和工作日 + dialog_repeat->widget[i+2]->alarmLabel1->setPixmap(repeat_on_Pixmap); + } else { + dialog_repeat->widget[i+2]->alarmLabel1->setPixmap(repeat_off_Pixmap); + } + } + dialog_repeat->show(); +} +/* + * 重复选项单击回调 + * Repeat option click callback + */ +void Clock::repeatListclickslot() +{ + int num=dialog_repeat->listWidget->currentRow(); + QString day[7] ; + day[0]= tr("Mon")+" "; + day[1] = tr("Tue")+" "; + day[2] = tr("Wed")+" "; + day[3] = tr("Thu")+" "; + day[4] = tr("Fri")+" "; + day[5] = tr("Sat")+" "; + day[6] = tr("Sun")+" "; + //存储"重复"数据 + switch (num) + { + case 0: + repeatSelectOnClockNew->textLabel->setText(tr("No repetition")); + repeat_str_model = tr("No repetition"); + //不重复 + for (int i=0; i<7; i++) { + // 周一到周日 全存1 + repeat_day[i] = 1; + qDebug() << repeat_day[i]; + //周一到周日 设为不选中 但后续会被覆盖? + dialog_repeat->widget[i+2]->alarmLabel1->setPixmap(repeat_off_Pixmap); + } + + dialog_repeat->close(); + return; + break; + case 1: + repeatSelectOnClockNew->textLabel->setText(tr("Workingday")); + repeat_str_model = tr("Workingday"); + for (int i=0; i<7; i++) { + if(i<5) { + repeat_day[i] = 1; + dialog_repeat->widget[i+2]->alarmLabel1->setPixmap(repeat_on_Pixmap); + } else { + repeat_day[i] = 0; + dialog_repeat->widget[i+2]->alarmLabel1->setPixmap(repeat_off_Pixmap); + } + } + dialog_repeat->widget[7]->alarmLabel1->setPixmap(repeat_on_Pixmap); + dialog_repeat->widget[8]->alarmLabel1->setPixmap(repeat_on_Pixmap); + dialog_repeat->close(); + return; + break; + case 2: + if (repeat_day[0] == 0 ) { + repeat_day[0] = 1; + dialog_repeat->widget[2]->alarmLabel1->setPixmap(repeat_on_Pixmap); + } else { + if(repeat_day[1]== 0 && repeat_day[2]== 0 && repeat_day[3]== 0 && repeat_day[4]== 0 && repeat_day[5]== 0 && repeat_day[6]== 0){ + //防止全部勾选被取消 + }else{ + repeat_day[0] = 0; + dialog_repeat->widget[2]->alarmLabel1->setPixmap(repeat_off_Pixmap); + } + } + break; + case 3: + if(repeat_day[1] == 0 ) { + repeat_day[1] = 1; + dialog_repeat->widget[3]->alarmLabel1->setPixmap(repeat_on_Pixmap); + } else { + if(repeat_day[0]== 0 && repeat_day[2]== 0 && repeat_day[3]== 0 && repeat_day[4]== 0 && repeat_day[5]== 0 && repeat_day[6]== 0){ + + }else{ + repeat_day[1] = 0; + dialog_repeat->widget[3]->alarmLabel1->setPixmap(repeat_off_Pixmap); + } + } + break; + case 4: + if (repeat_day[2] == 0 ) { + repeat_day[2] = 1; + dialog_repeat->widget[4]->alarmLabel1->setPixmap(repeat_on_Pixmap); + } else { + if(repeat_day[1]== 0 && repeat_day[0]== 0 && repeat_day[3]== 0 && repeat_day[4]== 0 && repeat_day[5]== 0 && repeat_day[6]== 0){ + + }else{ + repeat_day[2] = 0; + dialog_repeat->widget[4]->alarmLabel1->setPixmap(repeat_off_Pixmap); + } + } + break; + case 5: + if (repeat_day[3] == 0 ) { + repeat_day[3] = 1; + dialog_repeat->widget[5]->alarmLabel1->setPixmap(repeat_on_Pixmap); + } else { + if(repeat_day[1]== 0 && repeat_day[2]== 0 && repeat_day[0]== 0 && repeat_day[4]== 0 && repeat_day[5]== 0 && repeat_day[6]== 0){ + + }else{ + repeat_day[3] = 0; + dialog_repeat->widget[5]->alarmLabel1->setPixmap(repeat_off_Pixmap); + } + } + break; + case 6: + if (repeat_day[4] == 0 ) { + repeat_day[4] = 1; + dialog_repeat->widget[6]->alarmLabel1->setPixmap(repeat_on_Pixmap); + } else { + if(repeat_day[1]== 0 && repeat_day[2]== 0 && repeat_day[3]== 0 && repeat_day[0]== 0 && repeat_day[5]== 0 && repeat_day[6]== 0){ + + }else{ + repeat_day[4] = 0; + dialog_repeat->widget[6]->alarmLabel1->setPixmap(repeat_off_Pixmap); + } + } + break; + case 7: + if (repeat_day[5] == 0 ) { + repeat_day[5] = 1; + dialog_repeat->widget[7]->alarmLabel1->setPixmap(repeat_on_Pixmap); + } else { + if(repeat_day[1]== 0 && repeat_day[2]== 0 && repeat_day[3]== 0 && repeat_day[4]== 0 && repeat_day[0]== 0 && repeat_day[6]== 0){ + + }else{ + repeat_day[5] = 0; + dialog_repeat->widget[7]->alarmLabel1->setPixmap(repeat_off_Pixmap); + } + } + break; + case 8: + if (repeat_day[6] == 0 ) { + repeat_day[6] = 1; + dialog_repeat->widget[8]->alarmLabel1->setPixmap(repeat_on_Pixmap); + } else { + if(repeat_day[1]== 0 && repeat_day[2]== 0 && repeat_day[3]== 0 && repeat_day[4]== 0 && repeat_day[5]== 0 && repeat_day[0]== 0){ + + }else{ + repeat_day[6] = 0; + dialog_repeat->widget[8]->alarmLabel1->setPixmap(repeat_off_Pixmap); + } + } + break; + default: + break; + } + //构造重复repeat_str + for (int i=0; i<7; i++) { + if (repeat_day[i]) { + repeat_str=repeat_str+day[i]; + } + } + if(repeat_day[0]&&repeat_day[1]&&repeat_day[2]&&repeat_day[3]&&repeat_day[4]&&repeat_day[5]&&repeat_day[6]) + repeat_str = tr("Every day"); + repeatSelectOnClockNew->textLabel->setText(repeat_str); + repeat_str_model = repeat_str; + repeat_str=""; + updateRepeatStr(repeatSelectOnClockNew->textLabel); +} + +/* + * 闹钟初始化音乐选择界面回调 + * Alarm clock initialization music selection interface callback + */ +void Clock::selectAlarmMusic() +{ + musicSelectOnClockNew->updateIconLabel(1); + QPointF position = this->pos(); + dialog_music->move(position.x()+DIALOG_MOVE_WIDTH,position.y()+482); + dialog_music->setWindowFlags(Qt::Popup); + refreshMusicSelectList(dialog_music); + dialog_music->show(); +} + +void Clock::refreshMusicSelectList(set_alarm_repeat_Dialog *tempDialog) +{ +// tempDialog = new + QList * bellList = m_selectBtnUtil->getAllBellItem(); + int newSize = bellList->size(); + int currentSize = tempDialog->rowNum_all; + if(currentSizeset_aItem(i); + } + tempDialog->rowNum_all=newSize; + } + for (int i=0;isize();i++) { + tempDialog->widget[i]->alarmLabel0->setText(bellList->at(i)); + } +} + + + + + +void Clock::selectRemindLate() +{ + remindSelectOnClockNew->updateIconLabel(1); + QPointF position = this->pos(); + dialog_remind_late->move(position.x()+DIALOG_MOVE_WIDTH,position.y()+510); + dialog_remind_late->setWindowFlags(Qt::Popup); + dialog_remind_late->widget[0]->alarmLabel0->setText(tr("none")); + dialog_remind_late->widget[1]->alarmLabel0->setText(tr("five mins late")); + dialog_remind_late->widget[2]->alarmLabel0->setText(tr("ten mins late")); + dialog_remind_late->widget[3]->alarmLabel0->setText(tr("twenty mins late")); + dialog_remind_late->widget[4]->alarmLabel0->setText(tr("thirsty mins late")); + dialog_remind_late->widget[5]->alarmLabel0->setText(tr("one hour late")); + dialog_remind_late->show(); + +} + +/* + * 闹钟初始化单击选择音乐 + * Alarm initialization Click to select music + */ +void Clock::musicListclickslot() +{ + int num=dialog_music->listWidget->currentRow(); + int size = dialog_music->rowNum_all; + //最后一个自定义铃声 + if(num==(size-1)){ + addDivBell(dialog_music,Clock::add_clock); + }else{ + QString id = m_selectBtnUtil->getBellIdByIndex(num); + QString path = m_selectBtnUtil->getBellPathById(id); + QString name = m_selectBtnUtil->getBellNameById(id); + musicSelectOnClockNew->textLabel->setText(name); + //排除无 + if(num==0){ + path=""; + } + playMusicFromPath(path); + } + dialog_music->close(); +} + +void Clock::remindLateListClickSlot() +{ + int num=dialog_remind_late->listWidget->currentRow(); + remind_late_str_model =getRemindLateStrFromNum(num); + remindSelectOnClockNew->textLabel->setText(remind_late_str_model); + dialog_remind_late->close(); +} + +QString Clock::getRemindLateStrFromNum(int num) +{ + QString temp=tr("none"); + switch (num) + { + case 0: + temp=tr("none"); + break; + case 1: + temp=tr("five mins late"); + break; + case 2: + temp=tr("ten mins late"); + break; + case 3: + temp=tr("twenty mins late"); + break; + case 4: + temp=tr("thirsty mins late"); + break; + case 5: + temp=tr("one hour late"); + break; + default: + temp=tr("none"); + break; + } + return temp; +} + + + +/* + * Default setting database data initialization + * 默认设置数据库数据初始化 + */ +void Clock::modelSetupSet() +{ + int setup_rowNum; + setup_rowNum = model_setup->rowCount(); + if (setup_rowNum < 1) { + model_setup->insertRow(setup_rowNum); + model_setup->setData(model_setup->index(setup_rowNum, 0), int(0));//静音 Mute + QString id = m_selectBtnUtil->getDefaultBellId(); + model_setup->setData(model_setup->index(setup_rowNum, 1), id); + } + model_setup->submitAll(); +} + + + +void Clock::paintEvent(QPaintEvent *event) +{ + Q_UNUSED(event); + QPainter p(this); + p.setRenderHint(QPainter::Antialiasing); // 反锯齿; + QPainterPath rectPath; + rectPath.addRoundedRect(this->rect(), 0, 0); // 左上右下 + + QPainter painter(this); + QStyleOption opt; + opt.init(this); + painter.setBrush(opt.palette.color(QPalette::Base)); + + QColor mainColor; + mainColor = palette().color(QPalette::Base); + p.fillPath(rectPath,QBrush(mainColor)); +} + + + +bool Clock::eventFilter(QObject *watched, QEvent *event) +{ + if(watched == ui->editAlarmPage && event->type() == QEvent::Paint) + { + showPaint(); //响应函数 + } + + if(watched == shadow && event->type() == QEvent::Paint) + { +// showPaint7(); + } + return QWidget::eventFilter(watched,event); +} + +/* + * 实现响应函数设置页 +*/ +void Clock::showPaint() +{ + QPainter painter(ui->editAlarmPage); + painter.setPen(Qt::gray); + painter.setBrush(Qt::green); + QStyleOption opt; + opt.init(this); + painter.setBrush(opt.palette.color(QPalette::Base)); + painter.setPen(Qt::transparent); + QRect rect = ui->editAlarmPage->rect(); + rect.setWidth(rect.width() - 0); + rect.setHeight(rect.height() - 0); + painter.drawRoundedRect(rect, 7, 7); + { + QPainterPath painterPath; + painterPath.addRoundedRect(rect, 0, 0); + painter.drawPath(painterPath); + } +} + + + +/* + * 实现响应函数设置页 +*/ +void Clock::showPaint7() +{ + QPainter painter(shadow); + painter.setPen(Qt::gray); + painter.setBrush(Qt::green); + QStyleOption opt; + opt.init(this); + painter.setBrush(opt.palette.color(QPalette::Base)); + + + painter.setBrush(QColor(theme::timeScrollBackColor)); + + painter.setPen(Qt::transparent); + QRect rect = shadow->rect(); + rect.setWidth(rect.width() - 0); + rect.setHeight(rect.height() - 0); + painter.drawRoundedRect(rect, 7, 7); + { + QPainterPath painterPath; + painterPath.addRoundedRect(rect, 8, 8); + painter.drawPath(painterPath); + } +} +/** + * @brief 多屏幕下,Natice_alarm移动 + * @param spostion SP_LEFT 左下角 SP_RIGHT 右下角 SP_CENTER 居中 + * @param + * + * @return 返回说明 + */ +void Clock::moveUnderMultiScreen(Clock::ScreenPosition spostion,QWidget * tempDialog,int hiddenFlag) +{ + QScreen *screen=QGuiApplication::primaryScreen (); + int screen_width = screen->geometry().width(); + int screen_height = screen->geometry().height(); + int x = primaryManager->getNScreen_x(); + int y = primaryManager->getNScreen_y(); + int heightRadio = 20; + int widthRadio = 14; + + switch (spostion) { + case SP_LEFT: + { + int moveWidth = x+round(tempDialog->width()+round(1.0/heightRadio*screen_width)); + int moveHeight = y+round(screen_height-tempDialog->height()-round(1.0/widthRadio*screen_height)); + tempDialog->move(moveWidth,moveHeight); + }break; + case SP_RIGHT: + { + int moveWidth = x+round(screen_width-tempDialog->width()); + int moveHeight = y+round(screen_height-tempDialog->height()-50); + tempDialog->move(moveWidth,moveHeight); + if (hiddenFlag == 1) + tempDialog->move(moveWidth,moveHeight); + else + tempDialog->move(moveWidth,moveHeight-tempDialog->height()); + }break; + case SP_CENTER: + { + int moveWidth = x+round((screen_width-tempDialog->width())*1.0/2); + int moveHeight = y+round((screen_height-tempDialog->height())*1.0/2); + tempDialog->move(moveWidth,moveHeight); + }break; + case UP_LEFT: + { + int moveWidth = x+round(tempDialog->width()+round(1.0/heightRadio*screen_width)); + int moveHeight = y+round(tempDialog->height()+round(1.0/widthRadio*screen_height)); + tempDialog->move(moveWidth,moveHeight); + }break; + case UP_RIGHT: + { + int moveWidth = x+round(screen_width-tempDialog->width()-round(1.0/heightRadio*screen_width)); + int moveHeight = y+round(1.0/20*screen_height); + tempDialog->move(moveWidth,moveHeight); + }break; + case UP_CENTER: + { + int moveWidth = x+round((screen_width-tempDialog->width())*1.0/2); + int moveHeight = y+round((screen_height-tempDialog->height())*1.0/2); + tempDialog->move(moveWidth,moveHeight); + }break; + default: + {} + } +} + + +void Clock::updateTinyBtn() +{ + QPixmap pixmap = QPixmap(":image/switchIconB.png"); + ui->tinyWindowBtn->setProperty("useButtonPalette", true); + ui->tinyWindowBtn->setIcon(pixmap); + ui->tinyWindowBtn->setIconSize(QSize(24,24)); + ui->tinyWindowBtn->setToolTip(tr("mini window")); +// ui->tinyWindowBtn->setFlat(true); +} +void Clock::updateSwitchBtnStyle() +{ + int index=ui->mainWidget->currentIndex(); + if(index==1){ + AlarmPageSwitch(); + }else if(index==0){ + CountdownPageSwitch (); + }else if(index==2){ + StopwatchPageSwitch (); + } +} +//黑色主题 +void Clock::blackStyle() +{ + ui->timeShowBig->setStyleSheet("color: rgba(255, 255, 255, 0.9);font-size:38px;"); +// QString selfFont = Utils::loadFontFamilyFromTTF(); +// QFont f(selfFont); + QFont f; + f.setFamily("NotoSansCJKsc-Regular"); + f.setWeight(400); + f.setPixelSize(38); + ui->timeShowBig->setFont(f); + ui->remainTime->setStyleSheet("color: rgba(255, 255, 255, 0.9)"); + ui->noAlarmIcon->setPixmap(QPixmap(":/image/noClockBlack.png")); + ui->noAlarm->setStyleSheet("color: rgba(255, 255, 255, 0.6);font-size:16px;"); + + widgetListBlackStyle(ui->alarmListWidget); + widgetListBlackStyle(ui->timeListWidget); + QString itemRadius = QString::number(ITEM_RADIUS); + clockEditOnClockNew->clockNameLineEdit->setStyleSheet("QLineEdit{background-color:rgb(55, 55, 59);border-radius:"+itemRadius+"px;color: rgb(148, 148, 148);}"); + ui->tinyWindowBtn->setIcon(QIcon(":image/switchIconW.png")); + updateSwitchBtnStyle(); +} +//白色主题 +void Clock::whiteStyle() +{ + ui->timeShowBig->setStyleSheet("color: rgba(49, 66, 89, 1);font-size:38px;"); +// QString selfFont = Utils::loadFontFamilyFromTTF(); +// QFont f(selfFont); + QFont f; + f.setFamily("NotoSansCJKsc-Regular"); + f.setWeight(400); + f.setPixelSize(38); + ui->timeShowBig->setFont(f); + ui->remainTime->setStyleSheet("color: rgba(49, 66, 89, 1)"); + ui->noAlarmIcon->setPixmap(QPixmap(":/image/noClockWhite.png")); + ui->noAlarm->setStyleSheet("color: rgba(49, 66, 89, 0.6);font-size:16px;"); + widgetListWhiteStyle(ui->alarmListWidget); + widgetListWhiteStyle(ui->timeListWidget); + QString itemRadius = QString::number(ITEM_RADIUS); + clockEditOnClockNew->clockNameLineEdit->setStyleSheet("QLineEdit{background-color:rgb(240, 240, 240);border-radius:"+itemRadius+"px;color: rgb(148, 148, 148);}"); + ui->tinyWindowBtn->setIcon(QIcon(":image/switchIconB.png")); + updateSwitchBtnStyle(); +} + +QString Clock::getDefaultGreyColor() +{ + QColor color = QColor(COUNTDOWN_RING_BACKCOLOR_WHITE_STYLE); + QString str = theme::getColorStr(color); + return str; +} + + + + + diff --git a/clock.h b/clock.h new file mode 100644 index 0000000..154c315 --- /dev/null +++ b/clock.h @@ -0,0 +1,516 @@ +/* +* 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 3, or (at your option) +* any later version. +* +* This program is distributed in the hope that it will be useful, +* but WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +* GNU General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, see +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "stopwatchItem.h" +#include "verticalScroll24.h" +#include "verticalScroll60.h" +#include "verticalScroll99.h" +#include "dotlineDemo.h" +#include "setAlarmRepeatDialog.h" +#include "adaptscreeninfo.h" +#include "about.h" +#include "debug.h" +#include "connection.h" +#include "noticeAlarm.h" +#include "ui_noticeAlarm.h" +#include "deleteMsg.h" +#include "ui_deleteMsg.h" +#include "selectbtn.h" +#include "closeOrHide.h" +#include "constant_class.h" +#include "utils.h" +#include "primarymanager.h" +#include "tinycountdown.h" +#include "theme.h" +#include +#include "ClockInterface.h" +#include +#include "CJsonObject.hpp" +#include "commontooltip.h" +#include "btnNew.h" +#include "selectbtnutil.h" +#include +#include + +class QDialog; +class QSpinBox; +class QComboBox; +class QLabel; +class QFont; +class QPushButton; +class QMediaPlaylist; +class QSqlTableModel; +class SelectBtn; +class close_or_hide; + + +namespace Ui { +class Clock; +} + +class Clock : public QWidget +{ + Q_OBJECT + +public: + + explicit Clock(QWidget *parent = nullptr); + ~Clock(); + + void paintEvent(QPaintEvent *event) override; + void keyPressEvent(QKeyEvent * event) override; + void callUserGuide(); + bool eventFilter(QObject *watched, QEvent *event) override; + void showPaint(); + void showPaint7(); + void updateLabelFront(QLabel * label,int size); //修改label字体 + void updateQLineEditFront(QLineEdit * lineEdit,int size); //修改QLineEdit字体 + void updateAlarmItemFront(int size); //修改闹钟子项字体 + void updateStopwatchItemFront(int size); //修改秒表子项字体 + int CURRENT_FONT_SIZE=11; + enum ScreenPosition { + SP_LEFT = 1, + SP_CENTER = 2, + SP_RIGHT=3, + UP_LEFT=4, + UP_CENTER=5, + UP_RIGHT=6 + }; + enum btnType{ + count_down=1, + add_clock=2 + }; + void moveUnderMultiScreen(Clock::ScreenPosition,QWidget * dialog,int hiddenFlag); //多显示器下,位置移动 + QString formatX_h(int x_h); + Ui::Clock *ui; + QString m_timeZone; + QSqlTableModel *model_setup; + QString addAlarm(clockInterface::RequestParams param); + QString addAlarmJosn(QString param); + QString updateClockByIdJosn(QString param); + QString selectClockByIdJosn(QString param); + QString deleteClockByIdJosn(QString param); +protected: + void paintEvent1(QPaintEvent *); + void closeEvent(QCloseEvent *event) override; + +public slots: + void CountdownPageSwitch(); // 倒计时切换 + // Countdown switch + void AlarmPageSwitch(); // 闹钟窗口切换 + // Alarm window switching + void StopwatchPageSwitch(); // 秒表窗口切换 + // Stopwatch window switc + void settingsStyle(); // 监听主题 + + void blackStyle(); // 黑色主题 + + void whiteStyle(); // 白色主题 + void updateTinyBtn(); + + void drawNoAlarmPrompt(); // 绘制无闹钟提示 + // Draw no alarm prompt + +private slots: + void buttonImageInit(); // 闹钟按钮图片初始化 + // Alarm button picture initialization + void CountdownInit(); // 倒计时页初始化 + // Countdown page initialization + void stopwatchInit(); // 秒表页初始化 + // Stopwatch page initialization + void clockInit(); // 闹钟页初始化 + // Alarm page initialization + void setupInit(); // 默认初始设置 + void bellIni(); + // Default initial settings + void noticeDialogShow(int, int,QString id); // 通知弹窗 + // Notification Popup + void modelSetupSet(); // 默认设置数据库数据初始化 + // Default setting database data initialization + void CountDown(); // 秒表执行 + // Stopwatch execution + void onPushbuttonStartClicked(); // 秒表开始暂停继续 + // Stopwatch start pause continue + void onPushbuttonRingClicked(); // 计次 + void updateLongestShortLabel(); + // times count + void onPushbuttonTimeselectClicked(); // 位 + // reset + void windowClosingClicked(); // 窗口关闭 + // window closing + void windowMinimizingClicked(); // 窗口最小化 + void muteAllBell(); + // window minimizing + void timerUpdate(); // 动态监控闹钟与本地时间 + // Dynamic monitoring alarm clock and local time + void textTimerupdate(); // 闹钟上方电子表 + // Electronic watch above alarm clock + void setAlarmClock(); // 新建闹钟按钮回调 + void setMusicSelectDialogListById(QString bellId,QListWidget * temp); + void setRemindLateSelectDialogListByName(QString name,QListWidget * temp); + int getRemindStatusByName(QString name); + // New alarm button callback + void updateAlarmClock(); // 重绘窗口,更新闹钟 + // Redraw window, update alarm clock + void OnOffAlarm(); // 闹钟开关 + // Alarm switch + void deleteAlarm(); // 闹钟重编辑页面删除闹钟回调 + void deleteAlarmDatabase(QString id); + void updateClockDatabase(QString id,QString name,QString hour,QString minute,int onOff); + // Alarm re edit page delete alarm callback + void listdoubleClickslot(); // 双击闹钟打开重编辑页面 + + QString getClockPkByCurrentNum(); + + QSqlQuery getClockByPK(QString id); + // Double click the alarm clock to open the re edit page + void stopwatchStartAnimation(); // 倒计时开始动画移动 + // Countdown start animation move + void stopwatchStopAnimation(); // 倒计时结束动画移动 + // Countdown start animation move + void statCountdown(); // 倒计时执行 + void statCountdownMsec(); + // Countdown execution + void setcoutdownNumber(int h, int m, int s); // 设置倒计时初始时间 + // Set the initial countdown time + void startbtnCountdown(); // 倒计时开始-结束回调 + void tinyCountdownFinish(); + // Countdown start end callback + void onMin_5btnClicked(); // 倒计时5分钟设置回调 + // Countdown 5 minutes set callback + void getCountdownOverTime(); // 获取倒计时结束时间 + // Get countdown end time + void onCountPushClicked(); // 倒计时-暂停继续回调 + // Countdown - pause resume callback + void stopwatchJg(); // 时间间隔计算执行回调 + // Interval calculation execution callback + void changeTimeNum(int Hour, int Minute); // 修改时间单数 为两位数 + // Modify time singular to two digits + void countdownSetStartTime(); // 倒计时初始数字转盘 + // Countdown initial digital dial + void alarmSetStartTime(); // 闹钟初始化数字转盘绘制 + // Alarm clock initialization digital turntable drawing + void alarmCancelSave(); // 闹钟新建界面取消回调 + // Cancel callback in alarm new interface + void setAlarmSave(); // 闹钟新建界面保存回调 + void saveClockToDatabase(int rowNum); + QString getSelectBellId(set_alarm_repeat_Dialog * tempDialog); + + + QString addAlarm(QString clockName,int hour,int minute); // 闹钟新建界面保存回调 + QString formatReturnMsg(neb::CJsonObject oJson,clockInterface::STATUS_CODE status,std::string msg); + QString formatReturnMsg(clockInterface::STATUS_CODE status,std::string msg); + // Alarm new interface save callback + // Alarm clock new and re edit interface remaining time real-time display callback + void alarmRepeat(); // 闹钟初始化工作日选择界面绘制回调 + // Alarm clock initialization workday selection interface drawing callback + void repeatListclickslot(); // 重复选项单击回调 + // Repeat option click callback + void selectAlarmMusic(); // 闹钟初始化音乐选择界面回调 + void refreshMusicSelectList(set_alarm_repeat_Dialog * tempDialog); + void selectRemindLate(); + // Alarm clock initialization music selection interface callback + void musicListclickslot(); // 闹钟初始化单击选择音乐 + void remindLateListClickSlot(); + QString getRemindLateStrFromNum(int num); + // Alarm initialization Click to select music + // Alarm clock initialization music time selection interface callback + // Click to select music duration callback + // Set page draw callback + // Mute switch callback + // Set volume callback + void countdownMusicSellect(); // 倒计时音乐选择 + // Countdown music selection + void countMusicListclickslot(); // 倒计时音乐选择单机回调 + void playMusicFromPath(QString path); + void stopHisPlay(); + void addDivBell(set_alarm_repeat_Dialog *tempDialog,btnType type); + // Countdown music selection single callback + void countdownNoticeDialogShow(); // 倒计时通知弹窗 + // Countdown notification pop-up + void offAlarm(int); // 重复时单独关闭闹钟 + // Turn off the alarm separately if it is not repeated + // Calculate the next alarm ring interval + // Calculate the next alarm ring interval + QString changeNumToStr(int alarmHour); // 整型转字符 + // Integer to character + void onCustomContextMenuRequested(const QPoint &pos); // 闹钟右键删除事件处理函数 + + void countStatBtnGray(); + + QString get12hourStr(int x_h); + void createUserGuideDebusClient(); + void onTinyClicked(); + void activeWindow(); +private: + QPoint m_startPoint; + QTimer *timer = nullptr; + QTimer *countdown_timer = nullptr; + QTimer *timer_2 = nullptr; + int hour, minute, second, pushflag; + int stopwatch_hour, stopwatch_minute, stopwatch_second; + int countdown_hour, countdown_minute, countdown_second, countdown_pushflag; + int countdown_msec=1000; + int alarmHour; + int alarmMinute; + int cPauseTime; + bool isStarted; + /** + * @brief 倒计时运行标记 + */ + bool countdown_isStarted; + bool countdown_isStarted_2; + bool stopwatch_isStarted; + + QMediaPlayer *player; + QString ring;// 铃声名字 + // Ring name + QPixmap pixmap1; + QPixmap pixmap2; + QPixmap pixmap3; + QPixmap pixmap4; + QPixmap pixmap5; + QPixmap pixmap6; + QPixmap pixmap7; + QPixmap pixmap8; + QPixmap pixmap9; + QPixmap pixmap10; + QPixmap pixmap11; + QPixmap bgPixmap; + QPixmap repeat_on_Pixmap; + QPixmap repeat_off_Pixmap; + QPixmap hourPixmap; + QPixmap minutePixmap; + QPixmap secondPixmap; + QPixmap delBtnPixmap; + QPixmap on_pixmap; + QPixmap off_pixmap; + QPixmap clock_icon; + + QDialog *dialog; + QFont alarmFont; + QSpinBox *hourBox; + QSpinBox *minuteBox; + QComboBox *pauseTime; + + QMediaPlayer *player_alarm; + QMediaPlaylist *mediaList; /*播放列表 + playlist*/ + QSqlTableModel *model; /*数据库 + data base*/ + QSqlTableModel *model_Stopwatch; + QString musicPath; + + item_new *w1[20]; + QListWidgetItem *aItem[20]; + stopwatch_item *stopwatch_w[100]; + QListWidgetItem *stopwatch_aItem[100]; + QString stopwatch_h; + QString stopwatch_m; + QString stopwatch_s; + QString stopwatch_jg_h = "00"; + QString stopwatch_jg_m = "00"; + QString stopwatch_jg_s = "00"; + QString alarmHour_str; + QString alarmMinute_str; + + int stopwatch_item_flag = 0; + int clock_num = 0; + int on_off_flag = 0; + int add_change_flag = 0; + int change_alarm_line = 0; + int medel_flag = 0; + int continu_flag = 0; + int alarm_repeat_flag = 0; + int repeat_day[9]; /*重复日选择保存中介 + Select and save mediation for duplicate days*/ + int repeat_new_or_edit_flag; /*重复日判断 是新建,还是重编辑,两者获取数据库号不同; + Whether to create or re edit the duplicate day is determined. The database numbers obtained by the two methods are different*/ + int stopwatch_Animation = 0; + int system_time_flag; + int last_day_ring = 0; + + VerticalScroll_99 *hourTimerRing; + VerticalScroll_60 *minuteTimeRing; + VerticalScroll_60 *secondTimeRing; + VerticalScroll_24 *timer_alarm_start24; + VerticalScroll_60 *timer_alarm_start60; + + set_alarm_repeat_Dialog *dialog_repeat = nullptr; + set_alarm_repeat_Dialog *dialog_music = nullptr; + set_alarm_repeat_Dialog *dialog_remind_late = nullptr; + + QSqlTableModel * m_bellQueryModel = nullptr; +// set_alarm_repeat_Dialog *time_music = nullptr; + set_alarm_repeat_Dialog *count_music_sellect = nullptr; + + close_or_hide *close_or_hide_page; + adaptScreenInfo *m_pSreenInfo = nullptr; + PrimaryManager * primaryManager = nullptr; + Utils *utils = nullptr; + QWidget *grand = nullptr; + QString repeat_str; + QString repeat_str_model; + QString remind_late_str_model; +// QString time_music_str_model; + QString clock_name; + QPropertyAnimation *animation1; + QPropertyAnimation *animation2; + QPropertyAnimation *animation3; + + QPushButton *startCountSingle; + QWidget *shadow; + + QPoint m_dragPosition; /*拖动坐标*/ + bool mousePressed; /*鼠标是否按下*/ + + Btn_new *musicSelectOnCountdownSet; + Btn_new *musicSelectOnCountdownRun; + Btn_new *repeatSelectOnClockNew; + Btn_new *clockEditOnClockNew; + Btn_new *musicSelectOnClockNew; + Btn_new *remindSelectOnClockNew; +// Btn_new *ring_sel; + QMenu *m_menu; /*功能菜单*/ + + QMenu *popMenu_In_ListWidget_; /*闹钟右键删除菜单*/ + QAction *action_Delete_In_ListWidget_; + QAction *action_Clear_In_ListWidget_; /*闹钟右键删除动作*/ + QAction *action_edit_In_ListWidget_; /*闹钟右键删除动作*/ + Natice_alarm *countdownNoticeDialog = nullptr; + Natice_alarm *alarmNoticeDialog = nullptr; + QDBusInterface *userGuideInterface; // 用户手册 + bool refreshCountdownLabel11Flag = false; //是否刷新,倒计时上的小闹钟时间的数值。因为秒数的变化,如果一直动态计算,会出现1分钟的误差 + int x_h=0, x_m=0 ; + bool m_selectTinyCountdown = false; + tinyCountdown * tinycountdownDia = nullptr; + + void listenToGsettings(); //监听 + void updateFront(const int size); + void set24ClockItem(int time_H,int time_M,int time_S,int rowNum); + void set12ClockItem(int time_H,int time_M,int time_S,int rowNum); + void clearClockItem(int rowNum); + void iniSystemTimeFlag(); + bool checkSystem24(); + void muteBtnStyle(); + void minBtnStyle(); + void closeBtnStyle(); + void menuBtnStyle(); + bool checkTinyCountdownDia(); + void navigationBtnStyle(QPushButton * btn); + theme * currentTheme; + QHash * indexWeekdayMap = nullptr; + CommonToolTip * m_commonToolTip; + int m_commonToolTipRemainTime = 3; + bool m_muteOn = false; + bool onEditPage = false; + QTimer * m_commonToolTipCloseTimer; + QMap * timeSepOrderIndex = nullptr; + QList * hisLongShortIndex = nullptr; + SelectBtnUtil * m_selectBtnUtil = nullptr; + QMediaPlayer *music = nullptr; + + void updateClockSelectBtnStyle(SelectBtn * temp,int moveHeight); + void updateCountdownSelectBtnStyle(SelectBtn * temp,int moveWidth,int moveHeight); + + void updateClockSelectBtnStyle(Btn_new * temp,int moveHeight); + void updateCountdownSelectBtnStyle(Btn_new * temp,int moveWidth,int moveHeight); + + void updateClockSelectBtnLabel(QLabel * temp,int moveHeight,QString text); + void widgetListWhiteStyle(QListWidget * listWidget); + void widgetListBlackStyle(QListWidget * listWidget); + QMediaPlayer * hisPlayer = nullptr; + void updateSwitchBtnStyle(); + void setSwitchDefaultColor(QPushButton *btn); + QColor getButtonActive(); + QColor getHighlightActive(); + void setDefaultIcon(QPushButton *btn); + void setBtnIcon(QPushButton *btn, QString imgUrl, QString localUrl); + void changeIconHeight(QPushButton *btn); + void setSwitchHighlightColor(QPushButton *btn); + QString getDefaultGreyColor(); + void updateRepeatStr(QLabel *label); + void updateLabelTextByLength(QLabel *label, int limitSize); + void closeHandel(); + QPointer m_trayIcon; + QString m_trayIconTooltip = ""; + void enableTrayIcon(); + void disableTrayIcon(); + QString changeNumToStrWithAm(int alarmHour); + void updateTrayIconTooltip(QString info); + void setDefaultTrayIconTooltip(); +}; + +#endif // CLOCK_H diff --git a/clock.ico b/clock.ico new file mode 100644 index 0000000..35d1b77 Binary files /dev/null and b/clock.ico differ diff --git a/clock.rc b/clock.rc new file mode 100644 index 0000000..001d719 --- /dev/null +++ b/clock.rc @@ -0,0 +1 @@ +IDI_ICON1 ICON DISCARDABLE "clock.ico" \ No newline at end of file diff --git a/clock.ui b/clock.ui new file mode 100644 index 0000000..fc2b7ba --- /dev/null +++ b/clock.ui @@ -0,0 +1,775 @@ + + + Clock + + + + 0 + 0 + 390 + 580 + + + + Alarm + + + + + + + 0 + + + 0 + + + + + + 8 + + + 2 + + + 0 + + + + + + + + + + + + + + + + 0 + 0 + + + + Alarm + + + + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + + 24 + 24 + + + + + 24 + 24 + + + + + + + + + + + + 24 + 24 + + + + + 24 + 24 + + + + + + + + + + + + 24 + 24 + + + + + 24 + 24 + + + + + + + + + + + + 24 + 24 + + + + + 24 + 24 + + + + + + + + + + + + + + + 0 + + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + + 40 + 40 + + + + + 40 + 40 + + + + Alarm + + + + + + + Qt::Horizontal + + + QSizePolicy::Fixed + + + + 26 + 20 + + + + + + + + + 40 + 40 + + + + + 40 + 40 + + + + Count down + + + + + + + Qt::Horizontal + + + QSizePolicy::Fixed + + + + 26 + 20 + + + + + + + + + 40 + 40 + + + + + 40 + 40 + + + + Watch + + + + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + + + + + + + 0 + + + + + + 0 + 0 + 390 + 477 + + + + + + + 0 + + + + + + + 0 + 180 + 371 + 40 + + + + + + + + 24 + 24 + + + + + 24 + 24 + + + + + + + + + + + 24 + 24 + + + + + + + + + + 10 + 100 + 361 + 77 + + + + + + + font-size:40px; + + + 00:00:00 + + + + + + + + + 10 + 40 + 361 + 70 + + + + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + + 13 + 16 + + + + + 26 + 26 + + + + icon + + + + + + + + -1 + + + + color: rgb(176, 176, 176); +font-size:18px; + + + + + + PM + + + + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + + + 9 + 386 + 361 + 48 + + + + + + + + 120 + 34 + + + + + 120 + 16777215 + + + + + + + start + + + + + + + + 120 + 34 + + + + + 120 + 16777215 + + + + + + + suspend + + + + + + + + + + + + + 135 + 401 + 120 + 34 + + + + + 120 + 0 + + + + + + + add + + + + + + 25 + 0 + 340 + 354 + + + + + + + + + + 115 + 76 + 149 + 170 + + + + + + + + + + 125 + 262 + 140 + 31 + + + + color: rgba(49, 66, 89, 0.6); +font-size:16px; + + + no alarm + + + noAlarm + noAlarmIcon + addAlarmBtn + alarmListWidget + + + + + + 210 + 401 + 120 + 34 + + + + + 120 + 0 + + + + + + + start + + + + + + 90 + 55 + 210 + 41 + + + + color: rgb(176, 176, 176); +font: 19pt + + + + 00:00:00 + + + + + + 90 + 0 + 210 + 70 + + + + font: 30pt + + + 00:00:00 + + + + + + 65 + 401 + 120 + 34 + + + + + 120 + 0 + + + + + + + count + + + + + + 25 + 109 + 340 + 277 + + + + + + + + + + + + 0 + 0 + 390 + 477 + + + + + 16777215 + 16777215 + + + + + + + + + 65 + 425 + 120 + 34 + + + + + 120 + 0 + + + + + + + cancel + + + + + + 210 + 425 + 120 + 34 + + + + + 120 + 0 + + + + + + + save + + + + + + 60 + 80 + 41 + 22 + + + + + 0 + 0 + + + + + + + + + + + + + + true + + + + :/Images/Images/NO.png:/Images/Images/NO.png + + + On + + + + + + + Countdown_Animation + QWidget +
countdownAnimation.h
+ 1 +
+
+ + +
diff --git a/clock_conf.ini b/clock_conf.ini new file mode 100644 index 0000000..79c0352 --- /dev/null +++ b/clock_conf.ini @@ -0,0 +1,2 @@ +[common] +version=3.1.4.0-0k0 diff --git a/clockdbusadaptor.cpp b/clockdbusadaptor.cpp new file mode 100644 index 0000000..f6d107a --- /dev/null +++ b/clockdbusadaptor.cpp @@ -0,0 +1,41 @@ +/* +* Copyright (C) 2020, 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 3, or (at your option) +* any later version. +* +* This program is distributed in the hope that it will be useful, +* but WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +* GNU General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, see + + +ClockDbusAdaptor::ClockDbusAdaptor(QObject *parent, Clock *currentClock) : QDBusAbstractAdaptor(parent), + m_clock(currentClock) +{ +} + +ClockDbusAdaptor::~ClockDbusAdaptor() +{ +} + + + + + + + + +QString ClockDbusAdaptor::addAlarmRpc(QString param) +{ + return m_clock->addAlarmJosn(param); +} diff --git a/clockdbusadaptor.h b/clockdbusadaptor.h new file mode 100644 index 0000000..f1138d2 --- /dev/null +++ b/clockdbusadaptor.h @@ -0,0 +1,39 @@ +/* +* Copyright (C) 2020, 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 3, or (at your option) +* any later version. +* +* This program is distributed in the hope that it will be useful, +* but WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +* GNU General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, see +#include +#include "clock.h" +class ClockDbusAdaptor : public QDBusAbstractAdaptor +{ + Q_OBJECT + //声明它正在导出哪个接口 + Q_CLASSINFO("D-Bus Interface", CLOCK_DBUS_SERVICE_NAME) +public: + explicit ClockDbusAdaptor(QObject *parent = nullptr,Clock * currentClock = nullptr); + ~ClockDbusAdaptor(); +signals: +public slots: + QString addAlarmRpc(QString param); +private: + Clock * m_clock; +}; + +#endif // CLOCKDBUSADAPTOR_H diff --git a/clockentitydao.cpp b/clockentitydao.cpp new file mode 100644 index 0000000..2063110 --- /dev/null +++ b/clockentitydao.cpp @@ -0,0 +1,41 @@ +/* +* Copyright (C) 2020, 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 3, or (at your option) +* any later version. +* +* This program is distributed in the hope that it will be useful, +* but WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +* GNU General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, see +#include "connection.h" +class ClockEntityDao : public QObject +{ + Q_OBJECT +public: + explicit ClockEntityDao(QObject *parent = nullptr); + static QSqlQuery getClockByPK(QString id); + static bool checkClockExist(QString id); + +signals: + +}; + +#endif // CLOCKENTITYDAO_H diff --git a/closeOrHide.cpp b/closeOrHide.cpp new file mode 100644 index 0000000..5d65626 --- /dev/null +++ b/closeOrHide.cpp @@ -0,0 +1,136 @@ +/* +* Copyright (C) 2020, 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 3, or (at your option) +* any later version. +* +* This program is distributed in the hope that it will be useful, +* but WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +* GNU General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, see +#include "xatom-helper.h" +#include "constant_class.h" + +extern void qt_blurImage(QImage &blurImage, qreal radius, bool quality, int transposed); + +close_or_hide::close_or_hide(QWidget *parent) : + QDialog(parent), + ui(new Ui::close_or_hide) +{ + ui->setupUi(this); +// this->setProperty("blurRegion", QRegion(QRect(1, 1, 1, 1))); +// setAttribute(Qt::WA_TranslucentBackground); +// this->setWindowFlags(Qt::FramelessWindowHint | Qt::Dialog); + ui->backrunRadio->setChecked(1); + + // 添加窗管协议 + XAtomHelper::setStandardWindowHint(this->winId()); + XAtomHelper::setStandardWindowRadius(this->winId(),WINDOWN_RADIUS); + + ui->closeInfoLabel->setText(tr("Please select the state after closing:")); + ui->closeInfoLabel->setWordWrap(true); + ui->closeInfoLabel->setAlignment(Qt::AlignTop); + //调色板 + QPalette palette = ui->surebtn->palette(); + palette.setColor(QPalette::Button,QColor(61,107,229,255)); + palette.setBrush(QPalette::ButtonText, QBrush(Qt::white)); + //保留按钮 + ui->surebtn->setPalette(palette); + //退出按钮 + QPalette palette1 = ui->closebtn->palette(); + QColor ColorPlaceholderText1(255,255,255,0); + QBrush brush; + brush.setColor(ColorPlaceholderText1); + palette.setBrush(QPalette::Button, brush); + ui->closebtn->setPalette(palette1); + + ui->closebtn->setIcon(QIcon::fromTheme("window-close-symbolic")); + ui->closebtn->setProperty("isWindowButton", 0x2); + ui->closebtn->setProperty("useIconHighlightEffect", 0x8); + ui->closebtn->setFlat(true); +// 主题框架1.0.6-5kylin2 + + //配置重要按钮 + ui->surebtn->setProperty("isImportant", true); + ui->cancelbtn->setProperty("useButtonPalette", true); + //关闭按钮去掉聚焦状态 + ui->closebtn->setFocusPolicy(Qt::NoFocus); + +} + +close_or_hide::~close_or_hide() +{ + delete ui; +} + +void close_or_hide::on_closebtn_clicked() +{ + this->hide(); + close_flag = 0; +} + +void close_or_hide::on_surebtn_clicked() +{ + if(ui->backrunRadio->isChecked()==true){ + this->hide(); + close_flag = 1; + }else{ + this->hide(); + close_flag = 2; + } +} + +void close_or_hide::on_cancelbtn_clicked() +{ + this->hide(); +} + +void close_or_hide::paintEvent(QPaintEvent *event) +{ + Q_UNUSED(event); + QPainter p(this); + p.setRenderHint(QPainter::Antialiasing); // 反锯齿; + QPainterPath rectPath; + rectPath.addRect(this->rect()); + p.fillPath(rectPath,palette().color(QPalette::Base)); +} + +void close_or_hide::mousePressEvent(QMouseEvent *event) +{ + if (event->button() == Qt::LeftButton) { + this->dragPosition = event->globalPos() - frameGeometry().topLeft(); + this->mousePressed = true; + } + QWidget::mousePressEvent(event); +} + +void close_or_hide::mouseReleaseEvent(QMouseEvent *event) +{ + if (event->button() == Qt::LeftButton) { + this->mousePressed = false; + this->setCursor(Qt::ArrowCursor); + } + + QWidget::mouseReleaseEvent(event); +} + +void close_or_hide::mouseMoveEvent(QMouseEvent *event) +{ + if (this->mousePressed) { + move(event->globalPos() - this->dragPosition); + this->setCursor(Qt::ClosedHandCursor); + } + + QWidget::mouseMoveEvent(event); +} diff --git a/closeOrHide.h b/closeOrHide.h new file mode 100644 index 0000000..1116999 --- /dev/null +++ b/closeOrHide.h @@ -0,0 +1,62 @@ +/* +* Copyright (C) 2020, 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 3, or (at your option) +* any later version. +* +* This program is distributed in the hope that it will be useful, +* but WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +* GNU General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, see +#include +#include +#include +#include +#include + +namespace Ui { +class close_or_hide; +} +class Clock; +class close_or_hide : public QDialog +{ + Q_OBJECT + +public: + explicit close_or_hide(QWidget *parent = nullptr); + ~close_or_hide(); + + //绘制底部阴影 + // Draw bottom shadow + void paintEvent(QPaintEvent *event); + + void mousePressEvent(QMouseEvent *event); + void mouseReleaseEvent(QMouseEvent *event); + void mouseMoveEvent(QMouseEvent *event); + + int close_flag; +private slots: + void on_closebtn_clicked(); + + void on_surebtn_clicked(); + + void on_cancelbtn_clicked(); + +private: + Ui::close_or_hide *ui; + QPoint dragPosition; //拖动坐标 + bool mousePressed; //鼠标是否按下 +}; + +#endif // CLOSE_OR_HIDE_H diff --git a/closeOrHide.ui b/closeOrHide.ui new file mode 100644 index 0000000..21aac59 --- /dev/null +++ b/closeOrHide.ui @@ -0,0 +1,419 @@ + + + close_or_hide + + + + 0 + 0 + 350 + 174 + + + + Dialog + + + + + + + + 0 + 0 + 350 + 174 + + + + + 0 + 0 + + + + + + + + + 310 + 0 + 40 + 36 + + + + + 5 + + + 5 + + + 5 + + + + + + 30 + 30 + + + + + 30 + 30 + + + + + + + + + + + + + + + + 0 + 60 + 351 + 40 + + + + + 0 + + + + + Qt::Horizontal + + + QSizePolicy::Fixed + + + + 57 + 20 + + + + + + + + + 0 + 0 + + + + + 11 + + + + + + + backstage + + + + 14 + 14 + + + + + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + + 0 + 0 + + + + + 120 + 0 + + + + + 120 + 16777215 + + + + + 11 + + + + + + + Exit program + + + + 14 + 14 + + + + + + + + Qt::Horizontal + + + + 80 + 20 + + + + + + + + + + 0 + 120 + 351 + 31 + + + + + 0 + 0 + + + + + 0 + + + 0 + + + 0 + + + 0 + + + 0 + + + + + Qt::Horizontal + + + + 156 + 20 + + + + + + + + + 80 + 30 + + + + + 80 + 30 + + + + + 11 + + + + + + + cancel + + + + + + + Qt::Horizontal + + + + 10 + 20 + + + + + + + + + 80 + 30 + + + + + 80 + 30 + + + + + 11 + + + + + + + sure + + + + + + + Qt::Horizontal + + + QSizePolicy::Expanding + + + + 24 + 20 + + + + + + + + + + 0 + 20 + 351 + 41 + + + + + 0 + + + 0 + + + 0 + + + 0 + + + 0 + + + + + Qt::Horizontal + + + QSizePolicy::Fixed + + + + 24 + 20 + + + + + + + + + 24 + 24 + + + + + 24 + 24 + + + + border-image: url(:/image/warning-24x24.png); + + + + + + + + + + + 11 + + + + + + + 请选择关闭后的状态 + + + 0 + + + + + + + + + + diff --git a/commontooltip.cpp b/commontooltip.cpp new file mode 100644 index 0000000..c30d2a6 --- /dev/null +++ b/commontooltip.cpp @@ -0,0 +1,78 @@ +/* +* Copyright (C) 2020, 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 3, or (at your option) +* any later version. +* +* This program is distributed in the hope that it will be useful, +* but WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +* GNU General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, see +#include +#include "theme.h" +#include + +CommonToolTip::CommonToolTip(QWidget *parent) : QDialog(parent) +{ + + this->setAttribute(Qt::WA_TranslucentBackground);//设置窗口背景透明 + this->setWindowFlags(Qt::FramelessWindowHint|Qt::ToolTip); //设置无边框窗口 + setRoundStyle(); + setMsgLabelStyle(); + +} + +void CommonToolTip::setMsgText(QString msg) +{ + m_msgLabel->setText(msg); +} + +void CommonToolTip::paintEvent(QPaintEvent *event) +{ + Q_UNUSED(event); + QPainter painter(this); + painter.setRenderHint(QPainter::Antialiasing); // 反锯齿; + //底色 + painter.setBrush(theme::backcolcr); + painter.setPen(theme::boderColor); + QRect rect = this->rect(); + rect.setWidth(rect.width() - 1); + rect.setHeight(rect.height() - 1); + //圆角 + painter.drawRoundedRect(rect, 6, 6); + QWidget::paintEvent(event); +} + +void CommonToolTip::setRoundStyle() +{ + //圆角 + QBitmap bmp(this->size()); + bmp.fill(); + QPainter p(&bmp); + p.setRenderHint(QPainter::Antialiasing); // 反锯齿; + p.setPen(Qt::NoPen); + p.setBrush(palette().color(QPalette::Base)); + p.drawRoundedRect(bmp.rect(),6,6); + setMask(bmp); +} + +void CommonToolTip::setMsgLabelStyle() +{ + QSize size = QSize(50,32); + this->setMinimumSize(size); + QVBoxLayout *mainvbox=new QVBoxLayout(this); + this->setLayout(mainvbox); + m_msgLabel = new QLabel(this); + m_msgLabel->setMinimumSize(size); + mainvbox->addWidget(m_msgLabel); + +} diff --git a/commontooltip.h b/commontooltip.h new file mode 100644 index 0000000..db9fa8a --- /dev/null +++ b/commontooltip.h @@ -0,0 +1,43 @@ +/* +* Copyright (C) 2020, 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 3, or (at your option) +* any later version. +* +* This program is distributed in the hope that it will be useful, +* but WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +* GNU General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, see +#include +#include + +class CommonToolTip : public QDialog +{ + Q_OBJECT +public: + explicit CommonToolTip(QWidget *parent = nullptr); + void setMsgText(QString msg); + +protected: + void paintEvent(QPaintEvent * event) override; + void setRoundStyle(); + void setMsgLabelStyle(); + +signals: + +private: + QLabel * m_msgLabel; +}; + +#endif // COMMONTOOLTIP_H diff --git a/configutil.cpp b/configutil.cpp new file mode 100644 index 0000000..9e9d48b --- /dev/null +++ b/configutil.cpp @@ -0,0 +1,43 @@ +/* +* Copyright (C) 2020, 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 3, or (at your option) +* any later version. +* +* This program is distributed in the hope that it will be useful, +* but WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +* GNU General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, see +#include + +ConfigUtil::ConfigUtil(QString qstrfilename, QObject *parent) : QObject(parent),m_qstrFileName(qstrfilename) +{ + if (qstrfilename.isEmpty()){ +// m_qstrFileName = QStandardPaths::writableLocation(QStandardPaths::HomeLocation) +"/.config/ukui-clock/clock_conf.ini"; + m_qstrFileName = ":/clock_conf.ini"; + }else{ + m_qstrFileName = qstrfilename; + } + m_psetting = new QSettings(m_qstrFileName, QSettings::IniFormat); + qDebug() << m_qstrFileName; +} + +void ConfigUtil::Set(QString qstrnodename,QString qstrkeyname,QVariant qvarvalue) +{ + m_psetting->setValue(QString("/%1/%2").arg(qstrnodename).arg(qstrkeyname), qvarvalue); +} + +QVariant ConfigUtil::Get(QString qstrnodename,QString qstrkeyname) +{ + QVariant qvar = m_psetting->value(QString("/%1/%2").arg(qstrnodename).arg(qstrkeyname)); + return qvar; +} diff --git a/configutil.h b/configutil.h new file mode 100644 index 0000000..9346817 --- /dev/null +++ b/configutil.h @@ -0,0 +1,42 @@ +/* +* Copyright (C) 2020, 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 3, or (at your option) +* any later version. +* +* This program is distributed in the hope that it will be useful, +* but WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +* GNU General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, see + +#include +#include + +class ConfigUtil : public QObject +{ + Q_OBJECT +public: + explicit ConfigUtil(QString qstrfilename = "",QObject *parent = nullptr); + void Set(QString,QString,QVariant); + QVariant Get(QString,QString); + + +signals: +private: + QString m_qstrFileName; + QSettings *m_psetting; + +}; + +#endif // CONFIGUTIL_H diff --git a/connection.h b/connection.h new file mode 100644 index 0000000..5622478 --- /dev/null +++ b/connection.h @@ -0,0 +1,85 @@ +/* +* 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 3, or (at your option) +* any later version. +* +* This program is distributed in the hope that it will be useful, +* but WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +* GNU General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, see +#include +#include +#include +#include +#include +//创建或打开数据库 +//Create or open database +namespace clock_sql { +static QSqlDatabase db; +static bool createConnection() +{ + QString lan = QLocale().name(); + QString url_filepath = QStandardPaths::writableLocation(QStandardPaths::HomeLocation) +"/.config/Clock_database_"+lan+"_sp2.db"; + //SQLite是一款轻量级的开源的嵌入式数据库 + db = QSqlDatabase::addDatabase("QSQLITE"); + db.setDatabaseName(url_filepath); + if(!db.open()) return false; + //建表语句 + QSqlQuery query; + query.exec(QString( + "create table clock (hour int, minute int, bell_id QString, on_or_off int, num int, repeat Qstring," + "monday int, tuesday int, wednesday int, thursday int, friday int, saturday int , sunday int, " + "name Qstring, id Qstring,remind_status Qstring)")); + query.clear(); + query.exec(QString("create table setup (mute_on int, bell_id QString)")); + query.clear(); + query.exec(QString("create table bell (id QString, bell_cn QString,bell_en QString," + "bell_path QString,create_time int,bell_type int)")); + return true; +} +static QSqlQuery getQSqlQuery(){ + QSqlQuery query(db); + query.clear(); + return query; +} +static QSqlTableModel * getTableByName(QObject *parent,QString name){ + QSqlDatabase db = QSqlDatabase::database(); + QSqlTableModel * model = new QSqlTableModel(parent,db); + model->setTable(name); + model->setEditStrategy(QSqlTableModel::OnManualSubmit); + model->select(); + return model; +} + +static QSqlTableModel * getClockTable(QObject *parent){ + QSqlTableModel * model = getTableByName(parent,"clock"); + return model; +} + +static QSqlTableModel * getSetupTable(QObject *parent){ + QSqlTableModel * model = getTableByName(parent,"setup"); + return model; +} + +static QSqlTableModel * getBellTable(QObject *parent){ + QSqlTableModel * model = getTableByName(parent,"bell"); + return model; +} + + + +} + +#endif // CONNECTION_H diff --git a/constant_class.h b/constant_class.h new file mode 100644 index 0000000..7fef46a --- /dev/null +++ b/constant_class.h @@ -0,0 +1,61 @@ +/* +* Copyright (C) 2020, 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 3, or (at your option) +* any later version. +* +* This program is distributed in the hope that it will be useful, +* but WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +* GNU General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, see +#include "utils.h" +//声明一些必须的宏 +#define ORG_UKUI_STYLE "org.ukui.style" +#define STYLE_NAME "styleName" +#define STYLE_NAME_KEY_DARK "ukui-dark" +#define STYLE_NAME_KEY_DEFAULT "ukui-default" +#define STYLE_NAME_KEY_BLACK "ukui-black" +#define STYLE_NAME_KEY_LIGHT "ukui-light" +#define STYLE_NAME_KEY_WHITE "ukui-white" +#define STYLE_ICON "icon-theme-name" +#define STYLE_ICON_NAME "iconThemeName" +#define TIME_SEPARATOR ":" +#define TIME_SEPARATOR_CN ":" +#define APPLICATION_NAME "ukui-clock" +#define CLOCK_TITLE_NAME "Alarm" +#define KYLIN_CLOCK_APP_NAME "Alarm" + +const static QString chooseColor = "61,107,229,255"; +const static QString hoverColor = "55,144,250,255"; +#define SYSTEM_FONT_EKY "system-font-size" +/*! + * 系统时间 + */ +#define FORMAT_SCHEMA "org.ukui.control-center.panel.plugins" +#define TIME_FORMAT_KEY "hoursystem" +#define SYSTEM_FONT_SIZE "systemFontSize" +#define HOUR_SYSTEM "hoursystem" + +#define DEFAULT_BELL_SAVE_PATH "/usr/share/ukui-clock/" +#define DIY_BELL_SAVE_PATH "/kylindata/ukui-clock/" +#define WHEEL_KEY_HW "wheel-speed" +#define WHEEL_KEY_SP "wheelSpeed" +#define MOUSE_SCHEMA "org.ukui.peripherals-mouse" +const static int TIME_SCROLL_NUM_SIZE = 3; +const static int ITEM_RADIUS=6; +const static int WINDOWN_RADIUS=12; +const static int SELECT_DIA_RADIUS=8; +const static int SELECT_ITEM_RADIUS=6; +const static int COUNTDOWN_TIME=6; +#endif // CONSTANTCLASS_H diff --git a/coreplayer/mmediaplayer.cpp b/coreplayer/mmediaplayer.cpp new file mode 100644 index 0000000..f2367bc --- /dev/null +++ b/coreplayer/mmediaplayer.cpp @@ -0,0 +1,327 @@ +/* +* Copyright (C) 2022 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 3, or (at your option) +* any later version. +* +* This program is distributed in the hope that it will be useful, +* but WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +* GNU General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, see +#include +#include + +MMediaPlayer::MMediaPlayer(QObject *parent) + : QObject(parent) +{ + createMvpplayer(); +} + +void MMediaPlayer::setPlaylist(MMediaPlaylist *playlist) +{ + //异常情况:空指针 + if (playlist == nullptr) { + return; + } + m_playList = playlist; + connect(this,&MMediaPlayer::playFinish,m_playList,&MMediaPlaylist::palyFinish,Qt::UniqueConnection); + connect(this,&MMediaPlayer::playError,m_playList,&MMediaPlaylist::playError,Qt::UniqueConnection); + connect(m_playList,&MMediaPlaylist::autoPlay,this,&MMediaPlayer::autoPlay,Qt::UniqueConnection); + connect(m_playList,&MMediaPlaylist::stop,this,&MMediaPlayer::stop,Qt::UniqueConnection); + connect(this,&MMediaPlayer::playErrorMsg,m_playList,&MMediaPlaylist::playErrorMsg,Qt::UniqueConnection); +} + +void MMediaPlayer::truePlay(QString startTime) +{ + //异常情况:入参不合法 + if (startTime.isEmpty()) { + return; + } + //异常情况:播放列表空指针 + if (m_playList == nullptr) { + return; + } + QString filePath = m_playList->getPlayFileName(); + //异常情况:本地文件不存在 + if (!QFileInfo::exists(QUrl(filePath).toLocalFile())) { + Q_EMIT playErrorMsg(NotFound); + Q_EMIT playError(); + return; + } + + const QByteArray c_filename = filePath.toUtf8(); + //如果文件名和上次一样,且不是因为拖动进度条播放,说明上次是暂停 + if (c_filename == filenameBack && m_positionChangeed == false) { + if (filenameBack != "") { + //切换播放状态为播放 + pause(); + } + return; + } + //重置参数 + m_position = 0; + m_positionChangeed = false; + setProperty("start",startTime); + const char *args[] = {"loadfile",c_filename, NULL}; + mpv_command_async(m_mpvPlayer, 0, args); + + //如果不播放任何媒体,则切换状态为停止 + if (c_filename == "") { + changeState(StoppedState); + return; + } + //记录到上次播放变量中 + filenameBack = c_filename; + //切换播放状态为正在播放 + changeState(PlayingState); +} + +void MMediaPlayer::play() +{ + //从开头开始播放 + truePlay("0"); +} + +void MMediaPlayer::pause() +{ + // 获得mpv播放器的"暂停"状态 + QString pasued = getProperty("pause"); + + KyInfo() << "pauseState = " << pasued; + + // 根据"暂停"状态来选择暂停还是播放 + if(pasued == "no") { + KyInfo() << "set pause yes"; + + setProperty("pause", "yes"); + changeState(PausedState); + } else if(pasued == "yes") { + KyInfo() << "set pause no"; + + setProperty("pause", "no"); + changeState(PlayingState); + } +} + +void MMediaPlayer::stop() +{ + setProperty("pause", "no"); + const char *args[] = {"loadfile", "", NULL}; + mpv_command_async(m_mpvPlayer, 0, args); + changeState(StoppedState); +} + +MMediaPlayer::State MMediaPlayer::state() const +{ + return m_state; +} + +qint64 MMediaPlayer::position() const +{ + return m_position; +} + +void MMediaPlayer::setPosition(qint64 pos) +{ + double sec = double(pos)/1000; + m_positionChangeed = true; + //记录拖动进度条之前播放状态是否为暂停 + bool restartPlay = false; + if (m_state == PausedState) { + restartPlay = true; + } + //从拖动完成的位置开始播放 + truePlay(QString::number(sec)); + + if (restartPlay) { + //切换播放状态为播放 + pause(); + } +} + +void MMediaPlayer::setVolume(int vol) +{ +// setProperty("volume",QString::number(vol)); +// Q_EMIT signalVolume(vol); + // 设置音量,此音量和系统同步,不单独设置mpv音量 + QDBusMessage message = QDBusMessage::createSignal("/", "org.kylin.music", "sinkInputVolumeChanged"); + message << "kylin-music" << vol << false; + QDBusConnection::sessionBus().send(message); +} + +qint64 MMediaPlayer::duration() const +{ + return m_duration; +} + +void MMediaPlayer::setMedia(const MMediaContent &media) +{ + QUrl url =media.canonicalUrl(); + //防止内存泄漏 + if (m_tmpPlayList != nullptr) { + m_tmpPlayList->deleteLater(); + } + //创建新的播放列表并将歌曲录入 + m_tmpPlayList = new MMediaPlaylist(this); + m_tmpPlayList->addMedia(url); + setPlaylist(m_tmpPlayList); + //以暂停状态从头开始播放 + setProperty("pause", "yes"); + play(); +} + +bool MMediaPlayer::isAvailable() const +{ + return true; +} + + +void MMediaPlayer::onMpvEvents() +{ + //处理所有事件,直到事件队列为空 + while (m_mpvPlayer) + { + mpv_event *event = mpv_wait_event(m_mpvPlayer, 0); + if (event->event_id == MPV_EVENT_NONE) { + break; + } + handle_mpv_event(event); + } +} + +void MMediaPlayer::handle_mpv_event(mpv_event *event) +{ + switch (event->event_id) { + case MPV_EVENT_PROPERTY_CHANGE: { //属性改变事件 + mpv_event_property *prop = (mpv_event_property *)event->data; + //播放时,时间改变事件 + if (strcmp(prop->name, "time-pos") == 0) { + if (prop->format == MPV_FORMAT_DOUBLE) { + //将播放状态设置为播放中 + if (m_state == StoppedState) { + changeState(PlayingState); + } + // 获得播放时间 + double time = *(double *)prop->data; + //将单位换算为毫秒 + m_position = time * 1000; + Q_EMIT positionChanged(m_position); + } else if (prop->format == MPV_FORMAT_NONE) { + //当前时长距离总时长不超过500毫秒判断播放结束 + if ( m_duration!=0 && (m_duration - m_position < 500)) { + m_duration = 0; + m_position = 0; + //播放结束 + Q_EMIT playFinish(); + } else { + //切歌 + changeState(StoppedState); + } + } + } + } + break; + case MPV_EVENT_PLAYBACK_RESTART:{ //初始化完成事件 + //获取总时长 + m_duration = getProperty("duration").toDouble() *1000;//单位换算为毫秒 + Q_EMIT durationChanged(m_duration); + } + break; + case MPV_EVENT_IDLE:{ //播放器空闲事件,只有刚启动时、播放完成时、歌曲异常时会进入此分支 + QString playlist = getProperty("playlist"); + if (!playlist.contains(',')) { //排除播放完成 + if (playlist.length() > 2) { //排除刚启动 + //歌曲播放异常 + Q_EMIT playErrorMsg(Damage); + } + } + } + break; + //MPV会概率错误的发送此信号,导致没播放完也跳转到下一首 +// case MPV_EVENT_END_FILE:{ //播放结束事件 +// if (m_position != 0) { +// //重置参数 +// m_duration = 0; +// m_position = 0; +// //播放结束 +// Q_EMIT playFinish(); +// } +// } +// break; + default: ; + } +} + +// 回调函数 +static void wakeup(void *ctx) +{ + // 此回调可从任何mpv线程调用(但也可以从调用mpv API的线程递归地返回) + // 只是需要通知要唤醒的Qt GUI线程(以便它可以使用mpv_wait_event()),并尽快返回 + MMediaPlayer *mvpPlayer = (MMediaPlayer *)ctx; + Q_EMIT mvpPlayer->mpvEvents(); +} + +void MMediaPlayer::createMvpplayer() +{ + // 创建mpv实例 + setlocale(LC_NUMERIC,"C"); + m_mpvPlayer = mpv_create(); + if (m_mpvPlayer == nullptr) { + qDebug()<<"创建播放模块失败!"; + this->deleteLater(); + return; + } + //禁用视频流 + setProperty("vid", "no"); + //接收事件 + connect(this, &MMediaPlayer::mpvEvents, this, &MMediaPlayer::onMpvEvents, Qt::QueuedConnection); + mpv_set_wakeup_callback(m_mpvPlayer, wakeup, this); + //绑定事件 + mpv_observe_property(m_mpvPlayer, 0, "time-pos", MPV_FORMAT_DOUBLE); + // 判断mpv实例是否成功初始化 + if (mpv_initialize(m_mpvPlayer) < 0) { + qDebug()<<"初始化失败!"; + this->deleteLater(); + } +} + +void MMediaPlayer::setProperty(const QString &name, const QString &value) +{ + mpv_set_option_string(m_mpvPlayer, name.toLatin1().data(), value.toLatin1().data()); +} + +QString MMediaPlayer::getProperty(const QString &name) const +{ + return (QString)mpv_get_property_string(m_mpvPlayer, name.toLatin1().data()); +} + +void MMediaPlayer::changeState(MMediaPlayer::State stateNow) +{ + //待设置的循环模式和设置之前一致则不处理 + if (m_state == stateNow ) { + return; + } + m_state = stateNow; + Q_EMIT stateChanged(m_state); +} + +void MMediaPlayer::autoPlay(MMediaPlaylist::PlaybackMode playbackMode) +{ + //如果是单曲循环模式 + if (playbackMode == MMediaPlaylist::PlaybackMode::CurrentItemInLoop) { + //播放完毕自动切歌(借用播放点改变时间逻辑循环) + m_positionChangeed = true; + } + if(m_state!=StoppedState){ + truePlay("0"); + } +} diff --git a/coreplayer/mmediaplayer.h b/coreplayer/mmediaplayer.h new file mode 100644 index 0000000..6d404e4 --- /dev/null +++ b/coreplayer/mmediaplayer.h @@ -0,0 +1,80 @@ +/* +* Copyright (C) 2020, 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 3, or (at your option) +* any later version. +* +* This program is distributed in the hope that it will be useful, +* but WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +* GNU General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, see +#include +#include // MPV库头文件 + +#include "mmediaplaylist.h" + +class MMediaPlayer : public QObject +{ + Q_OBJECT +public: + // 停止播放 播放中 暂停中 + enum State{StoppedState=0,PlayingState,PausedState}; //播放状态枚举 + enum ErrorMsg{NotFound=-1,Damage=-2}; //播放状态枚举 + MMediaPlayer(QObject *parent = nullptr); + + void setPlaylist(MMediaPlaylist *playlist); //设置播放列表 + void pause(); //暂停或继续 + + State state() const; //获取状态 + qint64 position() const; //获取当前播放点 + void setPosition(qint64 pos); //设置播放起始点 + + bool isAvailable() const; //暂无实际功能 + void setVolume(int vol); //设置音量 + qint64 duration() const; //获取总时长 + void setMedia(const MMediaContent &media); //设置待播放媒体 + void play(); //播放 +public Q_SLOTS: + void stop(); //停止 + void onMpvEvents(); //接收mpv事件 + +private: + void truePlay(QString startTime = "0"); //实际的播放函数 + void handle_mpv_event(mpv_event *event); // 处理mpv事件 + void createMvpplayer(); // 创建mvpPlayer + void setProperty(const QString &name, const QString &value); // 设置mpv属性 + QString getProperty(const QString &name) const; // 获得mpv属性 + void changeState(State stateNow); //改变状态 + MMediaPlaylist * m_playList = nullptr; //私有播放列表 + MMediaPlaylist * m_tmpPlayList = nullptr; //私有临时播放列表 + mpv_handle *m_mpvPlayer = nullptr;//句柄 + State m_state = StoppedState;//播放状态 + QByteArray filenameBack = ""; //上次播放的媒体名 + bool m_positionChangeed = false; //播放进度被设置 + qint64 m_position = 0; //播放进度 + qint64 m_duration = 0; //总时长 +private Q_SLOTS: + void autoPlay(MMediaPlaylist::PlaybackMode playbackMode); //自动播放 +Q_SIGNALS: + void mpvEvents(); // 触发onMpvEvents()槽函数的信号 + void stateChanged(MMediaPlayer::State); //状态改变信号 + void durationChanged(qint64); //切换媒体时,总时长改变信号 + void positionChanged(qint64); //播放进度改变信号 + void playFinish(); //媒体播放完成信号 + void playError(); //媒体播放错误信号 + void playErrorMsg(ErrorMsg errorCode);//媒体播放错误信息信号 +// void signalVolume(int); +}; + +#endif // MMEDIAPLAYER_H diff --git a/coreplayer/mmediaplaylist.cpp b/coreplayer/mmediaplaylist.cpp new file mode 100644 index 0000000..1d6365c --- /dev/null +++ b/coreplayer/mmediaplaylist.cpp @@ -0,0 +1,242 @@ +/* +* Copyright (C) 2022 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 3, or (at your option) +* any later version. +* +* This program is distributed in the hope that it will be useful, +* but WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +* GNU General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, see = m_playerList.length()) { + m_index = m_playerList.length(); + return m_playerList.last().toString(); + } + return m_playerList.at(m_index).toString(); +} + +int MMediaPlaylist::currentIndex() const +{ + return m_index; +} + +bool MMediaPlaylist::addMedia(const QUrl &items) +{ + m_playerList.append(items); + return true; +} + +void MMediaPlaylist::next() +{ + //异常情况:播放列表为空 + if (m_playerList.isEmpty()) { + return; + } + //异常情况:无当前播放媒体 + if (m_index < 0) { + return; + } + switch (m_playbackMode) { + case Random: + m_index=randomIndex(); + break; + case Sequential: + m_index++; + if (m_index >= m_playerList.length()) { + m_index = m_playerList.length() - 1; + } + break; + default: + m_index++; + if (m_index >= m_playerList.length()) { + m_index = 0; + } + break; + } + Q_EMIT currentIndexChanged(m_index); + Q_EMIT stop(); +} + +void MMediaPlaylist::previous() +{ + //异常情况:播放列表为空 + if (m_playerList.isEmpty()) { + return; + } + + switch (m_playbackMode) { + case Random: + m_index=randomIndex(); + break; + case Sequential: + m_index--; + if (m_index < 0) { + m_index = 0; + } + break; + default: + m_index--; + if (m_index < 0) { + m_index = m_playerList.length() - 1; + } + break; + } + Q_EMIT currentIndexChanged(m_index); + Q_EMIT stop(); +} + +void MMediaPlaylist::setCurrentIndex(int index) +{ + //待设置的数量和设置之前一致则不处理,默认播放第一首除外 +// if (index == m_index && index != 0) { +// return; +// } + //异常情况:要设置的媒体位置超过列表总长度 + if (index >= m_playerList.length()) { + qDebug()<<"指定位置超过列表元素数量"; + return; + } + //统一所有非正常情况 + if (index < 0) { + index = -1; + } + m_index = index; + Q_EMIT currentIndexChanged(m_index); +} + +void MMediaPlaylist::setPlaybackMode(MMediaPlaylist::PlaybackMode mode) +{ + //待设置的循环模式和设置之前一致则不处理 + if (mode == m_playbackMode) { + return; + } + m_playbackMode = mode; + Q_EMIT playbackModeChanged(mode); +} + +int MMediaPlaylist::mediaCount() const +{ + return m_playerList.length(); +} + +MMediaContent MMediaPlaylist::media(int index) const +{ + //异常情况:要设置的媒体位置在列表中不存在 + if (index >= m_playerList.length() || index < 0) { + return MMediaContent(QUrl("")); + } + return MMediaContent(m_playerList.at(index)); +} + +bool MMediaPlaylist::clear() +{ + m_playerList.clear(); + return true; +} + +bool MMediaPlaylist::removeMedia(int pos) +{ + //异常情况:要移出的媒体位置在列表中不存在 + if (pos >= m_playerList.length() || pos < 0) { + return false; + } + m_playerList.removeAt(pos); + return true; +} + +void MMediaPlaylist::playError() +{ + //当前仅在存在播放列表中的媒体本地文件被删除时触发 + //播放异常时,轮询所有列表中的媒体文件是否存在 + for (auto url : m_playerList) { + //如果发现列表中有媒体文件没被删除 + if (QFileInfo::exists(url.toLocalFile())) { + //如果是单曲循环则切换下一首 + if (m_playbackMode == CurrentItemInLoop) { + next(); + } + //按播放完成处理 + palyFinish(); + return; + } + } + //列表中所有媒体的本地文件全部被删除了 + Q_EMIT currentIndexChanged(-1); +} + +void MMediaPlaylist::playErrorMsg(int Damage) +{ + if (Damage == -2) { + //如果是列表循环则切换下一首 + if (m_playbackMode == Loop) { + next(); + } else if(m_playbackMode == Random) { + m_index = randomIndex(); + Q_EMIT currentIndexChanged(m_index); + Q_EMIT stop(); + } + //不知为什么要加自动播放信号 +// Q_EMIT autoPlay(m_playbackMode); + } +} + +void MMediaPlaylist::palyFinish() +{ + //如果没有待播放的媒体则不处理 + if (m_index < 0) { + return; + } + if (m_playbackMode == CurrentItemOnce) { + return; + } + //如果循环模式不是单曲循环则切换下一首 + if (m_playbackMode != CurrentItemInLoop) { + next(); + Q_EMIT currentIndexChanged(m_index); + } + Q_EMIT autoPlay(m_playbackMode); +} + +MMediaPlaylist::PlaybackMode MMediaPlaylist::playbackMode() const +{ + return m_playbackMode; +} + +int MMediaPlaylist::randomIndex() +{ + qsrand(QDateTime::currentDateTime().toMSecsSinceEpoch()); + return qrand()%(m_playerList.length()); +} + + +MMediaContent::MMediaContent(QUrl url) +{ + m_url = url; +} + +QUrl MMediaContent::canonicalUrl() const +{ + return m_url; +} diff --git a/coreplayer/mmediaplaylist.h b/coreplayer/mmediaplaylist.h new file mode 100644 index 0000000..a7232f0 --- /dev/null +++ b/coreplayer/mmediaplaylist.h @@ -0,0 +1,74 @@ +/* +* Copyright (C) 2020, 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 3, or (at your option) +* any later version. +* +* This program is distributed in the hope that it will be useful, +* but WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +* GNU General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, see +#include +#include +#include +#include + +class MMediaContent +{ + +public: + MMediaContent(QUrl url); + QUrl canonicalUrl() const; //获取Qurl内容 +private: + QUrl m_url; //媒体url路径 +}; + + +class MMediaPlaylist : public QObject +{ + Q_OBJECT +public: + // 只播放一次 单曲循环 列表播放 列表循环 随机播放 + enum PlaybackMode { CurrentItemOnce=0, CurrentItemInLoop, Sequential, Loop, Random }; //播放循环模式枚举 + MMediaPlaylist(QObject *parent = nullptr); + + QString getPlayFileName(); //获取待播放媒体的文件名 + int currentIndex() const; //获取当前播放的歌曲在播放列表中的位置 + bool addMedia(const QUrl &items); //添加媒体 + void next(); //切换下一首 + void previous(); //切换上一首 + void setCurrentIndex(int index); //设置选中播放列表中的位置 + PlaybackMode playbackMode() const; //获取播放循环模式 + void setPlaybackMode(PlaybackMode mode); //设置循环播放模式 + int mediaCount() const; //列表中总媒体的数量 + MMediaContent media(int index) const; //获取列表中特定位置的媒体 + bool clear(); //清空列表 + bool removeMedia(int pos); //移出特定位置的歌曲 +public Q_SLOTS: + void palyFinish(); //播放完成槽函数 + void playError(); //播放异常槽函数 + void playErrorMsg(int Damage); //播放错误异常 +private: + int randomIndex(); //生成随机数 + QList m_playerList; //实际的播放队列 + int m_index = 0; //当前播放的歌曲位置 + PlaybackMode m_playbackMode = Loop; //当前列表的循环模式 +Q_SIGNALS: + void currentIndexChanged(int); //媒体切换信号 + void playbackModeChanged(MMediaPlaylist::PlaybackMode mode); //播放循环模式切换信号 + void autoPlay(MMediaPlaylist::PlaybackMode playbackMode); //自动播放下一首信号 + void stop(); //停止播放信号 +}; + +#endif // MMediaPlaylist_H diff --git a/coreplayer/playcontroller.cpp b/coreplayer/playcontroller.cpp new file mode 100644 index 0000000..7e72c12 --- /dev/null +++ b/coreplayer/playcontroller.cpp @@ -0,0 +1,540 @@ +/* +* Copyright (C) 2020, 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 3, or (at your option) +* any later version. +* +* This program is distributed in the hope that it will be useful, +* but WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +* GNU General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, see +#include +#include "playcontroller.h" + +bool playController::play(QString playlist, int index) +{ + if (playlist.compare(m_curList)==0) + { + stop(); + setSongIndex(index); + play(); + return true; + } + return false; +} + +bool playController::play() +{ + if (m_player == nullptr) { + return false; + } + if (m_player->isAvailable() == false) { //存疑 + return false; + } + if (m_player->state() == MMediaPlayer::State::PlayingState) { + m_player->pause(); + } else { + m_player->play(); + Q_EMIT curIndexChanged(m_playlist->currentIndex()); + } + return true; +} +bool playController::pause() +{ + if (m_player == nullptr) { + return false; + } + m_player->pause(); + + return true; +} +bool playController::stop() +{ + if (m_player == nullptr) { + return false; + } + m_player->stop(); + + return true; +} +void playController::setSongIndex(int index) +{ + if (m_playlist == nullptr) { + qDebug() << "m_playlist is null"; + return; + } + if(index < 0) + { + return; + } + if (index > m_playlist->mediaCount()) { + return; + } + m_playlist->setCurrentIndex(index); + Q_EMIT curIndexChanged(index); +} +int playController::songIndex() +{ + if (m_playlist == nullptr) { + qDebug() << "m_playlist is null"; + return -1; + } + + return m_playlist->currentIndex(); +} + +int playController::playmode() +{ + if (m_playlist == nullptr) { + qDebug() << "m_playlist is null"; + return -1; + } + + return static_cast(m_playlist->playbackMode()); +} +void playController::setPlaymode(int mode) +{ + if (m_playlist == nullptr || m_player == nullptr) { + return; + } + if (m_playlist == nullptr) { + qDebug() << "m_playlist is null"; + return; + } + m_playlist->setPlaybackMode(static_cast(mode)); +} + +void playController::curPlaylist() +{ + // Print Playlist information + if (m_playlist == nullptr) { + return; + } + + for (auto i = 0; i < m_playlist->mediaCount(); i++) { + MMediaContent content = m_playlist->media(i); +// qDebug() << " " +// << "media[" << i << "] is:" << content.canonicalUrl(); + } +} +void playController::setCurPlaylist(QString name, QStringList songPaths) +{ + if (m_curList.compare(name)==0) + { +// qDebug() << "setCurPlaylist m_curList.compare(name)==0" << m_curList << name; +// return ; + } + if (m_playlist == nullptr || m_player == nullptr) { + return; + } + disconnect(m_playlist,&MMediaPlaylist::currentIndexChanged,this,&playController::slotIndexChange); + m_curList = name; + m_playlist->clear(); + + for (auto path : songPaths) { + m_playlist->addMedia(QUrl::fromLocalFile(path)); + } + m_player->stop(); + m_player->setPlaylist(nullptr); + m_player->setPlaylist(m_playlist); + + +// m_playlist->setCurrentIndex(-1); + connect(m_playlist,&MMediaPlaylist::currentIndexChanged,this,&playController::slotIndexChange); + isInitialed = true; +} +void playController::addSongToCurList(QString name, QString songPath) +{ + if (name.compare(m_curList) != 0) { + qDebug() << __FUNCTION__ << " the playlist to add is not Current playlist."; + return; + } + if (m_playlist != nullptr) { + m_playlist->addMedia(QUrl::fromLocalFile(songPath)); + } +} +void playController::removeSongFromCurList(QString name, int index) +{ + if (name.compare(m_curList) != 0) + { +// qDebug() << __FUNCTION__ << " the playlist to add is not Current playlist."; + return; + } + if (m_playlist != nullptr) { +// m_playlist->removeMedia(index); + //判断删除后 播放歌曲的index 当前只判断了删除正在播放的歌曲 还没做删除正在播放之前的歌曲和之后的歌曲 + int count = m_playlist->mediaCount(); + + int state = m_player->state(); + + if(m_curIndex == index) + { + stop(); + if(m_curIndex == count - 1) + { + m_curIndex = 0; + m_playlist->removeMedia(index); + if(m_playlist->mediaCount() == 0) + { + m_curIndex = -1; + } + setSongIndex(m_curIndex); + } + else + { + m_playlist->removeMedia(index); + if(m_playlist->mediaCount() == 0) + { + m_curIndex = -1; + } +// setSongIndex(m_curIndex); + setSongIndex(m_curIndex); + } + //删除当前播放歌曲不更改播放状态 2021.09.10 + if (state == MMediaPlayer::State::PlayingState) { + m_player->play(); + } else { //设置进度条归 0 + Q_EMIT signalSetValue(); + m_player->pause(); + } + } + else if(m_curIndex > index) + { +// int position = 0; +// if(m_player->state()==MMediaPlayer::PlayingState) +// { +// position = m_player->position(); +// } +// m_player->stop(); + m_playlist->removeMedia(index); + m_curIndex = m_curIndex - 1; + //只负责高亮歌曲 + setSongIndex(m_curIndex); +// m_player->setPosition(position); + //歌曲删除重新播放(跨函数调用) +// PlaySongArea::getInstance().hSlider->setValue(position); + //MPV setPosition已经设置播放,不用再次设置播放 +// m_player->play(); + } + else if(m_curIndex < index) + { + m_playlist->removeMedia(index); + } + + Q_EMIT curIndexChanged(m_curIndex); + Q_EMIT currentIndexAndCurrentList(m_curIndex,m_curList); + slotIndexChange(m_curIndex); + } +} + + +void playController::removeSongFromLocalList(QString name, int index) +{ + if (name.compare(m_curList) != 0) + { + qDebug() << __FUNCTION__ << " the playlist to add is not Current playlist."; + return; + } + if (m_playlist != nullptr) + { + int count = m_playlist->mediaCount(); + + int state = m_player->state(); + + if(m_curIndex == index) + { + stop(); + if(m_curIndex == count - 1) + { + m_curIndex = 0; + m_playlist->removeMedia(index); + if(m_playlist->mediaCount() == 0) + { + m_curIndex = -1; + } + setSongIndex(m_curIndex); + } + else + { + m_playlist->removeMedia(index); + if(m_playlist->mediaCount() == 0) + { + m_curIndex = -1; + } + setSongIndex(m_curIndex); + } + //删除当前播放歌曲不更改播放状态 2021.09.10 + if (state == MMediaPlayer::State::PlayingState) { + m_player->play(); + } else { //设置进度条归 0 + Q_EMIT signalSetValue(); + m_player->pause(); + } + } + else if(m_curIndex > index) + { + + m_playlist->removeMedia(index); + m_curIndex = m_curIndex - 1; + setSongIndex(m_curIndex); + } + else if(m_curIndex < index) + { + m_playlist->removeMedia(index); + } + + Q_EMIT curIndexChanged(m_curIndex); + Q_EMIT currentIndexAndCurrentList(m_curIndex,m_curList); + slotIndexChange(m_curIndex); + } +} + +playController::PlayState playController::getState() +{ + if(m_player->state() == MMediaPlayer::State::PlayingState) + return PlayState::PLAY_STATE; + else if(m_player->state() == MMediaPlayer::State::PausedState) + return PlayState::PAUSED_STATE; + else if(m_player->state() == MMediaPlayer::State::StoppedState) + return PlayState::STOP_STATE; + else + return PlayState::STOP_STATE; +} + +playController::playController() + : m_curList(""),m_curIndex(-1) +{ + m_player = new MMediaPlayer(this); + if (m_player == nullptr) { + qDebug() << "failed to create player "; + return; + } + m_playlist = new MMediaPlaylist(m_player); + if (m_playlist == nullptr) { + qDebug() << "failed to create laylist"; + return; + } + m_player->setPlaylist(m_playlist); + init(); + //绑定铃声音量 +// initDbus(); + m_playlist->setPlaybackMode(MMediaPlaylist::Loop); +// m_playlist->setCurrentIndex(-1); + connect(m_playlist,&MMediaPlaylist::currentIndexChanged,this,&playController::slotIndexChange); + connect(m_player,&MMediaPlayer::stateChanged,this,&playController::slotStateChanged); + connect(m_playlist,&MMediaPlaylist::playbackModeChanged,this,&playController::slotPlayModeChange); +// connect(m_player,&MMediaPlayer::playErrorMsg,this,&playController::slotPlayErrorMsg); +} + + +void playController::init() +{ + m_volume=100; + m_player->setVolume(100); + m_curList = ALLMUSIC; + m_mode = Loop; +} + +void playController::initDbus() +{ + QDBusConnection::sessionBus().connect(QString(), "/", "org.ukui.media", "sinkVolumeChanged", this, SLOT(slotVolumeChange(QString,int,bool))); +} + +int playController::getVolume() +{ + return m_volume; +} + +void playController::setVolume(int volume) +{ + if(volume > 100) { + volume = 100; + } + if(volume < 0) { + volume = 0; + } + + m_volume = volume; + if (!m_receive) { + m_player->setVolume(volume); + } else { + m_receive = false; + } +} + +void playController::onCurrentIndexChanged() +{ + qDebug() << "onCurrentIndexChanged"; +} +void playController::onPositionChanged(double value) +{ + qDebug() << "onPositionChanged"; + if (m_player == nullptr) { + return; + } + m_player->setPosition(m_player->duration() * value); +} +void playController::onNextSong() +{ + if (m_playlist == nullptr || m_player == nullptr) { + qDebug() << "m_playlist or m_player is nullptr"; + return; + } + m_playlist->next(); + m_player->play(); + curPlaylist(); + auto index = m_playlist->currentIndex(); + Q_EMIT curIndexChanged(index); +} +void playController::onPreviousSong() +{ + if (m_playlist == nullptr || m_player == nullptr) { + qDebug() << "m_playlist or m_player is nullptr"; + return; + } + m_playlist->previous(); + m_player->play(); + auto index = m_playlist->currentIndex(); + Q_EMIT curIndexChanged(index); +} + +void playController::setCurList(QString renameList) +{ + m_curList = renameList; +} +void playController::onError() +{ + qDebug() << "onError"; +} +void playController::onMediaStatusChanged() +{ + qDebug() << "onMediaStatusChanged"; +} +playController::~playController(/* args */) +{ + if (m_playlist != nullptr) { + m_playlist->deleteLater(); + } + if (m_player != nullptr) { + m_player->deleteLater(); + } +} + +void playController::playSingleSong(QString Path, int playMode) +{ + QStringList filePaths; + filePaths<(playController::PlayMode::CurrentItemInLoop)); + else if(mode == MMediaPlaylist::PlaybackMode::Sequential) + Q_EMIT signalPlayMode(static_cast(playController::PlayMode::Sequential)); + else if(mode == MMediaPlaylist::PlaybackMode::Loop) + Q_EMIT signalPlayMode(static_cast(playController::PlayMode::Loop)); + else if(mode == MMediaPlaylist::PlaybackMode::Random) + Q_EMIT signalPlayMode(static_cast(playController::PlayMode::Random)); +} + +void playController::slotIndexChange(int index) +{ + if(index == -1) + { + Q_EMIT signalNotPlaying(); + //当index == -1时,会调用positionChanged导致时长显示错误 + Q_EMIT singalChangePath(""); + Q_EMIT currentIndexAndCurrentList(-1,m_curList); + return; + } + m_curIndex = index; + MMediaContent content = m_playlist->media(index); + QString path = content.canonicalUrl().toLocalFile(); + QFileInfo file(path.remove("file://")); + if(file.exists()) + { + x = 0; + Q_EMIT currentIndexAndCurrentList(index,m_curList); + Q_EMIT singalChangePath(path); + } + else + { + x++; + if(x > m_playlist->mediaCount()) + { + x = 0; + return; + } + } +} + +void playController::setPosition(int position) +{ + if (qAbs(m_player->position() - position) > 99) + m_player->setPosition(position); +} + +void playController::setPlayListName(QString playListName) +{ + m_curList=playListName; +} + +QString playController::getPlayListName() +{ + return m_curList; +} + +QString playController::getPath() +{ + return m_path; +} + +void playController::setMode(playController::PlayMode mode) +{ + m_mode = mode; +} + +playController::PlayMode playController::mode() const +{ + return m_mode; +} + +void playController::slotVolumeChange(QString app, int value, bool mute) +{ + if (app == "kylin-music") { + if (value < 0) { + return; + } + + if (value != m_volume) { + m_receive = true; + Q_EMIT signalVolume(value); + } + + //mute = true静音 mute = false取消静音 + Q_EMIT signalMute(mute); + } +} diff --git a/coreplayer/playcontroller.h b/coreplayer/playcontroller.h new file mode 100644 index 0000000..5f85a3a --- /dev/null +++ b/coreplayer/playcontroller.h @@ -0,0 +1,167 @@ +/* +* Copyright (C) 2020, 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 3, or (at your option) +* any later version. +* +* This program is distributed in the hope that it will be useful, +* but WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +* GNU General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, see +#include +#include "mmediaplayer.h" +#include "mmediaplaylist.h" + + +#define KYLINMUSIC "org.kylin-music-data.settings" +const QString ALLMUSIC = "LocalMusic"; //本地总表 +class playController : public QObject { + Q_OBJECT +public: + enum PlayState { + STOP_STATE = 0, + PLAY_STATE = 1, + PAUSED_STATE = 2 + }; + + enum PlayMode { + CurrentItemInLoop = 1, + Sequential = 2, + Loop = 3, + Random = 4, + }; +public: + static playController& getInstance() + { + static playController instance; + return instance; + } + +private: + playController(/* args */); + playController(playController const&); + playController& operator=(playController const&); + ~playController(); + void init(); + void initDbus(); +public: + //新增接口 fyf + void playSingleSong(QString Path, int playMode); + + bool play(QString playlist, int index); + + bool play(); + bool pause(); + bool stop(); + + int volume(); + + void setPlayPosition(int pos); + int playPosition(); + + void setSongIndex(int index); + int songIndex(); + + int playmode(); + void setPlaymode(int mode); + + void curPlaylist(); + void setCurPlaylist(QString name, QStringList songPaths); + void addSongToCurList(QString name, QString songPath); + //从歌单删除 + void removeSongFromCurList(QString name, int index); + //从本地删除 + void removeSongFromLocalList(QString name, int index); +// void removeMedia(QString name, int index); + PlayState getState(); + PlayMode mode() const; + MMediaPlayer* getPlayer() + { + return m_player; + } + MMediaPlaylist* getPlaylist() + { + return m_playlist; + } + + void setPosition(int position); + //获取音量 + int getVolume(); + //设置音量 + void setVolume(int volume); + //获取歌单名 + QString getPlayListName(); + //获取歌曲路径 + QString getPath(); +Q_SIGNALS: + void curPositionChanged(qint64); + void curDurationChanged(qint64); + void curIndexChanged(int index); + void playerError(int error, QString errMsg); + void playerStateChange(playController::PlayState newState); + void singalChangePath(QString path); + void currentIndexAndCurrentList(int index,QString listname); + void signalPlayMode(int playModel); + + void signalNotPlaying(); +// void playErrorMsg(int errorCode);//媒体播放错误信息信号 + + //进度条归 0 + void signalSetValue(); + //系统音乐音量改变 + void signalVolume(int value); + //系统音乐音量静音 + void signalMute(bool mute); +public Q_SLOTS: + void onCurrentIndexChanged(); + void onPositionChanged(double value); + void onNextSong(); + void onPreviousSong(); + void setCurList(QString renameList); + void setMode(playController::PlayMode mode); + void setPlayListName(QString playListName); +private Q_SLOTS: + void onError(); + void onMediaStatusChanged(); + //状态改变 + void slotStateChanged(MMediaPlayer::State newState); + //播放模式改变 + void slotPlayModeChange(MMediaPlaylist::PlaybackMode mode); + //获得当前播放的index + void slotIndexChange(int index); + //媒体播放错误信息槽函数 +// void slotPlayErrorMsg(MMediaPlayer::ErrorMsg msg); + //接收系统应用音量变化 + void slotVolumeChange(QString app, int value, bool mute); +private: + //当前播放列表名 + QString m_curList; + //当前播放的索引 + int m_curIndex; + MMediaPlayer* m_player = nullptr; + MMediaPlaylist* m_playlist = nullptr; + bool isInitialed = false; + //在列表里歌曲(判断本地歌曲是否存在)没有播放的情况下,当前函数掉了多少次,要是歌曲在播放(找到本地路径存在,x重新计数 + int x = 0; + int m_volume = 100; + QGSettings *playSetting = nullptr; + QString m_path; + PlayMode m_mode = playController::Loop; +// int m_msg = 0; + //标记系统音乐接收状态 + bool m_receive = false; +}; + + +#endif // PLAYCONTROLLER_H diff --git a/countdown.ui b/countdown.ui new file mode 100644 index 0000000..e8631e8 --- /dev/null +++ b/countdown.ui @@ -0,0 +1,172 @@ + + + countdown + + + + 0 + 0 + 1035 + 682 + + + + countdown + + + + + 20 + 100 + 80 + 26 + + + + 开始 + + + + + + 20 + 220 + 80 + 26 + + + + 铃声 + + + + + + 20 + 140 + 80 + 26 + + + + 暂停 + + + + + + 20 + 180 + 80 + 26 + + + + 时间选择 + + + + + + 637 + 470 + 80 + 80 + + + + color: rgb(255, 255, 255); +background-color: rgb(255, 255, 255); + + + + + + + + + 550 + 210 + 241 + 231 + + + + color: rgb(255, 255, 255); +font: 24pt "Sans Serif"; +background-color: rgb(14, 19, 22); + + + + + + 630 + 170 + 81 + 20 + + + + color: rgb(255, 255, 255); +color: rgb(148, 148, 148); +font: 12pt "Sans Serif"; + + + 00:00:00 + + + + + + 570 + 110 + 191 + 51 + + + + color: rgb(255, 255, 255); +text-decoration: underline; +font: 9pt "Sans Serif"; +font: 36pt "Sans Serif"; + + + 00:00:00 + + + + + + 760 + 580 + 80 + 26 + + + + color: rgb(255, 255, 255); + + + 复位 + + + + + + 510 + 580 + 80 + 26 + + + + color: rgb(255, 255, 255); + + + 计次 + + + + + + diff --git a/countdownAnimation.cpp b/countdownAnimation.cpp new file mode 100644 index 0000000..d800859 --- /dev/null +++ b/countdownAnimation.cpp @@ -0,0 +1,111 @@ +/* +* 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 3, or (at your option) +* any later version. +* +* This program is distributed in the hope that it will be useful, +* but WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +* GNU General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, see +#include +#include +#include +#include + + +Countdown_Animation::Countdown_Animation(QWidget *parent , int value) : + QWidget(parent), + value_max(value) +{ + setupUi(this); + //渐变色 + QGradientStops gradientPoints; + gradientPoints << QGradientStop(0.5, QColor(255, 160, 90)) << QGradientStop(1, QColor(180, 30, 10)); //渐变起止颜色设置 + // Gradient start and stop color settings + countdownRunRoundBar->setDataColors(gradientPoints); + //设置动态光圈转动频率 + connectToSlider(countdownRunRoundBar); +} + +Countdown_Animation::~Countdown_Animation() +{ + delete countdownRunRoundBar; + qDebug()<<"-------Countdown_Animation---------"; +} +//设置动态光圈转动频率 +// Set dynamic diaphragm rotation frequency +void Countdown_Animation::connectToSlider(QRoundProgressBar *bar) +{ + + bar->setRange(0, 3600); + bar->setValue(3600); + +// timer->start(); +} + +/** + * @brief 设置UI + * @param TestWidget 窗体 + * @param + * + * @return 返回说明 + */ +void Countdown_Animation::setupUi(QWidget *TestWidget) +{ + if (TestWidget->objectName().isEmpty()) + TestWidget->setObjectName(QString::fromUtf8("TestWidget")); + TestWidget->resize(454, 461); + //时间滚轮 + countdownRunRoundBar = new QRoundProgressBar(TestWidget); + countdownRunRoundBar->setObjectName(QString::fromUtf8("RoundBar3")); + countdownRunRoundBar->setGeometry(QRect(-12, -4, 454, 461)); + //管理着控件或窗体的所有颜色信息 +// QPalette palette; +// QBrush brush(QColor(255, 255, 255, 0)); +// brush.setStyle(Qt::SolidPattern); +// palette.setBrush(QPalette::Active, QPalette::Base, brush); +// //红色 +// QBrush brushRed(QColor(170, 0, 0, 255)); +// brushRed.setStyle(Qt::SolidPattern); +// //活跃状态(获得焦点) 高亮背景色 +// palette.setBrush(QPalette::Active, QPalette::Highlight, brushRed); +// palette.setBrush(QPalette::Inactive, QPalette::Base, brush); +// //不活跃状态(未获得焦点) +// palette.setBrush(QPalette::Inactive, QPalette::Highlight, brushRed); +// //白色 +// QBrush brushWhite(QColor(244, 244, 244, 255)); +// brushWhite.setStyle(Qt::SolidPattern); +// palette.setBrush(QPalette::Disabled, QPalette::Base, brushWhite); +// //深蓝 +// QBrush brushBlue(QColor(50, 100, 150, 255)); +// brushBlue.setStyle(Qt::SolidPattern); +// //不可用状态 +// palette.setBrush(QPalette::Disabled, QPalette::Highlight, brushBlue); +// countdownRunRoundBar->setPalette(palette); + + retranslateUi(TestWidget); + + QMetaObject::connectSlotsByName(TestWidget); +} +/** + * @brief 翻译窗体名称 + * @param + * @param + * + * @return 返回说明 + */ +void Countdown_Animation::retranslateUi(QWidget *TestWidget) +{ + //翻译标题是个"" + TestWidget->setWindowTitle(QApplication::translate("TestWidget", "TestWidget", nullptr)); +} diff --git a/countdownAnimation.h b/countdownAnimation.h new file mode 100644 index 0000000..b053744 --- /dev/null +++ b/countdownAnimation.h @@ -0,0 +1,57 @@ +/* +* 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 3, or (at your option) +* any later version. +* +* This program is distributed in the hope that it will be useful, +* but WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +* GNU General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, see +#include + +namespace Ui { +class Countdown_Animation; +} + +class Countdown_Animation : public QWidget +{ + Q_OBJECT +public: + + Countdown_Animation( QWidget *parent = 0, int value_max = 0); + ~Countdown_Animation(); + + QRoundProgressBar *countdownRunRoundBar; + + void setupUi(QWidget *TestWidget); + + void retranslateUi(QWidget *TestWidget); + + + int value_max=100; + +private: + //设置动态光圈转动频率 + // Set dynamic diaphragm rotation frequency + void connectToSlider(class QRoundProgressBar* bar); + + void con(); + + + + Ui::Countdown_Animation *ui; +}; + +#endif // TESTWIDGET_H diff --git a/dbusdeleteclockbyidadaptor.cpp b/dbusdeleteclockbyidadaptor.cpp new file mode 100644 index 0000000..cc5dd68 --- /dev/null +++ b/dbusdeleteclockbyidadaptor.cpp @@ -0,0 +1,29 @@ +/* +* Copyright (C) 2020, 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 3, or (at your option) +* any later version. +* +* This program is distributed in the hope that it will be useful, +* but WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +* GNU General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, see deleteClockByIdJosn(param); +} diff --git a/dbusdeleteclockbyidadaptor.h b/dbusdeleteclockbyidadaptor.h new file mode 100644 index 0000000..af96e02 --- /dev/null +++ b/dbusdeleteclockbyidadaptor.h @@ -0,0 +1,39 @@ +/* +* Copyright (C) 2020, 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 3, or (at your option) +* any later version. +* +* This program is distributed in the hope that it will be useful, +* but WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +* GNU General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, see +#include +#include "clock.h" +class DbusDeleteClockByIdAdaptor : public QDBusAbstractAdaptor +{ + Q_OBJECT + //声明它正在导出哪个接口 + Q_CLASSINFO("D-Bus Interface", CLOCK_DBUS_SERVICE_NAME) +public: + explicit DbusDeleteClockByIdAdaptor(QObject *parent = nullptr,Clock * currentClock = nullptr); + +signals: +public slots: + QString deleteClockByIdRpc(QString param); +private: + Clock * m_clock; +}; + +#endif // DBUSDELETECLOCKBYIDADAPTOR_H diff --git a/dbusselectclockbyidadaptor.cpp b/dbusselectclockbyidadaptor.cpp new file mode 100644 index 0000000..73524d4 --- /dev/null +++ b/dbusselectclockbyidadaptor.cpp @@ -0,0 +1,29 @@ +/* +* Copyright (C) 2020, 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 3, or (at your option) +* any later version. +* +* This program is distributed in the hope that it will be useful, +* but WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +* GNU General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, see selectClockByIdJosn(param); +} diff --git a/dbusselectclockbyidadaptor.h b/dbusselectclockbyidadaptor.h new file mode 100644 index 0000000..8ed5603 --- /dev/null +++ b/dbusselectclockbyidadaptor.h @@ -0,0 +1,39 @@ +/* +* Copyright (C) 2020, 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 3, or (at your option) +* any later version. +* +* This program is distributed in the hope that it will be useful, +* but WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +* GNU General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, see +#include +#include "clock.h" +class DbusSelectClockByIdAdaptor : public QDBusAbstractAdaptor +{ + Q_OBJECT + //声明它正在导出哪个接口 + Q_CLASSINFO("D-Bus Interface", CLOCK_DBUS_SERVICE_NAME) +public: + explicit DbusSelectClockByIdAdaptor(QObject *parent = nullptr,Clock * currentClock = nullptr); + +signals: +public slots: + QString selectClockByIdRpc(QString param); +private: + Clock * m_clock; +}; + +#endif // DBUSSELECTCLOCKBYIDADAPTOR_H diff --git a/dbusupdateclockadaptor.cpp b/dbusupdateclockadaptor.cpp new file mode 100644 index 0000000..b7bce47 --- /dev/null +++ b/dbusupdateclockadaptor.cpp @@ -0,0 +1,29 @@ +/* +* Copyright (C) 2020, 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 3, or (at your option) +* any later version. +* +* This program is distributed in the hope that it will be useful, +* but WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +* GNU General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, see updateClockByIdJosn(param); +} diff --git a/dbusupdateclockadaptor.h b/dbusupdateclockadaptor.h new file mode 100644 index 0000000..227a34f --- /dev/null +++ b/dbusupdateclockadaptor.h @@ -0,0 +1,39 @@ +/* +* Copyright (C) 2020, 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 3, or (at your option) +* any later version. +* +* This program is distributed in the hope that it will be useful, +* but WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +* GNU General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, see +#include +#include "clock.h" +class DbusUpdateClockAdaptor : public QDBusAbstractAdaptor +{ + Q_OBJECT + //声明它正在导出哪个接口 + Q_CLASSINFO("D-Bus Interface", CLOCK_DBUS_SERVICE_NAME) +public: + explicit DbusUpdateClockAdaptor(QObject *parent = nullptr,Clock * currentClock = nullptr); + +signals: +public slots: + QString updateClockByIdRpc(QString param); +private: + Clock * m_clock; +}; + +#endif // DBUSUPDATECLOCKADAPTOR_H diff --git a/debug.h b/debug.h new file mode 100644 index 0000000..1abde60 --- /dev/null +++ b/debug.h @@ -0,0 +1,68 @@ +/* +* 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 3, or (at your option) +* any later version. +* +* This program is distributed in the hope that it will be useful, +* but WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +* GNU General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, see +#include +#include +#include +#include + +//输出消息 +// Output message +static void outputMessage(QtMsgType type, const QMessageLogContext &context, const QString &msg) +{ + static QMutex mutex; + mutex.lock(); + + QString text; + switch(type) + { + case QtDebugMsg: + text = QString("Debug:"); + break; + + case QtWarningMsg: + text = QString("Warning:"); + break; + + case QtCriticalMsg: + text = QString("Critical:"); + break; + + case QtFatalMsg: + text = QString("Fatal:"); + } + + QString contextInfo = QString("File:(%1) Line:(%2)").arg(QString(context.file)).arg(context.line); + QString cDataTime = QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss ddd"); + QString cDate = QString("(%1)").arg(cDataTime); + QString message = QString("%1 %2 %3 %4").arg(text).arg(contextInfo).arg(msg).arg(cDate); + + QFile file("log.txt"); + file.open(QIODevice::WriteOnly | QIODevice::Append); + QTextStream textStream(&file); + textStream << message << "\r\n"; + file.flush(); + file.close(); + + mutex.unlock(); +} + +#endif // DEBUG_H diff --git a/deleteMsg.cpp b/deleteMsg.cpp new file mode 100644 index 0000000..d0eb83b --- /dev/null +++ b/deleteMsg.cpp @@ -0,0 +1,128 @@ +/* +* 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 3, or (at your option) +* any later version. +* +* This program is distributed in the hope that it will be useful, +* but WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +* GNU General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, see +#include "xatom-helper.h" + +extern void qt_blurImage(QImage &blurImage, qreal radius, bool quality, int transposed); + +delete_msg::delete_msg(QWidget *parent) : + QDialog(parent), + ui(new Ui::delete_msg) +{ + ui->setupUi(this); + + // 添加窗管协议 + XAtomHelper::setStandardWindowHint(this->winId()); +// this->setProperty("blurRegion", QRegion(QRect(1, 1, 1, 1))); +// setAttribute(Qt::WA_TranslucentBackground); +// this->setWindowFlags(Qt::FramelessWindowHint | Qt::Dialog); + + QPalette palette = ui->surebtn->palette(); + QColor ColorPlaceholderText(61,107,229,255); + QBrush brush2; + brush2.setColor(ColorPlaceholderText); + palette.setColor(QPalette::Button,QColor(61,107,229,255)); + palette.setBrush(QPalette::ButtonText, QBrush(Qt::white)); + ui->surebtn->setPalette(palette); + + QPalette palette1 = ui->closebtn->palette(); + QColor ColorPlaceholderText1(255,255,255,0); + QBrush brush; + brush.setColor(ColorPlaceholderText1); + palette.setBrush(QPalette::Button, brush); + ui->closebtn->setPalette(palette1); + + ui->closebtn->setIcon(QIcon::fromTheme("window-close-symbolic")); + ui->closebtn->setProperty("isWindowButton", 0x2); + ui->closebtn->setProperty("useIconHighlightEffect", 0x8); + //保存按钮边框是否凸起 + ui->closebtn->setFlat(true); + // 主题框架1.0.6-5kylin2 + + //配置重要按钮 + ui->surebtn->setProperty("isImportant", true); + //关闭按钮去掉聚焦状态 + ui->closebtn->setFocusPolicy(Qt::NoFocus); + ui->cancelbtn->setProperty("useButtonPalette", true); + + +} + +delete_msg::~delete_msg() +{ + delete ui; +} + +void delete_msg::on_closebtn_clicked() +{ + close_sure = 0; + this->close(); +} + +void delete_msg::on_surebtn_clicked() +{ + close_sure = 1; + this->close(); +} + +void delete_msg::on_cancelbtn_clicked() +{ + close_sure = 0; + this->close(); +} + +void delete_msg::paintEvent(QPaintEvent *event) +{ + Q_UNUSED(event); + QPainter p(this); + p.setRenderHint(QPainter::Antialiasing); // 反锯齿; + QPainterPath rectPath; + rectPath.addRect(this->rect()); + p.fillPath(rectPath,palette().color(QPalette::Base)); +} + +void delete_msg::mousePressEvent(QMouseEvent *event) +{ + if (event->button() == Qt::LeftButton) { + this->dragPosition = event->globalPos() - frameGeometry().topLeft(); + this->mousePressed = true; + } + QWidget::mousePressEvent(event); +} + +void delete_msg::mouseReleaseEvent(QMouseEvent *event) +{ + if (event->button() == Qt::LeftButton) { + this->mousePressed = false; + this->setCursor(Qt::ArrowCursor); + } + + QWidget::mouseReleaseEvent(event); +} + +void delete_msg::mouseMoveEvent(QMouseEvent *event) +{ + if (this->mousePressed) { + move(event->globalPos() - this->dragPosition); + this->setCursor(Qt::ClosedHandCursor); + } + + QWidget::mouseMoveEvent(event); +} diff --git a/deleteMsg.h b/deleteMsg.h new file mode 100644 index 0000000..02eae3b --- /dev/null +++ b/deleteMsg.h @@ -0,0 +1,60 @@ +/* +* 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 3, or (at your option) +* any later version. +* +* This program is distributed in the hope that it will be useful, +* but WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +* GNU General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, see +#include +#include +#include +#include +namespace Ui { +class delete_msg; +} +/** + * @brief 删除消息弹框 + */ +class delete_msg : public QDialog +{ + Q_OBJECT + +public: + explicit delete_msg(QWidget *parent = nullptr); + ~delete_msg(); + int close_sure; + //绘制底部阴影 + // Draw bottom shadow + void paintEvent(QPaintEvent *event); + Ui::delete_msg *ui; + void mousePressEvent(QMouseEvent *event); + void mouseReleaseEvent(QMouseEvent *event); + void mouseMoveEvent(QMouseEvent *event); + +private slots: + void on_closebtn_clicked(); + + void on_surebtn_clicked(); + + void on_cancelbtn_clicked(); + +private: + QPoint dragPosition; //拖动坐标 + bool mousePressed; //鼠标是否按下 +}; + +#endif // DELETE_MSG_H diff --git a/deleteMsg.ui b/deleteMsg.ui new file mode 100644 index 0000000..aef2d89 --- /dev/null +++ b/deleteMsg.ui @@ -0,0 +1,267 @@ + + + delete_msg + + + + 0 + 0 + 350 + 174 + + + + Dialog + + + + + + + + 0 + 0 + 350 + 174 + + + + + + + + + 0 + 50 + 350 + 46 + + + + + + + Qt::Horizontal + + + QSizePolicy::Fixed + + + + 19 + 20 + + + + + + + + + 24 + 24 + + + + + 24 + 24 + + + + border-image: url(:/image/warning-24x24.png); + + + + + + + + + + + + + are you sure ? + + + + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + + + 310 + 0 + 40 + 40 + + + + + 5 + + + 5 + + + 5 + + + 5 + + + + + + 30 + 30 + + + + + 30 + 30 + + + + + + + + + + + + + + + + 0 + 100 + 350 + 61 + + + + + 0 + + + 0 + + + 0 + + + 0 + + + 0 + + + + + Qt::Horizontal + + + + 156 + 20 + + + + + + + + + 80 + 30 + + + + + 80 + 30 + + + + + + + cancel + + + + + + + Qt::Horizontal + + + + 10 + 20 + + + + + + + + + 80 + 30 + + + + + 80 + 30 + + + + + + + sure + + + + + + + Qt::Horizontal + + + QSizePolicy::Fixed + + + + 24 + 20 + + + + + + + + + + + diff --git a/dotlineDemo.cpp b/dotlineDemo.cpp new file mode 100644 index 0000000..3e994af --- /dev/null +++ b/dotlineDemo.cpp @@ -0,0 +1,54 @@ +/* +* 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 3, or (at your option) +* any later version. +* +* This program is distributed in the hope that it will be useful, +* but WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +* GNU General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, see +#include +#include +#include "theme.h" + +DotLineDemo::DotLineDemo(QWidget *parent): + QWidget(parent) +{ + this->resize(390, 310); +} + +DotLineDemo::~DotLineDemo() +{ +} + +//绘制虚线圈 +// Draw a dashed circle +void DotLineDemo::paintEvent(QPaintEvent *event) +{ + Q_UNUSED(event); + + QPainter painter(this); + + QStyleOption opt; + opt.init(this); + QColor mainColor; + mainColor = theme::countdownRingBackColor; + painter.save(); + painter.setPen(mainColor); + painter.setBrush(mainColor); + QPainterPath bigCircle; + bigCircle.addEllipse(65, 13, 266, 266); + QPainterPath path = bigCircle ; + painter.drawPath(path); + painter.restore(); +} diff --git a/dotlineDemo.h b/dotlineDemo.h new file mode 100644 index 0000000..5e31dd7 --- /dev/null +++ b/dotlineDemo.h @@ -0,0 +1,45 @@ +/* +* 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 3, or (at your option) +* any later version. +* +* This program is distributed in the hope that it will be useful, +* but WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +* GNU General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, see +#include +#include + + + +class DotLineDemo : public QWidget +{ + Q_OBJECT + +public: + explicit DotLineDemo(QWidget *parent = nullptr); + ~DotLineDemo(); + + QWidget * widget; + +protected: + //绘制虚线圈 + // Draw a dashed circle + virtual void paintEvent(QPaintEvent *event); + +private: +}; + +#endif // DOTLINEDEMO_H diff --git a/fieldvalidutil.cpp b/fieldvalidutil.cpp new file mode 100644 index 0000000..3b9ca6a --- /dev/null +++ b/fieldvalidutil.cpp @@ -0,0 +1,437 @@ +/* +* Copyright (C) 2020, 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 3, or (at your option) +* any later version. +* +* This program is distributed in the hope that it will be useful, +* but WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +* GNU General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, see =small&&value<=big; +} + +bool FieldValidUtil::isNotNull(QString value) +{ + return !isNull(value); +} + +bool FieldValidUtil::isNotNull(long value) +{ + return !isNull(value); +} + + + + +#define URL_REGEX_STR "^http://([\\w-]+\\.)+[\\w-]+(/[\\w-./?%&=]*)?$" +/** + * @brief 匹配URL地址 + */ +bool FieldValidUtil::isUrl(QString str) +{ + return match(str, URL_REGEX_STR); +} +#define PWD_REGEX_STR "^[a-zA-Z]\\w{6,12}$" + +/** + * @brief 匹配密码,以字母开头,长度在6-12之间,只能包含字符、数字和下划线。 + */ +bool FieldValidUtil::isPwd(QString str) +{ + return match(str, PWD_REGEX_STR); +} +#define STRING_CHECK_REGEX_STR "^[a-zA-Z0-9\u4e00-\u9fa5-_]+$" + +/** + * @brief 验证字符,只能包含中文、英文、数字、下划线等字符。 + */ +bool FieldValidUtil::QStringCheck(QString str) +{ + return match(str, STRING_CHECK_REGEX_STR); +} +#define EMAIL_REGEX_STR "^\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*$" + +/** + * @brief 匹配Email地址 + */ +bool FieldValidUtil::isEmail(QString str) +{ + return match(str, EMAIL_REGEX_STR); +} +#define INTEGER_REGEX_STR "^[+]?\\d+$" + +/** + * @brief 匹配非负整数(正整数+0) + */ +bool FieldValidUtil::isInteger(QString str) +{ + return match(str, INTEGER_REGEX_STR); +} +/** + * @brief 判断数值类型,包括整数和浮点数 + */ +bool FieldValidUtil::isNumeric(QString str) +{ + if(isFloat(str) || isInteger(str)) return true; + return false; +} +#define DIGITS_REGEX_STR "^[0-9]*$" + +/** + * @brief 只能输入数字 + */ +bool FieldValidUtil::isDigits(QString str) +{ + return match(str, DIGITS_REGEX_STR); +} +#define FLOAT_REGEX_STR "^[-\\+]?\\d+(\\.\\d+)?$" + +/** + * @brief 匹配正浮点数 + */ +bool FieldValidUtil::isFloat(QString str) +{ + return match(str, FLOAT_REGEX_STR); +} +/** + * @brief 联系电话(手机/电话皆可)验证 + */ +bool FieldValidUtil::isTel(QString text) +{ + if(isMobile(text)||isPhone(text)) return true; + return false; +} +#define PHONE_REGEX_STR "^(\\d{3,4}-?)?\\d{7,9}$" + +/** + * @brief 电话号码验证 + */ +bool FieldValidUtil::isPhone(QString text) +{ + return match(text, PHONE_REGEX_STR); +} +#define MOBILE_REGEX_STR "^(((13[0-9]{1})|(15[0-9]{1})|(18[0-9]{1}))+\\d{8})$" + +/** + * @brief 手机号码验证 + */ +bool FieldValidUtil::isMobile(QString text) +{ + if(text.length()!=11) return false; + return match(text, MOBILE_REGEX_STR); +} +#define IDCARD_NO_REGEX_STR "^(\\d{6})()?(\\d{4})(\\d{2})(\\d{2})(\\d{3})(\\w)$" + +/** + * @brief 身份证号码验证 + */ +bool FieldValidUtil::isIdCardNo(QString text) +{ + return match(text, IDCARD_NO_REGEX_STR); +} +#define ZIPCODE_REGEX_STR "^[0-9]{6}$" + +/** + * @brief 邮政编码验证 + */ +bool FieldValidUtil::isZipCode(QString text) +{ + return match(text, ZIPCODE_REGEX_STR); +} +/** + * @brief 判断整数num是否等于0 + */ +bool FieldValidUtil::isIntEqZero(int num) +{ + return num==0; +} +/** + * @brief 判断整数num是否大于0 + */ +bool FieldValidUtil::isIntGtZero(int num) +{ + return num>0; +} +/** + * @brief 判断整数num是否大于或等于0 + */ +bool FieldValidUtil::isIntGteZero(int num) +{ + return num>=0; +} +/** + * @brief 判断浮点数num是否等于0 + */ +bool FieldValidUtil::isFloatEqZero(float num) +{ + return isNull(num); +} +/** + * @brief 判断浮点数num是否大于0 + */ +bool FieldValidUtil::isFloatGtZero(float num) +{ + return num>1e-6; +} +#define RIGHTFUL_STRING_REGEX_STR "^[A-Za-z0-9_-]+$" + +/** + * @brief 判断是否为合法字符(a-zA-Z0-9-_) + */ +bool FieldValidUtil::isRightfulQString(QString text) +{ + return match(text, RIGHTFUL_STRING_REGEX_STR); +} +#define ENGLISH_REGEX_STR "^[A-Za-z]+$" + +/** + * @brief 判断英文字符(a-zA-Z) + */ +bool FieldValidUtil::isEnglish(QString text) +{ + return match(text, ENGLISH_REGEX_STR); +} +#define CHINESE_CHAR_REGEX_STR "^[\u0391-\uFFE5]+$" + +/** + * @brief 判断中文字符(包括汉字和符号) + */ +bool FieldValidUtil::isChineseChar(QString text) +{ + return match(text, CHINESE_CHAR_REGEX_STR); +} +#define CHINESE_REGEX_STR "^[\u4e00-\u9fa5]+$" + +/** + * @brief 匹配汉字 + */ +bool FieldValidUtil::isChinese(QString text) +{ + return match(text, CHINESE_REGEX_STR); +} +/** + * @brief 是否包含中英文特殊字符,除英文"-_"字符外 + */ +bool FieldValidUtil::isContainsSpecialChar(QString text) +{ + if(isNull(text)) return false; + QString chars="[,`,~,!,@,#,$,%,^,&,*,(,),+,=,|,{,},',:,;,',[,],.,<,>,/,?,~,!,@,#,¥,%,…,&,*,(,),—,+,|,{,},【,】,‘,;,:,”,“,’,。,,,、,?,]"; + QStringList list =chars.split(","); + list<<","<<"\""; + for(QString ch : list){ + if(text.contains(ch)) return true; + } + return false; +} +#define SPECIAL_STRING_FILTER_REGEX_STR "[`~!@#$%^&*()+=|{}':;',\\[\\].<>/?~!@#¥%……&*()——+|{}【】‘;:\"\"”“’。,、?]" +/** + * @brief 过滤中英文特殊字符,除英文"-_"字符外 + */ +QString FieldValidUtil::QStringFilter(QString text) +{ + QString regExpr=SPECIAL_STRING_FILTER_REGEX_STR; + return replaceAll(text,regExpr); +} +/** + * @brief 过滤中英文特殊字符,除英文"-_"字符外 + */ +QString FieldValidUtil::QStringFilter(std::string text) +{ + QString regExpr=SPECIAL_STRING_FILTER_REGEX_STR; + return replaceAll(text,regExpr); +} +#define SCRIPT_REGEX_STR "<[\\s]*?script[^>]*?>[\\s\\S]*?<[\\s]*?\\/[\\s]*?script[\\s]*?>" +#define STYLE_REGEX_STR "<[\\s]*?style[^>]*?>[\\s\\S]*?<[\\s]*?\\/[\\s]*?style[\\s]*?>" +#define HTML_REGEX_STR "<[^>]+>" +#define PATTERN_REGEX_STR "\\s+" +/** + * @brief 过滤html代码 + */ +QString FieldValidUtil::htmlFilter(QString inputQString) +{ + // 含html标签的字符串 + QString htmlStr = inputQString; + QString textStr = ""; + // 定义script的正则表达式{或]*?>[\\s\\S]*?<\\/script> + QString regEx_script = SCRIPT_REGEX_STR; + // 定义style的正则表达式{或]*?>[\\s\\S]*?<\\/style> + QString regEx_style = STYLE_REGEX_STR; + // 定义HTML标签的正则表达式 + QString regEx_html = HTML_REGEX_STR; + //空白 + QString patternStr = PATTERN_REGEX_STR; + htmlStr = replaceAll(htmlStr,regEx_script); + htmlStr = replaceAll(htmlStr,regEx_style); + htmlStr = replaceAll(htmlStr,regEx_html); + htmlStr = replaceAll(htmlStr,patternStr); + textStr = htmlStr; + return textStr; +} +/** + * @brief 匹配,方便统一替换正则方法 + */ +bool FieldValidUtil::match(QString text, QString reg) +{ + if (isNull(text) || isNull(reg)) + return false; + QRegExp tempRexExp(reg); + return tempRexExp.exactMatch(text); +} +/** + * @brief 替换方法 + */ +QString FieldValidUtil::replaceAll(QString text, QString reg) +{ + return text.replace(QRegExp(reg),""); +} + +QString FieldValidUtil::replaceAll(std::string text, QString reg) +{ + return QString::fromStdString(text).replace(QRegExp(reg),""); +} + + + +void FieldValidUtil::createEntityCode(QString fields) +{ + QStringList list = fields.split(";"); + foreach (QString var, list) { + QStringList tmp = var.split(","); + QString methodName = makeFirstUpper(tmp.at(1)); + qDebug()<<"\t"<<"Q_PROPERTY ("<.*|< (.*) />/ +// 匹配首尾空格的正则表达式:(^s*)|(s*$) +// 匹配Email地址的正则表达式:w+([-+.]w+)*@w+([-.]w+)*.w+([-.]w+)* +// 匹配网址URL的正则表达式:^http://([\\w-]+\\.)+[\\w-]+(/[\\w-./?%&=]*)?$ diff --git a/fieldvalidutil.h b/fieldvalidutil.h new file mode 100644 index 0000000..f192e4a --- /dev/null +++ b/fieldvalidutil.h @@ -0,0 +1,81 @@ +/* +* Copyright (C) 2020, 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 3, or (at your option) +* any later version. +* +* This program is distributed in the hope that it will be useful, +* but WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +* GNU General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, see +#include +#include +#include +#include +class FieldValidUtil : public QObject +{ + Q_OBJECT +public: + explicit FieldValidUtil(QObject *parent = nullptr); + static bool isNull(int value) ; + static bool isNull(QString str) ; + static bool isNull(std::string str) ; + static bool isNull(long value) ; + static bool isNull(float value) ; + static bool isNull(double value) ; + static bool isNotNull(int value) ; + static bool isValueBetweenRange(int value,int small,int big) ; + static bool isNotNull(QString value) ; + static bool isNotNull(long value) ; + static bool isUrl(QString str); + static bool isPwd(QString str); + static bool QStringCheck(QString str); + static bool isEmail(QString str); + static bool isInteger(QString str); + static bool isNumeric(QString str); + static bool isDigits(QString str); + static bool isFloat(QString str); + static bool isTel(QString text); + static bool isPhone(QString text); + static bool isMobile(QString text); + static bool isIdCardNo(QString text); + static bool isZipCode(QString text); + static bool isIntEqZero(int num); + static bool isIntGtZero(int num); + static bool isIntGteZero(int num); + static bool isFloatEqZero(float num); + static bool isFloatGtZero(float num); + static bool isFloatGteZero(float num); + static bool isRightfulQString(QString text); + static bool isEnglish(QString text); + static bool isChineseChar(QString text); + static bool isChinese(QString text); + static bool isContainsSpecialChar(QString text); + static QString QStringFilter(QString text); + static QString QStringFilter(std::string text); + static QString htmlFilter(QString inputQString); + static bool match(QString text, QString reg); + static QString replaceAll(QString text, QString reg); + static QString replaceAll(std::string text, QString reg); + static void createEntityCode(QString fields); + static QString makeFirstUpper(QString str); + + + +signals: + +}; +#define NO_SPECIAL_CHAR "^[\u4E00-\u9FA5A-Za-z0-9_]+$" + +#endif // FIELDVALIDUTIL_H diff --git a/gsettingsubject.cpp b/gsettingsubject.cpp new file mode 100644 index 0000000..8b4fa29 --- /dev/null +++ b/gsettingsubject.cpp @@ -0,0 +1,147 @@ +/* +* Copyright (C) 2020, 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 3, or (at your option) +* any later version. +* +* This program is distributed in the hope that it will be useful, +* but WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +* GNU General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, see get(STYLE_NAME).toString())){ + theme::themetype=1; + emit blackStyle(); + }else{ + theme::themetype=0; + emit whiteStyle(); + } + } + if(key==STYLE_ICON_NAME || key==STYLE_ICON){ + emit iconChnaged(); + } + if (key == SYSTEM_FONT_SIZE) { + const int size = m_styleSettings->get(SYSTEM_FONT_EKY).toInt(); + emit fontChanged(size); + } + }); + } + if(m_formatSettings!=nullptr){ + connect(m_formatSettings, &QGSettings::changed, this, [=] (const QString &key) { + if (key == HOUR_SYSTEM) { + QString m_timeZone = m_formatSettings->get(TIME_FORMAT_KEY).toString(); + emit timeZoneChanged(m_timeZone); + } + }); + } + if(m_mouseSettings!=nullptr){ + connect(m_mouseSettings, &QGSettings::changed, this, [=] (const QString &key) { + if(WHEEL_KEY_HW==key||WHEEL_KEY_SP==key){ + getWheelSpeed(); + } + }); + } + +} + +void GsettingSubject::iniData() +{ + const QByteArray style_id(ORG_UKUI_STYLE); + m_stylelist<get(STYLE_NAME).toString())){ + emit blackStyle(); + }else{ + emit whiteStyle(); + } + } + +} +/** + * @brief 初始化时区 + */ +void GsettingSubject::iniTimeZone() +{ + // 监听时区变化 + if(m_formatSettings!=nullptr){ + QString m_timeZone = m_formatSettings->get(TIME_FORMAT_KEY).toString(); + emit timeZoneChanged(m_timeZone); + } + +} +/** + * @brief 初始化字体 + */ +void GsettingSubject::iniFontSize() +{ + if(m_styleSettings!=nullptr){ + //字体 + if (m_styleSettings->get(SYSTEM_FONT_EKY).toInt()) { + const int size = m_styleSettings->get(SYSTEM_FONT_EKY).toInt(); + emit fontChanged(size); + } + } +} +void GsettingSubject::iniMouseWheel() +{ + if(m_mouseSettings!=nullptr){ + getWheelSpeed(); + } +} +void GsettingSubject::getWheelSpeed() +{ + if (m_mouseSettings->get(WHEEL_KEY_HW).toInt()) { + const int speed = m_mouseSettings->get(WHEEL_KEY_HW).toInt(); + emit mouseWheelChanged(speed); + } + if (m_mouseSettings->get(WHEEL_KEY_SP).toInt()) { + const int speed = m_mouseSettings->get(WHEEL_KEY_SP).toInt(); + emit mouseWheelChanged(speed); + } +} + +GsettingSubject::~GsettingSubject() +{ + delete m_styleSettings; + delete m_formatSettings; + delete m_mouseSettings; +} diff --git a/gsettingsubject.h b/gsettingsubject.h new file mode 100644 index 0000000..fc5faef --- /dev/null +++ b/gsettingsubject.h @@ -0,0 +1,59 @@ +/* +* Copyright (C) 2020, 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 3, or (at your option) +* any later version. +* +* This program is distributed in the hope that it will be useful, +* but WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +* GNU General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, see +#include +#include "constant_class.h" +#include +class GsettingSubject : public QObject +{ + Q_OBJECT +public: + void iniWidgetStyle(); + void iniTimeZone(); + void iniFontSize(); + ~GsettingSubject(); + GsettingSubject(const GsettingSubject&)=delete; + GsettingSubject& operator=(const GsettingSubject&)=delete; + static GsettingSubject* getInstance(){ + static GsettingSubject instance; + return &instance; + } + void iniMouseWheel(); +signals: + void blackStyle(); + void whiteStyle(); + void iconChnaged(); + void fontChanged(int size); + void mouseWheelChanged(int speed); + void timeZoneChanged(QString timeZone); +private: + static void iniConnect(); + void iniConnection(); + void iniData(); + QGSettings *m_styleSettings = nullptr; + QStringList m_stylelist ; + QGSettings *m_formatSettings = nullptr; + QGSettings *m_mouseSettings = nullptr; + explicit GsettingSubject(QObject *parent = nullptr); + void getWheelSpeed(); +}; + +#endif // GSETTINGSUBJECT_H diff --git a/guide/en_US/image/1.png b/guide/en_US/image/1.png new file mode 100755 index 0000000..f3df3d9 Binary files /dev/null and b/guide/en_US/image/1.png differ diff --git a/guide/en_US/image/2.png b/guide/en_US/image/2.png new file mode 100755 index 0000000..94fa8dc Binary files /dev/null and b/guide/en_US/image/2.png differ diff --git a/guide/en_US/image/3.png b/guide/en_US/image/3.png new file mode 100755 index 0000000..5e0f606 Binary files /dev/null and b/guide/en_US/image/3.png differ diff --git a/guide/en_US/image/menu.jpg b/guide/en_US/image/menu.jpg new file mode 100644 index 0000000..db4cbb1 Binary files /dev/null and b/guide/en_US/image/menu.jpg differ diff --git a/guide/en_US/index.md b/guide/en_US/index.md new file mode 100644 index 0000000..1770bb1 --- /dev/null +++ b/guide/en_US/index.md @@ -0,0 +1,22 @@ +# Alarm +## Overview +​ Alarm clock is a self-developed desktop utility with simple operation. It not only supports setting alarm clock, but also is equipped with countdown and stopwatch. It can be switched through the corresponding icon at the top of the interface. Different ring reminders can be set in the alarm clock and timer. + +## Open mode +​ **“menu”>“Alarm”** or**“taskbar”>“search”>“Alarm”**。 + +## basic operation +​ The home page of the alarm clock is shown in the figure below. Select different icons at the top of the interface to switch to the interface of alarm clock, countdown and stopwatch. + +![](image/1.png) + +​ In the alarm clock interface, click **"add"** to add an alarm clock and set the time, alarm name, repeating day and ring tone. + +![](image/2.png) + +​ Click ![](image/menu.jpg) You can open the alarm menu bar. After selecting **"setting"** in the menu bar, a setting window will pop up. You can choose whether to mute, set the time format, later reminder time and default ring tone. + +![](image/3.png) + +​ In the alarm menu bar, select **"help"** to automatically jump to the user's manual and view the operating instructions of the tool. Select **"about"** to view the current version information, and **"exit"** to close the application. + diff --git a/guide/ukui-clock.png b/guide/ukui-clock.png new file mode 100644 index 0000000..7867463 Binary files /dev/null and b/guide/ukui-clock.png differ diff --git a/guide/zh_CN/image/1.png b/guide/zh_CN/image/1.png new file mode 100755 index 0000000..9b0d112 Binary files /dev/null and b/guide/zh_CN/image/1.png differ diff --git a/guide/zh_CN/image/2.png b/guide/zh_CN/image/2.png new file mode 100755 index 0000000..93791a0 Binary files /dev/null and b/guide/zh_CN/image/2.png differ diff --git a/guide/zh_CN/image/3.png b/guide/zh_CN/image/3.png new file mode 100755 index 0000000..e191127 Binary files /dev/null and b/guide/zh_CN/image/3.png differ diff --git a/guide/zh_CN/image/menu.jpg b/guide/zh_CN/image/menu.jpg new file mode 100644 index 0000000..db4cbb1 Binary files /dev/null and b/guide/zh_CN/image/menu.jpg differ diff --git a/guide/zh_CN/index.md b/guide/zh_CN/index.md new file mode 100644 index 0000000..f1e5917 --- /dev/null +++ b/guide/zh_CN/index.md @@ -0,0 +1,22 @@ +# 闹钟 +## 概 述 +​ 闹钟是自研的一款操作简易的桌面实用工具,不仅支持设置闹钟,还配置了倒计时和秒表,通过界面顶部对应的图标可进行切换。闹钟和计时器中可设置不同的铃声提醒。 + +## 打开方式 +​ **“开始菜单”>“闹钟”**或**“任务栏”>“搜索”>“闹钟”**。 + +## 基本操作 +​ 闹钟首页如下图所示,选择界面顶部的不同的图标可对应切换至闹钟、倒计时、秒表界面。 + +![](image/1.png) + +​ 在闹钟界面中,点击**“添加”**可添加闹钟,并设定时间、闹钟名、重复日及铃声。 + +![](image/2.png) + +​ 点击导航栏中的![](image/menu.jpg)可打开闹钟菜单栏,在菜单栏中选择**“设置”**后将弹出设置窗口,可选择是否静音,设置时间格式、稍后提醒时间和默认铃声。 + +![](image/3.png) + +​ 在闹钟菜单栏中,选择**“帮助”**将自动跳转至用户手册中,可查看该工具的操作说明。选择**“关于”**可查看当前版本信息,选择**“退出”**可关闭应用。 + diff --git a/image/DFPKingGothicGB-Semibold-2.ttf b/image/DFPKingGothicGB-Semibold-2.ttf new file mode 100644 index 0000000..de87069 Binary files /dev/null and b/image/DFPKingGothicGB-Semibold-2.ttf differ diff --git a/image/HuaKangJinGangHei-Regular-2.ttf b/image/HuaKangJinGangHei-Regular-2.ttf new file mode 100644 index 0000000..c0f598b Binary files /dev/null and b/image/HuaKangJinGangHei-Regular-2.ttf differ diff --git a/image/alarm.png b/image/alarm.png new file mode 100644 index 0000000..bad3c1f Binary files /dev/null and b/image/alarm.png differ diff --git a/image/alarmselect.png b/image/alarmselect.png new file mode 100644 index 0000000..7efa5c0 Binary files /dev/null and b/image/alarmselect.png differ diff --git a/image/aptdaemon-error.png b/image/aptdaemon-error.png new file mode 100644 index 0000000..d7780fd Binary files /dev/null and b/image/aptdaemon-error.png differ diff --git a/image/count.png b/image/count.png new file mode 100644 index 0000000..a0602f0 Binary files /dev/null and b/image/count.png differ diff --git a/image/countselect.png b/image/countselect.png new file mode 100644 index 0000000..9eab4eb Binary files /dev/null and b/image/countselect.png differ diff --git a/image/go-bottom-symbolic.png b/image/go-bottom-symbolic.png new file mode 100644 index 0000000..2febef8 Binary files /dev/null and b/image/go-bottom-symbolic.png differ diff --git a/image/go-up-symbolic.png b/image/go-up-symbolic.png new file mode 100644 index 0000000..44ebe31 Binary files /dev/null and b/image/go-up-symbolic.png differ diff --git a/image/icon-4-16x16.png b/image/icon-4-16x16.png new file mode 100644 index 0000000..a5c7377 Binary files /dev/null and b/image/icon-4-16x16.png differ diff --git a/image/kylin-alarm-clock.png b/image/kylin-alarm-clock.png new file mode 100644 index 0000000..e44547e Binary files /dev/null and b/image/kylin-alarm-clock.png differ diff --git a/image/kylin-alarm-clock.svg b/image/kylin-alarm-clock.svg new file mode 100644 index 0000000..db3a197 --- /dev/null +++ b/image/kylin-alarm-clock.svg @@ -0,0 +1,57 @@ + + + +画板 18 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/image/miniIcon/finish-dark-click.png b/image/miniIcon/finish-dark-click.png new file mode 100644 index 0000000..6e53405 Binary files /dev/null and b/image/miniIcon/finish-dark-click.png differ diff --git a/image/miniIcon/finish-dark-hover.png b/image/miniIcon/finish-dark-hover.png new file mode 100644 index 0000000..8e3f7cb Binary files /dev/null and b/image/miniIcon/finish-dark-hover.png differ diff --git a/image/miniIcon/finish-dark-inactive.png b/image/miniIcon/finish-dark-inactive.png new file mode 100644 index 0000000..425c12a Binary files /dev/null and b/image/miniIcon/finish-dark-inactive.png differ diff --git a/image/miniIcon/finish-dark-normal.png b/image/miniIcon/finish-dark-normal.png new file mode 100644 index 0000000..5ecd4ce Binary files /dev/null and b/image/miniIcon/finish-dark-normal.png differ diff --git a/image/miniIcon/finish-light-click.png b/image/miniIcon/finish-light-click.png new file mode 100644 index 0000000..5faa2f7 Binary files /dev/null and b/image/miniIcon/finish-light-click.png differ diff --git a/image/miniIcon/finish-light-hover.png b/image/miniIcon/finish-light-hover.png new file mode 100644 index 0000000..d189098 Binary files /dev/null and b/image/miniIcon/finish-light-hover.png differ diff --git a/image/miniIcon/finish-light-inactive.png b/image/miniIcon/finish-light-inactive.png new file mode 100644 index 0000000..37e1a3f Binary files /dev/null and b/image/miniIcon/finish-light-inactive.png differ diff --git a/image/miniIcon/finish-light-normal.png b/image/miniIcon/finish-light-normal.png new file mode 100644 index 0000000..54e7d3b Binary files /dev/null and b/image/miniIcon/finish-light-normal.png differ diff --git a/image/miniIcon/mute-off-64.png b/image/miniIcon/mute-off-64.png new file mode 100644 index 0000000..df5ed3c Binary files /dev/null and b/image/miniIcon/mute-off-64.png differ diff --git a/image/miniIcon/mute-off-dark.png b/image/miniIcon/mute-off-dark.png new file mode 100644 index 0000000..7a81d1b Binary files /dev/null and b/image/miniIcon/mute-off-dark.png differ diff --git a/image/miniIcon/mute-off.png b/image/miniIcon/mute-off.png new file mode 100644 index 0000000..d622ab9 Binary files /dev/null and b/image/miniIcon/mute-off.png differ diff --git a/image/miniIcon/mute-off.svg b/image/miniIcon/mute-off.svg new file mode 100644 index 0000000..6b89786 --- /dev/null +++ b/image/miniIcon/mute-off.svg @@ -0,0 +1,10 @@ + + + 画板 + + + + + + + \ No newline at end of file diff --git a/image/miniIcon/mute-on-dark.png b/image/miniIcon/mute-on-dark.png new file mode 100644 index 0000000..87df83a Binary files /dev/null and b/image/miniIcon/mute-on-dark.png differ diff --git a/image/miniIcon/mute-on.png b/image/miniIcon/mute-on.png new file mode 100644 index 0000000..55fc5af Binary files /dev/null and b/image/miniIcon/mute-on.png differ diff --git a/image/miniIcon/restore-active-b.png b/image/miniIcon/restore-active-b.png new file mode 100644 index 0000000..be7e9ab Binary files /dev/null and b/image/miniIcon/restore-active-b.png differ diff --git a/image/miniIcon/restore_active-w.png b/image/miniIcon/restore_active-w.png new file mode 100644 index 0000000..582ca0c Binary files /dev/null and b/image/miniIcon/restore_active-w.png differ diff --git a/image/miniIcon/start-hover-dark.png b/image/miniIcon/start-hover-dark.png new file mode 100644 index 0000000..8eb4ecf Binary files /dev/null and b/image/miniIcon/start-hover-dark.png differ diff --git a/image/miniIcon/start-hover-light.png b/image/miniIcon/start-hover-light.png new file mode 100644 index 0000000..8eb4ecf Binary files /dev/null and b/image/miniIcon/start-hover-light.png differ diff --git a/image/miniIcon/start-normal-dark.png b/image/miniIcon/start-normal-dark.png new file mode 100644 index 0000000..5161e7a Binary files /dev/null and b/image/miniIcon/start-normal-dark.png differ diff --git a/image/miniIcon/start-normal-light.png b/image/miniIcon/start-normal-light.png new file mode 100644 index 0000000..b940de1 Binary files /dev/null and b/image/miniIcon/start-normal-light.png differ diff --git a/image/miniIcon/suspend-click-dark.png b/image/miniIcon/suspend-click-dark.png new file mode 100644 index 0000000..a76e701 Binary files /dev/null and b/image/miniIcon/suspend-click-dark.png differ diff --git a/image/miniIcon/suspend-click-light.png b/image/miniIcon/suspend-click-light.png new file mode 100644 index 0000000..a76e701 Binary files /dev/null and b/image/miniIcon/suspend-click-light.png differ diff --git a/image/miniIcon/suspend-hover-dark.png b/image/miniIcon/suspend-hover-dark.png new file mode 100644 index 0000000..ccf1876 Binary files /dev/null and b/image/miniIcon/suspend-hover-dark.png differ diff --git a/image/miniIcon/suspend-hover-light.png b/image/miniIcon/suspend-hover-light.png new file mode 100644 index 0000000..ccf1876 Binary files /dev/null and b/image/miniIcon/suspend-hover-light.png differ diff --git a/image/miniIcon/suspend-normal-dark.png b/image/miniIcon/suspend-normal-dark.png new file mode 100644 index 0000000..adfce35 Binary files /dev/null and b/image/miniIcon/suspend-normal-dark.png differ diff --git a/image/miniIcon/suspend-normal-light.png b/image/miniIcon/suspend-normal-light.png new file mode 100644 index 0000000..9330912 Binary files /dev/null and b/image/miniIcon/suspend-normal-light.png differ diff --git a/image/noClockBlack.png b/image/noClockBlack.png new file mode 100644 index 0000000..3200584 Binary files /dev/null and b/image/noClockBlack.png differ diff --git a/image/noClockWhite.png b/image/noClockWhite.png new file mode 100644 index 0000000..b5d49a7 Binary files /dev/null and b/image/noClockWhite.png differ diff --git a/image/object-select-symbolic.png b/image/object-select-symbolic.png new file mode 100644 index 0000000..574ee4f Binary files /dev/null and b/image/object-select-symbolic.png differ diff --git a/image/siyuanheiti_CN_Medium.otf b/image/siyuanheiti_CN_Medium.otf new file mode 100644 index 0000000..53e03e0 Binary files /dev/null and b/image/siyuanheiti_CN_Medium.otf differ diff --git a/image/stopwatch.png b/image/stopwatch.png new file mode 100644 index 0000000..5d0fb40 Binary files /dev/null and b/image/stopwatch.png differ diff --git a/image/stopwatchselect.png b/image/stopwatchselect.png new file mode 100644 index 0000000..048472a Binary files /dev/null and b/image/stopwatchselect.png differ diff --git a/image/switchIconB.png b/image/switchIconB.png new file mode 100644 index 0000000..57e970b Binary files /dev/null and b/image/switchIconB.png differ diff --git a/image/switchIconW.png b/image/switchIconW.png new file mode 100644 index 0000000..8d3bc2a Binary files /dev/null and b/image/switchIconW.png differ diff --git a/image/warning-24x24.png b/image/warning-24x24.png new file mode 100644 index 0000000..c24c3e7 Binary files /dev/null and b/image/warning-24x24.png differ diff --git a/images.qrc b/images.qrc new file mode 100644 index 0000000..89c17ba --- /dev/null +++ b/images.qrc @@ -0,0 +1,55 @@ + + + clock.ico + image/noClockWhite.png + image/noClockBlack.png + image/HuaKangJinGangHei-Regular-2.ttf + image/DFPKingGothicGB-Semibold-2.ttf + image/alarm.png + image/count.png + image/stopwatch.png + image/stopwatchselect.png + image/alarmselect.png + image/countselect.png + image/aptdaemon-error.png + image/siyuanheiti_CN_Medium.otf + image/kylin-alarm-clock.png + image/go-bottom-symbolic.png + image/object-select-symbolic.png + image/icon-4-16x16.png + image/kylin-alarm-clock.svg + image/warning-24x24.png + image/switchIconB.png + image/switchIconW.png + translations/ukui-clock_zh_CN.ts + translations/ukui-clock_tr.ts + image/go-up-symbolic.png + clock_conf.ini + image/miniIcon/suspend-normal-light.png + image/miniIcon/suspend-normal-dark.png + image/miniIcon/suspend-hover-light.png + image/miniIcon/suspend-hover-dark.png + image/miniIcon/suspend-click-light.png + image/miniIcon/suspend-click-dark.png + image/miniIcon/start-normal-light.png + image/miniIcon/start-normal-dark.png + image/miniIcon/start-hover-light.png + image/miniIcon/start-hover-dark.png + image/miniIcon/mute-on.png + image/miniIcon/mute-on-dark.png + image/miniIcon/mute-off.png + image/miniIcon/mute-off-dark.png + image/miniIcon/finish-light-normal.png + image/miniIcon/finish-light-inactive.png + image/miniIcon/finish-light-hover.png + image/miniIcon/finish-light-click.png + image/miniIcon/finish-dark-normal.png + image/miniIcon/finish-dark-inactive.png + image/miniIcon/finish-dark-hover.png + image/miniIcon/finish-dark-click.png + image/miniIcon/mute-off.svg + image/miniIcon/mute-off-64.png + image/miniIcon/restore-active-b.png + image/miniIcon/restore_active-w.png + + diff --git a/integer.cpp b/integer.cpp new file mode 100644 index 0000000..c1576d8 --- /dev/null +++ b/integer.cpp @@ -0,0 +1,45 @@ +/* +* Copyright (C) 2020, 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 3, or (at your option) +* any later version. +* +* This program is distributed in the hope that it will be useful, +* but WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +* GNU General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, see m_value=-1; +} + +Integer::~Integer() +{ + +} + +Integer::Integer(int n) +{ + this->m_value=n; +} + +int Integer::value() const +{ + return m_value; +} + +void Integer::setValue(int value) +{ + m_value = value; +} + + diff --git a/integer.h b/integer.h new file mode 100644 index 0000000..acee9f0 --- /dev/null +++ b/integer.h @@ -0,0 +1,35 @@ +/* +* Copyright (C) 2020, 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 3, or (at your option) +* any later version. +* +* This program is distributed in the hope that it will be useful, +* but WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +* GNU General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, see +#include +#include +#include + +item_new::item_new(QWidget *parent) : + QWidget(parent) +{ + setupUi(this); + this->setFixedSize(340, 108); + + alarmLabel_w0 = new QLabel(this);//闹钟用途//Alarm function + alarmLabel_w0->move(27 ,6); + alarmLabel_w0->setFixedSize(200, 25); + alarmLabel_w0->setText("闹钟"); + + alarmLabel_s0 = new QLabel( this);//闹钟重复//Repetition of alarm clock + alarmLabel_s0->move(27, 74); + alarmLabel_s0->setFixedSize(270, 17); + alarmLabel_s0->setText("工作日"); + alarmLabel_s0->setVisible(true); + + alarmLabel0 = new QLabel(this);//闹钟//Alarm clock + alarmLabel0->move(25,24); + alarmLabel0->setFixedSize(125, 56); + alarmLabel0->setText("00:00"); + alarmLabel0->setVisible(true); + alarmLabel0->show(); + + alarmLabel1 = new QLabel(this);//上下午//Last afternoon + alarmLabel1->move(155,22); + alarmLabel1->setFixedSize(31, 56); + alarmLabel1->setStyleSheet("font: 10pt;background-color: rgb();"); + alarmLabel1->setText("上午"); + alarmLabel1->setVisible(true); + + alarm_on_off0 = new KSwitchButton(this);//闹钟开关// Alarm switch + alarm_on_off0->move(263,43); + alarm_on_off0->setFixedSize(50,24); + alarm_on_off0->setChecked(true); + alarm_on_off0->setFlat(true); + alarm_on_off0->setVisible(true); + settingsStyle(); +} + +item_new::~item_new() +{ +} + +void item_new::setupUi(QWidget *item_new) +{ + if (item_new->objectName().isEmpty()) + item_new->setObjectName(QString::fromUtf8("item_new")); + item_new->resize(376, 56); + item_new->setStyleSheet(QString::fromUtf8("border-radius:12px;\n" + "")); + retranslateUi(item_new); + + QMetaObject::connectSlotsByName(item_new); +} // setupUi + +void item_new::retranslateUi(QWidget *item_new) +{ + item_new->setWindowTitle(QApplication::translate("item_new", "Form", nullptr)); +} // retranslateUi + +/* +*监听主题 +*/ +void item_new::settingsStyle() +{ + GsettingSubject * subject = GsettingSubject::getInstance();; + connect(subject,&GsettingSubject::blackStyle, this,[=](){ + this->blackStyle(); + }); + connect(subject,&GsettingSubject::whiteStyle, this,[=](){ + this->whiteStyle(); + }); + subject->iniWidgetStyle(); +} + + + +//黑色主题 +void item_new::blackStyle() +{ + +} +//白色主题 +void item_new::whiteStyle() +{ + +} + +void item_new::openStyle(int size) +{ + m_itemClose=false; + commonStyle(size); +} + +void item_new::commonStyle(int size) +{ + alarmLabel0->setStyleSheet(getLabelStyleSheet(round(2.7*size)));//时间 + alarmLabel1->setStyleSheet(getLabelStyleSheet(round(0.9*size)));//上下午 + alarmLabel_w0->setStyleSheet(getLabelStyleSheet(round(1.1*size))); //名字 + alarmLabel_s0->setStyleSheet(getLabelStyleSheet(round(1.1*size)));//重复 +} +/** + * @brief 关闭纸灰 + */ +void item_new::closeStyle(int size) +{ + m_itemClose=true; + commonStyle(size); +} + +QString item_new::getLabelStyleSheet(int size) +{ + QString str = "font-size:"; + str = str.append(QString::number(size)); + str = str.append("px;"); + if(m_itemClose){ + str = str.append("color:rgba(172,172,172,255);"); + } + return str; +} + +QString item_new::id() const +{ + return m_id; +} + +void item_new::setId(const QString &id) +{ + m_id = id; +} + + diff --git a/itemNew.h b/itemNew.h new file mode 100644 index 0000000..314e032 --- /dev/null +++ b/itemNew.h @@ -0,0 +1,86 @@ +/* +* 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 3, or (at your option) +* any later version. +* +* This program is distributed in the hope that it will be useful, +* but WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +* GNU General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, see +#include +#include +#include +#include +#include +#include "CustomButton.h" +#include "constant_class.h" +#include "kwidget.h" +#include "kswitchbutton.h" + +using namespace kdk; + + + +namespace Ui { +class item_new; +} +/** + * @brief 闹钟列表子项 + */ +class item_new : public QWidget +{ + Q_OBJECT + +public: + explicit item_new(QWidget *parent = nullptr); + ~item_new(); + +//private: + + void setupUi(QWidget *item_new); + void retranslateUi(QWidget *item_new); + void settingsStyle(); + void blackStyle(); //黑色主题 + void whiteStyle(); //白色主题 + void closeStyle(int size); + void openStyle(int size); + void commonStyle(int size); + QString getLabelStyleSheet(int size); + + + Ui::item_new *ui; + + QPushButton *deleteAlarmBtn0; + QLabel *alarmLabel0; + QLabel *alarmLabel1; + QLabel *alarmLabel_w0; + QLabel *alarmLabel_s0; + +// CustomButton *alarm_on_off0; + KSwitchButton *alarm_on_off0; + QPushButton *alarm_changed0; + QPushButton *alarm_edit0; + + QFrame *alarm_line0; + + + QString id() const; + void setId(const QString &id); +private: + QString m_id; + bool m_itemClose = false; +}; + +#endif // ITEM_NEW_H diff --git a/kylinqfiledialog.cpp b/kylinqfiledialog.cpp new file mode 100644 index 0000000..eaf47cf --- /dev/null +++ b/kylinqfiledialog.cpp @@ -0,0 +1,27 @@ +/* +* Copyright (C) 2020, 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 3, or (at your option) +* any later version. +* +* This program is distributed in the hope that it will be useful, +* but WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +* GNU General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, see +#include + +KylinQFileDialog::KylinQFileDialog(QWidget *parent) : QFileDialog(parent) +{ + +} + + diff --git a/kylinqfiledialog.h b/kylinqfiledialog.h new file mode 100644 index 0000000..9109531 --- /dev/null +++ b/kylinqfiledialog.h @@ -0,0 +1,35 @@ +/* +* Copyright (C) 2020, 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 3, or (at your option) +* any later version. +* +* This program is distributed in the hope that it will be useful, +* but WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +* GNU General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, see +#include + +class KylinQFileDialog : public QFileDialog +{ + Q_OBJECT +public: + explicit KylinQFileDialog(QWidget *parent = nullptr); + +protected: +signals: + +}; + +#endif // KYLINQFILEDIALOG_H diff --git a/main.cpp b/main.cpp new file mode 100644 index 0000000..fc36352 --- /dev/null +++ b/main.cpp @@ -0,0 +1,176 @@ +/* +* 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 3, or (at your option) +* any later version. +* +* This program is distributed in the hope that it will be useful, +* but WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +* GNU General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, see +#include +#include +#include "xatom-helper.h" +#include +#include "gsettingsubject.h" +#include "clockdbusadaptor.h" +#include "dbusupdateclockadaptor.h" +#include "dbusdeleteclockbyidadaptor.h" +#include "dbusselectclockbyidadaptor.h" +#include "ClockInterface.h" +#include +/*! + * \brief myMessageOutput + * 日志打印输出 + */ +void myMessageOutput(QtMsgType type, const QMessageLogContext &context, const QString &msg) +{ + // 加锁 + static QMutex mutex; + mutex.lock(); + qDebug()<= QT_VERSION_CHECK(5, 12, 0)) + QApplication::setAttribute(Qt::AA_EnableHighDpiScaling); + QApplication::setAttribute(Qt::AA_UseHighDpiPixmaps); + #endif + #if (QT_VERSION >= QT_VERSION_CHECK(5, 14, 0)) + QApplication::setHighDpiScaleFactorRoundingPolicy(Qt::HighDpiScaleFactorRoundingPolicy::PassThrough); + #endif + //构造单例 利用本地连接qlocalsocket作为判断的公共访问资源 + SingleApplication a(argc, argv); + //支持主题框架图标 + a.setWindowIcon(QIcon::fromTheme("kylin-alarm-clock")); + //此属性保存关闭最后一个窗口时应用程序是否隐式退出。默认值为true。 + a.setQuitOnLastWindowClosed(false); + + + //如果没在运行 + if (!a.isRunning()) { + Clock w; + a.w = &w; + //发布dbus接口 + QObject obj; + publishDbusInterface(&w,&obj); + QObject updateObj; + publishDbusUpdateClock(&w,&updateObj); + QObject deleteObj; + publishDbusDeleteClock(&w,&deleteObj); + QObject selectObj; + publishDbusSelectClock(&w,&selectObj); + // 添加窗管协议。显示的位置 + XAtomHelper::setStandardWindowHint(w.winId()); + w.show(); + return a.exec(); + } + return 0; +} diff --git a/mediaplayerpool.cpp b/mediaplayerpool.cpp new file mode 100644 index 0000000..19f4a50 --- /dev/null +++ b/mediaplayerpool.cpp @@ -0,0 +1,89 @@ +/* +* Copyright (C) 2020, 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 3, or (at your option) +* any later version. +* +* This program is distributed in the hope that it will be useful, +* but WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +* GNU General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, see +#include +MediaPlayerPool::MediaPlayerPool(int size,QObject *parent) : QObject(parent),m_size(size) +{ + workerThread = new MediaPlayerThread(size,this); + createQMediaPlayerPool(m_size); +} + +MediaPlayerThread *MediaPlayerPool::getWorkerThread() const +{ + return workerThread; +} + +/** + * @brief 创建对象池 + */ +void MediaPlayerPool::createQMediaPlayerPool(int size) +{ + connect(workerThread, &MediaPlayerThread::resultReady, this, [=](ObjectPool * mediaPool){ + m_qMediaPlayerPool=mediaPool; + }); + connect(workerThread, &MediaPlayerThread::finished, workerThread, &QObject::deleteLater); + workerThread->start(); + /* + qDebug()<<"dbq-开始创建对象池"< * que = new ObjectPool(m_size); + m_qMediaPlayerPool=que; + qint64 timeT2 = QDateTime::currentDateTime().toMSecsSinceEpoch(); + qDebug()<<"dbq-创建耗时"<GetObject(); + //清空数据 + res->setPlaylist(NULL); + res->setMedia(NULL); +// res->stop(); +// res->moveToThread(QApplication::instance()->thread()); + qDebug()<<"dbq-state"<state()<<"MediaStatus"<mediaStatus(); + }else{ + qDebug()<<"dbq-新建"; + qint64 timeT1 = QDateTime::currentDateTime().toMSecsSinceEpoch(); + res = new QMediaPlayer(); + qint64 timeT2 = QDateTime::currentDateTime().toMSecsSinceEpoch(); + qDebug()<<"dbq-创建耗时"<returnObject(player); + } +} + +MediaPlayerPool::~MediaPlayerPool() +{ + delete m_qMediaPlayerPool; +} diff --git a/mediaplayerpool.h b/mediaplayerpool.h new file mode 100644 index 0000000..bedefca --- /dev/null +++ b/mediaplayerpool.h @@ -0,0 +1,54 @@ +/* +* Copyright (C) 2020, 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 3, or (at your option) +* any later version. +* +* This program is distributed in the hope that it will be useful, +* but WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +* GNU General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, see +#include "object_pool.h" +#include +#include "mediaplayerthread.h" +class MediaPlayerPool : public QObject +{ + Q_OBJECT +public: + QMediaPlayer * getQMediaPlayer(); + void pushBackQMediaPlayer(QMediaPlayer * player); + ~MediaPlayerPool(); + MediaPlayerPool(const MediaPlayerPool&)=delete; + MediaPlayerPool& operator=(const MediaPlayerPool&)=delete; + static MediaPlayerPool* getInstance(){ + static MediaPlayerPool instance; + return &instance; + } + + MediaPlayerThread *getWorkerThread() const; + +signals: + + + +private: + void createQMediaPlayerPool(int size); + explicit MediaPlayerPool(int size=3,QObject *parent = nullptr); + ObjectPool * m_qMediaPlayerPool = nullptr; + int m_size=0; + MediaPlayerThread *workerThread = nullptr; + +}; + +#endif // MEDIAPLAYERPOOL_H diff --git a/mediaplayerthread.cpp b/mediaplayerthread.cpp new file mode 100644 index 0000000..3777ab7 --- /dev/null +++ b/mediaplayerthread.cpp @@ -0,0 +1,36 @@ +/* +* Copyright (C) 2020, 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 3, or (at your option) +* any later version. +* +* This program is distributed in the hope that it will be useful, +* but WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +* GNU General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, see + + + +MediaPlayerThread::MediaPlayerThread(int size, QObject *parent):QThread(parent),m_size(size) +{ + +} + +void MediaPlayerThread::run() +{ + qDebug()<<"dbq-开始创建对象池"< * que = new ObjectPool(m_size); + qint64 timeT2 = QDateTime::currentDateTime().toMSecsSinceEpoch(); + qDebug()<<"dbq-创建耗时"< +#include +#include +#include "object_pool.h" + +class MediaPlayerThread : public QThread +{ + Q_OBJECT +public: + explicit MediaPlayerThread(int size=3,QObject *parent = nullptr); + void run() override; + +signals: + void resultReady(ObjectPool * mediaPool); + +private: + int m_size=0; +}; + +#endif // MEDIAPLAYERTHREAD_H diff --git a/music.qrc b/music.qrc new file mode 100644 index 0000000..6f8ba1a --- /dev/null +++ b/music.qrc @@ -0,0 +1,5 @@ + + + music/FallenDown.mp3 + + diff --git a/music/bark.ogg b/music/bark.ogg new file mode 100644 index 0000000..480950c Binary files /dev/null and b/music/bark.ogg differ diff --git a/music/bark.wav b/music/bark.wav new file mode 100644 index 0000000..d6916de Binary files /dev/null and b/music/bark.wav differ diff --git a/music/drip.ogg b/music/drip.ogg new file mode 100644 index 0000000..144d2b3 Binary files /dev/null and b/music/drip.ogg differ diff --git a/music/drip.wav b/music/drip.wav new file mode 100644 index 0000000..1973f29 Binary files /dev/null and b/music/drip.wav differ diff --git a/music/glass.ogg b/music/glass.ogg new file mode 100644 index 0000000..902a3c8 Binary files /dev/null and b/music/glass.ogg differ diff --git a/music/glass.wav b/music/glass.wav new file mode 100644 index 0000000..397116d Binary files /dev/null and b/music/glass.wav differ diff --git a/music/sonar.ogg b/music/sonar.ogg new file mode 100644 index 0000000..77aadec Binary files /dev/null and b/music/sonar.ogg differ diff --git a/music/sonar.wav b/music/sonar.wav new file mode 100644 index 0000000..d38a823 Binary files /dev/null and b/music/sonar.wav differ diff --git a/noticeAlarm.cpp b/noticeAlarm.cpp new file mode 100644 index 0000000..e2f3d0f --- /dev/null +++ b/noticeAlarm.cpp @@ -0,0 +1,435 @@ +/* +* 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 3, or (at your option) +* any later version. +* +* This program is distributed in the hope that it will be useful, +* but WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +* GNU General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, see +#include +#include +#include +#include +#include +#include +#include "clockentitydao.h" +#include "xatom-helper.h" +#include "mediaplayerpool.h" +#include "gsettingsubject.h" +#include +#include + +extern void qt_blurImage(QImage &blurImage, qreal radius, bool quality, int transposed); +/** + * @brief + * @param + * @param num 闹钟序号 倒计时传-1 + * + * @return 返回说明 + */ +Natice_alarm::Natice_alarm(int close_time, int num, QWidget *parent , QString clockId) : + QWidget(parent), + ui(new Ui::Natice_alarm), + timer_value(close_time), + num_flag(num), + m_clockId(clockId) +{ + ui->setupUi(this); + m_musicPlayer = new MMediaPlayer(this); + m_playList = new MMediaPlaylist(m_musicPlayer); + m_playList->setPlaybackMode(MMediaPlaylist::CurrentItemInLoop); + Qt::WindowFlags m_flags = windowFlags(); + this->setWindowFlags(m_flags | Qt::WindowStaysOnTopHint); + + // 添加窗管协议 + XAtomHelper::setStandardWindowHint(this->winId()); + m_selectBtnUtil = new SelectBtnUtil(); + //响铃提示 + this->setWindowTitle(tr("Ring prompt")); + this->setWindowIcon(QIcon::fromTheme("kylin-alarm-clock")); + //多少秒后自动关闭 + ui->autoCloseTime->setAlignment(Qt::AlignRight); + QPalette pa; + pa.setColor(QPalette::WindowText,Qt::gray); + ui->autoCloseTime->setPalette(pa); + + //this->setProperty("blurRegion", QRegion(QRect(1, 1, 1, 1))); + //保存一个多少秒后关闭,用于稍后提醒的显式 + timer_value2 = timer_value; + //右上角关闭 + connect(ui->closeTitleBtn, SIGNAL(clicked()), this, SLOT(set_dialog_close()) ); + //稍后提醒 + connect(ui->remindLateBtn, SIGNAL(clicked()), this, SLOT(show_again()) ); + //进行 剩余秒数显示 的定时 + timer = new QTimer(); + //剩余秒 减1 + connect(timer, SIGNAL(timeout()), this, SLOT(close_music())); + timer->setInterval(1000); + + timer_xumhuan = new QTimer(); + //稍后提醒的定时 + connect(timer_xumhuan, SIGNAL(timeout()), this, SLOT(ring())); + timer_xumhuan->setInterval(1000); + model_clock = clock_sql::getClockTable(this); + natice_init(); + QPalette palette1 = ui->closeTitleBtn->palette(); + QColor ColorPlaceholderText1(255,255,255,0); + QBrush brush; + brush.setColor(ColorPlaceholderText1); + ui->closeTitleBtn->setPalette(palette1); + + ui->closeTitleBtn->setIcon(QIcon::fromTheme("window-close-symbolic")); + ui->closeTitleBtn->setProperty("isWindowButton", 0x2); + ui->closeTitleBtn->setProperty("useIconHighlightEffect", 0x8); + ui->closeTitleBtn->setFlat(true); + //启用主题框架不需要代码 + ui->titleIcon->setPixmap(QIcon::fromTheme("kylin-alarm-clock").pixmap(24,24)); + // 主题框架1.0.6-5kylin2 + + //配置重要按钮 关闭 + ui->remindLateBtn->setProperty("isImportant", true); + ui->closeTitleBtn->setFocusPolicy(Qt::NoFocus); + //数据库 + model_setup = clock_sql::getSetupTable(this); + //倒计时初始化无稍后提醒 + if(num_flag < 0){ + hideRemindBtn(); + } + settingsStyle(); +} + +void Natice_alarm::settingsStyle() +{ + + GsettingSubject * subject = GsettingSubject::getInstance(); + connect(subject,&GsettingSubject::fontChanged, this,[=](int size){ + this->CURRENT_FONT_SIZE=size; + this->updateFront(size); + }); + connect(subject,&GsettingSubject::iconChnaged, this,[=](){ + ui->titleIcon->setPixmap(QIcon::fromTheme("kylin-alarm-clock").pixmap(24,24)); + }); + subject->iniFontSize(); + +} + +void Natice_alarm::updateFront(int size) +{ + double font = 1.15; + int pointSize = round(font*size); + updateLabelFront(ui->titleLabel,pointSize); + updateLabelFront(ui->timeEndInfo,pointSize); + updateLabelFront(ui->autoCloseTime,pointSize); + QFont tempFont; + tempFont.setPixelSize(pointSize); + ui->remindLateBtn->setFont(tempFont); +} +void Natice_alarm::updateLabelFront(QLabel *label, int size) +{ + QString styleSheet = "font-size:"; + styleSheet.append(QString::number(size)).append("px;"); + label->setStyleSheet(styleSheet); +} + +Natice_alarm::~Natice_alarm() +{ + delete timer; + delete timer_xumhuan; + delete ui; +} +/** + * @brief 初始化铃声 + * @param + * @param + * + * @return 返回说明 + */ +void Natice_alarm::natice_init() +{ + if(num_flag >= 0) + { + auto sqlQuery = ClockEntityDao::getClockByPK(m_clockId); + //更新闹钟名称 + QString info = model_clock->index(num_flag, 0).data().toString(); + info = Utils::changeNumToStr(info.toInt()); + info = info.append(":"); + info = info.append(Utils::changeNumToStr(model_clock->index(num_flag, 1).data().toInt())); + info = info.append(" "); + QString clockName = model_clock->index(num_flag, 13).data().toString(); + int sizeLimit = 3; + if(clockName.length()>sizeLimit){ + //名字超长 + ui->timeEndInfo->setToolTip(info+clockName); + clockName = clockName.left(sizeLimit); + clockName = clockName+"..."; + } + info = info.append(clockName); + ui->timeEndInfo->setText(info); + //稍后提醒逻辑 + QString remindLate = model_clock->index(num_flag, 15).data().toString(); + if(remindLate=="none"||remindLate==tr("none")){ + hideRemindBtn(); + }else{ + showRemindBtn(); + } + } else { + //倒计时 + ui->timeEndInfo->setText(tr("Time out")+"!"); + } +} + +void Natice_alarm::closeMusic() +{ + +} +//重新加载最新音乐 +void Natice_alarm::refreshMusic() +{ + QSqlTableModel *model = new QSqlTableModel(this); + model->setTable("clock"); + model->setEditStrategy(QSqlTableModel::OnManualSubmit); + model->select(); + model_setup->select(); + QString bellId=""; + if(num_flag >= 0){ + auto sqlQuery = ClockEntityDao::getClockByPK(m_clockId); + bellId = sqlQuery.value( 2).toString(); + } else { + bellId = model_setup->index(0, 1).data().toString(); + } + QString noneId = m_selectBtnUtil->getBellIdByNameEn("none"); + if(bellId!=noneId){ + QString path = m_selectBtnUtil->getBellPathById(bellId); + m_playList->clear(); + m_playList->addMedia(QUrl::fromLocalFile(path)); + m_musicPlayer->setPlaylist(m_playList); + int muteOn = model_setup->index(0, 0).data().toInt(); + if(muteOn){ + qDebug()<<"dbq-静音"; + }else{ + m_musicPlayer->setVolume( 100 ); + m_musicPlayer->play(); + } + } +} + +void Natice_alarm::hideRemindBtn() +{ + ui->widget_3->hide(); + this->setFixedSize(288,90); + +} + +void Natice_alarm::showRemindBtn() +{ + ui->widget_3->show(); + this->setFixedSize(288,120); +} + +void Natice_alarm::playMusic() +{ + timer_value = timer_value2; + m_musicPlayer->setVolume(100); + timer->start(); + show(); + refreshMusic(); +} + +//窗口关闭 +/** + * @brief 铃声、窗体、timer关闭 + * @param + * @param + * + * @return 返回说明 + */ +void Natice_alarm::set_dialog_close() +{ + timer->stop(); + m_musicPlayer->stop(); + if(num_flag >= 0) + { + this->close(); + }else{ //倒计时的隐藏不关闭 + this->hide(); + } +} +//关闭音乐 +/** + * @brief 剩余时间读秒 全关闭 + * @param + * @param + * + * @return 返回说明 + */ +void Natice_alarm::close_music() +{ + if (timer_value == 0) { + set_dialog_close(); + } + timer_value--; + ui->autoCloseTime->setText(QString::number(timer_value)+tr(" Seconds to close")); +} +//绘制背景 +// Draw background +void Natice_alarm::paintEvent(QPaintEvent *event) +{ +// if (!full_flag) { +// return; +// } + + Q_UNUSED(event); + QPainter p(this); + p.setRenderHint(QPainter::Antialiasing); // 反锯齿; + QPainterPath rectPath; + rectPath.addRect(this->rect()); + p.fillPath(rectPath,palette().color(QPalette::Base)); + +} +//再次弹出 +//Eject again +void Natice_alarm::show_again() +{ + this->hide(); + //刷新数据 + model_setup->select(); + QString info = model_clock->index(num_flag, 15).data().toString(); + int remind = getRemindStatusByName(info); + if (remind == 1) { + ring_num = 300; + } else if(remind == 2) { + ring_num = 600; + } else if(remind == 3) { + ring_num = 1200; + } else if(remind == 4) { + ring_num = 1800; + } else if(remind == 5) { + ring_num = 3600; + } + timer_value = timer_value2; + timer_xumhuan->start(); + timer->stop(); + m_musicPlayer->stop(); +} + +int Natice_alarm::getRemindStatusByName(QString name) +{ + int status = 0; + if(name.compare("none") == 0 || name.compare("不需要") == 0){ + status = 0; + }else if(name.compare("five mins late") == 0 || name.compare("5分钟后") == 0){ + status = 1; + }else if(name.compare("ten mins late") == 0 || name.compare("10分钟后") == 0){ + status = 2; + }else if(name.compare("twenty mins late") == 0 || name.compare("20分钟后") == 0){ + status = 3; + }else if(name.compare("thirsty mins late") == 0 || name.compare("30分钟后") == 0){ + status = 4; + }else if(name.compare("one hour late") == 0 || name.compare("1小时后") == 0){ + status = 5; + } + return status; +} +//响铃 +//Ring a bell 每一秒减一 +void Natice_alarm::ring() +{ + ring_num--; + if (ring_num == 0) { + timer_xumhuan->stop(); + if(num_flag >= 0){ + bool result = ClockEntityDao::checkClockExist(m_clockId); + if(result){ + natice_init(); + this->show(); + timer->start(); + refreshMusic(); + }else{ + qDebug()<<"dbq-闹钟被删-啥也不做"; + } + }else{ + natice_init(); + this->show(); + timer->start(); + refreshMusic(); + } + + } +} + + +//bool Natice_alarm::eventFilter(QObject *watched, QEvent *event) +//{ +// if(watched == ui->widget && event->type() == QEvent::Paint) +// { +// showPaint(); //响应函数 +// } +// return QWidget::eventFilter(watched,event); +//} + +////实现响应函数 +//void Natice_alarm::showPaint() +//{ +// QPainter p(ui->widget); +// p.setRenderHint(QPainter::Antialiasing); // 反锯齿; +// QPainterPath rectPath; +// rectPath.addRoundedRect(ui->widget->rect().adjusted(6, 6, -6, -6), 6, 6); + +// // 画一个黑底 +// QPixmap pixmap(ui->widget->rect().size()); +// pixmap.fill(Qt::transparent); +// QPainter pixmapPainter(&pixmap); +// pixmapPainter.setRenderHint(QPainter::Antialiasing); +// pixmapPainter.setPen(Qt::transparent); +// pixmapPainter.setBrush(Qt::gray); +// pixmapPainter.drawPath(rectPath); +// pixmapPainter.end(); + +// // 模糊这个黑底 +// QImage img = pixmap.toImage(); +// qt_blurImage(img, 10, false, false); + +// // 挖掉中心 +// pixmap = QPixmap::fromImage(img); +// QPainter pixmapPainter2(&pixmap); +// pixmapPainter2.setRenderHint(QPainter::Antialiasing); +// pixmapPainter2.setCompositionMode(QPainter::CompositionMode_Clear); +// pixmapPainter2.setPen(Qt::transparent); +// pixmapPainter2.setBrush(QColor(0,0,0)); +// pixmapPainter2.drawPath(rectPath); + +// // 绘制阴影 +// p.drawPixmap(ui->widget->rect(), pixmap, pixmap.rect()); +// p.setOpacity(0.9); +// // 绘制一个背景 +// p.save(); +// p.fillPath(rectPath,palette().color(QPalette::Base)); +// p.restore(); +//} + + +void Natice_alarm::closeEvent(QCloseEvent *event) +{ + timer->stop(); + m_musicPlayer->stop(); + if(num_flag >= 0) + { + event->accept();//接受 + this->close(); + }else{ + event->ignore();//忽视 + this->hide(); + } +} diff --git a/noticeAlarm.h b/noticeAlarm.h new file mode 100644 index 0000000..8c6bd55 --- /dev/null +++ b/noticeAlarm.h @@ -0,0 +1,104 @@ +/* +* 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 3, or (at your option) +* any later version. +* +* This program is distributed in the hope that it will be useful, +* but WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +* GNU General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, see +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "selectbtnutil.h" +#include +#include "coreplayer/playcontroller.h" +namespace Ui { +class Natice_alarm; +} +/** + * @brief 右下角通知弹窗 + */ +class Natice_alarm : public QWidget +{ + Q_OBJECT + +public: + explicit Natice_alarm( int close_time, int num,QWidget *parent = nullptr,QString clockId = nullptr); + ~Natice_alarm(); + Ui::Natice_alarm *ui; + + //bool eventFilter(QObject *watched, QEvent *event); + void showPaint(); + void closeEvent(QCloseEvent *event); + + QTimer *timer = nullptr; + QTimer *timer_xumhuan = nullptr; +// QMediaPlayer *music; + MMediaPlayer* m_musicPlayer = nullptr; + MMediaPlaylist* m_playList = nullptr; + int timer_value; + + void refreshMusic(); + void hideRemindBtn(); + void showRemindBtn(); + void playMusic(); + +protected: + //绘制背景 + // Draw background + void paintEvent(QPaintEvent *); + +private slots: + //窗口关闭 window closing + void set_dialog_close(); + //关闭音乐 Turn off music + void close_music(); + //再次弹出 Eject again + void show_again(); + //响铃 Ring a bell + void ring(); + +private: + void natice_init(); + void closeMusic(); + + int num_flag; +// QMediaPlaylist *playlist; + int ring_num; + int timer_value2; + int full_flag=1; + QSqlTableModel *model_setup; + QPoint dragPosition; //拖动坐标 + bool mousePressed; //鼠标是否按下 + QString m_clockId; + QSqlTableModel *model_clock; + SelectBtnUtil * m_selectBtnUtil = nullptr; + int CURRENT_FONT_SIZE; + + int getRemindStatusByName(QString name); + void settingsStyle(); + void updateFront(int size); + void updateLabelFront(QLabel *label, int size); +}; + +#endif // NATICE_ALARM_H diff --git a/noticeAlarm.ui b/noticeAlarm.ui new file mode 100644 index 0000000..8cc09b6 --- /dev/null +++ b/noticeAlarm.ui @@ -0,0 +1,348 @@ + + + Natice_alarm + + + + 0 + 0 + 288 + 120 + + + + Form + + + + 0 + + + 0 + + + 0 + + + 0 + + + 0 + + + + + + 0 + 0 + + + + + 16800 + 16800 + + + + + + + + 0 + + + 0 + + + 8 + + + + + + 0 + 0 + + + + + 16777215 + 16777215 + + + + + 5 + + + 5 + + + 5 + + + + + + 24 + 24 + + + + + 24 + 24 + + + + + + + + + + + + 100 + 22 + + + + + 100 + 22 + + + + + + + Alarm clock + + + + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + + 24 + 24 + + + + + 24 + 24 + + + + + + + + + + + + + + + + + + 0 + 0 + + + + + 0 + 35 + + + + + 16777215 + 16777215 + + + + + 0 + + + 11 + + + 0 + + + 11 + + + 0 + + + + + + 0 + 0 + + + + + 90 + 25 + + + + + 110 + 25 + + + + + -1 + + + + font-size:11px + + + 11:20 设计例会... + + + Qt::AlignLeading|Qt::AlignLeft|Qt::AlignVCenter + + + + + + + + 0 + 0 + + + + + 90 + 25 + + + + + 16777215 + 25 + + + + + 9 + + + + + + + + + + + + + + + 0 + 0 + + + + + 0 + 35 + + + + + 0 + + + 0 + + + 0 + + + 11 + + + 0 + + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + + 0 + 0 + + + + + 85 + 34 + + + + + 120 + 34 + + + + Qt::LeftToRight + + + Remind later + + + + + + + + + + + + + + diff --git a/notice_dialog.ui b/notice_dialog.ui new file mode 100644 index 0000000..60b884e --- /dev/null +++ b/notice_dialog.ui @@ -0,0 +1,192 @@ + + + Notice_Dialog + + + + 0 + 0 + 529 + 342 + + + + Dialog + + + background-color: rgb(83, 83, 83); + + + + + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + font: 25 28pt "Noto Sans CJK SC"; +color: rgb(39, 207, 129); + + + + + + + + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + + + font: 87 28pt "Noto Sans CJK SC"; +color: rgb(39, 207, 129); + + + + + 秒后关闭铃声 + + + + + + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + + + Qt::Vertical + + + + 20 + 40 + + + + + + + + + + color: rgb(39, 207, 129); + + + 闹钟: + + + + + + + color: rgb(39, 207, 129); + + + 起床铃 + + + + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + + 30 + 30 + + + + background-color: rgb(83, 83, 83); + + + + + + + + + + + + Qt::Vertical + + + + 20 + 40 + + + + + + + + + diff --git a/object_pool.h b/object_pool.h new file mode 100644 index 0000000..f18749f --- /dev/null +++ b/object_pool.h @@ -0,0 +1,66 @@ +/* +* Copyright (C) 2020, 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 3, or (at your option) +* any later version. +* +* This program is distributed in the hope that it will be useful, +* but WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +* GNU General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, see +template +class ObjectPool +{ +public: + ObjectPool(size_t unSize):m_unSize(unSize) + { + for(size_t unIdx=0;unIdx::iterator iter=m_oPool.begin(); + while(iter!=m_oPool.end()) + { + delete(*iter); + ++iter; + } + m_unSize=0; + } + Object* GetObject() + { + Object* pObj=NULL; + if(0==m_unSize) + { + pObj=new Object(); + } + else + { + pObj=m_oPool.front(); + m_oPool.pop_front(); + --m_unSize; + } + return pObj; + } + void returnObject(Object* pObj) + { + m_oPool.push_back(pObj); + ++m_unSize; + } +private: + size_t m_unSize; + std::listm_oPool; +}; +#endif // OBJECT_POOL_H diff --git a/primarymanager.cpp b/primarymanager.cpp new file mode 100644 index 0000000..afa65c7 --- /dev/null +++ b/primarymanager.cpp @@ -0,0 +1,180 @@ +#include "primarymanager.h" + + + + +PrimaryManager::PrimaryManager() +{ + this->m_on_wayland = checkWayland(); + if(m_on_wayland){ + //支持 wayland + mDbusXrandInter = new QDBusInterface(DBUS_NAME, + DBUS_PATH, + DBUS_INTERFACE, + QDBusConnection::sessionBus()); + this->m_nScreen_x = getScreenGeometry("x"); + this->m_nScreen_y = getScreenGeometry("y"); + this->m_screenWidth = getScreenGeometry("width"); + this->m_screenHeight = getScreenGeometry("height"); + qDebug("初始化, geometry is x=%d, y=%d, width=%d, height=%d", m_nScreen_x, m_nScreen_y, m_screenWidth, m_screenHeight); + /*监听dbus变化 更改主屏幕时,会进行信号发送 */ + connect(mDbusXrandInter, SIGNAL(screenPrimaryChanged(int,int,int,int)), + this, SLOT(priScreenChanged(int,int,int,int))); + }else{ + //不支持 wayland + m_pDeskWgt = QApplication::desktop(); + m_adaptScreenInfo = new adaptScreenInfo(); + updateInfoByAdapt(); + //当改变屏幕分辨率时 重新计算 主屏坐标 屏幕宽高 + connect(QApplication::primaryScreen(), &QScreen::geometryChanged, this, &PrimaryManager::updateInfoByAdapt); + //主屏发生变化槽函数 重新计算 主屏坐标 屏幕宽高 + connect(m_pDeskWgt, &QDesktopWidget::primaryScreenChanged, this, &PrimaryManager::updateInfoByAdapt); + //屏幕数量改变时 重新计算 主屏坐标 屏幕宽高 + connect(m_pDeskWgt, &QDesktopWidget::screenCountChanged, this, &PrimaryManager::updateInfoByAdapt); + } + +} +/** + * @brief 主屏幕变化监听函数 + */ +void PrimaryManager::priScreenChanged(int x, int y, int width, int height) +{ + QString priName; + priName = getScreenName ("priScreenName"); + this->m_nScreen_x=x; + this->m_nScreen_y=y; + this->m_screenWidth=width; + this->m_screenHeight=height; + qDebug("primary screen changed, geometry is x=%d, y=%d, width=%d, height=%d", x, y, width, height); +} +/** + * @brief 根据adaptScreenInfo更新数据 + */ +void PrimaryManager::updateInfoByAdapt() +{ + this->m_nScreen_x = m_adaptScreenInfo->m_nScreen_x; + this->m_nScreen_y = m_adaptScreenInfo->m_nScreen_y; + this->m_screenWidth = m_adaptScreenInfo->m_screenWidth; + this->m_screenHeight = m_adaptScreenInfo->m_screenHeight; +} +/** + * @brief 启动获取主屏幕坐标 x/y/width/height; 以及基于Kscreen获取的主屏幕名字 + */ +void PrimaryManager::start() +{ + int priX, priY, priWid, priHei; + QString priName; + priX = getScreenGeometry("x"); + priY = getScreenGeometry("y"); + priWid = getScreenGeometry("width"); + priHei = getScreenGeometry("height"); + priName = getScreenName ("priScreenName"); + + qDebug("Start: Primary screen geometry is x=%d, y=%d, width=%d, height=%d,", + priX, priY, priWid, priHei); + qDebug()<<"Primary screen name = " << priName; +} +/** + * @brief 根据dbus 提供method 获取X/Y/width/height 参数 + */ +int PrimaryManager::getScreenGeometry(QString methodName) +{ + int res = 0; + QDBusMessage message = QDBusMessage::createMethodCall(DBUS_NAME, + DBUS_PATH, + DBUS_INTERFACE, + methodName); + QDBusMessage response = QDBusConnection::sessionBus().call(message); + if (response.type() == QDBusMessage::ReplyMessage) + { + if(response.arguments().isEmpty() == false) { + int value = response.arguments().takeFirst().toInt(); + res = value; + qDebug() << value; + } + } else { + qDebug()<geometry().x() == dX && screen->geometry().y() == dY) { + mPriScreen = screen; + } + } +} + +PrimaryManager::~PrimaryManager() +{ + delete mDbusXrandInter; + delete m_adaptScreenInfo; +} + +int PrimaryManager::getScreenWidth() const +{ + return m_screenWidth; +} + +int PrimaryManager::getScreenHeight() const +{ + return m_screenHeight; +} + +int PrimaryManager::getNScreen_x() const +{ + return m_nScreen_x; +} + +int PrimaryManager::getNScreen_y() const +{ + return m_nScreen_y; +} +/** + * @brief 根据环境变量判断是否支持wayland + */ +bool PrimaryManager::checkWayland() +{ + QByteArray byte = qgetenv("DESKTOP_SESSION"); + QString info =QString::fromLocal8Bit(byte); + if("ukui-wayland"==info){ + return true; + }else{ + return false; + } +} diff --git a/primarymanager.h b/primarymanager.h new file mode 100644 index 0000000..ffff36f --- /dev/null +++ b/primarymanager.h @@ -0,0 +1,69 @@ +/* +* Copyright (C) 2020, 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 3, or (at your option) +* any later version. +* +* This program is distributed in the hope that it will be useful, +* but WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +* GNU General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, see +#include +#include +#include +#include +#include "adaptscreeninfo.h" + +#define DBUS_NAME "org.ukui.SettingsDaemon" // dbus 服务名字 +#define DBUS_PATH "/org/ukui/SettingsDaemon/wayland" // dbus 路径 +#define DBUS_INTERFACE "org.ukui.SettingsDaemon.wayland" // dbus 接口 + + + +class PrimaryManager:public QObject +{ + Q_OBJECT +public: + PrimaryManager(); + + void start(); + int getScreenGeometry(QString methodName); + QString getScreenName(QString methodName); + void init(); + ~PrimaryManager(); + + int getScreenWidth() const; + + int getScreenHeight() const; + + int getNScreen_x() const; + + int getNScreen_y() const; + bool checkWayland(); +public slots: + void priScreenChanged(int x, int y, int width, int height); +private: + QDBusInterface *mDbusXrandInter; + int m_screenWidth; // 桌面宽度 + int m_screenHeight; // 桌面高度 + int m_screenNum; // 屏幕数量 + int m_nScreen_x; // 主屏起始坐标X + int m_nScreen_y; // 主屏起始坐标Y + bool m_on_wayland; //是否是wayland + QDesktopWidget * m_pDeskWgt; + adaptScreenInfo * m_adaptScreenInfo = nullptr; + void updateInfoByAdapt(); + +}; + +#endif // PRIMARYMANAGER_H diff --git a/qroundProgressBar.cpp b/qroundProgressBar.cpp new file mode 100644 index 0000000..42a09f4 --- /dev/null +++ b/qroundProgressBar.cpp @@ -0,0 +1,391 @@ +/* + * QRoundProgressBar - a circular progress bar Qt widget. + * + * Sintegrial Technologies (c) 2015-now + * + * The software is freeware and is distributed "as is" with the complete source codes. + * Anybody is free to use it in any software projects, either commercial or non-commercial. + * Please do not remove this copyright message and remain the name of the author unchanged. + * + * It is very appreciated if you produce some feedback to us case you are going to use + * the software. + * + * Please send your questions, suggestions, and information about found issues to the + * + * sintegrial@gmail.com + * + */ + + +#include "qroundProgressBar.h" + +#include +#include +#include +#include +//#include + + +QRoundProgressBar::QRoundProgressBar(QWidget *parent) : + QWidget(parent), + m_min(0), m_max(100), + m_value(25), + m_nullPosition(PositionTop), + m_barStyle(StyleDonut), + m_outlinePenWidth(0.96), + m_dataPenWidth(1), + m_rebuildBrush(false), + m_format("%p%"), + m_decimals(1), + m_updateFlags(UF_PERCENT) +{ + settingsStyle(); +} + +void QRoundProgressBar::setRange(double min, double max) +{ + m_min = min; + m_max = max; + + if (m_max < m_min) + qSwap(m_max, m_min); + + if (m_value < m_min) + m_value = m_min; + else if (m_value > m_max) + m_value = m_max; + + if (!m_gradientData.isEmpty()) + m_rebuildBrush = true; + + update(); +} + +void QRoundProgressBar::setMinimum(double min) +{ + setRange(min, m_max); +} + +void QRoundProgressBar::setMaximum(double max) +{ + setRange(m_min, max); +} + +void QRoundProgressBar::setValue(double val) +{ + if (m_value != val) { + if (val < m_min) + m_value = m_min; + else if (val > m_max) + m_value = m_max; + else + m_value = val; + update(); + } +} + +//定义最小值位置 +void QRoundProgressBar::setNullPosition(double position) +{ + if (position != m_nullPosition) { + m_nullPosition = position; + if (!m_gradientData.isEmpty()) + m_rebuildBrush = true; + update(); + } +} +//设置视觉样式圆环(甜甜圈)风格、饼(派)风格、线型 +void QRoundProgressBar::setBarStyle(QRoundProgressBar::BarStyle style) +{ + if (style != m_barStyle) { + m_barStyle = style; + update(); + } +} +//设置轮廓圆笔的宽度。 +void QRoundProgressBar::setOutlinePenWidth(double penWidth) +{ + if (penWidth != m_outlinePenWidth) { + m_outlinePenWidth = penWidth; + update(); + } +} +//设置数据圆笔的宽度。 +void QRoundProgressBar::setDataPenWidth(double penWidth) +{ + if (penWidth != m_dataPenWidth) { + m_dataPenWidth = penWidth; + update(); + } +} +//设置可见数据的颜色,并使用它们制作渐变画笔。 +//此函数将覆盖widget的`palette()`来设置动态创建的渐变笔刷 +void QRoundProgressBar::setDataColors(const QGradientStops &stopPoints) +{ + if (stopPoints != m_gradientData) { + m_gradientData = stopPoints; + m_rebuildBrush = true; + update(); + } +} +//定义用于生成当前文本的字符串。 +//%p-用完成的百分比代替。 %v-由当前值替换。 %m-由最大值代替。 +//默认值为“%p%” +void QRoundProgressBar::setFormat(const QString &format) +{ + if (format != m_format) { + m_format = format; + + valueFormatChanged(); + } +} +//将格式字符串设置为空字符串。 因此,将不会显示任何文本。 +void QRoundProgressBar::resetFormat() +{ + m_format = QString::null; + valueFormatChanged(); +} +//设置要在逗号后显示的小数位数(默认为1)。 +void QRoundProgressBar::setDecimals(int count) +{ + if (count >= 0 && count != m_decimals) { + m_decimals = count; + valueFormatChanged(); + } +} + +void QRoundProgressBar::paintEvent(QPaintEvent* /*event*/) +{ + //构造和自定义(例如,设置笔或画笔)painter。 然后画。 记住在绘制后销毁QPainter对象。 + QPainter painter(this); + painter.save(); + //mainColor 在settingsStyle配置 + painter.setPen(mainColor); + painter.setBrush(mainColor); + //在指定的boundingRectangle中创建一个椭圆,并将其作为封闭的子路径添加到painter路径。 + QPainterPath bigCircle; + bigCircle.addEllipse(65, 13, 266, 266); + QPainterPath path = bigCircle ; + painter.drawPath(path); + //保存当前的画家状态(将状态推送到堆栈上)。 在save()之后必须有一个相应的restore(); end()函数展开堆栈。 + painter.restore(); + + double outerRadius = 133; + QRectF baseRect(198 - outerRadius, 146 - outerRadius, outerRadius * 2, outerRadius * 2); + QPainter p(this); + //表示引擎应尽可能对图元的边缘进行抗锯齿。 + p.setRenderHint(QPainter::Antialiasing); + // data brush + rebuildDataBrushIfNeeded(); + // background + drawBackground(p, rect()); + double innerRadius = 133; + QRectF innerRect = QRectF((198 - outerRadius) + 5, (146 - outerRadius) + 5, (outerRadius - 5) * 2 , (outerRadius - 5) * 2 ); + + //calculateInnerRect(baseRect, outerRadius, innerRect, innerRadius); + double arcStep = 360.0 / (m_max - m_min) * m_value; + // base circle + drawBase(p, baseRect,innerRect); + // data circle + drawValue(p, baseRect, m_value, arcStep,innerRect, innerRadius); + // finally draw the bar + p.end(); +} + +//背景色 +void QRoundProgressBar::drawBackground(QPainter &p, const QRectF &baseRect) +{ + p.fillRect(baseRect, palette().background()); +} + +//画基础 +void QRoundProgressBar::drawBase(QPainter &p, const QRectF &baseRect,const QRectF &innerRect) +{ + + QStyleOption opt; + opt.init(this); + switch (m_barStyle) + { + case StyleDonut: +// p.setPen(QPen(QColor(160, 160, 160), 4, Qt::DotLine, Qt::RoundCap, Qt::RoundJoin)); +// p.setBrush(Qt::NoBrush); +// p.drawEllipse(QPointF(227, 180),155,155); + break; + case StylePie: + p.setPen(QPen(palette().base().color(), m_outlinePenWidth, Qt::DotLine, Qt::RoundCap, Qt::RoundJoin)); + p.setBrush(palette().base()); + p.drawEllipse(baseRect); + break; + case StyleLine: + p.setPen(QPen(palette().base().color(), m_outlinePenWidth ,Qt::DotLine, Qt::RoundCap, Qt::RoundJoin)); + p.setBrush(Qt::NoBrush); + p.drawEllipse(baseRect.adjusted(m_outlinePenWidth/2, m_outlinePenWidth/2, -m_outlinePenWidth/2, -m_outlinePenWidth/2)); + break; + default:; + } +} +//画数据 +void QRoundProgressBar::drawValue(QPainter &p + , const QRectF &baseRect + , double value + , double arcLength + , const QRectF & innerRect + , double innerRadius) +{ + // nothing to draw + if (value == m_min) + return; + + // for Pie and Donut styles + QPainterPath dataPath; + dataPath.setFillRule(Qt::WindingFill); + dataPath.moveTo(baseRect.center()); + dataPath.arcTo(baseRect, m_nullPosition, -arcLength);//大家都是先绘制外圆的弧长 + + if(m_barStyle == StyleDonut) { + // draw dount outer + QPointF currentPoint = dataPath.currentPosition();//绘制完外圆弧长后,获取绘制完的位置绘制一个直线到达内圆 + currentPoint = baseRect.center() + (currentPoint - baseRect.center()) * m_innerOuterRate;//计算内圆的坐标点,m_innerOuterRate替代了原作者写的0.75,代表内圆是外圆的0.75倍 + dataPath.lineTo(currentPoint);//绘制外圆到内圆的直线 + dataPath.moveTo(baseRect.center());//坐标点回到中心准备绘制内圆弧形 + dataPath.arcTo(innerRect, m_nullPosition-arcLength, arcLength);//绘制内圆的弧形 + currentPoint = dataPath.currentPosition();//准备绘制内圆到外圆的直线,形成封闭区域 + currentPoint = baseRect.center() + ((currentPoint - baseRect.center()) * (2-m_innerOuterRate));//绘制内圆到外圆的直线,这里2-m_innerOuterRate其实是对应(1 + (1 -m_innerOuterRate))的 + dataPath.lineTo(currentPoint); + p.setPen(Qt::NoPen);//这个很重要不然就会有绘制过程的一些轮廓了 + } + + p.setBrush(palette().highlight()); + p.setBrush(ringRunColor); + + p.drawPath(dataPath); +} + +void QRoundProgressBar::calculateInnerRect(const QRectF &/*baseRect*/, double outerRadius, QRectF &innerRect, double &innerRadius) +{ + // for Line style + if (m_barStyle == StyleLine) { + innerRadius = outerRadius - m_outlinePenWidth; + } else { + innerRadius = outerRadius * m_outlinePenWidth; + } + + double delta = (outerRadius - innerRadius) / 2; + innerRect = QRectF(delta, delta, innerRadius, innerRadius); +// innerRect = QRectF(227 - outerRadius, 220 - outerRadius, innerRadius * 2, innerRadius * 2); +} + +void QRoundProgressBar::drawInnerBackground(QPainter &p, const QRectF &innerRect) +{ + if (m_barStyle == StyleDonut) { + p.setBrush(palette().alternateBase()); + p.drawEllipse(innerRect); + } +} + +void QRoundProgressBar::drawText(QPainter &p, const QRectF &innerRect, double innerRadius, double value) +{ + if (m_format.isEmpty()) + return; + + // !!! to revise + QFont f(font()); + f.setPixelSize(innerRadius * qMax(0.05, (0.35 - (double)m_decimals * 0.08))); + p.setFont(f); + + QRectF textRect(innerRect); + p.setPen(palette().text().color()); + p.drawText(textRect, Qt::AlignCenter, valueToText(value)); +} + +QString QRoundProgressBar::valueToText(double value) const +{ + QString textToDraw(m_format); + + if (m_updateFlags & UF_VALUE) + textToDraw.replace("%v", QString::number(value, 'f', m_decimals)); + + if (m_updateFlags & UF_PERCENT) { + double procent = (value - m_min) / (m_max - m_min) * 100.0; + textToDraw.replace("%p", QString::number(procent, 'f', m_decimals)); + } + + if (m_updateFlags & UF_MAX) + textToDraw.replace("%m", QString::number(m_max - m_min + 1, 'f', m_decimals)); + return textToDraw; +} + +void QRoundProgressBar::valueFormatChanged() +{ + m_updateFlags = 0; + + if (m_format.contains("%v")) + m_updateFlags |= UF_VALUE; + if (m_format.contains("%p")) + m_updateFlags |= UF_PERCENT; + if (m_format.contains("%m")) + m_updateFlags |= UF_MAX; + update(); +} + +void QRoundProgressBar::rebuildDataBrushIfNeeded() +{ + if (m_rebuildBrush) { + m_rebuildBrush = false; + QConicalGradient dataBrush; + dataBrush.setCenter(0.5,0.5); + dataBrush.setCoordinateMode(QGradient::StretchToDeviceMode); + // invert colors + for (int i = 0; i < m_gradientData.count(); i++) { + dataBrush.setColorAt(1.0 - m_gradientData.at(i).first, m_gradientData.at(i).second); + } + // angle + dataBrush.setAngle(m_nullPosition); + QPalette p(palette()); + p.setBrush(QPalette::Window,Qt::NoBrush); + p.setBrush(QPalette::AlternateBase,Qt::NoBrush); + p.setBrush(QPalette::Highlight, dataBrush); + setPalette(p); + } +} + +QColor QRoundProgressBar::getRingRunColor() const +{ + return ringRunColor; +} + +void QRoundProgressBar::setRingRunColor(const QColor &value) +{ + ringRunColor = value; +} + +void QRoundProgressBar::switchRunRingColor() +{ + ringRunColor = QColor(55, 144, 250,255); + update(); +} + +void QRoundProgressBar::switchStopRingColor() +{ + ringRunColor = QColor(69, 173, 110,255); + update(); +} + +/* +*监听主题 +*/ +void QRoundProgressBar::settingsStyle() +{ + + GsettingSubject * subject = GsettingSubject::getInstance();; + connect(subject,&GsettingSubject::blackStyle, this,[=](){ + mainColor = QColor(255, 255, 255, 40); + }); + connect(subject,&GsettingSubject::whiteStyle, this,[=](){ + mainColor = QColor(255, 255, 255, 107); + }); + subject->iniWidgetStyle(); + +} + + diff --git a/qroundProgressBar.h b/qroundProgressBar.h new file mode 100644 index 0000000..65a7936 --- /dev/null +++ b/qroundProgressBar.h @@ -0,0 +1,271 @@ +/* + * QRoundProgressBar - a circular progress bar Qt widget. + * + * Sintegrial Technologies (c) 2015-now + * + * The software is freeware and is distributed "as is" with the complete source codes. + * Anybody is free to use it in any software projects, either commercial or non-commercial. + * Please do not remove this copyright message and remain the name of the author unchanged. + * + * It is very appreciated if you produce some feedback to us case you are going to use + * the software. + * + * Please send your questions, suggestions, and information about found issues to the + * + * sintegrial@gmail.com + * + */ + +#ifndef QROUNDPROGRESSBAR_H +#define QROUNDPROGRESSBAR_H + +#include +#include +#include +#include "constant_class.h" +#include "gsettingsubject.h" + +/** + * @brief The QRoundProgressBar class represents a circular progress bar and maintains its API + * similar to the *QProgressBar*. + * + * ### Styles + * QRoundProgressBar currently supports Donut, Pie and Line styles. See setBarStyle() for more details. + * + * ### Colors + * Generally QRoundProgressBar uses its palette and font attributes to define how it will look. + * + * The following \a QPalette members are considered: + * - *QPalette::Window* background of the whole widget (normally should be set to Qt::NoBrush) + * - *QPalette::Base* background of the non-filled progress bar area (should be set to Qt::NoBrush to make it transparent) + * - *QPalette::AlternateBase* background of the central circle where the text is shown (for \a Donut style) + * - *QPalette::Shadow* foreground of the non-filled progress bar area (i.e. border color) + * - *QPalette::Highlight* background of the filled progress bar area + * - *QPalette::Text* color of the text shown in the center + * + * Create a \a QPalette with given attributes and apply it via `setPalette()`. + * + * ### Color gradient + * \a Donut and \a Pie styles allow to use color gradient for currernt value area instead of plain brush fill. + * See setDataColors() for more details. + * + * ### Value text + * Value text is generally drawn inside the QRoundProgressBar using its `font()` and \a QPalette::Text role from its `palette()`. + * + * To define pattern of the text, use setFormat() function (see Qt's \a QProgressBar for more details). + * + * To define number of decimals to be shown, use setDecimals() function. + * + * ### Font + * To use own font for value text, apply it via `setFont()`. + * + * By default, font size will be adjusted automatically to fit the inner circle of the widget. + */ + + +class QRoundProgressBar : public QWidget +{ + Q_OBJECT +public: + explicit QRoundProgressBar(QWidget *parent = 0); + + static const int PositionLeft = 90; + static const int PositionTop = 90; + static const int PositionRight = 0; + static const int PositionBottom = -90; + + /** + * @brief Return position (in degrees) of minimum value. + * \sa setNullPosition + */ + double nullPosition() const { return m_nullPosition; } + /** + * @brief Defines position of minimum value. + * @param position position on the circle (in degrees) of minimum value + * \sa nullPosition + */ + void setNullPosition(double position); + + /** + * @brief The BarStyle enum defines general look of the progress bar. + */ + enum BarStyle + { + /// Donut style (filled torus around the text) + StyleDonut, + /// Pie style (filled pie segment with the text in center) + StylePie, + /// Line style (thin round line around the text) + StyleLine + }; + /** + * @brief Sets visual style of the widget. + * \sa barStyle + */ + void setBarStyle(BarStyle style); + /** + * @brief Returns current progree bar style. + * \sa setBarStyle + */ + BarStyle barStyle() const { return m_barStyle; } + + /** + * @brief Sets width of the outline circle pen. + * @param penWidth width of the outline circle pen (in pixels) + */ + void setOutlinePenWidth(double penWidth); + /** + * @brief Returns width of the outline circle pen. + */ + double outlinePenWidth() const { return m_outlinePenWidth; } + + /** + * @brief Sets width of the data circle pen. + * @param penWidth width of the data circle pen (in pixels) + */ + void setDataPenWidth(double penWidth); + /** + * @brief Returns width of the data circle pen. + */ + double dataPenWidth() const { return m_dataPenWidth; } + + /** + * @brief Sets colors of the visible data and makes gradient brush from them. + * Gradient colors can be set for \a Donut and \a Pie styles (see setBarStyle() function). + * + * *Warning*: this function will override widget's `palette()` to set dynamically created gradient brush. + * + * @param stopPoints List of colors (should have at least 2 values, see Qt's \a QGradientStops for more details). + * Color value at point 0 corresponds to the minimum() value, while color value at point 1 + * corresponds to the maximum(). Other colors will be distributed accordingly to the defined ranges (see setRange()). + */ + void setDataColors(const QGradientStops& stopPoints); + + /** + * @brief Defines the string used to generate the current text. + * If no format is set, no text will be shown. + * @param format see \a QProgressBar's format description + * \sa setDecimals + */ + void setFormat(const QString& format); + /** + * @brief Sets format string to empty string. No text will be shown therefore. + * See setFormat() for more information. + */ + void resetFormat(); + /** + * @brief Returns the string used to generate the current text. + */ + QString format() const { return m_format; } + + /** + * @brief Sets number of decimals to show after the comma (default is 1). + * \sa setFormat + */ + void setDecimals(int count); + /** + * @brief Returns number of decimals to show after the comma (default is 1). + * \sa setFormat, setDecimals + */ + int decimals() const { return m_decimals; } + + /** + * @brief Returns current value shown on the widget. + * \sa setValue() + */ + double value() const { return m_value; } + /** + * @brief Returns minimum of the allowed value range. + * \sa setMinimum, setRange + */ + double minimum() const { return m_min; } + /** + * @brief Returns maximum of the allowed value range. + * \sa setMaximum, setRange + */ + double maximum() const { return m_max; } + double time_max = 10000; + double ring_max = 3600; + + QColor getRingRunColor() const; + void setRingRunColor(const QColor &value); + void switchRunRingColor(); + void switchStopRingColor(); + +public Q_SLOTS: + /** + * @brief Defines minimum und maximum of the allowed value range. + * If the current value does not fit into the range, it will be automatically adjusted. + * @param min minimum of the allowed value range + * @param max maximum of the allowed value range + */ + void setRange(double min, double max); + /** + * @brief Defines minimum of the allowed value range. + * If the current value does not fit into the range, it will be automatically adjusted. + * @param min minimum of the allowed value range + * \sa setRange + */ + void setMinimum(double min); + /** + * @brief Defines maximum of the allowed value range. + * If the current value does not fit into the range, it will be automatically adjusted. + * @param max maximum of the allowed value range + * \sa setRange + */ + void setMaximum(double max); + /** + * @brief Sets a value which will be shown on the widget. + * @param val must be between minimum() and maximum() + */ + void setValue(double val); + + + void settingsStyle(); +protected: + + virtual void paintEvent(QPaintEvent *event); + virtual void drawBackground(QPainter& p, const QRectF& baseRect); + //virtual void drawBase(QPainter& p, const QRectF& baseRect); + virtual void drawBase(QPainter &p, const QRectF &baseRect,const QRectF &innerRect); + //virtual void drawValue(QPainter& p, const QRectF& baseRect, double value, double arcLength); + virtual void drawValue(QPainter& p, const QRectF& baseRect, double value, double arcLength, const QRectF & innerRect, double innerRadius); + virtual void calculateInnerRect(const QRectF& baseRect, double outerRadius, QRectF& innerRect, double& innerRadius); + virtual void drawInnerBackground(QPainter& p, const QRectF& innerRect); + virtual void drawText(QPainter& p, const QRectF& innerRect, double innerRadius, double value); + virtual QString valueToText(double value) const; + virtual void valueFormatChanged(); + + virtual QSize minimumSizeHint() const { return QSize(32,32); } + + virtual bool hasHeightForWidth() const { return true; } + virtual int heightForWidth(int w) const { return w; } + + void rebuildDataBrushIfNeeded(); + + double m_min, m_max; + double m_value; + + double m_nullPosition; + BarStyle m_barStyle; + double m_outlinePenWidth, m_dataPenWidth; + + QGradientStops m_gradientData; + bool m_rebuildBrush; + + QString m_format; + int m_decimals; + + static const int UF_VALUE = 1; + static const int UF_PERCENT = 2; + static const int UF_MAX = 4; + int m_updateFlags; + + float m_innerOuterRate = 1; + QStyleOption opt; + QColor mainColor; +private: + QColor ringRunColor = QColor(55, 144, 250,255); +}; + +#endif // QROUNDPROGRESSBAR_H diff --git a/roundbtn.cpp b/roundbtn.cpp new file mode 100644 index 0000000..da368ca --- /dev/null +++ b/roundbtn.cpp @@ -0,0 +1,278 @@ +/* +* Copyright (C) 2020, 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 3, or (at your option) +* any later version. +* +* This program is distributed in the hope that it will be useful, +* but WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +* GNU General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, see +#include +#include "constant_class.h" + +RoundBtn::RoundBtn(QWidget *parent): + QPushButton(parent),m_text(""),m_radius(14),m_defaultIconPath(""),m_hoverIconPath(""),m_pressIconPath("") + ,m_pressColor(Qt::gray),m_hoverColor(Qt::gray),m_defaultColor(Qt::gray),m_flag(TEXT_FLAG) +{ + initForm(); +} +RoundBtn::RoundBtn(const QString text, int radius, QWidget *parent): + QPushButton(parent),m_text(text),m_radius(radius),m_flag(TEXT_FLAG) + { + initForm(); +} + +RoundBtn::RoundBtn(RoundBtn::BTN_TYPE flag, QWidget *parent): + QPushButton(parent),m_text(""),m_radius(28),m_flag(flag) +{ + initForm(); +} + +RoundBtn::RoundBtn(const QString text, int radius, RoundBtn::BTN_TYPE flag, QWidget *parent): + QPushButton(parent),m_text(text),m_radius(radius),m_flag(flag) +{ + initForm(); +} + + +void RoundBtn::paintEvent(QPaintEvent *) +{ + QPainter p(this);//将当前窗体作为画布 + p.save(); + p.setRenderHints(QPainter::Antialiasing | QPainter::SmoothPixmapTransform); + QPen pen = QPen(penColor); + /* + if(m_flag==TEXT_FLAG){ + if(_pressed){ + p.setBrush(pressBrush); + pen.setColor(penClickColor); + }else{ + p.setBrush(notPressBrush); + pen.setColor(penColor); + } + if(_hover){ + p.setBrush(hoverBrush); + pen.setColor(penHoverColor); + }else{ + p.setBrush(notHoverBrush); + pen.setColor(penColor); + } + p.setPen(Qt::NoPen);//没有线条 + }else{ + p.setPen(Qt::NoPen); + p.setBrush(Qt::NoBrush); + } + */ + if(_pressed){ + p.setBrush(pressBrush); + pen.setColor(penClickColor); + }else{ + p.setBrush(notPressBrush); + pen.setColor(penColor); + } + if(_hover){ + p.setBrush(hoverBrush); + pen.setColor(penHoverColor); + }else{ + p.setBrush(notHoverBrush); + pen.setColor(penColor); + } + p.setPen(Qt::NoPen);//没有线条 + + + + //画圆形 +// QPoint _center = this->rect().center(); +// p.drawEllipse(_center,_radius,_radius); + QRect rect = this->rect(); + rect.setWidth(rect.width() - 1); + rect.setHeight(rect.height() - 1); + //圆角 + p.drawRoundedRect(rect, m_radius, m_radius); + p.restore(); + if(m_flag==TEXT_FLAG){ + p.save(); + //添加文本 + p.setPen(pen); + p.drawText(rect, m_text, QTextOption(Qt::AlignCenter));//文本居中:QTextOption(Qt::AlignCenter) + p.restore(); + }else if(m_flag==ICON_FLAG){ + QPixmap pixmp = getIconPixmap(m_defaultIconPath); + if(_pressed){ + pixmp = getIconPixmap(m_pressIconPath); + } + if(_hover){ + pixmp = getIconPixmap(m_hoverIconPath); + } + p.save(); + p.drawPixmap(QRect(-1,-1,m_IconSize.width(),m_IconSize.height()),pixmp); + p.restore(); + } + +} + +void RoundBtn::mousePressEvent(QMouseEvent *e) +{ + Q_UNUSED(e) + _pressed = true; +} + +void RoundBtn::mouseReleaseEvent(QMouseEvent *e) +{ + Q_UNUSED(e) + if(_pressed) + { + _pressed = false; + emit clicked(); + } +} + +void RoundBtn::mouseMoveEvent(QMouseEvent *e) +{ + Q_UNUSED(e) +} + +void RoundBtn::enterEvent(QEvent *event) +{ + Q_UNUSED(event) + _hover = true; + update(); +} + +void RoundBtn::leaveEvent(QEvent *event) +{ + Q_UNUSED(event) + _hover = false; + update(); +} + +bool RoundBtn::isContains(QPoint p) +{ + Q_UNUSED(p) + return true; +} + +void RoundBtn::initForm() +{ + _pressed = false; + _hover = false; + pressBrush = QBrush(Qt::gray); + notPressBrush = QBrush(QColor("lightGrey")); + hoverBrush = QBrush(Qt::gray); + notHoverBrush = QBrush(QColor("lightGrey")); + penColor = QColor(Qt::black); + penClickColor = QColor(Qt::black); + penHoverColor = QColor(Qt::black); +// beginPos = this->pos(); + //无边框 +// this->setWindowFlags(Qt::FramelessWindowHint | Qt::WindowSystemMenuHint | Qt::WindowMinMaxButtonsHint|Qt::WindowStaysOnTopHint); + /* 窗口整体透明,但窗口控件不透明*/ +// this->setAttribute(Qt::WA_TranslucentBackground,true); + + +} + +void RoundBtn::setText(const QString &text) +{ + m_text = text; + update(); +} + +void RoundBtn::setBtnColor(QColor defaultColor, QColor hoverColor, QColor clickColor) +{ + pressBrush = QBrush(clickColor); + notPressBrush = QBrush(defaultColor); + hoverBrush = QBrush(hoverColor); + notHoverBrush = QBrush(defaultColor); +} + +void RoundBtn::setPenColor(QColor defaultColor, QColor hoverColor, QColor clickColor) +{ + penColor = defaultColor; + penHoverColor = hoverColor; + penClickColor = clickColor; +} +/** + * @brief 修改文字颜色 + */ +void RoundBtn::updateTextPenColor(QColor textPenColor) +{ + penColor=textPenColor; + update(); +} + +void RoundBtn::setRadius(int radius) +{ + m_radius = radius; +} + +QPixmap RoundBtn::getIconPixmap(QString filePath) +{ + QPixmap pixmap; + pixmap.load(filePath); + return pixmap; +} + +void RoundBtn::setFlag(const BTN_TYPE &flag) +{ + m_flag = flag; +} + +void RoundBtn::setBtnBackcolorTransparent() +{ + QPalette pale =this->palette(); + QColor color = pale.color(QPalette::Button); + QColor ColorPlaceholderText3 = QColor(255,255,255,0); + QBrush brush; + brush.setColor(ColorPlaceholderText3); + pale.setBrush(QPalette::Button, brush); + this->setPalette(pale); +} + +void RoundBtn::setBtnHighlightColorTransparent() +{ + QPalette pale =this->palette(); + QColor color = pale.color(QPalette::Button); + QColor ColorPlaceholderText3 = QColor(255,255,255,0); + QBrush brush; + brush.setColor(ColorPlaceholderText3); + pale.setBrush(QPalette::Highlight, brush); + this->setPalette(pale); +} + + + +void RoundBtn::setAllIconPatn(const QString &defaultIconPath, const QString &hoverIconPath, const QString &pressIconPath) +{ + m_pressIconPath = pressIconPath; + m_hoverIconPath = hoverIconPath; + m_defaultIconPath = defaultIconPath; + update(); +} + +void RoundBtn::setIconSize(const QSize &IconSize) +{ + m_IconSize = IconSize; +} + +void RoundBtn::setAngleRound(int angleRound) +{ + m_angleRound = angleRound; +} + +void RoundBtn::setIconPath(const QString &iconPath) +{ + m_defaultIconPath = iconPath; +} + + diff --git a/roundbtn.h b/roundbtn.h new file mode 100644 index 0000000..5855c29 --- /dev/null +++ b/roundbtn.h @@ -0,0 +1,91 @@ +/* +* Copyright (C) 2020, 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 3, or (at your option) +* any later version. +* +* This program is distributed in the hope that it will be useful, +* but WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +* GNU General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, see +#include +#include +#include + +class RoundBtn : public QPushButton +{ + Q_OBJECT +public: + explicit RoundBtn(QWidget *parent = 0); //explicit 避免歧义 +// RoundBtn(const QString text, QPoint center,int radius,QWidget* parent = 0); + RoundBtn(const QString text, int radius,QWidget* parent = 0); + enum BTN_TYPE{ + TEXT_FLAG = 0, + ICON_FLAG = 1, + }; + RoundBtn(const QString text, int radius,RoundBtn::BTN_TYPE flag = TEXT_FLAG,QWidget* parent = 0); + RoundBtn(RoundBtn::BTN_TYPE flag = TEXT_FLAG,QWidget* parent = 0); + + void paintEvent(QPaintEvent *) override; //--绘图事件,调用update()时触发 + void mousePressEvent(QMouseEvent *e) override; //--鼠标按下事件 + void mouseReleaseEvent(QMouseEvent *e) override; //--鼠标释放事件 + void mouseMoveEvent(QMouseEvent *e) override; //--鼠标移动事件 + void enterEvent(QEvent *event) override; + void leaveEvent(QEvent *event) override; + + bool isContains(QPoint p);//判断鼠标是否在圆形范围之内 + void initForm();//初始化窗体 + void setText(const QString &text); + void setBtnColor (QColor defaultColor,QColor hoverColor,QColor clickColor); + void setPenColor (QColor defaultColor,QColor hoverColor,QColor clickColor); + void updateTextPenColor(QColor textPenColor); +public slots: +private: + QString m_text; //控件显示文本 +// QPoint _center; //圆心位置坐标 + QPoint beginPos;//圆形起始坐标 + int m_radius; //圆形半径 + QPixmap getIconPixmap(QString filePath); + QString m_defaultIconPath; + QString m_hoverIconPath; + QString m_pressIconPath; + QColor m_pressColor; + QColor m_hoverColor; + QColor m_defaultColor; + QSize m_IconSize; + int m_angleRound = 6; + +protected: + QBrush pressBrush; + QBrush notPressBrush; + QBrush hoverBrush; + QBrush notHoverBrush; + QColor penColor; + QColor penClickColor; + QColor penHoverColor; + BTN_TYPE m_flag; +public: + bool _pressed;//左键单击变色控制 + bool _hover; //悬浮高亮 + void setIconPath(const QString &iconPath); + void setRadius(int radius); + void setAngleRound(int angleRound); + void setIconSize(const QSize &IconSize); + void setAllIconPatn(const QString &defaultIconPath,const QString &hoverIconPath,const QString &pressIconPath); + void setFlag(const BTN_TYPE &flag); + void setBtnBackcolorTransparent(); + void setBtnHighlightColorTransparent(); +}; + +#endif // ROUNDBTN_H diff --git a/selectbtn.cpp b/selectbtn.cpp new file mode 100644 index 0000000..c9e81fd --- /dev/null +++ b/selectbtn.cpp @@ -0,0 +1,88 @@ +/* +* Copyright (C) 2020, 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 3, or (at your option) +* any later version. +* +* This program is distributed in the hope that it will be useful, +* but WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +* GNU General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, see +#include +#include "clock.h" +#include +#include "theme.h" + +SelectBtn::SelectBtn(QString name,QWidget *parent) : QPushButton(parent) +{ + QPixmap pixmap = QPixmap(":/image/go-bottom-symbolic.png"); + textLabel = new QLabel(this); + IconLabel = new QLabel(this); + noName = new QLabel(this); + //num不同,name与text的大小配比不同 + textLabel->setFixedSize(164, 36); + IconLabel->setFixedSize(27, 36); + int sep = 3; + noName->setFixedSize(sep, 36); + textLabel->move(sep, 0); + noName->move(0, 0); + IconLabel->move(173, 0); + textLabel->setText(name); + IconLabel->setPixmap(pixmap); + textLabel->setAlignment(Qt::AlignLeft | Qt::AlignVCenter); + textLabel->setStyleSheet("font-size:14px;"); +// this->resize(290,36); + QPalette palette; + palette.setColor(QPalette::ButtonText,QColor(148, 148, 148, 255)); + textLabel->setPalette(palette); + +} + + +SelectBtn::~SelectBtn() +{ + +} + +void SelectBtn::paintEvent(QPaintEvent *event) +{ + Q_UNUSED(event); + QPainter p(this); + p.setRenderHint(QPainter::Antialiasing); // 反锯齿; + QPainterPath rectPath; + rectPath.addRoundedRect(this->rect(), 6, 6); // 左上右下 + + QPainter painter(this); + QStyleOption opt; + opt.init(this); + painter.setBrush(opt.palette.color(QPalette::Base)); + + QColor mainColor; + mainColor = theme::selectBtnBackColor; + + p.fillPath(rectPath,QBrush(mainColor)); +} +/** + * @brief 1 向上 0 向下 + * @param status + */ +void SelectBtn::updateIconLabel(int status) +{ + QPixmap pixmap ; + if(status==1){ + pixmap = QPixmap(":/image/go-up-symbolic.png"); + }else{ + pixmap = QPixmap(":/image/go-bottom-symbolic.png"); + } + IconLabel->setPixmap(pixmap); + IconLabel->update(); +} diff --git a/selectbtn.h b/selectbtn.h new file mode 100644 index 0000000..3832d50 --- /dev/null +++ b/selectbtn.h @@ -0,0 +1,54 @@ +/* +* Copyright (C) 2020, 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 3, or (at your option) +* any later version. +* +* This program is distributed in the hope that it will be useful, +* but WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +* GNU General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, see +#include +#include +#include +#include + +namespace Ui { +class Btn_new; +} +class Clock; + +class SelectBtn : public QPushButton +{ + Q_OBJECT +public: + explicit SelectBtn(QString name,QWidget *parent = nullptr); + ~SelectBtn(); + QLabel *textLabel; + QLabel *noName; + QLabel *IconLabel; + void paintEvent(QPaintEvent *event); + void updateIconLabel(int status); +private: + Ui::Btn_new *ui; + Clock * m_pclock; + int clock_num; + int pressflag; + +protected: +signals: + +}; + +#endif // SELECTBTN_H diff --git a/selectbtnutil.cpp b/selectbtnutil.cpp new file mode 100644 index 0000000..a263d8b --- /dev/null +++ b/selectbtnutil.cpp @@ -0,0 +1,281 @@ +/* +* Copyright (C) 2020, 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 3, or (at your option) +* any later version. +* +* This program is distributed in the hope that it will be useful, +* but WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +* GNU General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, see +#include +#include "utils.h" +#include +#include +#include "constant_class.h" + + +SelectBtnUtil::SelectBtnUtil(QObject *parent) : QObject(parent) +{ + m_bellQueryModel = clock_sql::getBellTable(this); + idIndexMap = new QMap(); + indexIdMap = new QMap(); + allBellItem = new QList(); + refreshBellData(); + +} + +int SelectBtnUtil::getBellListSize() +{ + return allBellItem->size(); +} + +int SelectBtnUtil::getBellIndexById(QString id) +{ + int index= idIndexMap->value(id); + return index; +} + +QString SelectBtnUtil::getBellIdByIndex(int index) +{ + QString id = indexIdMap->value(index); + return id; +} + +QString SelectBtnUtil::getBellNameById(QString id) +{ + auto sqlQuery = getBellkByPK(id); + QString name = sqlQuery.value(1).toString(); + return name; +} + +QString SelectBtnUtil::getBellPathById(QString id) +{ + auto sqlQuery = getBellkByPK(id); + QString path = sqlQuery.value(3).toString(); + return path; +} + +QString SelectBtnUtil::getDefaultBellId() +{ + if(m_defaultBellId.isEmpty()){ + auto sqlQuery = getBellkBynameEn("none"); + QString id = sqlQuery.value(0).toString(); + m_defaultBellId = id; + } + return m_defaultBellId; +} + +QString SelectBtnUtil::getBellIdByNameEn(QString nameEn) +{ + auto sqlQuery = getBellkBynameEn(nameEn); + QString id = sqlQuery.value(0).toString(); + return id; +} + +QSqlQuery SelectBtnUtil::getBellkByPK(QString id) +{ + auto sqlQuery = clock_sql::getQSqlQuery(); + sqlQuery.prepare("select * from bell where id=:id"); + sqlQuery.bindValue(":id",id); + sqlQuery.exec(); + sqlQuery.next(); + return sqlQuery; +} + +QSqlQuery SelectBtnUtil::getBellkBynameEn(QString nameEn) +{ + auto sqlQuery = clock_sql::getQSqlQuery(); + sqlQuery.prepare("select * from bell where bell_en=:bell_en limit 1"); + sqlQuery.bindValue(":bell_en",nameEn); + sqlQuery.exec(); + sqlQuery.next(); + return sqlQuery; + +} + +QList *SelectBtnUtil::getAllBellItem() const +{ + return allBellItem; +} +void SelectBtnUtil::refreshBellData() +{ + int index=0; + auto sqlQuery = clock_sql::getQSqlQuery(); + sqlQuery.exec("select * from bell where bell_type=0 order by create_time ASC"); + idIndexMap->clear(); + indexIdMap->clear(); + allBellItem->clear(); + while (sqlQuery.next()) { + QString itemId = sqlQuery.value(0).toString(); + idIndexMap->insert(itemId,index); + indexIdMap->insert(index,itemId); + QString bellCn = sqlQuery.value(1).toString(); + allBellItem->append(bellCn); + index++; + } + sqlQuery.clear(); + //最新的前5个 + sqlQuery.exec("select * from bell where bell_type=1 order by create_time DESC limit 5"); + QList * bellIdList = new QList(); + QList * bellNameList = new QList(); + while (sqlQuery.next()) { + QString itemId = sqlQuery.value(0).toString(); + bellIdList->append(itemId); + QString bellCn = sqlQuery.value(1).toString(); + bellNameList->append(bellCn); + } + //逆序 + int bellListSize = bellIdList->size(); + for (int i=0;iat(bellListSize-1-i); + idIndexMap->insert(itemId,index); + indexIdMap->insert(index,itemId); + QString bellCn = bellNameList->at(bellListSize-1-i); + allBellItem->append(bellCn); + index++; + } + delete bellIdList; + delete bellNameList; + //自定义铃声 + allBellItem->append(tr("diy bell")); +} + +QString SelectBtnUtil::getDefaultBellStr() +{ + QString str = getDefaultBellEn(); + return tr(str.toLatin1().data()); +} + +QString SelectBtnUtil::getDefaultBellEn() +{ + return "relax"; +} + +QList *SelectBtnUtil::getDefaultBellList() +{ + QList * list = new QList(); + list->append("none"); + list->append("glass"); + list->append("bark"); + list->append("sonar"); + list->append("drip"); + return list; +} + +QList *SelectBtnUtil::getDefaultBellTrList() +{ + QList * list = new QList(); + list->append(tr("none")); + list->append(tr("glass")); + list->append(tr("bark")); + list->append(tr("sonar")); + list->append(tr("drip")); + return list; +} +bool SelectBtnUtil::mkdir(QString path){ + bool res=false; + QDir targetDir(path); + if(!targetDir.exists()){ + res = targetDir.mkdir(targetDir.absolutePath()); + } + return res; +} +QString SelectBtnUtil::copyAudioFile(QString from) +{ + QString fileName =getFileNameFromPath(from); + QString path = QStandardPaths::writableLocation(QStandardPaths::HomeLocation); + path = path.append(DIY_BELL_SAVE_PATH); + QDir dir; + bool dirResult = dir.mkpath(path); + qWarning()<<"dbq-dirResult"<select(); + int rowNum = m_bellQueryModel->rowCount(); + int i = rowNum; + m_bellQueryModel->insertRow(i); + auto id = Utils::getRandomId(); + m_bellQueryModel->setData(m_bellQueryModel->index(i, 0),id); + m_bellQueryModel->setData(m_bellQueryModel->index(i, 1), name); + m_bellQueryModel->setData(m_bellQueryModel->index(i, 2), name); + m_bellQueryModel->setData(m_bellQueryModel->index(i, 3), filePath); + QDateTime time = QDateTime::currentDateTime(); //获取当前时间 + qint64 timeT = time.toMSecsSinceEpoch(); + m_bellQueryModel->setData(m_bellQueryModel->index(i, 4), timeT); + m_bellQueryModel->setData(m_bellQueryModel->index(i, 5), 1); + m_bellQueryModel->submitAll(); + //排序,暂停1ms + QThread::msleep(1); + refreshBellData(); + return id; +} + +QString SelectBtnUtil::openAudioFileDialog(QWidget * parent) +{ + KylinQFileDialog dialog; + dialog.setFileMode(QFileDialog::AnyFile); + dialog.setNameFilter(tr("audio files(*mp3 *wav *ogg)")); + dialog.setViewMode(QFileDialog::Detail); + dialog.setWindowTitle(tr("select bell")); + QStringList fileNames; + QString fileName=""; + if (dialog.exec()==QDialog::Accepted){ + fileNames = dialog.selectedFiles(); + }else{ + } + + if(fileNames.length()>0){ + fileName=fileNames.at(0); + } + return fileName; +} diff --git a/selectbtnutil.h b/selectbtnutil.h new file mode 100644 index 0000000..d2b28f8 --- /dev/null +++ b/selectbtnutil.h @@ -0,0 +1,66 @@ +/* +* Copyright (C) 2020, 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 3, or (at your option) +* any later version. +* +* This program is distributed in the hope that it will be useful, +* but WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +* GNU General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, see +#include +#include +#include +#include "kylinqfiledialog.h" +class SelectBtnUtil : public QObject +{ + Q_OBJECT +public: + explicit SelectBtnUtil(QObject *parent = nullptr); + int getBellListSize(); + int getBellIndexById(QString id); + QString getBellIdByIndex(int index); + QString getBellNameById(QString id); + QString getBellPathById(QString id); + QString getDefaultBellId(); + QString getBellIdByNameEn(QString nameEn); + void refreshBellData(); + static QString getDefaultBellStr(); + static QString getDefaultBellEn(); + static QList * getDefaultBellList(); + static QList * getDefaultBellTrList(); + QString copyAudioFile(QString from); + bool copyFile(QString from ,QString to); + QString getFileNameFromPath(QString path); + QString getFileNameWithoutSuffix(QString FileName); + QString saveToBellTable(QString filePath); + + QString openAudioFileDialog(QWidget * parent); + + QSqlQuery getBellkByPK(QString id); + QSqlQuery getBellkBynameEn(QString nameEn); + QList *getAllBellItem() const; + + bool mkdir(QString path); +signals: + +private: + QSqlTableModel * m_bellQueryModel = nullptr; + QMap * idIndexMap = nullptr; + QMap * indexIdMap = nullptr; + QString m_defaultBellId = ""; + QList * allBellItem = nullptr; +}; + +#endif // SELECTBTNUTIL_H diff --git a/setAlarmRepeatDialog.cpp b/setAlarmRepeatDialog.cpp new file mode 100644 index 0000000..63c4fb6 --- /dev/null +++ b/setAlarmRepeatDialog.cpp @@ -0,0 +1,250 @@ +/* +* 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 3, or (at your option) +* any later version. +* +* This program is distributed in the hope that it will be useful, +* but WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +* GNU General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, see +#include +#include +#include +#include +#include +#include +#include +#include "theme.h" + +extern void qt_blurImage(QImage &blurImage, qreal radius, bool quality, int transposed); + +set_alarm_repeat_Dialog::set_alarm_repeat_Dialog(int width, int Length, int rowNum , QWidget *parent ) : + QWidget(parent), + rowNum_all(rowNum), + width_num(width), + Length_num(Length) +{ + setupUi(this); + this->resize(width_num, Length_num); + + this->setWindowTitle(tr("Alarm")); + + setWindowFlags(Qt::Dialog); + this->setAttribute(Qt::WA_TranslucentBackground);//设置窗口背景透明 +// this->setWindowFlags(Qt::FramelessWindowHint|Qt::ToolTip); //设置无边框窗口 + +// this->setAttribute(Qt::WA_TranslucentBackground); +// QPainterPath blurPath; +// blurPath.addRoundedRect(rect().adjusted(10, 10, -10, -10), 10, 10); //增加圆角 +// setProperty("useSystemStyleBlur", true); +// setProperty("blurRegion", QRegion(blurPath.toFillPolygon().toPolygon()));//使用QPainterPath的api生成多边形Region + + //增加圆角 + QBitmap bmp(this->size()); + bmp.fill(); + QPainter p(&bmp); + p.setPen(Qt::black); + p.setBrush(Qt::black); + p.setRenderHint(QPainter::Antialiasing); + p.drawRoundedRect(bmp.rect(),10,10); + setMask(bmp); + + for (int i = 0; i < rowNum_all; i++) { + set_aItem(i); + } + + settingsStyle(); +} + +set_alarm_repeat_Dialog::~set_alarm_repeat_Dialog() +{ + for (int i =0 ; i blackStyle(); + }); + connect(subject,&GsettingSubject::whiteStyle, this,[=](){ + this->whiteStyle(); + }); + connect(subject,&GsettingSubject::fontChanged, this,[=](int size){ + this->CURRENT_FONT_SIZE=size; + updateSelectItemLabelFont(size); + + }); + subject->iniWidgetStyle(); + subject->iniFontSize(); +} +void set_alarm_repeat_Dialog::updateSelectItemLabelFont(int size) +{ + QListWidget * itemList = listWidget; + for (int i=0;icount() ;i++ ) { + QListWidgetItem * varItem = itemList->item(i); + set_alarm_repeat_widget * varWidget = static_cast(itemList->itemWidget(varItem)) ; + updateLabelFront(varWidget->alarmLabel0,qRound(1.3*size)); + } +} +/** + * @brief 更新麒麟闹钟字体 + */ +void set_alarm_repeat_Dialog::updateLabelFront(QLabel *label, int size) +{ + QString styleSheet = "QLabel{ font-size: "; + styleSheet.append(QString::number(size)).append("px;"); + styleSheet.append("background-color: rgb();}"); + label->setStyleSheet(styleSheet); +} +void set_alarm_repeat_Dialog::set_aItem(int rowNum) +{ + aItem[rowNum] =new QListWidgetItem; + //将列表项的大小提示设置为大小。如果未设置大小提示,则item委托将基于item数据计算大小提示。 + aItem[rowNum]->setSizeHint(QSize(340, 38)); + aItem[rowNum]->setTextColor(QColor(255, 0, 0, 255)); + listWidget->addItem(aItem[rowNum]); + listWidget->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff); + listWidget->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); + widget[rowNum] = new set_alarm_repeat_widget(listWidget); + listWidget->setItemWidget(aItem[rowNum],widget[rowNum]); + QScroller::grabGesture(listWidget,QScroller::LeftMouseButtonGesture); //设置鼠标左键拖动 + listWidget -> setVerticalScrollMode(QAbstractItemView::ScrollPerPixel); // 设置像素级滑动 +} + +void set_alarm_repeat_Dialog::setupUi(QWidget( *set_alarm_repeat_Dialog)) +{ + if (set_alarm_repeat_Dialog->objectName().isEmpty()) + set_alarm_repeat_Dialog->setObjectName(QString::fromUtf8("set_alarm_repeat_Dialog")); + listWidget = new QListWidget(set_alarm_repeat_Dialog); + listWidget->setObjectName(QString::fromUtf8("listWidget")); + listWidget->setGeometry(QRect(0, 0, width_num-20, Length_num-20)); + listWidget->move(10,10); + + retranslateUi(set_alarm_repeat_Dialog); + + QMetaObject::connectSlotsByName(set_alarm_repeat_Dialog); +} // setupUi + +void set_alarm_repeat_Dialog::retranslateUi(QWidget( *set_alarm_repeat_Dialog)) +{ + set_alarm_repeat_Dialog->setWindowTitle(QApplication::translate("set_alarm_repeat_Dialog", "Dialog", nullptr)); +} // retranslateUi + +void set_alarm_repeat_Dialog::paintEvent(QPaintEvent *event) +{ + Q_UNUSED(event); + QPainter p(this); + p.setRenderHint(QPainter::Antialiasing); + QPainterPath rectPath; + rectPath.addRoundedRect(this->rect().adjusted(SHADOW_RANGE, SHADOW_RANGE, -SHADOW_RANGE, -SHADOW_RANGE), WINDOWN_RADIUS, WINDOWN_RADIUS); + // 画一个黑底 + QPixmap pixmap(this->rect().size()); + pixmap.fill(Qt::transparent); + QPainter pixmapPainter(&pixmap); + pixmapPainter.setRenderHint(QPainter::Antialiasing); + auto shadowColor = palette().text().color(); + shadowColor.setAlphaF(SHADOWCOLOR_ALPHAF); + pixmapPainter.setBrush(shadowColor); + pixmapPainter.setPen(Qt::transparent); + pixmapPainter.drawPath(rectPath); + pixmapPainter.end(); + // 模糊这个黑底 + QImage img = pixmap.toImage(); + qt_blurImage(img, VAGUE_RADIUS, false, false); + // 挖掉中心 + pixmap = QPixmap::fromImage(img); + QPainter pixmapPainter2(&pixmap); + pixmapPainter2.setRenderHint(QPainter::Antialiasing); + pixmapPainter2.setCompositionMode(QPainter::CompositionMode_Clear); + pixmapPainter2.setPen(Qt::transparent); + pixmapPainter2.setBrush(Qt::transparent); + pixmapPainter2.drawPath(rectPath); + // 绘制阴影 + p.drawPixmap(this->rect(), pixmap, pixmap.rect()); + QStyleOption opt; + opt.init(this); + // 绘制一个背景 + p.save(); + //描边 + QColor borderColor = palette().text().color(); + borderColor.setAlphaF(BORDERCOLOR_ALPHAF); + p.setPen(borderColor); + p.translate(BORDER_RANGE, BORDER_RANGE); + p.setBrush(palette().color(QPalette::Base)); + p.drawPath(rectPath); + p.restore(); + +} + +void set_alarm_repeat_Dialog::closeEvent(QCloseEvent *event) +{ + emit dialogClose(); + QWidget::closeEvent(event); +} + + +//黑色主题 +void set_alarm_repeat_Dialog::blackStyle() +{ + QString itemRadius = QString::number(ITEM_RADIUS); + listWidget->setStyleSheet("QListWidget{background-color: rgba(0, 0, 0, 0);}\ + QListWidget::item::selected{background-color:rgba("+hoverColor+");border-radius:"+itemRadius+"px;border:1px solid rgba(131, 131, 131,0);}\ + QListWidget::item:hover{background-color:rgba("+hoverColor+");border-radius:"+itemRadius+"px;}\ + "); + +} +//白色主题 +void set_alarm_repeat_Dialog::whiteStyle() +{ + QString itemRadius = QString::number(ITEM_RADIUS); + listWidget->setStyleSheet("QListWidget{background-color: rgba(0, 0, 0, 0);}\ + QListWidget::item::selected{background-color:rgba("+hoverColor+");border-radius:"+itemRadius+"px;border:1px solid rgba(131, 131, 131,0);}\ + QListWidget::item:hover{background-color:rgba("+hoverColor+");border-radius:"+itemRadius+"px;}\ + "); + +} + +set_alarm_repeat_widget::set_alarm_repeat_widget(QWidget *parent): + QWidget(parent) +{ + this->setFixedSize(340, 38); + //选项 + alarmLabel0 = new QLabel(this); + alarmLabel0->move(16, 0); + alarmLabel0->setFixedSize(160, 38); + alarmLabel0->setStyleSheet("background-color: rgb();"); + alarmLabel0->setText("选项"); + + //对号 + alarmLabel1 = new QLabel(this); + alarmLabel1->move(235, 0); + alarmLabel1->setFixedSize(34, 38); + alarmLabel1->setText(""); + alarmLabel1->setProperty("useIconHighlightEffect", true); + alarmLabel1->setProperty("iconHighlightEffectMode", 1); + +} + +set_alarm_repeat_widget::~set_alarm_repeat_widget() +{ + +} + diff --git a/setAlarmRepeatDialog.h b/setAlarmRepeatDialog.h new file mode 100644 index 0000000..609feb9 --- /dev/null +++ b/setAlarmRepeatDialog.h @@ -0,0 +1,91 @@ +/* +* 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 3, or (at your option) +* any later version. +* +* This program is distributed in the hope that it will be useful, +* but WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +* GNU General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, see +#include +#include +#include +#include +#include "clickableLabel.h" +#include "constant_class.h" +#include "gsettingsubject.h" + + + +namespace Ui { +class set_alarm_repeat_Dialog; +} + +class set_alarm_repeat_widget; + + +class set_alarm_repeat_Dialog : public QWidget +{ + Q_OBJECT + +public: + explicit set_alarm_repeat_Dialog(int width, int Length, int rowNum = 0, QWidget *parent = nullptr); + ~set_alarm_repeat_Dialog(); + + void paintEvent(QPaintEvent *event) override; + set_alarm_repeat_widget *widget[20]; + QListWidgetItem *aItem[20]; + int rowNum_all ; + int width_num, Length_num; + QListWidget *listWidget; + void set_aItem(int rowNum); +protected: + void closeEvent(QCloseEvent *event) override; + +signals: + void dialogClose(); + +private: + void setupUi(QWidget *set_alarm_repeat_Dialog); + void retranslateUi(QWidget *set_alarm_repeat_Dialog); + void settingsStyle(); //监听主题 + void blackStyle(); //黑色主题 + void whiteStyle(); //白色主题 + void updateLabelFront(QLabel *label, int size); + void updateSelectItemLabelFont(int size); + int CURRENT_FONT_SIZE; +}; + + + +class set_alarm_repeat_widget : public QWidget +{ + Q_OBJECT + +public: + explicit set_alarm_repeat_widget(QWidget *parent = nullptr); + ~set_alarm_repeat_widget(); + +// void paintEvent(QPaintEvent *event); + + QLabel *alarmLabel0; + //QPushButton + QLabel *alarmLabel1; + +private: + +}; + +#endif // SET_ALARM_REPEAT_DIALOG_H diff --git a/set_clock.ui b/set_clock.ui new file mode 100644 index 0000000..b0b2488 --- /dev/null +++ b/set_clock.ui @@ -0,0 +1,27 @@ + + + set_clock + + + + 0 + 0 + 454 + 631 + + + + Form + + + width:454px; +height:631px; +background:rgba(14,255,255,1); +opacity:0.95; +border-radius:0px 0px 6px 6px; + + + + + + diff --git a/setupPage.cpp b/setupPage.cpp new file mode 100644 index 0000000..c8d436e --- /dev/null +++ b/setupPage.cpp @@ -0,0 +1,495 @@ +/* +* 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 3, or (at your option) +* any later version. +* +* This program is distributed in the hope that it will be useful, +* but WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +* GNU General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, see +#include "setAlarmRepeatDialog.h" +#include +#include +#include +#include "theme.h" + +extern void qt_blurImage(QImage &blurImage, qreal radius, bool quality, int transposed); + +static const int DIALOG_WIDTH = 200; + +static const int DIALOG_LEFT_SPACE = 130; + +setuppage::setuppage( double position_x, double position_y, QWidget *parent ) : + QWidget(parent), + pos_x(position_x), + pos_y(position_y), + ui(new Ui::setuppage) +{ +// setAttribute(Qt::WA_TranslucentBackground); +// QPainterPath blurPath; +// setProperty("useSystemStyleBlur", true); +// setProperty("blurRegion", QRegion(blurPath.toFillPolygon().toPolygon()));//使用QPainterPath的api生成多边形Region + +// this->setProperty("blurRegion", QRegion(QRect(1, 1, 1, 1))); + Qt::WindowFlags m_flags = windowFlags(); + this->setWindowFlags(m_flags | Qt::WindowStaysOnTopHint); + + ui->setupUi(this); + //时间格式 + Time_format = new set_alarm_repeat_Dialog(DIALOG_WIDTH,138,3,ui->widget); + //稍后提醒时间间隔 + Reminder_off = new set_alarm_repeat_Dialog(DIALOG_WIDTH,190,5,ui->widget); + //默认铃声 + Default_ringtone = new set_alarm_repeat_Dialog(DIALOG_WIDTH,169,4,ui->widget); + + connect(Time_format->listWidget,SIGNAL(itemClicked(QListWidgetItem*)),this,SLOT(Time_format_listClickslot())); + connect(Reminder_off->listWidget,SIGNAL(itemClicked(QListWidgetItem*)),this,SLOT(Reminder_off_listClickslot())); + connect(Default_ringtone->listWidget,SIGNAL(itemClicked(QListWidgetItem*)),this,SLOT(Default_ringtone_listClickslot())); + //时间格式 + timeformatBtn = new SelectBtn( tr(" time"), this); + //时间格式 + timeFormatLabel = new QLabel(this); + updateLabelStyle(timeFormatLabel,tr(" time"),108); + //提醒时间 + remindTimeLabel = new QLabel(this); + updateLabelStyle(remindTimeLabel,tr(" duration"),163); + //默认铃声 + defaultBellLabel = new QLabel(this); + updateLabelStyle(defaultBellLabel,tr(" ringtone"),218); + //稍后提醒时间间隔 + + remindDurationBtn = new SelectBtn( tr(" duration"), this); + //默认铃声 + defaultBellBtn = new SelectBtn( tr(" ringtone"), this); + int selectBtnLeftSpace = 102; + timeformatBtn->move(selectBtnLeftSpace, 108); + remindDurationBtn->move(selectBtnLeftSpace, 163); + defaultBellBtn->move(selectBtnLeftSpace, 218); + + timeformatBtn->resize(DIALOG_WIDTH,36); + remindDurationBtn->resize(DIALOG_WIDTH,36); + defaultBellBtn->resize(DIALOG_WIDTH,36); + + //绑定下拉框 + connect(timeformatBtn, SIGNAL(clicked()), this, SLOT(Time_format_set()) ); + connect(remindDurationBtn, SIGNAL(clicked()), this, SLOT(Reminder_off_set()) ); + connect(defaultBellBtn, SIGNAL(clicked()), this, SLOT(Default_ringtone_set()) ); + + connect(Time_format->listWidget,SIGNAL(itemClicked(QListWidgetItem*)),this,SLOT(Time_format_listClickslot())); + connect(Reminder_off->listWidget,SIGNAL(itemClicked(QListWidgetItem*)),this,SLOT(Reminder_off_listClickslot())); + connect(Default_ringtone->listWidget,SIGNAL(itemClicked(QListWidgetItem*)),this,SLOT(Default_ringtone_listClickslot())); + connect(Time_format,&set_alarm_repeat_Dialog::dialogClose,this,[=](){ + timeformatBtn->updateIconLabel(0); + }); + connect(Reminder_off,&set_alarm_repeat_Dialog::dialogClose,this,[=](){ + remindDurationBtn->updateIconLabel(0); + }); + connect(Default_ringtone,&set_alarm_repeat_Dialog::dialogClose,this,[=](){ + defaultBellBtn->updateIconLabel(0); + }); + + model_setup = new QSqlTableModel(this); + model_setup->setTable("setup"); + model_setup->setEditStrategy(QSqlTableModel::OnManualSubmit); + model_setup->select(); + model_setup->submitAll(); + + repeat_on_Pixmap = QPixmap(":/image/object-select-symbolic.png"); + repeat_off_Pixmap = QPixmap(""); + + QString werk_day; + QString Time = model_setup->index(0, 15).data().toString(); + QString Pop_up = model_setup->index(0, 16).data().toString(); + QString Reminder = model_setup->index(0, 17).data().toString(); + QString Default = model_setup->index(0, 5).data().toString(); + + int werk = 0; + for (int i=0; i<7; i++) { + if (model_setup->index(0, i+7).data().toInt()) { + if(i == 0){ + werk_day = werk_day + tr("Mon"); + }else if(i == 1){ + werk_day = werk_day + tr("Tue"); + }else if(i == 2){ + werk_day = werk_day + tr("Wed"); + }else if(i == 3){ + werk_day = werk_day + tr("Thu"); + }else if(i == 4){ + werk_day = werk_day + tr("Fri"); + }else if(i == 5){ + werk_day = werk_day + tr("Sat"); + }else if(i == 6){ + werk_day = werk_day + tr("Sun"); + } + }else{ + werk = 1; + } + } + + //可以比较 Time.compare(tr("Following system") + + if(Time.compare("Following system") == 0 || Time.compare("跟随系统") == 0){ + Time = tr("Following system"); + }else if(Time.compare("24 hour system") == 0 || Time.compare("24小时制") == 0){ + Time = tr("24 hour system"); + }else if(Time.compare("12 hour system") == 0 || Time.compare("12小时制") == 0){ + Time = tr("12 hour system"); + } + if(Pop_up.compare("Notification") == 0 || Pop_up.compare("通知栏弹窗") == 0){ + Pop_up = tr("Notification"); + }else if(Pop_up.compare("Full screen") == 0 || Pop_up.compare("全屏弹窗") == 0){ + Pop_up = tr("Full screen"); + } + if(Reminder.compare("Alert in 2 minutes") == 0 || Reminder.compare("2分钟后提醒") == 0){ + Reminder = tr("Alert in 2 minutes"); + }else if(Reminder.compare("Alert in 5 minutes") == 0 || Reminder.compare("5分钟后提醒") == 0){ + Reminder = tr("Alert in 5 minutes"); + }else if(Reminder.compare("Alert in 10 minutes") == 0 || Reminder.compare("10分钟后提醒") == 0){ + Reminder = tr("Alert in 10 minutes"); + }else if(Reminder.compare("Alert in 30 minutes") == 0 || Reminder.compare("30分钟后提醒") == 0){ + Reminder = tr("Alert in 30 minutes"); + }else if(Reminder.compare("Alert in 60 minutes") == 0 || Reminder.compare("60分钟后提醒") == 0){ + Reminder = tr("Alert in 60 minutes"); + } + + if(Default.compare("glass") == 0 || Default.compare("玻璃") == 0){ + Default = tr("glass"); + }else if(Default.compare("bark") == 0 || Default.compare("犬吠") == 0){ + Default = tr("bark"); + }else if(Default.compare("sonar") == 0 || Default.compare("声呐") == 0){ + Default = tr("sonar"); + }else if(Default.compare("drip") == 0 || Default.compare("雨滴") == 0){ + Default = tr("drip"); + } + timeformatBtn->textLabel->setText(Time); + remindDurationBtn->textLabel->setText(Reminder); + defaultBellBtn->textLabel->setText(Default); + + Time_format->hide() ; + Reminder_off->hide() ; + Default_ringtone->hide() ; + + QColor ColorPlaceholderText3(255,255,255,0); + QBrush brush; + brush.setColor(ColorPlaceholderText3); + + ui->closeBtn->setIcon(QIcon::fromTheme("window-close-symbolic")); + ui->closeBtn->setProperty("isWindowButton", 0x2); + ui->closeBtn->setProperty("useIconHighlightEffect", 0x8); + ui->closeBtn->setFlat(true); + connect(ui->closeBtn, &QPushButton::clicked, this, [=](){ + this->hide(); + }); + + muteBtn = new CustomButton(this,54,24,1); + muteBtn->move(236,66); + //静音labe + QString selfFont = Utils::loadFontHuaKangJinGangHeiRegularTTF(); + QFont f(selfFont); + ui->label_3->setFont(f); + + // 主题框架1.0.6-5kylin2 + + //关闭按钮去掉聚焦状态 + ui->closeBtn->setFocusPolicy(Qt::NoFocus); + //初始化 + musicSelectPlay = new QSoundEffect(this); + this->setAttribute(Qt::WA_TranslucentBackground);//设置窗口背景透明 + +} + +setuppage::~setuppage() +{ + delete model_setup; + delete Time_format ; + delete Reminder_off ; + delete Default_ringtone ; + delete ui; +} + +void setuppage::Mute_starting() +{ + +} + + +//时间格式设置回调 +// Time format callback +void setuppage::Time_format_set() +{ + timeformatBtn->updateIconLabel(1); + timeformatBtn->setAttribute(Qt::WA_UnderMouse, false); + QHoverEvent hoverEvent(QEvent::HoverLeave, QPoint(40, 40), QPoint(0, 0)); + QCoreApplication::sendEvent(timeformatBtn, &hoverEvent); + + Time_format->setWindowFlags(Qt::FramelessWindowHint | Qt::Popup); + //Time_format->setAttribute(Qt::WA_TranslucentBackground); + QPointF position = parentWidget()->pos(); + Time_format->move(position.x()+DIALOG_LEFT_SPACE,position.y()+255); + Time_format->resize(DIALOG_WIDTH,138); + Time_format->listWidget->setFixedSize(DIALOG_WIDTH-20,130); + Time_format->widget[0]->alarmLabel0->setText(tr("Following system")); + Time_format->widget[1]->alarmLabel0->setText(tr("24 hour system")); + Time_format->widget[2]->alarmLabel0->setText(tr("12 hour system")); + + Time_format->show(); + +} + +//时间格式选择单击回调 +// Time format selection click callback +void setuppage::Time_format_listClickslot() +{ + model_setup->select(); + + int num=Time_format->listWidget->currentRow(); + + switch (num) { + case 0: + model_setup->setData(model_setup->index(0, 2), 0); + model_setup->setData(model_setup->index(0, 15), tr("Following system")); + break; + + case 1: + model_setup->setData(model_setup->index(0, 2), 1); + model_setup->setData(model_setup->index(0, 15), tr("24 hour system")); + break; + + case 2: + model_setup->setData(model_setup->index(0, 2), 2); + model_setup->setData(model_setup->index(0, 15), tr("12 hour system")); + break; + default: + break; + } + + timeformatBtn->textLabel->setText(model_setup->index(0, 15).data().toString()); + Time_format->close(); + model_setup->submitAll(); +} + + + +//提醒关闭回调 +// Reminder close callback +void setuppage::Reminder_off_set() +{ + remindDurationBtn->updateIconLabel(1); + remindDurationBtn->setAttribute(Qt::WA_UnderMouse, false); + QHoverEvent hoverEvent(QEvent::HoverLeave, QPoint(40, 40), QPoint(0, 0)); + QCoreApplication::sendEvent(remindDurationBtn, &hoverEvent); + + Reminder_off->setWindowFlags(Qt::FramelessWindowHint | Qt::Popup); + //Reminder_off->setAttribute(Qt::WA_TranslucentBackground); + QPointF position = parentWidget()->pos(); + Reminder_off->move(position.x()+DIALOG_LEFT_SPACE,position.y()+310); + Reminder_off->resize(DIALOG_WIDTH,190); + Reminder_off->listWidget->setFixedSize(DIALOG_WIDTH-20,170); + Reminder_off->widget[0]->alarmLabel0->setText(tr("Alert in 2 minutes")); + Reminder_off->widget[1]->alarmLabel0->setText(tr("Alert in 5 minutes")); + Reminder_off->widget[2]->alarmLabel0->setText(tr("Alert in 10 minutes")); + Reminder_off->widget[3]->alarmLabel0->setText(tr("Alert in 30 minutes")); + Reminder_off->widget[4]->alarmLabel0->setText(tr("Alert in 60 minutes")); + Reminder_off->show(); +} + +//提醒关闭选择单击回调 +// Reminder off select click callback +void setuppage::Reminder_off_listClickslot() +{ + model_setup->select(); + int num=Reminder_off->listWidget->currentRow(); + //配置稍后提醒时间间隔 + model_setup->setData(model_setup->index(0, 4), num); + + switch (num) { + case 0: + model_setup->setData(model_setup->index(0, 17), tr("Alert in 2 minutes")); + break; + case 1: + model_setup->setData(model_setup->index(0, 17), tr("Alert in 5 minutes")); + break; + case 2: + model_setup->setData(model_setup->index(0, 17), tr("Alert in 10 minutes")); + break; + case 3: + model_setup->setData(model_setup->index(0, 17), tr("Alert in 30 minutes")); + break; + case 4: + model_setup->setData(model_setup->index(0, 17), tr("Alert in 60 minutes")); + break; + default: + break; + } + remindDurationBtn->textLabel->setText(model_setup->index(0, 17).data().toString()); + model_setup->submitAll(); + Reminder_off->close(); +} +//默认铃声设置回调 +// Default ringtone setting callback +void setuppage::Default_ringtone_set() +{ + defaultBellBtn->updateIconLabel(1); + defaultBellBtn->setAttribute(Qt::WA_UnderMouse, false); + QHoverEvent hoverEvent(QEvent::HoverLeave, QPoint(40, 40), QPoint(0, 0)); + QCoreApplication::sendEvent(defaultBellBtn, &hoverEvent); + + Default_ringtone->setWindowFlags(Qt::FramelessWindowHint | Qt::Popup); + //Default_ringtone->setAttribute(Qt::WA_TranslucentBackground); + QPointF position = parentWidget()->pos(); + Default_ringtone->move(position.x()+DIALOG_LEFT_SPACE,position.y()+363); + Default_ringtone->resize(DIALOG_WIDTH,169); + Default_ringtone->listWidget->setFixedSize(DIALOG_WIDTH-20,149); + Default_ringtone->widget[0]->alarmLabel0->setText(tr("glass")); + Default_ringtone->widget[1]->alarmLabel0->setText(tr("bark")); + Default_ringtone->widget[2]->alarmLabel0->setText(tr("sonar")); + Default_ringtone->widget[3]->alarmLabel0->setText(tr("drip")); + Default_ringtone->show(); + +} + +//默认铃声选择单击回调 +// Default ring tone selection click callback +void setuppage::Default_ringtone_listClickslot() +{ + model_setup->select(); + int num=Default_ringtone->listWidget->currentRow(); + delete musicSelectPlay; + musicSelectPlay = new QSoundEffect(this); + switch (num) + { + case 0: + model_setup->setData(model_setup->index(0, 5), tr("glass")); + musicSelectPlay->setSource(QUrl::fromLocalFile("/usr/share/ukui-clock/glass.wav")); + break; + case 1: + model_setup->setData(model_setup->index(0, 5), tr("bark")); + musicSelectPlay->setSource(QUrl::fromLocalFile("/usr/share/ukui-clock/bark.wav")); + break; + case 2: + model_setup->setData(model_setup->index(0, 5), tr("sonar")); + musicSelectPlay->setSource(QUrl::fromLocalFile("/usr/share/ukui-clock/sonar.wav")); + break; + case 3: + model_setup->setData(model_setup->index(0, 5), tr("drip")); + musicSelectPlay->setSource(QUrl::fromLocalFile("/usr/share/ukui-clock/drip.wav")); + break; + default: + break; + } + defaultBellBtn->textLabel->setText(model_setup->index(0, 5).data().toString()); + Default_ringtone->close(); + model_setup->submitAll(); + musicSelectPlay->play(); +} + + + + + +void setuppage::updateLabelStyle(QLabel *temp, QString text, int heightMove) +{ + temp->setText(text); + temp->resize(70,36); + temp->setAlignment(Qt::AlignLeft|Qt::AlignVCenter); + temp->setStyleSheet("font-size:14px;"); + QString selfFont = Utils::loadFontHuaKangJinGangHeiRegularTTF(); + QFont f(selfFont); + temp->setFont(f); + int labelLeftSpace = 22; + temp->move(labelLeftSpace, heightMove); +} + + +void setuppage::paintEvent(QPaintEvent *event) +{ + + Q_UNUSED(event); + QPainter p(this); + p.setRenderHint(QPainter::Antialiasing); + QPainterPath rectPath; + rectPath.addRoundedRect(this->rect().adjusted(10, 10, -10, -10), 10, 10); + // 画一个黑底 + QPixmap pixmap(this->rect().size()); + pixmap.fill(Qt::transparent); + QPainter pixmapPainter(&pixmap); + pixmapPainter.setRenderHint(QPainter::Antialiasing); + pixmapPainter.setPen(Qt::transparent); + pixmapPainter.setBrush(QColor(0,0,0,100)); + pixmapPainter.drawPath(rectPath); + pixmapPainter.end(); + + // 模糊这个黑底 + QImage img = pixmap.toImage(); + qt_blurImage(img, 10, false, false); + + // 挖掉中心 + pixmap = QPixmap::fromImage(img); + QPainter pixmapPainter2(&pixmap); + pixmapPainter2.setRenderHint(QPainter::Antialiasing); + pixmapPainter2.setCompositionMode(QPainter::CompositionMode_Clear); + pixmapPainter2.setPen(Qt::transparent); + pixmapPainter2.setBrush(Qt::transparent); + pixmapPainter2.drawPath(rectPath); + + // 绘制阴影 + p.drawPixmap(this->rect(), pixmap, pixmap.rect()); + + QStyleOption opt; + opt.init(this); + QColor mainColor; + mainColor = theme::dialogBackcolcr; + + + // 绘制一个背景 + p.save(); + p.fillPath(rectPath,mainColor); + p.restore(); + + +} + +/** + * @brief 事件拦截器 + */ +bool setuppage::eventFilter(QObject *watched, QEvent *event) +{ + return QWidget::eventFilter(watched,event); +} + +//实现响应函数 +void setuppage::showPaint() +{ +} + +//实现响应函数 +void setuppage::showPaint1() +{ + +} +/** + * @brief 颜色切换 + */ +void setuppage::showPaint2() +{ + QColor ColorPlaceholderText(248,163,76,255); + QBrush brush3; + brush3.setColor(ColorPlaceholderText); + QStyleOption opt; + opt.init(this); + + + +} diff --git a/setupPage.ui b/setupPage.ui new file mode 100644 index 0000000..3f612e8 --- /dev/null +++ b/setupPage.ui @@ -0,0 +1,114 @@ + + + setuppage + + + + 0 + 0 + 328 + 450 + + + + Form + + + + + + + + 0 + 0 + 328 + 450 + + + + + + + + + 100 + 400 + 197 + 24 + + + + + + + Qt::Horizontal + + + + + + 284 + 14 + 30 + 30 + + + + + 30 + 30 + + + + + 30 + 30 + + + + + + + + + + 30 + 10 + 81 + 50 + + + + font: "Noto Sans Bengali"; +font-size:18px; + + + setting + + + + + + 30 + 66 + 68 + 30 + + + + + true + + + + + + + Mute + + + + + + + diff --git a/singleApplication.cpp b/singleApplication.cpp new file mode 100644 index 0000000..070cb3e --- /dev/null +++ b/singleApplication.cpp @@ -0,0 +1,116 @@ +/* +* 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 3, or (at your option) +* any later version. +* +* This program is distributed in the hope that it will be useful, +* but WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +* GNU General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, see +#include + +#define TIME_OUT (500) // 500ms + +SingleApplication::SingleApplication(int &argc, char **argv) + : QApplication(argc, argv) + , w(NULL) + , _isRunning(false) + , _localServer(NULL) { + + // 取应用程序名作为LocalServer的名字 + // Take the application name as the name of localserver + _serverName = QFileInfo(QCoreApplication::applicationFilePath()).fileName() + QLatin1String(getenv("DISPLAY")); + _initLocalConnection(); +} + + +// 检查是否已經有一个实例在运行, true - 有实例运行, false - 没有实例运行 +// Check whether there is an instance running, true - there is an instance running, false - there is no instance running +bool SingleApplication::isRunning() { + return _isRunning; +} + + +// 通过socket通讯实现程序单实例运行,监听到新的连接时触发该函数 +// The single instance of the program is run through socket communication, which is triggered when listening to a new connection +void SingleApplication::_newLocalConnection() +{ + //返回下一个挂起的连接,作为连接的QLocalSocket对象。 + QLocalSocket *socket = _localServer->nextPendingConnection(); + if (socket) { + //该函数将阻塞,直到可以读取数据并且发出readyRead()信号为止。 该函数将在毫秒毫秒后超时; 默认超时为30000毫秒。 + // 如果有可供读取的数据,则该函数返回true;否则返回false 否则返回false(如果发生错误或操作超时)。 + socket->waitForReadyRead(2*TIME_OUT); + //关闭socket + delete socket; + + // 其他处理,如:读取启动参数 + // Other processing, such as reading start parameters + _activateWindow(); + } +} + +// 通过socket通讯实现程序单实例运行, +// Through socket communication, the single instance of program can be run, +// 初始化本地连接,如果连接不上server,则创建,否则退出 +// Initialize the local connection. If the server cannot be connected, create it. Otherwise, exit +void SingleApplication::_initLocalConnection() +{ + _isRunning = false; + + QLocalSocket socket; + socket.connectToServer(_serverName); + //建立链接,超时时间500ms + if (socket.waitForConnected(TIME_OUT)) { + fprintf(stderr, "%s already running.\n", + _serverName.toLocal8Bit().constData()); + //有连接,改状态,直接返回 + _isRunning = true; + // 其他处理,如:将启动参数发送到服务端 + // Other processing, such as sending startup parameters to the server + return; + } + + //连接不上服务器,就创建一个 + // If you can't connect to the server, create a + _newLocalServer(); +} + +// 创建LocalServer +// Create localserver +void SingleApplication::_newLocalServer() +{ + _localServer = new QLocalServer(this); + //信号:每当有新的连接 + connect(_localServer, SIGNAL(newConnection()), this, SLOT(_newLocalConnection())); + if (!_localServer->listen(_serverName)) { + // 此时监听失败,可能是程序崩溃时,残留进程服务导致的,移除之 + // At this time, listening fails. It may be caused by the residual process service when the program crashes. Remove it + if (_localServer->serverError() == QAbstractSocket::AddressInUseError) { + QLocalServer::removeServer(_serverName); // <-- 重点 a key + _localServer->listen(_serverName); // 再次监听 + // Monitor again + } + } +} + +// 激活主窗口 +// Activate main window +void SingleApplication::_activateWindow() { + if (w) { + w->show(); + w->raise(); + w->activateWindow(); // 激活窗口 + // Activate window + } +} diff --git a/singleApplication.h b/singleApplication.h new file mode 100644 index 0000000..416927e --- /dev/null +++ b/singleApplication.h @@ -0,0 +1,61 @@ +/* +* 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 3, or (at your option) +* any later version. +* +* This program is distributed in the hope that it will be useful, +* but WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +* GNU General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, see +#include +#include +#include "clock.h" + +class SingleApplication : public QApplication { + Q_OBJECT +public: + SingleApplication(int &argc, char **argv); + + bool isRunning(); //是否已经有实例在运行 + // Whether an instance is already running + Clock *w; // Widget指针 + // Widget pointer + +private slots: + // 有新连接时触发 + // Triggered when there is a new connection + void _newLocalConnection(); + +private: + // 初始化本地连接 + // Initialize local connection + void _initLocalConnection(); + // 创建服务端 + // Create server + void _newLocalServer(); + // 激活窗口 + // Activate window + void _activateWindow(); + + bool _isRunning; // 是否已經有实例在运行 + // Whether an instance is already running + QLocalServer *_localServer; // 本地socket Server + // Local socket server + QString _serverName; // 服务名称 + // Service name +}; + + +#endif // SINGLEAPPLICATION_H diff --git a/stopwatch.ui b/stopwatch.ui new file mode 100644 index 0000000..485ef6c --- /dev/null +++ b/stopwatch.ui @@ -0,0 +1,298 @@ + + + stopwatch + + + + 0 + 0 + 454 + 660 + + + + stopwatch + + + background-color: rgb(14, 19, 22); + + + + + + 40 + 60 + 51 + 26 + + + + + + + + + + 190 + 60 + 51 + 26 + + + + + + + + + + 330 + 60 + 51 + 26 + + + + + + + + + + 50 + 90 + 41 + 18 + + + + color: rgb(255, 255, 255); + + + 倒计时 + + + + + + 200 + 90 + 31 + 18 + + + + color: rgb(255, 255, 255); + + + 闹钟 + + + + + + 340 + 90 + 31 + 21 + + + + color: rgb(255, 255, 255); + + + 秒表 + + + + + + 0 + 120 + 660 + 1 + + + + color: rgb(255, 255, 255); +background-color: rgb(102, 102, 102); + + + + Qt::Horizontal + + + + + + 370 + 10 + 31 + 31 + + + + + + + + + + 410 + 10 + 31 + 31 + + + + + + + + + + 0 + 130 + 451 + 531 + + + + 1 + + + + + + + + 180 + 350 + 80 + 80 + + + + color: rgb(255, 255, 255); +background-color: rgb(255, 255, 255); + + + + + + + + + 20 + 360 + 20 + 91 + + + + color: rgb(255, 255, 255); +font: 24pt "Sans Serif"; +background-color: rgb(14, 19, 22); + + + + + + 200 + 60 + 81 + 20 + + + + color: rgb(255, 255, 255); +color: rgb(148, 148, 148); +font: 12pt "Sans Serif"; + + + 00:00:00 + + + + + + 140 + 0 + 191 + 51 + + + + color: rgb(255, 255, 255); +text-decoration: underline; +font: 9pt "Sans Serif"; +font: 36pt "Sans Serif"; + + + 00:00:00 + + + + + + 310 + 470 + 80 + 26 + + + + color: rgb(255, 255, 255); + + + 复位 + + + + + + 60 + 470 + 80 + 26 + + + + color: rgb(255, 255, 255); + + + 计次 + + + + + + 50 + 130 + 80 + 26 + + + + PushButton + + + + + + 250 + 140 + 55 + 18 + + + + TextLabel + + + + + + + + diff --git a/stopwatchItem.cpp b/stopwatchItem.cpp new file mode 100644 index 0000000..bb7970f --- /dev/null +++ b/stopwatchItem.cpp @@ -0,0 +1,128 @@ +/* +* 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 3, or (at your option) +* any later version. +* +* This program is distributed in the hope that it will be useful, +* but WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +* GNU General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, see +#include + +stopwatch_item::stopwatch_item(QWidget *parent) : + QWidget(parent) +{ + setupUi(this); + this->setFixedSize(340, 58); + stopwatch1 = new QLabel(this);//计次 + stopwatch1->move(13, 11); + stopwatch1->setFixedSize(100, 17); + stopwatch1->setText("计次"); + + + stopwatch2 = new QLabel( this);//间隔 + stopwatch2->move(13, 32); + stopwatch2->setFixedSize(138, 19); + stopwatch2->setText("工作日"); + stopwatch2->setVisible(true); + + stopwatch3 = new QLabel(this);//记次时间 + stopwatch3->move(183,13); + stopwatch3->setFixedSize(143, 54); + stopwatch3->setStyleSheet("font-size:24px;"); + stopwatch3->setAlignment(Qt::AlignRight); + stopwatch3->setText("00:00"); + stopwatch3->setVisible(true); + + tipLabel = new QLabel(this);//最长最短标记 + tipLabel->move(150,30); + tipLabel->setFixedSize(32, 20); + tipLabel->setAlignment(Qt::AlignCenter); + tipLabel->setText(tr("max")); + tipLabel->hide(); + + settingsStyle(); +} + +stopwatch_item::~stopwatch_item() +{ +} + +void stopwatch_item::setupUi(QWidget *stopwatch_item) +{ + if (stopwatch_item->objectName().isEmpty()) + stopwatch_item->setObjectName(QString::fromUtf8("stopwatch_item")); + stopwatch_item->resize(340, 58); + + retranslateUi(stopwatch_item); + + QMetaObject::connectSlotsByName(stopwatch_item); +} // setupUi + +void stopwatch_item::retranslateUi(QWidget *stopwatch_item) +{ + stopwatch_item->setWindowTitle(QApplication::translate("stopwatch_item", "Form", nullptr)); +} // retranslateUi + +/* +*监听主题 +*/ +void stopwatch_item::settingsStyle() +{ + GsettingSubject * subject = GsettingSubject::getInstance();; + connect(subject,&GsettingSubject::blackStyle, this,[=](){ + this->blackStyle(); + }); + connect(subject,&GsettingSubject::whiteStyle, this,[=](){ + this->whiteStyle(); + }); + subject->iniWidgetStyle(); +} + +//黑色主题 +void stopwatch_item::blackStyle() +{ + stopwatch1->setStyleSheet("color:rgba(255, 255, 255, 0.9);font-size:12px;"); + stopwatch2->setStyleSheet("font-size:12px;color:rgba(255, 255, 255, 0.55);"); + stopwatch3->setStyleSheet("color: rgba(255, 255, 255, 0.9)"); +} +//白色主题 +void stopwatch_item::whiteStyle() +{ + stopwatch1->setStyleSheet("color:rgba(49, 66, 89, 1);font-size:12px;"); + stopwatch2->setStyleSheet("font-size:12px;color:rgba(49, 66, 89, 0.5);"); + stopwatch3->setStyleSheet("color: rgba(49, 66, 89, 0.9)"); +} + +void stopwatch_item::updateTipCommonStyle() +{ + tipLabel->hide(); +} + +void stopwatch_item::updateTipLongestStyle() +{ + tipLabel->setText(tr("max")); + QString itemRadius = QString::number(ITEM_RADIUS); + tipLabel->setStyleSheet("QLabel{background-color:rgba(114, 46, 209, 255);border-radius: "+itemRadius+"px;color: white;text-align: center;font-size:12px;}"); + tipLabel->show(); +} + +void stopwatch_item::updateTipShortestStyle() +{ + tipLabel->setText(tr("min")); + QString itemRadius = QString::number(ITEM_RADIUS); + tipLabel->setStyleSheet("QLabel{background-color:rgba(55, 144, 250, 255);border-radius: "+itemRadius+"px;color: white;text-align: center;font-size:12px;}"); + tipLabel->show(); +} + + diff --git a/stopwatchItem.h b/stopwatchItem.h new file mode 100644 index 0000000..1c41a35 --- /dev/null +++ b/stopwatchItem.h @@ -0,0 +1,59 @@ +/* +* 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 3, or (at your option) +* any later version. +* +* This program is distributed in the hope that it will be useful, +* but WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +* GNU General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, see +#include +#include +#include "constant_class.h" +#include "gsettingsubject.h" + + +namespace Ui { +class stopwatch_item; +} + +class stopwatch_item : public QWidget +{ + Q_OBJECT + +public: + explicit stopwatch_item(QWidget *parent = nullptr); + ~stopwatch_item(); + void setupUi(QWidget *stopwatch_item); + void retranslateUi(QWidget *stopwatch_item); + void settingsStyle(); + void blackStyle(); //黑色主题 + void whiteStyle(); //白色主题 + + QLabel *stopwatch1; + QLabel *stopwatch2; + QLabel *stopwatch3; + QLabel *tipLabel; + + QFrame *stopwatch_line; + void updateTipCommonStyle(); + void updateTipLongestStyle(); + void updateTipShortestStyle(); + +private: + Ui::stopwatch_item *ui; +}; + +#endif // STOPWATCH_ITEM_H diff --git a/theme.cpp b/theme.cpp new file mode 100644 index 0000000..af287bc --- /dev/null +++ b/theme.cpp @@ -0,0 +1,190 @@ +/* +* Copyright (C) 2020, 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 3, or (at your option) +* any later version. +* +* This program is distributed in the hope that it will be useful, +* but WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +* GNU General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, see +#include +#include +/** + * QT主题 + */ +//#define THEME_QT_SCHEMA "org.ukui.style" +//#define MODE_QT_KEY "style-name" + +#define WHITE_BACK_COLOR 255, 255, 255,255 +#define BLACK_BACK_COLOR 18, 18, 18,255 +#define DIALOG_BACK_COLOR_WHITE_STYLE 255, 255, 255,255 +#define DIALOG_BACK_COLOR_BLACK_STYLE 26, 26, 26,255 +#define SELECT_DIALOG_BACK_COLOR_WHITE_STYLE 255, 255, 255,255 +#define SELECT_DIALOG_BACK_COLOR_BLACK_STYLE 51, 51, 51,255 +#define ITEM_BACK_COLOR_WHITE_STYLE 247, 247, 247,255 +#define ITEM_BACK_COLOR_BLACK_STYLE 41, 41, 41,255 +#define BTN_BACK_COLOR_WHITE_STYLE 240, 240, 240,255 +#define BTN_BACK_COLOR_BLACK_STYLE 55, 55, 59,255 +#define SWITCH_BTN_BACK_COLOR_WHITE_STYLE 233,233,233,255 +#define SWITCH_BTN_BACK_COLOR_BLACK_STYLE 72,72,76,255 +#define COUNTDOWN_RING_BACKCOLOR_WHITE_STYLE 247, 247, 247,255 +#define COUNTDOWN_RING_BACKCOLOR_BLACK_STYLE 37,37,37,255 +#define TINY_BTN_BACK_COLOR_WHITE_STYLE 233,233,233,255 +#define TINY_BTN_BACK_COLOR_BLACK_STYLE 65,65,65,255 +#define BODER_COLOR_WHITE_STYLE 0,0,0,40 +#define BODER_COLOR_BLACK_STYLE 0,0,0,40 +QColor theme::backcolcr=QColor(WHITE_BACK_COLOR); +QColor theme::dialogBackcolcr=QColor(DIALOG_BACK_COLOR_WHITE_STYLE); +QColor theme::selectDialogBackcolcr=QColor(SELECT_DIALOG_BACK_COLOR_WHITE_STYLE); +QColor theme::itemBackColor=QColor(ITEM_BACK_COLOR_WHITE_STYLE); +QColor theme::selectBtnBackColor=QColor(BTN_BACK_COLOR_WHITE_STYLE); +QColor theme::switchBtnBackColor=QColor(SWITCH_BTN_BACK_COLOR_WHITE_STYLE); +QColor theme::timeScrollBackColor=QColor(BTN_BACK_COLOR_WHITE_STYLE); +QColor theme::countdownRingBackColor=QColor(COUNTDOWN_RING_BACKCOLOR_WHITE_STYLE); +QColor theme::tinyBtnBackColor=QColor(TINY_BTN_BACK_COLOR_WHITE_STYLE); +QColor theme::boderColor=QColor(BODER_COLOR_WHITE_STYLE); + +//主题 +int theme::themetype=0; +theme::theme(QObject *parent) : QObject(parent) +{ + + //const QByteArray idd(THEME_QT_SCHEMA); + if (QGSettings::isSchemaInstalled(ORG_UKUI_STYLE)){ + qtSettings = new QGSettings(ORG_UKUI_STYLE); + + } else { + //qCritical() <get(STYLE_NAME) + QString currentThemeMode =qtSettings->get(STYLE_NAME).toString(); + setColorByTheme(currentThemeMode); + connect(qtSettings, &QGSettings::changed, this, [=]{ + QString currentThemeMode = qtSettings->get(STYLE_NAME).toString(); + setColorByTheme(currentThemeMode); + }); +} +theme::~theme() +{ + delete qtSettings; +} + +void theme::setColorByTheme(QString currentThemeMode) +{ + if ("ukui-white" == currentThemeMode) { + backcolcr=QColor(WHITE_BACK_COLOR); + itemBackColor=QColor(ITEM_BACK_COLOR_WHITE_STYLE); + selectBtnBackColor=QColor(BTN_BACK_COLOR_WHITE_STYLE); + switchBtnBackColor=QColor(SWITCH_BTN_BACK_COLOR_WHITE_STYLE); + timeScrollBackColor=QColor(BTN_BACK_COLOR_WHITE_STYLE); + dialogBackcolcr=QColor(DIALOG_BACK_COLOR_WHITE_STYLE); + selectDialogBackcolcr=QColor(SELECT_DIALOG_BACK_COLOR_WHITE_STYLE); + countdownRingBackColor=QColor(COUNTDOWN_RING_BACKCOLOR_WHITE_STYLE); + tinyBtnBackColor=QColor(TINY_BTN_BACK_COLOR_WHITE_STYLE); + boderColor=QColor(BODER_COLOR_WHITE_STYLE); + themetype=0; + }else if ("ukui-light" == currentThemeMode) { + backcolcr=QColor(WHITE_BACK_COLOR); + itemBackColor=QColor(ITEM_BACK_COLOR_WHITE_STYLE); + selectBtnBackColor=QColor(BTN_BACK_COLOR_WHITE_STYLE); + switchBtnBackColor=QColor(SWITCH_BTN_BACK_COLOR_WHITE_STYLE); + timeScrollBackColor=QColor(BTN_BACK_COLOR_WHITE_STYLE); + dialogBackcolcr=QColor(DIALOG_BACK_COLOR_WHITE_STYLE); + selectDialogBackcolcr=QColor(SELECT_DIALOG_BACK_COLOR_WHITE_STYLE); + countdownRingBackColor=QColor(COUNTDOWN_RING_BACKCOLOR_WHITE_STYLE); + tinyBtnBackColor=QColor(TINY_BTN_BACK_COLOR_WHITE_STYLE); + boderColor=QColor(BODER_COLOR_WHITE_STYLE); + themetype=0; + }else if ("ukui-dark" == currentThemeMode) { + backcolcr=QColor(BLACK_BACK_COLOR); + itemBackColor=QColor(ITEM_BACK_COLOR_BLACK_STYLE); + selectBtnBackColor=QColor(BTN_BACK_COLOR_BLACK_STYLE); + switchBtnBackColor=QColor(SWITCH_BTN_BACK_COLOR_BLACK_STYLE); + timeScrollBackColor=QColor(BTN_BACK_COLOR_BLACK_STYLE); + dialogBackcolcr=QColor(DIALOG_BACK_COLOR_BLACK_STYLE); + selectDialogBackcolcr=QColor(SELECT_DIALOG_BACK_COLOR_BLACK_STYLE); + countdownRingBackColor=QColor(COUNTDOWN_RING_BACKCOLOR_BLACK_STYLE); + tinyBtnBackColor=QColor(TINY_BTN_BACK_COLOR_BLACK_STYLE); + boderColor=QColor(BODER_COLOR_BLACK_STYLE); + themetype=1; + }else if ("ukui-black" == currentThemeMode) { + backcolcr=QColor(BLACK_BACK_COLOR); + itemBackColor=QColor(ITEM_BACK_COLOR_BLACK_STYLE); + selectBtnBackColor=QColor(BTN_BACK_COLOR_BLACK_STYLE); + switchBtnBackColor=QColor(SWITCH_BTN_BACK_COLOR_BLACK_STYLE); + timeScrollBackColor=QColor(BTN_BACK_COLOR_BLACK_STYLE); + dialogBackcolcr=QColor(DIALOG_BACK_COLOR_BLACK_STYLE); + selectDialogBackcolcr=QColor(SELECT_DIALOG_BACK_COLOR_BLACK_STYLE); + countdownRingBackColor=QColor(COUNTDOWN_RING_BACKCOLOR_BLACK_STYLE); + tinyBtnBackColor=QColor(TINY_BTN_BACK_COLOR_BLACK_STYLE); + boderColor=QColor(BODER_COLOR_BLACK_STYLE); + themetype=1; + }else if ("" == currentThemeMode) { + backcolcr=QColor(WHITE_BACK_COLOR); + itemBackColor=QColor(ITEM_BACK_COLOR_WHITE_STYLE); + selectBtnBackColor=QColor(BTN_BACK_COLOR_WHITE_STYLE); + switchBtnBackColor=QColor(SWITCH_BTN_BACK_COLOR_WHITE_STYLE); + timeScrollBackColor=QColor(BTN_BACK_COLOR_WHITE_STYLE); + dialogBackcolcr=QColor(DIALOG_BACK_COLOR_WHITE_STYLE); + selectDialogBackcolcr=QColor(SELECT_DIALOG_BACK_COLOR_WHITE_STYLE); + countdownRingBackColor=QColor(COUNTDOWN_RING_BACKCOLOR_WHITE_STYLE); + tinyBtnBackColor=QColor(TINY_BTN_BACK_COLOR_WHITE_STYLE); + boderColor=QColor(BODER_COLOR_WHITE_STYLE); + themetype=0; + } else{ + backcolcr=QColor(WHITE_BACK_COLOR); + itemBackColor=QColor(ITEM_BACK_COLOR_WHITE_STYLE); + selectBtnBackColor=QColor(BTN_BACK_COLOR_WHITE_STYLE); + switchBtnBackColor=QColor(SWITCH_BTN_BACK_COLOR_WHITE_STYLE); + timeScrollBackColor=QColor(BTN_BACK_COLOR_WHITE_STYLE); + dialogBackcolcr=QColor(DIALOG_BACK_COLOR_WHITE_STYLE); + selectDialogBackcolcr=QColor(SELECT_DIALOG_BACK_COLOR_WHITE_STYLE); + countdownRingBackColor=QColor(COUNTDOWN_RING_BACKCOLOR_WHITE_STYLE); + tinyBtnBackColor=QColor(TINY_BTN_BACK_COLOR_WHITE_STYLE); + boderColor=QColor(BODER_COLOR_WHITE_STYLE); + themetype=0; + } +} +QPixmap theme::changeIconColor(QPixmap pixmap, QColor color) +{ + QPixmap target = pixmap; + QPainter p(&target); + p.setRenderHint(QPainter::Antialiasing); + p.setRenderHint(QPainter::SmoothPixmapTransform); + p.setCompositionMode(QPainter::CompositionMode_SourceIn); + p.fillRect(target.rect(), color); + return target; +} +QString theme::getColorStr(QColor color) +{ + QString colorInfo=""+QString::number(color.red())+","+QString::number(color.green()) + +","+QString::number(color.blue())+","+QString::number(color.alpha()); + return "rgba("+colorInfo+")"; +} +QColor theme::highLight_Click() +{ + return QColor(41, 108, 217); +} +QColor theme::highLight_Hover() +{ + return QColor(64, 169, 251); +} +QColor theme::button_Click() +{ + return QColor(217, 217, 217); +} + +QColor theme::button_Hover() +{ + return QColor(235, 235, 235); +} diff --git a/theme.h b/theme.h new file mode 100644 index 0000000..911670c --- /dev/null +++ b/theme.h @@ -0,0 +1,60 @@ +/* +* Copyright (C) 2020, 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 3, or (at your option) +* any later version. +* +* This program is distributed in the hope that it will be useful, +* but WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +* GNU General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, see +#include +#include +#include +#include "constant_class.h" +class theme : public QObject +{ + Q_OBJECT +public: + explicit theme(QObject *parent = nullptr); + QGSettings* qtSettings; + static QString backcolor_str; + static QColor backcolcr; + static QColor dialogBackcolcr; + static QColor selectDialogBackcolcr; + static QColor itemBackColor; + static QColor selectBtnBackColor; + static QColor switchBtnBackColor; + static QColor timeScrollBackColor; + static QColor countdownRingBackColor; + static QColor tinyBtnBackColor; + static QColor boderColor; + static int themetype; + ~theme(); + static QPixmap changeIconColor(QPixmap pixmap, QColor color); + static QString getColorStr(QColor color); + static QColor highLight_Hover(); + static QColor button_Click(); + static QColor button_Hover(); + static QColor highLight_Click(); +signals: +private: + void setColorByTheme(QString currentThemeMode); +}; +#define COUNTDOWN_RING_BACKCOLOR_WHITE_STYLE 240,240,240,255 +#define BORDERCOLOR_ALPHAF 0.15 +#define SHADOWCOLOR_ALPHAF 0.16 +const static int SHADOW_RANGE=8; +const static int VAGUE_RADIUS=15; +const static double BORDER_RANGE=0.5; +#endif // THEME_H diff --git a/tinycountdown.cpp b/tinycountdown.cpp new file mode 100644 index 0000000..32949ad --- /dev/null +++ b/tinycountdown.cpp @@ -0,0 +1,353 @@ +/* +* Copyright (C) 2020, 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 3, or (at your option) +* any later version. +* +* This program is distributed in the hope that it will be useful, +* but WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +* GNU General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, see +#include "utils.h" +extern void qt_blurImage(QImage &blurImage, qreal radius, bool quality, int transposed); +tinyCountdown::tinyCountdown(QWidget *parent) : + QWidget(parent), + ui(new Ui::tinyCountdown) +{ + ui->setupUi(this); + + //右上角关闭 + closeStyle(); + switchStyle(); + suspendRunBtnStyle(); + finishBtnStyle(); + connect(ui->closeBtn, SIGNAL(clicked()), this, SLOT(set_dialog_close()) ); + //左上闹钟图标 + ui->clockIcon->setPixmap(QIcon::fromTheme("kylin-alarm-clock").pixmap(24,24)); + //闹钟时间字体改为灰色 + QPalette pa; + pa.setColor(QPalette::WindowText,Qt::gray); + //主窗口connect + connect(ui->mainBtn, SIGNAL(clicked()), this, SLOT(showMainWindow()) ); + //显示,但不可移动 + settingsStyle(); + updateWidgetRadius(); + +} + + +void tinyCountdown::updateWidgetRadius() +{ + + this->setAttribute(Qt::WA_TranslucentBackground);//设置窗口背景透明 + this->setWindowFlags(Qt::FramelessWindowHint|Qt::ToolTip); //设置无边框窗口 + this->setAttribute(Qt::WA_AlwaysShowToolTips); +// Qt::WindowFlags m_flags = windowFlags(); +// this->setWindowFlags(m_flags | Qt::WindowStaysOnTopHint); + + // 添加窗管协议 + XAtomHelper::setStandardWindowHint(this->winId()); + //圆角 + QBitmap bmp(this->size()); + bmp.fill(); + QPainter p(&bmp); + p.setRenderHint(QPainter::Antialiasing); // 反锯齿; + p.setPen(Qt::NoPen); + p.setBrush(palette().color(QPalette::Base)); + p.drawRoundedRect(bmp.rect(),WINDOWN_RADIUS,WINDOWN_RADIUS); + setMask(bmp); +} + +tinyCountdown::~tinyCountdown() +{ + delete ui; +} +/** + * @brief 显示倒计时时间 + */ +void tinyCountdown::updateTimeInfo(QString str) +{ + ui->timeLabel->setText(str); + ui->timeLabel->setAlignment(Qt::AlignVCenter); +} + + +/* +void tinyCountdown::focusOutEvent(QFocusEvent *event) +{ + qDebug()<<"dbq-"<<"focusOutEvent"; +} + +void tinyCountdown::focusInEvent(QFocusEvent *event) +{ + qDebug()<<"dbq-"<<"focusInEvent"; +} +*/ +// 在鼠标光标在小部件内部时按下鼠标按钮时调用,或者当小部件使用grabMouse ()抓住鼠标时调用。按下鼠标而不释放它实际上与调用grabMouse ()相同。 +void tinyCountdown::mousePressEvent(QMouseEvent *event) +{ + if (event->button() == Qt::LeftButton) { + this->dragPosition = event->globalPos() - frameGeometry().topLeft(); + this->mousePressed = true; + } + QWidget::mousePressEvent(event); +} +//在鼠标按钮被释放时被调用。当小部件接收到相应的鼠标按下事件时,它就会接收鼠标释放事件。这意味着如果用户在您的小部件内按下鼠标,然后在释放鼠标按钮之前将鼠标拖动到其他地方,您的小部件将收到释放事件。 +void tinyCountdown::mouseReleaseEvent(QMouseEvent *event) +{ + + if (event->button() == Qt::LeftButton) { + this->mousePressed = false; + } + + QWidget::mouseReleaseEvent(event); + this->setCursor(Qt::ArrowCursor); +} +//每当鼠标移动而按住鼠标按钮时调用。这在拖放操作期间很有用。 +void tinyCountdown::mouseMoveEvent(QMouseEvent *event) +{ + + + if (this->mousePressed) { + move(event->globalPos() - this->dragPosition); + this->setCursor(Qt::ClosedHandCursor); + } + + QWidget::mouseMoveEvent(event); +} + + + +void tinyCountdown::closeEvent(QCloseEvent *event) +{ + event->ignore();//忽视 + this->hide(); +} + +void tinyCountdown::paintEvent(QPaintEvent * event) +{ + Q_UNUSED(event); + QPainter p(this); + p.setRenderHint(QPainter::Antialiasing); + QPainterPath rectPath; + rectPath.addRoundedRect(this->rect().adjusted(SHADOW_RANGE, SHADOW_RANGE, -SHADOW_RANGE, -SHADOW_RANGE), WINDOWN_RADIUS, WINDOWN_RADIUS); + // 画一个黑底 + QPixmap pixmap(this->rect().size()); + pixmap.fill(Qt::transparent); + QPainter pixmapPainter(&pixmap); + pixmapPainter.setRenderHint(QPainter::Antialiasing); + auto shadowColor = palette().text().color(); + shadowColor.setAlphaF(SHADOWCOLOR_ALPHAF); + pixmapPainter.setBrush(shadowColor); + pixmapPainter.setPen(Qt::transparent); + pixmapPainter.drawPath(rectPath); + pixmapPainter.end(); + // 模糊这个黑底 + QImage img = pixmap.toImage(); + qt_blurImage(img, VAGUE_RADIUS, false, false); + // 挖掉中心 + pixmap = QPixmap::fromImage(img); + QPainter pixmapPainter2(&pixmap); + pixmapPainter2.setRenderHint(QPainter::Antialiasing); + pixmapPainter2.setCompositionMode(QPainter::CompositionMode_Clear); + pixmapPainter2.setPen(Qt::transparent); + pixmapPainter2.setBrush(Qt::transparent); + pixmapPainter2.drawPath(rectPath); + // 绘制阴影 + p.drawPixmap(this->rect(), pixmap, pixmap.rect()); + QStyleOption opt; + opt.init(this); + // 绘制一个背景 + p.save(); + //描边 + QColor borderColor = palette().text().color(); + borderColor.setAlphaF(BORDERCOLOR_ALPHAF); + p.setPen(borderColor); + p.translate(BORDER_RANGE, BORDER_RANGE); + p.setBrush(palette().color(QPalette::Base)); + p.drawPath(rectPath); + p.restore(); +} + + + + +/** + * @brief 清空数据 + */ +void tinyCountdown::clearData() +{ + ui->timeLabel->setText("00:00:00"); + this->hide(); + updateOnRunState(true); +} + + + +void tinyCountdown::set_dialog_close() +{ + this->hide(); +} + +void tinyCountdown::showMainWindow() +{ + this->hide(); + emit mainWindowClick(); +} + + + +void tinyCountdown::showTop() +{ + this->hide(); + this->update(); + this->show(); +} + +void tinyCountdown::updateOnRunState(int onRun) +{ + m_onRun = onRun; + suspendRunBtnIcon(theme::themetype); +} + + + + + + + +void tinyCountdown::settingsStyle() +{ + GsettingSubject * subject = GsettingSubject::getInstance();; + connect(subject,&GsettingSubject::blackStyle, this,[=](){ + this->blackStyle(); + }); + connect(subject,&GsettingSubject::whiteStyle, this,[=](){ + this->whiteStyle(); + }); + connect(subject,&GsettingSubject::iconChnaged, this,[=](){ + ui->clockIcon->setPixmap(QIcon::fromTheme("kylin-alarm-clock").pixmap(24,24)); + }); + subject->iniWidgetStyle(); +} + +void tinyCountdown::whiteStyle() +{ + ui->mainBtn->setIcon(QIcon(":image/miniIcon/restore_active-w.png")); + finishBtnIcon(0); + suspendRunBtnIcon(0); +} + +void tinyCountdown::blackStyle() +{ + ui->mainBtn->setIcon(QIcon(":image/miniIcon/restore-active-b.png")); + finishBtnIcon(1); + suspendRunBtnIcon(1); +} +void tinyCountdown::closeStyle() +{ + ui->closeBtn->setToolTip(tr("close")); + ui->closeBtn->setIcon(QIcon::fromTheme("window-close-symbolic")); + ui->closeBtn->setProperty("isWindowButton", 0x2); + ui->closeBtn->setProperty("useIconHighlightEffect", 0x8); + ui->closeBtn->setFlat(true); +} +void tinyCountdown::switchStyle() +{ + ui->mainBtn->setToolTip(tr("main window")); + ui->mainBtn->setProperty("useButtonPalette", true); + ui->mainBtn->setIcon(QIcon(":image/miniIcon/restore_active-w.png")); + ui->mainBtn->setIconSize(QSize(24,24)); + //手动改成透明色 + Utils::setBtnBackgroundColorTransparent(ui->mainBtn); +} +/** + * @brief 暂停运行按钮样式 + */ +void tinyCountdown::suspendRunBtnStyle() +{ + ui->suspendRunBtn->setToolTip(tr("suspend")); + ui->suspendRunBtn->setRadius(14); + ui->suspendRunBtn->setFlag(RoundBtn::ICON_FLAG); + ui->suspendRunBtn->setIconSize(QSize(32,32)); + QColor defaultColor = QColor(0, 0, 0, 0); + ui->suspendRunBtn->setBtnColor(defaultColor,defaultColor,defaultColor); + //初始化是运行中 + m_onRun = true; + suspendRunBtnIcon(theme::themetype); + connect(ui->suspendRunBtn,&QPushButton::clicked,this,[=](){ + m_onRun = !m_onRun; + suspendRunBtnIcon(theme::themetype); + emit suspendClick(m_onRun); + }); + +} + +void tinyCountdown::finishBtnStyle() +{ + ui->finishBtn->setToolTip(tr("finish")); + ui->finishBtn->setRadius(12); + ui->finishBtn->setFlag(RoundBtn::ICON_FLAG); + ui->finishBtn->setIconSize(QSize(28,28)); + QColor defaultColor = QColor(0, 0, 0, 0); + ui->finishBtn->setBtnColor(defaultColor,defaultColor,defaultColor); + finishBtnIcon(theme::themetype); + connect(ui->finishBtn,&QPushButton::clicked,this,[=](){ + emit finishClick(); + }); + +} + +void tinyCountdown::finishBtnIcon(int themeStatus) +{ + if(themeStatus==0){ + ui->finishBtn->setAllIconPatn(":image/miniIcon/finish-light-normal.png" + ,":image/miniIcon/finish-light-hover.png" + ,":image/miniIcon/finish-light-click.png"); + }else{ + ui->finishBtn->setAllIconPatn(":image/miniIcon/finish-dark-normal.png" + ,":image/miniIcon/finish-dark-hover.png" + ,":image/miniIcon/finish-dark-click.png"); + } +} + +void tinyCountdown::suspendRunBtnIcon(int themeStatus) +{ + qDebug()<<"dbq-m_onRun"<suspendRunBtn->setAllIconPatn(":image/miniIcon/suspend-normal-light.png" + ,":image/miniIcon/suspend-hover-light.png" + ,":image/miniIcon/suspend-click-light.png"); + }else{ + ui->suspendRunBtn->setAllIconPatn(":image/miniIcon/suspend-normal-dark.png" + ,":image/miniIcon/suspend-hover-dark.png" + ,":image/miniIcon/suspend-click-dark.png"); + } + }else{ + if(themeStatus==0){ + ui->suspendRunBtn->setAllIconPatn(":image/miniIcon/start-normal-light.png" + ,":image/miniIcon/start-hover-light.png" + ,":image/miniIcon/start-hover-light.png"); + }else{ + ui->suspendRunBtn->setAllIconPatn(":image/miniIcon/start-normal-dark.png" + ,":image/miniIcon/start-hover-dark.png" + ,":image/miniIcon/start-hover-dark.png"); + } + } +} + + + + diff --git a/tinycountdown.h b/tinycountdown.h new file mode 100644 index 0000000..25a21aa --- /dev/null +++ b/tinycountdown.h @@ -0,0 +1,95 @@ +/* +* Copyright (C) 2020, 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 3, or (at your option) +* any later version. +* +* This program is distributed in the hope that it will be useful, +* but WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +* GNU General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, see +#include +#include +#include "constant_class.h" +#include +#include +#include +#include +#include +#include +#include "gsettingsubject.h" +#include "xatom-helper.h" +#include "commontooltip.h" +namespace Ui { +class tinyCountdown; +} + +class tinyCountdown : public QWidget +{ + Q_OBJECT + +public: + explicit tinyCountdown(QWidget *parent = nullptr); + ~tinyCountdown(); + void updateTimeInfo(QString str); + + void mousePressEvent(QMouseEvent *event) override; + void mouseReleaseEvent(QMouseEvent *event) override; + void mouseMoveEvent(QMouseEvent *event) override; + + /* + void focusOutEvent ( QFocusEvent * event ) override; + void focusInEvent ( QFocusEvent * event ) override; +*/ + + void closeEvent(QCloseEvent *event) override; + void paintEvent(QPaintEvent * event) override; + void updateWidgetRadius(); + + void clearData(); +protected: + //绘制背景 + // Draw background + + +signals: + void mainWindowClick(); + void finishClick(); + void suspendClick(int m_onRun); + +public slots: + void set_dialog_close(); + void showTop(); + void updateOnRunState(int onRun); +private slots: + void showMainWindow(); + + +private: + Ui::tinyCountdown *ui; + bool mousePressed; + QPoint dragPosition; //拖动坐标 + void closeStyle(); + void settingsStyle(); + void whiteStyle(); + void blackStyle(); + void switchStyle(); + void suspendRunBtnStyle(); + void finishBtnStyle(); + void finishBtnIcon(int themeStatus); + void suspendRunBtnIcon(int themeStatus); + bool m_onRun = false; +}; + +#endif // TINYCOUNTDOWN_H diff --git a/tinycountdown.ui b/tinycountdown.ui new file mode 100644 index 0000000..b108bf1 --- /dev/null +++ b/tinycountdown.ui @@ -0,0 +1,200 @@ + + + tinyCountdown + + + + 0 + 0 + 336 + 62 + + + + + 336 + 62 + + + + + 336 + 62 + + + + Form + + + + 8 + + + 20 + + + 16 + + + + + + 24 + 24 + + + + + 24 + 24 + + + + 0 + + + + + + + + + 94 + 32 + + + + + 92 + 32 + + + + + 18 + + + + 01:29:58 + + + Qt::AlignLeading|Qt::AlignLeft|Qt::AlignVCenter + + + + + + + + 32 + 32 + + + + + 32 + 32 + + + + + + + + 32 + 32 + + + + + + + + true + + + + 28 + 28 + + + + + 28 + 28 + + + + + + + + 28 + 28 + + + + + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + + 24 + 24 + + + + + 24 + 24 + + + + + + + + + + + + 24 + 24 + + + + + 24 + 24 + + + + + + + + + + + + RoundBtn + QPushButton +
roundbtn.h
+
+
+ + +
diff --git a/translations/ukui-clock_bo_CN.ts b/translations/ukui-clock_bo_CN.ts new file mode 100644 index 0000000..98738cc --- /dev/null +++ b/translations/ukui-clock_bo_CN.ts @@ -0,0 +1,1002 @@ + + + + + Clock + + + Clock + + + + + + + + + start + + + + + + + + + 00:00:00 + + + + + 5min + + + + + 15min + + + + + 25min + + + + + 30min + + + + + 60min + + + + + + + + suspend + + + + Remind + Hatırlat + + + + + + + + + + + + PM + + + + + add alarm + + + + + + Remaining time + + + + + reset + + + + + + count + + + + + Count down + + + + + + + + Alarm + + + + Stopwatch + Kronometre + + + + deletealarm + + + + + + Preservation + + + + + 12hour43minThe bell rings + + + + + cancel + + + + + + New alarm + + + + + Name + + + + + repeat + + + + + + + Remind + + + + + ring time + + + + ring time + Çalma Zamanı + + + + On + + + + + + Continue + + + + + interval + + + + + + + + + + + + AM + + + + + + + + + 2min + + + + + + + + 3min + + + + + + + + 4min + + + + + + + + 6min + + + + + + + + + + + No repetition + + + + + Seconds to close + + + + + + + + + Workingday + + + + + + + (default) + + + + + + Please set alarm name! + + + + + hour + + + + + + + min bell rings + + + + + Edit alarm clock + + + + 点击闹钟显示剩余时间 + Alarm saatini düzenle + + + + Count + + + + + Watch + + + + + days + + + + + + hour + + + + + + + + + + + + + + glass + + + + + + + + + + + + bark + + + + + + + + + + + + sonar + + + + + + + + + + + + drip + + + + + 360 Seconds to close + + + + + Time out + + + + + End + + + + + after tomorrow + + + + + Tomorrow + + + + + + hour + + + + + + min + + + + + sec + + + + + + + + Mon + + + + + + + + Tue + + + + + + + + Wed + + + + + + + + Thu + + + + + + + + Fri + + + + + + + + Sat + + + + + + + + Sun + + + + + + + + Every day + + + + + + work + + + + + 工作日 + + + + + 不重复 + + + + + glass(default) + + + + + bark(default) + + + + + sonar(default) + + + + + drip(default) + + + + + + 1min + + + + + Monday to Friday + + + + + 24 hour system + + + + + Notification + + + + + Alert in 2 minutes + + + + + Natice_alarm + + + Form + + + + + Alarm clock + + + + + 工作会议 + + + + + 10 : 45 + + + + + Remind later + + + + + close + + + + + Ring prompt + + + + + + glass + + + + + + bark + + + + + + sonar + + + + + drip + + + + + Seconds to close + + + + + Notice_Dialog + + + Ring prompt + + + + + + glass + + + + + + bark + + + + + + sonar + + + + + drip + + + + + End of countdown time + + + + + Dialog + + + + + 秒后关闭铃声 + + + + + 闹钟: + + + + + 起床铃 + + + + + TestWidget + + + TestWidget + + + + + VerticalScroll_24 + + + PM + + + + + AM + + + + + VerticalScroll_24 + + + + + VerticalScroll_60 + + + VerticalScroll_60 + + + + + VerticalScroll_99 + + + VerticalScroll_99 + + + + + close_or_hide + + + Dialog + + + + + sure + + + + + cancel + + + + + backstage + + + + backstage + Arka Çalış + + + + Exit program + + + + + delete_msg + + + Dialog + + + + + sure + + + + + cancel + + + + + are you sure ? + + + + + item_new + + + Form + + + + + set_alarm_repeat_Dialog + + + Dialog + + + + + setuppage + + + Form + + + + Boot up + Önyükleme + + + + work + + + + + Time + + + + + Pop-up + + + + + duration + + + + + ringtone + + + + + Mute + + + + work + İş + + + Time + Zaman + + + Pop-up + Açılır + + + duration + Süre + + + ringtone + Zil sesi + + + Mute + Sessiz + + + + volume + + + + + setting + + + + + + + Mon + + + + + + + Tue + + + + + + + Wed + + + + + + + Thu + + + + + + + Fri + + + + + + + Sat + + + + + + + Sun + + + + + Every day + + + + + + + Following system + + + + + + + 24 hour system + + + + + + + 12 hour system + + + + + + + Notification + + + + + + + Full screen + + + + + + + Alert in 2 minutes + + + + + + + Alert in 5 minutes + + + + + + + Alert in 10 minutes + + + + + + + Alert in 30 minutes + + + + + + + Alert in 60 minutes + + + + + + + glass + + + + + + + bark + + + + + + + sonar + + + + + + + drip + + + + + stopwatch_item + + + Form + + + + diff --git a/translations/ukui-clock_fr.ts b/translations/ukui-clock_fr.ts new file mode 100644 index 0000000..7bb57bf --- /dev/null +++ b/translations/ukui-clock_fr.ts @@ -0,0 +1,1002 @@ + + + + + Clock + + + Clock + Horloge + + + + + + + + start + début + + + + + + + + 00:00:00 + 00:00:00 + + + + 5min + 5min + + + + 15min + 15min + + + + 25min + 25min + + + + 30min + 30min + + + + 60min + 60min + + + + + + + suspend + suspendre + + + Remind + Hatırlat + + + + + + + + + + + + PM + Après-midi + + + + add alarm + ajouter une alarme + + + + + Remaining time + Temps restant + + + + reset + réinitialiser + + + + + count + compter + + + + Count down + Compte à rebours + + + + + + + Alarm + Alarme + + + Stopwatch + Kronometre + + + + deletealarm + supprimer l'alarme + + + + + Preservation + Préservation + + + + 12hour43minThe bell rings + 12h43min La cloche sonne + + + + cancel + Annuler + + + + + New alarm + Nouvelle alarme + + + + Name + Nom + + + + repeat + répéter + + + + + + Remind + Rappeler + + + + ring time + temps de sonnerie + + + ring time + Çalma Zamanı + + + + On + Activé + + + + + Continue + Continuer + + + + interval + intervalle + + + + + + + + + + + AM + Matin + + + + + + + + 2min + 2min + + + + + + + 3min + 3min + + + + + + + 4min + 4min + + + + + + + 6min + 6min + + + + + + + + + + No repetition + Pas de répétition + + + + Seconds to close + Secondes pour fermer + + + + + + + + Workingday + Jour ouvrable + + + + + + (default) + (défaut) + + + + + Please set alarm name! + Veuillez définir le nom de l'alarme ! + + + + hour + heure + + + + + + min bell rings + min cloche sonne + + + + Edit alarm clock + Modifier le réveil + + + 点击闹钟显示剩余时间 + Alarm saatini düzenle + + + + Count + Compter + + + + Watch + Regarder + + + + days + journées + + + + + hour + heure + + + + + + + + + + + + + glass + verre + + + + + + + + + + + bark + écorce + + + + + + + + + + + sonar + sonar + + + + + + + + + + + drip + goutte + + + + 360 Seconds to close + 360 secondes pour fermer + + + + Time out + Temps expiré + + + + End + Fin + + + + after tomorrow + après-demain + + + + Tomorrow + Demain + + + + + hour + heure + + + + + min + min + + + + sec + seconde + + + + + + + Mon + Lun + + + + + + + Tue + Mar + + + + + + + Wed + Mer + + + + + + + Thu + Jeu + + + + + + + Fri + Ven + + + + + + + Sat + Sam + + + + + + + Sun + Dim + + + + + + + Every day + Tous les jours + + + + + work + travail + + + + 工作日 + Jour ouvrable + + + + 不重复 + Ne pas répéter + + + + glass(default) + verre (par défaut) + + + + bark(default) + écorce (par défaut) + + + + sonar(default) + sonar (par défaut) + + + + drip(default) + goutte à goutte (par défaut) + + + + + 1min + 1min + + + + Monday to Friday + Lundi à vendredi + + + + 24 hour system + Système 24 heures + + + + Notification + Notification + + + + Alert in 2 minutes + Alerte dans 2 minutes + + + + Natice_alarm + + + Form + Forme + + + + Alarm clock + Réveil + + + + 工作会议 + å · ¥ 作会议 + + + + 10 : 45 + 10 : 45 + + + + Remind later + Rappeler plus tard + + + + close + Fermer + + + + Ring prompt + Invite de sonnerie + + + + + glass + verre + + + + + bark + écorce + + + + + sonar + sonar + + + + drip + goutte + + + + Seconds to close + Secondes pour fermer + + + + Notice_Dialog + + + Ring prompt + Invite de sonnerie + + + + + glass + verre + + + + + bark + écorce + + + + + sonar + sonar + + + + drip + goutte + + + + End of countdown time + Fin du compte à rebours + + + + Dialog + Dialogue + + + + 秒后关闭铃声 + Éteindre la sonnerie en quelques secondes + + + + 闹钟: + Réveil : + + + + 起床铃 + Réveiller la cloche + + + + TestWidget + + + TestWidget + TestWidget + + + + VerticalScroll_24 + + + PM + PM + + + + AM + Matin + + + + VerticalScroll_24 + VerticalScroll_24 + + + + VerticalScroll_60 + + + VerticalScroll_60 + VerticalScroll_60 + + + + VerticalScroll_99 + + + VerticalScroll_99 + VerticalScroll_99 + + + + close_or_hide + + + Dialog + Dialogue + + + + sure + sûr + + + + cancel + Annuler + + + + backstage + dans les coulisses + + + backstage + Arka Çalış + + + + Exit program + Quitter le programme + + + + delete_msg + + + Dialog + Dialogue + + + + sure + sûr + + + + cancel + Annuler + + + + are you sure ? + êtes-vous sûr ? + + + + item_new + + + Form + Forme + + + + set_alarm_repeat_Dialog + + + Dialog + Dialogue + + + + setuppage + + + Form + Forme + + + Boot up + Önyükleme + + + + work + travail + + + + Time + Temps + + + + Pop-up + Pop-up + + + + duration + durée + + + + ringtone + sonnerie + + + + Mute + Muet + + + work + İş + + + Time + Zaman + + + Pop-up + Açılır + + + duration + Süre + + + ringtone + Zil sesi + + + Mute + Sessiz + + + + volume + volume + + + + setting + réglage + + + + + + Mon + Lun + + + + + + Tue + Mar + + + + + + Wed + Mer + + + + + + Thu + Jeu + + + + + + Fri + Ven + + + + + + Sat + Sam + + + + + + Sun + Dim + + + + Every day + Tous les jours + + + + + + Following system + Système suivant + + + + + + 24 hour system + Système 24 heures + + + + + + 12 hour system + Système 12 heures + + + + + + Notification + Notification + + + + + + Full screen + Plein écran + + + + + + Alert in 2 minutes + Alerte dans 2 minutes + + + + + + Alert in 5 minutes + Alerte dans 5 minutes + + + + + + Alert in 10 minutes + Alerte dans 10 minutes + + + + + + Alert in 30 minutes + Alerte dans 30 minutes + + + + + + Alert in 60 minutes + Alerte dans 60 minutes + + + + + + glass + verre + + + + + + bark + écorce + + + + + + sonar + sonar + + + + + + drip + goutte + + + + stopwatch_item + + + Form + Forme + + + diff --git a/translations/ukui-clock_tr.qm b/translations/ukui-clock_tr.qm new file mode 100644 index 0000000..a4e58d1 Binary files /dev/null and b/translations/ukui-clock_tr.qm differ diff --git a/translations/ukui-clock_tr.ts b/translations/ukui-clock_tr.ts new file mode 100644 index 0000000..24257f7 --- /dev/null +++ b/translations/ukui-clock_tr.ts @@ -0,0 +1,1175 @@ + + + + + About + + + Dialog + + + + + + Alarm + Saat + + + Kylin Alarm + kylin saat + + + Clock + kapat + + + Kylin Clock + kylin saat + + + + About + hakkında + + + + Version: + + + + Version: 2020.1.0 + Versyon: 2020.1.8 + + + + + Service & Support: + + + + Support and service team: support@kylinos.cn + Destek ve hizmet ekibi:support@kylinos.cn + + + + Clock + + Clock + Saat + + + + + + + + + start + Başlat + + + + + + 00:00:00 + + + + 5min + 5 dk + + + 15min + 15 dk + + + 25min + 25 dk + + + 30min + 30 dk + + + 60min + 60 dk + + + + + + + suspend + Askıya Al + + + + icon + + + + + add + Ekle + + + + no alarm + no Alarm + + + delete + Sil + + + + save + Cts + + + Remind + Hatırlat + + + + + + + PM + ÖS + + + add alarm + Alarm Ekle + + + Remaining time + Kalan süre + + + + reset + Sıfırla + + + + + + count + İşaret + + + + + + + Count down + Geri Sayım + + + + + + Alarm + Alarm + + + Stopwatch + Kronometre + + + deletealarm + Alarmı Sil + + + Preservation + Kaydet + + + 12hour43minThe bell rings + 12 saat 43 dk zil çalıyor + + + + cancel + İptal + + + New alarm + Yeni Alarm + + + Name + İsim + + + + repeat + Tekrarla + + + Remind + Hatırlat + + + ring time + Çalma Zamanı + + + ring time + Çalma Zamanı + + + + On + Açık + + + Continue + Devam Et + + + + interval + Aralık + + + + + + AM + ÖÖ + + + + 2min + 2 dk + + + + remind + + + + + 3min + 3 dk + + + + 4min + 4 dk + + + + 6min + 6 dk + + + + + + + + + + + No repetition + Tekrar yok + + + Seconds to close + saniye sonra kapanacak + + + + + + + + Workingday + İş günü + + + + (default) + (varsayılan) + + + + + Please set alarm name! + Lütfen alarm adını ayarlayın! + + + hour + Saat + + + min bell rings + dk sonra alarm çalar + + + Edit alarm clock + Alarm saatini düzenle + + + 点击闹钟显示剩余时间 + Alarm saatini düzenle + + + Count + Geri Sayım + + + + + Watch + Kronometre + + + days + gün + + + hour + Saat + + + + glass + Bardak + + + + + + bell + + + + + Minimize + küçültmek + + + + + Quit + Çık + + + + Menu + Menü + + + + Help + Yardım + + + bark + Havlama + + + + name + + + + + edit + + + + sonar + Sonar + + + drip + Damla + + + + up to 100 times + + + + + mute + + + + + All bells are off + + + + 360 Seconds to close + Kapatmak için 360 Saniye + + + Time out + Zaman doldu + + + + End + Son + + + + after tomorrow + Yarından sonra + + + + Tomorrow + Yarın + + + + + hour + Saat + + + + + min + Dk + + + + sec + Sn + + + + + + + Mon + Pzt + + + close + Kapat + + + + Delete + Sil + + + + ClearAll + + + + + + continue + + + + Set Up + ayarlandır + + + + About + hakkında + + + + Close + kapat + + + + recent alarm + + + + + + + + Tue + Sal + + + + + + + Wed + Çar + + + + + + + Thu + Per + + + + + + + Fri + Cum + + + + + + + Sat + Cts + + + + + + + Sun + Paz + + + + + + + Every day + Her gün + + + + + + + + none + + + + + warning + + + + + the number of alarms reaches limit!! + + + + + yes + + + + + + work + İş + + + + 工作日 + + + + + 不重复 + + + + + 60 Seconds to close + Kapatmak için 360 Saniye {60 ?} + + + + + five mins late + + + + + + ten mins late + + + + + + twenty mins late + + + + + + thirsty mins late + + + + + + one hour late + + + + + mini window + + + + glass(default) + Bardak (varsayılan) + + + bark(default) + Havlama (varsayılan) + + + sonar(default) + Sonar(varsayılan) + + + drip(default) + Damla(varsayılan) + + + 1min + 2 dk + + + Monday to Friday + Pazartesiden Cumaya + + + 24 hour system + 24 saat düzeni + + + Notification + Bildirim + + + Alert in 2 minutes + 2 dakika içinde uyar + + + + Natice_alarm + + + Form + + + + + Alarm clock + Saat + + + + 11:20 设计例会... + + + + 工作会议 + Toplantı + + + + Remind later + Hatırlat + + + close + Kapat + + + + Ring prompt + Çalma İsteği + + + + none + + + + + Time out + Zaman doldu + + + glass + Bardak + + + bark + Havlama + + + sonar + Sonar + + + drip + Damla + + + + Seconds to close + dakika sonra kapanacak + + + + Notice_Dialog + + Ring prompt + Çalma İsteği + + + glass + Bardak + + + bark + Havlama + + + sonar + Sonar + + + drip + Damla + + + End of countdown time + dk sonra kapanacak + + + 秒后关闭铃声 + Zili saniyeler içinde kapatın + + + 闹钟: + Alarm saati: + + + 起床铃 + Uyandırma zili + + + + QObject + + + Hint + + + + + Are you sure to delete? + + + + + sure + Tamam + + + + cancel + İptal + + + + SelectBtnUtil + + + glass + Bardak + + + + bark + Havlama + + + + sonar + Sonar + + + + drip + Damla + + + + diy bell + + + + + none + + + + + select bell + + + + + audio files(*mp3 *wav *ogg) + + + + + TestWidget + + + TestWidget + + + + + VerticalScroll_24 + + + PM + ÖS + + + + AM + ÖÖ + + + + VerticalScroll_24 + + + + + VerticalScroll_60 + + + VerticalScroll_60 + + + + + VerticalScroll_99 + + + VerticalScroll_99 + + + + + close_or_hide + + + Dialog + + + + + sure + Tamam + + + + 请选择关闭后的状态 + + + + + cancel + İptal + + + + backstage + Arka Çalış + + + backstage + Arka Çalış + + + + Exit program + Kapat + + + + Please select the state after closing: + + + + + delete_msg + + + Dialog + + + + + sure + Tamam + + + + cancel + İptal + + + + are you sure ? + Emin misiniz? + + + + item_new + + + Form + + + + + set_alarm_repeat_Dialog + + + Alarm + Alarm + + + + Dialog + + + + + setuppage + + 开机启动 + Başlat + + + Boot up + Önyükleme + + + work + İş + + + Time + Zaman + + + Pop-up + Açılır + + + duration + Süre + + + ringtone + Zil sesi + + + Mute + Sessiz + + + work + İş + + + Time + Zaman + + + Pop-up + Açılır + + + duration + Süre + + + ringtone + Zil sesi + + + Mute + Sessiz + + + volume + Ses + + + setting + Ayar + + + Mon + Pzt + + + Tue + Sal + + + Wed + Çar + + + Thu + Per + + + Fri + Cum + + + Sat + Cts + + + Sun + Paz + + + Every day + Her Gün + + + Following system + Takip sistemi + + + 24 hour system + 24 saat düzeni + + + 12 hour system + 12 saat düzeni + + + Notification + Bildirim + + + Full screen + Tam ekran + + + Alert in 2 minutes + 2 dakika içinde uyar + + + Alert in 5 minutes + 5 dakika içinde uyar + + + Alert in 10 minutes + 10 dakika içinde uyar + + + Alert in 30 minutes + 30 dakika içinde uyar + + + Alert in 60 minutes + 60 dakika içinde uyar + + + glass + Bardak + + + bark + Havlama + + + sonar + Sonar + + + drip + Damla + + + + stopwatch_item + + + Form + + + + + + max + + + + + min + Dk + + + + tinyCountdown + + + Form + + + + + 01:29:58 + + + + + close + Kapat + + + + main window + + + + + suspend + Askıya Al + + + + finish + + + + diff --git a/translations/ukui-clock_zh_CN.qm b/translations/ukui-clock_zh_CN.qm new file mode 100644 index 0000000..880313f Binary files /dev/null and b/translations/ukui-clock_zh_CN.qm differ diff --git a/translations/ukui-clock_zh_CN.ts b/translations/ukui-clock_zh_CN.ts new file mode 100644 index 0000000..e9043e3 --- /dev/null +++ b/translations/ukui-clock_zh_CN.ts @@ -0,0 +1,1663 @@ + + + + + About + + + Dialog + + + + + + Alarm + 闹钟 + + + Kylin Alarm + 麒麟 闹钟 + + + Clock + 闹钟 + 闹钟 + + + Kylin Clock + 麒麟 闹钟 + 麒麟 闹钟 + + + + About + 关于 + 关于 + + + + Version: + 版本: + 版本: + + + Version: 2020.1.0 + 版本: 2020.1.22 + 版本: 2020.1.22 + + + + + Service & Support: + 服务与支持团队: + 服务与支持团队: + + + Support and service team: support@kylinos.cn + 服务与支持团队: support@kylinos.cn + 服务与支持团队: support@kylinos.cn + + + + Clock + + Clock + 闹钟 + 闹钟 + + + + + + + + + start + 开始 + 开始 + + + 5min + 5分钟 + 5分钟 + + + 15min + 15分钟 + 15分钟 + + + 25min + 25分钟 + 25分钟 + + + 30min + 30分钟 + + + 60min + 60分钟 + + + + + + + suspend + 暂停 + + + tiny window + 迷你窗口 + + + + add + 添加 + 添加 + + + + no alarm + 无闹钟 + 无闹钟 + + + delete + 删除 + 删除 + + + + save + 保存 + 保存 + + + Remind + 提醒铃声 + + + + + + + PM + 下午 + + + add alarm + 添加 + 添加 + + + Remaining time + 点击闹钟显示剩余时间 + + + + reset + 复位 + + + + + + count + 计次 + + + + + + + Count down + 倒计时 + + + clock + 闹钟 + + + Stopwatch + 秒表 + + + deletealarm + 删除闹铃 + + + Preservation + 保存 + + + 12hour43minThe bell rings + 12小时43分后铃声响 + + + + cancel + 取消 + + + New alarm + 新建闹钟 + + + Name + 闹钟名 + + + + repeat + 重复 + + + Remind + 铃声 + + + ring time + 铃声时长 + + + ring time + 铃声时长 + + + 开始 + start + start + + + + + + 00:00:00 + + + + 5分钟 + 5min + 5min + + + 10分钟 + 10min + 10min + + + 20分钟 + 20min + 20min + + + 30分钟 + 30min + 30min + + + 60分钟 + 60min + 60min + + + 下午05:31 + PM + PM + + + 暂停 + suspend + suspend + + + 提醒铃声 + Remind + Remind + + + 添加闹钟 + add alarm + add alarm + + + Continue + 继续 + + + + interval + 间隔 + + + + recent alarm + 最近闹钟 + + + + + + AM + 上午 + + + + + + + Mon + 周一 + + + + + + + Tue + 周二 + + + + + + + Wed + 周三 + + + + + + + Thu + 周四 + + + + + + + Fri + 周五 + + + + + + + Sat + 周六 + + + + + + + Sun + 周日 + + + + 60 Seconds to close + 60秒后自动关闭 + + + + + five mins late + 5分钟后 + + + + + ten mins late + 10分钟后 + + + + + twenty mins late + 20分钟后 + + + + + thirsty mins late + 30分钟后 + + + + + one hour late + 1小时后 + + + + mini window + 小窗显示 + + + + 2min + 2分钟 + + + + + + Alarm + 闹钟 + + + Count + 计次 + + + + + Watch + 秒表 + + + + icon + + + + + + + bell + 铃声 + + + + Minimize + 最小化 + 最小化 + + + + + Quit + 退出 + 退出 + + + + Menu + 菜单 + 菜单 + + + + Delete + 删除 + 删除 + + + + ClearAll + 全部清空 + 全部清空 + + + Set Up + 设置 + 设置 + + + help + 帮助 + 帮助 + + + + Help + 帮助 + 帮助 + + + + About + 关于 + 关于 + + + + Close + 退出 + 退出 + + + + up to 100 times + 最多可记100次 + + + + remind + 稍后提醒 + + + + name + 闹钟名 + + + &Quit + 退出 + + + + edit + 编辑 + + + + mute + 静音 + + + + All bells are off + 所有铃声已关闭 + + + + 3min + 3分钟 + + + + 4min + 4分钟 + + + + 6min + 6分钟 + + + + + + + + + + + No repetition + 不重复 + + + Seconds to close + 秒后关闭 + + + + + + + + Workingday + 工作日 + + + + (default) + (默认) + + + + + + + + none + + + + + + Please set alarm name! + 请设置闹钟名! + 请设置闹钟名! + + + hour + 小时 + + + min bell rings + 分钟后铃响 + + + Edit alarm clock + 编辑闹钟 + + + 点击闹钟显示剩余时间 + Remaining time + Remaining time + + + days + + + + hour + 小时 + + + + glass + 玻璃 + + + minimize + 最小化 + 最小化 + + + close + 关闭 + 关闭 + + + menu + 菜单 + 菜单 + + + bark + 犬吠 + + + sonar + 声呐 + + + drip + 雨滴 + + + + + continue + 继续 + + + + warning + 警告 + + + + the number of alarms reaches limit!! + 闹钟数量已达上限! + + + + yes + 确认 + + + + + work + 工作日 + + + + 工作日 + + + + 360 Seconds to close + 360秒后关闭 + + + Time out + 时间到 + + + + End + 结束 + + + + after tomorrow + 后天 + + + + Tomorrow + 明天 + + + + + hour + + + + + + min + + + + + sec + + + + + + + + Every day + 每天 + + + glass(default) + 玻璃(默认) + + + bark(default) + 犬吠(默认) + + + sonar(default) + 声呐(默认) + + + drip(default) + 雨滴(默认) + + + 1min + 1分钟 + + + Monday to Friday + 周一周二周三周四周五 + + + 24 hour system + 24小时制 + + + Notification + 通知栏弹窗 + + + Alert in 2 minutes + 2分钟后提醒 + + + 复位 + reset + reset + + + 计次 + count + count + + + 删除闹铃 + deletealarm + deletealarm + + + 保存 + Preservation + Preservation + + + 倒计时 + Count down + Count down + + + 闹钟 + Alarm + Alarm + + + 秒表 + Stopwatch + Stopwatch + + + 12小时43分后铃声响 + 12hour43minThe bell rings + 12hour43minThe bell rings + + + 取消 + cancel + cancel + + + 新建闹钟 + New alarm + New alarm + + + 闹钟名 + Name + Name + + + 重复 + repeat + repeat + + + 铃声时长 + ring time + ring time + + + + On + on + + + 继续 + Continue + Continue + + + 间隔 + interval + interval + + + 下午 + PM + PM + + + 上午 + AM + AM + + + 周一 + Mon + Mon + + + 周二 + Tue + Tue + + + 周三 + Wed + Wed + + + 周四 + Thu + Thu + + + 周五 + Fri + Fri + + + 周六 + Sat + Sat + + + 周日 + Sun + Sun + + + 秒后自动关闭 + Seconds to close + Seconds to close + + + 2分钟后提醒 + Alert in 2 minutes + + + 5分钟后提醒 + Alert in 5 minutes + + + 10分钟后提醒 + Alert in 10 minutes + + + 30分钟后提醒 + Alert in 30 minutes + + + 60分钟后提醒 + Alert in 60 minutes + + + 天 + days + + + 玻璃 + glass + glass + + + 犬吠 + bark + bark + + + 声呐 + sonar + sonar + + + 雨滴 + drip + drip + + + 2分钟 + 2min + 2min + + + 3分钟 + 3min + 3min + + + 4分钟 + 4min + 4min + + + 6分钟 + 6min + 6min + + + 工作日 + Workingday + Workingday + + + (默认) + (default) + (default) + + + 每天 + Every day + Every day + + + 1分钟 + 1min + 1min + + + 小时 + hour + hour + + + 分钟后铃响 + min bell rings + min bell rings + + + 编辑闹钟 + Edit alarm clock + Edit alarm clock + + + 删除当前闹钟! + delete alame clock ! + delete alame clock ! + + + 您确定删除当前闹钟吗? + are you sure ? + are you sure ? + + + 倒计时时间结束 + End of countdown time + End of countdown time + + + 结束 + End + End + + + 明日 + Tom + Tom + + + 360秒后自动关闭 + 360 Seconds to close + 360 Seconds to close + + + 时间到 + Time out + + + 后天 + after tomorrow + after tomorrow + + + 明天 + Tomorrow + Tomorrow + + + 时 + hour + hour + + + 分 + min + min + + + 秒 + sec + sec + + + + 不重复 + No repetition + No repetition + + + 玻璃(默认) + glass(default) + glass(default) + + + 犬吠(默认) + bark(default) + bark(default) + + + 声呐(默认) + sonar(default) + sonar(default) + + + 雨滴(默认) + drip(default) + drip(default) + + + 1分钟(默认) + 1min(default) + 1min(default) + + + 2分钟(默认) + 2min(default) + 2min(default) + + + 3分钟(默认) + 3min(default) + 3min(default) + + + 4分钟(默认) + 4min(default) + 4min(default) + + + 6分钟(默认) + 6min(default) + 6min(default) + + + 周一周二周三周四周五 + Monday to Friday + + + 24小时制(23:59:59) + 24 hour system + 24 hour system + + + 通知栏弹窗 + Notification + Notification + + + 一分钟后自动关闭 + Turn off after 1 min + Turn off after 1 min + + + + Natice_alarm + + + Form + + + + + Alarm clock + 闹钟 + + + + 11:20 设计例会... + + + + 60秒后自动关闭 + 360 Seconds to close {60秒?} + + + + Remind later + 稍后提醒 + + + close + 关闭 + + + + Ring prompt + 响铃提示 + + + + none + + + + + Time out + 时间到 + + + glass + 玻璃 + + + bark + 犬吠 + + + sonar + 声呐 + + + drip + 雨滴 + + + + Seconds to close + 秒后自动关闭 + + + + Notice_Dialog + + Ring prompt + 响铃提示 + + + glass + 玻璃 + + + bark + 犬吠 + + + sonar + 声呐 + + + drip + 雨滴 + + + End of countdown time + End of countdown time + + + 秒后关闭铃声 + 秒后关闭铃声 + + + 闹钟: + 闹钟: + + + 起床铃 + 起床铃 + + + + QObject + + + Hint + + + + + Are you sure to delete? + 您确定删除当前闹钟吗? + + + + sure + 确定 + + + + cancel + 取消 + + + + SelectBtnUtil + + relax + 放松 + + + emotion + 情感 + + + silence + 静谧 + + + + glass + 玻璃 + + + + bark + 犬吠 + + + + sonar + 声呐 + + + + drip + 雨滴 + + + + diy bell + 自定义铃声 + + + + none + + + + + select bell + 选择铃声 + + + + audio files(*mp3 *wav *ogg) + 类型(*mp3 *wav *ogg) + + + + TestWidget + + + TestWidget + + + + + VerticalScroll_24 + + + PM + 下午 + + + + AM + 上午 + + + + VerticalScroll_24 + + + + + VerticalScroll_60 + + + VerticalScroll_60 + + + + + VerticalScroll_99 + + + VerticalScroll_99 + + + + + close_or_hide + + + Dialog + + + + + sure + 确定 + + + + 请选择关闭后的状态 + + + + + cancel + 取消 + + + + backstage + 后台运行 + + + backstage + 后台运行 + + + + Exit program + 直接退出 + + + + Please select the state after closing: + 请选择关闭后状态: + + + + delete_msg + + + Dialog + + + + + sure + 确定 + + + + cancel + 取消 + + + + are you sure ? + 您确定删除当前闹钟吗? + + + + item_new + + + Form + + + + + set_alarm_repeat_Dialog + + + Alarm + 闹钟 + + + + Dialog + + + + + setuppage + + 开机启动 + Boot up + Boot up + + + Boot up + 开机启动 + + + work + 工作日 + + + Time + 时间格式 + + + Pop-up + 弹窗方式 + + + duration + 稍后提醒 + + + ringtone + 默认铃声 + + + Mute + 静音 + + + work + 工作日 + + + Time + 时间格式 + + + Pop-up + 弹窗方式 + + + duration + 稍后提醒 + + + ringtone + 默认铃声 + + + Mute + 静音 + + + volume + 铃声音量 + + + setting + 设置 + 设置 + + + Mon + 周一 + + + Tue + 周二 + + + Wed + 周三 + + + Thu + 周四 + + + Fri + 周五 + + + Sat + 周六 + + + Sun + 周日 + + + Every day + 每天 + + + Following system + 跟随系统 + + + time + 时间格式 + + + 24 hour system + 24小时制 + + + 12 hour system + 12小时制 + + + Notification + 通知栏弹窗 + + + Full screen + 全屏弹窗 + + + Alert in 2 minutes + 2分钟后提醒 + + + Alert in 5 minutes + 5分钟后提醒 + + + Alert in 10 minutes + 10分钟后提醒 + + + Alert in 30 minutes + 30分钟后提醒 + + + Alert in 60 minutes + 60分钟后提醒 + + + glass + 玻璃 + + + bark + 犬吠 + + + sonar + 声呐 + + + drip + 雨滴 + + + + stopwatch_item + + longest + 最长 + + + + Form + + + + + + max + 最长 + + + + min + 最短 + + + shortest + 最短 + + + + tinyCountdown + + + Form + + + + Countdown + 倒计时 + + + + 01:29:58 + + + + switch + 切换 + + + + close + 关闭 + + + + main window + 主窗口 + + + + suspend + 暂停 + + + + finish + 结束 + + + diff --git a/ukui-clock-build-deps_3.1.3-1-1000.7_all.deb b/ukui-clock-build-deps_3.1.3-1-1000.7_all.deb new file mode 100644 index 0000000..731c18a Binary files /dev/null and b/ukui-clock-build-deps_3.1.3-1-1000.7_all.deb differ diff --git a/ukui-clock.desktop b/ukui-clock.desktop new file mode 100644 index 0000000..1e3f34c --- /dev/null +++ b/ukui-clock.desktop @@ -0,0 +1,22 @@ +[Desktop Entry] +Name=Alarm +Name[zh_CN]=闹钟 +Name[tr_TR]=Çalar Saat +Name[bo_CN]=ཐིར་བརྡའི་ཆུ་ཚོད། +GenericName=Kylin Alarm +GenericName[zh_CN]=闹钟 +GenericName[tr_TR]=Ukui Çalar Saat +GenericName[bo_CN]=ཐིར་བརྡའི་ཆུ་ཚོད། +Comment=Ukui Alarm +Comment[zh_CN]=闹钟 +Comment[tr_TR]=Ukui Çalar Saat +Comment[bo_CN]=ཐིར་བརྡའི་ཆུ་ཚོད། +Keywords=guide; +Exec=/usr/bin/ukui-clock +Icon=kylin-alarm-clock +Terminal=false +Type=Application +NoDisplay=false +Categories=System;Utility; +StartupNotify=false + diff --git a/ukui-clock.pro b/ukui-clock.pro new file mode 100644 index 0000000..9700d1d --- /dev/null +++ b/ukui-clock.pro @@ -0,0 +1,187 @@ +#------------------------------------------------- +# +# Project created by QtCreator 2014-06-28T21:00:26 +# +#------------------------------------------------- + +QT += core gui multimedia sql + +# 适配窗口管理器圆角阴影 +QT += KWindowSystem dbus x11extras + +# 适配窗口管理器圆角阴影 +LIBS +=-lpthread +LIBS +=-lX11 +LIBS += -lukui-log4qt +# 配置gsettings +CONFIG += link_pkgconfig +PKGCONFIG += gsettings-qt + +greaterThan(QT_MAJOR_VERSION, 4): QT += widgets + +TARGET = ukui-clock +TEMPLATE = app + + +CONFIG += c++11 link_pkgconfig +PKGCONFIG += gsettings-qt kysdk-qtwidgets + +INCLUDEPATH += /usr/include/mpv/ +LIBS += -lmpv +# 解析音频文件 +LIBS += -lavformat + +SOURCES += \ + CustomButton.cpp \ + about.cpp \ + adaptscreeninfo.cpp \ + baseverticalscroll.cpp \ + btnNew.cpp \ + clickableLabel.cpp \ + clock.cpp \ + clockentitydao.cpp \ + clockdbusadaptor.cpp \ + closeOrHide.cpp \ + configutil.cpp \ + commontooltip.cpp \ + coreplayer/mmediaplayer.cpp \ + coreplayer/mmediaplaylist.cpp \ + coreplayer/playcontroller.cpp \ + countdownAnimation.cpp \ + dbusdeleteclockbyidadaptor.cpp \ + dbusselectclockbyidadaptor.cpp \ + dbusupdateclockadaptor.cpp \ + deleteMsg.cpp \ + dotlineDemo.cpp \ + fieldvalidutil.cpp \ + gsettingsubject.cpp \ + integer.cpp \ + itemNew.cpp \ + kylinqfiledialog.cpp \ + main.cpp \ + mediaplayerpool.cpp \ + mediaplayerthread.cpp \ + noticeAlarm.cpp \ + primarymanager.cpp \ + qroundProgressBar.cpp \ + roundbtn.cpp \ + selectbtn.cpp \ + selectbtnutil.cpp \ + setAlarmRepeatDialog.cpp \ + singleApplication.cpp \ + stopwatchItem.cpp \ + theme.cpp \ + utils.cpp \ + verticalScroll24.cpp \ + verticalScroll60.cpp \ + verticalScroll99.cpp \ + tinycountdown.cpp \ + CJsonObject.cpp \ + cJSON.c \ + xatom-helper.cpp + +TRANSLATIONS += translations/ukui-clock_tr.ts \ + translations/ukui-clock_zh_CN.ts + + + +HEADERS += clock.h \ + ClockInterface.h \ + CustomButton.h \ + about.h \ + adaptscreeninfo.h \ + baseverticalscroll.h \ + btnNew.h \ + clickableLabel.h \ + clockentitydao.h \ + clockdbusadaptor.h \ + closeOrHide.h \ + configutil.h \ + commontooltip.h \ + connection.h \ + constant_class.h \ + coreplayer/mmediaplayer.h \ + coreplayer/mmediaplaylist.h \ + coreplayer/playcontroller.h \ + countdownAnimation.h \ + dbusdeleteclockbyidadaptor.h \ + dbusselectclockbyidadaptor.h \ + dbusupdateclockadaptor.h \ + debug.h \ + deleteMsg.h \ + dotlineDemo.h \ + fieldvalidutil.h \ + gsettingsubject.h \ + integer.h \ + itemNew.h \ + kylinqfiledialog.h \ + mediaplayerpool.h \ + mediaplayerthread.h \ + noticeAlarm.h \ + object_pool.h \ + primarymanager.h \ + qroundProgressBar.h \ + roundbtn.h \ + selectbtn.h \ + selectbtnutil.h \ + setAlarmRepeatDialog.h \ + singleApplication.h \ + stopwatchItem.h \ + theme.h \ + utils.h \ + verticalScroll24.h \ + verticalScroll60.h \ + verticalScroll99.h \ + tinycountdown.h \ + CJsonObject.hpp \ + cJSON.h \ + xatom-helper.h + + +FORMS += clock.ui \ + about.ui \ + closeOrHide.ui \ + deleteMsg.ui \ + noticeAlarm.ui \ + tinycountdown.ui + + +RESOURCES += \ + images.qrc + +RC_FILE = clock.rc + +unix { + target.path = /usr/bin/ + INSTALLS += target + + music.path = /usr/share/ukui-clock/ + music.files += music/bark.wav + music.files += music/drip.wav + music.files += music/glass.wav + music.files += music/sonar.wav + INSTALLS += music + + translation.path = /usr/share/ukui-clock/ukui31 + translation.files += translations/*.qm + INSTALLS += translation + + guide.path = /usr/share/kylin-user-guide/data/guide/ukui-clock/ + guide.files += guide/* + INSTALLS += guide + + +} +desktopfile.files = ukui-clock.desktop +desktopfile.path = /usr/share/applications/ + +INSTALLS += desktopfile + +DISTFILES += \ + clock_conf.ini \ + image/DFPKingGothicGB-Semibold-2.ttf \ + image/noClockBlack.svg \ + music/bark.wav \ + music/drip.wav \ + music/glass.wav \ + music/sonar.wav diff --git a/ukui-clock.pro.user b/ukui-clock.pro.user new file mode 100644 index 0000000..b4d8fc8 --- /dev/null +++ b/ukui-clock.pro.user @@ -0,0 +1,317 @@ + + + + + + EnvironmentId + {a59d6fe1-ce4c-4f9e-af0a-b3f85c417b40} + + + ProjectExplorer.Project.ActiveTarget + 0 + + + ProjectExplorer.Project.EditorSettings + + true + false + true + + Cpp + + CppGlobal + + + + QmlJS + + QmlJSGlobal + + + 2 + UTF-8 + false + 4 + false + 80 + true + true + 1 + true + false + 0 + true + true + 0 + 8 + true + 1 + true + true + true + false + + + + ProjectExplorer.Project.PluginSettings + + + true + + + + ProjectExplorer.Project.Target.0 + + 桌面 + 桌面 + {873ec1cd-e92f-4e4b-865a-d0944351c717} + 0 + 0 + 0 + + /home/dbq/workspace/git_re/workspace/sp2/build-ukui-clock-unknown-Debug + + + true + QtProjectManager.QMakeBuildStep + true + + false + false + false + + + true + Qt4ProjectManager.MakeStep + + false + + + false + + 2 + Build + Build + ProjectExplorer.BuildSteps.Build + + + + true + Qt4ProjectManager.MakeStep + + true + clean + + false + + 1 + Clean + Clean + ProjectExplorer.BuildSteps.Clean + + 2 + false + + Debug + Qt4ProjectManager.Qt4BuildConfiguration + 2 + + + /home/dbq/workspace/git_re/workspace/sp2/build-ukui-clock-unknown-Release + + + true + QtProjectManager.QMakeBuildStep + false + + false + false + false + + + true + Qt4ProjectManager.MakeStep + + false + + + false + + 2 + Build + Build + ProjectExplorer.BuildSteps.Build + + + + true + Qt4ProjectManager.MakeStep + + true + clean + + false + + 1 + Clean + Clean + ProjectExplorer.BuildSteps.Clean + + 2 + false + + Release + Qt4ProjectManager.Qt4BuildConfiguration + 0 + + + /home/dbq/workspace/git_re/workspace/sp2/build-ukui-clock-unknown-Profile + + + true + QtProjectManager.QMakeBuildStep + true + + false + true + false + + + true + Qt4ProjectManager.MakeStep + + false + + + false + + 2 + Build + Build + ProjectExplorer.BuildSteps.Build + + + + true + Qt4ProjectManager.MakeStep + + true + clean + + false + + 1 + Clean + Clean + ProjectExplorer.BuildSteps.Clean + + 2 + false + + Profile + Qt4ProjectManager.Qt4BuildConfiguration + 0 + + 3 + + + 0 + Deploy + Deploy + ProjectExplorer.BuildSteps.Deploy + + 1 + ProjectExplorer.DefaultDeployConfiguration + + 1 + + + dwarf + + cpu-cycles + + + 250 + + -e + cpu-cycles + --call-graph + dwarf,4096 + -F + 250 + + -F + true + 4096 + false + false + 1000 + + true + + false + false + false + false + true + 0.01 + 10 + true + kcachegrind + 1 + 25 + + 1 + true + false + true + valgrind + + 0 + 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10 + 11 + 12 + 13 + 14 + + 2 + + Qt4ProjectManager.Qt4RunConfiguration:/home/dbq/workspace/git_re/workspace/sp2/ukui-clock/ukui-clock.pro + /home/dbq/workspace/git_re/workspace/sp2/ukui-clock/ukui-clock.pro + + false + + false + true + true + false + false + true + + /home/dbq/workspace/git_re/workspace/sp2/build-ukui-clock-unknown-Debug + + 1 + + + + ProjectExplorer.Project.TargetCount + 1 + + + ProjectExplorer.Project.Updater.FileVersion + 22 + + + Version + 22 + + diff --git a/ukui-clock.pro.user.324bec7 b/ukui-clock.pro.user.324bec7 new file mode 100644 index 0000000..f6af565 --- /dev/null +++ b/ukui-clock.pro.user.324bec7 @@ -0,0 +1,317 @@ + + + + + + EnvironmentId + {324bec7f-8104-44b1-8317-09374db08e54} + + + ProjectExplorer.Project.ActiveTarget + 0 + + + ProjectExplorer.Project.EditorSettings + + true + false + true + + Cpp + + CppGlobal + + + + QmlJS + + QmlJSGlobal + + + 2 + UTF-8 + false + 4 + false + 80 + true + true + 1 + true + false + 0 + true + true + 0 + 8 + true + 1 + true + true + true + false + + + + ProjectExplorer.Project.PluginSettings + + + true + + + + ProjectExplorer.Project.Target.0 + + 桌面 + 桌面 + {36c2133b-df8c-4d29-b2e2-215ec1680a62} + 0 + 0 + 0 + + /home/dbq/git_re/workspace/sp2/build-ukui-clock-unknown-Debug + + + true + QtProjectManager.QMakeBuildStep + true + + false + false + false + + + true + Qt4ProjectManager.MakeStep + + false + + + false + + 2 + Build + Build + ProjectExplorer.BuildSteps.Build + + + + true + Qt4ProjectManager.MakeStep + + true + clean + + false + + 1 + Clean + Clean + ProjectExplorer.BuildSteps.Clean + + 2 + false + + Debug + Qt4ProjectManager.Qt4BuildConfiguration + 2 + + + /home/dbq/git_re/workspace/sp2/build-ukui-clock-unknown-Release + + + true + QtProjectManager.QMakeBuildStep + false + + false + false + true + + + true + Qt4ProjectManager.MakeStep + + false + + + false + + 2 + Build + Build + ProjectExplorer.BuildSteps.Build + + + + true + Qt4ProjectManager.MakeStep + + true + clean + + false + + 1 + Clean + Clean + ProjectExplorer.BuildSteps.Clean + + 2 + false + + Release + Qt4ProjectManager.Qt4BuildConfiguration + 0 + + + /home/dbq/git_re/workspace/sp2/build-ukui-clock-unknown-Profile + + + true + QtProjectManager.QMakeBuildStep + true + + false + true + true + + + true + Qt4ProjectManager.MakeStep + + false + + + false + + 2 + Build + Build + ProjectExplorer.BuildSteps.Build + + + + true + Qt4ProjectManager.MakeStep + + true + clean + + false + + 1 + Clean + Clean + ProjectExplorer.BuildSteps.Clean + + 2 + false + + Profile + Qt4ProjectManager.Qt4BuildConfiguration + 0 + + 3 + + + 0 + Deploy + Deploy + ProjectExplorer.BuildSteps.Deploy + + 1 + ProjectExplorer.DefaultDeployConfiguration + + 1 + + + dwarf + + cpu-cycles + + + 250 + + -e + cpu-cycles + --call-graph + dwarf,4096 + -F + 250 + + -F + true + 4096 + false + false + 1000 + + true + + false + false + false + false + true + 0.01 + 10 + true + kcachegrind + 1 + 25 + + 1 + true + false + true + valgrind + + 0 + 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10 + 11 + 12 + 13 + 14 + + 2 + + Qt4ProjectManager.Qt4RunConfiguration:/home/dbq/git_re/workspace/sp2/ukui-clock/ukui-clock.pro + /home/dbq/git_re/workspace/sp2/ukui-clock/ukui-clock.pro + + false + + false + true + true + false + false + true + + /home/dbq/git_re/workspace/sp2/build-ukui-clock-unknown-Debug + + 1 + + + + ProjectExplorer.Project.TargetCount + 1 + + + ProjectExplorer.Project.Updater.FileVersion + 22 + + + Version + 22 + + diff --git a/utils.cpp b/utils.cpp new file mode 100644 index 0000000..9382b53 --- /dev/null +++ b/utils.cpp @@ -0,0 +1,164 @@ +/* +* Copyright (C) 2020, 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 3, or (at your option) +* any later version. +* +* This program is distributed in the hope that it will be useful, +* but WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +* GNU General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, see + + +/** + * @brief 移到鼠标所在屏幕中央。兼容990 + */ +Utils::Utils(QObject *parent):QObject(parent) +{ + +} + +void Utils::centerToScreen(QWidget *widget) +{ + if (!widget) + + return; + + QDesktopWidget* m = QApplication::desktop(); + + QRect desk_rect = m->screenGeometry(m->screenNumber(QCursor::pos())); + + int desk_x = desk_rect.width(); + + int desk_y = desk_rect.height(); + + int x = widget->width(); + + int y = widget->height(); + + widget->move(desk_x / 2 - x / 2 + desk_rect.left(), desk_y / 2 - y / 2 + desk_rect.top()); +} + +QString Utils::loadFontFamilyFromTTF() +{ + static QString font; + static bool loaded = false; + if(!loaded) + { + loaded = true; + int loadedFontID = QFontDatabase::addApplicationFont(":/image/DFPKingGothicGB-Semibold-2.ttf"); + QStringList loadedFontFamilies = QFontDatabase::applicationFontFamilies(loadedFontID); + if(!loadedFontFamilies.empty()) + font = loadedFontFamilies.at(0); + } + return font; +} + +QString Utils::loadFontHuaKangJinGangHeiRegularTTF() +{ + static QString font; + static bool loaded = false; + if(!loaded) + { + loaded = true; + int loadedFontID = QFontDatabase::addApplicationFont(":/image/HuaKangJinGangHei-Regular-2.ttf"); + QStringList loadedFontFamilies = QFontDatabase::applicationFontFamilies(loadedFontID); + if(!loadedFontFamilies.empty()) + font = loadedFontFamilies.at(0); + } + return font; +} + +QString Utils::getRandomId() +{ + //time(0) 随机种子 + static std::default_random_engine e(time(0)); + //5位数 + static std::uniform_int_distribution u(10000, 99999); + //转字符串 + return QString::number(u(e)); +} +/* + * 单位变双位 + * Integer to character + */ +QString Utils::changeNumToStr(int alarmHour) +{ + QString str; + if (alarmHour < 10) { + QString hours_str = QString::number(alarmHour); + str = "0"+hours_str; + } else { + str = QString::number(alarmHour); + } + return str; +} +void Utils::setBtnBackgroundColorTransparent(QPushButton *btn) +{ + QPalette pale =btn->palette(); + QColor color = pale.color(QPalette::Button); + QColor ColorPlaceholderText3 = QColor(255,255,255,0); + QBrush brush; + brush.setColor(ColorPlaceholderText3); + pale.setBrush(QPalette::Button, brush); + btn->setPalette(pale); +} + +void Utils::setBtnHighlightColorTransparent(QPushButton *btn) +{ + QPalette pale =btn->palette(); + QColor color = pale.color(QPalette::Button); + QColor ColorPlaceholderText3 = QColor(255,255,255,0); + QBrush brush; + brush.setColor(ColorPlaceholderText3); + pale.setBrush(QPalette::Highlight, brush); + btn->setPalette(pale); +} + +QIcon Utils::getQIcon(QString themeUrl, QString localUrl) +{ + QIcon icon = QIcon::fromTheme(themeUrl); + if(icon.isNull()){ + qDebug()<<"dbq-空的url"<sizeLimit){ + str = str.left(sizeLimit); + str = str+"..."; + } + return str; +} + +bool Utils::checkLocalChina() +{ + return QLocale().name()=="zh_CN"; +} +bool Utils::checkLocalUs() +{ + return QLocale().name()=="en_US"; +} +int Utils::handelColorRange(int value) +{ + if(value<0){ + return 0; + }else if(value>255){ + return 255; + }else{ + return value; + } +} + + diff --git a/utils.h b/utils.h new file mode 100644 index 0000000..faeaf7c --- /dev/null +++ b/utils.h @@ -0,0 +1,50 @@ +/* +* Copyright (C) 2020, 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 3, or (at your option) +* any later version. +* +* This program is distributed in the hope that it will be useful, +* but WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +* GNU General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, see +#include +#include +#include +#include +#include +#include +#include +#include + +class Utils :public QObject +{ + Q_OBJECT + +public: + explicit Utils(QObject *parent = nullptr); + void centerToScreen(QWidget* widget); + static QString loadFontFamilyFromTTF(); + static QString loadFontHuaKangJinGangHeiRegularTTF(); + static QString getRandomId(); + static void setBtnBackgroundColorTransparent(QPushButton * btn); + static void setBtnHighlightColorTransparent(QPushButton * btn); + static QString changeNumToStr(int alarmHour); + static QIcon getQIcon(QString themeUrl, QString localUrl); + static QString getOmitStr(QString str,int sizeLimit); + static bool checkLocalChina(); + static bool checkLocalUs(); + static int handelColorRange(int value); +}; + +#endif // UTILS_H diff --git a/verticalScroll24.cpp b/verticalScroll24.cpp new file mode 100644 index 0000000..f793a0b --- /dev/null +++ b/verticalScroll24.cpp @@ -0,0 +1,230 @@ +/* +* 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 3, or (at your option) +* any later version. +* +* This program is distributed in the hope that it will be useful, +* but WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +* GNU General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, see +#include +#include +#include "clock.h" +#include "ui_clock.h" +#include +VerticalScroll_24::VerticalScroll_24(QWidget *parent, Clock *clock) : + BaseVerticalScroll(0,0,23,parent) +{ + setupUi(this); + m_Pclock = clock; + homingAni = new QPropertyAnimation(this, "deviation"); + homingAni->setDuration(300); + homingAni->setEasingCurve(QEasingCurve::OutQuad); +} + +VerticalScroll_24::~VerticalScroll_24() +{ + delete homingAni; + + qDebug()<<"-------VerticalScroll_24---------"; + //delete ui; +} +/* + * 设置范围 set range + * int min 最小值 + * int max 最大值 +*/ +void VerticalScroll_24::setRange(int min, int max) +{ + m_minRange = min; + m_maxRange = max; + if (m_currentValue < min) + m_currentValue = min; + if (m_currentValue > max) + m_currentValue = max; + repaint(); +} +//获取当前值 +//Get current value +int VerticalScroll_24::readValue() +{ + return m_currentValue; +} + +//鼠标按压选择当前值 +// Press the mouse to select the current value +void VerticalScroll_24::mousePressEvent(QMouseEvent *e) +{ + qDebug()<<"mouse pressed on vertical scroll"; + + homingAni->stop(); + isDragging = true; + m_mouseSrcPos = e->pos().y(); + QWidget::mousePressEvent(e); +} + + + +//鼠标释放,数值弹回正中间 +// Release the mouse, and the value will bounce back to the middle +void VerticalScroll_24::mouseReleaseEvent(QMouseEvent *) +{ + if (isDragging) { + isDragging = false; + homing(); + } +} + + + +//绘制当前数值轮画面 +// Draw the current numerical wheel screen +void VerticalScroll_24::paintEvent(QPaintEvent *) +{ + QProcess process; + process.start("gsettings get org.ukui.control-center.panel.plugins hoursystem"); + process.waitForFinished(); + QByteArray output = process.readAllStandardOutput(); + QString str_output = output; + + QPainter painter(this); + painter.setRenderHint(QPainter::Antialiasing, true); + int Height = height() - 1; + + commonCalcValue(Height); + if (str_output.compare("'24'\n") == 0) { + paintNum_24( painter, Height); + } else { + paintNum_12( painter, Height); + } +} + +void VerticalScroll_24::enterEvent(QEvent *event) +{ + m_isFirstFocus = true; + event->ignore(); +} + +void VerticalScroll_24::leaveEvent(QEvent *event) +{ + m_isFirstFocus = false; + event->ignore(); +} + + + + + + + +void VerticalScroll_24::paintNum_24(QPainter &painter, int Height) +{ + // 中间数 + //middle number + paintNum(painter, m_currentValue, m_deviation); + + //两侧数字 + // Numbers on both sides + if (m_currentValue != m_minRange) { + paintNum(painter, m_currentValue - interval, m_deviation - Height / devide); + } else { + paintNum(painter, m_maxRange, m_deviation - Height / devide); + } + + if (m_currentValue != m_maxRange) { + paintNum(painter, m_currentValue + interval, m_deviation + Height / devide); + } else { + paintNum(painter, m_minRange, m_deviation + Height / devide); + } + m_Pclock->ui->timeFormatOnTimeWheel->hide(); +} + +void VerticalScroll_24::paintNum_12(QPainter &painter, int Height) +{ + int system_12_Value = m_currentValue; + if (m_currentValue > 12) { + system_12_Value = m_currentValue - 12; + paintNum(painter, system_12_Value, m_deviation); + } else { + if (m_currentValue == 0) { + system_12_Value = 12; + paintNum(painter, system_12_Value, m_deviation); + } else { + system_12_Value = m_currentValue; + paintNum(painter, system_12_Value, m_deviation); + } + } + + if (system_12_Value != m_minRange) { + if (system_12_Value == 1) { + paintNum(painter, 12, m_deviation - Height / devide); + } else { + paintNum(painter, system_12_Value - interval, m_deviation - Height / devide); + } + } else { + paintNum(painter, m_maxRange, m_deviation - Height / devide); + } + + + if (system_12_Value != m_maxRange) { + if (system_12_Value == 12) { + paintNum(painter, 1, m_deviation + Height / devide); + } else { + paintNum(painter, system_12_Value + interval, m_deviation + Height / devide); + } + } else { + paintNum(painter, m_minRange, m_deviation + Height / devide); + } + m_Pclock->ui->timeFormatOnTimeWheel->show(); + if (m_currentValue>=12) { + m_Pclock->ui->timeFormatOnTimeWheel->setText(tr("PM")); + } else { + m_Pclock->ui->timeFormatOnTimeWheel->setText(tr("AM")); + } +} + + + + +//鼠标移动偏移量,默认为0 +// Mouse movement offset, default is 0 +int VerticalScroll_24::readDeviation() +{ + return m_deviation; +} +//设置偏移量 +// Set offset +void VerticalScroll_24::setDeviation(int n) +{ + m_deviation = n; + repaint(); +} + + +void VerticalScroll_24::setupUi(QWidget *VerticalScroll_24) +{ + if (VerticalScroll_24->objectName().isEmpty()) + VerticalScroll_24->setObjectName(QString::fromUtf8("VerticalScroll_24")); + VerticalScroll_24->resize(53, 200); + + retranslateUi(VerticalScroll_24); + + QMetaObject::connectSlotsByName(VerticalScroll_24); +} // setupUi + +void VerticalScroll_24::retranslateUi(QWidget *VerticalScroll_24) +{ + VerticalScroll_24->setWindowTitle(QApplication::translate("VerticalScroll_24", "VerticalScroll_24", nullptr)); +} // retranslateUi + + diff --git a/verticalScroll24.h b/verticalScroll24.h new file mode 100644 index 0000000..0d0d695 --- /dev/null +++ b/verticalScroll24.h @@ -0,0 +1,102 @@ +/* +* 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 3, or (at your option) +* any later version. +* +* This program is distributed in the hope that it will be useful, +* but WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +* GNU General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, see +#include +#include +#include +#include "baseverticalscroll.h" + +namespace Ui { + +class VerticalScroll_24; + +} +class Clock; +class VerticalScroll_24 : public BaseVerticalScroll + +{ + Q_OBJECT + + Q_PROPERTY(int deviation READ readDeviation WRITE setDeviation ) + +public: + + explicit VerticalScroll_24(QWidget *parent = 0, Clock *clock = 0); + + ~VerticalScroll_24(); + //设置范围 + // set range + void setRange(int min, int max); + //获取当前值 + // Get current value + int readValue(); + Clock *m_Pclock; + +protected: + //鼠标按压选择当前值 + // Press the mouse to select the current value + void mousePressEvent(QMouseEvent *) override; + //鼠标拖动,滚轮滚动 + // Mouse drag, scroll wheel + //鼠标释放,数值弹回正中间 + // Release the mouse, and the value will bounce back to the middle + void mouseReleaseEvent(QMouseEvent *) override; + //鼠标滑轮滚动,数值滚动 + // Mouse wheel scrolling, numerical scrolling + //绘制当前数值轮画面 + // Draw the current numerical wheel screen + void paintEvent(QPaintEvent *) override; + + void enterEvent ( QEvent * event ) override; + void leaveEvent ( QEvent * event ) override; + + //描绘数字 + //使选中的数字回到屏幕中间 + //Bring the selected number back to the middle of the screen + //鼠标移动偏移量,默认为0 + // Mouse movement offset, default is 0 + int readDeviation(); + //设置偏移量 + // Set offset + void setDeviation(int n); + + void setupUi(QWidget *VerticalScroll_24); + + void retranslateUi(QWidget *VerticalScroll_24); + +signals: + + void currentValueChanged(int value); + + void deviationChange(int deviation); + + + +private: + + Ui::VerticalScroll_24 *ui; + +private: + void paintNum_24(QPainter &painter, int Height); + void paintNum_12(QPainter &painter, int Height); +}; + +#endif // VERTICALSCROLL_24_H diff --git a/verticalScroll60.cpp b/verticalScroll60.cpp new file mode 100644 index 0000000..65698c6 --- /dev/null +++ b/verticalScroll60.cpp @@ -0,0 +1,162 @@ +/* +* 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 3, or (at your option) +* any later version. +* +* This program is distributed in the hope that it will be useful, +* but WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +* GNU General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, see +#include +#include +#include "constant_class.h" +#include "theme.h" +VerticalScroll_60::VerticalScroll_60(QWidget *parent) : + BaseVerticalScroll(0,0,59,parent) +{ + + setupUi(this); + + homingAni = new QPropertyAnimation(this, "deviation"); + homingAni->setDuration(300); + homingAni->setEasingCurve(QEasingCurve::OutQuad); +} + +VerticalScroll_60::~VerticalScroll_60() +{ + delete homingAni; + qDebug()<<"-------VerticalScroll_60---------"; + + //delete ui; +} +/* + * 设置范围 set range + * int min 最小值 + * int max 最大值 +*/ +void VerticalScroll_60::setRange(int min, int max) +{ + m_minRange = min; + m_maxRange = max; + if (m_currentValue < min) + m_currentValue = min; + + if (m_currentValue > max) + m_currentValue = max; + repaint(); +} +//获取当前值 +//Get current value +int VerticalScroll_60::readValue() +{ + return m_currentValue; +} + +void VerticalScroll_60::mousePressEvent(QMouseEvent *e) +{ + qDebug()<<"mouse pressed on vertical scroll"; + homingAni->stop(); + isDragging = true; + m_mouseSrcPos = e->pos().y(); + QWidget::mousePressEvent(e); +} + + + +void VerticalScroll_60::mouseReleaseEvent(QMouseEvent *) +{ + if (isDragging) { + isDragging = false; + homing(); + } +} + + + +void VerticalScroll_60::paintEvent(QPaintEvent *) +{ + QPainter painter(this); + painter.setRenderHint(QPainter::Antialiasing, true); + int Height = height() - 1; + + commonCalcValue(Height); + + // 中间数 + //middle number + paintNum(painter, m_currentValue, m_deviation); + + //两侧数字 + // Numbers on both sides + if (m_currentValue != m_minRange) { + paintNum(painter, m_currentValue - interval, m_deviation - Height / devide); + } else { + paintNum(painter, m_maxRange, m_deviation - Height / devide); + } + + if (m_currentValue != m_maxRange) { + paintNum(painter, m_currentValue + interval, m_deviation + Height / devide); + } else { + paintNum(painter, m_minRange, m_deviation + Height / devide); + } + + for (int i=2; i <= devide/2; ++i) { + if (m_currentValue - interval * i >= m_minRange) + paintNum(painter, m_currentValue - interval * i, m_deviation - Height / devide * i); + if (m_currentValue + interval * i <= m_maxRange) + paintNum(painter, m_currentValue + interval * i, m_deviation + Height / devide * i); + } +} + +void VerticalScroll_60::enterEvent(QEvent *event) +{ + m_isFirstFocus = true; + event->ignore(); +} + +void VerticalScroll_60::leaveEvent(QEvent *event) +{ + m_isFirstFocus = false; + event->ignore(); +} + + + + + + +int VerticalScroll_60::readDeviation() +{ + return m_deviation; +} + +void VerticalScroll_60::setDeviation(int n) +{ + m_deviation = n; + repaint(); +} + +void VerticalScroll_60::setupUi(QWidget *VerticalScroll_60) +{ + if (VerticalScroll_60->objectName().isEmpty()) + VerticalScroll_60->setObjectName(QString::fromUtf8("VerticalScroll_60")); + VerticalScroll_60->resize(53, 200); + + retranslateUi(VerticalScroll_60); + + QMetaObject::connectSlotsByName(VerticalScroll_60); +} // setupUi + +void VerticalScroll_60::retranslateUi(QWidget *VerticalScroll_60) +{ + VerticalScroll_60->setWindowTitle(QApplication::translate("VerticalScroll_60", "VerticalScroll_60", nullptr)); +} // retranslateUi diff --git a/verticalScroll60.h b/verticalScroll60.h new file mode 100644 index 0000000..c21668f --- /dev/null +++ b/verticalScroll60.h @@ -0,0 +1,93 @@ +/* +* 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 3, or (at your option) +* any later version. +* +* This program is distributed in the hope that it will be useful, +* but WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +* GNU General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, see +#include +#include +#include +#include "baseverticalscroll.h" + +namespace Ui { + +class VerticalScroll_60; + +} + +class VerticalScroll_60 : public BaseVerticalScroll + +{ + + Q_OBJECT + + Q_PROPERTY(int deviation READ readDeviation WRITE setDeviation ) + +public: + + explicit VerticalScroll_60(QWidget *parent = 0); + + ~VerticalScroll_60(); + //设置范围 + // set range + void setRange(int min, int max); + //获取当前值 + // Get current value + int readValue(); + + void setupUi(QWidget *VerticalScroll_60); + + void retranslateUi(QWidget *VerticalScroll_60); + +protected: + void mousePressEvent(QMouseEvent *) override; + + + void mouseReleaseEvent(QMouseEvent *) override; + + + void paintEvent(QPaintEvent *) override; + void enterEvent ( QEvent * event ) override; + void leaveEvent ( QEvent * event ) override; + //描绘数字 + //使选中的数字回到屏幕中间 + //鼠标移动偏移量,默认为0 + // Mouse movement offset, default is 0 + int readDeviation(); + //设置偏移量 + // Set offset + void setDeviation(int n); + + +signals: + + void currentValueChanged(int value); + + void deviationChange(int deviation); + + + +private: + + + Ui::VerticalScroll_60 *ui; + +private: +}; + +#endif // VERTICALSCROLL_60_H diff --git a/verticalScroll99.cpp b/verticalScroll99.cpp new file mode 100644 index 0000000..91d118e --- /dev/null +++ b/verticalScroll99.cpp @@ -0,0 +1,173 @@ +/* +* 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 3, or (at your option) +* any later version. +* +* This program is distributed in the hope that it will be useful, +* but WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +* GNU General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, see +#include +#include +#include "constant_class.h" +#include "theme.h" +VerticalScroll_99::VerticalScroll_99(QWidget *parent) : + BaseVerticalScroll(0,0,23,parent) +{ + setupUi(this); + + homingAni = new QPropertyAnimation(this, "deviation"); + homingAni->setDuration(300); + homingAni->setEasingCurve(QEasingCurve::OutQuad); + + timer_21111 = new QTimer(); + connect(timer_21111, SIGNAL(timeout()), this, SLOT(listClickslot())); + timer_21111->setInterval(1000); + qDebug() << m_currentValue; +} + +VerticalScroll_99::~VerticalScroll_99() +{ + delete timer_21111; + delete homingAni; + qDebug()<<"-------VerticalScroll_99---------"; + +} +/* + * 设置范围 + * set range + * int min 最小值 + * int max 最大值 +*/ +void VerticalScroll_99::setRange(int min, int max) +{ + m_minRange = min; + m_maxRange = max; + if (m_currentValue < min) + m_currentValue = min; + if (m_currentValue > max) + m_currentValue = max; + repaint(); +} +//获取当前值 +//Get current value +int VerticalScroll_99::readValue() +{ + return m_currentValue; +} + +void VerticalScroll_99::listClickslot() +{ + qDebug() << m_currentValue; +} + +void VerticalScroll_99::mousePressEvent(QMouseEvent *e) +{ + qDebug()<<"mouse pressed on vertical scroll"; + homingAni->stop(); + isDragging = true; + m_mouseSrcPos = e->pos().y(); + QWidget::mousePressEvent(e); +} + + + +void VerticalScroll_99::mouseReleaseEvent(QMouseEvent *) +{ + if (isDragging) { + isDragging = false; + homing(); + } +} + + + +void VerticalScroll_99::paintEvent(QPaintEvent *) +{ + QPainter painter(this); + painter.setRenderHint(QPainter::Antialiasing, true); + int Height = height() - 1; + + commonCalcValue(Height); + + // 中间数 + //middle number + paintNum(painter, m_currentValue, m_deviation); + + //两侧数字 + // Numbers on both sides + if (m_currentValue != m_minRange) + paintNum(painter, m_currentValue - interval, m_deviation - Height / devide); + else + paintNum(painter, m_maxRange, m_deviation - Height / devide); + + if (m_currentValue != m_maxRange) + paintNum(painter, m_currentValue + interval, m_deviation + Height / devide); + else + paintNum(painter, m_minRange, m_deviation + Height / devide); + + + for (int i=2; i <= devide/2; ++i) { + if (m_currentValue - interval * i >= m_minRange) + paintNum(painter, m_currentValue - interval * i, m_deviation - Height / devide * i); + if (m_currentValue + interval * i <= m_maxRange) + paintNum(painter, m_currentValue + interval * i, m_deviation + Height / devide * i); + } + +} + +void VerticalScroll_99::enterEvent(QEvent *event) +{ + m_isFirstFocus = true; + event->ignore(); +} + +void VerticalScroll_99::leaveEvent(QEvent *event) +{ + m_isFirstFocus = false; + event->ignore(); +} + + + + +//鼠标移动偏移量,默认为0 +// Mouse movement offset, default is 0 +int VerticalScroll_99::readDeviation() +{ + return m_deviation; +} + +//设置偏移量 +// Set offset +void VerticalScroll_99::setDeviation(int n) +{ + m_deviation = n; + repaint(); +} + +void VerticalScroll_99::setupUi(QWidget *VerticalScroll_99) +{ + if (VerticalScroll_99->objectName().isEmpty()) + VerticalScroll_99->setObjectName(QString::fromUtf8("VerticalScroll_99")); + VerticalScroll_99->resize(53, 200); + + retranslateUi(VerticalScroll_99); + + QMetaObject::connectSlotsByName(VerticalScroll_99); +} // setupUi + +void VerticalScroll_99::retranslateUi(QWidget *VerticalScroll_99) +{ + VerticalScroll_99->setWindowTitle(QApplication::translate("VerticalScroll_99", "VerticalScroll_99", nullptr)); +} // retranslateUi diff --git a/verticalScroll99.h b/verticalScroll99.h new file mode 100644 index 0000000..22c90ac --- /dev/null +++ b/verticalScroll99.h @@ -0,0 +1,97 @@ +/* +* 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 3, or (at your option) +* any later version. +* +* This program is distributed in the hope that it will be useful, +* but WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +* GNU General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, see +#include +#include +#include +#include +#include "baseverticalscroll.h" + +namespace Ui { + +class VerticalScroll_99; + +} + +class VerticalScroll_99 : public BaseVerticalScroll + +{ + + Q_OBJECT + + Q_PROPERTY(int deviation READ readDeviation WRITE setDeviation ) + +public: + + explicit VerticalScroll_99(QWidget *parent = 0); + + ~VerticalScroll_99(); + //设置范围 + // set range + void setRange(int min, int max); + //获取当前值 + // Get current value + int readValue(); + + void setupUi(QWidget *VerticalScroll_99); + + void retranslateUi(QWidget *VerticalScroll_99); + +private slots: + void listClickslot(); + + +protected: + void mousePressEvent(QMouseEvent *) override; + + + void mouseReleaseEvent(QMouseEvent *) override; + + + void paintEvent(QPaintEvent *) override; + void enterEvent ( QEvent * event ) override; + void leaveEvent ( QEvent * event ) override; + //描绘数字 + //使选中的数字回到屏幕中间 + //Bring the selected number back to the middle of the screen + //鼠标移动偏移量,默认为0 + // Mouse movement offset, default is 0 + int readDeviation(); + //设置偏移量 + // Set offset + void setDeviation(int n); + + +signals: + + void currentValueChanged(int value); + + void deviationChange(int deviation); + +private: + + Ui::VerticalScroll_99 *ui; + QTimer *timer_21111; + +private: +}; + +#endif // VERTICALSCROLL_99_H diff --git a/widget.ui b/widget.ui new file mode 100644 index 0000000..0178b4c --- /dev/null +++ b/widget.ui @@ -0,0 +1,72 @@ + + + Widget + + + + 0 + 0 + 205 + 231 + + + + Widget + + + + + 0 + 70 + 80 + 26 + + + + 开始 + + + + + + 0 + 110 + 80 + 26 + + + + 暂停 + + + + + + 0 + 150 + 80 + 26 + + + + 时间选择 + + + + + + 0 + 190 + 80 + 26 + + + + 铃声 + + + + + + + diff --git a/xatom-helper.cpp b/xatom-helper.cpp new file mode 100644 index 0000000..cd827ae --- /dev/null +++ b/xatom-helper.cpp @@ -0,0 +1,227 @@ +/* + * KWin Style UKUI + * + * Copyright (C) 2020, KylinSoft Co., Ltd. + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + * Authors: Yue Lan + * + */ + +#include "xatom-helper.h" + +#include +#include +#include +#include + +static XAtomHelper *global_instance = nullptr; + +XAtomHelper *XAtomHelper::getInstance() +{ + if (!global_instance) + global_instance = new XAtomHelper; + return global_instance; +} + +bool XAtomHelper::isFrameLessWindow(int winId) +{ + auto hints = getInstance()->getWindowMotifHint(winId); + if (hints.flags == MWM_HINTS_DECORATIONS && hints.functions == 1) { + return true; + } + return false; +} + +bool XAtomHelper::isWindowDecorateBorderOnly(int winId) +{ + return isWindowMotifHintDecorateBorderOnly(getInstance()->getWindowMotifHint(winId)); +} + +bool XAtomHelper::isWindowMotifHintDecorateBorderOnly(const MotifWmHints &hint) +{ + bool isDeco = false; + if (hint.flags & MWM_HINTS_DECORATIONS && hint.flags != MWM_HINTS_DECORATIONS) { + if (hint.decorations == MWM_DECOR_BORDER) + isDeco = true; + } + return isDeco; +} + +bool XAtomHelper::isUKUICsdSupported() +{ + // fixme: + return false; +} + +bool XAtomHelper::isUKUIDecorationWindow(int winId) +{ + if (m_ukuiDecorationAtion == None) + return false; + + Atom type; + int format; + ulong nitems; + ulong bytes_after; + uchar *data; + + bool isUKUIDecoration = false; + + XGetWindowProperty(QX11Info::display(), winId, m_ukuiDecorationAtion, + 0, LONG_MAX, false, + m_ukuiDecorationAtion, &type, + &format, &nitems, + &bytes_after, &data); + + if (type == m_ukuiDecorationAtion) { + if (nitems == 1) { + isUKUIDecoration = data[0]; + } + } + + return isUKUIDecoration; +} + +UnityCorners XAtomHelper::getWindowBorderRadius(int winId) +{ + UnityCorners corners; + + Atom type; + int format; + ulong nitems; + ulong bytes_after; + uchar *data; + + if (m_unityBorderRadiusAtom != None) { + XGetWindowProperty(QX11Info::display(), winId, m_unityBorderRadiusAtom, + 0, LONG_MAX, false, + XA_CARDINAL, &type, + &format, &nitems, + &bytes_after, &data); + + if (type == XA_CARDINAL) { + if (nitems == 4) { + corners.topLeft = static_cast(data[0]); + corners.topRight = static_cast(data[1*sizeof (ulong)]); + corners.bottomLeft = static_cast(data[2*sizeof (ulong)]); + corners.bottomRight = static_cast(data[3*sizeof (ulong)]); + } + XFree(data); + } + } + + return corners; +} + +void XAtomHelper::setWindowBorderRadius(int winId, const UnityCorners &data) +{ + if (m_unityBorderRadiusAtom == None) + return; + + ulong corners[4] = {data.topLeft, data.topRight, data.bottomLeft, data.bottomRight}; + + XChangeProperty(QX11Info::display(), winId, m_unityBorderRadiusAtom, XA_CARDINAL, + 32, XCB_PROP_MODE_REPLACE, (const unsigned char *) &corners, sizeof (corners)/sizeof (corners[0])); +} + +void XAtomHelper::setWindowBorderRadius(int winId, int topLeft, int topRight, int bottomLeft, int bottomRight) +{ + if (m_unityBorderRadiusAtom == None) + return; + + ulong corners[4] = {(ulong)topLeft, (ulong)topRight, (ulong)bottomLeft, (ulong)bottomRight}; + + XChangeProperty(QX11Info::display(), winId, m_unityBorderRadiusAtom, XA_CARDINAL, + 32, XCB_PROP_MODE_REPLACE, (const unsigned char *) &corners, sizeof (corners)/sizeof (corners[0])); +} + +void XAtomHelper::setUKUIDecoraiontHint(int winId, bool set) +{ + if (m_ukuiDecorationAtion == None) + return; + + XChangeProperty(QX11Info::display(), winId, m_ukuiDecorationAtion, m_ukuiDecorationAtion, 32, XCB_PROP_MODE_REPLACE, (const unsigned char *) &set, 1); +} + +void XAtomHelper::setWindowMotifHint(int winId, const MotifWmHints &hints) +{ + if (m_unityBorderRadiusAtom == None) + return; + + XChangeProperty(QX11Info::display(), winId, m_motifWMHintsAtom, m_motifWMHintsAtom, + 32, XCB_PROP_MODE_REPLACE, (const unsigned char *)&hints, sizeof (MotifWmHints)/ sizeof (ulong)); +} + +MotifWmHints XAtomHelper::getWindowMotifHint(int winId) +{ + MotifWmHints hints; + + if (m_unityBorderRadiusAtom == None) + return hints; + + uchar *data; + Atom type; + int format; + ulong nitems; + ulong bytes_after; + + XGetWindowProperty(QX11Info::display(), winId, m_motifWMHintsAtom, + 0, sizeof (MotifWmHints)/sizeof (long), false, AnyPropertyType, &type, + &format, &nitems, &bytes_after, &data); + + if (type == None) { + return hints; + } else { + hints = *(MotifWmHints *)data; + XFree(data); + } + return hints; +} +/** + * @brief 标准窗管协议 + */ +void XAtomHelper::setStandardWindowHint(int winId) +{ + MotifWmHints hints; + hints.flags = MWM_HINTS_FUNCTIONS|MWM_HINTS_DECORATIONS; + hints.functions = MWM_FUNC_ALL; + hints.decorations = MWM_DECOR_BORDER; + XAtomHelper::getInstance()->setWindowMotifHint(winId, hints); +} +void XAtomHelper::setStandardWindowRadius(int winId, int radius) +{ + XAtomHelper::getInstance()->setWindowBorderRadius(winId,radius,radius,radius,radius); +} + +XAtomHelper::XAtomHelper(QObject *parent) : QObject(parent) +{ + if (!QX11Info::isPlatformX11()) + return; + + m_motifWMHintsAtom = XInternAtom(QX11Info::display(), "_MOTIF_WM_HINTS", true); + m_unityBorderRadiusAtom = XInternAtom(QX11Info::display(), "_UNITY_GTK_BORDER_RADIUS", false); + m_ukuiDecorationAtion = XInternAtom(QX11Info::display(), "_KWIN_UKUI_DECORAION", false); +} + +Atom XAtomHelper::registerUKUICsdNetWmSupportAtom() +{ + // fixme: + return None; +} + +void XAtomHelper::unregisterUKUICsdNetWmSupportAtom() +{ + // fixme: +} diff --git a/xatom-helper.h b/xatom-helper.h new file mode 100644 index 0000000..3b4d0de --- /dev/null +++ b/xatom-helper.h @@ -0,0 +1,111 @@ +/* + * KWin Style UKUI + * + * Copyright (C) 2020, KylinSoft Co., Ltd. + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + * Authors: Yue Lan + * + */ + +#ifndef XATOMHELPER_H +#define XATOMHELPER_H + +#include +#include + +struct UnityCorners { + ulong topLeft = 0; + ulong topRight = 0; + ulong bottomLeft = 0; + ulong bottomRight = 0; +}; + +typedef struct { + ulong flags = 0; + ulong functions = 0; + ulong decorations = 0; + long input_mode = 0; + ulong status = 0; +} MotifWmHints, MwmHints; + +#define MWM_HINTS_FUNCTIONS (1L << 0) +#define MWM_HINTS_DECORATIONS (1L << 1) +#define MWM_HINTS_INPUT_MODE (1L << 2) +#define MWM_HINTS_STATUS (1L << 3) + +#define MWM_FUNC_ALL (1L << 0) +#define MWM_FUNC_RESIZE (1L << 1) +#define MWM_FUNC_MOVE (1L << 2) +#define MWM_FUNC_MINIMIZE (1L << 3) +#define MWM_FUNC_MAXIMIZE (1L << 4) +#define MWM_FUNC_CLOSE (1L << 5) + +#define MWM_DECOR_ALL (1L << 0) +#define MWM_DECOR_BORDER (1L << 1) +#define MWM_DECOR_RESIZEH (1L << 2) +#define MWM_DECOR_TITLE (1L << 3) +#define MWM_DECOR_MENU (1L << 4) +#define MWM_DECOR_MINIMIZE (1L << 5) +#define MWM_DECOR_MAXIMIZE (1L << 6) + +#define MWM_INPUT_MODELESS 0 +#define MWM_INPUT_PRIMARY_APPLICATION_MODAL 1 +#define MWM_INPUT_SYSTEM_MODAL 2 +#define MWM_INPUT_FULL_APPLICATION_MODAL 3 +#define MWM_INPUT_APPLICATION_MODAL MWM_INPUT_PRIMARY_APPLICATION_MODAL + +#define MWM_TEAROFF_WINDOW (1L<<0) + +namespace UKUI { +class Decoration; +} + +class XAtomHelper : public QObject +{ + friend class UKUI::Decoration; + Q_OBJECT +public: + static XAtomHelper *getInstance(); + + static bool isFrameLessWindow(int winId); + + bool isWindowDecorateBorderOnly(int winId); + bool isWindowMotifHintDecorateBorderOnly(const MotifWmHints &hint); + bool isUKUICsdSupported(); + bool isUKUIDecorationWindow(int winId); + + UnityCorners getWindowBorderRadius(int winId); + void setWindowBorderRadius(int winId, const UnityCorners &data); + void setWindowBorderRadius(int winId, int topLeft, int topRight, int bottomLeft, int bottomRight); + void setUKUIDecoraiontHint(int winId, bool set = true); + + void setWindowMotifHint(int winId, const MotifWmHints &hints); + MotifWmHints getWindowMotifHint(int winId); + static void setStandardWindowHint(int winId); + static void setStandardWindowRadius(int winId, int radius); + +private: + explicit XAtomHelper(QObject *parent = nullptr); + + Atom registerUKUICsdNetWmSupportAtom(); + void unregisterUKUICsdNetWmSupportAtom(); + + Atom m_motifWMHintsAtom = None; + Atom m_unityBorderRadiusAtom = None; + Atom m_ukuiDecorationAtion = None; +}; + +#endif // XATOMHELPER_H