File indexing completed on 2024-04-14 05:24:53

0001 /*
0002     SPDX-FileCopyrightText: 2018 Michail Vourlakos <mvourlakos@gmail.com>
0003     SPDX-License-Identifier: GPL-2.0-or-later
0004 */
0005 
0006 #ifndef EXTRAS_H
0007 #define EXTRAS_H
0008 
0009 // local
0010 #include <config-latte-lib.h>
0011 
0012 // C++
0013 #include <type_traits>
0014 #include <numeric>
0015 #include <memory>
0016 #include <cmath>
0017 
0018 // Qt
0019 #include <QObject>
0020 #include <QString>
0021 #include <QStringBuilder>
0022 #include <QRect>
0023 #include <QMetaEnum>
0024 #include <QMetaType>
0025 
0026 // Plasma
0027 #include <Plasma>
0028 
0029 //! There are gcc versions that don't support yet that function even though they
0030 //! publish themselves as C++14 compatible. Such a case is gcc 4.8.x that openSUSE
0031 //! LEAP 42.2-3 is using. By enabling this flag such systems can be build correctly.
0032 #if ENABLE_MAKE_UNIQUE
0033 namespace std {
0034 template<class T, class... Args>
0035 unique_ptr<T> make_unique(Args &&... args)
0036 {
0037     return std::unique_ptr<T>(new T(std::forward<Args>(args)...));
0038 }
0039 }
0040 #endif
0041 
0042 /*!
0043  * @brief convert a QRect to a QString with format `(<x>, <y>) <width>x<height>`
0044  */
0045 inline QString qRectToStr(const QRect &r)
0046 {
0047     return "(" % QString::number(r.x()) % ", " % QString::number(r.y()) % ") "
0048            % QString::number(r.width()) % "x" % QString::number(r.height());
0049 }
0050 
0051 /*!
0052  * @brief convert a `Q_ENUM` to c-string
0053  */
0054 template<typename EnumType>
0055 inline const char *qEnumToStr(EnumType value)
0056 {
0057     return QMetaEnum::fromType<EnumType>().valueToKey(value);
0058 }
0059 
0060 /*!
0061  * @brief convert a `Q_ENUMS` of `Plasma::Types::Location` to c-string
0062  */
0063 inline const char *qEnumToStr(Plasma::Types::Location Enum)
0064 {
0065     static const int Index = Plasma::Types::staticMetaObject.indexOfEnumerator("Location");
0066     return Plasma::Types::staticMetaObject.enumerator(Index).valueToKey(Enum);
0067 }
0068 
0069 /*!
0070  * @brief convert a `Q_ENUMS` of `Plasma::Types::FormFactor` to c-string
0071  */
0072 inline const char *qEnumToStr(Plasma::Types::FormFactor Enum)
0073 {
0074     static const int Index = Plasma::Types::staticMetaObject.indexOfEnumerator("FormFactor");
0075     return Plasma::Types::staticMetaObject.enumerator(Index).valueToKey(Enum);
0076 }
0077 
0078 /*!
0079  * @brief machine epsilon
0080  */
0081 template<class T>
0082 typename std::enable_if < !std::is_integral<T>(), bool >::type almost_equal(T x, T y, int ulp)
0083 {
0084     return std::abs(x - y) < std::numeric_limits<T>::epsilon() * std::abs(x + y) * ulp
0085            || std::abs(x - y) < std::numeric_limits<T>::min();
0086 }
0087 
0088 #endif // EXTRAS_H