diff options
author | Louis-Bertrand Varin <louisbvarin@gmail.com> | 2018-03-31 23:01:30 +0300 |
---|---|---|
committer | Louis-Bertrand Varin <louisbvarin@gmail.com> | 2018-03-31 23:01:30 +0300 |
commit | 8324d03f0a015e62b6182843b4478226a5197090 (patch) | |
tree | faf34febaec7c7e764d357dc5e439f6f2b1fcaf3 /src/core | |
parent | 74efc57369b068a0f93cb84ac68b6c17f64c8abe (diff) |
Formatting the code.
Diffstat (limited to 'src/core')
49 files changed, 783 insertions, 792 deletions
diff --git a/src/core/AsyncTask.h b/src/core/AsyncTask.h index 67cab1609..45bb191bc 100644 --- a/src/core/AsyncTask.h +++ b/src/core/AsyncTask.h @@ -22,42 +22,42 @@ #include <QFutureWatcher> #include <QtConcurrent> - /** * Asynchronously run computations outside the GUI thread. */ namespace AsyncTask { -/** - * Wait for the given future without blocking the event loop. - * - * @param future future to wait for - * @return async task result - */ -template<typename FunctionObject> -typename std::result_of<FunctionObject()>::type waitForFuture(QFuture<typename std::result_of<FunctionObject()>::type> future) -{ - QEventLoop loop; - QFutureWatcher<typename std::result_of<FunctionObject()>::type> watcher; - QObject::connect(&watcher, SIGNAL(finished()), &loop, SLOT(quit())); - watcher.setFuture(future); - loop.exec(); - return future.result(); -} - -/** - * Run a given task and wait for it to finish without blocking the event loop. - * - * @param task std::function object to run - * @return async task result - */ -template<typename FunctionObject> -typename std::result_of<FunctionObject()>::type runAndWaitForFuture(FunctionObject task) -{ - return waitForFuture<FunctionObject>(QtConcurrent::run(task)); -} - -}; // namespace AsyncTask - -#endif //KEEPASSXC_ASYNCTASK_HPP + /** + * Wait for the given future without blocking the event loop. + * + * @param future future to wait for + * @return async task result + */ + template <typename FunctionObject> + typename std::result_of<FunctionObject()>::type + waitForFuture(QFuture<typename std::result_of<FunctionObject()>::type> future) + { + QEventLoop loop; + QFutureWatcher<typename std::result_of<FunctionObject()>::type> watcher; + QObject::connect(&watcher, SIGNAL(finished()), &loop, SLOT(quit())); + watcher.setFuture(future); + loop.exec(); + return future.result(); + } + + /** + * Run a given task and wait for it to finish without blocking the event loop. + * + * @param task std::function object to run + * @return async task result + */ + template <typename FunctionObject> + typename std::result_of<FunctionObject()>::type runAndWaitForFuture(FunctionObject task) + { + return waitForFuture<FunctionObject>(QtConcurrent::run(task)); + } + +}; // namespace AsyncTask + +#endif // KEEPASSXC_ASYNCTASK_HPP diff --git a/src/core/AutoTypeAssociations.cpp b/src/core/AutoTypeAssociations.cpp index 04221733f..730e38ca1 100644 --- a/src/core/AutoTypeAssociations.cpp +++ b/src/core/AutoTypeAssociations.cpp @@ -27,7 +27,6 @@ bool AutoTypeAssociations::Association::operator!=(const AutoTypeAssociations::A return window != other.window || sequence != other.sequence; } - AutoTypeAssociations::AutoTypeAssociations(QObject* parent) : QObject(parent) { @@ -106,7 +105,7 @@ int AutoTypeAssociations::size() const int AutoTypeAssociations::associationsSize() const { int size = 0; - for (const Association &association : m_associations) { + for (const Association& association : m_associations) { size += association.sequence.toUtf8().size() + association.window.toUtf8().size(); } return size; diff --git a/src/core/AutoTypeMatch.cpp b/src/core/AutoTypeMatch.cpp index c1faab9e6..9b7940f4d 100644 --- a/src/core/AutoTypeMatch.cpp +++ b/src/core/AutoTypeMatch.cpp @@ -19,14 +19,16 @@ #include "AutoTypeMatch.h" AutoTypeMatch::AutoTypeMatch() - : entry(nullptr), - sequence() -{} + : entry(nullptr) + , sequence() +{ +} AutoTypeMatch::AutoTypeMatch(Entry* entry, QString sequence) - : entry(entry), - sequence(sequence) -{} + : entry(entry) + , sequence(sequence) +{ +} bool AutoTypeMatch::operator==(const AutoTypeMatch& other) const { diff --git a/src/core/Config.cpp b/src/core/Config.cpp index 461ab1f74..ccdc24fd1 100644 --- a/src/core/Config.cpp +++ b/src/core/Config.cpp @@ -21,8 +21,8 @@ #include <QCoreApplication> #include <QDir> #include <QSettings> -#include <QTemporaryFile> #include <QStandardPaths> +#include <QTemporaryFile> Config* Config::m_instance(nullptr); @@ -80,7 +80,7 @@ Config::Config(QObject* parent) QString userPath; QString homePath = QDir::homePath(); - #if defined(Q_OS_UNIX) && !defined(Q_OS_MAC) +#if defined(Q_OS_UNIX) && !defined(Q_OS_MAC) // we can't use QStandardPaths on X11 as it uses XDG_DATA_HOME instead of XDG_CONFIG_HOME QByteArray env = qgetenv("XDG_CONFIG_HOME"); if (env.isEmpty()) { @@ -95,17 +95,17 @@ Config::Config(QObject* parent) } userPath += "/keepassxc/"; - #else +#else userPath = QDir::fromNativeSeparators(QStandardPaths::writableLocation(QStandardPaths::DataLocation)); // storageLocation() appends the application name ("/keepassxc") to the end userPath += "/"; - #endif +#endif - #ifdef QT_DEBUG +#ifdef QT_DEBUG userPath += "keepassxc_debug.ini"; - #else +#else userPath += "keepassxc.ini"; - #endif +#endif init(userPath); } diff --git a/src/core/Config.h b/src/core/Config.h index eb7978622..fcb27e2ca 100644 --- a/src/core/Config.h +++ b/src/core/Config.h @@ -26,7 +26,7 @@ class QSettings; class Config : public QObject { -Q_OBJECT + Q_OBJECT public: Q_DISABLE_COPY(Config) @@ -54,7 +54,8 @@ private: QHash<QString, QVariant> m_defaults; }; -inline Config* config() { +inline Config* config() +{ return Config::instance(); } diff --git a/src/core/CsvParser.cpp b/src/core/CsvParser.cpp index 4fc4281ba..a66c919b2 100644 --- a/src/core/CsvParser.cpp +++ b/src/core/CsvParser.cpp @@ -18,8 +18,8 @@ #include "CsvParser.h" -#include <QTextCodec> #include <QObject> +#include <QTextCodec> #include "core/Tools.h" @@ -44,21 +44,24 @@ CsvParser::CsvParser() m_ts.setCodec("UTF-8"); } -CsvParser::~CsvParser() { +CsvParser::~CsvParser() +{ m_csv.close(); } -bool CsvParser::isFileLoaded() { +bool CsvParser::isFileLoaded() +{ return m_isFileLoaded; } -bool CsvParser::reparse() { +bool CsvParser::reparse() +{ reset(); return parseFile(); } - -bool CsvParser::parse(QFile *device) { +bool CsvParser::parse(QFile* device) +{ clear(); if (nullptr == device) { appendStatusMsg(QObject::tr("NULL device"), true); @@ -69,7 +72,8 @@ bool CsvParser::parse(QFile *device) { return parseFile(); } -bool CsvParser::readFile(QFile *device) { +bool CsvParser::readFile(QFile* device) +{ if (device->isOpen()) device->close(); @@ -77,20 +81,20 @@ bool CsvParser::readFile(QFile *device) { if (!Tools::readAllFromDevice(device, m_array)) { appendStatusMsg(QObject::tr("error reading from device"), true); m_isFileLoaded = false; - } - else { + } else { device->close(); m_array.replace("\r\n", "\n"); m_array.replace("\r", "\n"); if (0 == m_array.size()) - appendStatusMsg(QObject::tr("file empty").append("\n")); + appendStatusMsg(QObject::tr("file empty").append("\n")); m_isFileLoaded = true; } return m_isFileLoaded; } -void CsvParser::reset() { +void CsvParser::reset() +{ m_ch = 0; m_currCol = 1; m_currRow = 1; @@ -101,21 +105,23 @@ void CsvParser::reset() { m_statusMsg = ""; m_ts.seek(0); m_table.clear(); - //the following are users' concern :) - //m_comment = '#'; - //m_backslashSyntax = false; - //m_comment = '#'; - //m_qualifier = '"'; - //m_separator = ','; + // the following are users' concern :) + // m_comment = '#'; + // m_backslashSyntax = false; + // m_comment = '#'; + // m_qualifier = '"'; + // m_separator = ','; } -void CsvParser::clear() { +void CsvParser::clear() +{ reset(); m_isFileLoaded = false; m_array.clear(); } -bool CsvParser::parseFile() { +bool CsvParser::parseFile() +{ parseRecord(); while (!m_isEof) { if (!skipEndline()) @@ -128,7 +134,8 @@ bool CsvParser::parseFile() { return m_isGood; } -void CsvParser::parseRecord() { +void CsvParser::parseRecord() +{ CsvRow row; if (isComment()) { skipLine(); @@ -151,19 +158,21 @@ void CsvParser::parseRecord() { m_currCol++; } -void CsvParser::parseField(CsvRow& row) { +void CsvParser::parseField(CsvRow& row) +{ QString field; peek(m_ch); if (!isTerminator(m_ch)) { if (isQualifier(m_ch)) - parseQuoted(field); + parseQuoted(field); else parseSimple(field); } row.push_back(field); } -void CsvParser::parseSimple(QString &s) { +void CsvParser::parseSimple(QString& s) +{ QChar c; getChar(c); while ((isText(c)) && (!m_isEof)) { @@ -174,16 +183,18 @@ void CsvParser::parseSimple(QString &s) { ungetChar(); } -void CsvParser::parseQuoted(QString &s) { - //read and discard initial qualifier (e.g. quote) +void CsvParser::parseQuoted(QString& s) +{ + // read and discard initial qualifier (e.g. quote) getChar(m_ch); parseEscaped(s); - //getChar(m_ch); + // getChar(m_ch); if (!isQualifier(m_ch)) appendStatusMsg(QObject::tr("missing closing quote"), true); } -void CsvParser::parseEscaped(QString &s) { +void CsvParser::parseEscaped(QString& s) +{ parseEscapedText(s); while (processEscapeMark(s, m_ch)) parseEscapedText(s); @@ -191,7 +202,8 @@ void CsvParser::parseEscaped(QString &s) { ungetChar(); } -void CsvParser::parseEscapedText(QString &s) { +void CsvParser::parseEscapedText(QString& s) +{ getChar(m_ch); while ((!isQualifier(m_ch)) && !m_isEof) { s.append(m_ch); @@ -199,19 +211,20 @@ void CsvParser::parseEscapedText(QString &s) { } } -bool CsvParser::processEscapeMark(QString &s, QChar c) { +bool CsvParser::processEscapeMark(QString& s, QChar c) +{ QChar buf; peek(buf); QChar c2; if (true == m_isBackslashSyntax) { - //escape-character syntax, e.g. \" + // escape-character syntax, e.g. \" if (c != '\\') { return false; } - //consume (and append) second qualifier + // consume (and append) second qualifier getChar(c2); if (m_isEof) { - c2='\\'; + c2 = '\\'; s.append('\\'); return false; } else { @@ -219,11 +232,11 @@ bool CsvParser::processEscapeMark(QString &s, QChar c) { return true; } } else { - //double quote syntax, e.g. "" + // double quote syntax, e.g. "" if (!isQualifier(c)) return false; peek(c2); - if (!m_isEof) { //not EOF, can read one char + if (!m_isEof) { // not EOF, can read one char if (isQualifier(c2)) { s.append(c2); getChar(c2); @@ -234,10 +247,11 @@ bool CsvParser::processEscapeMark(QString &s, QChar c) { } } -void CsvParser::fillColumns() { - //fill shorter rows with empty placeholder columns +void CsvParser::fillColumns() +{ + // fill shorter rows with empty placeholder columns for (int i = 0; i < m_table.size(); ++i) { - int gap = m_maxCols-m_table.at(i).size(); + int gap = m_maxCols - m_table.at(i).size(); if (gap > 0) { CsvRow r = m_table.at(i); for (int j = 0; j < gap; ++j) { @@ -248,18 +262,20 @@ void CsvParser::fillColumns() { } } -void CsvParser::skipLine() { +void CsvParser::skipLine() +{ m_ts.readLine(); m_ts.seek(m_ts.pos() - 1); } -bool CsvParser::skipEndline() { +bool CsvParser::skipEndline() +{ getChar(m_ch); return (m_ch == '\n'); } - -void CsvParser::getChar(QChar& c) { +void CsvParser::getChar(QChar& c) +{ m_isEof = m_ts.atEnd(); if (!m_isEof) { m_lastPos = m_ts.pos(); @@ -267,32 +283,37 @@ void CsvParser::getChar(QChar& c) { } } -void CsvParser::ungetChar() { +void CsvParser::ungetChar() +{ if (!m_ts.seek(m_lastPos)) { qWarning("CSV Parser: unget lower bound exceeded"); m_isGood = false; } } -void CsvParser::peek(QChar& c) { +void CsvParser::peek(QChar& c) +{ getChar(c); if (!m_isEof) ungetChar(); } -bool CsvParser::isQualifier(const QChar &c) const { +bool CsvParser::isQualifier(const QChar& c) const +{ if (true == m_isBackslashSyntax && (c != m_qualifier)) return (c == '\\'); else return (c == m_qualifier); } -bool CsvParser::isComment() { +bool CsvParser::isComment() +{ bool result = false; QChar c2; qint64 pos = m_ts.pos(); - do getChar(c2); + do + getChar(c2); while ((isSpace(c2) || isTab(c2)) && (!m_isEof)); if (c2 == m_comment) @@ -301,84 +322,100 @@ bool CsvParser::isComment() { return result; } -bool CsvParser::isText(QChar c) const { - return !( (isCRLF(c)) || (isSeparator(c)) ); +bool CsvParser::isText(QChar c) const +{ + return !((isCRLF(c)) || (isSeparator(c))); } -bool CsvParser::isEmptyRow(CsvRow row) const { +bool CsvParser::isEmptyRow(CsvRow row) const +{ CsvRow::const_iterator it = row.constBegin(); for (; it != row.constEnd(); ++it) - if ( ((*it) != "\n") && ((*it) != "") ) + if (((*it) != "\n") && ((*it) != "")) return false; return true; } -bool CsvParser::isCRLF(const QChar &c) const { +bool CsvParser::isCRLF(const QChar& c) const +{ return (c == '\n'); } -bool CsvParser::isSpace(const QChar &c) const { +bool CsvParser::isSpace(const QChar& c) const +{ return (c == ' '); } -bool CsvParser::isTab(const QChar &c) const { +bool CsvParser::isTab(const QChar& c) const +{ return (c == '\t'); } -bool CsvParser::isSeparator(const QChar &c) const { +bool CsvParser::isSeparator(const QChar& c) const +{ return (c == m_separator); } -bool CsvParser::isTerminator(const QChar &c) const { +bool CsvParser::isTerminator(const QChar& c) const +{ return (isSeparator(c) || (c == '\n') || (c == '\r')); } -void CsvParser::setBackslashSyntax(bool set) { +void CsvParser::setBackslashSyntax(bool set) +{ m_isBackslashSyntax = set; } -void CsvParser::setComment(const QChar &c) { +void CsvParser::setComment(const QChar& c) +{ m_comment = c.unicode(); } -void CsvParser::setCodec(const QString &s) { +void CsvParser::setCodec(const QString& s) +{ m_ts.setCodec(QTextCodec::codecForName(s.toLocal8Bit())); } -void CsvParser::setFieldSeparator(const QChar &c) { +void CsvParser::setFieldSeparator(const QChar& c) +{ m_separator = c.unicode(); } -void CsvParser::setTextQualifier(const QChar &c) { +void CsvParser::setTextQualifier(const QChar& c) +{ m_qualifier = c.unicode(); } -int CsvParser::getFileSize() const { +int CsvParser::getFileSize() const +{ return m_csv.size(); } -const CsvTable CsvParser::getCsvTable() const { +const CsvTable CsvParser::getCsvTable() const +{ return m_table; } -QString CsvParser::getStatus() const { +QString CsvParser::getStatus() const +{ return m_statusMsg; } -int CsvParser::getCsvCols() const { +int CsvParser::getCsvCols() const +{ if ((m_table.size() > 0) && (m_table.at(0).size() > 0)) return m_table.at(0).size(); - else return 0; + else + return 0; } -int CsvParser::getCsvRows() const { +int CsvParser::getCsvRows() const +{ return m_table.size(); } - -void CsvParser::appendStatusMsg(QString s, bool isCritical) { - m_statusMsg += QObject::tr("%1: (row, col) %2,%3") - .arg(s, m_currRow, m_currCol) - .append("\n"); +void CsvParser::appendStatusMsg(QString s, bool isCritical) +{ + m_statusMsg += QObject::tr("%1: (row, col) %2,%3").arg(s, m_currRow, m_currCol).append("\n"); m_isGood = !isCritical; } diff --git a/src/core/CsvParser.h b/src/core/CsvParser.h index 3ab31bf67..323023114 100644 --- a/src/core/CsvParser.h +++ b/src/core/CsvParser.h @@ -19,28 +19,29 @@ #ifndef KEEPASSX_CSVPARSER_H #define KEEPASSX_CSVPARSER_H -#include <QFile> #include <QBuffer> +#include <QFile> #include <QQueue> #include <QTextStream> typedef QStringList CsvRow; typedef QList<CsvRow> CsvTable; -class CsvParser { +class CsvParser +{ public: CsvParser(); ~CsvParser(); - //read data from device and parse it - bool parse(QFile *device); + // read data from device and parse it + bool parse(QFile* device); bool isFileLoaded(); - //reparse the same buffer (device is not opened again) + // reparse the same buffer (device is not opened again) bool reparse(); - void setCodec(const QString &s); - void setComment(const QChar &c); - void setFieldSeparator(const QChar &c); - void setTextQualifier(const QChar &c); + void setCodec(const QString& s); + void setComment(const QChar& c); + void setFieldSeparator(const QChar& c); + void setTextQualifier(const QChar& c); void setBackslashSyntax(bool set); int getFileSize() const; int getCsvRows() const; @@ -52,45 +53,45 @@ protected: CsvTable m_table; private: - QByteArray m_array; - QBuffer m_csv; - QChar m_ch; - QChar m_comment; + QByteArray m_array; + QBuffer m_csv; + QChar m_ch; + QChar m_comment; unsigned int m_currCol; unsigned int m_currRow; - bool m_isBackslashSyntax; - bool m_isEof; - bool m_isFileLoaded; - bool m_isGood; - qint64 m_lastPos; - int m_maxCols; - QChar m_qualifier; - QChar m_separator; - QString m_statusMsg; - QTextStream m_ts; + bool m_isBackslashSyntax; + bool m_isEof; + bool m_isFileLoaded; + bool m_isGood; + qint64 m_lastPos; + int m_maxCols; + QChar m_qualifier; + QChar m_separator; + QString m_statusMsg; + QTextStream m_ts; - void getChar(QChar &c); + void getChar(QChar& c); void ungetChar(); - void peek(QChar &c); + void peek(QChar& c); void fillColumns(); - bool isTerminator(const QChar &c) const; - bool isSeparator(const QChar &c) const; - bool isQualifier(const QChar &c) const; - bool processEscapeMark(QString &s, QChar c); + bool isTerminator(const QChar& c) const; + bool isSeparator(const QChar& c) const; + bool isQualifier(const QChar& c) const; + bool processEscapeMark(QString& s, QChar c); bool isText(QChar c) const; bool isComment(); - bool isCRLF(const QChar &c) const; - bool isSpace(const QChar &c) const; - bool isTab(const QChar &c) const; + bool isCRLF(const QChar& c) const; + bool isSpace(const QChar& c) const; + bool isTab(const QChar& c) const; bool isEmptyRow(CsvRow row) const; bool parseFile(); void parseRecord(); - void parseField(CsvRow &row); - void parseSimple(QString &s); - void parseQuoted(QString &s); - void parseEscaped(QString &s); - void parseEscapedText(QString &s); - bool readFile(QFile *device); + void parseField(CsvRow& row); + void parseSimple(QString& s); + void parseQuoted(QString& s); + void parseEscaped(QString& s); + void parseEscapedText(QString& s); + bool readFile(QFile* device); void reset(); void clear(); bool skipEndline(); @@ -98,5 +99,4 @@ private: void appendStatusMsg(QString s, bool isCritical = false); }; -#endif //CSVPARSER_H - +#endif // CSVPARSER_H diff --git a/src/core/CustomData.cpp b/src/core/CustomData.cpp index 61ac2980e..ea0a35804 100644 --- a/src/core/CustomData.cpp +++ b/src/core/CustomData.cpp @@ -54,7 +54,7 @@ void CustomData::set(const QString& key, const QString& value) if (addAttribute) { emit aboutToBeAdded(key); - } + } if (addAttribute || changeValue) { m_data.insert(key, value); diff --git a/src/core/CustomData.h b/src/core/CustomData.h index 3a6b64bce..297fd16fb 100644 --- a/src/core/CustomData.h +++ b/src/core/CustomData.h @@ -25,7 +25,7 @@ class CustomData : public QObject { -Q_OBJECT + Q_OBJECT public: explicit CustomData(QObject* parent = nullptr); @@ -45,7 +45,6 @@ public: bool operator==(const CustomData& other) const; bool operator!=(const CustomData& other) const; - signals: void modified(); void aboutToBeAdded(const QString& key); diff --git a/src/core/Database.cpp b/src/core/Database.cpp index 0c2d06b3d..219a97f3d 100644 --- a/src/core/Database.cpp +++ b/src/core/Database.cpp @@ -32,8 +32,8 @@ #include "format/KeePass2.h" #include "format/KeePass2Reader.h" #include "format/KeePass2Writer.h" -#include "keys/PasswordKey.h" #include "keys/FileKey.h" +#include "keys/PasswordKey.h" QHash<Uuid, Database*> Database::m_uuidMap; @@ -129,7 +129,8 @@ Entry* Database::findEntryRecursive(const Uuid& uuid, Group* group) Entry* Database::findEntryRecursive(const QString& text, EntryReferenceType referenceType, Group* group) { - Q_ASSERT_X(referenceType != EntryReferenceType::Unknown, "Database::findEntryRecursive", + Q_ASSERT_X(referenceType != EntryReferenceType::Unknown, + "Database::findEntryRecursive", "Can't search entry with \"referenceType\" parameter equal to \"Unknown\""); bool found = false; @@ -335,7 +336,6 @@ void Database::setPublicCustomData(const QVariantMap& customData) m_data.publicCustomData = customData; } - void Database::createRecycleBin() { Group* recycleBin = Group::createRecycleBin(); @@ -407,7 +407,6 @@ void Database::setEmitModified(bool value) m_emitModified = value; } - Uuid Database::uuid() { return m_uuid; diff --git a/src/core/Database.h b/src/core/Database.h index 583ed3cac..26b0ab663 100644 --- a/src/core/Database.h +++ b/src/core/Database.h @@ -23,8 +23,8 @@ #include <QHash> #include <QObject> -#include "crypto/kdf/Kdf.h" #include "core/Uuid.h" +#include "crypto/kdf/Kdf.h" #include "keys/CompositeKey.h" class Entry; @@ -101,8 +101,7 @@ public: void setCipher(const Uuid& cipher); void setCompressionAlgo(Database::CompressionAlgorithm algo); void setKdf(QSharedPointer<Kdf> kdf); - bool setKey(const CompositeKey& key, bool updateChangedTime = true, - bool updateTransformSalt = false); + bool setKey(const CompositeKey& key, bool updateChangedTime = true, bool updateTransformSalt = false); bool hasKey() const; bool verifyKey(const CompositeKey& key) const; QVariantMap& publicCustomData(); diff --git a/src/core/DatabaseIcons.cpp b/src/core/DatabaseIcons.cpp index e53c6aa2c..ddb4e9106 100644 --- a/src/core/DatabaseIcons.cpp +++ b/src/core/DatabaseIcons.cpp @@ -106,8 +106,7 @@ QImage DatabaseIcons::icon(int index) if (!m_iconCache[index].isNull()) { return m_iconCache[index]; - } - else { + } else { QString iconPath = QString("icons/database/").append(m_indexToName[index]); QImage icon(filePath()->dataPath(iconPath)); diff --git a/src/core/DatabaseIcons.h b/src/core/DatabaseIcons.h index a1d9480b6..43a6df216 100644 --- a/src/core/DatabaseIcons.h +++ b/src/core/DatabaseIcons.h @@ -46,7 +46,8 @@ private: Q_DISABLE_COPY(DatabaseIcons) }; -inline DatabaseIcons* databaseIcons() { +inline DatabaseIcons* databaseIcons() +{ return DatabaseIcons::instance(); } diff --git a/src/core/Endian.h b/src/core/Endian.h index cd01eb483..c2d87ee3f 100644 --- a/src/core/Endian.h +++ b/src/core/Endian.h @@ -20,59 +20,55 @@ #define KEEPASSX_ENDIAN_H #include <QByteArray> +#include <QIODevice> #include <QSysInfo> #include <QtEndian> -#include <QIODevice> namespace Endian { -template<typename SizedQInt> -SizedQInt bytesToSizedInt(const QByteArray& ba, QSysInfo::Endian byteOrder) -{ - Q_ASSERT(ba.size() == sizeof(SizedQInt)); + template <typename SizedQInt> SizedQInt bytesToSizedInt(const QByteArray& ba, QSysInfo::Endian byteOrder) + { + Q_ASSERT(ba.size() == sizeof(SizedQInt)); - if (byteOrder == QSysInfo::LittleEndian) { - return qFromLittleEndian<SizedQInt>(reinterpret_cast<const uchar*>(ba.constData())); + if (byteOrder == QSysInfo::LittleEndian) { + return qFromLittleEndian<SizedQInt>(reinterpret_cast<const uchar*>(ba.constData())); + } + return qFromBigEndian<SizedQInt>(reinterpret_cast<const uchar*>(ba.constData())); } - return qFromBigEndian<SizedQInt>(reinterpret_cast<const uchar*>(ba.constData())); -} -template<typename SizedQInt> -SizedQInt readSizedInt(QIODevice* device, QSysInfo::Endian byteOrder, bool* ok) -{ - QByteArray ba = device->read(sizeof(SizedQInt)); + template <typename SizedQInt> SizedQInt readSizedInt(QIODevice* device, QSysInfo::Endian byteOrder, bool* ok) + { + QByteArray ba = device->read(sizeof(SizedQInt)); - if (ba.size() != sizeof(SizedQInt)) { - *ok = false; - return 0; + if (ba.size() != sizeof(SizedQInt)) { + *ok = false; + return 0; + } + *ok = true; + return bytesToSizedInt<SizedQInt>(ba, byteOrder); } - *ok = true; - return bytesToSizedInt<SizedQInt>(ba, byteOrder); -} -template<typename SizedQInt> -QByteArray sizedIntToBytes(SizedQInt num, QSysInfo::Endian byteOrder) -{ - QByteArray ba; - ba.resize(sizeof(SizedQInt)); + template <typename SizedQInt> QByteArray sizedIntToBytes(SizedQInt num, QSysInfo::Endian byteOrder) + { + QByteArray ba; + ba.resize(sizeof(SizedQInt)); - if (byteOrder == QSysInfo::LittleEndian) { - qToLittleEndian<SizedQInt>(num, reinterpret_cast<uchar*>(ba.data())); - } else { - qToBigEndian<SizedQInt>(num, reinterpret_cast<uchar*>(ba.data())); - } + if (byteOrder == QSysInfo::LittleEndian) { + qToLittleEndian<SizedQInt>(num, reinterpret_cast<uchar*>(ba.data())); + } else { + qToBigEndian<SizedQInt>(num, reinterpret_cast<uchar*>(ba.data())); + } - return ba; -} + return ba; + } -template<typename SizedQInt> -bool writeSizedInt(SizedQInt num, QIODevice* device, QSysInfo::Endian byteOrder) -{ - QByteArray ba = sizedIntToBytes<SizedQInt>(num, byteOrder); - qint64 bytesWritten = device->write(ba); - return (bytesWritten == ba.size()); -} + template <typename SizedQInt> bool writeSizedInt(SizedQInt num, QIODevice* device, QSysInfo::Endian byteOrder) + { + QByteArray ba = sizedIntToBytes<SizedQInt>(num, byteOrder); + qint64 bytesWritten = device->write(ba); + return (bytesWritten == ba.size()); + } } // namespace Endian diff --git a/src/core/Entry.cpp b/src/core/Entry.cpp index 00fec506f..b63f4c703 100644 --- a/src/core/Entry.cpp +++ b/src/core/Entry.cpp @@ -32,7 +32,6 @@ const int Entry::ResolveMaximumDepth = 10; const QString Entry::AutoTypeSequenceUsername = "{USERNAME}{ENTER}"; const QString Entry::AutoTypeSequencePassword = "{PASSWORD}{ENTER}"; - Entry::Entry() : m_attributes(new EntryAttributes(this)) , m_attachments(new EntryAttachments(this)) @@ -78,8 +77,7 @@ template <class T> inline bool Entry::set(T& property, const T& value) property = value; emit modified(); return true; - } - else { + } else { return false; } } @@ -129,14 +127,12 @@ QImage Entry::icon() const { if (m_data.customIcon.isNull()) { return databaseIcons()->icon(m_data.iconNumber); - } - else { + } else { Q_ASSERT(database()); if (database()) { return database()->metadata()->customIcon(m_data.customIcon); - } - else { + } else { return QImage(); } } @@ -146,14 +142,12 @@ QPixmap Entry::iconPixmap() const { if (m_data.customIcon.isNull()) { return databaseIcons()->iconPixmap(m_data.iconNumber); - } - else { + } else { Q_ASSERT(database()); if (database()) { return database()->metadata()->customIconPixmap(m_data.customIcon); - } - else { + } else { return QPixmap(); } } @@ -164,8 +158,7 @@ QPixmap Entry::iconScaledPixmap() const if (m_data.customIcon.isNull()) { // built-in icons are 16x16 so don't need to be scaled return databaseIcons()->iconPixmap(m_data.iconNumber); - } - else { + } else { Q_ASSERT(database()); return database()->metadata()->customIconScaledPixmap(m_data.customIcon); @@ -381,7 +374,7 @@ void Entry::setTotp(const QString& seed, quint8& step, quint8& digits) } QString data; - const Totp::Encoder & enc = Totp::encoders.value(digits, Totp::defaultEncoder); + const Totp::Encoder& enc = Totp::encoders.value(digits, Totp::defaultEncoder); if (m_attributes->hasKey("otp")) { data = QString("key=%1&step=%2&size=%3").arg(seed).arg(step).arg(enc.digits == 0 ? digits : enc.digits); @@ -503,9 +496,9 @@ void Entry::setTitle(const QString& title) void Entry::setUrl(const QString& url) { - bool remove = url != m_attributes->value(EntryAttributes::URLKey) && - (m_attributes->value(EntryAttributes::RememberCmdExecAttr) == "1" || - m_attributes->value(EntryAttributes::RememberCmdExecAttr) == "0"); + bool remove = url != m_attributes->value(EntryAttributes::URLKey) + && (m_attributes->value(EntryAttributes::RememberCmdExecAttr) == "1" + || m_attributes->value(EntryAttributes::RememberCmdExecAttr) == "0"); if (remove) { m_attributes->remove(EntryAttributes::RememberCmdExecAttr); } @@ -640,8 +633,7 @@ Entry* Entry::clone(CloneFlags flags) const entry->setUpdateTimeinfo(false); if (flags & CloneNewUuid) { entry->m_uuid = Uuid::random(); - } - else { + } else { entry->m_uuid = m_uuid; } entry->m_data = m_data; @@ -652,12 +644,14 @@ Entry* Entry::clone(CloneFlags flags) const if (flags & CloneUserAsRef) { // Build the username reference QString username = "{REF:U@I:" + m_uuid.toHex() + "}"; - entry->m_attributes->set(EntryAttributes::UserNameKey, username.toUpper(), m_attributes->isProtected(EntryAttributes::UserNameKey)); + entry->m_attributes->set( + EntryAttributes::UserNameKey, username.toUpper(), m_attributes->isProtected(EntryAttributes::UserNameKey)); } if (flags & ClonePassAsRef) { QString password = "{REF:P@I:" + m_uuid.toHex() + "}"; - entry->m_attributes->set(EntryAttributes::PasswordKey, password.toUpper(), m_attributes->isProtected(EntryAttributes::PasswordKey)); + entry->m_attributes->set( + EntryAttributes::PasswordKey, password.toUpper(), m_attributes->isProtected(EntryAttributes::PasswordKey)); } entry->m_autoTypeAssociations->copyDataFrom(m_autoTypeAssociations); @@ -719,8 +713,7 @@ bool Entry::endUpdate() m_tmpHistoryItem->setUpdateTimeinfo(true); addHistoryItem(m_tmpHistoryItem); truncateHistory(); - } - else { + } else { delete m_tmpHistoryItem; } @@ -933,8 +926,8 @@ void Entry::setGroup(Group* group) // copy custom icon to the new database if (!iconUuid().isNull() && group->database() - && m_group->database()->metadata()->containsCustomIcon(iconUuid()) - && !group->database()->metadata()->containsCustomIcon(iconUuid())) { + && m_group->database()->metadata()->containsCustomIcon(iconUuid()) + && !group->database()->metadata()->containsCustomIcon(iconUuid())) { group->database()->metadata()->addCustomIcon(iconUuid(), icon()); } } @@ -959,8 +952,7 @@ const Database* Entry::database() const { if (m_group) { return m_group->database(); - } - else { + } else { return nullptr; } } @@ -1028,26 +1020,25 @@ Entry::PlaceholderType Entry::placeholderType(const QString& placeholder) const return PlaceholderType::Reference; } - static const QMap<QString, PlaceholderType> placeholders { - { QStringLiteral("{TITLE}"), PlaceholderType::Title }, - { QStringLiteral("{USERNAME}"), PlaceholderType::UserName }, - { QStringLiteral("{PASSWORD}"), PlaceholderType::Password }, - { QStringLiteral("{NOTES}"), PlaceholderType::Notes }, - { QStringLiteral("{TOTP}"), PlaceholderType::Totp }, - { QStringLiteral("{URL}"), PlaceholderType::Url }, - { QStringLiteral("{URL:RMVSCM}"), PlaceholderType::UrlWithoutScheme }, - { QStringLiteral("{URL:WITHOUTSCHEME}"), PlaceholderType::UrlWithoutScheme }, - { QStringLiteral("{URL:SCM}"), PlaceholderType::UrlScheme }, - { QStringLiteral("{URL:SCHEME}"), PlaceholderType::UrlScheme }, - { QStringLiteral("{URL:HOST}"), PlaceholderType::UrlHost }, - { QStringLiteral("{URL:PORT}"), PlaceholderType::UrlPort }, - { QStringLiteral("{URL:PATH}"), PlaceholderType::UrlPath }, - { QStringLiteral("{URL:QUERY}"), PlaceholderType::UrlQuery }, - { QStringLiteral("{URL:FRAGMENT}"), PlaceholderType::UrlFragment }, - { QStringLiteral("{URL:USERINFO}"), PlaceholderType::UrlUserInfo }, - { QStringLiteral("{URL:USERNAME}"), PlaceholderType::UrlUserName }, - { QStringLiteral("{URL:PASSWORD}"), PlaceholderType::UrlPassword } - }; + static const QMap<QString, PlaceholderType> placeholders{ + {QStringLiteral("{TITLE}"), PlaceholderType::Title}, + {QStringLiteral("{USERNAME}"), PlaceholderType::UserName}, + {QStringLiteral("{PASSWORD}"), PlaceholderType::Password}, + {QStringLiteral("{NOTES}"), PlaceholderType::Notes}, + {QStringLiteral("{TOTP}"), PlaceholderType::Totp}, + {QStringLiteral("{URL}"), PlaceholderType::Url}, + {QStringLiteral("{URL:RMVSCM}"), PlaceholderType::UrlWithoutScheme}, + {QStringLiteral("{URL:WITHOUTSCHEME}"), PlaceholderType::UrlWithoutScheme}, + {QStringLiteral("{URL:SCM}"), PlaceholderType::UrlScheme}, + {QStringLiteral("{URL:SCHEME}"), PlaceholderType::UrlScheme}, + {QStringLiteral("{URL:HOST}"), PlaceholderType::UrlHost}, + {QStringLiteral("{URL:PORT}"), PlaceholderType::UrlPort}, + {QStringLiteral("{URL:PATH}"), PlaceholderType::UrlPath}, + {QStringLiteral("{URL:QUERY}"), PlaceholderType::UrlQuery}, + {QStringLiteral("{URL:FRAGMENT}"), PlaceholderType::UrlFragment}, + {QStringLiteral("{URL:USERINFO}"), PlaceholderType::UrlUserInfo}, + {QStringLiteral("{URL:USERNAME}"), PlaceholderType::UrlUserName}, + {QStringLiteral("{URL:PASSWORD}"), PlaceholderType::UrlPassword}}; return placeholders.value(placeholder.toUpper(), PlaceholderType::Unknown); } @@ -1062,7 +1053,7 @@ QString Entry::resolveUrl(const QString& url) const if (newUrl.startsWith("cmd://")) { QStringList cmdList = newUrl.split(" "); - for (int i=1; i < cmdList.size(); ++i) { + for (int i = 1; i < cmdList.size(); ++i) { // Don't pass arguments to the resolveUrl function (they look like URL's) if (!cmdList[i].startsWith("-") && !cmdList[i].startsWith("/")) { return resolveUrl(cmdList[i].remove(QRegExp("'|\""))); diff --git a/src/core/Entry.h b/src/core/Entry.h index 6ddf87dea..c096a9a25 100644 --- a/src/core/Entry.h +++ b/src/core/Entry.h @@ -37,7 +37,8 @@ class Database; class Group; -enum class EntryReferenceType { +enum class EntryReferenceType +{ Unknown, Title, UserName, @@ -142,18 +143,20 @@ public: void removeHistoryItems(const QList<Entry*>& historyEntries); void truncateHistory(); - enum CloneFlag { - CloneNoFlags = 0, - CloneNewUuid = 1, // generate a random uuid for the clone - CloneResetTimeInfo = 2, // set all TimeInfo attributes to the current time - CloneIncludeHistory = 4, // clone the history items - CloneRenameTitle = 8, // add "-Clone" after the original title - CloneUserAsRef = 16, // Add the user as a reference to the original entry - ClonePassAsRef = 32, // Add the password as a reference to the original entry + enum CloneFlag + { + CloneNoFlags = 0, + CloneNewUuid = 1, // generate a random uuid for the clone + CloneResetTimeInfo = 2, // set all TimeInfo attributes to the current time + CloneIncludeHistory = 4, // clone the history items + CloneRenameTitle = 8, // add "-Clone" after the original title + CloneUserAsRef = 16, // Add the user as a reference to the original entry + ClonePassAsRef = 32, // Add the password as a reference to the original entry }; Q_DECLARE_FLAGS(CloneFlags, CloneFlag) - enum class PlaceholderType { + enum class PlaceholderType + { NotPlaceholder, Unknown, Title, diff --git a/src/core/EntryAttachments.cpp b/src/core/EntryAttachments.cpp index 4dcc0262b..d6d459636 100644 --- a/src/core/EntryAttachments.cpp +++ b/src/core/EntryAttachments.cpp @@ -17,8 +17,8 @@ #include "EntryAttachments.h" -#include <QStringList> #include <QSet> +#include <QStringList> EntryAttachments::EntryAttachments(QObject* parent) : QObject(parent) @@ -61,8 +61,7 @@ void EntryAttachments::set(const QString& key, const QByteArray& value) if (addAttachment) { emit added(key); - } - else { + } else { emit keyModified(key); } @@ -74,8 +73,7 @@ void EntryAttachments::set(const QString& key, const QByteArray& value) void EntryAttachments::remove(const QString& key) { if (!m_attachments.contains(key)) { - Q_ASSERT_X(false, "EntryAttachments::remove", - qPrintable(QString("Can't find attachment for key %1").arg(key))); + Q_ASSERT_X(false, "EntryAttachments::remove", qPrintable(QString("Can't find attachment for key %1").arg(key))); return; } @@ -94,10 +92,10 @@ void EntryAttachments::remove(const QStringList& keys) } bool isModified = false; - for (const QString &key: keys) { + for (const QString& key : keys) { if (!m_attachments.contains(key)) { - Q_ASSERT_X(false, "EntryAttachments::remove", - qPrintable(QString("Can't find attachment for key %1").arg(key))); + Q_ASSERT_X( + false, "EntryAttachments::remove", qPrintable(QString("Can't find attachment for key %1").arg(key))); continue; } diff --git a/src/core/EntryAttributes.cpp b/src/core/EntryAttributes.cpp index 772a56611..423e9d49e 100644 --- a/src/core/EntryAttributes.cpp +++ b/src/core/EntryAttributes.cpp @@ -23,8 +23,8 @@ const QString EntryAttributes::UserNameKey = "UserName"; const QString EntryAttributes::PasswordKey = "Password"; const QString EntryAttributes::URLKey = "URL"; const QString EntryAttributes::NotesKey = "Notes"; -const QStringList EntryAttributes::DefaultAttributes(QStringList() << TitleKey << UserNameKey - << PasswordKey << URLKey << NotesKey); +const QStringList EntryAttributes::DefaultAttributes(QStringList() << TitleKey << UserNameKey << PasswordKey << URLKey + << NotesKey); const QString EntryAttributes::WantedFieldGroupName = "WantedField"; const QString EntryAttributes::SearchInGroupName = "SearchIn"; @@ -113,8 +113,7 @@ void EntryAttributes::set(const QString& key, const QString& value, bool protect emitModified = true; } m_protectedAttributes.insert(key); - } - else if (m_protectedAttributes.remove(key)) { + } else if (m_protectedAttributes.remove(key)) { emitModified = true; } @@ -124,11 +123,9 @@ void EntryAttributes::set(const QString& key, const QString& value, bool protect if (defaultAttribute && changeValue) { emit defaultKeyModified(); - } - else if (addAttribute) { + } else if (addAttribute) { emit added(key); - } - else if (emitModified) { + } else if (emitModified) { emit customKeyModified(key); } } @@ -249,21 +246,19 @@ void EntryAttributes::copyDataFrom(const EntryAttributes* other) bool EntryAttributes::operator==(const EntryAttributes& other) const { - return (m_attributes == other.m_attributes - && m_protectedAttributes == other.m_protectedAttributes); + return (m_attributes == other.m_attributes && m_protectedAttributes == other.m_protectedAttributes); } bool EntryAttributes::operator!=(const EntryAttributes& other) const { - return (m_attributes != other.m_attributes - || m_protectedAttributes != other.m_protectedAttributes); + return (m_attributes != other.m_attributes || m_protectedAttributes != other.m_protectedAttributes); } QRegularExpressionMatch EntryAttributes::matchReference(const QString& text) { static QRegularExpression referenceRegExp( - "\\{REF:(?<WantedField>[TUPANI])@(?<SearchIn>[TUPANIO]):(?<SearchText>[^}]+)\\}", - QRegularExpression::CaseInsensitiveOption); + "\\{REF:(?<WantedField>[TUPANI])@(?<SearchIn>[TUPANIO]):(?<SearchText>[^}]+)\\}", + QRegularExpression::CaseInsensitiveOption); return referenceRegExp.match(text); } diff --git a/src/core/EntrySearcher.cpp b/src/core/EntrySearcher.cpp index deaefa1aa..820646a98 100644 --- a/src/core/EntrySearcher.cpp +++ b/src/core/EntrySearcher.cpp @@ -20,8 +20,7 @@ #include "core/Group.h" -QList<Entry*> EntrySearcher::search(const QString& searchTerm, const Group* group, - Qt::CaseSensitivity caseSensitivity) +QList<Entry*> EntrySearcher::search(const QString& searchTerm, const Group* group, Qt::CaseSensitivity caseSensitivity) { if (!group->resolveSearchingEnabled()) { return QList<Entry*>(); @@ -30,14 +29,14 @@ QList<Entry*> EntrySearcher::search(const QString& searchTerm, const Group* grou return searchEntries(searchTerm, group, caseSensitivity); } -QList<Entry*> EntrySearcher::searchEntries(const QString& searchTerm, const Group* group, - Qt::CaseSensitivity caseSensitivity) +QList<Entry*> +EntrySearcher::searchEntries(const QString& searchTerm, const Group* group, Qt::CaseSensitivity caseSensitivity) { QList<Entry*> searchResult; const QList<Entry*> entryList = group->entries(); for (Entry* entry : entryList) { - searchResult.append(matchEntry(searchTerm, entry, caseSensitivity)); + searchResult.append(matchEntry(searchTerm, entry, caseSensitivity)); } const QList<Group*> children = group->children(); @@ -54,8 +53,7 @@ QList<Entry*> EntrySearcher::searchEntries(const QString& searchTerm, const Grou return searchResult; } -QList<Entry*> EntrySearcher::matchEntry(const QString& searchTerm, Entry* entry, - Qt::CaseSensitivity caseSensitivity) +QList<Entry*> EntrySearcher::matchEntry(const QString& searchTerm, Entry* entry, Qt::CaseSensitivity caseSensitivity) { const QStringList wordList = searchTerm.split(QRegExp("\\s"), QString::SkipEmptyParts); for (const QString& word : wordList) { @@ -69,10 +67,10 @@ QList<Entry*> EntrySearcher::matchEntry(const QString& searchTerm, Entry* entry, bool EntrySearcher::wordMatch(const QString& word, Entry* entry, Qt::CaseSensitivity caseSensitivity) { - return entry->resolvePlaceholder(entry->title()).contains(word, caseSensitivity) || - entry->resolvePlaceholder(entry->username()).contains(word, caseSensitivity) || - entry->resolvePlaceholder(entry->url()).contains(word, caseSensitivity) || - entry->resolvePlaceholder(entry->notes()).contains(word, caseSensitivity); + return entry->resolvePlaceholder(entry->title()).contains(word, caseSensitivity) + || entry->resolvePlaceholder(entry->username()).contains(word, caseSensitivity) + || entry->resolvePlaceholder(entry->url()).contains(word, caseSensitivity) + || entry->resolvePlaceholder(entry->notes()).contains(word, caseSensitivity); } bool EntrySearcher::matchGroup(const QString& searchTerm, const Group* group, Qt::CaseSensitivity caseSensitivity) @@ -89,6 +87,5 @@ bool EntrySearcher::matchGroup(const QString& searchTerm, const Group* group, Qt bool EntrySearcher::wordMatch(const QString& word, const Group* group, Qt::CaseSensitivity caseSensitivity) { - return group->name().contains(word, caseSensitivity) || - group->notes().contains(word, caseSensitivity); + return group->name().contains(word, caseSensitivity) || group->notes().contains(word, caseSensitivity); } diff --git a/src/core/EntrySearcher.h b/src/core/EntrySearcher.h index da51eebc7..343734737 100644 --- a/src/core/EntrySearcher.h +++ b/src/core/EntrySearcher.h @@ -21,7 +21,6 @@ #include <QString> - class Group; class Entry; diff --git a/src/core/Exporter.h b/src/core/Exporter.h index dedb1c8a5..1dd24b3fb 100644 --- a/src/core/Exporter.h +++ b/src/core/Exporter.h @@ -8,7 +8,9 @@ class Exporter { public: virtual Database* exportGroup(Group* group) = 0; - virtual ~Exporter() {} + virtual ~Exporter() + { + } }; #endif // KEEPASSX_EXPORTER_H diff --git a/src/core/FilePath.cpp b/src/core/FilePath.cpp index c6f1907ad..80de1f0a7 100644 --- a/src/core/FilePath.cpp +++ b/src/core/FilePath.cpp @@ -23,8 +23,8 @@ #include <QLibrary> #include "config-keepassx.h" -#include "core/Global.h" #include "core/Config.h" +#include "core/Global.h" FilePath* FilePath::m_instance(nullptr); @@ -32,8 +32,7 @@ QString FilePath::dataPath(const QString& name) { if (name.isEmpty() || name.startsWith('/')) { return m_dataPath + name; - } - else { + } else { return m_dataPath + "/" + name; } } @@ -61,14 +60,12 @@ QString FilePath::pluginPath(const QString& name) if (configuredPluginDir != ".") { if (QDir(configuredPluginDir).isAbsolute()) { pluginPaths << configuredPluginDir; - } - else { - QString relativePluginDir = QString("%1/../%2") - .arg(QCoreApplication::applicationDirPath(), configuredPluginDir); + } else { + QString relativePluginDir = + QString("%1/../%2").arg(QCoreApplication::applicationDirPath(), configuredPluginDir); pluginPaths << QDir(relativePluginDir).canonicalPath(); - QString absolutePluginDir = QString("%1/%2") - .arg(KEEPASSX_PREFIX_DIR, configuredPluginDir); + QString absolutePluginDir = QString("%1/%2").arg(KEEPASSX_PREFIX_DIR, configuredPluginDir); pluginPaths << QDir(absolutePluginDir).canonicalPath(); } } @@ -151,11 +148,11 @@ QIcon FilePath::icon(const QString& category, const QString& name, bool fromThem } if (icon.isNull()) { - const QList<int> pngSizes = { 16, 22, 24, 32, 48, 64, 128 }; + const QList<int> pngSizes = {16, 22, 24, 32, 48, 64, 128}; QString filename; for (int size : pngSizes) { - filename = QString("%1/icons/application/%2x%2/%3.png").arg(m_dataPath, QString::number(size), - combinedName); + filename = + QString("%1/icons/application/%2x%2/%3.png").arg(m_dataPath, QString::number(size), combinedName); if (QFile::exists(filename)) { icon.addFile(filename, QSize(size, size)); } @@ -189,17 +186,16 @@ QIcon FilePath::onOffIcon(const QString& category, const QString& name) if (i == 0) { state = QIcon::Off; stateName = "off"; - } - else { + } else { state = QIcon::On; stateName = "on"; } - const QList<int> pngSizes = { 16, 22, 24, 32, 48, 64, 128 }; + const QList<int> pngSizes = {16, 22, 24, 32, 48, 64, 128}; QString filename; for (int size : pngSizes) { - filename = QString("%1/icons/application/%2x%2/%3-%4.png").arg(m_dataPath, QString::number(size), - combinedName, stateName); + filename = QString("%1/icons/application/%2x%2/%3-%4.png") + .arg(m_dataPath, QString::number(size), combinedName, stateName); if (QFile::exists(filename)) { icon.addFile(filename, QSize(size, size), QIcon::Normal, state); } @@ -229,10 +225,8 @@ FilePath::FilePath() #endif #if defined(Q_OS_UNIX) && !(defined(Q_OS_MAC) && defined(WITH_APP_BUNDLE)) else if (isDataDirAbsolute && testSetDir(KEEPASSX_DATA_DIR)) { - } - else if (!isDataDirAbsolute && testSetDir(QString("%1/../%2").arg(appDirPath, KEEPASSX_DATA_DIR))) { - } - else if (!isDataDirAbsolute && testSetDir(QString("%1/%2").arg(KEEPASSX_PREFIX_DIR, KEEPASSX_DATA_DIR))) { + } else if (!isDataDirAbsolute && testSetDir(QString("%1/../%2").arg(appDirPath, KEEPASSX_DATA_DIR))) { + } else if (!isDataDirAbsolute && testSetDir(QString("%1/%2").arg(KEEPASSX_PREFIX_DIR, KEEPASSX_DATA_DIR))) { } #endif #if defined(Q_OS_MAC) && defined(WITH_APP_BUNDLE) @@ -249,8 +243,7 @@ FilePath::FilePath() if (m_dataPath.isEmpty()) { qWarning("FilePath::DataPath: can't find data dir"); - } - else { + } else { m_dataPath = QDir::cleanPath(m_dataPath); } } @@ -260,8 +253,7 @@ bool FilePath::testSetDir(const QString& dir) if (QFile::exists(dir + "/icons/database/C00_Password.png")) { m_dataPath = dir; return true; - } - else { + } else { return false; } } diff --git a/src/core/FilePath.h b/src/core/FilePath.h index b0f0397e2..b304b5f14 100644 --- a/src/core/FilePath.h +++ b/src/core/FilePath.h @@ -50,7 +50,8 @@ private: Q_DISABLE_COPY(FilePath) }; -inline FilePath* filePath() { +inline FilePath* filePath() +{ return FilePath::instance(); } diff --git a/src/core/Global.h b/src/core/Global.h index 1cae4b51e..64570b33b 100644 --- a/src/core/Global.h +++ b/src/core/Global.h @@ -23,26 +23,30 @@ #include <QtGlobal> #if defined(Q_OS_WIN) -# if defined(KEEPASSX_BUILDING_CORE) -# define KEEPASSX_EXPORT Q_DECL_IMPORT -# else -# define KEEPASSX_EXPORT Q_DECL_EXPORT -# endif +#if defined(KEEPASSX_BUILDING_CORE) +#define KEEPASSX_EXPORT Q_DECL_IMPORT #else -# define KEEPASSX_EXPORT Q_DECL_EXPORT +#define KEEPASSX_EXPORT Q_DECL_EXPORT +#endif +#else +#define KEEPASSX_EXPORT Q_DECL_EXPORT #endif #ifndef QUINT32_MAX #define QUINT32_MAX 4294967295U #endif -template <typename T> struct AddConst { typedef const T Type; }; +template <typename T> struct AddConst +{ + typedef const T Type; +}; // this adds const to non-const objects (like std::as_const) -template <typename T> -constexpr typename AddConst<T>::Type& asConst(T &t) noexcept { return t; } +template <typename T> constexpr typename AddConst<T>::Type& asConst(T& t) noexcept +{ + return t; +} // prevent rvalue arguments: -template <typename T> -void asConst(const T&&) = delete; +template <typename T> void asConst(const T&&) = delete; #endif // KEEPASSX_GLOBAL_H diff --git a/src/core/Group.cpp b/src/core/Group.cpp index 262a4af86..b8bca108d 100644 --- a/src/core/Group.cpp +++ b/src/core/Group.cpp @@ -27,10 +27,10 @@ const int Group::DefaultIconNumber = 48; const int Group::RecycleBinIconNumber = 43; const QString Group::RootAutoTypeSequence = "{USERNAME}{TAB}{PASSWORD}{ENTER}"; -Group::CloneFlags Group::DefaultCloneFlags = static_cast<Group::CloneFlags>( - Group::CloneNewUuid | Group::CloneResetTimeInfo | Group::CloneIncludeEntries); -Entry::CloneFlags Group::DefaultEntryCloneFlags = static_cast<Entry::CloneFlags>( - Entry::CloneNewUuid | Entry::CloneResetTimeInfo); +Group::CloneFlags Group::DefaultCloneFlags = + static_cast<Group::CloneFlags>(Group::CloneNewUuid | Group::CloneResetTimeInfo | Group::CloneIncludeEntries); +Entry::CloneFlags Group::DefaultEntryCloneFlags = + static_cast<Entry::CloneFlags>(Entry::CloneNewUuid | Entry::CloneResetTimeInfo); Group::Group() : m_customData(new CustomData(this)) @@ -81,7 +81,8 @@ Group* Group::createRecycleBin() return recycleBin; } -template <class P, class V> inline bool Group::set(P& property, const V& value) { +template <class P, class V> inline bool Group::set(P& property, const V& value) +{ if (property != value) { property = value; emit modified(); @@ -123,14 +124,12 @@ QImage Group::icon() const { if (m_data.customIcon.isNull()) { return databaseIcons()->icon(m_data.iconNumber); - } - else { + } else { Q_ASSERT(m_db); if (m_db) { return m_db->metadata()->customIcon(m_data.customIcon); - } - else { + } else { return QImage(); } } @@ -140,14 +139,12 @@ QPixmap Group::iconPixmap() const { if (m_data.customIcon.isNull()) { return databaseIcons()->iconPixmap(m_data.iconNumber); - } - else { + } else { Q_ASSERT(m_db); if (m_db) { return m_db->metadata()->customIconPixmap(m_data.customIcon); - } - else { + } else { return QPixmap(); } } @@ -158,14 +155,12 @@ QPixmap Group::iconScaledPixmap() const if (m_data.customIcon.isNull()) { // built-in icons are 16x16 so don't need to be scaled return databaseIcons()->iconPixmap(m_data.iconNumber); - } - else { + } else { Q_ASSERT(m_db); if (m_db) { return m_db->metadata()->customIconScaledPixmap(m_data.customIcon); - } - else { + } else { return QPixmap(); } } @@ -401,9 +396,8 @@ void Group::setParent(Group* parent, int index) recCreateDelObjects(); // copy custom icon to the new database - if (!iconUuid().isNull() && parent->m_db - && m_db->metadata()->containsCustomIcon(iconUuid()) - && !parent->m_db->metadata()->containsCustomIcon(iconUuid())) { + if (!iconUuid().isNull() && parent->m_db && m_db->metadata()->containsCustomIcon(iconUuid()) + && !parent->m_db->metadata()->containsCustomIcon(iconUuid())) { parent->m_db->metadata()->addCustomIcon(iconUuid(), icon()); } } @@ -414,8 +408,7 @@ void Group::setParent(Group* parent, int index) emit aboutToAdd(this, index); Q_ASSERT(index <= parent->m_children.size()); parent->m_children.insert(index, this); - } - else { + } else { emit aboutToMove(this, parent, index); m_parent->m_children.removeAll(this); m_parent = parent; @@ -432,8 +425,7 @@ void Group::setParent(Group* parent, int index) if (!moveWithinDatabase) { emit added(); - } - else { + } else { emit moved(); } } @@ -457,7 +449,7 @@ QStringList Group::hierarchy() const const Group* group = this; const Group* parent = m_parent; hierarchy.prepend(group->name()); - + while (parent) { group = group->parentGroup(); parent = group->parentGroup(); @@ -733,7 +725,6 @@ void Group::merge(const Group* other) resolveGroupConflict(existingGroup, group); existingGroup->merge(group); } - } emit modified(); @@ -849,9 +840,9 @@ void Group::recSetDatabase(Database* db) disconnect(SIGNAL(dataChanged(Group*)), m_db); disconnect(SIGNAL(aboutToRemove(Group*)), m_db); disconnect(SIGNAL(removed()), m_db); - disconnect(SIGNAL(aboutToAdd(Group*,int)), m_db); + disconnect(SIGNAL(aboutToAdd(Group*, int)), m_db); disconnect(SIGNAL(added()), m_db); - disconnect(SIGNAL(aboutToMove(Group*,Group*,int)), m_db); + disconnect(SIGNAL(aboutToMove(Group*, Group*, int)), m_db); disconnect(SIGNAL(moved()), m_db); disconnect(SIGNAL(modified()), m_db); } @@ -869,9 +860,9 @@ void Group::recSetDatabase(Database* db) connect(this, SIGNAL(dataChanged(Group*)), db, SIGNAL(groupDataChanged(Group*))); connect(this, SIGNAL(aboutToRemove(Group*)), db, SIGNAL(groupAboutToRemove(Group*))); connect(this, SIGNAL(removed()), db, SIGNAL(groupRemoved())); - connect(this, SIGNAL(aboutToAdd(Group*,int)), db, SIGNAL(groupAboutToAdd(Group*,int))); + connect(this, SIGNAL(aboutToAdd(Group*, int)), db, SIGNAL(groupAboutToAdd(Group*, int))); connect(this, SIGNAL(added()), db, SIGNAL(groupAdded())); - connect(this, SIGNAL(aboutToMove(Group*,Group*,int)), db, SIGNAL(groupAboutToMove(Group*,Group*,int))); + connect(this, SIGNAL(aboutToMove(Group*, Group*, int)), db, SIGNAL(groupAboutToMove(Group*, Group*, int))); connect(this, SIGNAL(moved()), db, SIGNAL(groupMoved())); connect(this, SIGNAL(modified()), db, SIGNAL(modifiedImmediate())); } @@ -910,8 +901,7 @@ void Group::recCreateDelObjects() void Group::markOlderEntry(Entry* entry) { entry->attributes()->set( - "merged", - tr("older entry merged from database \"%1\"").arg(entry->group()->database()->metadata()->name())); + "merged", tr("older entry merged from database \"%1\"").arg(entry->group()->database()->metadata()->name())); } bool Group::resolveSearchingEnabled() const @@ -920,8 +910,7 @@ bool Group::resolveSearchingEnabled() const case Inherit: if (!m_parent) { return true; - } - else { + } else { return m_parent->resolveSearchingEnabled(); } case Enable: @@ -940,8 +929,7 @@ bool Group::resolveAutoTypeEnabled() const case Inherit: if (!m_parent) { return true; - } - else { + } else { return m_parent->resolveAutoTypeEnabled(); } case Enable: @@ -1003,13 +991,12 @@ void Group::resolveGroupConflict(Group* existingGroup, Group* otherGroup) existingGroup->setName(otherGroup->name()); existingGroup->setNotes(otherGroup->notes()); if (otherGroup->iconNumber() == 0) { - existingGroup->setIcon(otherGroup->iconUuid()); + existingGroup->setIcon(otherGroup->iconUuid()); } else { - existingGroup->setIcon(otherGroup->iconNumber()); + existingGroup->setIcon(otherGroup->iconNumber()); } existingGroup->setExpiryTime(otherGroup->timeInfo().expiryTime()); } - } QStringList Group::locate(QString locateTerm, QString currentPath) @@ -1059,5 +1046,4 @@ Entry* Group::addEntryWithPath(QString entryPath) entry->setGroup(group); return entry; - } diff --git a/src/core/Group.h b/src/core/Group.h index cc923e43b..22220e42c 100644 --- a/src/core/Group.h +++ b/src/core/Group.h @@ -24,9 +24,9 @@ #include <QPixmapCache> #include <QPointer> +#include "core/CustomData.h" #include "core/Database.h" #include "core/Entry.h" -#include "core/CustomData.h" #include "core/TimeInfo.h" #include "core/Uuid.h" @@ -35,14 +35,26 @@ class Group : public QObject Q_OBJECT public: - enum TriState { Inherit, Enable, Disable }; - enum MergeMode { ModeInherit, KeepBoth, KeepNewer, KeepExisting }; - - enum CloneFlag { - CloneNoFlags = 0, - CloneNewUuid = 1, // generate a random uuid for the clone - CloneResetTimeInfo = 2, // set all TimeInfo attributes to the current time - CloneIncludeEntries = 4, // clone the group entries + enum TriState + { + Inherit, + Enable, + Disable + }; + enum MergeMode + { + ModeInherit, + KeepBoth, + KeepNewer, + KeepExisting + }; + + enum CloneFlag + { + CloneNoFlags = 0, + CloneNewUuid = 1, // generate a random uuid for the clone + CloneResetTimeInfo = 2, // set all TimeInfo attributes to the current time + CloneIncludeEntries = 4, // clone the group entries }; Q_DECLARE_FLAGS(CloneFlags, CloneFlag) diff --git a/src/core/InactivityTimer.cpp b/src/core/InactivityTimer.cpp index 0cfc8f0d4..405970cc6 100644 --- a/src/core/InactivityTimer.cpp +++ b/src/core/InactivityTimer.cpp @@ -56,9 +56,9 @@ bool InactivityTimer::eventFilter(QObject* watched, QEvent* event) { const QEvent::Type type = event->type(); - if ( (type >= QEvent::MouseButtonPress && type <= QEvent::KeyRelease) - || (type >= QEvent::HoverEnter && type <= QEvent::HoverMove) - || (type == QEvent::Wheel) ) { + if ((type >= QEvent::MouseButtonPress && type <= QEvent::KeyRelease) + || (type >= QEvent::HoverEnter && type <= QEvent::HoverMove) + || (type == QEvent::Wheel)) { m_timer->start(); } diff --git a/src/core/ListDeleter.h b/src/core/ListDeleter.h index 5687cbb1d..6f289546f 100644 --- a/src/core/ListDeleter.h +++ b/src/core/ListDeleter.h @@ -20,12 +20,15 @@ #include <QList> -template <typename T> -class ListDeleter +template <typename T> class ListDeleter { public: - inline explicit ListDeleter(QList<T>* list) : m_list(list) {} - inline ~ListDeleter() { + inline explicit ListDeleter(QList<T>* list) + : m_list(list) + { + } + inline ~ListDeleter() + { qDeleteAll(*m_list); } diff --git a/src/core/MacPasteboard.cpp b/src/core/MacPasteboard.cpp index 98dc6f7ab..ae63ea4e4 100644 --- a/src/core/MacPasteboard.cpp +++ b/src/core/MacPasteboard.cpp @@ -17,9 +17,13 @@ #include "MacPasteboard.h" -QString MacPasteboard::convertorName() { return QLatin1String("MacPasteboard"); } +QString MacPasteboard::convertorName() +{ + return QLatin1String("MacPasteboard"); +} -QString MacPasteboard::flavorFor(const QString& mimetype) { +QString MacPasteboard::flavorFor(const QString& mimetype) +{ if (mimetype == QLatin1String("text/plain")) { return QLatin1String("public.utf8-plain-text"); } else if (mimetype == QLatin1String("application/x-nspasteboard-concealed-type")) { @@ -38,15 +42,15 @@ QString MacPasteboard::flavorFor(const QString& mimetype) { if (cs == QLatin1String("system")) { return QLatin1String("public.utf8-plain-text"); - } else if (cs == QLatin1String("iso-10646-ucs-2") || - cs == QLatin1String("utf16")) { + } else if (cs == QLatin1String("iso-10646-ucs-2") || cs == QLatin1String("utf16")) { return QLatin1String("public.utf16-plain-text"); } } return QString(); } -QString MacPasteboard::mimeFor(QString flavor) { +QString MacPasteboard::mimeFor(QString flavor) +{ if (flavor == QLatin1String("public.utf8-plain-text")) return QLatin1String("text/plain"); if (flavor == QLatin1String("org.nspasteboard.ConcealedType")) @@ -56,13 +60,15 @@ QString MacPasteboard::mimeFor(QString flavor) { return QString(); } -bool MacPasteboard::canConvert(const QString& mimetype, QString flavor) { +bool MacPasteboard::canConvert(const QString& mimetype, QString flavor) +{ Q_UNUSED(mimetype); Q_UNUSED(flavor); return true; } -QVariant MacPasteboard::convertToMime(const QString& mimetype, QList<QByteArray> data, QString flavor) { +QVariant MacPasteboard::convertToMime(const QString& mimetype, QList<QByteArray> data, QString flavor) +{ if (data.count() > 1) qWarning("QMime::convertToMime: Cannot handle multiple member data"); const QByteArray& firstData = data.first(); @@ -74,13 +80,13 @@ QVariant MacPasteboard::convertToMime(const QString& mimetype, QList<QByteArray> } else if (flavor == QLatin1String("public.utf16-plain-text")) { ret = QTextCodec::codecForName("UTF-16")->toUnicode(firstData); } else { - qWarning("QMime::convertToMime: unhandled mimetype: %s", - qPrintable(mimetype)); + qWarning("QMime::convertToMime: unhandled mimetype: %s", qPrintable(mimetype)); } return ret; } -QList<QByteArray> MacPasteboard::convertFromMime(const QString&, QVariant data, QString flavor) { +QList<QByteArray> MacPasteboard::convertFromMime(const QString&, QVariant data, QString flavor) +{ QList<QByteArray> ret; QString string = data.toString(); if (flavor == QLatin1String("public.utf8-plain-text")) @@ -91,4 +97,3 @@ QList<QByteArray> MacPasteboard::convertFromMime(const QString&, QVariant data, ret.append(QTextCodec::codecForName("UTF-16")->fromUnicode(string)); return ret; } - diff --git a/src/core/MacPasteboard.h b/src/core/MacPasteboard.h index d471a096a..f2a71e73f 100644 --- a/src/core/MacPasteboard.h +++ b/src/core/MacPasteboard.h @@ -19,20 +19,23 @@ #define KEEPASSXC_MACPASTEBOARD_H #include <QMacPasteboardMime> -#include <QTextCodec> #include <QObject> +#include <QTextCodec> class MacPasteboard : public QObject, public QMacPasteboardMime { public: - explicit MacPasteboard() : QMacPasteboardMime(MIME_ALL) {} + explicit MacPasteboard() + : QMacPasteboardMime(MIME_ALL) + { + } QString convertorName() override; - bool canConvert(const QString &mime, QString flav) override; + bool canConvert(const QString& mime, QString flav) override; QString mimeFor(QString flav) override; - QString flavorFor(const QString &mime) override; - QVariant convertToMime(const QString &mime, QList<QByteArray> data, QString flav) override; - QList<QByteArray> convertFromMime(const QString &mime, QVariant data, QString flav) override; + QString flavorFor(const QString& mime) override; + QVariant convertToMime(const QString& mime, QList<QByteArray> data, QString flav) override; + QList<QByteArray> convertFromMime(const QString& mime, QVariant data, QString flav) override; }; #endif // KEEPASSXC_MACPASTEBOARD_H diff --git a/src/core/Metadata.cpp b/src/core/Metadata.cpp index 9da2f30dc..f8b0fd2fe 100644 --- a/src/core/Metadata.cpp +++ b/src/core/Metadata.cpp @@ -15,8 +15,8 @@ * along with this program. If not, see <http://www.gnu.org/licenses/>. */ -#include <QtCore/QCryptographicHash> #include "Metadata.h" +#include <QtCore/QCryptographicHash> #include "core/Entry.h" #include "core/Group.h" @@ -61,13 +61,13 @@ template <class P, class V> bool Metadata::set(P& property, const V& value) property = value; emit modified(); return true; - } - else { + } else { return false; } } -template <class P, class V> bool Metadata::set(P& property, const V& value, QDateTime& dateTime) { +template <class P, class V> bool Metadata::set(P& property, const V& value, QDateTime& dateTime) +{ if (property != value) { property = value; if (m_updateDatetime) { @@ -75,8 +75,7 @@ template <class P, class V> bool Metadata::set(P& property, const V& value, QDat } emit modified(); return true; - } - else { + } else { return false; } } @@ -402,10 +401,8 @@ void Metadata::addCustomIconScaled(const Uuid& uuid, const QImage& icon) // scale down to 128x128 if icon is larger if (icon.width() > 128 || icon.height() > 128) { - iconScaled = icon.scaled(QSize(128, 128), Qt::KeepAspectRatio, - Qt::SmoothTransformation); - } - else { + iconScaled = icon.scaled(QSize(128, 128), Qt::KeepAspectRatio, Qt::SmoothTransformation); + } else { iconScaled = icon; } @@ -433,7 +430,7 @@ void Metadata::removeCustomIcon(const Uuid& uuid) emit modified(); } -Uuid Metadata::findCustomIcon(const QImage &candidate) +Uuid Metadata::findCustomIcon(const QImage& candidate) { QByteArray hash = hashImage(candidate); return m_customIconsHashes.value(hash, Uuid()); diff --git a/src/core/Metadata.h b/src/core/Metadata.h index a52cb0a78..a40fb502d 100644 --- a/src/core/Metadata.h +++ b/src/core/Metadata.h @@ -26,8 +26,8 @@ #include <QPixmapCache> #include <QPointer> -#include "core/Uuid.h" #include "core/CustomData.h" +#include "core/Uuid.h" class Database; class Group; diff --git a/src/core/PassphraseGenerator.cpp b/src/core/PassphraseGenerator.cpp index 88871eb8c..f972e0ef2 100644 --- a/src/core/PassphraseGenerator.cpp +++ b/src/core/PassphraseGenerator.cpp @@ -17,12 +17,12 @@ #include "PassphraseGenerator.h" -#include <cmath> #include <QFile> #include <QTextStream> +#include <cmath> -#include "crypto/Random.h" #include "core/FilePath.h" +#include "crypto/Random.h" const char* PassphraseGenerator::DefaultSeparator = " "; const char* PassphraseGenerator::DefaultWordList = "eff_large.wordlist"; @@ -52,7 +52,6 @@ void PassphraseGenerator::setWordCount(int wordCount) // safe default if something goes wrong m_wordCount = DefaultWordCount; } - } void PassphraseGenerator::setWordList(const QString& path) @@ -82,7 +81,8 @@ void PassphraseGenerator::setDefaultWordList() setWordList(path); } -void PassphraseGenerator::setWordSeparator(const QString& separator) { +void PassphraseGenerator::setWordSeparator(const QString& separator) +{ m_separator = separator; } @@ -91,7 +91,7 @@ QString PassphraseGenerator::generatePassphrase() const Q_ASSERT(isValid()); // In case there was an error loading the wordlist - if(m_wordlist.length() == 0) { + if (m_wordlist.length() == 0) { return QString(); } @@ -107,7 +107,7 @@ QString PassphraseGenerator::generatePassphrase() const bool PassphraseGenerator::isValid() const { if (m_wordCount == 0) { - return false; + return false; } return m_wordlist.size() >= 1000; diff --git a/src/core/PasswordGenerator.cpp b/src/core/PasswordGenerator.cpp index 740fb5467..00984d313 100644 --- a/src/core/PasswordGenerator.cpp +++ b/src/core/PasswordGenerator.cpp @@ -45,7 +45,7 @@ void PasswordGenerator::setLength(int length) void PasswordGenerator::setCharClasses(const CharClasses& classes) { if (classes == 0) { - m_classes = DefaultCharset; + m_classes = DefaultCharset; return; } m_classes = classes; @@ -92,8 +92,7 @@ QString PasswordGenerator::generatePassword() const password[i] = password[j]; password[j] = tmp; } - } - else { + } else { for (int i = 0; i < m_length; i++) { int pos = randomGen()->randomUInt(passwordChars.size()); @@ -110,7 +109,7 @@ int PasswordGenerator::getbits() const int bits = 0; QVector<QChar> passwordChars; - for (const PasswordGroup& group: groups) { + for (const PasswordGroup& group : groups) { bits += group.size(); } @@ -119,13 +118,11 @@ int PasswordGenerator::getbits() const return bits; } - bool PasswordGenerator::isValid() const { if (m_classes == 0) { return false; - } - else if (m_length == 0) { + } else if (m_length == 0) { return false; } diff --git a/src/core/PasswordGenerator.h b/src/core/PasswordGenerator.h index 15a0dcefe..d6866b5ef 100644 --- a/src/core/PasswordGenerator.h +++ b/src/core/PasswordGenerator.h @@ -30,20 +30,20 @@ class PasswordGenerator public: enum CharClass { - LowerLetters = 0x1, - UpperLetters = 0x2, - Numbers = 0x4, + LowerLetters = 0x1, + UpperLetters = 0x2, + Numbers = 0x4, SpecialCharacters = 0x8, - EASCII = 0x10, - DefaultCharset = LowerLetters | UpperLetters | Numbers + EASCII = 0x10, + DefaultCharset = LowerLetters | UpperLetters | Numbers }; Q_DECLARE_FLAGS(CharClasses, CharClass) enum GeneratorFlag { - ExcludeLookAlike = 0x1, + ExcludeLookAlike = 0x1, CharFromEveryGroup = 0x2, - DefaultFlags = ExcludeLookAlike | CharFromEveryGroup + DefaultFlags = ExcludeLookAlike | CharFromEveryGroup }; Q_DECLARE_FLAGS(GeneratorFlags, GeneratorFlag) diff --git a/src/core/ScreenLockListener.cpp b/src/core/ScreenLockListener.cpp index eb78cd608..2c1ba055a 100644 --- a/src/core/ScreenLockListener.cpp +++ b/src/core/ScreenLockListener.cpp @@ -18,11 +18,13 @@ #include "ScreenLockListener.h" #include "ScreenLockListenerPrivate.h" -ScreenLockListener::ScreenLockListener(QWidget* parent): - QObject(parent){ +ScreenLockListener::ScreenLockListener(QWidget* parent) + : QObject(parent) +{ m_listener = ScreenLockListenerPrivate::instance(parent); - connect(m_listener,SIGNAL(screenLocked()), this,SIGNAL(screenLocked())); + connect(m_listener, SIGNAL(screenLocked()), this, SIGNAL(screenLocked())); } -ScreenLockListener::~ScreenLockListener(){ +ScreenLockListener::~ScreenLockListener() +{ } diff --git a/src/core/ScreenLockListener.h b/src/core/ScreenLockListener.h index b4eb81e04..107d342a6 100644 --- a/src/core/ScreenLockListener.h +++ b/src/core/ScreenLockListener.h @@ -21,7 +21,8 @@ class ScreenLockListenerPrivate; -class ScreenLockListener : public QObject { +class ScreenLockListener : public QObject +{ Q_OBJECT public: diff --git a/src/core/ScreenLockListenerDBus.cpp b/src/core/ScreenLockListenerDBus.cpp index 03eed58ad..5c57861bd 100644 --- a/src/core/ScreenLockListenerDBus.cpp +++ b/src/core/ScreenLockListenerDBus.cpp @@ -22,60 +22,54 @@ #include <QDBusReply> #include <QProcessEnvironment> -ScreenLockListenerDBus::ScreenLockListenerDBus(QWidget *parent): - ScreenLockListenerPrivate(parent) +ScreenLockListenerDBus::ScreenLockListenerDBus(QWidget* parent) + : ScreenLockListenerPrivate(parent) { QDBusConnection sessionBus = QDBusConnection::sessionBus(); QDBusConnection systemBus = QDBusConnection::systemBus(); - sessionBus.connect( - "org.freedesktop.ScreenSaver", // service - "/org/freedesktop/ScreenSaver", // path - "org.freedesktop.ScreenSaver", // interface - "ActiveChanged", // signal name - this, //receiver - SLOT(freedesktopScreenSaver(bool))); + sessionBus.connect("org.freedesktop.ScreenSaver", // service + "/org/freedesktop/ScreenSaver", // path + "org.freedesktop.ScreenSaver", // interface + "ActiveChanged", // signal name + this, // receiver + SLOT(freedesktopScreenSaver(bool))); - sessionBus.connect( - "org.gnome.ScreenSaver", // service - "/org/gnome/ScreenSaver", // path - "org.gnome.ScreenSaver", // interface - "ActiveChanged", // signal name - this, //receiver - SLOT(freedesktopScreenSaver(bool))); + sessionBus.connect("org.gnome.ScreenSaver", // service + "/org/gnome/ScreenSaver", // path + "org.gnome.ScreenSaver", // interface + "ActiveChanged", // signal name + this, // receiver + SLOT(freedesktopScreenSaver(bool))); - sessionBus.connect( - "org.gnome.SessionManager", // service - "/org/gnome/SessionManager/Presence", // path - "org.gnome.SessionManager.Presence", // interface - "StatusChanged", // signal name - this, //receiver - SLOT(gnomeSessionStatusChanged(uint))); + sessionBus.connect("org.gnome.SessionManager", // service + "/org/gnome/SessionManager/Presence", // path + "org.gnome.SessionManager.Presence", // interface + "StatusChanged", // signal name + this, // receiver + SLOT(gnomeSessionStatusChanged(uint))); - systemBus.connect( - "org.freedesktop.login1", // service - "/org/freedesktop/login1", // path - "org.freedesktop.login1.Manager", // interface - "PrepareForSleep", // signal name - this, //receiver - SLOT(logindPrepareForSleep(bool))); + systemBus.connect("org.freedesktop.login1", // service + "/org/freedesktop/login1", // path + "org.freedesktop.login1.Manager", // interface + "PrepareForSleep", // signal name + this, // receiver + SLOT(logindPrepareForSleep(bool))); QString sessionId = QProcessEnvironment::systemEnvironment().value("XDG_SESSION_ID"); - systemBus.connect( - "", // service - QString("/org/freedesktop/login1/session/") + sessionId, // path - "org.freedesktop.login1.Session", // interface - "Lock", // signal name - this, //receiver - SLOT(unityLocked())); + systemBus.connect("", // service + QString("/org/freedesktop/login1/session/") + sessionId, // path + "org.freedesktop.login1.Session", // interface + "Lock", // signal name + this, // receiver + SLOT(unityLocked())); - sessionBus.connect( - "com.canonical.Unity", // service - "/com/canonical/Unity/Session", // path - "com.canonical.Unity.Session", // interface - "Locked", // signal name - this, //receiver - SLOT(unityLocked())); + sessionBus.connect("com.canonical.Unity", // service + "/com/canonical/Unity/Session", // path + "com.canonical.Unity.Session", // interface + "Locked", // signal name + this, // receiver + SLOT(unityLocked())); } void ScreenLockListenerDBus::gnomeSessionStatusChanged(uint status) diff --git a/src/core/ScreenLockListenerDBus.h b/src/core/ScreenLockListenerDBus.h index 72f308f72..dd6f5ea86 100644 --- a/src/core/ScreenLockListenerDBus.h +++ b/src/core/ScreenLockListenerDBus.h @@ -17,15 +17,15 @@ #ifndef SCREENLOCKLISTENERDBUS_H #define SCREENLOCKLISTENERDBUS_H +#include "ScreenLockListenerPrivate.h" #include <QObject> #include <QWidget> -#include "ScreenLockListenerPrivate.h" class ScreenLockListenerDBus : public ScreenLockListenerPrivate { Q_OBJECT public: - explicit ScreenLockListenerDBus(QWidget *parent = 0); + explicit ScreenLockListenerDBus(QWidget* parent = 0); private slots: void gnomeSessionStatusChanged(uint status); diff --git a/src/core/ScreenLockListenerPrivate.cpp b/src/core/ScreenLockListenerPrivate.cpp index b36b9a33a..1371a0c92 100644 --- a/src/core/ScreenLockListenerPrivate.cpp +++ b/src/core/ScreenLockListenerPrivate.cpp @@ -25,7 +25,7 @@ #endif ScreenLockListenerPrivate::ScreenLockListenerPrivate(QWidget* parent) - : QObject(parent) + : QObject(parent) { } diff --git a/src/core/ScreenLockListenerWin.cpp b/src/core/ScreenLockListenerWin.cpp index 80fa32894..05d01f4cc 100644 --- a/src/core/ScreenLockListenerWin.cpp +++ b/src/core/ScreenLockListenerWin.cpp @@ -25,7 +25,7 @@ * See https://msdn.microsoft.com/en-us/library/aa383841(v=vs.85).aspx * See https://blogs.msdn.microsoft.com/oldnewthing/20060104-50/?p=32783 */ -ScreenLockListenerWin::ScreenLockListenerWin(QWidget* parent) +ScreenLockListenerWin::ScreenLockListenerWin(QWidget* parent) : ScreenLockListenerPrivate(parent) , QAbstractNativeEventFilter() { @@ -36,20 +36,17 @@ ScreenLockListenerWin::ScreenLockListenerWin(QWidget* parent) // This call requests a notification from windows when a laptop is closed HPOWERNOTIFY hPnotify = RegisterPowerSettingNotification( - reinterpret_cast<HWND>(parent->winId()), - &GUID_LIDSWITCH_STATE_CHANGE, DEVICE_NOTIFY_WINDOW_HANDLE); + reinterpret_cast<HWND>(parent->winId()), &GUID_LIDSWITCH_STATE_CHANGE, DEVICE_NOTIFY_WINDOW_HANDLE); m_powerNotificationHandle = reinterpret_cast<void*>(hPnotify); // This call requests a notification for session changes - if (!WTSRegisterSessionNotification( - reinterpret_cast<HWND>(parent->winId()), - NOTIFY_FOR_THIS_SESSION)) { + if (!WTSRegisterSessionNotification(reinterpret_cast<HWND>(parent->winId()), NOTIFY_FOR_THIS_SESSION)) { } } ScreenLockListenerWin::~ScreenLockListenerWin() { - HWND h= reinterpret_cast<HWND>(static_cast<QWidget*>(parent())->winId()); + HWND h = reinterpret_cast<HWND>(static_cast<QWidget*>(parent())->winId()); WTSUnRegisterSessionNotification(h); if (m_powerNotificationHandle) { diff --git a/src/core/ScreenLockListenerWin.h b/src/core/ScreenLockListenerWin.h index 6a8380efe..0778c99d8 100644 --- a/src/core/ScreenLockListenerWin.h +++ b/src/core/ScreenLockListenerWin.h @@ -17,9 +17,9 @@ #ifndef SCREENLOCKLISTENERWIN_H #define SCREENLOCKLISTENERWIN_H +#include <QAbstractNativeEventFilter> #include <QObject> #include <QWidget> -#include <QAbstractNativeEventFilter> #include "ScreenLockListenerPrivate.h" @@ -29,10 +29,10 @@ class ScreenLockListenerWin : public ScreenLockListenerPrivate, public QAbstract public: explicit ScreenLockListenerWin(QWidget* parent = 0); ~ScreenLockListenerWin(); - virtual bool nativeEventFilter(const QByteArray &eventType, void* message, long*) override; + virtual bool nativeEventFilter(const QByteArray& eventType, void* message, long*) override; private: - void* m_powerNotificationHandle ; + void* m_powerNotificationHandle; }; #endif // SCREENLOCKLISTENERWIN_H diff --git a/src/core/SignalMultiplexer.cpp b/src/core/SignalMultiplexer.cpp index 0f99b8e65..d1ed89e30 100644 --- a/src/core/SignalMultiplexer.cpp +++ b/src/core/SignalMultiplexer.cpp @@ -131,8 +131,7 @@ void SignalMultiplexer::connect(const Connection& con) if (con.sender) { QObject::connect(con.sender, con.signal, m_currentObject, con.slot); - } - else { + } else { QObject::connect(m_currentObject, con.signal, con.receiver, con.slot); } } @@ -143,8 +142,7 @@ void SignalMultiplexer::disconnect(const Connection& con) if (con.sender) { QObject::disconnect(con.sender, con.signal, m_currentObject, con.slot); - } - else { + } else { QObject::disconnect(m_currentObject, con.signal, con.receiver, con.slot); } } diff --git a/src/core/TimeDelta.cpp b/src/core/TimeDelta.cpp index e2dbdac40..a5331736c 100644 --- a/src/core/TimeDelta.cpp +++ b/src/core/TimeDelta.cpp @@ -19,10 +19,9 @@ #include <QDateTime> -QDateTime operator+(const QDateTime& dateTime, const TimeDelta& delta) { - return dateTime.addDays(delta.getDays()) - .addMonths(delta.getMonths()) - .addYears(delta.getYears()); +QDateTime operator+(const QDateTime& dateTime, const TimeDelta& delta) +{ + return dateTime.addDays(delta.getDays()).addMonths(delta.getMonths()).addYears(delta.getYears()); } TimeDelta TimeDelta::fromDays(int days) diff --git a/src/core/Tools.cpp b/src/core/Tools.cpp index b9e4be8e0..47a0df03c 100644 --- a/src/core/Tools.cpp +++ b/src/core/Tools.cpp @@ -20,16 +20,16 @@ #include "Tools.h" #include <QCoreApplication> -#include <QImageReader> #include <QIODevice> +#include <QImageReader> #include <QLocale> #include <QStringList> #include <QElapsedTimer> #ifdef Q_OS_WIN +#include <aclapi.h> // for SetSecurityInfo() #include <windows.h> // for Sleep(), SetDllDirectoryA(), SetSearchPathMode(), ... -#include <aclapi.h> // for SetSecurityInfo() #endif #ifdef Q_OS_UNIX @@ -47,314 +47,298 @@ #endif #ifdef HAVE_PT_DENY_ATTACH -#include <sys/types.h> #include <sys/ptrace.h> +#include <sys/types.h> #endif -namespace Tools { - -QString humanReadableFileSize(qint64 bytes) +namespace Tools { - double size = bytes; - QStringList units = QStringList() << "B" << "KiB" << "MiB" << "GiB"; - int i = 0; - int maxI = units.size() - 1; + QString humanReadableFileSize(qint64 bytes) + { + double size = bytes; + + QStringList units = QStringList() << "B" + << "KiB" + << "MiB" + << "GiB"; + int i = 0; + int maxI = units.size() - 1; - while ((size >= 1024) && (i < maxI)) { - size /= 1024; - i++; + while ((size >= 1024) && (i < maxI)) { + size /= 1024; + i++; + } + + return QString("%1 %2").arg(QLocale().toString(size, 'f', 2), units.at(i)); } - return QString("%1 %2").arg(QLocale().toString(size, 'f', 2), units.at(i)); -} + bool hasChild(const QObject* parent, const QObject* child) + { + if (!parent || !child) { + return false; + } -bool hasChild(const QObject* parent, const QObject* child) -{ - if (!parent || !child) { + const QObjectList children = parent->children(); + for (QObject* c : children) { + if (child == c || hasChild(c, child)) { + return true; + } + } return false; } - const QObjectList children = parent->children(); - for (QObject* c : children) { - if (child == c || hasChild(c, child)) { + bool readFromDevice(QIODevice* device, QByteArray& data, int size) + { + QByteArray buffer; + buffer.resize(size); + + qint64 readResult = device->read(buffer.data(), size); + if (readResult == -1) { + return false; + } else { + buffer.resize(readResult); + data = buffer; return true; } } - return false; -} - -bool readFromDevice(QIODevice* device, QByteArray& data, int size) -{ - QByteArray buffer; - buffer.resize(size); - qint64 readResult = device->read(buffer.data(), size); - if (readResult == -1) { - return false; - } - else { - buffer.resize(readResult); - data = buffer; - return true; - } -} + bool readAllFromDevice(QIODevice* device, QByteArray& data) + { + QByteArray result; + qint64 readBytes = 0; + qint64 readResult; + do { + result.resize(result.size() + 16384); + readResult = device->read(result.data() + readBytes, result.size() - readBytes); + if (readResult > 0) { + readBytes += readResult; + } + } while (readResult > 0); -bool readAllFromDevice(QIODevice* device, QByteArray& data) -{ - QByteArray result; - qint64 readBytes = 0; - qint64 readResult; - do { - result.resize(result.size() + 16384); - readResult = device->read(result.data() + readBytes, result.size() - readBytes); - if (readResult > 0) { - readBytes += readResult; + if (readResult == -1) { + return false; + } else { + result.resize(static_cast<int>(readBytes)); + data = result; + return true; } - } while (readResult > 0); - - if (readResult == -1) { - return false; } - else { - result.resize(static_cast<int>(readBytes)); - data = result; - return true; - } -} -QString imageReaderFilter() -{ - const QList<QByteArray> formats = QImageReader::supportedImageFormats(); - QStringList formatsStringList; + QString imageReaderFilter() + { + const QList<QByteArray> formats = QImageReader::supportedImageFormats(); + QStringList formatsStringList; - for (const QByteArray& format : formats) { - for (int i = 0; i < format.size(); i++) { - if (!QChar(format.at(i)).isLetterOrNumber()) { - continue; + for (const QByteArray& format : formats) { + for (int i = 0; i < format.size(); i++) { + if (!QChar(format.at(i)).isLetterOrNumber()) { + continue; + } } + + formatsStringList.append("*." + QString::fromLatin1(format).toLower()); } - formatsStringList.append("*." + QString::fromLatin1(format).toLower()); + return formatsStringList.join(" "); } - return formatsStringList.join(" "); -} - -bool isHex(const QByteArray& ba) -{ - for (char c : ba) { - if ( !( (c >= '0' && c <= '9') || (c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F') ) ) { - return false; + bool isHex(const QByteArray& ba) + { + for (char c : ba) { + if (!((c >= '0' && c <= '9') || (c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F'))) { + return false; + } } + + return true; } - return true; -} + bool isBase64(const QByteArray& ba) + { + QRegExp regexp( + "^(?:[a-z0-9+/]{4})*(?:[a-z0-9+/]{3}=|[a-z0-9+/]{2}==)?$", Qt::CaseInsensitive, QRegExp::RegExp2); -bool isBase64(const QByteArray& ba) -{ - QRegExp regexp("^(?:[a-z0-9+/]{4})*(?:[a-z0-9+/]{3}=|[a-z0-9+/]{2}==)?$", - Qt::CaseInsensitive, QRegExp::RegExp2); + QString base64 = QString::fromLatin1(ba.constData(), ba.size()); - QString base64 = QString::fromLatin1(ba.constData(), ba.size()); + return regexp.exactMatch(base64); + } - return regexp.exactMatch(base64); -} + void sleep(int ms) + { + Q_ASSERT(ms >= 0); -void sleep(int ms) -{ - Q_ASSERT(ms >= 0); - - if (ms == 0) { - return; - } + if (ms == 0) { + return; + } #ifdef Q_OS_WIN - Sleep(uint(ms)); + Sleep(uint(ms)); #else - timespec ts; - ts.tv_sec = ms / 1000; - ts.tv_nsec = (ms % 1000) * 1000 * 1000; - nanosleep(&ts, nullptr); + timespec ts; + ts.tv_sec = ms / 1000; + ts.tv_nsec = (ms % 1000) * 1000 * 1000; + nanosleep(&ts, nullptr); #endif -} - -void wait(int ms) -{ - Q_ASSERT(ms >= 0); - - if (ms == 0) { - return; } - QElapsedTimer timer; - timer.start(); + void wait(int ms) + { + Q_ASSERT(ms >= 0); - if (ms <= 50) { - QCoreApplication::processEvents(QEventLoop::AllEvents, ms); - sleep(qMax(ms - static_cast<int>(timer.elapsed()), 0)); - } - else { - int timeLeft; - do { - timeLeft = ms - timer.elapsed(); - if (timeLeft > 0) { - QCoreApplication::processEvents(QEventLoop::AllEvents, timeLeft); - sleep(10); - } - } while (!timer.hasExpired(ms)); + if (ms == 0) { + return; + } + + QElapsedTimer timer; + timer.start(); + + if (ms <= 50) { + QCoreApplication::processEvents(QEventLoop::AllEvents, ms); + sleep(qMax(ms - static_cast<int>(timer.elapsed()), 0)); + } else { + int timeLeft; + do { + timeLeft = ms - timer.elapsed(); + if (timeLeft > 0) { + QCoreApplication::processEvents(QEventLoop::AllEvents, timeLeft); + sleep(10); + } + } while (!timer.hasExpired(ms)); + } } -} -void disableCoreDumps() -{ - // default to true - // there is no point in printing a warning if this is not implemented on the platform - bool success = true; + void disableCoreDumps() + { + // default to true + // there is no point in printing a warning if this is not implemented on the platform + bool success = true; #if defined(HAVE_RLIMIT_CORE) - struct rlimit limit; - limit.rlim_cur = 0; - limit.rlim_max = 0; - success = success && (setrlimit(RLIMIT_CORE, &limit) == 0); + struct rlimit limit; + limit.rlim_cur = 0; + limit.rlim_max = 0; + success = success && (setrlimit(RLIMIT_CORE, &limit) == 0); #endif #if defined(HAVE_PR_SET_DUMPABLE) - success = success && (prctl(PR_SET_DUMPABLE, 0) == 0); + success = success && (prctl(PR_SET_DUMPABLE, 0) == 0); #endif - // Mac OS X +// Mac OS X #ifdef HAVE_PT_DENY_ATTACH - success = success && (ptrace(PT_DENY_ATTACH, 0, 0, 0) == 0); + success = success && (ptrace(PT_DENY_ATTACH, 0, 0, 0) == 0); #endif #ifdef Q_OS_WIN - success = success && createWindowsDACL(); + success = success && createWindowsDACL(); #endif - if (!success) { - qWarning("Unable to disable core dumps."); + if (!success) { + qWarning("Unable to disable core dumps."); + } } -} -void setupSearchPaths() -{ + void setupSearchPaths() + { #ifdef Q_OS_WIN - // Make sure Windows doesn't load DLLs from the current working directory - SetDllDirectoryA(""); - SetSearchPathMode(BASE_SEARCH_PATH_ENABLE_SAFE_SEARCHMODE); + // Make sure Windows doesn't load DLLs from the current working directory + SetDllDirectoryA(""); + SetSearchPathMode(BASE_SEARCH_PATH_ENABLE_SAFE_SEARCHMODE); #endif -} - -// -// This function grants the user associated with the process token minimal access rights and -// denies everything else on Windows. This includes PROCESS_QUERY_INFORMATION and -// PROCESS_VM_READ access rights that are required for MiniDumpWriteDump() or ReadProcessMemory(). -// We do this using a discretionary access control list (DACL). Effectively this prevents -// crash dumps and disallows other processes from accessing our memory. This works as long -// as you do not have admin privileges, since then you are able to grant yourself the -// SeDebugPrivilege or SeTakeOwnershipPrivilege and circumvent the DACL. -// -bool createWindowsDACL() -{ - bool bSuccess = false; + } + + // + // This function grants the user associated with the process token minimal access rights and + // denies everything else on Windows. This includes PROCESS_QUERY_INFORMATION and + // PROCESS_VM_READ access rights that are required for MiniDumpWriteDump() or ReadProcessMemory(). + // We do this using a discretionary access control list (DACL). Effectively this prevents + // crash dumps and disallows other processes from accessing our memory. This works as long + // as you do not have admin privileges, since then you are able to grant yourself the + // SeDebugPrivilege or SeTakeOwnershipPrivilege and circumvent the DACL. + // + bool createWindowsDACL() + { + bool bSuccess = false; #ifdef Q_OS_WIN - // Process token and user - HANDLE hToken = nullptr; - PTOKEN_USER pTokenUser = nullptr; - DWORD cbBufferSize = 0; - - // Access control list - PACL pACL = nullptr; - DWORD cbACL = 0; - - // Open the access token associated with the calling process - if (!OpenProcessToken( - GetCurrentProcess(), - TOKEN_QUERY, - &hToken - )) { - goto Cleanup; - } + // Process token and user + HANDLE hToken = nullptr; + PTOKEN_USER pTokenUser = nullptr; + DWORD cbBufferSize = 0; + + // Access control list + PACL pACL = nullptr; + DWORD cbACL = 0; + + // Open the access token associated with the calling process + if (!OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &hToken)) { + goto Cleanup; + } - // Retrieve the token information in a TOKEN_USER structure - GetTokenInformation( - hToken, - TokenUser, - nullptr, - 0, - &cbBufferSize - ); - - pTokenUser = static_cast<PTOKEN_USER>(HeapAlloc(GetProcessHeap(), 0, cbBufferSize)); - if (pTokenUser == nullptr) { - goto Cleanup; - } + // Retrieve the token information in a TOKEN_USER structure + GetTokenInformation(hToken, TokenUser, nullptr, 0, &cbBufferSize); - if (!GetTokenInformation( - hToken, - TokenUser, - pTokenUser, - cbBufferSize, - &cbBufferSize - )) { - goto Cleanup; - } + pTokenUser = static_cast<PTOKEN_USER>(HeapAlloc(GetProcessHeap(), 0, cbBufferSize)); + if (pTokenUser == nullptr) { + goto Cleanup; + } - if (!IsValidSid(pTokenUser->User.Sid)) { - goto Cleanup; - } + if (!GetTokenInformation(hToken, TokenUser, pTokenUser, cbBufferSize, &cbBufferSize)) { + goto Cleanup; + } - // Calculate the amount of memory that must be allocated for the DACL - cbACL = sizeof(ACL) - + sizeof(ACCESS_ALLOWED_ACE) + GetLengthSid(pTokenUser->User.Sid); + if (!IsValidSid(pTokenUser->User.Sid)) { + goto Cleanup; + } - // Create and initialize an ACL - pACL = static_cast<PACL>(HeapAlloc(GetProcessHeap(), 0, cbACL)); - if (pACL == nullptr) { - goto Cleanup; - } + // Calculate the amount of memory that must be allocated for the DACL + cbACL = sizeof(ACL) + sizeof(ACCESS_ALLOWED_ACE) + GetLengthSid(pTokenUser->User.Sid); - if (!InitializeAcl(pACL, cbACL, ACL_REVISION)) { - goto Cleanup; - } + // Create and initialize an ACL + pACL = static_cast<PACL>(HeapAlloc(GetProcessHeap(), 0, cbACL)); + if (pACL == nullptr) { + goto Cleanup; + } - // Add allowed access control entries, everything else is denied - if (!AddAccessAllowedAce( - pACL, - ACL_REVISION, - SYNCHRONIZE | PROCESS_QUERY_LIMITED_INFORMATION | PROCESS_TERMINATE, // same as protected process - pTokenUser->User.Sid // pointer to the trustee's SID - )) { - goto Cleanup; - } + if (!InitializeAcl(pACL, cbACL, ACL_REVISION)) { + goto Cleanup; + } - // Set discretionary access control list - bSuccess = ERROR_SUCCESS == SetSecurityInfo( - GetCurrentProcess(), // object handle - SE_KERNEL_OBJECT, // type of object - DACL_SECURITY_INFORMATION, // change only the objects DACL - nullptr, nullptr, // do not change owner or group - pACL, // DACL specified - nullptr // do not change SACL - ); + // Add allowed access control entries, everything else is denied + if (!AddAccessAllowedAce( + pACL, + ACL_REVISION, + SYNCHRONIZE | PROCESS_QUERY_LIMITED_INFORMATION | PROCESS_TERMINATE, // same as protected process + pTokenUser->User.Sid // pointer to the trustee's SID + )) { + goto Cleanup; + } -Cleanup: + // Set discretionary access control list + bSuccess = ERROR_SUCCESS == SetSecurityInfo(GetCurrentProcess(), // object handle + SE_KERNEL_OBJECT, // type of object + DACL_SECURITY_INFORMATION, // change only the objects DACL + nullptr, + nullptr, // do not change owner or group + pACL, // DACL specified + nullptr // do not change SACL + ); - if (pACL != nullptr) { - HeapFree(GetProcessHeap(), 0, pACL); - } - if (pTokenUser != nullptr) { - HeapFree(GetProcessHeap(), 0, pTokenUser); - } - if (hToken != nullptr) { - CloseHandle(hToken); - } + Cleanup: + + if (pACL != nullptr) { + HeapFree(GetProcessHeap(), 0, pACL); + } + if (pTokenUser != nullptr) { + HeapFree(GetProcessHeap(), 0, pTokenUser); + } + if (hToken != nullptr) { + CloseHandle(hToken); + } #endif - return bSuccess; -} + return bSuccess; + } } // namespace Tools diff --git a/src/core/Tools.h b/src/core/Tools.h index b6fa49c02..b11760079 100644 --- a/src/core/Tools.h +++ b/src/core/Tools.h @@ -29,33 +29,33 @@ class QIODevice; -namespace Tools { - -QString humanReadableFileSize(qint64 bytes); -bool hasChild(const QObject* parent, const QObject* child); -bool readFromDevice(QIODevice* device, QByteArray& data, int size = 16384); -bool readAllFromDevice(QIODevice* device, QByteArray& data); -QString imageReaderFilter(); -bool isHex(const QByteArray& ba); -bool isBase64(const QByteArray& ba); -void sleep(int ms); -void wait(int ms); -void disableCoreDumps(); -void setupSearchPaths(); -bool createWindowsDACL(); - -template <typename RandomAccessIterator, typename T> -RandomAccessIterator binaryFind(RandomAccessIterator begin, RandomAccessIterator end, const T& value) +namespace Tools { - RandomAccessIterator it = std::lower_bound(begin, end, value); - if ((it == end) || (value < *it)) { - return end; + QString humanReadableFileSize(qint64 bytes); + bool hasChild(const QObject* parent, const QObject* child); + bool readFromDevice(QIODevice* device, QByteArray& data, int size = 16384); + bool readAllFromDevice(QIODevice* device, QByteArray& data); + QString imageReaderFilter(); + bool isHex(const QByteArray& ba); + bool isBase64(const QByteArray& ba); + void sleep(int ms); + void wait(int ms); + void disableCoreDumps(); + void setupSearchPaths(); + bool createWindowsDACL(); + + template <typename RandomAccessIterator, typename T> + RandomAccessIterator binaryFind(RandomAccessIterator begin, RandomAccessIterator end, const T& value) + { + RandomAccessIterator it = std::lower_bound(begin, end, value); + + if ((it == end) || (value < *it)) { + return end; + } else { + return it; + } } - else { - return it; - } -} } // namespace Tools diff --git a/src/core/Translator.cpp b/src/core/Translator.cpp index 34bc7c2e6..595dadfa1 100644 --- a/src/core/Translator.cpp +++ b/src/core/Translator.cpp @@ -22,8 +22,8 @@ #include <QDir> #include <QLibraryInfo> #include <QLocale> -#include <QTranslator> #include <QRegularExpression> +#include <QTranslator> #include "config-keepassx.h" #include "core/Config.h" @@ -47,8 +47,7 @@ void Translator::installTranslators() #ifdef QT_DEBUG QString("%1/share/translations").arg(KEEPASSX_BINARY_DIR), #endif - filePath()->dataPath("translations") - }; + filePath()->dataPath("translations")}; bool translationsLoaded = false; for (const QString& path : paths) { @@ -72,10 +71,9 @@ QList<QPair<QString, QString>> Translator::availableLanguages() #ifdef QT_DEBUG QString("%1/share/translations").arg(KEEPASSX_BINARY_DIR), #endif - filePath()->dataPath("translations") - }; + filePath()->dataPath("translations")}; - QList<QPair<QString, QString> > languages; + QList<QPair<QString, QString>> languages; languages.append(QPair<QString, QString>("system", "System default")); QRegularExpression regExp("^keepassx_([a-zA-Z_]+)\\.qm$", QRegularExpression::CaseInsensitiveOption); @@ -138,7 +136,8 @@ bool Translator::installQtTranslator(const QString& language, const QString& pat QScopedPointer<QTranslator> qtTranslator(new QTranslator(qApp)); if (qtTranslator->load(QString("qtbase_%1").arg(language), path)) { return QCoreApplication::installTranslator(qtTranslator.take()); - } else if (qtTranslator->load(QString("qtbase_%1").arg(language), QLibraryInfo::location(QLibraryInfo::TranslationsPath))) { + } else if (qtTranslator->load(QString("qtbase_%1").arg(language), + QLibraryInfo::location(QLibraryInfo::TranslationsPath))) { return QCoreApplication::installTranslator(qtTranslator.take()); } return false; diff --git a/src/core/Uuid.cpp b/src/core/Uuid.cpp index 1b531159f..a0a07aa6c 100644 --- a/src/core/Uuid.cpp +++ b/src/core/Uuid.cpp @@ -22,8 +22,8 @@ #include "crypto/Random.h" const int Uuid::Length = 16; -const QRegExp Uuid::HexRegExp = QRegExp(QString("^[0-9A-F]{%1}$").arg(QString::number(Uuid::Length * 2)), - Qt::CaseInsensitive); +const QRegExp Uuid::HexRegExp = + QRegExp(QString("^[0-9A-F]{%1}$").arg(QString::number(Uuid::Length * 2)), Qt::CaseInsensitive); Uuid::Uuid() : m_data(Length, 0) @@ -120,5 +120,5 @@ QDataStream& operator>>(QDataStream& stream, Uuid& uuid) bool Uuid::isUuid(const QString& uuid) { - return Uuid::HexRegExp.exactMatch(uuid); + return Uuid::HexRegExp.exactMatch(uuid); } diff --git a/src/core/Uuid.h b/src/core/Uuid.h index ecb20e0c3..169d99dca 100644 --- a/src/core/Uuid.h +++ b/src/core/Uuid.h @@ -19,8 +19,8 @@ #define KEEPASSX_UUID_H #include <QByteArray> -#include <QString> #include <QRegExp> +#include <QString> class Uuid { |