diff options
author | Gianluca Recchia <gianluca.recchia97@gmail.com> | 2018-11-01 06:27:38 +0300 |
---|---|---|
committer | Jonathan White <support@dmapps.us> | 2018-11-29 02:29:15 +0300 |
commit | fc930bae69be516cb2ad72e83dad1cf6d8631956 (patch) | |
tree | 3deee79bad7608204299f3f6cc6dce51865c49fd /src/core | |
parent | f9625189cb7ddf9d1353a6dab079830778623d48 (diff) |
Restore correct formatting
Many lines were not conformant with the project's formatting rules.
This patch should fix all formatting and whitespace issues in the code
base.
A clang-format directive was put around the connect() calls containing
SIGNALs and SLOTs whose signatures would be denormalized because of the
formatting rules.
Diffstat (limited to 'src/core')
-rw-r--r-- | src/core/AsyncTask.h | 2 | ||||
-rw-r--r-- | src/core/Bootstrap.cpp | 308 | ||||
-rw-r--r-- | src/core/Bootstrap.h | 16 | ||||
-rw-r--r-- | src/core/Config.cpp | 2 | ||||
-rw-r--r-- | src/core/Database.cpp | 5 | ||||
-rw-r--r-- | src/core/Entry.cpp | 9 | ||||
-rw-r--r-- | src/core/Entry.h | 3 | ||||
-rw-r--r-- | src/core/EntryAttributes.cpp | 4 | ||||
-rw-r--r-- | src/core/Group.cpp | 6 | ||||
-rw-r--r-- | src/core/InactivityTimer.cpp | 3 | ||||
-rw-r--r-- | src/core/Merger.cpp | 68 | ||||
-rw-r--r-- | src/core/Merger.h | 20 | ||||
-rw-r--r-- | src/core/Metadata.cpp | 2 | ||||
-rw-r--r-- | src/core/OSEventFilter.h | 1 | ||||
-rw-r--r-- | src/core/PasswordGenerator.cpp | 1 | ||||
-rw-r--r-- | src/core/Tools.cpp | 226 | ||||
-rw-r--r-- | src/core/Tools.h | 42 |
17 files changed, 378 insertions, 340 deletions
diff --git a/src/core/AsyncTask.h b/src/core/AsyncTask.h index 45bb191bc..f74d7c738 100644 --- a/src/core/AsyncTask.h +++ b/src/core/AsyncTask.h @@ -13,7 +13,7 @@ * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. -*/ + */ #ifndef KEEPASSXC_ASYNCTASK_HPP #define KEEPASSXC_ASYNCTASK_HPP diff --git a/src/core/Bootstrap.cpp b/src/core/Bootstrap.cpp index 0610def8b..a62cc5a9b 100644 --- a/src/core/Bootstrap.cpp +++ b/src/core/Bootstrap.cpp @@ -26,201 +26,201 @@ namespace Bootstrap { -/** - * When QNetworkAccessManager is instantiated it regularly starts polling - * all network interfaces to see if anything changes and if so, what. This - * creates a latency spike every 10 seconds on Mac OS 10.12+ and Windows 7 >= - * when on a wifi connection. - * So here we disable it for lack of better measure. - * This will also cause this message: QObject::startTimer: Timers cannot - * have negative intervals - * For more info see: - * - https://bugreports.qt.io/browse/QTBUG-40332 - * - https://bugreports.qt.io/browse/QTBUG-46015 - */ -static inline void applyEarlyQNetworkAccessManagerWorkaround() -{ - qputenv("QT_BEARER_POLL_TIMEOUT", QByteArray::number(-1)); -} + /** + * When QNetworkAccessManager is instantiated it regularly starts polling + * all network interfaces to see if anything changes and if so, what. This + * creates a latency spike every 10 seconds on Mac OS 10.12+ and Windows 7 >= + * when on a wifi connection. + * So here we disable it for lack of better measure. + * This will also cause this message: QObject::startTimer: Timers cannot + * have negative intervals + * For more info see: + * - https://bugreports.qt.io/browse/QTBUG-40332 + * - https://bugreports.qt.io/browse/QTBUG-46015 + */ + static inline void applyEarlyQNetworkAccessManagerWorkaround() + { + qputenv("QT_BEARER_POLL_TIMEOUT", QByteArray::number(-1)); + } -/** - * Perform early application bootstrapping such as setting up search paths, - * configuration OS security properties, and loading translators. - * A QApplication object has to be instantiated before calling this function. - */ -void bootstrapApplication() -{ + /** + * Perform early application bootstrapping such as setting up search paths, + * configuration OS security properties, and loading translators. + * A QApplication object has to be instantiated before calling this function. + */ + void bootstrapApplication() + { #ifdef QT_NO_DEBUG - disableCoreDumps(); + disableCoreDumps(); #endif - setupSearchPaths(); - applyEarlyQNetworkAccessManagerWorkaround(); - Translator::installTranslators(); + setupSearchPaths(); + applyEarlyQNetworkAccessManagerWorkaround(); + Translator::installTranslators(); #ifdef Q_OS_MACOS - // Don't show menu icons on OSX - QApplication::setAttribute(Qt::AA_DontShowIconsInMenus); + // Don't show menu icons on OSX + QApplication::setAttribute(Qt::AA_DontShowIconsInMenus); #endif -} - -/** - * Restore the main window's state after launch - * - * @param mainWindow the main window whose state to restore - */ -void restoreMainWindowState(MainWindow& mainWindow) -{ - // start minimized if configured - if (config()->get("GUI/MinimizeOnStartup").toBool()) { - mainWindow.showMinimized(); - } else { - mainWindow.bringToFront(); } - if (config()->get("OpenPreviousDatabasesOnStartup").toBool()) { - const QStringList fileNames = config()->get("LastOpenedDatabases").toStringList(); - for (const QString& filename : fileNames) { - if (!filename.isEmpty() && QFile::exists(filename)) { - mainWindow.openDatabase(filename); + /** + * Restore the main window's state after launch + * + * @param mainWindow the main window whose state to restore + */ + void restoreMainWindowState(MainWindow& mainWindow) + { + // start minimized if configured + if (config()->get("GUI/MinimizeOnStartup").toBool()) { + mainWindow.showMinimized(); + } else { + mainWindow.bringToFront(); + } + + if (config()->get("OpenPreviousDatabasesOnStartup").toBool()) { + const QStringList fileNames = config()->get("LastOpenedDatabases").toStringList(); + for (const QString& filename : fileNames) { + if (!filename.isEmpty() && QFile::exists(filename)) { + mainWindow.openDatabase(filename); + } } } } -} -// LCOV_EXCL_START -void disableCoreDumps() -{ - // default to true - // there is no point in printing a warning if this is not implemented on the platform - bool success = true; + // LCOV_EXCL_START + 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 #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."); + } } -} - -// -// 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); + // 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; - } + pTokenUser = static_cast<PTOKEN_USER>(HeapAlloc(GetProcessHeap(), 0, cbBufferSize)); + if (pTokenUser == nullptr) { + goto Cleanup; + } - if (!GetTokenInformation(hToken, TokenUser, pTokenUser, cbBufferSize, &cbBufferSize)) { - goto Cleanup; - } + if (!GetTokenInformation(hToken, TokenUser, pTokenUser, cbBufferSize, &cbBufferSize)) { + goto Cleanup; + } - if (!IsValidSid(pTokenUser->User.Sid)) { - goto Cleanup; - } + if (!IsValidSid(pTokenUser->User.Sid)) { + 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); + // Calculate the amount of memory that must be allocated for the DACL + cbACL = sizeof(ACL) + sizeof(ACCESS_ALLOWED_ACE) + GetLengthSid(pTokenUser->User.Sid); - // Create and initialize an ACL - pACL = static_cast<PACL>(HeapAlloc(GetProcessHeap(), 0, cbACL)); - if (pACL == nullptr) { - goto Cleanup; - } + // Create and initialize an ACL + pACL = static_cast<PACL>(HeapAlloc(GetProcessHeap(), 0, cbACL)); + if (pACL == nullptr) { + goto Cleanup; + } - if (!InitializeAcl(pACL, cbACL, ACL_REVISION)) { - goto Cleanup; - } + if (!InitializeAcl(pACL, cbACL, ACL_REVISION)) { + 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; - } + // 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; + } - // 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 - ); - -Cleanup: - - if (pACL != nullptr) { - HeapFree(GetProcessHeap(), 0, pACL); - } - if (pTokenUser != nullptr) { - HeapFree(GetProcessHeap(), 0, pTokenUser); - } - if (hToken != nullptr) { - CloseHandle(hToken); - } + // 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 + ); + + Cleanup: + + if (pACL != nullptr) { + HeapFree(GetProcessHeap(), 0, pACL); + } + if (pTokenUser != nullptr) { + HeapFree(GetProcessHeap(), 0, pTokenUser); + } + if (hToken != nullptr) { + CloseHandle(hToken); + } #endif - return bSuccess; -} -// LCOV_EXCL_STOP + return bSuccess; + } + // LCOV_EXCL_STOP -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 -} + } -} // namespace Bootstrap +} // namespace Bootstrap diff --git a/src/core/Bootstrap.h b/src/core/Bootstrap.h index 0e9db155a..95158fb8c 100644 --- a/src/core/Bootstrap.h +++ b/src/core/Bootstrap.h @@ -15,7 +15,6 @@ * along with this program. If not, see <http://www.gnu.org/licenses/>. */ - #ifndef KEEPASSXC_BOOTSTRAP_H #define KEEPASSXC_BOOTSTRAP_H @@ -23,12 +22,11 @@ namespace Bootstrap { -void bootstrapApplication(); -void restoreMainWindowState(MainWindow& mainWindow); -void disableCoreDumps(); -bool createWindowsDACL(); -void setupSearchPaths(); -}; - + void bootstrapApplication(); + void restoreMainWindowState(MainWindow& mainWindow); + void disableCoreDumps(); + bool createWindowsDACL(); + void setupSearchPaths(); +}; // namespace Bootstrap -#endif //KEEPASSXC_BOOTSTRAP_H +#endif // KEEPASSXC_BOOTSTRAP_H diff --git a/src/core/Config.cpp b/src/core/Config.cpp index 01497caf9..66591a851 100644 --- a/src/core/Config.cpp +++ b/src/core/Config.cpp @@ -84,7 +84,7 @@ void Config::upgrade() { for (const auto& setting : deprecationMap.keys()) { if (m_settings->contains(setting)) { - if(!deprecationMap.value(setting).isEmpty()) { + if (!deprecationMap.value(setting).isEmpty()) { // Add entry with new name and old entry's value m_settings->setValue(deprecationMap.value(setting), m_settings->value(setting)); } diff --git a/src/core/Database.cpp b/src/core/Database.cpp index 6d475acf9..ff345c84e 100644 --- a/src/core/Database.cpp +++ b/src/core/Database.cpp @@ -720,14 +720,15 @@ QSharedPointer<Database> Database::unlockFromStdin(const QString& databaseFilena QString errorMessage; // LCOV_EXCL_START if (!fileKey->load(keyFilename, &errorMessage)) { - err << QObject::tr("Failed to load key file %1: %2").arg(keyFilename, errorMessage)<< endl; + err << QObject::tr("Failed to load key file %1: %2").arg(keyFilename, errorMessage) << endl; return {}; } if (fileKey->type() != FileKey::Hashed) { err << QObject::tr("WARNING: You are using a legacy key file format which may become\n" "unsupported in the future.\n\n" - "Please consider generating a new key file.") << endl; + "Please consider generating a new key file.") + << endl; } // LCOV_EXCL_STOP diff --git a/src/core/Entry.cpp b/src/core/Entry.cpp index 793a373bb..55f56f583 100644 --- a/src/core/Entry.cpp +++ b/src/core/Entry.cpp @@ -657,12 +657,14 @@ Entry* Entry::clone(CloneFlags flags) const if (flags & CloneUserAsRef) { // Build the username reference QString username = "{REF:U@I:" + uuidToHex() + "}"; - 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:" + uuidToHex() + "}"; - 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); @@ -1065,7 +1067,8 @@ QString Entry::resolveUrl(const QString& url) const // Validate the URL QUrl tempUrl = QUrl(newUrl); - if (tempUrl.isValid() && (tempUrl.scheme() == "http" || tempUrl.scheme() == "https" || tempUrl.scheme() == "file")) { + if (tempUrl.isValid() + && (tempUrl.scheme() == "http" || tempUrl.scheme() == "https" || tempUrl.scheme() == "file")) { return tempUrl.url(); } diff --git a/src/core/Entry.h b/src/core/Entry.h index f6518bdd3..655cc3621 100644 --- a/src/core/Entry.h +++ b/src/core/Entry.h @@ -36,7 +36,8 @@ class Database; class Group; -namespace Totp { +namespace Totp +{ struct Settings; } diff --git a/src/core/EntryAttributes.cpp b/src/core/EntryAttributes.cpp index b9fcd9ac2..fc0793ce8 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"; diff --git a/src/core/Group.cpp b/src/core/Group.cpp index 2051fe437..ec7633b88 100644 --- a/src/core/Group.cpp +++ b/src/core/Group.cpp @@ -630,10 +630,12 @@ Entry* Group::findEntryByPathRecursive(const QString& entryPath, const QString& // Return the first entry that matches the full path OR if there is no leading // slash, return the first entry title that matches for (Entry* entry : entries()) { + // clang-format off if (entryPath == (basePath + entry->title()) || (!entryPath.startsWith("/") && entry->title() == entryPath)) { return entry; } + // clang-format on } for (Group* group : children()) { @@ -654,9 +656,11 @@ Group* Group::findGroupByPath(const QString& groupPath) if (groupPath.isEmpty()) { normalizedGroupPath = QString("/"); // root group } else { + // clang-format off normalizedGroupPath = (groupPath.startsWith("/") ? "" : "/") + groupPath + (groupPath.endsWith("/") ? "" : "/"); + // clang-format on } return findGroupByPathRecursive(normalizedGroupPath, "/"); } @@ -894,6 +898,7 @@ void Group::connectDatabaseSignalsRecursive(Database* db) } if (db) { + // clang-format off connect(this, SIGNAL(groupDataChanged(Group*)), db, SIGNAL(groupDataChanged(Group*))); connect(this, SIGNAL(groupAboutToRemove(Group*)), db, SIGNAL(groupAboutToRemove(Group*))); connect(this, SIGNAL(groupRemoved()), db, SIGNAL(groupRemoved())); @@ -902,6 +907,7 @@ void Group::connectDatabaseSignalsRecursive(Database* db) connect(this, SIGNAL(aboutToMove(Group*,Group*,int)), db, SIGNAL(groupAboutToMove(Group*,Group*,int))); connect(this, SIGNAL(groupMoved()), db, SIGNAL(groupMoved())); connect(this, SIGNAL(groupModified()), db, SLOT(markAsModified())); + // clang-format on } m_db = db; diff --git a/src/core/InactivityTimer.cpp b/src/core/InactivityTimer.cpp index 405970cc6..85c58d269 100644 --- a/src/core/InactivityTimer.cpp +++ b/src/core/InactivityTimer.cpp @@ -55,12 +55,13 @@ void InactivityTimer::deactivate() bool InactivityTimer::eventFilter(QObject* watched, QEvent* event) { const QEvent::Type type = event->type(); - + // clang-format off if ((type >= QEvent::MouseButtonPress && type <= QEvent::KeyRelease) || (type >= QEvent::HoverEnter && type <= QEvent::HoverMove) || (type == QEvent::Wheel)) { m_timer->start(); } + // clang-format on return QObject::eventFilter(watched, event); } diff --git a/src/core/Merger.cpp b/src/core/Merger.cpp index 0da7458ea..cc57ae3b2 100644 --- a/src/core/Merger.cpp +++ b/src/core/Merger.cpp @@ -93,7 +93,8 @@ Merger::ChangeList Merger::mergeGroup(const MergeContext& context) moveEntry(targetEntry, context.m_targetGroup); } else { // Entry is already present in the database. Update it. - const bool locationChanged = targetEntry->timeInfo().locationChanged() < sourceEntry->timeInfo().locationChanged(); + const bool locationChanged = + targetEntry->timeInfo().locationChanged() < sourceEntry->timeInfo().locationChanged(); if (locationChanged && targetEntry->group() != context.m_targetGroup) { changes << tr("Relocating %1 [%2]").arg(sourceEntry->title(), sourceEntry->uuidToHex()); moveEntry(targetEntry, context.m_targetGroup); @@ -136,7 +137,8 @@ Merger::ChangeList Merger::mergeGroup(const MergeContext& context) return changes; } -Merger::ChangeList Merger::resolveGroupConflict(const MergeContext& context, const Group* sourceChildGroup, Group* targetChildGroup) +Merger::ChangeList +Merger::resolveGroupConflict(const MergeContext& context, const Group* sourceChildGroup, Group* targetChildGroup) { Q_UNUSED(context); ChangeList changes; @@ -261,10 +263,13 @@ void Merger::eraseGroup(Group* group) database->setDeletedObjects(deletions); } -Merger::ChangeList Merger::resolveEntryConflict_Duplicate(const MergeContext& context, const Entry* sourceEntry, Entry* targetEntry) +Merger::ChangeList +Merger::resolveEntryConflict_Duplicate(const MergeContext& context, const Entry* sourceEntry, Entry* targetEntry) { ChangeList changes; - const int comparison = compare(targetEntry->timeInfo().lastModificationTime(), sourceEntry->timeInfo().lastModificationTime(), CompareItemIgnoreMilliseconds); + const int comparison = compare(targetEntry->timeInfo().lastModificationTime(), + sourceEntry->timeInfo().lastModificationTime(), + CompareItemIgnoreMilliseconds); // if one entry is newer, create a clone and add it to the group if (comparison < 0) { Entry* clonedEntry = sourceEntry->clone(Entry::CloneNewUuid | Entry::CloneIncludeHistory); @@ -280,11 +285,14 @@ Merger::ChangeList Merger::resolveEntryConflict_Duplicate(const MergeContext& co return changes; } -Merger::ChangeList Merger::resolveEntryConflict_KeepLocal(const MergeContext& context, const Entry* sourceEntry, Entry* targetEntry) +Merger::ChangeList +Merger::resolveEntryConflict_KeepLocal(const MergeContext& context, const Entry* sourceEntry, Entry* targetEntry) { Q_UNUSED(context); ChangeList changes; - const int comparison = compare(targetEntry->timeInfo().lastModificationTime(), sourceEntry->timeInfo().lastModificationTime(), CompareItemIgnoreMilliseconds); + const int comparison = compare(targetEntry->timeInfo().lastModificationTime(), + sourceEntry->timeInfo().lastModificationTime(), + CompareItemIgnoreMilliseconds); if (comparison < 0) { // we need to make our older entry "newer" than the new entry - therefore // we just create a new history entry without any changes - this preserves @@ -293,18 +301,21 @@ Merger::ChangeList Merger::resolveEntryConflict_KeepLocal(const MergeContext& co // this type of merge changes the database timestamp since reapplying the // old entry is an active change of the database! changes << tr("Reapplying older target entry on top of newer source %1 [%2]") - .arg(targetEntry->title(), targetEntry->uuidToHex()); + .arg(targetEntry->title(), targetEntry->uuidToHex()); Entry* agedTargetEntry = targetEntry->clone(Entry::CloneNoFlags); targetEntry->addHistoryItem(agedTargetEntry); } return changes; } -Merger::ChangeList Merger::resolveEntryConflict_KeepRemote(const MergeContext& context, const Entry* sourceEntry, Entry* targetEntry) +Merger::ChangeList +Merger::resolveEntryConflict_KeepRemote(const MergeContext& context, const Entry* sourceEntry, Entry* targetEntry) { Q_UNUSED(context); ChangeList changes; - const int comparison = compare(targetEntry->timeInfo().lastModificationTime(), sourceEntry->timeInfo().lastModificationTime(), CompareItemIgnoreMilliseconds); + const int comparison = compare(targetEntry->timeInfo().lastModificationTime(), + sourceEntry->timeInfo().lastModificationTime(), + CompareItemIgnoreMilliseconds); if (comparison > 0) { // we need to make our older entry "newer" than the new entry - therefore // we just create a new history entry without any changes - this preserves @@ -313,7 +324,7 @@ Merger::ChangeList Merger::resolveEntryConflict_KeepRemote(const MergeContext& c // this type of merge changes the database timestamp since reapplying the // old entry is an active change of the database! changes << tr("Reapplying older source entry on top of newer target %1 [%2]") - .arg(targetEntry->title(), targetEntry->uuidToHex()); + .arg(targetEntry->title(), targetEntry->uuidToHex()); targetEntry->beginUpdate(); targetEntry->copyDataFrom(sourceEntry); targetEntry->endUpdate(); @@ -322,13 +333,17 @@ Merger::ChangeList Merger::resolveEntryConflict_KeepRemote(const MergeContext& c return changes; } - -Merger::ChangeList Merger::resolveEntryConflict_MergeHistories(const MergeContext& context, const Entry* sourceEntry, Entry* targetEntry, Group::MergeMode mergeMethod) +Merger::ChangeList Merger::resolveEntryConflict_MergeHistories(const MergeContext& context, + const Entry* sourceEntry, + Entry* targetEntry, + Group::MergeMode mergeMethod) { Q_UNUSED(context); ChangeList changes; - const int comparison = compare(targetEntry->timeInfo().lastModificationTime(), sourceEntry->timeInfo().lastModificationTime(), CompareItemIgnoreMilliseconds); + const int comparison = compare(targetEntry->timeInfo().lastModificationTime(), + sourceEntry->timeInfo().lastModificationTime(), + CompareItemIgnoreMilliseconds); if (comparison < 0) { Group* currentGroup = targetEntry->group(); Entry* clonedEntry = sourceEntry->clone(Entry::CloneIncludeHistory); @@ -347,14 +362,15 @@ Merger::ChangeList Merger::resolveEntryConflict_MergeHistories(const MergeContex qPrintable(targetEntry->group()->name())); const bool changed = mergeHistory(sourceEntry, targetEntry, mergeMethod); if (changed) { - changes << tr("Synchronizing from older source %1 [%2]").arg(targetEntry->title(), targetEntry->uuidToHex()); + changes + << tr("Synchronizing from older source %1 [%2]").arg(targetEntry->title(), targetEntry->uuidToHex()); } } return changes; } - -Merger::ChangeList Merger::resolveEntryConflict(const MergeContext& context, const Entry* sourceEntry, Entry* targetEntry) +Merger::ChangeList +Merger::resolveEntryConflict(const MergeContext& context, const Entry* sourceEntry, Entry* targetEntry) { ChangeList changes; // We need to cut off the milliseconds since the persistent format only supports times down to seconds @@ -395,15 +411,19 @@ bool Merger::mergeHistory(const Entry* sourceEntry, Entry* targetEntry, Group::M Q_UNUSED(mergeMethod); const auto targetHistoryItems = targetEntry->historyItems(); const auto sourceHistoryItems = sourceEntry->historyItems(); - const int comparison = compare(sourceEntry->timeInfo().lastModificationTime(), targetEntry->timeInfo().lastModificationTime(), CompareItemIgnoreMilliseconds); + const int comparison = compare(sourceEntry->timeInfo().lastModificationTime(), + targetEntry->timeInfo().lastModificationTime(), + CompareItemIgnoreMilliseconds); const bool preferLocal = mergeMethod == Group::KeepLocal || comparison < 0; const bool preferRemote = mergeMethod == Group::KeepRemote || comparison > 0; QMap<QDateTime, Entry*> merged; for (Entry* historyItem : targetHistoryItems) { const QDateTime modificationTime = Clock::serialized(historyItem->timeInfo().lastModificationTime()); - if (merged.contains(modificationTime) && !merged[modificationTime]->equals(historyItem, CompareItemIgnoreMilliseconds)) { - ::qWarning("Inconsistent history entry of %s[%s] at %s contains conflicting changes - conflict resolution may lose data!", + if (merged.contains(modificationTime) + && !merged[modificationTime]->equals(historyItem, CompareItemIgnoreMilliseconds)) { + ::qWarning("Inconsistent history entry of %s[%s] at %s contains conflicting changes - conflict resolution " + "may lose data!", qPrintable(sourceEntry->title()), qPrintable(sourceEntry->uuidToHex()), qPrintable(modificationTime.toString("yyyy-MM-dd HH-mm-ss-zzz"))); @@ -413,8 +433,10 @@ bool Merger::mergeHistory(const Entry* sourceEntry, Entry* targetEntry, Group::M for (Entry* historyItem : sourceHistoryItems) { // Items with same modification-time changes will be regarded as same (like KeePass2) const QDateTime modificationTime = Clock::serialized(historyItem->timeInfo().lastModificationTime()); - if (merged.contains(modificationTime) && !merged[modificationTime]->equals(historyItem, CompareItemIgnoreMilliseconds)) { - ::qWarning("History entry of %s[%s] at %s contains conflicting changes - conflict resolution may lose data!", + if (merged.contains(modificationTime) + && !merged[modificationTime]->equals(historyItem, CompareItemIgnoreMilliseconds)) { + ::qWarning( + "History entry of %s[%s] at %s contains conflicting changes - conflict resolution may lose data!", qPrintable(sourceEntry->title()), qPrintable(sourceEntry->uuidToHex()), qPrintable(modificationTime.toString("yyyy-MM-dd HH-mm-ss-zzz"))); @@ -430,7 +452,9 @@ bool Merger::mergeHistory(const Entry* sourceEntry, Entry* targetEntry, Group::M const QDateTime targetModificationTime = Clock::serialized(targetEntry->timeInfo().lastModificationTime()); const QDateTime sourceModificationTime = Clock::serialized(sourceEntry->timeInfo().lastModificationTime()); - if (targetModificationTime == sourceModificationTime && !targetEntry->equals(sourceEntry, CompareItemIgnoreMilliseconds | CompareItemIgnoreHistory | CompareItemIgnoreLocation)) { + if (targetModificationTime == sourceModificationTime + && !targetEntry->equals(sourceEntry, + CompareItemIgnoreMilliseconds | CompareItemIgnoreHistory | CompareItemIgnoreLocation)) { ::qWarning("Entry of %s[%s] contains conflicting changes - conflict resolution may lose data!", qPrintable(sourceEntry->title()), qPrintable(sourceEntry->uuidToHex())); diff --git a/src/core/Merger.h b/src/core/Merger.h index 1f16fe026..03a47a27f 100644 --- a/src/core/Merger.h +++ b/src/core/Merger.h @@ -55,14 +55,22 @@ private: bool mergeHistory(const Entry* sourceEntry, Entry* targetEntry, Group::MergeMode mergeMethod); void moveEntry(Entry* entry, Group* targetGroup); void moveGroup(Group* group, Group* targetGroup); - void eraseEntry(Entry* entry); // remove an entry without a trace in the deletedObjects - needed for elemination cloned entries - void eraseGroup(Group* group); // remove an entry without a trace in the deletedObjects - needed for elemination cloned entries + // remove an entry without a trace in the deletedObjects - needed for elemination cloned entries + void eraseEntry(Entry* entry); + // remove an entry without a trace in the deletedObjects - needed for elemination cloned entries + void eraseGroup(Group* group); ChangeList resolveEntryConflict(const MergeContext& context, const Entry* existingEntry, Entry* otherEntry); ChangeList resolveGroupConflict(const MergeContext& context, const Group* existingGroup, Group* otherGroup); - Merger::ChangeList resolveEntryConflict_Duplicate(const MergeContext& context, const Entry* sourceEntry, Entry* targetEntry); - Merger::ChangeList resolveEntryConflict_KeepLocal(const MergeContext& context, const Entry* sourceEntry, Entry* targetEntry); - Merger::ChangeList resolveEntryConflict_KeepRemote(const MergeContext& context, const Entry* sourceEntry, Entry* targetEntry); - Merger::ChangeList resolveEntryConflict_MergeHistories(const MergeContext& context, const Entry* sourceEntry, Entry* targetEntry, Group::MergeMode mergeMethod); + Merger::ChangeList + resolveEntryConflict_Duplicate(const MergeContext& context, const Entry* sourceEntry, Entry* targetEntry); + Merger::ChangeList + resolveEntryConflict_KeepLocal(const MergeContext& context, const Entry* sourceEntry, Entry* targetEntry); + Merger::ChangeList + resolveEntryConflict_KeepRemote(const MergeContext& context, const Entry* sourceEntry, Entry* targetEntry); + Merger::ChangeList resolveEntryConflict_MergeHistories(const MergeContext& context, + const Entry* sourceEntry, + Entry* targetEntry, + Group::MergeMode mergeMethod); private: MergeContext m_context; diff --git a/src/core/Metadata.cpp b/src/core/Metadata.cpp index 40bf52775..45010a4ff 100644 --- a/src/core/Metadata.cpp +++ b/src/core/Metadata.cpp @@ -429,7 +429,7 @@ void Metadata::removeCustomIcon(const QUuid& uuid) emit metadataModified(); } -QUuid Metadata::findCustomIcon(const QImage &candidate) +QUuid Metadata::findCustomIcon(const QImage& candidate) { QByteArray hash = hashImage(candidate); return m_customIconsHashes.value(hash, QUuid()); diff --git a/src/core/OSEventFilter.h b/src/core/OSEventFilter.h index 1dca5392e..a27ade713 100644 --- a/src/core/OSEventFilter.h +++ b/src/core/OSEventFilter.h @@ -9,6 +9,7 @@ class OSEventFilter : public QAbstractNativeEventFilter public: OSEventFilter(); bool nativeEventFilter(const QByteArray& eventType, void* message, long* result) override; + private: Q_DISABLE_COPY(OSEventFilter) }; diff --git a/src/core/PasswordGenerator.cpp b/src/core/PasswordGenerator.cpp index 69a0dfb3e..1132582d6 100644 --- a/src/core/PasswordGenerator.cpp +++ b/src/core/PasswordGenerator.cpp @@ -124,7 +124,6 @@ bool PasswordGenerator::isValid() const } return !passwordGroups().isEmpty(); - } QVector<PasswordGroup> PasswordGenerator::passwordGroups() const diff --git a/src/core/Tools.cpp b/src/core/Tools.cpp index 362cfa937..673e6a604 100644 --- a/src/core/Tools.cpp +++ b/src/core/Tools.cpp @@ -22,14 +22,12 @@ #include "core/Translator.h" #include <QCoreApplication> +#include <QElapsedTimer> #include <QIODevice> #include <QImageReader> #include <QLocale> -#include <QStringList> #include <QRegularExpression> - -#include <QElapsedTimer> - +#include <QStringList> #include <cctype> #ifdef Q_OS_WIN @@ -59,147 +57,145 @@ namespace Tools { -QString humanReadableFileSize(qint64 bytes, quint32 precision) -{ - constexpr auto kibibyte = 1024; - double size = bytes; - - QStringList units = QStringList() << "B" - << "KiB" - << "MiB" - << "GiB"; - int i = 0; - int maxI = units.size() - 1; - - while ((size >= kibibyte) && (i < maxI)) { - size /= kibibyte; - i++; - } - - return QString("%1 %2").arg(QLocale().toString(size, 'f', precision), units.at(i)); -} + QString humanReadableFileSize(qint64 bytes, quint32 precision) + { + constexpr auto kibibyte = 1024; + double size = bytes; + + QStringList units = QStringList() << "B" + << "KiB" + << "MiB" + << "GiB"; + int i = 0; + int maxI = units.size() - 1; + + while ((size >= kibibyte) && (i < maxI)) { + size /= kibibyte; + i++; + } -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 QString("%1 %2").arg(QLocale().toString(size, 'f', precision), units.at(i)); } -} -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; + 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; } } - while (readResult > 0); - if (readResult == -1) { - return false; - } else { - result.resize(static_cast<int>(readBytes)); - data = result; - 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); + + 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 (char codePoint : format) { - if (!QChar(codePoint).isLetterOrNumber()) { - continue; + for (const QByteArray& format : formats) { + for (char codePoint : format) { + if (!QChar(codePoint).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 (const unsigned char c : ba) { - if (!std::isxdigit(c)) { - return false; + bool isHex(const QByteArray& ba) + { + for (const unsigned char c : ba) { + if (!std::isxdigit(c)) { + return false; + } } + + return true; } - return true; -} + bool isBase64(const QByteArray& ba) + { + constexpr auto pattern = R"(^(?:[a-z0-9+]{4})*(?:[a-z0-9+]{3}=|[a-z0-9+]{2}==)?$)"; + QRegExp regexp(pattern, Qt::CaseInsensitive, QRegExp::RegExp2); -bool isBase64(const QByteArray& ba) -{ - constexpr auto pattern = R"(^(?:[a-z0-9+]{4})*(?:[a-z0-9+]{3}=|[a-z0-9+]{2}==)?$)"; - QRegExp regexp(pattern, 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); - } + 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)); } - while (!timer.hasExpired(ms)); } -} // Escape common regex symbols except for *, ?, and | auto regexEscape = QRegularExpression(R"re(([-[\]{}()+.,\\\/^$#]))re"); diff --git a/src/core/Tools.h b/src/core/Tools.h index 37214f069..984bab491 100644 --- a/src/core/Tools.h +++ b/src/core/Tools.h @@ -31,28 +31,28 @@ class QRegularExpression; namespace Tools { -QString humanReadableFileSize(qint64 bytes, quint32 precision = 2); -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); -QRegularExpression convertToRegex(const QString& string, bool useWildcards = false, bool exactMatch = false, - bool caseSensitive = false); - -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; + QString humanReadableFileSize(qint64 bytes, quint32 precision = 2); + 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); + QRegularExpression convertToRegex(const QString& string, bool useWildcards = false, + bool exactMatch = false, bool caseSensitive = false); + + 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; + } } -} } // namespace Tools |