From 8324d03f0a015e62b6182843b4478226a5197090 Mon Sep 17 00:00:00 2001 From: Louis-Bertrand Varin Date: Sat, 31 Mar 2018 16:01:30 -0400 Subject: [PATCH] Formatting the code. --- src/autotype/AutoType.cpp | 69 +-- src/autotype/AutoType.h | 5 +- src/autotype/AutoTypeAction.cpp | 4 - src/autotype/AutoTypeAction.h | 10 +- src/autotype/AutoTypePlatformPlugin.h | 8 +- src/autotype/AutoTypeSelectDialog.cpp | 4 +- src/autotype/AutoTypeSelectView.cpp | 3 +- src/autotype/ShortcutWidget.cpp | 9 +- src/autotype/WildcardMatcher.cpp | 6 +- src/autotype/test/AutoTypeTest.h | 6 +- src/autotype/test/AutoTypeTestInterface.h | 4 +- src/autotype/windows/AutoTypeWindows.cpp | 11 +- src/autotype/windows/AutoTypeWindows.h | 3 +- src/autotype/xcb/AutoTypeXCB.cpp | 114 ++--- src/autotype/xcb/AutoTypeXCB.h | 10 +- src/browser/BrowserAccessControlDialog.cpp | 11 +- src/browser/BrowserAccessControlDialog.h | 5 +- src/browser/BrowserAction.cpp | 82 ++-- src/browser/BrowserAction.h | 73 +-- src/browser/BrowserClients.cpp | 12 +- src/browser/BrowserClients.h | 35 +- src/browser/BrowserEntryConfig.cpp | 7 +- src/browser/BrowserEntryConfig.h | 10 +- src/browser/BrowserOptionDialog.cpp | 21 +- src/browser/BrowserOptionDialog.h | 7 +- src/browser/BrowserService.cpp | 143 +++--- src/browser/BrowserService.h | 99 +++-- src/browser/BrowserSettings.cpp | 36 +- src/browser/BrowserSettings.h | 12 +- src/browser/HostInstaller.cpp | 143 +++--- src/browser/HostInstaller.h | 30 +- src/browser/NativeMessagingBase.cpp | 9 +- src/browser/NativeMessagingBase.h | 36 +- src/browser/NativeMessagingHost.cpp | 24 +- src/browser/NativeMessagingHost.h | 42 +- src/browser/Variant.h | 3 +- src/cli/Diceware.cpp | 15 +- src/cli/Edit.cpp | 5 +- src/cli/Extract.cpp | 4 +- src/cli/Generate.cpp | 32 +- src/cli/Show.cpp | 14 +- src/core/AsyncTask.h | 60 +-- src/core/AutoTypeAssociations.cpp | 3 +- src/core/AutoTypeMatch.cpp | 14 +- src/core/Config.cpp | 14 +- src/core/Config.h | 5 +- src/core/CsvParser.cpp | 179 +++++--- src/core/CsvParser.h | 80 ++-- src/core/CustomData.cpp | 2 +- src/core/CustomData.h | 3 +- src/core/Database.cpp | 7 +- src/core/Database.h | 5 +- src/core/DatabaseIcons.cpp | 3 +- src/core/DatabaseIcons.h | 3 +- src/core/Endian.h | 82 ++-- src/core/Entry.cpp | 87 ++-- src/core/Entry.h | 23 +- src/core/EntryAttachments.cpp | 14 +- src/core/EntryAttributes.cpp | 23 +- src/core/EntrySearcher.cpp | 23 +- src/core/EntrySearcher.h | 1 - src/core/Exporter.h | 4 +- src/core/FilePath.cpp | 42 +- src/core/FilePath.h | 3 +- src/core/Global.h | 26 +- src/core/Group.cpp | 66 ++- src/core/Group.h | 28 +- src/core/InactivityTimer.cpp | 6 +- src/core/ListDeleter.h | 11 +- src/core/MacPasteboard.cpp | 27 +- src/core/MacPasteboard.h | 15 +- src/core/Metadata.cpp | 19 +- src/core/Metadata.h | 2 +- src/core/PassphraseGenerator.cpp | 12 +- src/core/PasswordGenerator.cpp | 11 +- src/core/PasswordGenerator.h | 14 +- src/core/ScreenLockListener.cpp | 10 +- src/core/ScreenLockListener.h | 3 +- src/core/ScreenLockListenerDBus.cpp | 82 ++-- src/core/ScreenLockListenerDBus.h | 4 +- src/core/ScreenLockListenerPrivate.cpp | 2 +- src/core/ScreenLockListenerWin.cpp | 11 +- src/core/ScreenLockListenerWin.h | 6 +- src/core/SignalMultiplexer.cpp | 6 +- src/core/TimeDelta.cpp | 7 +- src/core/Tools.cpp | 464 ++++++++++---------- src/core/Tools.h | 48 +- src/core/Translator.cpp | 13 +- src/core/Uuid.cpp | 6 +- src/core/Uuid.h | 2 +- src/crypto/Crypto.cpp | 30 +- src/crypto/Random.cpp | 1 - src/crypto/Random.h | 7 +- src/crypto/SymmetricCipher.h | 2 +- src/crypto/SymmetricCipherBackend.h | 4 +- src/crypto/SymmetricCipherGcrypt.cpp | 9 +- src/crypto/SymmetricCipherGcrypt.h | 5 +- src/crypto/argon2/argon2.h | 2 +- src/crypto/kdf/AesKdf.cpp | 7 +- src/crypto/kdf/AesKdf.h | 8 +- src/crypto/kdf/Argon2Kdf.cpp | 35 +- src/crypto/kdf/Argon2Kdf.h | 3 +- src/crypto/kdf/Kdf.h | 1 - src/crypto/kdf/Kdf_p.h | 4 +- src/format/Kdbx3Reader.cpp | 18 +- src/format/Kdbx3Reader.h | 10 +- src/format/Kdbx3Writer.cpp | 33 +- src/format/Kdbx3Writer.h | 4 +- src/format/Kdbx4Reader.cpp | 26 +- src/format/Kdbx4Reader.h | 8 +- src/format/Kdbx4Writer.cpp | 43 +- src/format/Kdbx4Writer.h | 2 +- src/format/KdbxReader.cpp | 4 +- src/format/KdbxReader.h | 9 +- src/format/KdbxWriter.h | 10 +- src/format/KdbxXmlReader.cpp | 28 +- src/format/KdbxXmlReader.h | 10 +- src/format/KdbxXmlWriter.cpp | 64 ++- src/format/KdbxXmlWriter.h | 4 +- src/format/KeePass1Reader.cpp | 131 ++---- src/format/KeePass1Reader.h | 12 +- src/format/KeePass2.cpp | 13 +- src/format/KeePass2.h | 216 ++++----- src/format/KeePass2RandomStream.cpp | 6 +- src/format/KeePass2RandomStream.h | 2 +- src/format/KeePass2Reader.cpp | 2 +- src/format/KeePass2Reader.h | 15 +- src/format/KeePass2Repair.cpp | 10 +- src/format/KeePass2Writer.cpp | 13 +- src/format/KeePass2Writer.h | 2 +- src/gui/AboutDialog.cpp | 23 +- src/gui/AboutDialog.h | 3 +- src/gui/Application.cpp | 62 +-- src/gui/Application.h | 2 +- src/gui/CategoryListWidget.cpp | 44 +- src/gui/CategoryListWidget.h | 14 +- src/gui/ChangeMasterKeyWidget.cpp | 43 +- src/gui/ChangeMasterKeyWidget.h | 3 +- src/gui/Clipboard.cpp | 3 +- src/gui/Clipboard.h | 3 +- src/gui/CloneDialog.cpp | 2 +- src/gui/CloneDialog.h | 9 +- src/gui/DatabaseOpenWidget.cpp | 32 +- src/gui/DatabaseOpenWidget.h | 3 +- src/gui/DatabaseRepairWidget.cpp | 16 +- src/gui/DatabaseSettingsWidget.cpp | 45 +- src/gui/DatabaseSettingsWidget.h | 18 +- src/gui/DatabaseTabWidget.cpp | 129 +++--- src/gui/DatabaseTabWidget.h | 5 +- src/gui/DatabaseWidget.cpp | 228 +++++----- src/gui/DatabaseWidget.h | 13 +- src/gui/DatabaseWidgetStateSync.cpp | 21 +- src/gui/DetailsWidget.cpp | 27 +- src/gui/DetailsWidget.h | 3 +- src/gui/DialogyWidget.cpp | 34 +- src/gui/DragTabBar.cpp | 9 +- src/gui/EditWidget.cpp | 8 +- src/gui/EditWidget.h | 5 +- src/gui/EditWidgetIcons.cpp | 79 ++-- src/gui/EditWidgetIcons.h | 5 +- src/gui/EditWidgetProperties.cpp | 28 +- src/gui/EditWidgetProperties.h | 5 +- src/gui/FileDialog.cpp | 58 +-- src/gui/FileDialog.h | 36 +- src/gui/Font.h | 5 +- src/gui/IconModels.cpp | 9 +- src/gui/KeePass1OpenWidget.cpp | 13 +- src/gui/LineEdit.cpp | 11 +- src/gui/MainWindow.cpp | 386 ++++++++-------- src/gui/MainWindow.h | 27 +- src/gui/MessageBox.cpp | 24 +- src/gui/MessageBox.h | 12 +- src/gui/MessageWidget.cpp | 4 +- src/gui/PasswordEdit.cpp | 10 +- src/gui/PasswordGeneratorWidget.cpp | 25 +- src/gui/PasswordGeneratorWidget.h | 9 +- src/gui/SearchWidget.cpp | 1 - src/gui/SearchWidget.h | 3 +- src/gui/SettingsWidget.cpp | 91 ++-- src/gui/SettingsWidget.h | 18 +- src/gui/SetupTotpDialog.cpp | 11 +- src/gui/SetupTotpDialog.h | 9 +- src/gui/TotpDialog.cpp | 2 - src/gui/TotpDialog.h | 9 +- src/gui/UnlockDatabaseDialog.cpp | 2 +- src/gui/UnlockDatabaseDialog.h | 2 +- src/gui/UnlockDatabaseWidget.cpp | 2 +- src/gui/WelcomeWidget.cpp | 18 +- src/gui/WelcomeWidget.h | 5 +- src/gui/csvImport/CsvImportWidget.cpp | 161 ++++--- src/gui/csvImport/CsvImportWidget.h | 14 +- src/gui/csvImport/CsvImportWizard.cpp | 6 +- src/gui/csvImport/CsvImportWizard.h | 10 +- src/gui/csvImport/CsvParserModel.cpp | 67 +-- src/gui/csvImport/CsvParserModel.h | 15 +- src/gui/entry/AutoTypeAssociationsModel.cpp | 17 +- src/gui/entry/AutoTypeMatchModel.cpp | 3 +- src/gui/entry/AutoTypeMatchView.cpp | 3 +- src/gui/entry/EditEntryWidget.cpp | 155 ++++--- src/gui/entry/EditEntryWidget.h | 8 +- src/gui/entry/EditEntryWidget_p.h | 3 +- src/gui/entry/EntryAttachmentsModel.cpp | 8 +- src/gui/entry/EntryAttachmentsModel.h | 3 +- src/gui/entry/EntryAttachmentsWidget.cpp | 35 +- src/gui/entry/EntryAttachmentsWidget.h | 5 +- src/gui/entry/EntryAttributesModel.cpp | 35 +- src/gui/entry/EntryHistoryModel.cpp | 6 +- src/gui/entry/EntryModel.cpp | 10 +- src/gui/entry/EntryView.cpp | 9 +- src/gui/entry/EntryView.h | 4 +- src/gui/group/EditGroupWidget.cpp | 36 +- src/gui/group/EditGroupWidget.h | 3 +- src/gui/group/GroupModel.cpp | 63 +-- src/gui/group/GroupModel.h | 4 +- src/gui/group/GroupView.cpp | 12 +- src/gui/widgets/ElidedLabel.cpp | 7 +- src/gui/widgets/ElidedLabel.h | 4 +- src/keys/ChallengeResponseKey.h | 4 +- src/keys/CompositeKey.cpp | 2 +- src/keys/CompositeKey.h | 6 +- src/keys/FileKey.cpp | 3 +- src/keys/FileKey.h | 5 +- src/keys/Key.h | 4 +- src/keys/YkChallengeResponseKey.cpp | 20 +- src/keys/YkChallengeResponseKey.h | 1 - src/keys/drivers/YubiKey.cpp | 13 +- src/keys/drivers/YubiKey.h | 10 +- src/keys/drivers/YubiKeyStub.cpp | 4 +- src/main.cpp | 35 +- src/proxy/NativeMessagingHost.cpp | 17 +- src/proxy/NativeMessagingHost.h | 2 +- src/proxy/keepassxc-proxy.cpp | 14 +- src/sshagent/ASN1Key.cpp | 16 +- src/sshagent/AgentSettingsPage.cpp | 1 - src/sshagent/AgentSettingsPage.h | 2 +- src/sshagent/AgentSettingsWidget.cpp | 2 +- src/sshagent/AgentSettingsWidget.h | 5 +- src/sshagent/BinaryStream.cpp | 33 +- src/sshagent/BinaryStream.h | 4 +- src/sshagent/KeeAgentSettings.cpp | 4 +- src/sshagent/KeeAgentSettings.h | 4 +- src/sshagent/OpenSSHKey.cpp | 8 +- src/sshagent/OpenSSHKey.h | 2 +- src/sshagent/SSHAgent.cpp | 15 +- src/sshagent/SSHAgent.h | 22 +- src/sshagent/includes.h | 3 +- src/streams/HashedBlockStream.cpp | 17 +- src/streams/HmacBlockStream.h | 4 +- src/streams/LayeredStream.cpp | 10 +- src/streams/SymmetricCipherStream.cpp | 28 +- src/streams/SymmetricCipherStream.h | 6 +- src/totp/totp.cpp | 26 +- src/totp/totp.h | 4 +- tests/FailDevice.cpp | 6 +- tests/TestAutoType.cpp | 37 +- tests/TestCryptoHash.cpp | 9 +- tests/TestCsvExporter.cpp | 12 +- tests/TestCsvParser.cpp | 52 ++- tests/TestCsvParser.h | 5 +- tests/TestDatabase.cpp | 10 +- tests/TestDeletedObjects.cpp | 22 +- tests/TestEntry.cpp | 123 +++--- tests/TestEntryModel.cpp | 38 +- tests/TestEntrySearcher.cpp | 3 +- tests/TestEntrySearcher.h | 1 - tests/TestGlobal.h | 64 ++- tests/TestGroup.cpp | 7 +- tests/TestGroup.h | 2 +- tests/TestGroupModel.cpp | 16 +- tests/TestKdbx2.cpp | 6 +- tests/TestKdbx2.h | 2 +- tests/TestKdbx3.cpp | 25 +- tests/TestKdbx3.h | 17 +- tests/TestKdbx4.cpp | 63 +-- tests/TestKdbx4.h | 16 +- tests/TestKeePass1Reader.cpp | 3 +- tests/TestKeePass2Format.cpp | 23 +- tests/TestKeePass2Format.h | 18 +- tests/TestKeePass2RandomStream.cpp | 4 - tests/TestKeys.cpp | 5 +- tests/TestMerge.cpp | 1 - tests/TestModified.cpp | 4 +- tests/TestOpenSSHKey.cpp | 202 ++++----- tests/TestRandom.cpp | 2 - tests/TestSymmetricCipher.cpp | 177 +++----- tests/TestTotp.cpp | 76 ++-- tests/TestWildcardMatcher.cpp | 3 +- tests/TestYkChallengeResponseKey.cpp | 4 +- tests/TestYkChallengeResponseKey.h | 2 +- tests/gui/TemporaryFile.cpp | 4 +- tests/gui/TemporaryFile.h | 6 +- tests/gui/TestGui.cpp | 94 ++-- tests/gui/TestGui.h | 12 +- tests/mock/MockChallengeResponseKey.h | 2 +- 294 files changed, 3796 insertions(+), 3740 deletions(-) mode change 100755 => 100644 src/browser/BrowserAccessControlDialog.cpp mode change 100755 => 100644 src/browser/BrowserAccessControlDialog.h mode change 100755 => 100644 src/browser/BrowserAction.cpp mode change 100755 => 100644 src/browser/BrowserAction.h mode change 100755 => 100644 src/browser/BrowserClients.cpp mode change 100755 => 100644 src/browser/BrowserClients.h mode change 100755 => 100644 src/browser/BrowserOptionDialog.cpp mode change 100755 => 100644 src/browser/BrowserOptionDialog.h mode change 100755 => 100644 src/browser/BrowserSettings.cpp mode change 100755 => 100644 src/browser/BrowserSettings.h mode change 100755 => 100644 src/browser/NativeMessagingHost.cpp mode change 100755 => 100644 src/browser/NativeMessagingHost.h mode change 100755 => 100644 src/proxy/NativeMessagingHost.cpp mode change 100755 => 100644 src/proxy/NativeMessagingHost.h diff --git a/src/autotype/AutoType.cpp b/src/autotype/AutoType.cpp index 3f44a9944..e215f726e 100644 --- a/src/autotype/AutoType.cpp +++ b/src/autotype/AutoType.cpp @@ -20,7 +20,7 @@ #include #include -#include +#include #include "config-keepassx.h" @@ -304,8 +304,8 @@ void AutoType::performGlobalAutoType(const QList& dbList) auto* msgBox = new QMessageBox(); msgBox->setAttribute(Qt::WA_DeleteOnClose); msgBox->setWindowTitle(tr("Auto-Type - KeePassXC")); - msgBox->setText(tr("Couldn't find an entry that matches the window title:").append("\n\n") - .append(windowTitle)); + msgBox->setText( + tr("Couldn't find an entry that matches the window title:").append("\n\n").append(windowTitle)); msgBox->setIcon(QMessageBox::Information); msgBox->setStandardButtons(QMessageBox::Ok); msgBox->show(); @@ -323,8 +323,7 @@ void AutoType::performGlobalAutoType(const QList& dbList) auto* selectDialog = new AutoTypeSelectDialog(); // connect slots, both of which must unlock the m_inGlobalAutoTypeDialog mutex - connect(selectDialog, SIGNAL(matchActivated(AutoTypeMatch)), - SLOT(performAutoTypeFromGlobal(AutoTypeMatch))); + connect(selectDialog, SIGNAL(matchActivated(AutoTypeMatch)), SLOT(performAutoTypeFromGlobal(AutoTypeMatch))); connect(selectDialog, SIGNAL(rejected()), SLOT(autoTypeRejectedFromGlobal())); selectDialog->setMatchList(matchList); @@ -449,11 +448,11 @@ QList AutoType::createActionFromTemplate(const QString& tmpl, c list.append(new AutoTypeKey(Qt::Key_Left)); } else if (tmplName.compare("right", Qt::CaseInsensitive) == 0) { list.append(new AutoTypeKey(Qt::Key_Right)); - } else if (tmplName.compare("insert", Qt::CaseInsensitive) == 0 || - tmplName.compare("ins", Qt::CaseInsensitive) == 0) { + } else if (tmplName.compare("insert", Qt::CaseInsensitive) == 0 + || tmplName.compare("ins", Qt::CaseInsensitive) == 0) { list.append(new AutoTypeKey(Qt::Key_Insert)); - } else if (tmplName.compare("delete", Qt::CaseInsensitive) == 0 || - tmplName.compare("del", Qt::CaseInsensitive) == 0) { + } else if (tmplName.compare("delete", Qt::CaseInsensitive) == 0 + || tmplName.compare("del", Qt::CaseInsensitive) == 0) { list.append(new AutoTypeKey(Qt::Key_Delete)); } else if (tmplName.compare("home", Qt::CaseInsensitive) == 0) { list.append(new AutoTypeKey(Qt::Key_Home)); @@ -463,8 +462,9 @@ QList AutoType::createActionFromTemplate(const QString& tmpl, c list.append(new AutoTypeKey(Qt::Key_PageUp)); } else if (tmplName.compare("pgdown", Qt::CaseInsensitive) == 0) { list.append(new AutoTypeKey(Qt::Key_PageDown)); - } else if (tmplName.compare("backspace", Qt::CaseInsensitive) == 0 || - tmplName.compare("bs", Qt::CaseInsensitive) == 0 || tmplName.compare("bksp", Qt::CaseInsensitive) == 0) { + } else if (tmplName.compare("backspace", Qt::CaseInsensitive) == 0 + || tmplName.compare("bs", Qt::CaseInsensitive) == 0 + || tmplName.compare("bksp", Qt::CaseInsensitive) == 0) { list.append(new AutoTypeKey(Qt::Key_Backspace)); } else if (tmplName.compare("break", Qt::CaseInsensitive) == 0) { list.append(new AutoTypeKey(Qt::Key_Pause)); @@ -591,13 +591,13 @@ QList AutoType::autoTypeSequences(const Entry* entry, const QString& wi } } - if (config()->get("AutoTypeEntryTitleMatch").toBool() && - windowMatchesTitle(windowTitle, entry->resolvePlaceholder(entry->title()))) { + if (config()->get("AutoTypeEntryTitleMatch").toBool() + && windowMatchesTitle(windowTitle, entry->resolvePlaceholder(entry->title()))) { sequenceList.append(entry->effectiveAutoTypeSequence()); } - if (config()->get("AutoTypeEntryURLMatch").toBool() && - windowMatchesUrl(windowTitle, entry->resolvePlaceholder(entry->url()))) { + if (config()->get("AutoTypeEntryURLMatch").toBool() + && windowMatchesUrl(windowTitle, entry->resolvePlaceholder(entry->url()))) { sequenceList.append(entry->effectiveAutoTypeSequence()); } @@ -605,7 +605,7 @@ QList AutoType::autoTypeSequences(const Entry* entry, const QString& wi return sequenceList; } } else { - sequenceList.append(entry->effectiveAutoTypeSequence()); + sequenceList.append(entry->effectiveAutoTypeSequence()); } return sequenceList; @@ -659,7 +659,7 @@ bool AutoType::checkSyntax(const QString& string) QString allowRepetition = "(?:\\s\\d+)?"; // the ":" allows custom commands with syntax S:Field // exclude BEEP otherwise will be checked as valid - QString normalCommands = "(?!BEEP\\s)[A-Z:]*" + allowRepetition; + QString normalCommands = "(?!BEEP\\s)[A-Z:]*" + allowRepetition; QString specialLiterals = "[\\^\\%\\(\\)~\\{\\}\\[\\]\\+]" + allowRepetition; QString functionKeys = "(?:F[1-9]" + allowRepetition + "|F1[0-2])" + allowRepetition; QString numpad = "NUMPAD\\d" + allowRepetition; @@ -673,9 +673,21 @@ bool AutoType::checkSyntax(const QString& string) // a normal string not in parentheses QString fixedStrings = "[^\\^\\%~\\+@\\{\\}]*"; - QRegularExpression autoTypeSyntax("^(?:" + shortcutKeys + "|" + fixedStrings + "|\\{(?:" + normalCommands + "|" + specialLiterals + - "|" + functionKeys + "|" + numpad + "|" + delay + "|" + beep + "|" + vkey + ")\\}|\\{" + customAttributes + "\\})*$", - QRegularExpression::CaseInsensitiveOption); + QRegularExpression autoTypeSyntax( + "^(?:" + shortcutKeys + "|" + fixedStrings + "|\\{(?:" + normalCommands + "|" + specialLiterals + "|" + + functionKeys + + "|" + + numpad + + "|" + + delay + + "|" + + beep + + "|" + + vkey + + ")\\}|\\{" + + customAttributes + + "\\})*$", + QRegularExpression::CaseInsensitiveOption); QRegularExpressionMatch match = autoTypeSyntax.match(string); return match.hasMatch(); } @@ -686,7 +698,7 @@ bool AutoType::checkSyntax(const QString& string) bool AutoType::checkHighDelay(const QString& string) { // 5 digit numbers(10 seconds) are too much - QRegularExpression highDelay("\\{DELAY\\s\\d{5,}\\}", QRegularExpression::CaseInsensitiveOption); + QRegularExpression highDelay("\\{DELAY\\s\\d{5,}\\}", QRegularExpression::CaseInsensitiveOption); QRegularExpressionMatch match = highDelay.match(string); return match.hasMatch(); } @@ -697,7 +709,7 @@ bool AutoType::checkHighDelay(const QString& string) bool AutoType::checkSlowKeypress(const QString& string) { // 3 digit numbers(100 milliseconds) are too much - QRegularExpression slowKeypress("\\{DELAY=\\d{3,}\\}", QRegularExpression::CaseInsensitiveOption); + QRegularExpression slowKeypress("\\{DELAY=\\d{3,}\\}", QRegularExpression::CaseInsensitiveOption); QRegularExpressionMatch match = slowKeypress.match(string); return match.hasMatch(); } @@ -724,7 +736,9 @@ bool AutoType::verifyAutoTypeSyntax(const QString& sequence) return false; } else if (AutoType::checkHighDelay(sequence)) { QMessageBox::StandardButton reply; - reply = QMessageBox::question(nullptr, tr("Auto-Type"), + reply = QMessageBox::question( + nullptr, + tr("Auto-Type"), tr("This Auto-Type command contains a very long delay. Do you really want to proceed?")); if (reply == QMessageBox::No) { @@ -732,7 +746,9 @@ bool AutoType::verifyAutoTypeSyntax(const QString& sequence) } } else if (AutoType::checkSlowKeypress(sequence)) { QMessageBox::StandardButton reply; - reply = QMessageBox::question(nullptr, tr("Auto-Type"), + reply = QMessageBox::question( + nullptr, + tr("Auto-Type"), tr("This Auto-Type command contains very slow key presses. Do you really want to proceed?")); if (reply == QMessageBox::No) { @@ -740,8 +756,9 @@ bool AutoType::verifyAutoTypeSyntax(const QString& sequence) } } else if (AutoType::checkHighRepetition(sequence)) { QMessageBox::StandardButton reply; - reply = QMessageBox::question(nullptr, tr("Auto-Type"), - tr("This Auto-Type command contains arguments which are repeated very often. Do you really want to proceed?")); + reply = + QMessageBox::question(nullptr, tr("Auto-Type"), tr("This Auto-Type command contains arguments which are " + "repeated very often. Do you really want to proceed?")); if (reply == QMessageBox::No) { return false; diff --git a/src/autotype/AutoType.h b/src/autotype/AutoType.h index ad60bd76c..28b36bd82 100644 --- a/src/autotype/AutoType.h +++ b/src/autotype/AutoType.h @@ -19,10 +19,10 @@ #ifndef KEEPASSX_AUTOTYPE_H #define KEEPASSX_AUTOTYPE_H +#include #include #include #include -#include #include "core/AutoTypeMatch.h" @@ -47,8 +47,7 @@ public: static bool checkSlowKeypress(const QString& string); static bool checkHighDelay(const QString& string); static bool verifyAutoTypeSyntax(const QString& sequence); - void performAutoType(const Entry* entry, - QWidget* hideWindow = nullptr); + void performAutoType(const Entry* entry, QWidget* hideWindow = nullptr); inline bool isAvailable() { diff --git a/src/autotype/AutoTypeAction.cpp b/src/autotype/AutoTypeAction.cpp index 64dae7962..0beb19b39 100644 --- a/src/autotype/AutoTypeAction.cpp +++ b/src/autotype/AutoTypeAction.cpp @@ -34,7 +34,6 @@ void AutoTypeChar::accept(AutoTypeExecutor* executor) executor->execChar(this); } - AutoTypeKey::AutoTypeKey(Qt::Key key) : key(key) { @@ -50,7 +49,6 @@ void AutoTypeKey::accept(AutoTypeExecutor* executor) executor->execKey(this); } - AutoTypeDelay::AutoTypeDelay(int delayMs) : delayMs(delayMs) { @@ -66,7 +64,6 @@ void AutoTypeDelay::accept(AutoTypeExecutor* executor) executor->execDelay(this); } - AutoTypeClearField::AutoTypeClearField() { } @@ -81,7 +78,6 @@ void AutoTypeClearField::accept(AutoTypeExecutor* executor) executor->execClearField(this); } - void AutoTypeExecutor::execDelay(AutoTypeDelay* action) { Tools::wait(action->delayMs); diff --git a/src/autotype/AutoTypeAction.h b/src/autotype/AutoTypeAction.h index 7f0d829c0..263566dd8 100644 --- a/src/autotype/AutoTypeAction.h +++ b/src/autotype/AutoTypeAction.h @@ -19,8 +19,8 @@ #define KEEPASSX_AUTOTYPEACTION_H #include -#include #include +#include #include "core/Global.h" @@ -29,7 +29,9 @@ class AutoTypeExecutor; class KEEPASSX_EXPORT AutoTypeAction { public: - virtual ~AutoTypeAction() {} + virtual ~AutoTypeAction() + { + } virtual AutoTypeAction* clone() = 0; virtual void accept(AutoTypeExecutor* executor) = 0; }; @@ -75,7 +77,9 @@ public: class KEEPASSX_EXPORT AutoTypeExecutor { public: - virtual ~AutoTypeExecutor() {} + virtual ~AutoTypeExecutor() + { + } virtual void execChar(AutoTypeChar* action) = 0; virtual void execKey(AutoTypeKey* action) = 0; virtual void execDelay(AutoTypeDelay* action); diff --git a/src/autotype/AutoTypePlatformPlugin.h b/src/autotype/AutoTypePlatformPlugin.h index 2945e98c5..898b04e60 100644 --- a/src/autotype/AutoTypePlatformPlugin.h +++ b/src/autotype/AutoTypePlatformPlugin.h @@ -25,7 +25,9 @@ class AutoTypePlatformInterface { public: - virtual ~AutoTypePlatformInterface() {} + virtual ~AutoTypePlatformInterface() + { + } virtual bool isAvailable() = 0; virtual QStringList windowTitles() = 0; virtual WId activeWindow() = 0; @@ -35,7 +37,9 @@ public: virtual int platformEventFilter(void* event) = 0; virtual int initialTimeout() = 0; virtual bool raiseWindow(WId window) = 0; - virtual void unload() {} + virtual void unload() + { + } virtual AutoTypeExecutor* createExecutor() = 0; diff --git a/src/autotype/AutoTypeSelectDialog.cpp b/src/autotype/AutoTypeSelectDialog.cpp index eae9e6ffb..a4fd98dec 100644 --- a/src/autotype/AutoTypeSelectDialog.cpp +++ b/src/autotype/AutoTypeSelectDialog.cpp @@ -61,7 +61,7 @@ AutoTypeSelectDialog::AutoTypeSelectDialog(QWidget* parent) connect(m_view, SIGNAL(activated(QModelIndex)), SLOT(emitMatchActivated(QModelIndex))); connect(m_view, SIGNAL(clicked(QModelIndex)), SLOT(emitMatchActivated(QModelIndex))); - connect(m_view->model(), SIGNAL(rowsRemoved(QModelIndex,int,int)), SLOT(matchRemoved())); + connect(m_view->model(), SIGNAL(rowsRemoved(QModelIndex, int, int)), SLOT(matchRemoved())); connect(m_view, SIGNAL(rejected()), SLOT(reject())); layout->addWidget(m_view); @@ -109,7 +109,7 @@ void AutoTypeSelectDialog::matchRemoved() if (m_rejected) { return; } - + if (m_view->model()->rowCount() == 0) { reject(); } diff --git a/src/autotype/AutoTypeSelectView.cpp b/src/autotype/AutoTypeSelectView.cpp index e4dba0515..cfa113671 100644 --- a/src/autotype/AutoTypeSelectView.cpp +++ b/src/autotype/AutoTypeSelectView.cpp @@ -36,8 +36,7 @@ void AutoTypeSelectView::mouseMoveEvent(QMouseEvent* event) if (index.isValid()) { setCurrentIndex(index); setCursor(Qt::PointingHandCursor); - } - else { + } else { unsetCursor(); } diff --git a/src/autotype/ShortcutWidget.cpp b/src/autotype/ShortcutWidget.cpp index 56a374011..95174e430 100644 --- a/src/autotype/ShortcutWidget.cpp +++ b/src/autotype/ShortcutWidget.cpp @@ -50,8 +50,7 @@ void ShortcutWidget::setShortcut(Qt::Key key, Qt::KeyboardModifiers modifiers) if (autoType()->registerGlobalShortcut(m_key, m_modifiers)) { setStyleSheet(""); - } - else { + } else { setStyleSheet("background-color: #FF9696;"); } } @@ -112,14 +111,12 @@ void ShortcutWidget::keyEvent(QKeyEvent* event) if (!release && !keyIsModifier) { if (modifiers != 0) { setShortcut(key, modifiers); - } - else { + } else { resetShortcut(); setStyleSheet(""); displayShortcut(key, modifiers); } - } - else { + } else { if (m_locked) { resetShortcut(); setStyleSheet(""); diff --git a/src/autotype/WildcardMatcher.cpp b/src/autotype/WildcardMatcher.cpp index ad83f9b0a..bac785897 100644 --- a/src/autotype/WildcardMatcher.cpp +++ b/src/autotype/WildcardMatcher.cpp @@ -33,8 +33,7 @@ bool WildcardMatcher::match(const QString& pattern) if (patternContainsWildcard()) { return matchWithWildcards(); - } - else { + } else { return patternEqualsText(); } } @@ -63,8 +62,7 @@ bool WildcardMatcher::matchWithWildcards() bool WildcardMatcher::startOrEndDoesNotMatch(const QStringList& parts) { - return !m_text.startsWith(parts.first(), Sensitivity) || - !m_text.endsWith(parts.last(), Sensitivity); + return !m_text.startsWith(parts.first(), Sensitivity) || !m_text.endsWith(parts.last(), Sensitivity); } bool WildcardMatcher::partsMatch(const QStringList& parts) diff --git a/src/autotype/test/AutoTypeTest.h b/src/autotype/test/AutoTypeTest.h index d9a86c3de..849a3b242 100644 --- a/src/autotype/test/AutoTypeTest.h +++ b/src/autotype/test/AutoTypeTest.h @@ -20,13 +20,11 @@ #include -#include "autotype/AutoTypePlatformPlugin.h" #include "autotype/AutoTypeAction.h" +#include "autotype/AutoTypePlatformPlugin.h" #include "autotype/test/AutoTypeTestInterface.h" -class AutoTypePlatformTest : public QObject, - public AutoTypePlatformInterface, - public AutoTypeTestInterface +class AutoTypePlatformTest : public QObject, public AutoTypePlatformInterface, public AutoTypeTestInterface { Q_OBJECT Q_PLUGIN_METADATA(IID "org.keepassx.AutoTypePlatformInterface") diff --git a/src/autotype/test/AutoTypeTestInterface.h b/src/autotype/test/AutoTypeTestInterface.h index 7ee6f21a8..7681f2ecb 100644 --- a/src/autotype/test/AutoTypeTestInterface.h +++ b/src/autotype/test/AutoTypeTestInterface.h @@ -23,7 +23,9 @@ class AutoTypeTestInterface { public: - virtual ~AutoTypeTestInterface() {} + virtual ~AutoTypeTestInterface() + { + } virtual void setActiveWindowTitle(const QString& title) = 0; virtual QString actionChars() = 0; diff --git a/src/autotype/windows/AutoTypeWindows.cpp b/src/autotype/windows/AutoTypeWindows.cpp index c3c2c30a5..634f6893a 100644 --- a/src/autotype/windows/AutoTypeWindows.cpp +++ b/src/autotype/windows/AutoTypeWindows.cpp @@ -94,7 +94,7 @@ void AutoTypePlatformWin::unregisterGlobalShortcut(Qt::Key key, Qt::KeyboardModi // int AutoTypePlatformWin::platformEventFilter(void* event) { - MSG *msg = static_cast(event); + MSG* msg = static_cast(event); if (msg->message == WM_HOTKEY && msg->wParam == HOTKEY_ID) { emit globalShortcutTriggered(); @@ -480,17 +480,14 @@ BOOL AutoTypePlatformWin::isAltTabWindow(HWND hwnd) // // Window title enum proc // -BOOL CALLBACK AutoTypePlatformWin::windowTitleEnumProc( - _In_ HWND hwnd, - _In_ LPARAM lParam -) +BOOL CALLBACK AutoTypePlatformWin::windowTitleEnumProc(_In_ HWND hwnd, _In_ LPARAM lParam) { if (!isAltTabWindow(hwnd)) { // Skip window return TRUE; } - QStringList *list = reinterpret_cast(lParam); + QStringList* list = reinterpret_cast(lParam); QString title = windowTitle(hwnd); if (!title.isEmpty()) { @@ -508,7 +505,7 @@ QString AutoTypePlatformWin::windowTitle(HWND hwnd) wchar_t title[MAX_WINDOW_TITLE_LENGTH]; int count = ::GetWindowTextW(hwnd, title, MAX_WINDOW_TITLE_LENGTH); - return QString::fromUtf16(reinterpret_cast(title), count); + return QString::fromUtf16(reinterpret_cast(title), count); } // diff --git a/src/autotype/windows/AutoTypeWindows.h b/src/autotype/windows/AutoTypeWindows.h index 88b9a9fd2..33d61ef28 100644 --- a/src/autotype/windows/AutoTypeWindows.h +++ b/src/autotype/windows/AutoTypeWindows.h @@ -22,8 +22,8 @@ #include #include -#include "autotype/AutoTypePlatformPlugin.h" #include "autotype/AutoTypeAction.h" +#include "autotype/AutoTypePlatformPlugin.h" class AutoTypePlatformWin : public QObject, public AutoTypePlatformInterface { @@ -72,4 +72,3 @@ private: }; #endif // KEEPASSX_AUTOTYPEWINDOWS_H - diff --git a/src/autotype/xcb/AutoTypeXCB.cpp b/src/autotype/xcb/AutoTypeXCB.cpp index 1946c8883..e6f4496cb 100644 --- a/src/autotype/xcb/AutoTypeXCB.cpp +++ b/src/autotype/xcb/AutoTypeXCB.cpp @@ -40,11 +40,14 @@ AutoTypePlatformX11::AutoTypePlatformX11() m_atomUtf8String = XInternAtom(m_dpy, "UTF8_STRING", True); m_atomNetActiveWindow = XInternAtom(m_dpy, "_NET_ACTIVE_WINDOW", True); - m_classBlacklist << "desktop_window" << "gnome-panel"; // Gnome - m_classBlacklist << "kdesktop" << "kicker"; // KDE 3 + m_classBlacklist << "desktop_window" + << "gnome-panel"; // Gnome + m_classBlacklist << "kdesktop" + << "kicker"; // KDE 3 m_classBlacklist << "Plasma"; // KDE 4 m_classBlacklist << "plasmashell"; // KDE 5 - m_classBlacklist << "xfdesktop" << "xfce4-panel"; // Xfce 4 + m_classBlacklist << "xfdesktop" + << "xfce4-panel"; // Xfce 4 m_currentGlobalKey = static_cast(0); m_currentGlobalModifiers = 0; @@ -146,12 +149,9 @@ bool AutoTypePlatformX11::registerGlobalShortcut(Qt::Key key, Qt::KeyboardModifi startCatchXErrors(); XGrabKey(m_dpy, keycode, nativeModifiers, m_rootWindow, True, GrabModeAsync, GrabModeAsync); - XGrabKey(m_dpy, keycode, nativeModifiers | Mod2Mask, m_rootWindow, True, GrabModeAsync, - GrabModeAsync); - XGrabKey(m_dpy, keycode, nativeModifiers | LockMask, m_rootWindow, True, GrabModeAsync, - GrabModeAsync); - XGrabKey(m_dpy, keycode, nativeModifiers | Mod2Mask | LockMask, m_rootWindow, True, - GrabModeAsync, GrabModeAsync); + XGrabKey(m_dpy, keycode, nativeModifiers | Mod2Mask, m_rootWindow, True, GrabModeAsync, GrabModeAsync); + XGrabKey(m_dpy, keycode, nativeModifiers | LockMask, m_rootWindow, True, GrabModeAsync, GrabModeAsync); + XGrabKey(m_dpy, keycode, nativeModifiers | Mod2Mask | LockMask, m_rootWindow, True, GrabModeAsync, GrabModeAsync); stopCatchXErrors(); if (!m_xErrorOccurred) { @@ -160,8 +160,7 @@ bool AutoTypePlatformX11::registerGlobalShortcut(Qt::Key key, Qt::KeyboardModifi m_currentGlobalKeycode = keycode; m_currentGlobalNativeModifiers = nativeModifiers; return true; - } - else { + } else { unregisterGlobalShortcut(key, modifiers); return false; } @@ -211,29 +210,26 @@ int AutoTypePlatformX11::platformEventFilter(void* event) if (type == XCB_KEY_PRESS || type == XCB_KEY_RELEASE) { xcb_key_press_event_t* keyPressEvent = static_cast(event); if (keyPressEvent->detail == m_currentGlobalKeycode - && (keyPressEvent->state & m_modifierMask) == m_currentGlobalNativeModifiers - && (!QApplication::activeWindow() || QApplication::activeWindow()->isMinimized()) - && m_loaded) { + && (keyPressEvent->state & m_modifierMask) == m_currentGlobalNativeModifiers + && (!QApplication::activeWindow() || QApplication::activeWindow()->isMinimized()) + && m_loaded) { if (type == XCB_KEY_PRESS) { emit globalShortcutTriggered(); } return 1; } - } - else if (type == XCB_MAPPING_NOTIFY) { + } else if (type == XCB_MAPPING_NOTIFY) { xcb_mapping_notify_event_t* mappingNotifyEvent = static_cast(event); if (mappingNotifyEvent->request == XCB_MAPPING_KEYBOARD - || mappingNotifyEvent->request == XCB_MAPPING_MODIFIER) - { + || mappingNotifyEvent->request == XCB_MAPPING_MODIFIER) { XMappingEvent xMappingEvent; memset(&xMappingEvent, 0, sizeof(xMappingEvent)); xMappingEvent.type = MappingNotify; xMappingEvent.display = m_dpy; if (mappingNotifyEvent->request == XCB_MAPPING_KEYBOARD) { xMappingEvent.request = MappingKeyboard; - } - else { + } else { xMappingEvent.request = MappingModifier; } xMappingEvent.first_keycode = mappingNotifyEvent->first_keycode; @@ -263,13 +259,12 @@ QString AutoTypePlatformX11::windowTitle(Window window, bool useBlacklist) // the window manager spec says we should read _NET_WM_NAME first, then fall back to WM_NAME - int retVal = XGetWindowProperty(m_dpy, window, m_atomNetWmName, 0, 1000, False, m_atomUtf8String, - &type, &format, &nitems, &after, &data); + int retVal = XGetWindowProperty( + m_dpy, window, m_atomNetWmName, 0, 1000, False, m_atomUtf8String, &type, &format, &nitems, &after, &data); if ((retVal == 0) && data) { title = QString::fromUtf8(reinterpret_cast(data)); - } - else { + } else { XTextProperty textProp; retVal = XGetTextProperty(m_dpy, window, &textProp, m_atomWmName); if ((retVal != 0) && textProp.value) { @@ -278,12 +273,10 @@ QString AutoTypePlatformX11::windowTitle(Window window, bool useBlacklist) if (textProp.encoding == m_atomUtf8String) { title = QString::fromUtf8(reinterpret_cast(textProp.value)); - } - else if ((XmbTextPropertyToTextList(m_dpy, &textProp, &textList, &count) == 0) - && textList && (count > 0)) { + } else if ((XmbTextPropertyToTextList(m_dpy, &textProp, &textList, &count) == 0) && textList + && (count > 0)) { title = QString::fromLocal8Bit(textList[0]); - } - else if (textProp.encoding == m_atomString) { + } else if (textProp.encoding == m_atomString) { title = QString::fromLocal8Bit(reinterpret_cast(textProp.value)); } @@ -386,8 +379,8 @@ bool AutoTypePlatformX11::isTopLevelWindow(Window window) unsigned long nitems; unsigned long after; unsigned char* data = Q_NULLPTR; - int retVal = XGetWindowProperty(m_dpy, window, m_atomWmState, 0, 2, False, m_atomWmState, &type, &format, - &nitems, &after, &data); + int retVal = XGetWindowProperty( + m_dpy, window, m_atomWmState, 0, 2, False, m_atomWmState, &type, &format, &nitems, &after, &data); bool result = false; @@ -408,15 +401,12 @@ KeySym AutoTypePlatformX11::charToKeySym(const QChar& ch) ushort unicode = ch.unicode(); /* first check for Latin-1 characters (1:1 mapping) */ - if ((unicode >= 0x0020 && unicode <= 0x007e) - || (unicode >= 0x00a0 && unicode <= 0x00ff)) { + if ((unicode >= 0x0020 && unicode <= 0x007e) || (unicode >= 0x00a0 && unicode <= 0x00ff)) { return unicode; } /* mapping table generated from keysymdef.h */ - const uint* match = Tools::binaryFind(m_unicodeToKeysymKeys, - m_unicodeToKeysymKeys + m_unicodeToKeysymLen, - unicode); + const uint* match = Tools::binaryFind(m_unicodeToKeysymKeys, m_unicodeToKeysymKeys + m_unicodeToKeysymLen, unicode); int index = match - m_unicodeToKeysymKeys; if (index != m_unicodeToKeysymLen) { return m_unicodeToKeysymValues[index]; @@ -483,8 +473,7 @@ KeySym AutoTypePlatformX11::keyToKeySym(Qt::Key key) default: if (key >= Qt::Key_F1 && key <= Qt::Key_F16) { return XK_F1 + (key - Qt::Key_F1); - } - else { + } else { return NoSymbol; } } @@ -493,13 +482,13 @@ KeySym AutoTypePlatformX11::keyToKeySym(Qt::Key key) /* * Update the keyboard and modifier mapping. * We need the KeyboardMapping for AddKeysym. - * Modifier mapping is required for clearing the modifiers. + * Modifier mapping is required for clearing the modifiers. */ void AutoTypePlatformX11::updateKeymap() { int keycode, inx; int mod_index, mod_key; - XModifierKeymap *modifiers; + XModifierKeymap* modifiers; if (m_xkb) { XkbFreeKeyboard(m_xkb, XkbAllComponentsMask, True); @@ -507,10 +496,9 @@ void AutoTypePlatformX11::updateKeymap() m_xkb = getKeyboard(); XDisplayKeycodes(m_dpy, &m_minKeycode, &m_maxKeycode); - if (m_keysymTable != NULL) XFree(m_keysymTable); - m_keysymTable = XGetKeyboardMapping(m_dpy, - m_minKeycode, m_maxKeycode - m_minKeycode + 1, - &m_keysymPerKeycode); + if (m_keysymTable != NULL) + XFree(m_keysymTable); + m_keysymTable = XGetKeyboardMapping(m_dpy, m_minKeycode, m_maxKeycode - m_minKeycode + 1, &m_keysymPerKeycode); /* determine the keycode to use for remapped keys */ inx = (m_remapKeycode - m_minKeycode) * m_keysymPerKeycode; @@ -518,16 +506,16 @@ void AutoTypePlatformX11::updateKeymap() for (keycode = m_minKeycode; keycode <= m_maxKeycode; keycode++) { inx = (keycode - m_minKeycode) * m_keysymPerKeycode; if (m_keysymTable[inx] == NoSymbol) { - m_remapKeycode = keycode; - m_currentRemapKeysym = NoSymbol; - break; + m_remapKeycode = keycode; + m_currentRemapKeysym = NoSymbol; + break; } } } /* determine the keycode to use for modifiers */ modifiers = XGetModifierMapping(m_dpy); - for (mod_index = ShiftMapIndex; mod_index <= Mod5MapIndex; mod_index ++) { + for (mod_index = ShiftMapIndex; mod_index <= Mod5MapIndex; mod_index++) { m_modifier_keycode[mod_index] = 0; for (mod_key = 0; mod_key < modifiers->max_keypermod; mod_key++) { keycode = modifiers->modifiermap[mod_index * modifiers->max_keypermod + mod_key]; @@ -625,7 +613,7 @@ int AutoTypePlatformX11::AddKeysym(KeySym keysym) return 0; } - int inx = (m_remapKeycode- m_minKeycode) * m_keysymPerKeycode; + int inx = (m_remapKeycode - m_minKeycode) * m_keysymPerKeycode; m_keysymTable[inx] = keysym; m_currentRemapKeysym = keysym; @@ -644,7 +632,7 @@ int AutoTypePlatformX11::AddKeysym(KeySym keysym) void AutoTypePlatformX11::SendKeyEvent(unsigned keycode, bool press) { XSync(m_dpy, False); - int (*oldHandler) (Display*, XErrorEvent*) = XSetErrorHandler(MyErrorHandler); + int (*oldHandler)(Display*, XErrorEvent*) = XSetErrorHandler(MyErrorHandler); XTestFakeKeyEvent(m_dpy, keycode, press, 0); XFlush(m_dpy); @@ -659,7 +647,7 @@ void AutoTypePlatformX11::SendKeyEvent(unsigned keycode, bool press) void AutoTypePlatformX11::SendModifiers(unsigned int mask, bool press) { int mod_index; - for (mod_index = ShiftMapIndex; mod_index <= Mod5MapIndex; mod_index ++) { + for (mod_index = ShiftMapIndex; mod_index <= Mod5MapIndex; mod_index++) { if (mask & (1 << mod_index)) { SendKeyEvent(m_modifier_keycode[mod_index], press); } @@ -670,7 +658,7 @@ void AutoTypePlatformX11::SendModifiers(unsigned int mask, bool press) * Determines the keycode and modifier mask for the given * keysym. */ -int AutoTypePlatformX11::GetKeycode(KeySym keysym, unsigned int *mask) +int AutoTypePlatformX11::GetKeycode(KeySym keysym, unsigned int* mask) { int keycode = XKeysymToKeycode(m_dpy, keysym); @@ -688,15 +676,15 @@ int AutoTypePlatformX11::GetKeycode(KeySym keysym, unsigned int *mask) return 0; } -bool AutoTypePlatformX11::keysymModifiers(KeySym keysym, int keycode, unsigned int *mask) +bool AutoTypePlatformX11::keysymModifiers(KeySym keysym, int keycode, unsigned int* mask) { int shift, mod; unsigned int mods_rtrn; /* determine whether there is a combination of the modifiers (Mod1-Mod5) with or without shift which returns keysym */ - for (shift = 0; shift < 2; shift ++) { - for (mod = ControlMapIndex; mod <= Mod5MapIndex; mod ++) { + for (shift = 0; shift < 2; shift++) { + for (mod = ControlMapIndex; mod <= Mod5MapIndex; mod++) { KeySym keysym_rtrn; *mask = (mod == ControlMapIndex) ? shift : shift | (1 << mod); XkbTranslateKeyCode(m_xkb, keycode, *mask, &mods_rtrn, &keysym_rtrn); @@ -709,8 +697,6 @@ bool AutoTypePlatformX11::keysymModifiers(KeySym keysym, int keycode, unsigned i return false; } - - /* * Send sequence of KeyPressed/KeyReleased events to the focused * window to simulate keyboard. If modifiers (shift, control, etc) @@ -753,7 +739,7 @@ void AutoTypePlatformX11::SendKey(KeySym keysym, unsigned int modifiers) if (!modifiers) { // check every release_check_mask individually if it affects the keysym we would generate // if it doesn't we probably don't need to release it - for (int mod_index = ShiftMapIndex; mod_index <= Mod5MapIndex; mod_index ++) { + for (int mod_index = ShiftMapIndex; mod_index <= Mod5MapIndex; mod_index++) { if (release_check_mask & (1 << mod_index)) { unsigned int mods_rtrn; KeySym keysym_rtrn; @@ -768,7 +754,8 @@ void AutoTypePlatformX11::SendKey(KeySym keysym, unsigned int modifiers) // finally check if the combination of pressed modifiers that we chose to ignore affects the keysym unsigned int mods_rtrn; KeySym keysym_rtrn; - XkbTranslateKeyCode(m_xkb, keycode, wanted_mask | (release_check_mask & ~release_mask), &mods_rtrn, &keysym_rtrn); + XkbTranslateKeyCode( + m_xkb, keycode, wanted_mask | (release_check_mask & ~release_mask), &mods_rtrn, &keysym_rtrn); if (keysym_rtrn != keysym) { // oh well, release all the modifiers we don't want release_mask = release_check_mask; @@ -810,7 +797,6 @@ int AutoTypePlatformX11::MyErrorHandler(Display* my_dpy, XErrorEvent* event) return 0; } - AutoTypeExecutorX11::AutoTypeExecutorX11(AutoTypePlatformX11* platform) : m_platform(platform) { @@ -844,7 +830,6 @@ void AutoTypeExecutorX11::execClearField(AutoTypeClearField* action = nullptr) nanosleep(&ts, nullptr); } - int AutoTypePlatformX11::initialTimeout() { return 500; @@ -870,15 +855,12 @@ bool AutoTypePlatformX11::raiseWindow(WId window) QWidget* activeWindow = QApplication::activeWindow(); if (activeWindow) { event.xclient.data.l[2] = activeWindow->internalWinId(); - } - else { + } else { event.xclient.data.l[2] = 0; } event.xclient.data.l[3] = 0; event.xclient.data.l[4] = 0; - XSendEvent(m_dpy, m_rootWindow, False, - SubstructureRedirectMask | SubstructureNotifyMask, - &event); + XSendEvent(m_dpy, m_rootWindow, False, SubstructureRedirectMask | SubstructureNotifyMask, &event); XFlush(m_dpy); return true; diff --git a/src/autotype/xcb/AutoTypeXCB.h b/src/autotype/xcb/AutoTypeXCB.h index 600e001aa..f339c7c0a 100644 --- a/src/autotype/xcb/AutoTypeXCB.h +++ b/src/autotype/xcb/AutoTypeXCB.h @@ -22,16 +22,16 @@ #include #include -#include #include #include +#include +#include #include #include -#include -#include "autotype/AutoTypePlatformPlugin.h" #include "autotype/AutoTypeAction.h" +#include "autotype/AutoTypePlatformPlugin.h" #define N_MOD_INDICES (Mod5MapIndex + 1) @@ -81,8 +81,8 @@ private: void AddModifier(KeySym keysym); void SendKeyEvent(unsigned keycode, bool press); void SendModifiers(unsigned int mask, bool press); - int GetKeycode(KeySym keysym, unsigned int *mask); - bool keysymModifiers(KeySym keysym, int keycode, unsigned int *mask); + int GetKeycode(KeySym keysym, unsigned int* mask); + bool keysymModifiers(KeySym keysym, int keycode, unsigned int* mask); static int MyErrorHandler(Display* my_dpy, XErrorEvent* event); diff --git a/src/browser/BrowserAccessControlDialog.cpp b/src/browser/BrowserAccessControlDialog.cpp old mode 100755 new mode 100644 index 7090a4d16..51abf2e95 --- a/src/browser/BrowserAccessControlDialog.cpp +++ b/src/browser/BrowserAccessControlDialog.cpp @@ -17,12 +17,12 @@ */ #include "BrowserAccessControlDialog.h" -#include "ui_BrowserAccessControlDialog.h" #include "core/Entry.h" +#include "ui_BrowserAccessControlDialog.h" -BrowserAccessControlDialog::BrowserAccessControlDialog(QWidget* parent) : - QDialog(parent), - ui(new Ui::BrowserAccessControlDialog()) +BrowserAccessControlDialog::BrowserAccessControlDialog(QWidget* parent) + : QDialog(parent) + , ui(new Ui::BrowserAccessControlDialog()) { this->setWindowFlags(windowFlags() | Qt::WindowStaysOnTopHint); @@ -38,7 +38,8 @@ BrowserAccessControlDialog::~BrowserAccessControlDialog() void BrowserAccessControlDialog::setUrl(const QString& url) { ui->label->setText(QString(tr("%1 has requested access to passwords for the following item(s).\n" - "Please select whether you want to allow access.")).arg(QUrl(url).host())); + "Please select whether you want to allow access.")) + .arg(QUrl(url).host())); } void BrowserAccessControlDialog::setItems(const QList& items) diff --git a/src/browser/BrowserAccessControlDialog.h b/src/browser/BrowserAccessControlDialog.h old mode 100755 new mode 100644 index d2a66ce0d..9f24a1e16 --- a/src/browser/BrowserAccessControlDialog.h +++ b/src/browser/BrowserAccessControlDialog.h @@ -24,8 +24,9 @@ class Entry; -namespace Ui { -class BrowserAccessControlDialog; +namespace Ui +{ + class BrowserAccessControlDialog; } class BrowserAccessControlDialog : public QDialog diff --git a/src/browser/BrowserAction.cpp b/src/browser/BrowserAction.cpp old mode 100755 new mode 100644 index b15d8ed59..1a2fdf6ea --- a/src/browser/BrowserAction.cpp +++ b/src/browser/BrowserAction.cpp @@ -16,21 +16,20 @@ * along with this program. If not, see . */ -#include -#include #include "BrowserAction.h" #include "BrowserSettings.h" +#include "config-keepassx.h" #include "sodium.h" #include "sodium/crypto_box.h" #include "sodium/randombytes.h" -#include "config-keepassx.h" +#include +#include -BrowserAction::BrowserAction(BrowserService& browserService) : - m_mutex(QMutex::Recursive), - m_browserService(browserService), - m_associated(false) +BrowserAction::BrowserAction(BrowserService& browserService) + : m_mutex(QMutex::Recursive) + , m_browserService(browserService) + , m_associated(false) { - } QJsonObject BrowserAction::readResponse(const QJsonObject& json) @@ -62,7 +61,6 @@ QJsonObject BrowserAction::readResponse(const QJsonObject& json) return handleAction(json); } - // Private functions /////////////////////// @@ -80,7 +78,7 @@ QJsonObject BrowserAction::handleAction(const QJsonObject& json) } else if (action.compare("associate", Qt::CaseSensitive) == 0) { return handleAssociate(json, action); } else if (action.compare("test-associate", Qt::CaseSensitive) == 0) { - return handleTestAssociate(json, action); + return handleTestAssociate(json, action); } else if (action.compare("get-logins", Qt::CaseSensitive) == 0) { return handleGetLogins(json, action); } else if (action.compare("generate-password", Qt::CaseSensitive) == 0) { @@ -270,7 +268,7 @@ QJsonObject BrowserAction::handleGeneratePassword(const QJsonObject& json, const QJsonArray arr; QJsonObject passwd; - passwd["login"] = QString::number(password.length() * 8); //bits; + passwd["login"] = QString::number(password.length() * 8); // bits; passwd["password"] = password; arr.append(passwd); @@ -386,31 +384,49 @@ QJsonObject BrowserAction::buildResponse(const QString& action, const QJsonObjec QString BrowserAction::getErrorMessage(const int errorCode) const { switch (errorCode) { - case ERROR_KEEPASS_DATABASE_NOT_OPENED: return QObject::tr("Database not opened"); - case ERROR_KEEPASS_DATABASE_HASH_NOT_RECEIVED: return QObject::tr("Database hash not available"); - case ERROR_KEEPASS_CLIENT_PUBLIC_KEY_NOT_RECEIVED: return QObject::tr("Client public key not received"); - case ERROR_KEEPASS_CANNOT_DECRYPT_MESSAGE: return QObject::tr("Cannot decrypt message"); - case ERROR_KEEPASS_TIMEOUT_OR_NOT_CONNECTED: return QObject::tr("Timeout or cannot connect to KeePassXC"); - case ERROR_KEEPASS_ACTION_CANCELLED_OR_DENIED: return QObject::tr("Action cancelled or denied"); - case ERROR_KEEPASS_CANNOT_ENCRYPT_MESSAGE: return QObject::tr("Cannot encrypt message or public key not found. Is Native Messaging enabled in KeePassXC?"); - case ERROR_KEEPASS_ASSOCIATION_FAILED: return QObject::tr("KeePassXC association failed, try again"); - case ERROR_KEEPASS_KEY_CHANGE_FAILED: return QObject::tr("Key change was not successful"); - case ERROR_KEEPASS_ENCRYPTION_KEY_UNRECOGNIZED: return QObject::tr("Encryption key is not recognized"); - case ERROR_KEEPASS_NO_SAVED_DATABASES_FOUND: return QObject::tr("No saved databases found"); - case ERROR_KEEPASS_INCORRECT_ACTION: return QObject::tr("Incorrect action"); - case ERROR_KEEPASS_EMPTY_MESSAGE_RECEIVED: return QObject::tr("Empty message received"); - case ERROR_KEEPASS_NO_URL_PROVIDED: return QObject::tr("No URL provided"); - case ERROR_KEEPASS_NO_LOGINS_FOUND: return QObject::tr("No logins found"); - default: return QObject::tr("Unknown error"); + case ERROR_KEEPASS_DATABASE_NOT_OPENED: + return QObject::tr("Database not opened"); + case ERROR_KEEPASS_DATABASE_HASH_NOT_RECEIVED: + return QObject::tr("Database hash not available"); + case ERROR_KEEPASS_CLIENT_PUBLIC_KEY_NOT_RECEIVED: + return QObject::tr("Client public key not received"); + case ERROR_KEEPASS_CANNOT_DECRYPT_MESSAGE: + return QObject::tr("Cannot decrypt message"); + case ERROR_KEEPASS_TIMEOUT_OR_NOT_CONNECTED: + return QObject::tr("Timeout or cannot connect to KeePassXC"); + case ERROR_KEEPASS_ACTION_CANCELLED_OR_DENIED: + return QObject::tr("Action cancelled or denied"); + case ERROR_KEEPASS_CANNOT_ENCRYPT_MESSAGE: + return QObject::tr("Cannot encrypt message or public key not found. Is Native Messaging enabled in KeePassXC?"); + case ERROR_KEEPASS_ASSOCIATION_FAILED: + return QObject::tr("KeePassXC association failed, try again"); + case ERROR_KEEPASS_KEY_CHANGE_FAILED: + return QObject::tr("Key change was not successful"); + case ERROR_KEEPASS_ENCRYPTION_KEY_UNRECOGNIZED: + return QObject::tr("Encryption key is not recognized"); + case ERROR_KEEPASS_NO_SAVED_DATABASES_FOUND: + return QObject::tr("No saved databases found"); + case ERROR_KEEPASS_INCORRECT_ACTION: + return QObject::tr("Incorrect action"); + case ERROR_KEEPASS_EMPTY_MESSAGE_RECEIVED: + return QObject::tr("Empty message received"); + case ERROR_KEEPASS_NO_URL_PROVIDED: + return QObject::tr("No URL provided"); + case ERROR_KEEPASS_NO_LOGINS_FOUND: + return QObject::tr("No logins found"); + default: + return QObject::tr("Unknown error"); } } QString BrowserAction::getDatabaseHash() { QMutexLocker locker(&m_mutex); - QByteArray hash = QCryptographicHash::hash( - (m_browserService.getDatabaseRootUuid() + m_browserService.getDatabaseRecycleBinUuid()).toUtf8(), - QCryptographicHash::Sha256).toHex(); + QByteArray hash = + QCryptographicHash::hash( + (m_browserService.getDatabaseRootUuid() + m_browserService.getDatabaseRecycleBinUuid()).toUtf8(), + QCryptographicHash::Sha256) + .toHex(); return QString(hash); } @@ -463,8 +479,8 @@ QString BrowserAction::encrypt(const QString plaintext, const QString nonce) } if (crypto_box_easy(e.data(), m.data(), m.size(), n.data(), ck.data(), sk.data()) == 0) { - QByteArray res = getQByteArray(e.data(), (crypto_box_MACBYTES + ma.length())); - return res.toBase64(); + QByteArray res = getQByteArray(e.data(), (crypto_box_MACBYTES + ma.length())); + return res.toBase64(); } return QString(); @@ -491,7 +507,7 @@ QByteArray BrowserAction::decrypt(const QString encrypted, const QString nonce) } if (crypto_box_open_easy(d.data(), m.data(), ma.length(), n.data(), ck.data(), sk.data()) == 0) { - return getQByteArray(d.data(), std::char_traits::length(reinterpret_cast(d.data()))); + return getQByteArray(d.data(), std::char_traits::length(reinterpret_cast(d.data()))); } return QByteArray(); diff --git a/src/browser/BrowserAction.h b/src/browser/BrowserAction.h old mode 100755 new mode 100644 index c4d59d3c9..46fb9d04f --- a/src/browser/BrowserAction.h +++ b/src/browser/BrowserAction.h @@ -19,32 +19,33 @@ #ifndef BROWSERACTION_H #define BROWSERACTION_H -#include -#include +#include "BrowserService.h" #include #include -#include "BrowserService.h" +#include +#include class BrowserAction : public QObject { Q_OBJECT - enum { - ERROR_KEEPASS_DATABASE_NOT_OPENED = 1, - ERROR_KEEPASS_DATABASE_HASH_NOT_RECEIVED = 2, - ERROR_KEEPASS_CLIENT_PUBLIC_KEY_NOT_RECEIVED = 3, - ERROR_KEEPASS_CANNOT_DECRYPT_MESSAGE = 4, - ERROR_KEEPASS_TIMEOUT_OR_NOT_CONNECTED = 5, - ERROR_KEEPASS_ACTION_CANCELLED_OR_DENIED = 6, - ERROR_KEEPASS_CANNOT_ENCRYPT_MESSAGE = 7, - ERROR_KEEPASS_ASSOCIATION_FAILED = 8, - ERROR_KEEPASS_KEY_CHANGE_FAILED = 9, - ERROR_KEEPASS_ENCRYPTION_KEY_UNRECOGNIZED = 10, - ERROR_KEEPASS_NO_SAVED_DATABASES_FOUND = 11, - ERROR_KEEPASS_INCORRECT_ACTION = 12, - ERROR_KEEPASS_EMPTY_MESSAGE_RECEIVED = 13, - ERROR_KEEPASS_NO_URL_PROVIDED = 14, - ERROR_KEEPASS_NO_LOGINS_FOUND = 15 + enum + { + ERROR_KEEPASS_DATABASE_NOT_OPENED = 1, + ERROR_KEEPASS_DATABASE_HASH_NOT_RECEIVED = 2, + ERROR_KEEPASS_CLIENT_PUBLIC_KEY_NOT_RECEIVED = 3, + ERROR_KEEPASS_CANNOT_DECRYPT_MESSAGE = 4, + ERROR_KEEPASS_TIMEOUT_OR_NOT_CONNECTED = 5, + ERROR_KEEPASS_ACTION_CANCELLED_OR_DENIED = 6, + ERROR_KEEPASS_CANNOT_ENCRYPT_MESSAGE = 7, + ERROR_KEEPASS_ASSOCIATION_FAILED = 8, + ERROR_KEEPASS_KEY_CHANGE_FAILED = 9, + ERROR_KEEPASS_ENCRYPTION_KEY_UNRECOGNIZED = 10, + ERROR_KEEPASS_NO_SAVED_DATABASES_FOUND = 11, + ERROR_KEEPASS_INCORRECT_ACTION = 12, + ERROR_KEEPASS_EMPTY_MESSAGE_RECEIVED = 13, + ERROR_KEEPASS_NO_URL_PROVIDED = 14, + ERROR_KEEPASS_NO_LOGINS_FOUND = 15 }; public: @@ -54,8 +55,8 @@ public: QJsonObject readResponse(const QJsonObject& json); public slots: - void removeSharedEncryptionKeys(); - void removeStoredPermissions(); + void removeSharedEncryptionKeys(); + void removeStoredPermissions(); private: QJsonObject handleAction(const QJsonObject& json); @@ -71,28 +72,28 @@ private: QJsonObject buildMessage(const QString& nonce) const; QJsonObject buildResponse(const QString& action, const QJsonObject& message, const QString& nonce); QJsonObject getErrorReply(const QString& action, const int errorCode) const; - QString getErrorMessage(const int errorCode) const; - QString getDatabaseHash(); + QString getErrorMessage(const int errorCode) const; + QString getDatabaseHash(); - QString encryptMessage(const QJsonObject& message, const QString& nonce); + QString encryptMessage(const QJsonObject& message, const QString& nonce); QJsonObject decryptMessage(const QString& message, const QString& nonce, const QString& action = QString()); - QString encrypt(const QString plaintext, const QString nonce); - QByteArray decrypt(const QString encrypted, const QString nonce); + QString encrypt(const QString plaintext, const QString nonce); + QByteArray decrypt(const QString encrypted, const QString nonce); - QString getBase64FromKey(const uchar* array, const uint len); - QByteArray getQByteArray(const uchar* array, const uint len) const; + QString getBase64FromKey(const uchar* array, const uint len); + QByteArray getQByteArray(const uchar* array, const uint len) const; QJsonObject getJsonObject(const uchar* pArray, const uint len) const; QJsonObject getJsonObject(const QByteArray ba) const; - QByteArray base64Decode(const QString str); - QString incrementNonce(const QString& nonce); + QByteArray base64Decode(const QString str); + QString incrementNonce(const QString& nonce); private: - QMutex m_mutex; - BrowserService& m_browserService; - QString m_clientPublicKey; - QString m_publicKey; - QString m_secretKey; - bool m_associated; + QMutex m_mutex; + BrowserService& m_browserService; + QString m_clientPublicKey; + QString m_publicKey; + QString m_secretKey; + bool m_associated; }; #endif // BROWSERACTION_H diff --git a/src/browser/BrowserClients.cpp b/src/browser/BrowserClients.cpp old mode 100755 new mode 100644 index 9c47fdd46..c994ef1d0 --- a/src/browser/BrowserClients.cpp +++ b/src/browser/BrowserClients.cpp @@ -16,13 +16,13 @@ * along with this program. If not, see . */ -#include -#include #include "BrowserClients.h" +#include +#include -BrowserClients::BrowserClients(BrowserService& browserService) : - m_mutex(QMutex::Recursive), - m_browserService(browserService) +BrowserClients::BrowserClients(BrowserService& browserService) + : m_mutex(QMutex::Recursive) + , m_browserService(browserService) { m_clients.reserve(1000); } @@ -63,7 +63,7 @@ QString BrowserClients::getClientID(const QJsonObject& json) const BrowserClients::ClientPtr BrowserClients::getClient(const QString& clientID) { QMutexLocker locker(&m_mutex); - for (const auto &i : m_clients) { + for (const auto& i : m_clients) { if (i->clientID.compare(clientID, Qt::CaseSensitive) == 0) { return i; } diff --git a/src/browser/BrowserClients.h b/src/browser/BrowserClients.h old mode 100755 new mode 100644 index f9052e7de..b725154a5 --- a/src/browser/BrowserClients.h +++ b/src/browser/BrowserClients.h @@ -19,22 +19,27 @@ #ifndef BROWSERCLIENTS_H #define BROWSERCLIENTS_H -#include -#include -#include -#include -#include #include "BrowserAction.h" +#include +#include +#include +#include +#include class BrowserClients { - struct Client { - Client(const QString& id, QSharedPointer ba) : clientID(id), browserAction(ba) {} - QString clientID; - QSharedPointer browserAction; + struct Client + { + Client(const QString& id, QSharedPointer ba) + : clientID(id) + , browserAction(ba) + { + } + QString clientID; + QSharedPointer browserAction; }; - typedef QSharedPointer ClientPtr; + typedef QSharedPointer ClientPtr; public: BrowserClients(BrowserService& browserService); @@ -44,13 +49,13 @@ public: private: QJsonObject byteArrayToJson(const QByteArray& arr) const; - QString getClientID(const QJsonObject& json) const; - ClientPtr getClient(const QString& clientID); + QString getClientID(const QJsonObject& json) const; + ClientPtr getClient(const QString& clientID); private: - QMutex m_mutex; - QVector m_clients; - BrowserService& m_browserService; + QMutex m_mutex; + QVector m_clients; + BrowserService& m_browserService; }; #endif // BROWSERCLIENTS_H diff --git a/src/browser/BrowserEntryConfig.cpp b/src/browser/BrowserEntryConfig.cpp index 36d0c7339..90d9f107c 100644 --- a/src/browser/BrowserEntryConfig.cpp +++ b/src/browser/BrowserEntryConfig.cpp @@ -17,15 +17,14 @@ */ #include "BrowserEntryConfig.h" -#include #include "core/Entry.h" #include "core/EntryAttributes.h" +#include static const char KEEPASSBROWSER_NAME[] = "KeePassXC-Browser Settings"; - -BrowserEntryConfig::BrowserEntryConfig(QObject* parent) : - QObject(parent) +BrowserEntryConfig::BrowserEntryConfig(QObject* parent) + : QObject(parent) { } diff --git a/src/browser/BrowserEntryConfig.h b/src/browser/BrowserEntryConfig.h index 0ffaf985b..3b808b7e0 100644 --- a/src/browser/BrowserEntryConfig.h +++ b/src/browser/BrowserEntryConfig.h @@ -19,11 +19,11 @@ #ifndef BROWSERENTRYCONFIG_H #define BROWSERENTRYCONFIG_H +#include "Variant.h" #include +#include #include #include -#include -#include "Variant.h" class Entry; @@ -31,8 +31,8 @@ class BrowserEntryConfig : public QObject { Q_OBJECT Q_PROPERTY(QStringList Allow READ allowedHosts WRITE setAllowedHosts) - Q_PROPERTY(QStringList Deny READ deniedHosts WRITE setDeniedHosts ) - Q_PROPERTY(QString Realm READ realm WRITE setRealm ) + Q_PROPERTY(QStringList Deny READ deniedHosts WRITE setDeniedHosts) + Q_PROPERTY(QString Realm READ realm WRITE setRealm) public: BrowserEntryConfig(QObject* object = 0); @@ -54,7 +54,7 @@ private: QSet m_allowedHosts; QSet m_deniedHosts; - QString m_realm; + QString m_realm; }; #endif // BROWSERENTRYCONFIG_H diff --git a/src/browser/BrowserOptionDialog.cpp b/src/browser/BrowserOptionDialog.cpp old mode 100755 new mode 100644 index 1ad7e8b36..707d60326 --- a/src/browser/BrowserOptionDialog.cpp +++ b/src/browser/BrowserOptionDialog.cpp @@ -18,23 +18,24 @@ */ #include "BrowserOptionDialog.h" -#include "ui_BrowserOptionDialog.h" -#include "config-keepassx.h" #include "BrowserSettings.h" +#include "config-keepassx.h" #include "core/FilePath.h" +#include "ui_BrowserOptionDialog.h" -#include #include +#include -BrowserOptionDialog::BrowserOptionDialog(QWidget* parent) : - QWidget(parent), - m_ui(new Ui::BrowserOptionDialog()) +BrowserOptionDialog::BrowserOptionDialog(QWidget* parent) + : QWidget(parent) + , m_ui(new Ui::BrowserOptionDialog()) { m_ui->setupUi(this); connect(m_ui->removeSharedEncryptionKeys, SIGNAL(clicked()), this, SIGNAL(removeSharedEncryptionKeys())); connect(m_ui->removeStoredPermissions, SIGNAL(clicked()), this, SIGNAL(removeStoredPermissions())); - m_ui->warningWidget->showMessage(tr("Warning: The following options can be dangerous!"), MessageWidget::Warning); + m_ui->warningWidget->showMessage(tr("Warning: The following options can be dangerous!"), + MessageWidget::Warning); m_ui->warningWidget->setCloseButtonVisible(false); m_ui->warningWidget->setAutoHideTimeout(-1); @@ -95,7 +96,8 @@ void BrowserOptionDialog::loadSettings() m_ui->enableBrowserSupport->setChecked(false); m_ui->enableBrowserSupport->setEnabled(false); m_ui->browserGlobalWarningWidget->showMessage( - tr("We're sorry, but KeePassXC-Browser is not supported for Snap releases at the moment."), MessageWidget::Warning); + tr("We're sorry, but KeePassXC-Browser is not supported for Snap releases at the moment."), + MessageWidget::Warning); m_ui->browserGlobalWarningWidget->setCloseButtonVisible(false); m_ui->browserGlobalWarningWidget->setAutoHideTimeout(-1); #endif @@ -134,7 +136,8 @@ void BrowserOptionDialog::showProxyLocationFileDialog() #else QString fileTypeFilter(QString("%1 (*)").arg(tr("Executable Files"))); #endif - auto proxyLocation = QFileDialog::getOpenFileName(this, tr("Select custom proxy location"), + auto proxyLocation = QFileDialog::getOpenFileName(this, + tr("Select custom proxy location"), QFileInfo(QCoreApplication::applicationDirPath()).filePath(), fileTypeFilter); m_ui->customProxyLocation->setText(proxyLocation); diff --git a/src/browser/BrowserOptionDialog.h b/src/browser/BrowserOptionDialog.h old mode 100755 new mode 100644 index b562f6c18..a48504dfd --- a/src/browser/BrowserOptionDialog.h +++ b/src/browser/BrowserOptionDialog.h @@ -20,11 +20,12 @@ #ifndef BROWSEROPTIONDIALOG_H #define BROWSEROPTIONDIALOG_H -#include #include +#include -namespace Ui { -class BrowserOptionDialog; +namespace Ui +{ + class BrowserOptionDialog; } class BrowserOptionDialog : public QWidget diff --git a/src/browser/BrowserService.cpp b/src/browser/BrowserService.cpp index e59411aee..331bc6b78 100644 --- a/src/browser/BrowserService.cpp +++ b/src/browser/BrowserService.cpp @@ -17,41 +17,43 @@ * along with this program. If not, see . */ -#include -#include -#include -#include #include "BrowserService.h" -#include "BrowserSettings.h" -#include "BrowserEntryConfig.h" #include "BrowserAccessControlDialog.h" +#include "BrowserEntryConfig.h" +#include "BrowserSettings.h" #include "core/Database.h" -#include "core/Group.h" #include "core/EntrySearcher.h" +#include "core/Group.h" #include "core/Metadata.h" -#include "core/Uuid.h" #include "core/PasswordGenerator.h" +#include "core/Uuid.h" #include "gui/MainWindow.h" - +#include +#include +#include +#include // de887cc3-0363-43b8-974b-5911b8816224 -static const unsigned char KEEPASSXCBROWSER_UUID_DATA[] = { - 0xde, 0x88, 0x7c, 0xc3, 0x03, 0x63, 0x43, 0xb8, - 0x97, 0x4b, 0x59, 0x11, 0xb8, 0x81, 0x62, 0x24 -}; -static const Uuid KEEPASSXCBROWSER_UUID = Uuid(QByteArray::fromRawData(reinterpret_cast(KEEPASSXCBROWSER_UUID_DATA), sizeof(KEEPASSXCBROWSER_UUID_DATA))); +static const unsigned char KEEPASSXCBROWSER_UUID_DATA[] = + {0xde, 0x88, 0x7c, 0xc3, 0x03, 0x63, 0x43, 0xb8, 0x97, 0x4b, 0x59, 0x11, 0xb8, 0x81, 0x62, 0x24}; +static const Uuid KEEPASSXCBROWSER_UUID = + Uuid(QByteArray::fromRawData(reinterpret_cast(KEEPASSXCBROWSER_UUID_DATA), + sizeof(KEEPASSXCBROWSER_UUID_DATA))); static const char KEEPASSXCBROWSER_NAME[] = "KeePassXC-Browser Settings"; static const char ASSOCIATE_KEY_PREFIX[] = "Public Key: "; static const char KEEPASSXCBROWSER_GROUP_NAME[] = "KeePassXC-Browser Passwords"; -static int KEEPASSXCBROWSER_DEFAULT_ICON = 1; +static int KEEPASSXCBROWSER_DEFAULT_ICON = 1; -BrowserService::BrowserService(DatabaseTabWidget* parent) : - m_dbTabWidget(parent), - m_dialogActive(false) +BrowserService::BrowserService(DatabaseTabWidget* parent) + : m_dbTabWidget(parent) + , m_dialogActive(false) { connect(m_dbTabWidget, SIGNAL(databaseLocked(DatabaseWidget*)), this, SLOT(databaseLocked(DatabaseWidget*))); connect(m_dbTabWidget, SIGNAL(databaseUnlocked(DatabaseWidget*)), this, SLOT(databaseUnlocked(DatabaseWidget*))); - connect(m_dbTabWidget, SIGNAL(activateDatabaseChanged(DatabaseWidget*)), this, SLOT(activateDatabaseChanged(DatabaseWidget*))); + connect(m_dbTabWidget, + SIGNAL(activateDatabaseChanged(DatabaseWidget*)), + this, + SLOT(activateDatabaseChanged(DatabaseWidget*))); } bool BrowserService::isDatabaseOpened() const @@ -62,7 +64,6 @@ bool BrowserService::isDatabaseOpened() const } return dbWidget->currentMode() == DatabaseWidget::ViewMode || dbWidget->currentMode() == DatabaseWidget::EditMode; - } bool BrowserService::openDatabase(bool triggerUnlock) @@ -167,9 +168,8 @@ QString BrowserService::storeKey(const QString& key) QString id; if (thread() != QThread::currentThread()) { - QMetaObject::invokeMethod(this, "storeKey", Qt::BlockingQueuedConnection, - Q_RETURN_ARG(QString, id), - Q_ARG(const QString&, key)); + QMetaObject::invokeMethod( + this, "storeKey", Qt::BlockingQueuedConnection, Q_RETURN_ARG(QString, id), Q_ARG(const QString&, key)); return id; } @@ -185,8 +185,8 @@ QString BrowserService::storeKey(const QString& key) QInputDialog keyDialog; keyDialog.setWindowTitle(tr("KeePassXC: New key association request")); keyDialog.setLabelText(tr("You have received an association request for the above key.\n\n" - "If you would like to allow it access to your KeePassXC database,\n" - "give it a unique name to identify and accept it.")); + "If you would like to allow it access to your KeePassXC database,\n" + "give it a unique name to identify and accept it.")); keyDialog.setOkButtonText(tr("Save and allow access")); keyDialog.setWindowFlags(keyDialog.windowFlags() | Qt::WindowStaysOnTopHint); keyDialog.show(); @@ -202,7 +202,8 @@ QString BrowserService::storeKey(const QString& key) contains = config->attributes()->contains(QLatin1String(ASSOCIATE_KEY_PREFIX) + id); if (contains) { - dialogResult = QMessageBox::warning(nullptr, tr("KeePassXC: Overwrite existing key?"), + dialogResult = QMessageBox::warning(nullptr, + tr("KeePassXC: Overwrite existing key?"), tr("A shared encryption key with the name \"%1\" " "already exists.\nDo you want to overwrite it?") .arg(id), @@ -224,11 +225,16 @@ QString BrowserService::getKey(const QString& id) return config->attributes()->value(QLatin1String(ASSOCIATE_KEY_PREFIX) + id); } -QJsonArray BrowserService::findMatchingEntries(const QString& id, const QString& url, const QString& submitUrl, const QString& realm) +QJsonArray BrowserService::findMatchingEntries(const QString& id, + const QString& url, + const QString& submitUrl, + const QString& realm) { QJsonArray result; if (thread() != QThread::currentThread()) { - QMetaObject::invokeMethod(this, "findMatchingEntries", Qt::BlockingQueuedConnection, + QMetaObject::invokeMethod(this, + "findMatchingEntries", + Qt::BlockingQueuedConnection, Q_RETURN_ARG(QJsonArray, result), Q_ARG(const QString&, id), Q_ARG(const QString&, url), @@ -283,7 +289,12 @@ QJsonArray BrowserService::findMatchingEntries(const QString& id, const QString& return result; } -void BrowserService::addEntry(const QString&, const QString& login, const QString& password, const QString& url, const QString& submitUrl, const QString& realm) +void BrowserService::addEntry(const QString&, + const QString& login, + const QString& password, + const QString& url, + const QString& submitUrl, + const QString& realm) { Group* group = findCreateAddEntryGroup(); if (!group) { @@ -313,10 +324,16 @@ void BrowserService::addEntry(const QString&, const QString& login, const QStrin config.save(entry); } -void BrowserService::updateEntry(const QString& id, const QString& uuid, const QString& login, const QString& password, const QString& url) +void BrowserService::updateEntry(const QString& id, + const QString& uuid, + const QString& login, + const QString& password, + const QString& url) { if (thread() != QThread::currentThread()) { - QMetaObject::invokeMethod(this, "updateEntry", Qt::BlockingQueuedConnection, + QMetaObject::invokeMethod(this, + "updateEntry", + Qt::BlockingQueuedConnection, Q_ARG(const QString&, id), Q_ARG(const QString&, uuid), Q_ARG(const QString&, login), @@ -339,13 +356,15 @@ void BrowserService::updateEntry(const QString& id, const QString& uuid, const Q return; } - if (username.compare(login, Qt::CaseSensitive) != 0 || entry->password().compare(password, Qt::CaseSensitive) != 0) { + if (username.compare(login, Qt::CaseSensitive) != 0 + || entry->password().compare(password, Qt::CaseSensitive) != 0) { QMessageBox::StandardButton dialogResult = QMessageBox::No; if (!BrowserSettings::alwaysAllowUpdate()) { - dialogResult = QMessageBox::warning(0, tr("KeePassXC: Update Entry"), - tr("Do you want to update the information in %1 - %2?") - .arg(QUrl(url).host()).arg(username), - QMessageBox::Yes|QMessageBox::No); + dialogResult = QMessageBox::warning( + 0, + tr("KeePassXC: Update Entry"), + tr("Do you want to update the information in %1 - %2?").arg(QUrl(url).host()).arg(username), + QMessageBox::Yes | QMessageBox::No); } if (BrowserSettings::alwaysAllowUpdate() || dialogResult == QMessageBox::Yes) { @@ -370,11 +389,10 @@ QList BrowserService::searchEntries(Database* db, const QString& hostnam QString url = entry->url(); // Filter to match hostname in Title and Url fields - if ((!title.isEmpty() && hostname.contains(title)) - || (!url.isEmpty() && hostname.contains(url)) + if ((!title.isEmpty() && hostname.contains(title)) || (!url.isEmpty() && hostname.contains(url)) || (matchUrlScheme(title) && hostname.endsWith(QUrl(title).host())) - || (matchUrlScheme(url) && hostname.endsWith(QUrl(url).host())) ) { - entries.append(entry); + || (matchUrlScheme(url) && hostname.endsWith(QUrl(url).host()))) { + entries.append(entry); } } @@ -413,7 +431,8 @@ QList BrowserService::searchEntries(const QString& text) void BrowserService::removeSharedEncryptionKeys() { if (!isDatabaseOpened()) { - QMessageBox::critical(0, tr("KeePassXC: Database locked!"), + QMessageBox::critical(0, + tr("KeePassXC: Database locked!"), tr("The active database is locked!\n" "Please unlock the selected database or choose another one which is unlocked."), QMessageBox::Ok); @@ -422,7 +441,8 @@ void BrowserService::removeSharedEncryptionKeys() Entry* entry = getConfigEntry(); if (!entry) { - QMessageBox::information(0, tr("KeePassXC: Settings not available!"), + QMessageBox::information(0, + tr("KeePassXC: Settings not available!"), tr("The active database does not contain a settings entry."), QMessageBox::Ok); return; @@ -436,7 +456,8 @@ void BrowserService::removeSharedEncryptionKeys() } if (keysToRemove.isEmpty()) { - QMessageBox::information(0, tr("KeePassXC: No keys found"), + QMessageBox::information(0, + tr("KeePassXC: No keys found"), tr("No shared encryption keys found in KeePassXC settings."), QMessageBox::Ok); return; @@ -449,16 +470,17 @@ void BrowserService::removeSharedEncryptionKeys() entry->endUpdate(); const int count = keysToRemove.count(); - QMessageBox::information(0, tr("KeePassXC: Removed keys from database"), + QMessageBox::information(0, + tr("KeePassXC: Removed keys from database"), tr("Successfully removed %n encryption key(s) from KeePassXC settings.", "", count), QMessageBox::Ok); - } void BrowserService::removeStoredPermissions() { if (!isDatabaseOpened()) { - QMessageBox::critical(0, tr("KeePassXC: Database locked!"), + QMessageBox::critical(0, + tr("KeePassXC: Database locked!"), tr("The active database is locked!\n" "Please unlock the selected database or choose another one which is unlocked."), QMessageBox::Ok); @@ -492,11 +514,13 @@ void BrowserService::removeStoredPermissions() progress.reset(); if (counter > 0) { - QMessageBox::information(0, tr("KeePassXC: Removed permissions"), + QMessageBox::information(0, + tr("KeePassXC: Removed permissions"), tr("Successfully removed permissions from %n entry(s).", "", counter), QMessageBox::Ok); } else { - QMessageBox::information(0, tr("KeePassXC: No entry with permissions found!"), + QMessageBox::information(0, + tr("KeePassXC: No entry with permissions found!"), tr("The active database does not contain an entry with permissions."), QMessageBox::Ok); } @@ -510,7 +534,8 @@ QList BrowserService::sortEntries(QList& pwEntries, const QStrin } const QString submitUrl = url.toString(QUrl::StripTrailingSlash); - const QString baseSubmitUrl = url.toString(QUrl::StripTrailingSlash | QUrl::RemovePath | QUrl::RemoveQuery | QUrl::RemoveFragment); + const QString baseSubmitUrl = + url.toString(QUrl::StripTrailingSlash | QUrl::RemovePath | QUrl::RemoveQuery | QUrl::RemoveFragment); QMultiMap priorities; for (const Entry* entry : pwEntries) { @@ -529,7 +554,11 @@ QList BrowserService::sortEntries(QList& pwEntries, const QStrin return pwEntries; } -bool BrowserService::confirmEntries(QList& pwEntriesToConfirm, const QString& url, const QString& host, const QString& submitHost, const QString& realm) +bool BrowserService::confirmEntries(QList& pwEntriesToConfirm, + const QString& url, + const QString& host, + const QString& submitHost, + const QString& realm) { if (pwEntriesToConfirm.isEmpty() || m_dialogActive) { return false; @@ -593,7 +622,8 @@ QJsonObject BrowserService::prepareEntry(const Entry* entry) return res; } -BrowserService::Access BrowserService::checkAccess(const Entry* entry, const QString& host, const QString& submitHost, const QString& realm) +BrowserService::Access +BrowserService::checkAccess(const Entry* entry, const QString& host, const QString& submitHost, const QString& realm) { BrowserEntryConfig config; if (!config.load(entry)) { @@ -623,7 +653,8 @@ Group* BrowserService::findCreateAddEntryGroup() return nullptr; } - const QString groupName = QLatin1String(KEEPASSXCBROWSER_GROUP_NAME); //TODO: setting to decide where new keys are created + const QString groupName = + QLatin1String(KEEPASSXCBROWSER_GROUP_NAME); // TODO: setting to decide where new keys are created for (const Group* g : rootGroup->groupsRecursive(true)) { if (g->name() == groupName) { @@ -639,14 +670,18 @@ Group* BrowserService::findCreateAddEntryGroup() return group; } -int BrowserService::sortPriority(const Entry* entry, const QString& host, const QString& submitUrl, const QString& baseSubmitUrl) const +int BrowserService::sortPriority(const Entry* entry, + const QString& host, + const QString& submitUrl, + const QString& baseSubmitUrl) const { QUrl url(entry->url()); if (url.scheme().isEmpty()) { url.setScheme("http"); } const QString entryURL = url.toString(QUrl::StripTrailingSlash); - const QString baseEntryURL = url.toString(QUrl::StripTrailingSlash | QUrl::RemovePath | QUrl::RemoveQuery | QUrl::RemoveFragment); + const QString baseEntryURL = + url.toString(QUrl::StripTrailingSlash | QUrl::RemovePath | QUrl::RemoveQuery | QUrl::RemoveFragment); if (submitUrl == entryURL) { return 100; diff --git a/src/browser/BrowserService.h b/src/browser/BrowserService.h index 5a96e1ecd..127c4f6ae 100644 --- a/src/browser/BrowserService.h +++ b/src/browser/BrowserService.h @@ -20,63 +20,86 @@ #ifndef BROWSERSERVICE_H #define BROWSERSERVICE_H -#include -#include -#include "gui/DatabaseTabWidget.h" #include "core/Entry.h" +#include "gui/DatabaseTabWidget.h" +#include +#include -enum { max_length = 16*1024 }; +enum +{ + max_length = 16 * 1024 +}; class BrowserService : public QObject { Q_OBJECT public: - explicit BrowserService(DatabaseTabWidget* parent); + explicit BrowserService(DatabaseTabWidget* parent); - bool isDatabaseOpened() const; - bool openDatabase(bool triggerUnlock); - QString getDatabaseRootUuid(); - QString getDatabaseRecycleBinUuid(); - Entry* getConfigEntry(bool create = false); - QString getKey(const QString& id); - void addEntry(const QString& id, const QString& login, const QString& password, const QString& url, const QString& submitUrl, const QString& realm); - QList searchEntries(Database* db, const QString& hostname); - QList searchEntries(const QString& text); - void removeSharedEncryptionKeys(); - void removeStoredPermissions(); + bool isDatabaseOpened() const; + bool openDatabase(bool triggerUnlock); + QString getDatabaseRootUuid(); + QString getDatabaseRecycleBinUuid(); + Entry* getConfigEntry(bool create = false); + QString getKey(const QString& id); + void addEntry(const QString& id, + const QString& login, + const QString& password, + const QString& url, + const QString& submitUrl, + const QString& realm); + QList searchEntries(Database* db, const QString& hostname); + QList searchEntries(const QString& text); + void removeSharedEncryptionKeys(); + void removeStoredPermissions(); public slots: - QJsonArray findMatchingEntries(const QString& id, const QString& url, const QString& submitUrl, const QString& realm); - QString storeKey(const QString& key); - void updateEntry(const QString& id, const QString& uuid, const QString& login, const QString& password, const QString& url); - void databaseLocked(DatabaseWidget* dbWidget); - void databaseUnlocked(DatabaseWidget* dbWidget); - void activateDatabaseChanged(DatabaseWidget* dbWidget); - void lockDatabase(); + QJsonArray + findMatchingEntries(const QString& id, const QString& url, const QString& submitUrl, const QString& realm); + QString storeKey(const QString& key); + void updateEntry(const QString& id, + const QString& uuid, + const QString& login, + const QString& password, + const QString& url); + void databaseLocked(DatabaseWidget* dbWidget); + void databaseUnlocked(DatabaseWidget* dbWidget); + void activateDatabaseChanged(DatabaseWidget* dbWidget); + void lockDatabase(); signals: - void databaseLocked(); - void databaseUnlocked(); - void databaseChanged(); + void databaseLocked(); + void databaseUnlocked(); + void databaseChanged(); private: - enum Access { Denied, Unknown, Allowed}; + enum Access + { + Denied, + Unknown, + Allowed + }; private: - QList sortEntries(QList& pwEntries, const QString& host, const QString& submitUrl); - bool confirmEntries(QList& pwEntriesToConfirm, const QString& url, const QString& host, const QString& submitHost, const QString& realm); - QJsonObject prepareEntry(const Entry* entry); - Access checkAccess(const Entry* entry, const QString& host, const QString& submitHost, const QString& realm); - Group* findCreateAddEntryGroup(); - int sortPriority(const Entry* entry, const QString &host, const QString& submitUrl, const QString& baseSubmitUrl) const; - bool matchUrlScheme(const QString& url); - bool removeFirstDomain(QString& hostname); - Database* getDatabase(); + QList sortEntries(QList& pwEntries, const QString& host, const QString& submitUrl); + bool confirmEntries(QList& pwEntriesToConfirm, + const QString& url, + const QString& host, + const QString& submitHost, + const QString& realm); + QJsonObject prepareEntry(const Entry* entry); + Access checkAccess(const Entry* entry, const QString& host, const QString& submitHost, const QString& realm); + Group* findCreateAddEntryGroup(); + int + sortPriority(const Entry* entry, const QString& host, const QString& submitUrl, const QString& baseSubmitUrl) const; + bool matchUrlScheme(const QString& url); + bool removeFirstDomain(QString& hostname); + Database* getDatabase(); private: - DatabaseTabWidget* const m_dbTabWidget; - bool m_dialogActive; + DatabaseTabWidget* const m_dbTabWidget; + bool m_dialogActive; }; #endif // BROWSERSERVICE_H diff --git a/src/browser/BrowserSettings.cpp b/src/browser/BrowserSettings.cpp old mode 100755 new mode 100644 index ecaf8e23e..4a75797fd --- a/src/browser/BrowserSettings.cpp +++ b/src/browser/BrowserSettings.cpp @@ -177,36 +177,48 @@ void BrowserSettings::setUpdateBinaryPath(bool enabled) config()->set("Browser/UpdateBinaryPath", enabled); } -bool BrowserSettings::chromeSupport() { +bool BrowserSettings::chromeSupport() +{ return m_hostInstaller.checkIfInstalled(HostInstaller::SupportedBrowsers::CHROME); } -void BrowserSettings::setChromeSupport(bool enabled) { - m_hostInstaller.installBrowser(HostInstaller::SupportedBrowsers::CHROME, enabled, supportBrowserProxy(), customProxyLocation()); +void BrowserSettings::setChromeSupport(bool enabled) +{ + m_hostInstaller.installBrowser( + HostInstaller::SupportedBrowsers::CHROME, enabled, supportBrowserProxy(), customProxyLocation()); } -bool BrowserSettings::chromiumSupport() { +bool BrowserSettings::chromiumSupport() +{ return m_hostInstaller.checkIfInstalled(HostInstaller::SupportedBrowsers::CHROMIUM); } -void BrowserSettings::setChromiumSupport(bool enabled) { - m_hostInstaller.installBrowser(HostInstaller::SupportedBrowsers::CHROMIUM, enabled, supportBrowserProxy(), customProxyLocation()); +void BrowserSettings::setChromiumSupport(bool enabled) +{ + m_hostInstaller.installBrowser( + HostInstaller::SupportedBrowsers::CHROMIUM, enabled, supportBrowserProxy(), customProxyLocation()); } -bool BrowserSettings::firefoxSupport() { +bool BrowserSettings::firefoxSupport() +{ return m_hostInstaller.checkIfInstalled(HostInstaller::SupportedBrowsers::FIREFOX); } -void BrowserSettings::setFirefoxSupport(bool enabled) { - m_hostInstaller.installBrowser(HostInstaller::SupportedBrowsers::FIREFOX, enabled, supportBrowserProxy(), customProxyLocation()); +void BrowserSettings::setFirefoxSupport(bool enabled) +{ + m_hostInstaller.installBrowser( + HostInstaller::SupportedBrowsers::FIREFOX, enabled, supportBrowserProxy(), customProxyLocation()); } -bool BrowserSettings::vivaldiSupport() { +bool BrowserSettings::vivaldiSupport() +{ return m_hostInstaller.checkIfInstalled(HostInstaller::SupportedBrowsers::VIVALDI); } -void BrowserSettings::setVivaldiSupport(bool enabled) { - m_hostInstaller.installBrowser(HostInstaller::SupportedBrowsers::VIVALDI, enabled, supportBrowserProxy(), customProxyLocation()); +void BrowserSettings::setVivaldiSupport(bool enabled) +{ + m_hostInstaller.installBrowser( + HostInstaller::SupportedBrowsers::VIVALDI, enabled, supportBrowserProxy(), customProxyLocation()); } bool BrowserSettings::passwordUseNumbers() diff --git a/src/browser/BrowserSettings.h b/src/browser/BrowserSettings.h old mode 100755 new mode 100644 index eb59fa5ac..ac4a84493 --- a/src/browser/BrowserSettings.h +++ b/src/browser/BrowserSettings.h @@ -20,9 +20,9 @@ #ifndef BROWSERSETTINGS_H #define BROWSERSETTINGS_H -#include "core/PasswordGenerator.h" -#include "core/PassphraseGenerator.h" #include "HostInstaller.h" +#include "core/PassphraseGenerator.h" +#include "core/PasswordGenerator.h" class BrowserSettings { @@ -30,9 +30,9 @@ public: static bool isEnabled(); static void setEnabled(bool enabled); - static bool showNotification(); //TODO!! + static bool showNotification(); // TODO!! static void setShowNotification(bool showNotification); - static bool bestMatchOnly(); //TODO!! + static bool bestMatchOnly(); // TODO!! static void setBestMatchOnly(bool bestMatchOnly); static bool unlockDatabase(); static void setUnlockDatabase(bool unlockDatabase); @@ -46,7 +46,7 @@ public: static void setAlwaysAllowAccess(bool alwaysAllowAccess); static bool alwaysAllowUpdate(); static void setAlwaysAllowUpdate(bool alwaysAllowUpdate); - static bool searchInAllDatabases();//TODO!! + static bool searchInAllDatabases(); // TODO!! static void setSearchInAllDatabases(bool searchInAllDatabases); static bool supportKphFields(); static void setSupportKphFields(bool supportKphFields); @@ -88,7 +88,7 @@ public: static void setPasswordEveryGroup(bool everyGroup); static bool passwordExcludeAlike(); static void setPasswordExcludeAlike(bool excludeAlike); - static int passwordLength(); + static int passwordLength(); static void setPasswordLength(int length); static PasswordGenerator::CharClasses passwordCharClasses(); static PasswordGenerator::GeneratorFlags passwordGeneratorFlags(); diff --git a/src/browser/HostInstaller.cpp b/src/browser/HostInstaller.cpp index 9b27ab1cf..95d202a22 100644 --- a/src/browser/HostInstaller.cpp +++ b/src/browser/HostInstaller.cpp @@ -18,43 +18,45 @@ #include "HostInstaller.h" #include "config-keepassx.h" +#include #include #include -#include #include #include -#include -#include #include +#include +#include const QString HostInstaller::HOST_NAME = "org.keepassxc.keepassxc_browser"; const QStringList HostInstaller::ALLOWED_ORIGINS = QStringList() - << "chrome-extension://iopaggbpplllidnfmcghoonnokmjoicf/" - << "chrome-extension://oboonakemofpalcgghocfoadofidjkkk/"; + << "chrome-extension://iopaggbpplllidnfmcghoonnokmjoicf/" + << "chrome-extension://oboonakemofpalcgghocfoadofidjkkk/"; -const QStringList HostInstaller::ALLOWED_EXTENSIONS = QStringList() - << "keepassxc-browser@keepassxc.org"; +const QStringList HostInstaller::ALLOWED_EXTENSIONS = QStringList() << "keepassxc-browser@keepassxc.org"; #if defined(Q_OS_OSX) - const QString HostInstaller::TARGET_DIR_CHROME = "/Library/Application Support/Google/Chrome/NativeMessagingHosts"; - const QString HostInstaller::TARGET_DIR_CHROMIUM = "/Library/Application Support/Chromium/NativeMessagingHosts"; - const QString HostInstaller::TARGET_DIR_FIREFOX = "/Library/Application Support/Mozilla/NativeMessagingHosts"; - const QString HostInstaller::TARGET_DIR_VIVALDI = "/Library/Application Support/Vivaldi/NativeMessagingHosts"; +const QString HostInstaller::TARGET_DIR_CHROME = "/Library/Application Support/Google/Chrome/NativeMessagingHosts"; +const QString HostInstaller::TARGET_DIR_CHROMIUM = "/Library/Application Support/Chromium/NativeMessagingHosts"; +const QString HostInstaller::TARGET_DIR_FIREFOX = "/Library/Application Support/Mozilla/NativeMessagingHosts"; +const QString HostInstaller::TARGET_DIR_VIVALDI = "/Library/Application Support/Vivaldi/NativeMessagingHosts"; #elif defined(Q_OS_LINUX) - const QString HostInstaller::TARGET_DIR_CHROME = "/.config/google-chrome/NativeMessagingHosts"; - const QString HostInstaller::TARGET_DIR_CHROMIUM = "/.config/chromium/NativeMessagingHosts"; - const QString HostInstaller::TARGET_DIR_FIREFOX = "/.mozilla/native-messaging-hosts"; - const QString HostInstaller::TARGET_DIR_VIVALDI = "/.config/vivaldi/NativeMessagingHosts"; +const QString HostInstaller::TARGET_DIR_CHROME = "/.config/google-chrome/NativeMessagingHosts"; +const QString HostInstaller::TARGET_DIR_CHROMIUM = "/.config/chromium/NativeMessagingHosts"; +const QString HostInstaller::TARGET_DIR_FIREFOX = "/.mozilla/native-messaging-hosts"; +const QString HostInstaller::TARGET_DIR_VIVALDI = "/.config/vivaldi/NativeMessagingHosts"; #elif defined(Q_OS_WIN) - const QString HostInstaller::TARGET_DIR_CHROME = "HKEY_CURRENT_USER\\Software\\Google\\Chrome\\NativeMessagingHosts\\" + HostInstaller::HOST_NAME; - const QString HostInstaller::TARGET_DIR_CHROMIUM = "HKEY_CURRENT_USER\\Software\\Chromium\\NativeMessagingHosts\\" + HostInstaller::HOST_NAME; - const QString HostInstaller::TARGET_DIR_FIREFOX = "HKEY_CURRENT_USER\\Software\\Mozilla\\NativeMessagingHosts\\" + HostInstaller::HOST_NAME; - const QString HostInstaller::TARGET_DIR_VIVALDI = "HKEY_CURRENT_USER\\Software\\Vivaldi\\NativeMessagingHosts\\" + HostInstaller::HOST_NAME; +const QString HostInstaller::TARGET_DIR_CHROME = + "HKEY_CURRENT_USER\\Software\\Google\\Chrome\\NativeMessagingHosts\\" + HostInstaller::HOST_NAME; +const QString HostInstaller::TARGET_DIR_CHROMIUM = + "HKEY_CURRENT_USER\\Software\\Chromium\\NativeMessagingHosts\\" + HostInstaller::HOST_NAME; +const QString HostInstaller::TARGET_DIR_FIREFOX = + "HKEY_CURRENT_USER\\Software\\Mozilla\\NativeMessagingHosts\\" + HostInstaller::HOST_NAME; +const QString HostInstaller::TARGET_DIR_VIVALDI = + "HKEY_CURRENT_USER\\Software\\Vivaldi\\NativeMessagingHosts\\" + HostInstaller::HOST_NAME; #endif HostInstaller::HostInstaller() { - } bool HostInstaller::checkIfInstalled(SupportedBrowsers browser) @@ -68,34 +70,39 @@ bool HostInstaller::checkIfInstalled(SupportedBrowsers browser) #endif } -void HostInstaller::installBrowser(SupportedBrowsers browser, const bool& enabled, const bool& proxy, const QString& location) +void HostInstaller::installBrowser(SupportedBrowsers browser, + const bool& enabled, + const bool& proxy, + const QString& location) { if (enabled) { - #ifdef Q_OS_WIN - // Create a registry key - QSettings settings(getTargetPath(browser), QSettings::NativeFormat); - if (!registryEntryFound(settings)) { - settings.setValue("Default", getPath(browser)); - } - #endif - // Always create the script file - QJsonObject script = constructFile(browser, proxy, location); - if (!saveFile(browser, script)) { - QMessageBox::critical(0, tr("KeePassXC: Cannot save file!"), - tr("Cannot save the native messaging script file."), QMessageBox::Ok); - } - } else { - // Remove the script file - QString fileName = getPath(browser); - QFile::remove(fileName); - #ifdef Q_OS_WIN - // Remove the registry entry - QSettings settings(getTargetPath(browser), QSettings::NativeFormat); - if (registryEntryFound(settings)) { - settings.remove("Default"); - } - #endif - } +#ifdef Q_OS_WIN + // Create a registry key + QSettings settings(getTargetPath(browser), QSettings::NativeFormat); + if (!registryEntryFound(settings)) { + settings.setValue("Default", getPath(browser)); + } +#endif + // Always create the script file + QJsonObject script = constructFile(browser, proxy, location); + if (!saveFile(browser, script)) { + QMessageBox::critical(0, + tr("KeePassXC: Cannot save file!"), + tr("Cannot save the native messaging script file."), + QMessageBox::Ok); + } + } else { + // Remove the script file + QString fileName = getPath(browser); + QFile::remove(fileName); +#ifdef Q_OS_WIN + // Remove the registry entry + QSettings settings(getTargetPath(browser), QSettings::NativeFormat); + if (registryEntryFound(settings)) { + settings.remove("Default"); + } +#endif + } } void HostInstaller::updateBinaryPaths(const bool& proxy, const QString& location) @@ -110,22 +117,32 @@ void HostInstaller::updateBinaryPaths(const bool& proxy, const QString& location QString HostInstaller::getTargetPath(SupportedBrowsers browser) const { switch (browser) { - case SupportedBrowsers::CHROME: return HostInstaller::TARGET_DIR_CHROME; - case SupportedBrowsers::CHROMIUM: return HostInstaller::TARGET_DIR_CHROMIUM; - case SupportedBrowsers::FIREFOX: return HostInstaller::TARGET_DIR_FIREFOX; - case SupportedBrowsers::VIVALDI: return HostInstaller::TARGET_DIR_VIVALDI; - default: return QString(); + case SupportedBrowsers::CHROME: + return HostInstaller::TARGET_DIR_CHROME; + case SupportedBrowsers::CHROMIUM: + return HostInstaller::TARGET_DIR_CHROMIUM; + case SupportedBrowsers::FIREFOX: + return HostInstaller::TARGET_DIR_FIREFOX; + case SupportedBrowsers::VIVALDI: + return HostInstaller::TARGET_DIR_VIVALDI; + default: + return QString(); } } QString HostInstaller::getBrowserName(SupportedBrowsers browser) const { switch (browser) { - case SupportedBrowsers::CHROME: return "chrome"; - case SupportedBrowsers::CHROMIUM: return "chromium"; - case SupportedBrowsers::FIREFOX: return "firefox"; - case SupportedBrowsers::VIVALDI: return "vivaldi"; - default: return QString(); + case SupportedBrowsers::CHROME: + return "chrome"; + case SupportedBrowsers::CHROMIUM: + return "chromium"; + case SupportedBrowsers::FIREFOX: + return "firefox"; + case SupportedBrowsers::VIVALDI: + return "vivaldi"; + default: + return QString(); } } @@ -142,7 +159,7 @@ QString HostInstaller::getPath(SupportedBrowsers browser) const } QString winPath = QString("%1/%2_%3.json").arg(userPath, HostInstaller::HOST_NAME, getBrowserName(browser)); - winPath.replace("/","\\"); + winPath.replace("/", "\\"); return winPath; #else QString path = getTargetPath(browser); @@ -184,16 +201,16 @@ QJsonObject HostInstaller::constructFile(SupportedBrowsers browser, const bool& path = QFileInfo(QCoreApplication::applicationFilePath()).absoluteFilePath(); } #ifdef Q_OS_WIN - path.replace("/","\\"); + path.replace("/", "\\"); #endif -#endif // #ifdef KEEPASSXC_DIST_APPIMAGE +#endif // #ifdef KEEPASSXC_DIST_APPIMAGE QJsonObject script; - script["name"] = HostInstaller::HOST_NAME; - script["description"] = "KeePassXC integration with native messaging support"; - script["path"] = path; - script["type"] = "stdio"; + script["name"] = HostInstaller::HOST_NAME; + script["description"] = "KeePassXC integration with native messaging support"; + script["path"] = path; + script["type"] = "stdio"; QJsonArray arr; if (browser == SupportedBrowsers::FIREFOX) { diff --git a/src/browser/HostInstaller.h b/src/browser/HostInstaller.h index c3fc85620..2fac0609d 100644 --- a/src/browser/HostInstaller.h +++ b/src/browser/HostInstaller.h @@ -19,8 +19,8 @@ #ifndef HOSTINSTALLER_H #define HOSTINSTALLER_H -#include #include +#include #include class HostInstaller : public QObject @@ -28,27 +28,31 @@ class HostInstaller : public QObject Q_OBJECT public: - enum SupportedBrowsers : int { - CHROME = 0, - CHROMIUM = 1, - FIREFOX = 2, - VIVALDI = 3 + enum SupportedBrowsers : int + { + CHROME = 0, + CHROMIUM = 1, + FIREFOX = 2, + VIVALDI = 3 }; public: HostInstaller(); bool checkIfInstalled(SupportedBrowsers browser); - void installBrowser(SupportedBrowsers browser, const bool& enabled, const bool& proxy = false, const QString& location = ""); + void installBrowser(SupportedBrowsers browser, + const bool& enabled, + const bool& proxy = false, + const QString& location = ""); void updateBinaryPaths(const bool& proxy, const QString& location = ""); private: - QString getTargetPath(SupportedBrowsers browser) const; - QString getBrowserName(SupportedBrowsers browser) const; - QString getPath(SupportedBrowsers browser) const; - QString getInstallDir(SupportedBrowsers browser) const; + QString getTargetPath(SupportedBrowsers browser) const; + QString getBrowserName(SupportedBrowsers browser) const; + QString getPath(SupportedBrowsers browser) const; + QString getInstallDir(SupportedBrowsers browser) const; QJsonObject constructFile(SupportedBrowsers browser, const bool& proxy, const QString& location); - bool registryEntryFound(const QSettings& settings); - bool saveFile(SupportedBrowsers browser, const QJsonObject& script); + bool registryEntryFound(const QSettings& settings); + bool saveFile(SupportedBrowsers browser, const QJsonObject& script); private: static const QString HOST_NAME; diff --git a/src/browser/NativeMessagingBase.cpp b/src/browser/NativeMessagingBase.cpp index f61a36045..64a6df484 100644 --- a/src/browser/NativeMessagingBase.cpp +++ b/src/browser/NativeMessagingBase.cpp @@ -20,9 +20,9 @@ #include #if defined(Q_OS_UNIX) && !defined(Q_OS_LINUX) -#include #include #include +#include #include #endif @@ -51,7 +51,7 @@ void NativeMessagingBase::newNativeMessage() { #if defined(Q_OS_UNIX) && !defined(Q_OS_LINUX) struct kevent ev[1]; - struct timespec ts = { 5, 0 }; + struct timespec ts = {5, 0}; int fd = kqueue(); if (fd == -1) { @@ -123,7 +123,8 @@ void NativeMessagingBase::sendReply(const QString& reply) if (!reply.isEmpty()) { QByteArray bytes = reply.toUtf8(); uint len = bytes.size(); - std::cout << char(((len>>0) & 0xFF)) << char(((len>>8) & 0xFF)) << char(((len>>16) & 0xFF)) << char(((len>>24) & 0xFF)); + std::cout << char(((len >> 0) & 0xFF)) << char(((len >> 8) & 0xFF)) << char(((len >> 16) & 0xFF)) + << char(((len >> 24) & 0xFF)); std::cout << reply.toStdString() << std::flush; } } @@ -136,7 +137,7 @@ QString NativeMessagingBase::getLocalServerPath() const // Use XDG_RUNTIME_DIR instead of /tmp/ if it's available QString path = QStandardPaths::writableLocation(QStandardPaths::RuntimeLocation) + "/kpxc_server"; return path.isEmpty() ? "/tmp/kpxc_server" : path; -#else // Q_OS_MAC and others +#else // Q_OS_MAC and others return "/tmp/kpxc_server"; #endif } diff --git a/src/browser/NativeMessagingBase.h b/src/browser/NativeMessagingBase.h index 4253b7585..e9ee2cc73 100644 --- a/src/browser/NativeMessagingBase.h +++ b/src/browser/NativeMessagingBase.h @@ -19,16 +19,16 @@ #ifndef NATIVEMESSAGINGBASE_H #define NATIVEMESSAGINGBASE_H -#include -#include -#include +#include #include -#include -#include -#include +#include +#include #include #include -#include +#include +#include +#include +#include #include #include @@ -41,21 +41,21 @@ public: ~NativeMessagingBase() = default; protected slots: - void newNativeMessage(); + void newNativeMessage(); protected: - virtual void readLength() = 0; - virtual void readStdIn(const quint32 length) = 0; - void readNativeMessages(); - QString jsonToString(const QJsonObject& json) const; - void sendReply(const QJsonObject& json); - void sendReply(const QString& reply); - QString getLocalServerPath() const; + virtual void readLength() = 0; + virtual void readStdIn(const quint32 length) = 0; + void readNativeMessages(); + QString jsonToString(const QJsonObject& json) const; + void sendReply(const QJsonObject& json); + void sendReply(const QString& reply); + QString getLocalServerPath() const; protected: - QAtomicInteger m_running; + QAtomicInteger m_running; QSharedPointer m_notifier; - QFuture m_future; + QFuture m_future; }; -#endif // NATIVEMESSAGINGBASE_H +#endif // NATIVEMESSAGINGBASE_H diff --git a/src/browser/NativeMessagingHost.cpp b/src/browser/NativeMessagingHost.cpp old mode 100755 new mode 100644 index 0101e9444..7c26ea085 --- a/src/browser/NativeMessagingHost.cpp +++ b/src/browser/NativeMessagingHost.cpp @@ -16,18 +16,18 @@ * along with this program. If not, see . */ +#include "NativeMessagingHost.h" +#include "BrowserSettings.h" +#include "sodium.h" #include #include #include -#include "sodium.h" -#include "NativeMessagingHost.h" -#include "BrowserSettings.h" -NativeMessagingHost::NativeMessagingHost(DatabaseTabWidget* parent) : - NativeMessagingBase(), - m_mutex(QMutex::Recursive), - m_browserClients(m_browserService), - m_browserService(parent) +NativeMessagingHost::NativeMessagingHost(DatabaseTabWidget* parent) + : NativeMessagingBase() + , m_mutex(QMutex::Recursive) + , m_browserClients(m_browserService) + , m_browserService(parent) { m_localServer.reset(new QLocalServer(this)); m_localServer->setSocketOptions(QLocalServer::UserAccessOption); @@ -61,12 +61,14 @@ void NativeMessagingHost::run() // Update KeePassXC/keepassxc-proxy binary paths to Native Messaging scripts if (BrowserSettings::updateBinaryPath()) { - BrowserSettings::updateBinaryPaths(BrowserSettings::useCustomProxy() ? BrowserSettings::customProxyLocation() : ""); + BrowserSettings::updateBinaryPaths(BrowserSettings::useCustomProxy() ? BrowserSettings::customProxyLocation() + : ""); } m_running.store(true); #ifdef Q_OS_WIN - m_future = QtConcurrent::run(this, static_cast(&NativeMessagingHost::readNativeMessages)); + m_future = + QtConcurrent::run(this, static_cast(&NativeMessagingHost::readNativeMessages)); #endif if (BrowserSettings::supportBrowserProxy()) { @@ -101,7 +103,7 @@ void NativeMessagingHost::readLength() if (!std::cin.eof() && length > 0) { readStdIn(length); } else { - m_notifier->setEnabled(false); + m_notifier->setEnabled(false); } } diff --git a/src/browser/NativeMessagingHost.h b/src/browser/NativeMessagingHost.h old mode 100755 new mode 100644 index 80825237b..0239acd3a --- a/src/browser/NativeMessagingHost.h +++ b/src/browser/NativeMessagingHost.h @@ -19,9 +19,9 @@ #ifndef NATIVEMESSAGINGHOST_H #define NATIVEMESSAGINGHOST_H -#include "NativeMessagingBase.h" #include "BrowserClients.h" #include "BrowserService.h" +#include "NativeMessagingBase.h" #include "gui/DatabaseTabWidget.h" class NativeMessagingHost : public NativeMessagingBase @@ -31,37 +31,37 @@ class NativeMessagingHost : public NativeMessagingBase typedef QList SocketList; public: - explicit NativeMessagingHost(DatabaseTabWidget* parent = 0); + explicit NativeMessagingHost(DatabaseTabWidget* parent = 0); ~NativeMessagingHost(); - int init(); - void run(); - void stop(); + int init(); + void run(); + void stop(); public slots: - void removeSharedEncryptionKeys(); - void removeStoredPermissions(); + void removeSharedEncryptionKeys(); + void removeStoredPermissions(); signals: - void quit(); + void quit(); private: - void readLength(); - void readStdIn(const quint32 length); - void sendReplyToAllClients(const QJsonObject& json); + void readLength(); + void readStdIn(const quint32 length); + void sendReplyToAllClients(const QJsonObject& json); private slots: - void databaseLocked(); - void databaseUnlocked(); - void newLocalConnection(); - void newLocalMessage(); - void disconnectSocket(); + void databaseLocked(); + void databaseUnlocked(); + void newLocalConnection(); + void newLocalMessage(); + void disconnectSocket(); private: - QMutex m_mutex; - BrowserClients m_browserClients; - BrowserService m_browserService; - QSharedPointer m_localServer; - SocketList m_socketList; + QMutex m_mutex; + BrowserClients m_browserClients; + BrowserService m_browserService; + QSharedPointer m_localServer; + SocketList m_socketList; }; #endif // NATIVEMESSAGINGHOST_H diff --git a/src/browser/Variant.h b/src/browser/Variant.h index e467b4211..8acdbaa56 100644 --- a/src/browser/Variant.h +++ b/src/browser/Variant.h @@ -20,6 +20,7 @@ #include -QVariantMap qo2qv(const QObject* object, const QStringList& ignoredProperties = QStringList(QString(QLatin1String("objectName")))); +QVariantMap qo2qv(const QObject* object, + const QStringList& ignoredProperties = QStringList(QString(QLatin1String("objectName")))); #endif // VARIANT_H diff --git a/src/cli/Diceware.cpp b/src/cli/Diceware.cpp index c71b57d7e..4cdda0a73 100644 --- a/src/cli/Diceware.cpp +++ b/src/cli/Diceware.cpp @@ -42,14 +42,15 @@ int Diceware::execute(const QStringList& arguments) QCommandLineParser parser; parser.setApplicationDescription(this->description); - QCommandLineOption words(QStringList() << "W" << "words", - QObject::tr("Word count for the diceware passphrase."), - QObject::tr("count")); + QCommandLineOption words(QStringList() << "W" + << "words", + QObject::tr("Word count for the diceware passphrase."), + QObject::tr("count")); parser.addOption(words); QCommandLineOption wordlistFile(QStringList() << "w" - << "word-list", - QObject::tr("Wordlist for the diceware generator.\n[Default: EFF English]"), - QObject::tr("path")); + << "word-list", + QObject::tr("Wordlist for the diceware generator.\n[Default: EFF English]"), + QObject::tr("path")); parser.addOption(wordlistFile); parser.process(arguments); @@ -78,7 +79,7 @@ int Diceware::execute(const QStringList& arguments) outputTextStream << parser.helpText().replace("keepassxc-cli", "keepassxc-cli diceware"); return EXIT_FAILURE; } - + QString password = dicewareGenerator.generatePassphrase(); outputTextStream << password << endl; diff --git a/src/cli/Edit.cpp b/src/cli/Edit.cpp index 967ddd8ed..056a0a595 100644 --- a/src/cli/Edit.cpp +++ b/src/cli/Edit.cpp @@ -115,8 +115,9 @@ int Edit::execute(const QStringList& arguments) return EXIT_FAILURE; } - if (parser.value("username").isEmpty() && parser.value("url").isEmpty() && parser.value("title").isEmpty() && - !parser.isSet(prompt) && !parser.isSet(generate)) { + if (parser.value("username").isEmpty() && parser.value("url").isEmpty() && parser.value("title").isEmpty() + && !parser.isSet(prompt) + && !parser.isSet(generate)) { qCritical("Not changing any field for entry %s.", qPrintable(entryPath)); return EXIT_FAILURE; } diff --git a/src/cli/Extract.cpp b/src/cli/Extract.cpp index b48d5a6aa..089a784d2 100644 --- a/src/cli/Extract.cpp +++ b/src/cli/Extract.cpp @@ -84,8 +84,8 @@ int Extract::execute(const QStringList& arguments) if (fileKey.type() != FileKey::Hashed) { errorTextStream << 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."); + "unsupported in the future.\n\n" + "Please consider generating a new key file."); errorTextStream << endl; } diff --git a/src/cli/Generate.cpp b/src/cli/Generate.cpp index eb8fea5e8..45b67259c 100644 --- a/src/cli/Generate.cpp +++ b/src/cli/Generate.cpp @@ -42,24 +42,20 @@ int Generate::execute(const QStringList& arguments) QCommandLineParser parser; parser.setApplicationDescription(this->description); - QCommandLineOption len(QStringList() << "L" << "length", - QObject::tr("Length of the generated password."), - QObject::tr("length")); + QCommandLineOption len(QStringList() << "L" + << "length", + QObject::tr("Length of the generated password."), + QObject::tr("length")); parser.addOption(len); - QCommandLineOption lower(QStringList() << "l", - QObject::tr("Use lowercase characters in the generated password.")); + QCommandLineOption lower(QStringList() << "l", QObject::tr("Use lowercase characters in the generated password.")); parser.addOption(lower); - QCommandLineOption upper(QStringList() << "u", - QObject::tr("Use uppercase characters in the generated password.")); + QCommandLineOption upper(QStringList() << "u", QObject::tr("Use uppercase characters in the generated password.")); parser.addOption(upper); - QCommandLineOption numeric(QStringList() << "n", - QObject::tr("Use numbers in the generated password.")); + QCommandLineOption numeric(QStringList() << "n", QObject::tr("Use numbers in the generated password.")); parser.addOption(numeric); - QCommandLineOption special(QStringList() << "s", - QObject::tr("Use special characters in the generated password.")); + QCommandLineOption special(QStringList() << "s", QObject::tr("Use special characters in the generated password.")); parser.addOption(special); - QCommandLineOption extended(QStringList() << "e", - QObject::tr("Use extended ASCII in the generated password.")); + QCommandLineOption extended(QStringList() << "e", QObject::tr("Use extended ASCII in the generated password.")); parser.addOption(extended); parser.process(arguments); @@ -81,19 +77,19 @@ int Generate::execute(const QStringList& arguments) PasswordGenerator::CharClasses classes = 0x0; if (parser.isSet(lower)) { - classes |= PasswordGenerator::LowerLetters; + classes |= PasswordGenerator::LowerLetters; } if (parser.isSet(upper)) { - classes |= PasswordGenerator::UpperLetters; + classes |= PasswordGenerator::UpperLetters; } if (parser.isSet(numeric)) { - classes |= PasswordGenerator::Numbers; + classes |= PasswordGenerator::Numbers; } if (parser.isSet(special)) { - classes |= PasswordGenerator::SpecialCharacters; + classes |= PasswordGenerator::SpecialCharacters; } if (parser.isSet(extended)) { - classes |= PasswordGenerator::EASCII; + classes |= PasswordGenerator::EASCII; } passwordGenerator.setCharClasses(classes); diff --git a/src/cli/Show.cpp b/src/cli/Show.cpp index 54561b1f7..be188c75c 100644 --- a/src/cli/Show.cpp +++ b/src/cli/Show.cpp @@ -49,12 +49,14 @@ int Show::execute(const QStringList& arguments) QObject::tr("Key file of the database."), QObject::tr("path")); parser.addOption(keyFile); - QCommandLineOption attributes(QStringList() << "a" - << "attributes", - QObject::tr("Names of the attributes to show. " - "This option can be specified more than once, with each attribute shown one-per-line in the given order. " - "If no attributes are specified, a summary of the default attributes is given."), - QObject::tr("attribute")); + QCommandLineOption attributes( + QStringList() << "a" + << "attributes", + QObject::tr( + "Names of the attributes to show. " + "This option can be specified more than once, with each attribute shown one-per-line in the given order. " + "If no attributes are specified, a summary of the default attributes is given."), + QObject::tr("attribute")); parser.addOption(attributes); parser.addPositionalArgument("entry", QObject::tr("Name of the entry to show.")); parser.process(arguments); 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 #include - /** * 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 std::result_of::type waitForFuture(QFuture::type> future) -{ - QEventLoop loop; - QFutureWatcher::type> watcher; - QObject::connect(&watcher, SIGNAL(finished()), &loop, SLOT(quit())); - watcher.setFuture(future); - loop.exec(); - return future.result(); -} + /** + * Wait for the given future without blocking the event loop. + * + * @param future future to wait for + * @return async task result + */ + template + typename std::result_of::type + waitForFuture(QFuture::type> future) + { + QEventLoop loop; + QFutureWatcher::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 std::result_of::type runAndWaitForFuture(FunctionObject task) -{ - return waitForFuture(QtConcurrent::run(task)); -} + /** + * 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 std::result_of::type runAndWaitForFuture(FunctionObject task) + { + return waitForFuture(QtConcurrent::run(task)); + } -}; // namespace AsyncTask +}; // namespace AsyncTask -#endif //KEEPASSXC_ASYNCTASK_HPP +#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 #include #include -#include #include +#include 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 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 #include +#include #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 #include +#include #include #include typedef QStringList CsvRow; typedef QList 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 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 #include -#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); - 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 +#include #include #include -#include namespace Endian { -template -SizedQInt bytesToSizedInt(const QByteArray& ba, QSysInfo::Endian byteOrder) -{ - Q_ASSERT(ba.size() == sizeof(SizedQInt)); + template SizedQInt bytesToSizedInt(const QByteArray& ba, QSysInfo::Endian byteOrder) + { + Q_ASSERT(ba.size() == sizeof(SizedQInt)); - if (byteOrder == QSysInfo::LittleEndian) { - return qFromLittleEndian(reinterpret_cast(ba.constData())); - } - return qFromBigEndian(reinterpret_cast(ba.constData())); -} - -template -SizedQInt readSizedInt(QIODevice* device, QSysInfo::Endian byteOrder, bool* ok) -{ - QByteArray ba = device->read(sizeof(SizedQInt)); - - if (ba.size() != sizeof(SizedQInt)) { - *ok = false; - return 0; - } - *ok = true; - return bytesToSizedInt(ba, byteOrder); -} - -template -QByteArray sizedIntToBytes(SizedQInt num, QSysInfo::Endian byteOrder) -{ - QByteArray ba; - ba.resize(sizeof(SizedQInt)); - - if (byteOrder == QSysInfo::LittleEndian) { - qToLittleEndian(num, reinterpret_cast(ba.data())); - } else { - qToBigEndian(num, reinterpret_cast(ba.data())); + if (byteOrder == QSysInfo::LittleEndian) { + return qFromLittleEndian(reinterpret_cast(ba.constData())); + } + return qFromBigEndian(reinterpret_cast(ba.constData())); } - return ba; -} + template SizedQInt readSizedInt(QIODevice* device, QSysInfo::Endian byteOrder, bool* ok) + { + QByteArray ba = device->read(sizeof(SizedQInt)); -template -bool writeSizedInt(SizedQInt num, QIODevice* device, QSysInfo::Endian byteOrder) -{ - QByteArray ba = sizedIntToBytes(num, byteOrder); - qint64 bytesWritten = device->write(ba); - return (bytesWritten == ba.size()); -} + if (ba.size() != sizeof(SizedQInt)) { + *ok = false; + return 0; + } + *ok = true; + return bytesToSizedInt(ba, byteOrder); + } + + template QByteArray sizedIntToBytes(SizedQInt num, QSysInfo::Endian byteOrder) + { + QByteArray ba; + ba.resize(sizeof(SizedQInt)); + + if (byteOrder == QSysInfo::LittleEndian) { + qToLittleEndian(num, reinterpret_cast(ba.data())); + } else { + qToBigEndian(num, reinterpret_cast(ba.data())); + } + + return ba; + } + + template bool writeSizedInt(SizedQInt num, QIODevice* device, QSysInfo::Endian byteOrder) + { + QByteArray ba = sizedIntToBytes(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 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 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 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& 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 #include +#include 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:(?[TUPANI])@(?[TUPANIO]):(?[^}]+)\\}", - QRegularExpression::CaseInsensitiveOption); + "\\{REF:(?[TUPANI])@(?[TUPANIO]):(?[^}]+)\\}", + 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 EntrySearcher::search(const QString& searchTerm, const Group* group, - Qt::CaseSensitivity caseSensitivity) +QList EntrySearcher::search(const QString& searchTerm, const Group* group, Qt::CaseSensitivity caseSensitivity) { if (!group->resolveSearchingEnabled()) { return QList(); @@ -30,14 +29,14 @@ QList EntrySearcher::search(const QString& searchTerm, const Group* grou return searchEntries(searchTerm, group, caseSensitivity); } -QList EntrySearcher::searchEntries(const QString& searchTerm, const Group* group, - Qt::CaseSensitivity caseSensitivity) +QList +EntrySearcher::searchEntries(const QString& searchTerm, const Group* group, Qt::CaseSensitivity caseSensitivity) { QList searchResult; const QList entryList = group->entries(); for (Entry* entry : entryList) { - searchResult.append(matchEntry(searchTerm, entry, caseSensitivity)); + searchResult.append(matchEntry(searchTerm, entry, caseSensitivity)); } const QList children = group->children(); @@ -54,8 +53,7 @@ QList EntrySearcher::searchEntries(const QString& searchTerm, const Grou return searchResult; } -QList EntrySearcher::matchEntry(const QString& searchTerm, Entry* entry, - Qt::CaseSensitivity caseSensitivity) +QList 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 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 - 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 #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 pngSizes = { 16, 22, 24, 32, 48, 64, 128 }; + const QList 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 pngSizes = { 16, 22, 24, 32, 48, 64, 128 }; + const QList 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 #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 struct AddConst { typedef const T Type; }; +template struct AddConst +{ + typedef const T Type; +}; // this adds const to non-const objects (like std::as_const) -template -constexpr typename AddConst::Type& asConst(T &t) noexcept { return t; } +template constexpr typename AddConst::Type& asConst(T& t) noexcept +{ + return t; +} // prevent rvalue arguments: -template -void asConst(const T&&) = delete; +template 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::CloneNewUuid | Group::CloneResetTimeInfo | Group::CloneIncludeEntries); -Entry::CloneFlags Group::DefaultEntryCloneFlags = static_cast( - Entry::CloneNewUuid | Entry::CloneResetTimeInfo); +Group::CloneFlags Group::DefaultCloneFlags = + static_cast(Group::CloneNewUuid | Group::CloneResetTimeInfo | Group::CloneIncludeEntries); +Entry::CloneFlags Group::DefaultEntryCloneFlags = + static_cast(Entry::CloneNewUuid | Entry::CloneResetTimeInfo); Group::Group() : m_customData(new CustomData(this)) @@ -81,7 +81,8 @@ Group* Group::createRecycleBin() return recycleBin; } -template inline bool Group::set(P& property, const V& value) { +template 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 #include +#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 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 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 -template -class ListDeleter +template class ListDeleter { public: - inline explicit ListDeleter(QList* list) : m_list(list) {} - inline ~ListDeleter() { + inline explicit ListDeleter(QList* 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 data, QString flavor) { +QVariant MacPasteboard::convertToMime(const QString& mimetype, QList 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 } 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 MacPasteboard::convertFromMime(const QString&, QVariant data, QString flavor) { +QList MacPasteboard::convertFromMime(const QString&, QVariant data, QString flavor) +{ QList ret; QString string = data.toString(); if (flavor == QLatin1String("public.utf8-plain-text")) @@ -91,4 +97,3 @@ QList 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 -#include #include +#include 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 data, QString flav) override; - QList convertFromMime(const QString &mime, QVariant data, QString flav) override; + QString flavorFor(const QString& mime) override; + QVariant convertToMime(const QString& mime, QList data, QString flav) override; + QList 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 . */ -#include #include "Metadata.h" +#include #include "core/Entry.h" #include "core/Group.h" @@ -61,13 +61,13 @@ template bool Metadata::set(P& property, const V& value) property = value; emit modified(); return true; - } - else { + } else { return false; } } -template bool Metadata::set(P& property, const V& value, QDateTime& dateTime) { +template bool Metadata::set(P& property, const V& value, QDateTime& dateTime) +{ if (property != value) { property = value; if (m_updateDatetime) { @@ -75,8 +75,7 @@ template 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 #include -#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 #include #include +#include -#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 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 #include -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 #include -#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(parent->winId()), - &GUID_LIDSWITCH_STATE_CHANGE, DEVICE_NOTIFY_WINDOW_HANDLE); + reinterpret_cast(parent->winId()), &GUID_LIDSWITCH_STATE_CHANGE, DEVICE_NOTIFY_WINDOW_HANDLE); m_powerNotificationHandle = reinterpret_cast(hPnotify); // This call requests a notification for session changes - if (!WTSRegisterSessionNotification( - reinterpret_cast(parent->winId()), - NOTIFY_FOR_THIS_SESSION)) { + if (!WTSRegisterSessionNotification(reinterpret_cast(parent->winId()), NOTIFY_FOR_THIS_SESSION)) { } } ScreenLockListenerWin::~ScreenLockListenerWin() { - HWND h= reinterpret_cast(static_cast(parent())->winId()); + HWND h = reinterpret_cast(static_cast(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 #include #include -#include #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 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 -#include #include +#include #include #include #include #ifdef Q_OS_WIN +#include // for SetSecurityInfo() #include // for Sleep(), SetDllDirectoryA(), SetSearchPathMode(), ... -#include // for SetSecurityInfo() #endif #ifdef Q_OS_UNIX @@ -47,314 +47,298 @@ #endif #ifdef HAVE_PT_DENY_ATTACH -#include #include +#include #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; - while ((size >= 1024) && (i < maxI)) { - size /= 1024; - i++; + QStringList units = QStringList() << "B" + << "KiB" + << "MiB" + << "GiB"; + int i = 0; + int maxI = units.size() - 1; + + 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); + 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); - 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; + if (readResult == -1) { + return false; + } else { + result.resize(static_cast(readBytes)); + data = result; + return true; } - } while (readResult > 0); - - if (readResult == -1) { - return false; } - else { - result.resize(static_cast(readBytes)); - data = result; - return true; + + QString imageReaderFilter() + { + const QList 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; + } + } + + formatsStringList.append("*." + QString::fromLatin1(format).toLower()); + } + + return formatsStringList.join(" "); } -} -QString imageReaderFilter() -{ - const QList 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; + bool isHex(const QByteArray& ba) + { + for (char c : ba) { + if (!((c >= '0' && c <= '9') || (c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F'))) { + return false; } } - formatsStringList.append("*." + QString::fromLatin1(format).toLower()); + return true; } - return formatsStringList.join(" "); -} + bool isBase64(const QByteArray& ba) + { + QRegExp regexp( + "^(?:[a-z0-9+/]{4})*(?:[a-z0-9+/]{3}=|[a-z0-9+/]{2}==)?$", Qt::CaseInsensitive, QRegExp::RegExp2); -bool isHex(const QByteArray& ba) -{ - for (char c : ba) { - if ( !( (c >= '0' && c <= '9') || (c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F') ) ) { - return false; + QString base64 = QString::fromLatin1(ba.constData(), ba.size()); + + return regexp.exactMatch(base64); + } + + void sleep(int ms) + { + Q_ASSERT(ms >= 0); + + if (ms == 0) { + return; } - } - - 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); - - QString base64 = QString::fromLatin1(ba.constData(), ba.size()); - - return regexp.exactMatch(base64); -} - -void sleep(int ms) -{ - Q_ASSERT(ms >= 0); - - 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(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; + } -void disableCoreDumps() -{ - // default to true - // there is no point in printing a warning if this is not implemented on the platform - bool success = true; + QElapsedTimer timer; + timer.start(); + + if (ms <= 50) { + QCoreApplication::processEvents(QEventLoop::AllEvents, ms); + sleep(qMax(ms - static_cast(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; #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; + // Process token and user + HANDLE hToken = nullptr; + PTOKEN_USER pTokenUser = nullptr; + DWORD cbBufferSize = 0; - // Access control list - PACL pACL = nullptr; - DWORD cbACL = 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; - } + // 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(HeapAlloc(GetProcessHeap(), 0, cbBufferSize)); - if (pTokenUser == nullptr) { - goto Cleanup; - } + pTokenUser = static_cast(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(HeapAlloc(GetProcessHeap(), 0, cbACL)); - if (pACL == nullptr) { - goto Cleanup; - } + // Create and initialize an ACL + pACL = static_cast(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 - ); + // 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: + Cleanup: - if (pACL != nullptr) { - HeapFree(GetProcessHeap(), 0, pACL); - } - if (pTokenUser != nullptr) { - HeapFree(GetProcessHeap(), 0, pTokenUser); - } - if (hToken != nullptr) { - CloseHandle(hToken); - } + 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 -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 + 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 #include #include -#include #include +#include #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> Translator::availableLanguages() #ifdef QT_DEBUG QString("%1/share/translations").arg(KEEPASSX_BINARY_DIR), #endif - filePath()->dataPath("translations") - }; + filePath()->dataPath("translations")}; - QList > languages; + QList> languages; languages.append(QPair("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 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 -#include #include +#include class Uuid { diff --git a/src/crypto/Crypto.cpp b/src/crypto/Crypto.cpp index 7ba78a6b3..c8bac11e5 100644 --- a/src/crypto/Crypto.cpp +++ b/src/crypto/Crypto.cpp @@ -116,7 +116,8 @@ bool Crypto::checkAlgorithms() bool Crypto::selfTest() { - return testSha256() && testSha512() && testAes256Cbc() && testAes256Ecb() && testTwofish() && testSalsa20() && testChaCha20(); + return testSha256() && testSha512() && testAes256Cbc() && testAes256Ecb() && testTwofish() && testSalsa20() + && testChaCha20(); } void Crypto::raiseError(const QString& str) @@ -127,8 +128,8 @@ void Crypto::raiseError(const QString& str) bool Crypto::testSha256() { - QByteArray sha256Test = CryptoHash::hash("abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq", - CryptoHash::Sha256); + QByteArray sha256Test = + CryptoHash::hash("abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq", CryptoHash::Sha256); if (sha256Test != QByteArray::fromHex("248D6A61D20638B8E5C026930C3E6039A33CE45964FF2167F6ECEDD419DB06C1")) { raiseError("SHA-256 mismatch."); @@ -140,10 +141,11 @@ bool Crypto::testSha256() bool Crypto::testSha512() { - QByteArray sha512Test = CryptoHash::hash("abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq", - CryptoHash::Sha512); + QByteArray sha512Test = + CryptoHash::hash("abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq", CryptoHash::Sha512); - if (sha512Test != QByteArray::fromHex("204a8fc6dda82f0a0ced7beb8e08a41657c16ef468b228a8279be331a703c33596fd15c13b1b07f9aa1d3bea57789ca031ad85c7a71dd70354ec631238ca3445")) { + if (sha512Test != QByteArray::fromHex("204a8fc6dda82f0a0ced7beb8e08a41657c16ef468b228a8279be331a703c33596fd15c13b1b" + "07f9aa1d3bea57789ca031ad85c7a71dd70354ec631238ca3445")) { raiseError("SHA-512 mismatch."); return false; } @@ -262,7 +264,6 @@ bool Crypto::testTwofish() return false; } - SymmetricCipher twofishDecrypt(SymmetricCipher::Twofish, SymmetricCipher::Cbc, SymmetricCipher::Decrypt); if (!twofishDecrypt.init(key, iv)) { raiseError(twofishEncrypt.errorString()); @@ -289,8 +290,7 @@ bool Crypto::testSalsa20() QByteArray salsa20Cipher = QByteArray::fromHex("B4C0AFA503BE7FC29A62058166D56F8F"); bool ok; - SymmetricCipher salsa20Stream(SymmetricCipher::Salsa20, SymmetricCipher::Stream, - SymmetricCipher::Encrypt); + SymmetricCipher salsa20Stream(SymmetricCipher::Salsa20, SymmetricCipher::Stream, SymmetricCipher::Encrypt); if (!salsa20Stream.init(salsa20Key, salsa20iv)) { raiseError(salsa20Stream.errorString()); return false; @@ -309,15 +309,17 @@ bool Crypto::testSalsa20() return true; } -bool Crypto::testChaCha20() { +bool Crypto::testChaCha20() +{ QByteArray chacha20Key = QByteArray::fromHex("0000000000000000000000000000000000000000000000000000000000000000"); QByteArray chacha20iv = QByteArray::fromHex("0000000000000000"); - QByteArray chacha20Plain = QByteArray::fromHex("00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"); - QByteArray chacha20Cipher = QByteArray::fromHex("76b8e0ada0f13d90405d6ae55386bd28bdd219b8a08ded1aa836efcc8b770dc7da41597c5157488d7724e03fb8d84a376a43b8f41518a11cc387b669b2ee6586"); + QByteArray chacha20Plain = QByteArray::fromHex("0000000000000000000000000000000000000000000000000000000000000000000" + "0000000000000000000000000000000000000000000000000000000000000"); + QByteArray chacha20Cipher = QByteArray::fromHex("76b8e0ada0f13d90405d6ae55386bd28bdd219b8a08ded1aa836efcc8b770dc7da" + "41597c5157488d7724e03fb8d84a376a43b8f41518a11cc387b669b2ee6586"); bool ok; - SymmetricCipher chacha20Stream(SymmetricCipher::ChaCha20, SymmetricCipher::Stream, - SymmetricCipher::Encrypt); + SymmetricCipher chacha20Stream(SymmetricCipher::ChaCha20, SymmetricCipher::Stream, SymmetricCipher::Encrypt); if (!chacha20Stream.init(chacha20Key, chacha20iv)) { raiseError(chacha20Stream.errorString()); return false; diff --git a/src/crypto/Random.cpp b/src/crypto/Random.cpp index dc0667fae..69c786306 100644 --- a/src/crypto/Random.cpp +++ b/src/crypto/Random.cpp @@ -89,7 +89,6 @@ Random::Random(RandomBackend* backend) { } - void RandomBackendGcrypt::randomize(void* data, int len) { Q_ASSERT(Crypto::initalized()); diff --git a/src/crypto/Random.h b/src/crypto/Random.h index 038ae7aea..1a36c4107 100644 --- a/src/crypto/Random.h +++ b/src/crypto/Random.h @@ -25,7 +25,9 @@ class RandomBackend { public: virtual void randomize(void* data, int len) = 0; - virtual ~RandomBackend() {} + virtual ~RandomBackend() + { + } }; class Random @@ -56,7 +58,8 @@ private: Q_DISABLE_COPY(Random) }; -inline Random* randomGen() { +inline Random* randomGen() +{ return Random::instance(); } diff --git a/src/crypto/SymmetricCipher.h b/src/crypto/SymmetricCipher.h index 0c683d224..bf5b60a4f 100644 --- a/src/crypto/SymmetricCipher.h +++ b/src/crypto/SymmetricCipher.h @@ -22,9 +22,9 @@ #include #include +#include "core/Uuid.h" #include "crypto/SymmetricCipherBackend.h" #include "format/KeePass2.h" -#include "core/Uuid.h" class SymmetricCipher { diff --git a/src/crypto/SymmetricCipherBackend.h b/src/crypto/SymmetricCipherBackend.h index dd493d2df..27a39177e 100644 --- a/src/crypto/SymmetricCipherBackend.h +++ b/src/crypto/SymmetricCipherBackend.h @@ -23,7 +23,9 @@ class SymmetricCipherBackend { public: - virtual ~SymmetricCipherBackend() {} + virtual ~SymmetricCipherBackend() + { + } virtual bool init() = 0; virtual bool setKey(const QByteArray& key) = 0; virtual bool setIv(const QByteArray& iv) = 0; diff --git a/src/crypto/SymmetricCipherGcrypt.cpp b/src/crypto/SymmetricCipherGcrypt.cpp index 97d53cd83..c7a5e6a07 100644 --- a/src/crypto/SymmetricCipherGcrypt.cpp +++ b/src/crypto/SymmetricCipherGcrypt.cpp @@ -20,7 +20,8 @@ #include "config-keepassx.h" #include "crypto/Crypto.h" -SymmetricCipherGcrypt::SymmetricCipherGcrypt(SymmetricCipher::Algorithm algo, SymmetricCipher::Mode mode, +SymmetricCipherGcrypt::SymmetricCipherGcrypt(SymmetricCipher::Algorithm algo, + SymmetricCipher::Mode mode, SymmetricCipher::Direction direction) : m_ctx(nullptr) , m_algo(gcryptAlgo(algo)) @@ -84,8 +85,8 @@ void SymmetricCipherGcrypt::setErrorString(gcry_error_t err) const char* gcryptError = gcry_strerror(err); const char* gcryptErrorSource = gcry_strsource(err); - m_errorString = QString("%1/%2").arg(QString::fromLocal8Bit(gcryptErrorSource), - QString::fromLocal8Bit(gcryptError)); + m_errorString = + QString("%1/%2").arg(QString::fromLocal8Bit(gcryptErrorSource), QString::fromLocal8Bit(gcryptError)); } bool SymmetricCipherGcrypt::init() @@ -94,7 +95,7 @@ bool SymmetricCipherGcrypt::init() gcry_error_t error; - if(m_ctx != nullptr) + if (m_ctx != nullptr) gcry_cipher_close(m_ctx); error = gcry_cipher_open(&m_ctx, m_algo, m_mode, 0); if (error != 0) { diff --git a/src/crypto/SymmetricCipherGcrypt.h b/src/crypto/SymmetricCipherGcrypt.h index 2436c3be1..6f806b90b 100644 --- a/src/crypto/SymmetricCipherGcrypt.h +++ b/src/crypto/SymmetricCipherGcrypt.h @@ -23,10 +23,11 @@ #include "crypto/SymmetricCipher.h" #include "crypto/SymmetricCipherBackend.h" -class SymmetricCipherGcrypt: public SymmetricCipherBackend +class SymmetricCipherGcrypt : public SymmetricCipherBackend { public: - SymmetricCipherGcrypt(SymmetricCipher::Algorithm algo, SymmetricCipher::Mode mode, + SymmetricCipherGcrypt(SymmetricCipher::Algorithm algo, + SymmetricCipher::Mode mode, SymmetricCipher::Direction direction); ~SymmetricCipherGcrypt(); diff --git a/src/crypto/argon2/argon2.h b/src/crypto/argon2/argon2.h index 8ea6108aa..8eba85a6f 100644 --- a/src/crypto/argon2/argon2.h +++ b/src/crypto/argon2/argon2.h @@ -31,4 +31,4 @@ #include -#endif //KEEPASSXC_CRYPTO_ARGON2_H +#endif // KEEPASSXC_CRYPTO_ARGON2_H diff --git a/src/crypto/kdf/AesKdf.cpp b/src/crypto/kdf/AesKdf.cpp index 593b01c24..a6f8f71e7 100644 --- a/src/crypto/kdf/AesKdf.cpp +++ b/src/crypto/kdf/AesKdf.cpp @@ -19,8 +19,8 @@ #include -#include "format/KeePass2.h" #include "crypto/CryptoHash.h" +#include "format/KeePass2.h" AesKdf::AesKdf() : Kdf::Kdf(KeePass2::KDF_AES_KDBX4) @@ -35,7 +35,7 @@ AesKdf::AesKdf(bool legacyKdbx3) { } -bool AesKdf::processParameters(const QVariantMap &p) +bool AesKdf::processParameters(const QVariantMap& p) { bool ok; int rounds = p.value(KeePass2::KDFPARAM_AES_ROUNDS).toInt(&ok); @@ -84,8 +84,7 @@ bool AesKdf::transform(const QByteArray& raw, QByteArray& result) const bool AesKdf::transformKeyRaw(const QByteArray& key, const QByteArray& seed, int rounds, QByteArray* result) { QByteArray iv(16, 0); - SymmetricCipher cipher(SymmetricCipher::Aes256, SymmetricCipher::Ecb, - SymmetricCipher::Encrypt); + SymmetricCipher cipher(SymmetricCipher::Aes256, SymmetricCipher::Ecb, SymmetricCipher::Encrypt); if (!cipher.init(seed, iv)) { qWarning("AesKdf::transformKeyRaw: error in SymmetricCipher::init: %s", cipher.errorString().toUtf8().data()); return false; diff --git a/src/crypto/kdf/AesKdf.h b/src/crypto/kdf/AesKdf.h index 31ee1fa70..20ef5c476 100644 --- a/src/crypto/kdf/AesKdf.h +++ b/src/crypto/kdf/AesKdf.h @@ -20,7 +20,7 @@ #include "Kdf.h" -class AesKdf: public Kdf +class AesKdf : public Kdf { public: AesKdf(); @@ -35,10 +35,8 @@ protected: int benchmarkImpl(int msec) const override; private: - static bool transformKeyRaw(const QByteArray& key, - const QByteArray& seed, - int rounds, - QByteArray* result) Q_REQUIRED_RESULT; + static bool + transformKeyRaw(const QByteArray& key, const QByteArray& seed, int rounds, QByteArray* result) Q_REQUIRED_RESULT; }; #endif // KEEPASSX_AESKDF_H diff --git a/src/crypto/kdf/Argon2Kdf.cpp b/src/crypto/kdf/Argon2Kdf.cpp index f67c9c1fb..3f3298450 100644 --- a/src/crypto/kdf/Argon2Kdf.cpp +++ b/src/crypto/kdf/Argon2Kdf.cpp @@ -30,10 +30,10 @@ * or associated data. KeePass uses the latest version of Argon2, v1.3. */ Argon2Kdf::Argon2Kdf() - : Kdf::Kdf(KeePass2::KDF_ARGON2) - , m_version(0x13) - , m_memory(1 << 16) - , m_parallelism(static_cast(QThread::idealThreadCount())) + : Kdf::Kdf(KeePass2::KDF_ARGON2) + , m_version(0x13) + , m_memory(1 << 16) + , m_parallelism(static_cast(QThread::idealThreadCount())) { m_rounds = 1; } @@ -86,7 +86,7 @@ bool Argon2Kdf::setParallelism(quint32 threads) return false; } -bool Argon2Kdf::processParameters(const QVariantMap &p) +bool Argon2Kdf::processParameters(const QVariantMap& p) { QByteArray salt = p.value(KeePass2::KDFPARAM_ARGON2_SALT).toByteArray(); if (!setSeed(salt)) { @@ -161,13 +161,28 @@ bool Argon2Kdf::transform(const QByteArray& raw, QByteArray& result) const return transformKeyRaw(raw, seed(), version(), rounds(), memory(), parallelism(), result); } -bool Argon2Kdf::transformKeyRaw(const QByteArray& key, const QByteArray& seed, quint32 version, - quint32 rounds, quint64 memory, quint32 parallelism, QByteArray& result) +bool Argon2Kdf::transformKeyRaw(const QByteArray& key, + const QByteArray& seed, + quint32 version, + quint32 rounds, + quint64 memory, + quint32 parallelism, + QByteArray& result) { // Time Cost, Mem Cost, Threads/Lanes, Password, length, Salt, length, out, length - int rc = argon2_hash(rounds, memory, parallelism, key.data(), key.size(), - seed.data(), seed.size(), result.data(), result.size(), - nullptr, 0, Argon2_d, version); + int rc = argon2_hash(rounds, + memory, + parallelism, + key.data(), + key.size(), + seed.data(), + seed.size(), + result.data(), + result.size(), + nullptr, + 0, + Argon2_d, + version); if (rc != ARGON2_OK) { qWarning("Argon2 error: %s", argon2_error_message(rc)); return false; diff --git a/src/crypto/kdf/Argon2Kdf.h b/src/crypto/kdf/Argon2Kdf.h index fe62b2953..9449f3455 100644 --- a/src/crypto/kdf/Argon2Kdf.h +++ b/src/crypto/kdf/Argon2Kdf.h @@ -20,7 +20,8 @@ #include "Kdf.h" -class Argon2Kdf : public Kdf { +class Argon2Kdf : public Kdf +{ public: Argon2Kdf(); diff --git a/src/crypto/kdf/Kdf.h b/src/crypto/kdf/Kdf.h index 216224a6f..ab21bc4d5 100644 --- a/src/crypto/kdf/Kdf.h +++ b/src/crypto/kdf/Kdf.h @@ -55,7 +55,6 @@ protected: private: class BenchmarkThread; const Uuid m_uuid; - }; #endif // KEEPASSX_KDF_H diff --git a/src/crypto/kdf/Kdf_p.h b/src/crypto/kdf/Kdf_p.h index 5606c0bf5..55ad2401b 100644 --- a/src/crypto/kdf/Kdf_p.h +++ b/src/crypto/kdf/Kdf_p.h @@ -22,9 +22,9 @@ #ifndef KEEPASSXC_KDF_P_H #define KEEPASSXC_KDF_P_H -class Kdf::BenchmarkThread: public QThread +class Kdf::BenchmarkThread : public QThread { -Q_OBJECT + Q_OBJECT public: explicit BenchmarkThread(int msec, const Kdf* kdf); diff --git a/src/format/Kdbx3Reader.cpp b/src/format/Kdbx3Reader.cpp index 82d59bc62..00b0adebe 100644 --- a/src/format/Kdbx3Reader.cpp +++ b/src/format/Kdbx3Reader.cpp @@ -18,19 +18,21 @@ #include "Kdbx3Reader.h" -#include "core/Group.h" #include "core/Endian.h" +#include "core/Group.h" #include "crypto/CryptoHash.h" -#include "format/KeePass2RandomStream.h" #include "format/KdbxXmlReader.h" +#include "format/KeePass2RandomStream.h" #include "streams/HashedBlockStream.h" #include "streams/QtIOCompressor" #include "streams/SymmetricCipherStream.h" #include -Database* Kdbx3Reader::readDatabaseImpl(QIODevice* device, const QByteArray& headerData, - const CompositeKey& key, bool keepDatabase) +Database* Kdbx3Reader::readDatabaseImpl(QIODevice* device, + const QByteArray& headerData, + const CompositeKey& key, + bool keepDatabase) { Q_ASSERT(m_kdbxVersion <= KeePass2::FILE_VERSION_3_1); @@ -39,8 +41,8 @@ Database* Kdbx3Reader::readDatabaseImpl(QIODevice* device, const QByteArray& hea } // check if all required headers were present - if (m_masterSeed.isEmpty() || m_encryptionIV.isEmpty() - || m_streamStartBytes.isEmpty() || m_protectedStreamKey.isEmpty() + if (m_masterSeed.isEmpty() || m_encryptionIV.isEmpty() || m_streamStartBytes.isEmpty() + || m_protectedStreamKey.isEmpty() || m_db->cipher().isNull()) { raiseError(tr("missing database headers")); return nullptr; @@ -63,8 +65,8 @@ Database* Kdbx3Reader::readDatabaseImpl(QIODevice* device, const QByteArray& hea QByteArray finalKey = hash.result(); SymmetricCipher::Algorithm cipher = SymmetricCipher::cipherToAlgorithm(m_db->cipher()); - SymmetricCipherStream cipherStream(device, cipher, - SymmetricCipher::algorithmMode(cipher), SymmetricCipher::Decrypt); + SymmetricCipherStream cipherStream( + device, cipher, SymmetricCipher::algorithmMode(cipher), SymmetricCipher::Decrypt); if (!cipherStream.init(finalKey, m_encryptionIV)) { raiseError(cipherStream.errorString()); return nullptr; diff --git a/src/format/Kdbx3Reader.h b/src/format/Kdbx3Reader.h index e62901578..41916d0e5 100644 --- a/src/format/Kdbx3Reader.h +++ b/src/format/Kdbx3Reader.h @@ -24,13 +24,15 @@ /** * KDBX 2/3 reader implementation. */ -class Kdbx3Reader: public KdbxReader +class Kdbx3Reader : public KdbxReader { -Q_DECLARE_TR_FUNCTIONS(Kdbx3Reader) + Q_DECLARE_TR_FUNCTIONS(Kdbx3Reader) public: - Database* readDatabaseImpl(QIODevice* device, const QByteArray& headerData, - const CompositeKey& key, bool keepDatabase) override; + Database* readDatabaseImpl(QIODevice* device, + const QByteArray& headerData, + const CompositeKey& key, + bool keepDatabase) override; protected: bool readHeaderField(StoreDataStream& headerStream) override; diff --git a/src/format/Kdbx3Writer.cpp b/src/format/Kdbx3Writer.cpp index c2fefff1b..866acae07 100644 --- a/src/format/Kdbx3Writer.cpp +++ b/src/format/Kdbx3Writer.cpp @@ -23,9 +23,9 @@ #include "core/Database.h" #include "crypto/CryptoHash.h" #include "crypto/Random.h" +#include "format/KdbxXmlWriter.h" #include "format/KeePass2.h" #include "format/KeePass2RandomStream.h" -#include "format/KdbxXmlWriter.h" #include "streams/HashedBlockStream.h" #include "streams/QtIOCompressor" #include "streams/SymmetricCipherStream.h" @@ -65,23 +65,27 @@ bool Kdbx3Writer::writeDatabase(QIODevice* device, Database* db) writeMagicNumbers(&header, KeePass2::SIGNATURE_1, KeePass2::SIGNATURE_2, KeePass2::FILE_VERSION_3_1); - CHECK_RETURN_FALSE(writeHeaderField(&header, KeePass2::HeaderFieldID::CipherID, db->cipher().toByteArray())); - CHECK_RETURN_FALSE(writeHeaderField(&header, KeePass2::HeaderFieldID::CompressionFlags, - Endian::sizedIntToBytes(db->compressionAlgo(), - KeePass2::BYTEORDER))); + CHECK_RETURN_FALSE( + writeHeaderField(&header, KeePass2::HeaderFieldID::CipherID, db->cipher().toByteArray())); + CHECK_RETURN_FALSE( + writeHeaderField(&header, + KeePass2::HeaderFieldID::CompressionFlags, + Endian::sizedIntToBytes(db->compressionAlgo(), KeePass2::BYTEORDER))); auto kdf = db->kdf(); CHECK_RETURN_FALSE(writeHeaderField(&header, KeePass2::HeaderFieldID::MasterSeed, masterSeed)); CHECK_RETURN_FALSE(writeHeaderField(&header, KeePass2::HeaderFieldID::TransformSeed, kdf->seed())); - CHECK_RETURN_FALSE(writeHeaderField(&header, KeePass2::HeaderFieldID::TransformRounds, - Endian::sizedIntToBytes(kdf->rounds(), - KeePass2::BYTEORDER))); + CHECK_RETURN_FALSE(writeHeaderField(&header, + KeePass2::HeaderFieldID::TransformRounds, + Endian::sizedIntToBytes(kdf->rounds(), KeePass2::BYTEORDER))); CHECK_RETURN_FALSE(writeHeaderField(&header, KeePass2::HeaderFieldID::EncryptionIV, encryptionIV)); - CHECK_RETURN_FALSE(writeHeaderField(&header, KeePass2::HeaderFieldID::ProtectedStreamKey, protectedStreamKey)); + CHECK_RETURN_FALSE( + writeHeaderField(&header, KeePass2::HeaderFieldID::ProtectedStreamKey, protectedStreamKey)); CHECK_RETURN_FALSE(writeHeaderField(&header, KeePass2::HeaderFieldID::StreamStartBytes, startBytes)); - CHECK_RETURN_FALSE(writeHeaderField(&header, KeePass2::HeaderFieldID::InnerRandomStreamID, - Endian::sizedIntToBytes(static_cast( - KeePass2::ProtectedStreamAlgo::Salsa20), - KeePass2::BYTEORDER))); + CHECK_RETURN_FALSE(writeHeaderField( + &header, + KeePass2::HeaderFieldID::InnerRandomStreamID, + Endian::sizedIntToBytes(static_cast(KeePass2::ProtectedStreamAlgo::Salsa20), + KeePass2::BYTEORDER))); CHECK_RETURN_FALSE(writeHeaderField(&header, KeePass2::HeaderFieldID::EndOfHeader, endOfHeader)); header.close(); @@ -93,8 +97,7 @@ bool Kdbx3Writer::writeDatabase(QIODevice* device, Database* db) // write cipher stream SymmetricCipher::Algorithm algo = SymmetricCipher::cipherToAlgorithm(db->cipher()); - SymmetricCipherStream cipherStream(device, algo, - SymmetricCipher::algorithmMode(algo), SymmetricCipher::Encrypt); + SymmetricCipherStream cipherStream(device, algo, SymmetricCipher::algorithmMode(algo), SymmetricCipher::Encrypt); cipherStream.init(finalKey, encryptionIV); if (!cipherStream.open(QIODevice::WriteOnly)) { raiseError(cipherStream.errorString()); diff --git a/src/format/Kdbx3Writer.h b/src/format/Kdbx3Writer.h index 8acc198a5..eb98a470d 100644 --- a/src/format/Kdbx3Writer.h +++ b/src/format/Kdbx3Writer.h @@ -23,9 +23,9 @@ /** * KDBX2/3 writer implementation. */ -class Kdbx3Writer: public KdbxWriter +class Kdbx3Writer : public KdbxWriter { -Q_DECLARE_TR_FUNCTIONS(Kdbx3Writer) + Q_DECLARE_TR_FUNCTIONS(Kdbx3Writer) public: bool writeDatabase(QIODevice* device, Database* db) override; diff --git a/src/format/Kdbx4Reader.cpp b/src/format/Kdbx4Reader.cpp index 2919db785..92c8187cd 100644 --- a/src/format/Kdbx4Reader.cpp +++ b/src/format/Kdbx4Reader.cpp @@ -19,17 +19,19 @@ #include -#include "core/Group.h" #include "core/Endian.h" +#include "core/Group.h" #include "crypto/CryptoHash.h" -#include "format/KeePass2RandomStream.h" #include "format/KdbxXmlReader.h" +#include "format/KeePass2RandomStream.h" #include "streams/HmacBlockStream.h" #include "streams/QtIOCompressor" #include "streams/SymmetricCipherStream.h" -Database* Kdbx4Reader::readDatabaseImpl(QIODevice* device, const QByteArray& headerData, - const CompositeKey& key, bool keepDatabase) +Database* Kdbx4Reader::readDatabaseImpl(QIODevice* device, + const QByteArray& headerData, + const CompositeKey& key, + bool keepDatabase) { Q_ASSERT(m_kdbxVersion == KeePass2::FILE_VERSION_4); @@ -40,9 +42,7 @@ Database* Kdbx4Reader::readDatabaseImpl(QIODevice* device, const QByteArray& hea } // check if all required headers were present - if (m_masterSeed.isEmpty() - || m_encryptionIV.isEmpty() - || m_db->cipher().isNull()) { + if (m_masterSeed.isEmpty() || m_encryptionIV.isEmpty() || m_db->cipher().isNull()) { raiseError(tr("missing database headers")); return nullptr; } @@ -69,8 +69,8 @@ Database* Kdbx4Reader::readDatabaseImpl(QIODevice* device, const QByteArray& hea } QByteArray hmacKey = KeePass2::hmacKey(m_masterSeed, m_db->transformedMasterKey()); - if (headerHmac != CryptoHash::hmac(headerData, - HmacBlockStream::getHmacKey(UINT64_MAX, hmacKey), CryptoHash::Sha256)) { + if (headerHmac + != CryptoHash::hmac(headerData, HmacBlockStream::getHmacKey(UINT64_MAX, hmacKey), CryptoHash::Sha256)) { raiseError(tr("Wrong key or database file is corrupt. (HMAC mismatch)")); return nullptr; } @@ -85,8 +85,8 @@ Database* Kdbx4Reader::readDatabaseImpl(QIODevice* device, const QByteArray& hea raiseError(tr("Unknown cipher")); return nullptr; } - SymmetricCipherStream cipherStream(&hmacStream, cipher, - SymmetricCipher::algorithmMode(cipher), SymmetricCipher::Decrypt); + SymmetricCipherStream cipherStream( + &hmacStream, cipher, SymmetricCipher::algorithmMode(cipher), SymmetricCipher::Decrypt); if (!cipherStream.init(finalKey, m_encryptionIV)) { raiseError(cipherStream.errorString()); return nullptr; @@ -304,8 +304,8 @@ bool Kdbx4Reader::readInnerHeaderField(QIODevice* device) QVariantMap Kdbx4Reader::readVariantMap(QIODevice* device) { bool ok; - quint16 version = Endian::readSizedInt(device, KeePass2::BYTEORDER, &ok) - & KeePass2::VARIANTMAP_CRITICAL_MASK; + quint16 version = + Endian::readSizedInt(device, KeePass2::BYTEORDER, &ok) & KeePass2::VARIANTMAP_CRITICAL_MASK; quint16 maxVersion = KeePass2::VARIANTMAP_VERSION & KeePass2::VARIANTMAP_CRITICAL_MASK; if (!ok || (version > maxVersion)) { //: Translation: variant map = data structure for storing meta data diff --git a/src/format/Kdbx4Reader.h b/src/format/Kdbx4Reader.h index 24d4a9142..ce965a7bb 100644 --- a/src/format/Kdbx4Reader.h +++ b/src/format/Kdbx4Reader.h @@ -27,11 +27,13 @@ */ class Kdbx4Reader : public KdbxReader { -Q_DECLARE_TR_FUNCTIONS(Kdbx4Reader) + Q_DECLARE_TR_FUNCTIONS(Kdbx4Reader) public: - Database* readDatabaseImpl(QIODevice* device, const QByteArray& headerData, - const CompositeKey& key, bool keepDatabase) override; + Database* readDatabaseImpl(QIODevice* device, + const QByteArray& headerData, + const CompositeKey& key, + bool keepDatabase) override; QHash binaryPoolInverse() const; QHash binaryPool() const; diff --git a/src/format/Kdbx4Writer.cpp b/src/format/Kdbx4Writer.cpp index bd671d9c7..43234b1ee 100644 --- a/src/format/Kdbx4Writer.cpp +++ b/src/format/Kdbx4Writer.cpp @@ -20,14 +20,14 @@ #include #include -#include "streams/HmacBlockStream.h" +#include "core/CustomData.h" #include "core/Database.h" #include "core/Metadata.h" -#include "core/CustomData.h" #include "crypto/CryptoHash.h" #include "crypto/Random.h" -#include "format/KeePass2RandomStream.h" #include "format/KdbxXmlWriter.h" +#include "format/KeePass2RandomStream.h" +#include "streams/HmacBlockStream.h" #include "streams/QtIOCompressor" #include "streams/SymmetricCipherStream.h" @@ -73,10 +73,12 @@ bool Kdbx4Writer::writeDatabase(QIODevice* device, Database* db) writeMagicNumbers(&header, KeePass2::SIGNATURE_1, KeePass2::SIGNATURE_2, KeePass2::FILE_VERSION_4); - CHECK_RETURN_FALSE(writeHeaderField(&header, KeePass2::HeaderFieldID::CipherID, db->cipher().toByteArray())); - CHECK_RETURN_FALSE(writeHeaderField(&header, KeePass2::HeaderFieldID::CompressionFlags, - Endian::sizedIntToBytes(static_cast(db->compressionAlgo()), - KeePass2::BYTEORDER))); + CHECK_RETURN_FALSE( + writeHeaderField(&header, KeePass2::HeaderFieldID::CipherID, db->cipher().toByteArray())); + CHECK_RETURN_FALSE(writeHeaderField( + &header, + KeePass2::HeaderFieldID::CompressionFlags, + Endian::sizedIntToBytes(static_cast(db->compressionAlgo()), KeePass2::BYTEORDER))); CHECK_RETURN_FALSE(writeHeaderField(&header, KeePass2::HeaderFieldID::MasterSeed, masterSeed)); CHECK_RETURN_FALSE(writeHeaderField(&header, KeePass2::HeaderFieldID::EncryptionIV, encryptionIV)); @@ -94,8 +96,8 @@ bool Kdbx4Writer::writeDatabase(QIODevice* device, Database* db) if (!publicCustomData.isEmpty()) { QByteArray serialized; serializeVariantMap(publicCustomData, serialized); - CHECK_RETURN_FALSE(writeHeaderField( - &header, KeePass2::HeaderFieldID::PublicCustomData, serialized)); + CHECK_RETURN_FALSE( + writeHeaderField(&header, KeePass2::HeaderFieldID::PublicCustomData, serialized)); } CHECK_RETURN_FALSE(writeHeaderField(&header, KeePass2::HeaderFieldID::EndOfHeader, endOfHeader)); @@ -109,8 +111,8 @@ bool Kdbx4Writer::writeDatabase(QIODevice* device, Database* db) // write HMAC-authenticated cipher stream QByteArray hmacKey = KeePass2::hmacKey(masterSeed, db->transformedMasterKey()); - QByteArray headerHmac = CryptoHash::hmac(headerData, HmacBlockStream::getHmacKey(UINT64_MAX, hmacKey), - CryptoHash::Sha256); + QByteArray headerHmac = + CryptoHash::hmac(headerData, HmacBlockStream::getHmacKey(UINT64_MAX, hmacKey), CryptoHash::Sha256); CHECK_RETURN_FALSE(writeData(device, headerHash)); CHECK_RETURN_FALSE(writeData(device, headerHmac)); @@ -123,9 +125,8 @@ bool Kdbx4Writer::writeDatabase(QIODevice* device, Database* db) return false; } - cipherStream.reset(new SymmetricCipherStream(hmacBlockStream.data(), algo, - SymmetricCipher::algorithmMode(algo), - SymmetricCipher::Encrypt)); + cipherStream.reset(new SymmetricCipherStream( + hmacBlockStream.data(), algo, SymmetricCipher::algorithmMode(algo), SymmetricCipher::Encrypt)); if (!cipherStream->init(finalKey, encryptionIV)) { raiseError(cipherStream->errorString()); @@ -153,11 +154,12 @@ bool Kdbx4Writer::writeDatabase(QIODevice* device, Database* db) Q_ASSERT(outputDevice); - CHECK_RETURN_FALSE(writeInnerHeaderField(outputDevice, KeePass2::InnerHeaderFieldID::InnerRandomStreamID, - Endian::sizedIntToBytes(static_cast(KeePass2::ProtectedStreamAlgo::ChaCha20), - KeePass2::BYTEORDER))); - CHECK_RETURN_FALSE(writeInnerHeaderField(outputDevice, KeePass2::InnerHeaderFieldID::InnerRandomStreamKey, - protectedStreamKey)); + CHECK_RETURN_FALSE(writeInnerHeaderField( + outputDevice, + KeePass2::InnerHeaderFieldID::InnerRandomStreamID, + Endian::sizedIntToBytes(static_cast(KeePass2::ProtectedStreamAlgo::ChaCha20), KeePass2::BYTEORDER))); + CHECK_RETURN_FALSE( + writeInnerHeaderField(outputDevice, KeePass2::InnerHeaderFieldID::InnerRandomStreamKey, protectedStreamKey)); // Write attachments to the inner header writeAttachments(outputDevice, db); @@ -208,7 +210,8 @@ bool Kdbx4Writer::writeInnerHeaderField(QIODevice* device, KeePass2::InnerHeader QByteArray fieldIdArr; fieldIdArr[0] = static_cast(fieldId); CHECK_RETURN_FALSE(writeData(device, fieldIdArr)); - CHECK_RETURN_FALSE(writeData(device, Endian::sizedIntToBytes(static_cast(data.size()), KeePass2::BYTEORDER))); + CHECK_RETURN_FALSE( + writeData(device, Endian::sizedIntToBytes(static_cast(data.size()), KeePass2::BYTEORDER))); CHECK_RETURN_FALSE(writeData(device, data)); return true; diff --git a/src/format/Kdbx4Writer.h b/src/format/Kdbx4Writer.h index 90a8e658e..c8540245b 100644 --- a/src/format/Kdbx4Writer.h +++ b/src/format/Kdbx4Writer.h @@ -25,7 +25,7 @@ */ class Kdbx4Writer : public KdbxWriter { -Q_DECLARE_TR_FUNCTIONS(Kdbx4Writer) + Q_DECLARE_TR_FUNCTIONS(Kdbx4Writer) public: bool writeDatabase(QIODevice* device, Database* db) override; diff --git a/src/format/KdbxReader.cpp b/src/format/KdbxReader.cpp index 5393b743f..ade824fb6 100644 --- a/src/format/KdbxReader.cpp +++ b/src/format/KdbxReader.cpp @@ -249,8 +249,8 @@ void KdbxReader::setInnerRandomStreamID(const QByteArray& data) } auto id = Endian::bytesToSizedInt(data, KeePass2::BYTEORDER); KeePass2::ProtectedStreamAlgo irsAlgo = KeePass2::idToProtectedStreamAlgo(id); - if (irsAlgo == KeePass2::ProtectedStreamAlgo::InvalidProtectedStreamAlgo || - irsAlgo == KeePass2::ProtectedStreamAlgo::ArcFourVariant) { + if (irsAlgo == KeePass2::ProtectedStreamAlgo::InvalidProtectedStreamAlgo + || irsAlgo == KeePass2::ProtectedStreamAlgo::ArcFourVariant) { raiseError(tr("Invalid inner random stream cipher")); return; } diff --git a/src/format/KdbxReader.h b/src/format/KdbxReader.h index 994cfb7ef..23050d28f 100644 --- a/src/format/KdbxReader.h +++ b/src/format/KdbxReader.h @@ -33,7 +33,7 @@ class QIODevice; */ class KdbxReader { -Q_DECLARE_TR_FUNCTIONS(KdbxReader) + Q_DECLARE_TR_FUNCTIONS(KdbxReader) public: KdbxReader() = default; @@ -61,8 +61,8 @@ protected: * @param keepDatabase keep database in case of read failure * @return pointer to the read database, nullptr on failure */ - virtual Database* readDatabaseImpl(QIODevice* device, const QByteArray& headerData, - const CompositeKey& key, bool keepDatabase) = 0; + virtual Database* + readDatabaseImpl(QIODevice* device, const QByteArray& headerData, const CompositeKey& key, bool keepDatabase) = 0; /** * Read next header field from stream. @@ -103,5 +103,4 @@ private: QString m_errorStr = ""; }; - -#endif //KEEPASSXC_KDBXREADER_H +#endif // KEEPASSXC_KDBXREADER_H diff --git a/src/format/KdbxWriter.h b/src/format/KdbxWriter.h index 8fec336df..4685797ca 100644 --- a/src/format/KdbxWriter.h +++ b/src/format/KdbxWriter.h @@ -35,7 +35,7 @@ class Database; */ class KdbxWriter { -Q_DECLARE_TR_FUNCTIONS(KdbxWriter) + Q_DECLARE_TR_FUNCTIONS(KdbxWriter) public: KdbxWriter() = default; @@ -56,7 +56,6 @@ public: QString errorString() const; protected: - /** * Helper method for writing a KDBX header field to a device. * @@ -74,8 +73,8 @@ protected: QByteArray fieldIdArr; fieldIdArr[0] = static_cast(fieldId); CHECK_RETURN_FALSE(writeData(device, fieldIdArr)); - CHECK_RETURN_FALSE(writeData(device, Endian::sizedIntToBytes(static_cast(data.size()), - KeePass2::BYTEORDER))); + CHECK_RETURN_FALSE(writeData( + device, Endian::sizedIntToBytes(static_cast(data.size()), KeePass2::BYTEORDER))); CHECK_RETURN_FALSE(writeData(device, data)); return true; @@ -88,5 +87,4 @@ protected: QString m_errorStr = ""; }; - -#endif //KEEPASSXC_KDBXWRITER_H +#endif // KEEPASSXC_KDBXWRITER_H diff --git a/src/format/KdbxXmlReader.cpp b/src/format/KdbxXmlReader.cpp index 77ec26047..b10df2ebe 100644 --- a/src/format/KdbxXmlReader.cpp +++ b/src/format/KdbxXmlReader.cpp @@ -17,16 +17,16 @@ #include "KdbxXmlReader.h" #include "KeePass2RandomStream.h" -#include "core/Global.h" -#include "core/Tools.h" -#include "core/Entry.h" -#include "core/Group.h" #include "core/DatabaseIcons.h" #include "core/Endian.h" +#include "core/Entry.h" +#include "core/Global.h" +#include "core/Group.h" +#include "core/Tools.h" #include "streams/QtIOCompressor" -#include #include +#include /** * @param version KDBX version @@ -114,13 +114,11 @@ void KdbxXmlReader::readDatabase(QIODevice* device, Database* db, KeePass2Random } if (!m_tmpParent->children().isEmpty()) { - qWarning("KdbxXmlReader::readDatabase: found %d invalid group reference(s)", - m_tmpParent->children().size()); + qWarning("KdbxXmlReader::readDatabase: found %d invalid group reference(s)", m_tmpParent->children().size()); } if (!m_tmpParent->entries().isEmpty()) { - qWarning("KdbxXmlReader::readDatabase: found %d invalid entry reference(s)", - m_tmpParent->children().size()); + qWarning("KdbxXmlReader::readDatabase: found %d invalid entry reference(s)", m_tmpParent->children().size()); } const QSet poolKeys = m_binaryPool.keys().toSet(); @@ -136,7 +134,7 @@ void KdbxXmlReader::readDatabase(QIODevice* device, Database* db, KeePass2Random qWarning("KdbxXmlReader::readDatabase: found unused key \"%s\"", qPrintable(key)); } - QHash >::const_iterator i; + QHash>::const_iterator i; for (i = m_binaryMap.constBegin(); i != m_binaryMap.constEnd(); ++i) { const QPair& target = i.value(); target.first->attachments()->set(target.second, m_binaryPool[i.key()]); @@ -191,8 +189,7 @@ QString KdbxXmlReader::errorString() const bool KdbxXmlReader::isTrueValue(const QStringRef& value) { - return value.compare(QLatin1String("true"), Qt::CaseInsensitive) == 0 - || value == "1"; + return value.compare(QLatin1String("true"), Qt::CaseInsensitive) == 0 || value == "1"; } void KdbxXmlReader::raiseError(const QString& errorMessage) @@ -386,12 +383,10 @@ void KdbxXmlReader::parseBinaries() QXmlStreamAttributes attr = m_xml.attributes(); QString id = attr.value("ID").toString(); - QByteArray data = isTrueValue(attr.value("Compressed")) - ? readCompressedBinary() : readBinary(); + QByteArray data = isTrueValue(attr.value("Compressed")) ? readCompressedBinary() : readBinary(); if (m_binaryPool.contains(id)) { - qWarning("KdbxXmlReader::parseBinaries: overwriting binary item \"%s\"", - qPrintable(id)); + qWarning("KdbxXmlReader::parseBinaries: overwriting binary item \"%s\"", qPrintable(id)); } m_binaryPool.insert(id, data); @@ -1192,4 +1187,3 @@ void KdbxXmlReader::skipCurrentElement() qWarning("KdbxXmlReader::skipCurrentElement: skip element \"%s\"", qPrintable(m_xml.name().toString())); m_xml.skipCurrentElement(); } - diff --git a/src/format/KdbxXmlReader.h b/src/format/KdbxXmlReader.h index 500151828..00c898d17 100644 --- a/src/format/KdbxXmlReader.h +++ b/src/format/KdbxXmlReader.h @@ -18,14 +18,14 @@ #ifndef KEEPASSXC_KDBXXMLREADER_H #define KEEPASSXC_KDBXXMLREADER_H +#include "core/Database.h" #include "core/Metadata.h" #include "core/TimeInfo.h" #include "core/Uuid.h" -#include "core/Database.h" #include -#include #include +#include #include class QIODevice; @@ -38,7 +38,7 @@ class KeePass2RandomStream; */ class KdbxXmlReader { -Q_DECLARE_TR_FUNCTIONS(KdbxXmlReader) + Q_DECLARE_TR_FUNCTIONS(KdbxXmlReader) public: explicit KdbxXmlReader(quint32 version); @@ -112,11 +112,11 @@ protected: QHash m_entries; QHash m_binaryPool; - QHash > m_binaryMap; + QHash> m_binaryMap; QByteArray m_headerHash; bool m_error = false; QString m_errorStr = ""; }; -#endif //KEEPASSXC_KDBXXMLREADER_H +#endif // KEEPASSXC_KDBXXMLREADER_H diff --git a/src/format/KdbxXmlWriter.cpp b/src/format/KdbxXmlWriter.cpp index a546f3171..748e16d31 100644 --- a/src/format/KdbxXmlWriter.cpp +++ b/src/format/KdbxXmlWriter.cpp @@ -33,7 +33,10 @@ KdbxXmlWriter::KdbxXmlWriter(quint32 version) { } -void KdbxXmlWriter::writeDatabase(QIODevice* device, Database* db, KeePass2RandomStream* randomStream, const QByteArray& headerHash) +void KdbxXmlWriter::writeDatabase(QIODevice* device, + Database* db, + KeePass2RandomStream* randomStream, + const QByteArray& headerHash) { m_db = db; m_meta = db->metadata(); @@ -64,7 +67,7 @@ void KdbxXmlWriter::writeDatabase(QIODevice* device, Database* db, KeePass2Rando void KdbxXmlWriter::writeDatabase(const QString& filename, Database* db) { QFile file(filename); - file.open(QIODevice::WriteOnly|QIODevice::Truncate); + file.open(QIODevice::WriteOnly | QIODevice::Truncate); writeDatabase(&file, db); } @@ -204,8 +207,7 @@ void KdbxXmlWriter::writeBinaries() buffer.seek(0); data = buffer.readAll(); - } - else { + } else { data = i.key(); } @@ -354,12 +356,12 @@ void KdbxXmlWriter::writeEntry(const Entry* entry) for (const QString& key : attributesKeyList) { m_xml.writeStartElement("String"); - bool protect = ( ((key == "Title") && m_meta->protectTitle()) || - ((key == "UserName") && m_meta->protectUsername()) || - ((key == "Password") && m_meta->protectPassword()) || - ((key == "URL") && m_meta->protectUrl()) || - ((key == "Notes") && m_meta->protectNotes()) || - entry->attributes()->isProtected(key) ); + bool protect = + (((key == "Title") && m_meta->protectTitle()) || ((key == "UserName") && m_meta->protectUsername()) + || ((key == "Password") && m_meta->protectPassword()) + || ((key == "URL") && m_meta->protectUrl()) + || ((key == "Notes") && m_meta->protectNotes()) + || entry->attributes()->isProtected(key)); writeString("Key", key); @@ -375,13 +377,11 @@ void KdbxXmlWriter::writeEntry(const Entry* entry) raiseError(m_randomStream->errorString()); } value = QString::fromLatin1(rawData.toBase64()); - } - else { + } else { m_xml.writeAttribute("ProtectInMemory", "True"); value = entry->attributes()->value(key); } - } - else { + } else { value = entry->attributes()->value(key); } @@ -462,8 +462,7 @@ void KdbxXmlWriter::writeString(const QString& qualifiedName, const QString& str { if (string.isEmpty()) { m_xml.writeEmptyElement(qualifiedName); - } - else { + } else { m_xml.writeTextElement(qualifiedName, stripInvalidXml10Chars(string)); } } @@ -477,8 +476,7 @@ void KdbxXmlWriter::writeBool(const QString& qualifiedName, bool b) { if (b) { writeString(qualifiedName, "True"); - } - else { + } else { writeString(qualifiedName, "False"); } } @@ -513,8 +511,7 @@ void KdbxXmlWriter::writeUuid(const QString& qualifiedName, const Group* group) { if (group) { writeUuid(qualifiedName, group->uuid()); - } - else { + } else { writeUuid(qualifiedName, Uuid()); } } @@ -523,8 +520,7 @@ void KdbxXmlWriter::writeUuid(const QString& qualifiedName, const Entry* entry) { if (entry) { writeUuid(qualifiedName, entry->uuid()); - } - else { + } else { writeUuid(qualifiedName, Uuid()); } } @@ -539,9 +535,8 @@ void KdbxXmlWriter::writeColor(const QString& qualifiedName, const QColor& color QString colorStr; if (color.isValid()) { - colorStr = QString("#%1%2%3").arg(colorPartToString(color.red()), - colorPartToString(color.green()), - colorPartToString(color.blue())); + colorStr = QString("#%1%2%3").arg( + colorPartToString(color.red()), colorPartToString(color.green()), colorPartToString(color.blue())); } writeString(qualifiedName, colorStr); @@ -553,11 +548,9 @@ void KdbxXmlWriter::writeTriState(const QString& qualifiedName, Group::TriState if (triState == Group::Inherit) { value = "null"; - } - else if (triState == Group::Enable) { + } else if (triState == Group::Enable) { value = "true"; - } - else { + } else { value = "false"; } @@ -583,13 +576,12 @@ QString KdbxXmlWriter::stripInvalidXml10Chars(QString str) if (ch.isLowSurrogate() && i != 0 && str.at(i - 1).isHighSurrogate()) { // keep valid surrogate pair i--; - } - else if ((uc < 0x20 && uc != 0x09 && uc != 0x0A && uc != 0x0D) // control characters - || (uc >= 0x7F && uc <= 0x84) // control characters, valid but discouraged by XML - || (uc >= 0x86 && uc <= 0x9F) // control characters, valid but discouraged by XML - || (uc > 0xFFFD) // noncharacter - || ch.isLowSurrogate() // single low surrogate - || ch.isHighSurrogate()) // single high surrogate + } else if ((uc < 0x20 && uc != 0x09 && uc != 0x0A && uc != 0x0D) // control characters + || (uc >= 0x7F && uc <= 0x84) // control characters, valid but discouraged by XML + || (uc >= 0x86 && uc <= 0x9F) // control characters, valid but discouraged by XML + || (uc > 0xFFFD) // noncharacter + || ch.isLowSurrogate() // single low surrogate + || ch.isHighSurrogate()) // single high surrogate { qWarning("Stripping invalid XML 1.0 codepoint %x", uc); str.remove(i, 1); diff --git a/src/format/KdbxXmlWriter.h b/src/format/KdbxXmlWriter.h index e2c5b73c8..a8ed79b8e 100644 --- a/src/format/KdbxXmlWriter.h +++ b/src/format/KdbxXmlWriter.h @@ -37,7 +37,9 @@ class KdbxXmlWriter public: explicit KdbxXmlWriter(quint32 version); - void writeDatabase(QIODevice* device, Database* db, KeePass2RandomStream* randomStream = nullptr, + void writeDatabase(QIODevice* device, + Database* db, + KeePass2RandomStream* randomStream = nullptr, const QByteArray& headerHash = QByteArray()); void writeDatabase(const QString& filename, Database* db); bool hasError(); diff --git a/src/format/KeePass1Reader.cpp b/src/format/KeePass1Reader.cpp index 02810b989..5789c590d 100644 --- a/src/format/KeePass1Reader.cpp +++ b/src/format/KeePass1Reader.cpp @@ -21,7 +21,6 @@ #include #include -#include "crypto/kdf/AesKdf.h" #include "core/Database.h" #include "core/Endian.h" #include "core/Entry.h" @@ -29,6 +28,7 @@ #include "core/Metadata.h" #include "core/Tools.h" #include "crypto/CryptoHash.h" +#include "crypto/kdf/AesKdf.h" #include "format/KeePass1.h" #include "keys/FileKey.h" #include "keys/PasswordKey.h" @@ -47,7 +47,6 @@ private: QByteArray m_keyfileData; }; - KeePass1Reader::KeePass1Reader() : m_db(nullptr) , m_tmpParent(nullptr) @@ -58,8 +57,7 @@ KeePass1Reader::KeePass1Reader() { } -Database* KeePass1Reader::readDatabase(QIODevice* device, const QString& password, - QIODevice* keyfileDevice) +Database* KeePass1Reader::readDatabase(QIODevice* device, const QString& password, QIODevice* keyfileDevice) { m_error = false; m_errorStr.clear(); @@ -112,8 +110,9 @@ Database* KeePass1Reader::readDatabase(QIODevice* device, const QString& passwor } auto version = Endian::readSizedInt(m_device, KeePass1::BYTEORDER, &ok); - if (!ok || (version & KeePass1::FILE_VERSION_CRITICAL_MASK) - != (KeePass1::FILE_VERSION & KeePass1::FILE_VERSION_CRITICAL_MASK)) { + if (!ok + || (version & KeePass1::FILE_VERSION_CRITICAL_MASK) + != (KeePass1::FILE_VERSION & KeePass1::FILE_VERSION_CRITICAL_MASK)) { raiseError(tr("Unsupported KeePass database version.")); return nullptr; } @@ -200,8 +199,7 @@ Database* KeePass1Reader::readDatabase(QIODevice* device, const QString& passwor parseMetaStream(entry); delete entry; - } - else { + } else { quint32 groupId = m_entryGroupIds.value(entry); if (!m_groupIds.contains(groupId)) { qWarning("Orphaned entry found, assigning to root group."); @@ -251,8 +249,7 @@ Database* KeePass1Reader::readDatabase(QIODevice* device, const QString& passwor return db.take(); } -Database* KeePass1Reader::readDatabase(QIODevice* device, const QString& password, - const QString& keyfileName) +Database* KeePass1Reader::readDatabase(QIODevice* device, const QString& password, const QString& keyfileName) { QScopedPointer keyFile; if (!keyfileName.isEmpty()) { @@ -268,8 +265,7 @@ Database* KeePass1Reader::readDatabase(QIODevice* device, const QString& passwor return db.take(); } -Database* KeePass1Reader::readDatabase(const QString& filename, const QString& password, - const QString& keyfileName) +Database* KeePass1Reader::readDatabase(const QString& filename, const QString& password, const QString& keyfileName) { QFile dbFile(filename); if (!dbFile.open(QFile::ReadOnly)) { @@ -297,10 +293,10 @@ QString KeePass1Reader::errorString() return m_errorStr; } -SymmetricCipherStream* KeePass1Reader::testKeys(const QString& password, const QByteArray& keyfileData, - qint64 contentPos) +SymmetricCipherStream* +KeePass1Reader::testKeys(const QString& password, const QByteArray& keyfileData, qint64 contentPos) { - const QList encodings = { Windows1252, Latin1, UTF8 }; + const QList encodings = {Windows1252, Latin1, UTF8}; QScopedPointer cipherStream; QByteArray passwordData; @@ -310,28 +306,24 @@ SymmetricCipherStream* KeePass1Reader::testKeys(const QString& password, const Q for (PasswordEncoding encoding : encodings) { if (encoding == Windows1252) { passwordData = passwordDataCorrect; - } - else if (encoding == Latin1) { + } else if (encoding == Latin1) { // KeePassX used Latin-1 encoding for passwords until version 0.3.1 // but KeePass/Win32 uses Windows Codepage 1252. passwordData = password.toLatin1(); if (passwordData == passwordDataCorrect) { continue; - } - else { + } else { qWarning("Testing password encoded as Latin-1."); } - } - else if (encoding == UTF8) { + } else if (encoding == UTF8) { // KeePassX used UTF-8 encoding for passwords until version 0.2.2 // but KeePass/Win32 uses Windows Codepage 1252. passwordData = password.toUtf8(); if (passwordData == passwordDataCorrect) { continue; - } - else { + } else { qWarning("Testing password encoded as UTF-8."); } } @@ -341,12 +333,11 @@ SymmetricCipherStream* KeePass1Reader::testKeys(const QString& password, const Q return nullptr; } if (m_encryptionFlags & KeePass1::Rijndael) { - cipherStream.reset(new SymmetricCipherStream(m_device, SymmetricCipher::Aes256, - SymmetricCipher::Cbc, SymmetricCipher::Decrypt)); - } - else { - cipherStream.reset(new SymmetricCipherStream(m_device, SymmetricCipher::Twofish, - SymmetricCipher::Cbc, SymmetricCipher::Decrypt)); + cipherStream.reset(new SymmetricCipherStream( + m_device, SymmetricCipher::Aes256, SymmetricCipher::Cbc, SymmetricCipher::Decrypt)); + } else { + cipherStream.reset(new SymmetricCipherStream( + m_device, SymmetricCipher::Twofish, SymmetricCipher::Cbc, SymmetricCipher::Decrypt)); } if (!cipherStream->init(finalKey, m_encryptionIV)) { @@ -375,8 +366,7 @@ SymmetricCipherStream* KeePass1Reader::testKeys(const QString& password, const Q if (success) { break; - } - else { + } else { cipherStream.reset(); } } @@ -476,8 +466,7 @@ Group* KeePass1Reader::readGroup(QIODevice* cipherStream) case 0x0002: group->setName(QString::fromUtf8(fieldData.constData())); break; - case 0x0003: - { + case 0x0003: { if (fieldSize != 5) { raiseError(tr("Incorrect group creation time field size")); return nullptr; @@ -488,8 +477,7 @@ Group* KeePass1Reader::readGroup(QIODevice* cipherStream) } break; } - case 0x0004: - { + case 0x0004: { if (fieldSize != 5) { raiseError(tr("Incorrect group modification time field size")); return nullptr; @@ -500,8 +488,7 @@ Group* KeePass1Reader::readGroup(QIODevice* cipherStream) } break; } - case 0x0005: - { + case 0x0005: { if (fieldSize != 5) { raiseError(tr("Incorrect group access time field size")); } @@ -511,8 +498,7 @@ Group* KeePass1Reader::readGroup(QIODevice* cipherStream) } break; } - case 0x0006: - { + case 0x0006: { if (fieldSize != 5) { raiseError(tr("Incorrect group expiry time field size")); } @@ -523,8 +509,7 @@ Group* KeePass1Reader::readGroup(QIODevice* cipherStream) } break; } - case 0x0007: - { + case 0x0007: { if (fieldSize != 4) { raiseError(tr("Incorrect group icon field size")); return nullptr; @@ -533,8 +518,7 @@ Group* KeePass1Reader::readGroup(QIODevice* cipherStream) group->setIcon(iconNumber); break; } - case 0x0008: - { + case 0x0008: { if (fieldSize != 2) { raiseError(tr("Incorrect group level field size")); return nullptr; @@ -610,8 +594,7 @@ Entry* KeePass1Reader::readEntry(QIODevice* cipherStream) } m_entryUuids.insert(fieldData, entry.data()); break; - case 0x0002: - { + case 0x0002: { if (fieldSize != 4) { raiseError(tr("Invalid entry group id field size")); return nullptr; @@ -620,8 +603,7 @@ Entry* KeePass1Reader::readEntry(QIODevice* cipherStream) m_entryGroupIds.insert(entry.data(), groupId); break; } - case 0x0003: - { + case 0x0003: { if (fieldSize != 4) { raiseError(tr("Invalid entry icon field size")); return nullptr; @@ -645,8 +627,7 @@ Entry* KeePass1Reader::readEntry(QIODevice* cipherStream) case 0x0008: parseNotes(QString::fromUtf8(fieldData.constData()), entry.data()); break; - case 0x0009: - { + case 0x0009: { if (fieldSize != 5) { raiseError(tr("Invalid entry creation time field size")); return nullptr; @@ -657,8 +638,7 @@ Entry* KeePass1Reader::readEntry(QIODevice* cipherStream) } break; } - case 0x000A: - { + case 0x000A: { if (fieldSize != 5) { raiseError(tr("Invalid entry modification time field size")); return nullptr; @@ -669,8 +649,7 @@ Entry* KeePass1Reader::readEntry(QIODevice* cipherStream) } break; } - case 0x000B: - { + case 0x000B: { if (fieldSize != 5) { raiseError(tr("Invalid entry creation time field size")); return nullptr; @@ -681,8 +660,7 @@ Entry* KeePass1Reader::readEntry(QIODevice* cipherStream) } break; } - case 0x000C: - { + case 0x000C: { if (fieldSize != 5) { raiseError(tr("Invalid entry expiry time field size")); return nullptr; @@ -734,27 +712,23 @@ void KeePass1Reader::parseNotes(const QString& rawNotes, Entry* entry) if (sequenceRegexp.exactMatch(line)) { if (sequenceRegexp.cap(1).isEmpty()) { entry->setDefaultAutoTypeSequence(sequenceRegexp.cap(2)); - } - else { + } else { sequences[sequenceRegexp.cap(1).toInt()] = sequenceRegexp.cap(2); } lastLineAutoType = true; - } - else if (windowRegexp.exactMatch(line)) { + } else if (windowRegexp.exactMatch(line)) { int nr; if (windowRegexp.cap(1).isEmpty()) { nr = -1; // special number that matches no other sequence - } - else { + } else { nr = windowRegexp.cap(1).toInt(); } windows[nr].append(windowRegexp.cap(2)); lastLineAutoType = true; - } - else { + } else { // don't add empty lines following a removed auto-type line if (!lastLineAutoType || !line.isEmpty()) { notes.append(line); @@ -788,8 +762,7 @@ bool KeePass1Reader::constructGroupTree(const QList& groups) if (level == 0) { groups[i]->setParent(m_db->rootGroup()); - } - else { + } else { for (int j = (i - 1); j >= 0; j--) { if (m_groupLevels.value(groups[j]) < level) { if ((level - m_groupLevels.value(groups[j])) != 1) { @@ -818,13 +791,11 @@ void KeePass1Reader::parseMetaStream(const Entry* entry) if (!parseGroupTreeState(data)) { qWarning("Unable to parse group tree state metastream."); } - } - else if (entry->notes() == "KPX_CUSTOM_ICONS_4") { + } else if (entry->notes() == "KPX_CUSTOM_ICONS_4") { if (!parseCustomIcons4(data)) { qWarning("Unable to parse custom icons metastream."); } - } - else { + } else { qWarning("Ignoring unknown metastream \"%s\".", entry->notes().toLocal8Bit().constData()); } } @@ -962,20 +933,16 @@ QDateTime KeePass1Reader::dateFromPackedStruct(const QByteArray& data) // check for the special "never" datetime if (dateTime == QDateTime(QDate(2999, 12, 28), QTime(23, 59, 59), Qt::UTC)) { return QDateTime(); - } - else { + } else { return dateTime; } } bool KeePass1Reader::isMetaStream(const Entry* entry) { - return entry->attachments()->keys().contains("bin-stream") - && !entry->notes().isEmpty() - && entry->title() == "Meta-Info" - && entry->username() == "SYSTEM" - && entry->url() == "$" - && entry->iconNumber() == 0; + return entry->attachments()->keys().contains("bin-stream") && !entry->notes().isEmpty() + && entry->title() == "Meta-Info" && entry->username() == "SYSTEM" && entry->url() == "$" + && entry->iconNumber() == 0; } QByteArray KeePass1Reader::readKeyfile(QIODevice* device) @@ -1002,8 +969,7 @@ QByteArray KeePass1Reader::readKeyfile(QIODevice* device) if (Tools::isHex(data)) { return QByteArray::fromHex(data); - } - else { + } else { device->seek(0); } } @@ -1021,16 +987,13 @@ QByteArray KeePass1Reader::readKeyfile(QIODevice* device) return cryptoHash.result(); } - QByteArray KeePass1Key::rawKey() const { if (m_keyfileData.isEmpty()) { return CryptoHash::hash(m_password, CryptoHash::Sha256); - } - else if (m_password.isEmpty()) { + } else if (m_password.isEmpty()) { return m_keyfileData; - } - else { + } else { CryptoHash keyHash(CryptoHash::Sha256); keyHash.addData(CryptoHash::hash(m_password, CryptoHash::Sha256)); keyHash.addData(m_keyfileData); diff --git a/src/format/KeePass1Reader.h b/src/format/KeePass1Reader.h index e98dd7d1f..8302746c8 100644 --- a/src/format/KeePass1Reader.h +++ b/src/format/KeePass1Reader.h @@ -34,12 +34,9 @@ class KeePass1Reader public: KeePass1Reader(); - Database* readDatabase(QIODevice* device, const QString& password, - QIODevice* keyfileDevice); - Database* readDatabase(QIODevice* device, const QString& password, - const QString& keyfileName); - Database* readDatabase(const QString& filename, const QString& password, - const QString& keyfileName); + Database* readDatabase(QIODevice* device, const QString& password, QIODevice* keyfileDevice); + Database* readDatabase(QIODevice* device, const QString& password, const QString& keyfileName); + Database* readDatabase(const QString& filename, const QString& password, const QString& keyfileName); bool hasError(); QString errorString(); @@ -51,8 +48,7 @@ private: UTF8 }; - SymmetricCipherStream* testKeys(const QString& password, const QByteArray& keyfileData, - qint64 contentPos); + SymmetricCipherStream* testKeys(const QString& password, const QByteArray& keyfileData, qint64 contentPos); QByteArray key(const QByteArray& password, const QByteArray& keyfileData); bool verifyKey(SymmetricCipherStream* cipherStream); Group* readGroup(QIODevice* cipherStream); diff --git a/src/format/KeePass2.cpp b/src/format/KeePass2.cpp index 9c0355cd4..b53ff092d 100644 --- a/src/format/KeePass2.cpp +++ b/src/format/KeePass2.cpp @@ -16,10 +16,10 @@ */ #include "KeePass2.h" -#include +#include "crypto/CryptoHash.h" #include "crypto/kdf/AesKdf.h" #include "crypto/kdf/Argon2Kdf.h" -#include "crypto/CryptoHash.h" +#include const Uuid KeePass2::CIPHER_AES = Uuid(QByteArray::fromHex("31c1f2e6bf714350be5805216afc5aff")); const Uuid KeePass2::CIPHER_TWOFISH = Uuid(QByteArray::fromHex("ad68f29f576f4bb9a36ad47af965346c")); @@ -47,16 +47,15 @@ const QString KeePass2::KDFPARAM_ARGON2_ASSOCDATA("A"); const QList> KeePass2::CIPHERS{ qMakePair(KeePass2::CIPHER_AES, QString(QT_TRANSLATE_NOOP("KeePass2", "AES: 256-bit"))), qMakePair(KeePass2::CIPHER_TWOFISH, QString(QT_TRANSLATE_NOOP("KeePass2", "Twofish: 256-bit"))), - qMakePair(KeePass2::CIPHER_CHACHA20, QString(QT_TRANSLATE_NOOP("KeePass2", "ChaCha20: 256-bit"))) -}; + qMakePair(KeePass2::CIPHER_CHACHA20, QString(QT_TRANSLATE_NOOP("KeePass2", "ChaCha20: 256-bit")))}; const QList> KeePass2::KDFS{ qMakePair(KeePass2::KDF_ARGON2, QString(QT_TRANSLATE_NOOP("KeePass2", "Argon2 (KDBX 4 – recommended)"))), qMakePair(KeePass2::KDF_AES_KDBX4, QString(QT_TRANSLATE_NOOP("KeePass2", "AES-KDF (KDBX 4)"))), - qMakePair(KeePass2::KDF_AES_KDBX3, QString(QT_TRANSLATE_NOOP("KeePass2", "AES-KDF (KDBX 3.1)"))) -}; + qMakePair(KeePass2::KDF_AES_KDBX3, QString(QT_TRANSLATE_NOOP("KeePass2", "AES-KDF (KDBX 3.1)")))}; -QByteArray KeePass2::hmacKey(QByteArray masterSeed, QByteArray transformedMasterKey) { +QByteArray KeePass2::hmacKey(QByteArray masterSeed, QByteArray transformedMasterKey) +{ CryptoHash hmacKeyHash(CryptoHash::Sha512); hmacKeyHash.addData(masterSeed); hmacKeyHash.addData(transformedMasterKey); diff --git a/src/format/KeePass2.h b/src/format/KeePass2.h index a46df7fa9..bcfef238f 100644 --- a/src/format/KeePass2.h +++ b/src/format/KeePass2.h @@ -1,137 +1,137 @@ - /* - * Copyright (C) 2010 Felix Geyer - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 2 or (at your option) - * version 3 of the License. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ +/* + * Copyright (C) 2010 Felix Geyer + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 2 or (at your option) + * version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ #ifndef KEEPASSX_KEEPASS2_H #define KEEPASSX_KEEPASS2_H -#include -#include -#include #include +#include #include +#include +#include +#include "core/Uuid.h" #include "crypto/SymmetricCipher.h" #include "crypto/kdf/Kdf.h" -#include "core/Uuid.h" namespace KeePass2 { -constexpr quint32 SIGNATURE_1 = 0x9AA2D903; -constexpr quint32 SIGNATURE_2 = 0xB54BFB67; + constexpr quint32 SIGNATURE_1 = 0x9AA2D903; + constexpr quint32 SIGNATURE_2 = 0xB54BFB67; -constexpr quint32 FILE_VERSION_CRITICAL_MASK = 0xFFFF0000; -constexpr quint32 FILE_VERSION_4 = 0x00040000; -constexpr quint32 FILE_VERSION_3_1 = 0x00030001; -constexpr quint32 FILE_VERSION_3 = 0x00030000; -constexpr quint32 FILE_VERSION_2 = 0x00020000; -constexpr quint32 FILE_VERSION_MIN = FILE_VERSION_2; + constexpr quint32 FILE_VERSION_CRITICAL_MASK = 0xFFFF0000; + constexpr quint32 FILE_VERSION_4 = 0x00040000; + constexpr quint32 FILE_VERSION_3_1 = 0x00030001; + constexpr quint32 FILE_VERSION_3 = 0x00030000; + constexpr quint32 FILE_VERSION_2 = 0x00020000; + constexpr quint32 FILE_VERSION_MIN = FILE_VERSION_2; -constexpr quint16 VARIANTMAP_VERSION = 0x0100; -constexpr quint16 VARIANTMAP_CRITICAL_MASK = 0xFF00; + constexpr quint16 VARIANTMAP_VERSION = 0x0100; + constexpr quint16 VARIANTMAP_CRITICAL_MASK = 0xFF00; -const QSysInfo::Endian BYTEORDER = QSysInfo::LittleEndian; + const QSysInfo::Endian BYTEORDER = QSysInfo::LittleEndian; -extern const Uuid CIPHER_AES; -extern const Uuid CIPHER_TWOFISH; -extern const Uuid CIPHER_CHACHA20; + extern const Uuid CIPHER_AES; + extern const Uuid CIPHER_TWOFISH; + extern const Uuid CIPHER_CHACHA20; -extern const Uuid KDF_AES_KDBX3; -extern const Uuid KDF_AES_KDBX4; -extern const Uuid KDF_ARGON2; + extern const Uuid KDF_AES_KDBX3; + extern const Uuid KDF_AES_KDBX4; + extern const Uuid KDF_ARGON2; -extern const QByteArray INNER_STREAM_SALSA20_IV; + extern const QByteArray INNER_STREAM_SALSA20_IV; -extern const QString KDFPARAM_UUID; -extern const QString KDFPARAM_AES_ROUNDS; -extern const QString KDFPARAM_AES_SEED; -extern const QString KDFPARAM_ARGON2_SALT; -extern const QString KDFPARAM_ARGON2_PARALLELISM; -extern const QString KDFPARAM_ARGON2_MEMORY; -extern const QString KDFPARAM_ARGON2_ITERATIONS; -extern const QString KDFPARAM_ARGON2_VERSION; -extern const QString KDFPARAM_ARGON2_SECRET; -extern const QString KDFPARAM_ARGON2_ASSOCDATA; + extern const QString KDFPARAM_UUID; + extern const QString KDFPARAM_AES_ROUNDS; + extern const QString KDFPARAM_AES_SEED; + extern const QString KDFPARAM_ARGON2_SALT; + extern const QString KDFPARAM_ARGON2_PARALLELISM; + extern const QString KDFPARAM_ARGON2_MEMORY; + extern const QString KDFPARAM_ARGON2_ITERATIONS; + extern const QString KDFPARAM_ARGON2_VERSION; + extern const QString KDFPARAM_ARGON2_SECRET; + extern const QString KDFPARAM_ARGON2_ASSOCDATA; -extern const QList> CIPHERS; -extern const QList> KDFS; + extern const QList> CIPHERS; + extern const QList> KDFS; -enum class HeaderFieldID -{ - EndOfHeader = 0, - Comment = 1, - CipherID = 2, - CompressionFlags = 3, - MasterSeed = 4, - TransformSeed = 5, - TransformRounds = 6, - EncryptionIV = 7, - ProtectedStreamKey = 8, - StreamStartBytes = 9, - InnerRandomStreamID = 10, - KdfParameters = 11, - PublicCustomData = 12 -}; + enum class HeaderFieldID + { + EndOfHeader = 0, + Comment = 1, + CipherID = 2, + CompressionFlags = 3, + MasterSeed = 4, + TransformSeed = 5, + TransformRounds = 6, + EncryptionIV = 7, + ProtectedStreamKey = 8, + StreamStartBytes = 9, + InnerRandomStreamID = 10, + KdfParameters = 11, + PublicCustomData = 12 + }; -enum class InnerHeaderFieldID : quint8 -{ - End = 0, - InnerRandomStreamID = 1, - InnerRandomStreamKey = 2, - Binary = 3 -}; + enum class InnerHeaderFieldID : quint8 + { + End = 0, + InnerRandomStreamID = 1, + InnerRandomStreamKey = 2, + Binary = 3 + }; -enum class ProtectedStreamAlgo -{ - ArcFourVariant = 1, - Salsa20 = 2, - ChaCha20 = 3, - InvalidProtectedStreamAlgo = -1 -}; + enum class ProtectedStreamAlgo + { + ArcFourVariant = 1, + Salsa20 = 2, + ChaCha20 = 3, + InvalidProtectedStreamAlgo = -1 + }; -enum class VariantMapFieldType : quint8 -{ - End = 0, - // Byte = 0x02, - // UInt16 = 0x03, - UInt32 = 0x04, - UInt64 = 0x05, - // Signed mask: 0x08 - Bool = 0x08, - // SByte = 0x0A, - // Int16 = 0x0B, - Int32 = 0x0C, - Int64 = 0x0D, - // Float = 0x10, - // Double = 0x11, - // Decimal = 0x12, - // Char = 0x17, // 16-bit Unicode character - String = 0x18, - // Array mask: 0x40 - ByteArray = 0x42 -}; + enum class VariantMapFieldType : quint8 + { + End = 0, + // Byte = 0x02, + // UInt16 = 0x03, + UInt32 = 0x04, + UInt64 = 0x05, + // Signed mask: 0x08 + Bool = 0x08, + // SByte = 0x0A, + // Int16 = 0x0B, + Int32 = 0x0C, + Int64 = 0x0D, + // Float = 0x10, + // Double = 0x11, + // Decimal = 0x12, + // Char = 0x17, // 16-bit Unicode character + String = 0x18, + // Array mask: 0x40 + ByteArray = 0x42 + }; -QByteArray hmacKey(QByteArray masterSeed, QByteArray transformedMasterKey); -QSharedPointer kdfFromParameters(const QVariantMap& p); -QVariantMap kdfToParameters(QSharedPointer kdf); -QSharedPointer uuidToKdf(const Uuid& uuid); -Uuid kdfToUuid(QSharedPointer kdf); -ProtectedStreamAlgo idToProtectedStreamAlgo(quint32 id); + QByteArray hmacKey(QByteArray masterSeed, QByteArray transformedMasterKey); + QSharedPointer kdfFromParameters(const QVariantMap& p); + QVariantMap kdfToParameters(QSharedPointer kdf); + QSharedPointer uuidToKdf(const Uuid& uuid); + Uuid kdfToUuid(QSharedPointer kdf); + ProtectedStreamAlgo idToProtectedStreamAlgo(quint32 id); -} // namespace KeePass2 +} // namespace KeePass2 #endif // KEEPASSX_KEEPASS2_H diff --git a/src/format/KeePass2RandomStream.cpp b/src/format/KeePass2RandomStream.cpp index 26824b7e5..2f8c8340d 100644 --- a/src/format/KeePass2RandomStream.cpp +++ b/src/format/KeePass2RandomStream.cpp @@ -30,8 +30,7 @@ bool KeePass2RandomStream::init(const QByteArray& key) { switch (m_cipher.algorithm()) { case SymmetricCipher::Salsa20: - return m_cipher.init(CryptoHash::hash(key, CryptoHash::Sha256), - KeePass2::INNER_STREAM_SALSA20_IV); + return m_cipher.init(CryptoHash::hash(key, CryptoHash::Sha256), KeePass2::INNER_STREAM_SALSA20_IV); case SymmetricCipher::ChaCha20: { QByteArray keyIv = CryptoHash::hash(key, CryptoHash::Sha512); return m_cipher.init(keyIv.left(32), keyIv.mid(32, 12)); @@ -121,7 +120,8 @@ bool KeePass2RandomStream::loadBlock() return true; } -SymmetricCipher::Algorithm KeePass2RandomStream::mapAlgo(KeePass2::ProtectedStreamAlgo algo) { +SymmetricCipher::Algorithm KeePass2RandomStream::mapAlgo(KeePass2::ProtectedStreamAlgo algo) +{ switch (algo) { case KeePass2::ProtectedStreamAlgo::ChaCha20: return SymmetricCipher::ChaCha20; diff --git a/src/format/KeePass2RandomStream.h b/src/format/KeePass2RandomStream.h index 1e341bacc..e41f5a5d6 100644 --- a/src/format/KeePass2RandomStream.h +++ b/src/format/KeePass2RandomStream.h @@ -20,8 +20,8 @@ #include -#include "crypto/SymmetricCipher.h" #include "KeePass2.h" +#include "crypto/SymmetricCipher.h" class KeePass2RandomStream { diff --git a/src/format/KeePass2Reader.cpp b/src/format/KeePass2Reader.cpp index abc7f54e1..1c16e76d6 100644 --- a/src/format/KeePass2Reader.cpp +++ b/src/format/KeePass2Reader.cpp @@ -16,9 +16,9 @@ */ #include "format/KeePass2Reader.h" -#include "format/KeePass1.h" #include "format/Kdbx3Reader.h" #include "format/Kdbx4Reader.h" +#include "format/KeePass1.h" #include diff --git a/src/format/KeePass2Reader.h b/src/format/KeePass2Reader.h index 1b91223ee..c4947c732 100644 --- a/src/format/KeePass2Reader.h +++ b/src/format/KeePass2Reader.h @@ -18,21 +18,21 @@ #ifndef KEEPASSX_KEEPASS2READER_H #define KEEPASSX_KEEPASS2READER_H -#include "format/KeePass2.h" -#include "core/Database.h" -#include "keys/CompositeKey.h" #include "KdbxReader.h" +#include "core/Database.h" +#include "format/KeePass2.h" +#include "keys/CompositeKey.h" -#include #include -#include #include -#include #include +#include +#include +#include class KeePass2Reader { -Q_DECLARE_TR_FUNCTIONS(KdbxReader) + Q_DECLARE_TR_FUNCTIONS(KdbxReader) public: Database* readDatabase(const QString& filename, const CompositeKey& key); @@ -46,6 +46,7 @@ public: QSharedPointer reader() const; quint32 version() const; + private: void raiseError(const QString& errorMessage); diff --git a/src/format/KeePass2Repair.cpp b/src/format/KeePass2Repair.cpp index 47ed59dc9..508a9517b 100644 --- a/src/format/KeePass2Repair.cpp +++ b/src/format/KeePass2Repair.cpp @@ -21,11 +21,11 @@ #include #include "core/Group.h" +#include "format/Kdbx4Reader.h" +#include "format/KdbxXmlReader.h" #include "format/KeePass2.h" #include "format/KeePass2RandomStream.h" #include "format/KeePass2Reader.h" -#include "format/Kdbx4Reader.h" -#include "format/KdbxXmlReader.h" KeePass2Repair::RepairOutcome KeePass2Repair::repairDatabase(QIODevice* device, const CompositeKey& key) { @@ -51,8 +51,7 @@ KeePass2Repair::RepairOutcome KeePass2Repair::repairDatabase(QIODevice* device, QRegExp encodingRegExp("encoding=\"([^\"]+)\"", Qt::CaseInsensitive, QRegExp::RegExp2); if (encodingRegExp.indexIn(xmlStart) != -1) { if (encodingRegExp.cap(1).compare("utf-8", Qt::CaseInsensitive) != 0 - && encodingRegExp.cap(1).compare("utf8", Qt::CaseInsensitive) != 0) - { + && encodingRegExp.cap(1).compare("utf8", Qt::CaseInsensitive) != 0) { // database is not utf-8 encoded, we don't support repairing that return qMakePair(RepairFailed, nullptr); } @@ -92,8 +91,7 @@ KeePass2Repair::RepairOutcome KeePass2Repair::repairDatabase(QIODevice* device, if (hasError) { return qMakePair(RepairFailed, nullptr); - } - else { + } else { return qMakePair(RepairSuccess, db.take()); } } diff --git a/src/format/KeePass2Writer.cpp b/src/format/KeePass2Writer.cpp index 325986a33..262bebc24 100644 --- a/src/format/KeePass2Writer.cpp +++ b/src/format/KeePass2Writer.cpp @@ -15,16 +15,16 @@ * along with this program. If not, see . */ -#include #include +#include #include "core/Database.h" #include "core/Group.h" #include "core/Metadata.h" #include "crypto/kdf/AesKdf.h" -#include "format/KeePass2Writer.h" #include "format/Kdbx3Writer.h" #include "format/Kdbx4Writer.h" +#include "format/KeePass2Writer.h" /** * Write a database to a KDBX file. @@ -52,17 +52,17 @@ bool KeePass2Writer::implicitUpgradeNeeded(Database const* db) const return true; } - for (const auto& group: db->rootGroup()->groupsRecursive(true)) { + for (const auto& group : db->rootGroup()->groupsRecursive(true)) { if (group->customData() && !group->customData()->isEmpty()) { return true; } - for (const auto& entry: group->entries()) { + for (const auto& entry : group->entries()) { if (entry->customData() && !entry->customData()->isEmpty()) { return true; } - for (const auto& historyItem: entry->historyItems()) { + for (const auto& historyItem : entry->historyItems()) { if (historyItem->customData() && !historyItem->customData()->isEmpty()) { return true; } @@ -81,7 +81,8 @@ bool KeePass2Writer::implicitUpgradeNeeded(Database const* db) const * @return true on success */ -bool KeePass2Writer::writeDatabase(QIODevice* device, Database* db) { +bool KeePass2Writer::writeDatabase(QIODevice* device, Database* db) +{ m_error = false; m_errorStr.clear(); diff --git a/src/format/KeePass2Writer.h b/src/format/KeePass2Writer.h index f024d4a83..e5b26eaea 100644 --- a/src/format/KeePass2Writer.h +++ b/src/format/KeePass2Writer.h @@ -28,7 +28,7 @@ class Database; class KeePass2Writer { -Q_DECLARE_TR_FUNCTIONS(KeePass2Writer) + Q_DECLARE_TR_FUNCTIONS(KeePass2Writer) public: bool writeDatabase(const QString& filename, Database* db); diff --git a/src/gui/AboutDialog.cpp b/src/gui/AboutDialog.cpp index 73d8ec553..5a082851f 100644 --- a/src/gui/AboutDialog.cpp +++ b/src/gui/AboutDialog.cpp @@ -20,16 +20,16 @@ #include "ui_AboutDialog.h" #include "config-keepassx.h" -#include "version.h" #include "core/FilePath.h" #include "crypto/Crypto.h" +#include "version.h" #include #include AboutDialog::AboutDialog(QWidget* parent) - : QDialog(parent), - m_ui(new Ui::AboutDialog()) + : QDialog(parent) + , m_ui(new Ui::AboutDialog()) { m_ui->setupUi(this); @@ -47,8 +47,7 @@ AboutDialog::AboutDialog(QWidget* parent) QString commitHash; if (!QString(GIT_HEAD).isEmpty()) { commitHash = GIT_HEAD; - } - else if (!QString(DIST_HASH).contains("Format")) { + } else if (!QString(DIST_HASH).contains("Format")) { commitHash = DIST_HASH; } @@ -66,16 +65,16 @@ AboutDialog::AboutDialog(QWidget* parent) #endif debugInfo.append("\n").append(QString("%1\n- Qt %2\n- %3\n\n") - .arg(tr("Libraries:")) - .arg(QString::fromLocal8Bit(qVersion())) - .arg(Crypto::backendVersion())); + .arg(tr("Libraries:")) + .arg(QString::fromLocal8Bit(qVersion())) + .arg(Crypto::backendVersion())); #if QT_VERSION >= QT_VERSION_CHECK(5, 4, 0) debugInfo.append(tr("Operating system: %1\nCPU architecture: %2\nKernel: %3 %4") - .arg(QSysInfo::prettyProductName(), - QSysInfo::currentCpuArchitecture(), - QSysInfo::kernelType(), - QSysInfo::kernelVersion())); + .arg(QSysInfo::prettyProductName(), + QSysInfo::currentCpuArchitecture(), + QSysInfo::kernelType(), + QSysInfo::kernelVersion())); debugInfo.append("\n\n"); #endif diff --git a/src/gui/AboutDialog.h b/src/gui/AboutDialog.h index 9d0c1c355..bd6b2edb9 100644 --- a/src/gui/AboutDialog.h +++ b/src/gui/AboutDialog.h @@ -22,7 +22,8 @@ #include #include -namespace Ui { +namespace Ui +{ class AboutDialog; } diff --git a/src/gui/Application.cpp b/src/gui/Application.cpp index 48cd0d8d7..02209b142 100644 --- a/src/gui/Application.cpp +++ b/src/gui/Application.cpp @@ -34,13 +34,14 @@ #if defined(Q_OS_UNIX) #include -#include #include +#include #endif -namespace { -constexpr int WaitTimeoutMSec = 150; -const char BlockSizeProperty[] = "blockSize"; +namespace +{ + constexpr int WaitTimeoutMSec = 150; + const char BlockSizeProperty[] = "blockSize"; } #if defined(Q_OS_UNIX) && !defined(Q_OS_OSX) @@ -70,7 +71,7 @@ public: Q_UNUSED(result); if (eventType == QByteArrayLiteral("windows_generic_MSG") - || eventType == QByteArrayLiteral("windows_dispatcher_MSG")) { + || eventType == QByteArrayLiteral("windows_dispatcher_MSG")) { int retCode = autoType()->callEventFilter(message); if (retCode == 1) { return true; @@ -109,8 +110,8 @@ Application::Application(int& argc, char** argv) identifier += "-" + userName; } #ifdef QT_DEBUG - // In DEBUG mode don't interfere with Release instances - identifier += "-DEBUG"; + // In DEBUG mode don't interfere with Release instances + identifier += "-DEBUG"; #endif QString lockName = identifier + ".lock"; m_socketName = identifier + ".socket"; @@ -146,9 +147,10 @@ Application::Application(int& argc, char** argv) if (!m_alreadyRunning) { // If we get here then the original instance is likely dead - qWarning() << QCoreApplication::translate("Main", - "Existing single-instance lock file is invalid. Launching new instance.") - .toUtf8().constData(); + qWarning() << QCoreApplication::translate( + "Main", "Existing single-instance lock file is invalid. Launching new instance.") + .toUtf8() + .constData(); // forceably reset the lock file m_lockFile->removeStaleLockFile(); @@ -161,8 +163,9 @@ Application::Application(int& argc, char** argv) } default: qWarning() << QCoreApplication::translate("Main", - "The lock file could not be created. Single-instance mode disabled.") - .toUtf8().constData(); + "The lock file could not be created. Single-instance mode disabled.") + .toUtf8() + .constData(); } } @@ -214,17 +217,17 @@ void Application::registerUnixSignals() // application will be unresponsive to signals such as SIGINT or SIGTERM return; } - - QVector const handledSignals = { SIGQUIT, SIGINT, SIGTERM, SIGHUP }; - for (auto s: handledSignals) { + + QVector const handledSignals = {SIGQUIT, SIGINT, SIGTERM, SIGHUP}; + for (auto s : handledSignals) { struct sigaction sigAction; - + sigAction.sa_handler = handleUnixSignal; sigemptyset(&sigAction.sa_mask); sigAction.sa_flags = 0 | SA_RESTART; sigaction(s, &sigAction, nullptr); } - + m_unixSignalNotifier = new QSocketNotifier(unixSignalSocket[1], QSocketNotifier::Read, this); connect(m_unixSignalNotifier, SIGNAL(activated(int)), this, SLOT(quitBySignal())); } @@ -232,16 +235,15 @@ void Application::registerUnixSignals() void Application::handleUnixSignal(int sig) { switch (sig) { - case SIGQUIT: - case SIGINT: - case SIGTERM: - { - char buf = 0; - Q_UNUSED(::write(unixSignalSocket[0], &buf, sizeof(buf))); - return; - } - case SIGHUP: - return; + case SIGQUIT: + case SIGINT: + case SIGTERM: { + char buf = 0; + Q_UNUSED(::write(unixSignalSocket[0], &buf, sizeof(buf))); + return; + } + case SIGHUP: + return; } } @@ -289,7 +291,7 @@ void Application::socketReadyRead() QStringList fileNames; in >> fileNames; - for (const QString& fileName: asConst(fileNames)) { + for (const QString& fileName : asConst(fileNames)) { const QFileInfo fInfo(fileName); if (fInfo.isFile() && fInfo.suffix().toLower() == "kdbx") { emit openFile(fileName); @@ -319,8 +321,7 @@ bool Application::sendFileNamesToRunningInstance(const QStringList& fileNames) QByteArray data; QDataStream out(&data, QIODevice::WriteOnly); out.setVersion(QDataStream::Qt_5_0); - out << quint32(0) - << fileNames; + out << quint32(0) << fileNames; out.device()->seek(0); out << quint32(data.size() - sizeof(quint32)); @@ -329,4 +330,3 @@ bool Application::sendFileNamesToRunningInstance(const QStringList& fileNames) const bool disconnected = client.waitForDisconnected(WaitTimeoutMSec); return writeOk && disconnected; } - diff --git a/src/gui/Application.h b/src/gui/Application.h index 1f5759368..a6c6fdf90 100644 --- a/src/gui/Application.h +++ b/src/gui/Application.h @@ -56,7 +56,7 @@ private slots: private: QWidget* m_mainWindow; - + #if defined(Q_OS_UNIX) /** * Register Unix signals such as SIGINT and SIGTERM for clean shutdown. diff --git a/src/gui/CategoryListWidget.cpp b/src/gui/CategoryListWidget.cpp index f091cc243..14429083b 100644 --- a/src/gui/CategoryListWidget.cpp +++ b/src/gui/CategoryListWidget.cpp @@ -19,15 +19,15 @@ #include "ui_CategoryListWidget.h" #include +#include #include #include #include -#include CategoryListWidget::CategoryListWidget(QWidget* parent) - : QWidget(parent), - m_itemDelegate(nullptr), - m_ui(new Ui::CategoryListWidget()) + : QWidget(parent) + , m_itemDelegate(nullptr) + , m_ui(new Ui::CategoryListWidget()) { m_ui->setupUi(this); m_itemDelegate = new CategoryListWidgetDelegate(m_ui->categoryList); @@ -38,7 +38,8 @@ CategoryListWidget::CategoryListWidget(QWidget* parent) connect(m_ui->scrollUp, SIGNAL(clicked()), SLOT(scrollCategoriesUp())); connect(m_ui->scrollDown, SIGNAL(clicked()), SLOT(scrollCategoriesDown())); connect(m_ui->categoryList->verticalScrollBar(), SIGNAL(valueChanged(int)), SLOT(updateCategoryScrollButtons())); - connect(m_ui->categoryList->verticalScrollBar(), SIGNAL(rangeChanged(int, int)), SLOT(updateCategoryScrollButtons())); + connect( + m_ui->categoryList->verticalScrollBar(), SIGNAL(rangeChanged(int, int)), SLOT(updateCategoryScrollButtons())); } CategoryListWidget::~CategoryListWidget() @@ -128,16 +129,14 @@ void CategoryListWidget::updateCategoryScrollButtons() void CategoryListWidget::scrollCategoriesUp() { - m_ui->categoryList->verticalScrollBar()->setValue( - m_ui->categoryList->verticalScrollBar()->value() - m_ui->categoryList->verticalScrollBar()->pageStep() - ); + m_ui->categoryList->verticalScrollBar()->setValue(m_ui->categoryList->verticalScrollBar()->value() + - m_ui->categoryList->verticalScrollBar()->pageStep()); } void CategoryListWidget::scrollCategoriesDown() { - m_ui->categoryList->verticalScrollBar()->setValue( - m_ui->categoryList->verticalScrollBar()->value() + m_ui->categoryList->verticalScrollBar()->pageStep() - ); + m_ui->categoryList->verticalScrollBar()->setValue(m_ui->categoryList->verticalScrollBar()->value() + + m_ui->categoryList->verticalScrollBar()->pageStep()); } void CategoryListWidget::emitCategoryChanged(int index) @@ -145,14 +144,12 @@ void CategoryListWidget::emitCategoryChanged(int index) emit categoryChanged(index); } - /* =============================================================================================== */ - CategoryListWidgetDelegate::CategoryListWidgetDelegate(QListWidget* parent) - : QStyledItemDelegate(parent), - m_listWidget(parent), - m_size(96, 96) + : QStyledItemDelegate(parent) + , m_listWidget(parent) + , m_size(96, 96) { m_size.setWidth(minWidth()); if (m_listWidget && m_listWidget->width() > m_size.width()) { @@ -165,7 +162,10 @@ CategoryListWidgetDelegate::CategoryListWidgetDelegate(QListWidget* parent) class WindowsCorrectedStyle : public QProxyStyle { public: - void drawPrimitive(PrimitiveElement element, const QStyleOption* option, QPainter* painter, const QWidget* widget) const override + void drawPrimitive(PrimitiveElement element, + const QStyleOption* option, + QPainter* painter, + const QWidget* widget) const override { painter->save(); @@ -187,7 +187,9 @@ public: }; #endif -void CategoryListWidgetDelegate::paint(QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index) const +void CategoryListWidgetDelegate::paint(QPainter* painter, + const QStyleOptionViewItem& option, + const QModelIndex& index) const { QStyleOptionViewItem opt = option; initStyleOption(&opt, index); @@ -225,8 +227,8 @@ int CategoryListWidgetDelegate::minWidth() const for (int i = 0; i < c; ++i) { QFontMetrics fm(m_listWidget->font()); - QRect fontRect = fm.boundingRect( - QRect(0, 0, 0, 0), Qt::TextWordWrap | Qt::ElideNone, m_listWidget->item(i)->text()); + QRect fontRect = + fm.boundingRect(QRect(0, 0, 0, 0), Qt::TextWordWrap | Qt::ElideNone, m_listWidget->item(i)->text()); if (fontRect.width() > maxWidth) { maxWidth = fontRect.width(); @@ -239,7 +241,7 @@ int CategoryListWidgetDelegate::minWidth() const return maxWidth < m_size.height() ? m_size.height() : maxWidth; } -QSize CategoryListWidgetDelegate::sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const +QSize CategoryListWidgetDelegate::sizeHint(const QStyleOptionViewItem& option, const QModelIndex& index) const { Q_UNUSED(option); Q_UNUSED(index); diff --git a/src/gui/CategoryListWidget.h b/src/gui/CategoryListWidget.h index 3cf82fd1b..911b5cc98 100644 --- a/src/gui/CategoryListWidget.h +++ b/src/gui/CategoryListWidget.h @@ -15,14 +15,15 @@ * along with this program. If not, see . */ -#include -#include #include +#include +#include class CategoryListWidgetDelegate; class QListWidget; -namespace Ui { +namespace Ui +{ class CategoryListWidget; } @@ -46,7 +47,7 @@ signals: protected: void showEvent(QShowEvent* event) override; - void resizeEvent(QResizeEvent * event) override; + void resizeEvent(QResizeEvent* event) override; QSize sizeHint() const override; QSize minimumSizeHint() const override; @@ -63,10 +64,8 @@ private: Q_DISABLE_COPY(CategoryListWidget) }; - /* =============================================================================================== */ - class CategoryListWidgetDelegate : public QStyledItemDelegate { Q_OBJECT @@ -77,10 +76,9 @@ public: protected: void paint(QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index) const override; - QSize sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const override; + QSize sizeHint(const QStyleOptionViewItem& option, const QModelIndex& index) const override; private: - const int ICON_SIZE = 32; QPointer m_listWidget; diff --git a/src/gui/ChangeMasterKeyWidget.cpp b/src/gui/ChangeMasterKeyWidget.cpp index 79fd2712b..b91495f78 100644 --- a/src/gui/ChangeMasterKeyWidget.cpp +++ b/src/gui/ChangeMasterKeyWidget.cpp @@ -19,19 +19,19 @@ #include "ChangeMasterKeyWidget.h" #include "ui_ChangeMasterKeyWidget.h" +#include "MainWindow.h" #include "core/FilePath.h" +#include "crypto/Random.h" +#include "gui/FileDialog.h" +#include "gui/MessageBox.h" #include "keys/FileKey.h" #include "keys/PasswordKey.h" #include "keys/YkChallengeResponseKey.h" -#include "gui/FileDialog.h" -#include "gui/MessageBox.h" -#include "crypto/Random.h" -#include "MainWindow.h" #include "config-keepassx.h" -#include #include +#include ChangeMasterKeyWidget::ChangeMasterKeyWidget(QWidget* parent) : DialogyWidget(parent) @@ -65,7 +65,7 @@ ChangeMasterKeyWidget::ChangeMasterKeyWidget(QWidget* parent) connect(m_ui->challengeResponseGroup, SIGNAL(clicked(bool)), SLOT(setOkEnabled())); connect(m_ui->buttonRedetectYubikey, SIGNAL(clicked()), SLOT(pollYubikey())); - connect(YubiKey::instance(), SIGNAL(detected(int,bool)), SLOT(yubikeyDetected(int,bool)), Qt::QueuedConnection); + connect(YubiKey::instance(), SIGNAL(detected(int, bool)), SLOT(yubikeyDetected(int, bool)), Qt::QueuedConnection); connect(YubiKey::instance(), SIGNAL(notFound()), SLOT(noYubikeyFound()), Qt::QueuedConnection); #else m_ui->challengeResponseGroup->setVisible(false); @@ -86,8 +86,7 @@ void ChangeMasterKeyWidget::createKeyFile() bool created = FileKey::create(fileName, &errorMsg); if (!created) { m_ui->messageWidget->showMessage(tr("Unable to create key file: %1").arg(errorMsg), MessageWidget::Error); - } - else { + } else { m_ui->keyFileCombo->setEditText(fileName); } } @@ -138,15 +137,16 @@ void ChangeMasterKeyWidget::generateKey() if (m_ui->passwordGroup->isChecked()) { if (m_ui->enterPasswordEdit->text() == m_ui->repeatPasswordEdit->text()) { if (m_ui->enterPasswordEdit->text().isEmpty()) { - if (MessageBox::warning(this, tr("Empty password"), + if (MessageBox::warning(this, + tr("Empty password"), tr("Do you really want to use an empty string as password?"), - QMessageBox::Yes | QMessageBox::No) != QMessageBox::Yes) { + QMessageBox::Yes | QMessageBox::No) + != QMessageBox::Yes) { return; } } m_key.addKey(PasswordKey(m_ui->enterPasswordEdit->text())); - } - else { + } else { m_ui->messageWidget->showMessage(tr("Different passwords supplied."), MessageWidget::Error); m_ui->enterPasswordEdit->setText(""); m_ui->repeatPasswordEdit->setText(""); @@ -158,16 +158,16 @@ void ChangeMasterKeyWidget::generateKey() QString errorMsg; QString fileKeyName = m_ui->keyFileCombo->currentText(); if (!fileKey.load(fileKeyName, &errorMsg)) { - m_ui->messageWidget->showMessage( - tr("Failed to set %1 as the key file:\n%2").arg(fileKeyName, errorMsg), MessageWidget::Error); + m_ui->messageWidget->showMessage(tr("Failed to set %1 as the key file:\n%2").arg(fileKeyName, errorMsg), + MessageWidget::Error); return; } if (fileKey.type() != FileKey::Hashed) { QMessageBox::warning(this, tr("Legacy key file format"), tr("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."), + "unsupported in the future.\n\n" + "Please consider generating a new key file."), QMessageBox::Ok); } m_key.addKey(fileKey); @@ -186,8 +186,8 @@ void ChangeMasterKeyWidget::generateKey() // read blocking mode from LSB and slot index number from second LSB bool blocking = comboPayload & 1; - int slot = comboPayload >> 1; - auto key = QSharedPointer(new YkChallengeResponseKey(slot, blocking)); + int slot = comboPayload >> 1; + auto key = QSharedPointer(new YkChallengeResponseKey(slot, blocking)); m_key.addChallengeResponseKey(key); } #endif @@ -196,7 +196,6 @@ void ChangeMasterKeyWidget::generateKey() emit editFinished(true); } - void ChangeMasterKeyWidget::reject() { emit editFinished(false); @@ -240,9 +239,9 @@ void ChangeMasterKeyWidget::noYubikeyFound() void ChangeMasterKeyWidget::setOkEnabled() { - bool ok = m_ui->passwordGroup->isChecked() || - (m_ui->challengeResponseGroup->isChecked() && !m_ui->comboChallengeResponse->currentText().isEmpty()) || - (m_ui->keyFileGroup->isChecked() && !m_ui->keyFileCombo->currentText().isEmpty()); + bool ok = m_ui->passwordGroup->isChecked() + || (m_ui->challengeResponseGroup->isChecked() && !m_ui->comboChallengeResponse->currentText().isEmpty()) + || (m_ui->keyFileGroup->isChecked() && !m_ui->keyFileCombo->currentText().isEmpty()); m_ui->buttonBox->button(QDialogButtonBox::Ok)->setEnabled(ok); } diff --git a/src/gui/ChangeMasterKeyWidget.h b/src/gui/ChangeMasterKeyWidget.h index 2825d8d55..2a4e0cc4a 100644 --- a/src/gui/ChangeMasterKeyWidget.h +++ b/src/gui/ChangeMasterKeyWidget.h @@ -25,7 +25,8 @@ #include "keys/CompositeKey.h" class QLabel; -namespace Ui { +namespace Ui +{ class ChangeMasterKeyWidget; } diff --git a/src/gui/Clipboard.cpp b/src/gui/Clipboard.cpp index 2c0d3d6ed..b30fd64b7 100644 --- a/src/gui/Clipboard.cpp +++ b/src/gui/Clipboard.cpp @@ -88,8 +88,7 @@ void Clipboard::clearClipboard() clipboard->clear(QClipboard::Clipboard); } - if (clipboard->supportsSelection() - && (clipboard->text(QClipboard::Selection) == m_lastCopied)) { + if (clipboard->supportsSelection() && (clipboard->text(QClipboard::Selection) == m_lastCopied)) { clipboard->clear(QClipboard::Selection); } diff --git a/src/gui/Clipboard.h b/src/gui/Clipboard.h index 279ae7f03..60c66c885 100644 --- a/src/gui/Clipboard.h +++ b/src/gui/Clipboard.h @@ -55,7 +55,8 @@ private: QString m_lastCopied; }; -inline Clipboard* clipboard() { +inline Clipboard* clipboard() +{ return Clipboard::instance(); } diff --git a/src/gui/CloneDialog.cpp b/src/gui/CloneDialog.cpp index 7af504395..990a590e0 100644 --- a/src/gui/CloneDialog.cpp +++ b/src/gui/CloneDialog.cpp @@ -19,12 +19,12 @@ #include "ui_CloneDialog.h" #include "config-keepassx.h" -#include "version.h" #include "core/Database.h" #include "core/Entry.h" #include "core/FilePath.h" #include "crypto/Crypto.h" #include "gui/DatabaseWidget.h" +#include "version.h" CloneDialog::CloneDialog(DatabaseWidget* parent, Database* db, Entry* entry) : QDialog(parent) diff --git a/src/gui/CloneDialog.h b/src/gui/CloneDialog.h index a925bb47a..569938464 100644 --- a/src/gui/CloneDialog.h +++ b/src/gui/CloneDialog.h @@ -18,13 +18,14 @@ #ifndef KEEPASSX_CLONEDIALOG_H #define KEEPASSX_CLONEDIALOG_H +#include "core/Database.h" +#include "core/Entry.h" +#include "gui/DatabaseWidget.h" #include #include -#include "core/Entry.h" -#include "core/Database.h" -#include "gui/DatabaseWidget.h" -namespace Ui { +namespace Ui +{ class CloneDialog; } diff --git a/src/gui/DatabaseOpenWidget.cpp b/src/gui/DatabaseOpenWidget.cpp index 16792e78a..78fa08587 100644 --- a/src/gui/DatabaseOpenWidget.cpp +++ b/src/gui/DatabaseOpenWidget.cpp @@ -22,20 +22,19 @@ #include "core/Config.h" #include "core/Database.h" #include "core/FilePath.h" -#include "gui/MainWindow.h" -#include "gui/FileDialog.h" -#include "gui/MessageBox.h" +#include "crypto/Random.h" #include "format/KeePass2Reader.h" +#include "gui/FileDialog.h" +#include "gui/MainWindow.h" +#include "gui/MessageBox.h" #include "keys/FileKey.h" #include "keys/PasswordKey.h" -#include "crypto/Random.h" #include "keys/YkChallengeResponseKey.h" #include "config-keepassx.h" -#include #include - +#include DatabaseOpenWidget::DatabaseOpenWidget(QWidget* parent) : DialogyWidget(parent) @@ -52,8 +51,7 @@ DatabaseOpenWidget::DatabaseOpenWidget(QWidget* parent) m_ui->labelHeadline->setFont(font); m_ui->buttonTogglePassword->setIcon(filePath()->onOffIcon("actions", "password-show")); - connect(m_ui->buttonTogglePassword, SIGNAL(toggled(bool)), - m_ui->editPassword, SLOT(setShowPassword(bool))); + connect(m_ui->buttonTogglePassword, SIGNAL(toggled(bool)), m_ui->editPassword, SLOT(setShowPassword(bool))); connect(m_ui->buttonBrowseFile, SIGNAL(clicked()), SLOT(browseKeyFile())); connect(m_ui->editPassword, SIGNAL(textChanged(QString)), SLOT(activatePassword())); @@ -97,8 +95,8 @@ void DatabaseOpenWidget::showEvent(QShowEvent* event) #ifdef WITH_XC_YUBIKEY // showEvent() may be called twice, so make sure we are only polling once if (!m_yubiKeyBeingPolled) { - connect(YubiKey::instance(), SIGNAL(detected(int, bool)), SLOT(yubikeyDetected(int, bool)), - Qt::QueuedConnection); + connect( + YubiKey::instance(), SIGNAL(detected(int, bool)), SLOT(yubikeyDetected(int, bool)), Qt::QueuedConnection); connect(YubiKey::instance(), SIGNAL(detectComplete()), SLOT(yubikeyDetectComplete()), Qt::QueuedConnection); connect(YubiKey::instance(), SIGNAL(notFound()), SLOT(noYubikeyFound()), Qt::QueuedConnection); @@ -147,7 +145,6 @@ void DatabaseOpenWidget::clearForms() m_db = nullptr; } - Database* DatabaseOpenWidget::database() { return m_db; @@ -178,8 +175,8 @@ void DatabaseOpenWidget::openDatabase() QFile file(m_filename); if (!file.open(QIODevice::ReadOnly)) { - m_ui->messageWidget->showMessage( - tr("Unable to open the database.").append("\n").append(file.errorString()), MessageWidget::Error); + m_ui->messageWidget->showMessage(tr("Unable to open the database.").append("\n").append(file.errorString()), + MessageWidget::Error); return; } if (m_db) { @@ -217,22 +214,21 @@ QSharedPointer DatabaseOpenWidget::databaseKey() QString keyFilename = m_ui->comboKeyFile->currentText(); QString errorMsg; if (!key.load(keyFilename, &errorMsg)) { - m_ui->messageWidget->showMessage(tr("Can't open key file:\n%1").arg(errorMsg), - MessageWidget::Error); + m_ui->messageWidget->showMessage(tr("Can't open key file:\n%1").arg(errorMsg), MessageWidget::Error); return QSharedPointer(); } if (key.type() != FileKey::Hashed && !config()->get("Messages/NoLegacyKeyFileWarning").toBool()) { QMessageBox legacyWarning; legacyWarning.setWindowTitle(tr("Legacy key file format")); legacyWarning.setText(tr("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.")); + "unsupported in the future.\n\n" + "Please consider generating a new key file.")); legacyWarning.setIcon(QMessageBox::Icon::Warning); legacyWarning.addButton(QMessageBox::Ok); legacyWarning.setDefaultButton(QMessageBox::Ok); legacyWarning.setCheckBox(new QCheckBox(tr("Don't show this warning again"))); - connect(legacyWarning.checkBox(), &QCheckBox::stateChanged, [](int state){ + connect(legacyWarning.checkBox(), &QCheckBox::stateChanged, [](int state) { config()->set("Messages/NoLegacyKeyFileWarning", state == Qt::CheckState::Checked); }); diff --git a/src/gui/DatabaseOpenWidget.h b/src/gui/DatabaseOpenWidget.h index aade111c3..0c4c938b8 100644 --- a/src/gui/DatabaseOpenWidget.h +++ b/src/gui/DatabaseOpenWidget.h @@ -27,7 +27,8 @@ class Database; class QFile; -namespace Ui { +namespace Ui +{ class DatabaseOpenWidget; } diff --git a/src/gui/DatabaseRepairWidget.cpp b/src/gui/DatabaseRepairWidget.cpp index aa9613a25..b4be71247 100644 --- a/src/gui/DatabaseRepairWidget.cpp +++ b/src/gui/DatabaseRepairWidget.cpp @@ -21,13 +21,13 @@ #include #include -#include "ui_DatabaseOpenWidget.h" #include "core/Database.h" #include "core/Metadata.h" #include "format/KeePass2Repair.h" #include "gui/MessageBox.h" #include "keys/FileKey.h" #include "keys/PasswordKey.h" +#include "ui_DatabaseOpenWidget.h" DatabaseRepairWidget::DatabaseRepairWidget(QWidget* parent) : DatabaseOpenWidget(parent) @@ -61,8 +61,8 @@ void DatabaseRepairWidget::openDatabase() QFile file(m_filename); if (!file.open(QIODevice::ReadOnly)) { - MessageBox::warning(this, tr("Error"), tr("Unable to open the database.").append("\n") - .append(file.errorString())); + MessageBox::warning( + this, tr("Error"), tr("Unable to open the database.").append("\n").append(file.errorString())); emit editFinished(false); return; } @@ -80,13 +80,14 @@ void DatabaseRepairWidget::openDatabase() emit editFinished(false); return; case KeePass2Repair::UnableToOpen: - MessageBox::warning(this, tr("Error"), tr("Unable to open the database.").append("\n") - .append(repair.errorString())); + MessageBox::warning( + this, tr("Error"), tr("Unable to open the database.").append("\n").append(repair.errorString())); emit editFinished(false); return; case KeePass2Repair::RepairSuccess: m_db = repairOutcome.second; - MessageBox::warning(this, tr("Success"), tr("The database has been successfully repaired\nYou can now save it.")); + MessageBox::warning( + this, tr("Success"), tr("The database has been successfully repaired\nYou can now save it.")); emit editFinished(true); return; case KeePass2Repair::RepairFailed: @@ -100,8 +101,7 @@ void DatabaseRepairWidget::processEditFinished(bool result) { if (result) { emit success(); - } - else { + } else { emit error(); } } diff --git a/src/gui/DatabaseSettingsWidget.cpp b/src/gui/DatabaseSettingsWidget.cpp index 79b84f88c..1fa95c106 100644 --- a/src/gui/DatabaseSettingsWidget.cpp +++ b/src/gui/DatabaseSettingsWidget.cpp @@ -18,22 +18,22 @@ #include "DatabaseSettingsWidget.h" #include "ui_DatabaseSettingsWidget.h" -#include "ui_DatabaseSettingsWidgetGeneral.h" #include "ui_DatabaseSettingsWidgetEncryption.h" +#include "ui_DatabaseSettingsWidgetGeneral.h" #include #include #include -#include "core/Global.h" -#include "core/FilePath.h" +#include "MessageBox.h" #include "core/AsyncTask.h" #include "core/Database.h" +#include "core/FilePath.h" +#include "core/Global.h" #include "core/Group.h" #include "core/Metadata.h" #include "crypto/SymmetricCipher.h" #include "crypto/kdf/Argon2Kdf.h" -#include "MessageBox.h" DatabaseSettingsWidget::DatabaseSettingsWidget(QWidget* parent) : DialogyWidget(parent) @@ -50,10 +50,14 @@ DatabaseSettingsWidget::DatabaseSettingsWidget(QWidget* parent) connect(m_ui->buttonBox, SIGNAL(accepted()), SLOT(save())); connect(m_ui->buttonBox, SIGNAL(rejected()), SLOT(reject())); - connect(m_uiGeneral->historyMaxItemsCheckBox, SIGNAL(toggled(bool)), - m_uiGeneral->historyMaxItemsSpinBox, SLOT(setEnabled(bool))); - connect(m_uiGeneral->historyMaxSizeCheckBox, SIGNAL(toggled(bool)), - m_uiGeneral->historyMaxSizeSpinBox, SLOT(setEnabled(bool))); + connect(m_uiGeneral->historyMaxItemsCheckBox, + SIGNAL(toggled(bool)), + m_uiGeneral->historyMaxItemsSpinBox, + SLOT(setEnabled(bool))); + connect(m_uiGeneral->historyMaxSizeCheckBox, + SIGNAL(toggled(bool)), + m_uiGeneral->historyMaxSizeSpinBox, + SLOT(setEnabled(bool))); connect(m_uiEncryption->transformBenchmarkButton, SIGNAL(clicked()), SLOT(transformRoundsBenchmark())); connect(m_uiEncryption->kdfComboBox, SIGNAL(currentIndexChanged(int)), SLOT(kdfChanged(int))); @@ -101,8 +105,9 @@ void DatabaseSettingsWidget::load(Database* db) } m_uiEncryption->algorithmComboBox->clear(); - for (auto& cipher: asConst(KeePass2::CIPHERS)) { - m_uiEncryption->algorithmComboBox->addItem(QCoreApplication::translate("KeePass2", cipher.second.toUtf8()), cipher.first.toByteArray()); + for (auto& cipher : asConst(KeePass2::CIPHERS)) { + m_uiEncryption->algorithmComboBox->addItem(QCoreApplication::translate("KeePass2", cipher.second.toUtf8()), + cipher.first.toByteArray()); } int cipherIndex = m_uiEncryption->algorithmComboBox->findData(m_db->cipher().toByteArray()); if (cipherIndex > -1) { @@ -112,8 +117,9 @@ void DatabaseSettingsWidget::load(Database* db) // Setup kdf combo box m_uiEncryption->kdfComboBox->blockSignals(true); m_uiEncryption->kdfComboBox->clear(); - for (auto& kdf: asConst(KeePass2::KDFS)) { - m_uiEncryption->kdfComboBox->addItem(QCoreApplication::translate("KeePass2", kdf.second.toUtf8()), kdf.first.toByteArray()); + for (auto& kdf : asConst(KeePass2::KDFS)) { + m_uiEncryption->kdfComboBox->addItem(QCoreApplication::translate("KeePass2", kdf.second.toUtf8()), + kdf.first.toByteArray()); } m_uiEncryption->kdfComboBox->blockSignals(false); @@ -158,7 +164,7 @@ void DatabaseSettingsWidget::save() return; } } else if ((kdf->uuid() == KeePass2::KDF_AES_KDBX3 || kdf->uuid() == KeePass2::KDF_AES_KDBX4) - && m_uiEncryption->transformRoundsSpinBox->value() < 100000) { + && m_uiEncryption->transformRoundsSpinBox->value() < 100000) { QMessageBox warning; warning.setIcon(QMessageBox::Warning); warning.setWindowTitle(tr("Number of rounds too low", "Key transformation rounds")); @@ -173,7 +179,8 @@ void DatabaseSettingsWidget::save() } } - m_db->setCompressionAlgo(m_uiGeneral->compressionCheckbox->isChecked() ? Database::CompressionGZip : Database::CompressionNone); + m_db->setCompressionAlgo(m_uiGeneral->compressionCheckbox->isChecked() ? Database::CompressionGZip + : Database::CompressionNone); Metadata* meta = m_db->metadata(); @@ -228,7 +235,8 @@ void DatabaseSettingsWidget::save() QApplication::restoreOverrideCursor(); if (!ok) { - MessageBox::warning(this, tr("KDF unchanged"), + MessageBox::warning(this, + tr("KDF unchanged"), tr("Failed to transform key with new KDF parameters; KDF unchanged."), QMessageBox::Ok); } @@ -261,9 +269,7 @@ void DatabaseSettingsWidget::transformRoundsBenchmark() } // Determine the number of rounds required to meet 1 second delay - int rounds = AsyncTask::runAndWaitForFuture([&kdf]() { - return kdf->benchmark(1000); - }); + int rounds = AsyncTask::runAndWaitForFuture([&kdf]() { return kdf->benchmark(1000); }); m_uiEncryption->transformRoundsSpinBox->setValue(rounds); m_uiEncryption->transformBenchmarkButton->setEnabled(true); @@ -298,8 +304,7 @@ void DatabaseSettingsWidget::kdfChanged(int index) */ void DatabaseSettingsWidget::memoryChanged(int value) { - m_uiEncryption->memorySpinBox->setSuffix( - tr(" MiB", "Abbreviation for Mebibytes (KDF settings)", value)); + m_uiEncryption->memorySpinBox->setSuffix(tr(" MiB", "Abbreviation for Mebibytes (KDF settings)", value)); } /** diff --git a/src/gui/DatabaseSettingsWidget.h b/src/gui/DatabaseSettingsWidget.h index b0cae5dbc..5abad8e05 100644 --- a/src/gui/DatabaseSettingsWidget.h +++ b/src/gui/DatabaseSettingsWidget.h @@ -18,26 +18,26 @@ #ifndef KEEPASSX_DATABASESETTINGSWIDGET_H #define KEEPASSX_DATABASESETTINGSWIDGET_H -#include -#include -#include #include +#include +#include +#include -#include "gui/DialogyWidget.h" #include "crypto/kdf/Kdf.h" +#include "gui/DialogyWidget.h" class Database; namespace Ui { -class DatabaseSettingsWidget; -class DatabaseSettingsWidgetGeneral; -class DatabaseSettingsWidgetEncryption; + class DatabaseSettingsWidget; + class DatabaseSettingsWidgetGeneral; + class DatabaseSettingsWidgetEncryption; } -class DatabaseSettingsWidget: public DialogyWidget +class DatabaseSettingsWidget : public DialogyWidget { -Q_OBJECT + Q_OBJECT public: explicit DatabaseSettingsWidget(QWidget* parent = nullptr); diff --git a/src/gui/DatabaseTabWidget.cpp b/src/gui/DatabaseTabWidget.cpp index 832512e91..ff7a42282 100644 --- a/src/gui/DatabaseTabWidget.cpp +++ b/src/gui/DatabaseTabWidget.cpp @@ -19,16 +19,16 @@ #include "DatabaseTabWidget.h" #include -#include #include +#include #include "autotype/AutoType.h" +#include "core/AsyncTask.h" #include "core/Config.h" -#include "core/Global.h" #include "core/Database.h" +#include "core/Global.h" #include "core/Group.h" #include "core/Metadata.h" -#include "core/AsyncTask.h" #include "format/CsvExporter.h" #include "gui/Clipboard.h" #include "gui/DatabaseWidget.h" @@ -36,9 +36,9 @@ #include "gui/DragTabBar.h" #include "gui/FileDialog.h" #include "gui/MessageBox.h" +#include "gui/UnlockDatabaseDialog.h" #include "gui/entry/EntryView.h" #include "gui/group/GroupView.h" -#include "gui/UnlockDatabaseDialog.h" DatabaseManagerStruct::DatabaseManagerStruct() : dbWidget(nullptr) @@ -48,7 +48,6 @@ DatabaseManagerStruct::DatabaseManagerStruct() { } - const int DatabaseTabWidget::LastDatabasesCount = 5; DatabaseTabWidget::DatabaseTabWidget(QWidget* parent) @@ -62,7 +61,8 @@ DatabaseTabWidget::DatabaseTabWidget(QWidget* parent) connect(this, SIGNAL(tabCloseRequested(int)), SLOT(closeDatabase(int))); connect(this, SIGNAL(currentChanged(int)), SLOT(emitActivateDatabaseChanged())); - connect(this, SIGNAL(activateDatabaseChanged(DatabaseWidget*)), m_dbWidgetStateSync, SLOT(setActive(DatabaseWidget*))); + connect( + this, SIGNAL(activateDatabaseChanged(DatabaseWidget*)), m_dbWidgetStateSync, SLOT(setActive(DatabaseWidget*))); connect(autoType(), SIGNAL(globalShortcutTriggered()), SLOT(performGlobalAutoType())); connect(autoType(), SIGNAL(autotypePerformed()), SLOT(relockPendingDatabase())); } @@ -108,15 +108,13 @@ void DatabaseTabWidget::newDatabase() void DatabaseTabWidget::openDatabase() { QString filter = QString("%1 (*.kdbx);;%2 (*)").arg(tr("KeePass 2 Database"), tr("All files")); - QString fileName = fileDialog()->getOpenFileName(this, tr("Open database"), QDir::homePath(), - filter); + QString fileName = fileDialog()->getOpenFileName(this, tr("Open database"), QDir::homePath(), filter); if (!fileName.isEmpty()) { openDatabase(fileName); } } -void DatabaseTabWidget::openDatabase(const QString& fileName, const QString& pw, - const QString& keyFile) +void DatabaseTabWidget::openDatabase(const QString& fileName, const QString& pw, const QString& keyFile) { QFileInfo fileInfo(fileName); QString canonicalFilePath = fileInfo.canonicalFilePath(); @@ -125,7 +123,6 @@ void DatabaseTabWidget::openDatabase(const QString& fileName, const QString& pw, return; } - QHashIterator i(m_dbList); while (i.hasNext()) { i.next(); @@ -147,11 +144,10 @@ void DatabaseTabWidget::openDatabase(const QString& fileName, const QString& pw, if (!file.open(QIODevice::ReadWrite)) { if (!file.open(QIODevice::ReadOnly)) { // can't open - emit messageGlobal( - tr("Unable to open the database.").append("\n").append(file.errorString()), MessageWidget::Error); + emit messageGlobal(tr("Unable to open the database.").append("\n").append(file.errorString()), + MessageWidget::Error); return; - } - else { + } else { // can only open read-only dbStruct.readOnly = true; } @@ -175,15 +171,14 @@ void DatabaseTabWidget::openDatabase(const QString& fileName, const QString& pw, } else { dbStruct.dbWidget->switchToOpenDatabase(dbStruct.fileInfo.absoluteFilePath()); } - + emit messageDismissTab(); } void DatabaseTabWidget::importCsv() { QString filter = QString("%1 (*.csv);;%2 (*)").arg(tr("CSV file"), tr("All files")); - QString fileName = fileDialog()->getOpenFileName(this, tr("Open CSV file"), QString(), - filter); + QString fileName = fileDialog()->getOpenFileName(this, tr("Open CSV file"), QString(), filter); if (fileName.isEmpty()) { return; @@ -200,8 +195,7 @@ void DatabaseTabWidget::importCsv() void DatabaseTabWidget::mergeDatabase() { QString filter = QString("%1 (*.kdbx);;%2 (*)").arg(tr("KeePass 2 Database"), tr("All files")); - const QString fileName = fileDialog()->getOpenFileName(this, tr("Merge database"), QString(), - filter); + const QString fileName = fileDialog()->getOpenFileName(this, tr("Merge database"), QString(), filter); if (!fileName.isEmpty()) { mergeDatabase(fileName); } @@ -215,8 +209,7 @@ void DatabaseTabWidget::mergeDatabase(const QString& fileName) void DatabaseTabWidget::importKeePass1Database() { QString filter = QString("%1 (*.kdb);;%2 (*)").arg(tr("KeePass 1 database"), tr("All files")); - QString fileName = fileDialog()->getOpenFileName(this, tr("Open KeePass 1 database"), QString(), - filter); + QString fileName = fileDialog()->getOpenFileName(this, tr("Open KeePass 1 database"), QString(), filter); if (fileName.isEmpty()) { return; @@ -247,11 +240,12 @@ bool DatabaseTabWidget::closeDatabase(Database* db) dbName.chop(1); } if (dbStruct.dbWidget->isInEditMode() && db->hasKey() && dbStruct.dbWidget->isEditWidgetModified()) { - QMessageBox::StandardButton result = - MessageBox::question( - this, tr("Close?"), + QMessageBox::StandardButton result = MessageBox::question( + this, + tr("Close?"), tr("\"%1\" is in edit mode.\nDiscard changes and close anyway?").arg(dbName.toHtmlEscaped()), - QMessageBox::Discard | QMessageBox::Cancel, QMessageBox::Cancel); + QMessageBox::Discard | QMessageBox::Cancel, + QMessageBox::Cancel); if (result == QMessageBox::Cancel) { return false; } @@ -263,10 +257,11 @@ bool DatabaseTabWidget::closeDatabase(Database* db) } } else if (dbStruct.dbWidget->currentMode() != DatabaseWidget::LockedMode) { QMessageBox::StandardButton result = - MessageBox::question( - this, tr("Save changes?"), - tr("\"%1\" was modified.\nSave changes?").arg(dbName.toHtmlEscaped()), - QMessageBox::Yes | QMessageBox::Discard | QMessageBox::Cancel, QMessageBox::Yes); + MessageBox::question(this, + tr("Save changes?"), + tr("\"%1\" was modified.\nSave changes?").arg(dbName.toHtmlEscaped()), + QMessageBox::Yes | QMessageBox::Discard | QMessageBox::Cancel, + QMessageBox::Yes); if (result == QMessageBox::Yes) { if (!saveDatabase(db)) { return false; @@ -349,11 +344,13 @@ bool DatabaseTabWidget::saveDatabase(Database* db, QString filePath) if (++dbStruct.saveAttempts > 2 && useAtomicSaves) { // Saving failed 3 times, issue a warning and attempt to resolve - auto choice = MessageBox::question(this, tr("Disable safe saves?"), + auto choice = MessageBox::question(this, + tr("Disable safe saves?"), tr("KeePassXC has failed to save the database multiple times. " - "This is likely caused by file sync services holding a lock on " - "the save file.\nDisable safe saves and try again?"), - QMessageBox::Yes | QMessageBox::No, QMessageBox::Yes); + "This is likely caused by file sync services holding a lock on " + "the save file.\nDisable safe saves and try again?"), + QMessageBox::Yes | QMessageBox::No, + QMessageBox::Yes); if (choice == QMessageBox::Yes) { config()->set("UseAtomicSaves", false); return saveDatabase(db, filePath); @@ -362,8 +359,7 @@ bool DatabaseTabWidget::saveDatabase(Database* db, QString filePath) dbStruct.saveAttempts = 0; } - emit messageTab(tr("Writing the database failed.").append("\n").append(errorMessage), - MessageWidget::Error); + emit messageTab(tr("Writing the database failed.").append("\n").append(errorMessage), MessageWidget::Error); return false; } } else { @@ -381,9 +377,13 @@ bool DatabaseTabWidget::saveDatabaseAs(Database* db) } else { oldFilePath = QDir::toNativeSeparators(QDir::homePath() + "/" + tr("Passwords").append(".kdbx")); } - QString newFilePath = fileDialog()->getSaveFileName(this, tr("Save database as"), oldFilePath, + QString newFilePath = fileDialog()->getSaveFileName(this, + tr("Save database as"), + oldFilePath, tr("KeePass 2 Database").append(" (*.kdbx)"), - nullptr, 0, "kdbx"); + nullptr, + 0, + "kdbx"); if (!newFilePath.isEmpty()) { // Ensure we don't recurse back into this function dbStruct.readOnly = false; @@ -450,18 +450,16 @@ void DatabaseTabWidget::exportToCsv() return; } - QString fileName = fileDialog()->getSaveFileName(this, tr("Export database to CSV file"), - QString(), tr("CSV file").append(" (*.csv)"), - nullptr, 0, "csv"); + QString fileName = fileDialog()->getSaveFileName( + this, tr("Export database to CSV file"), QString(), tr("CSV file").append(" (*.csv)"), nullptr, 0, "csv"); if (fileName.isEmpty()) { return; } CsvExporter csvExporter; if (!csvExporter.exportDatabase(fileName, db)) { - emit messageGlobal( - tr("Writing the CSV file failed.").append("\n") - .append(csvExporter.errorString()), MessageWidget::Error); + emit messageGlobal(tr("Writing the CSV file failed.").append("\n").append(csvExporter.errorString()), + MessageWidget::Error); } } @@ -512,7 +510,6 @@ QString DatabaseTabWidget::databasePath(int index) return indexDatabaseManagerStruct(index).fileInfo.absoluteFilePath(); } - void DatabaseTabWidget::updateTabName(Database* db) { int index = databaseIndex(db); @@ -566,7 +563,7 @@ void DatabaseTabWidget::updateTabNameFromDbWidgetSender() updateTabName(databaseFromDatabaseWidget(dbWidget)); Database* db = dbWidget->database(); - Group *autoload = db->rootGroup()->findChildByName("AutoOpen"); + Group* autoload = db->rootGroup()->findChildByName("AutoOpen"); if (autoload) { const DatabaseManagerStruct& dbStruct = m_dbList.value(db); QDir dbFolder(dbStruct.fileInfo.canonicalPath()); @@ -578,8 +575,7 @@ void DatabaseTabWidget::updateTabNameFromDbWidgetSender() if (entry->url().startsWith("file://")) { QUrl url(entry->url()); filepath.setFile(url.toLocalFile()); - } - else { + } else { filepath.setFile(entry->url()); if (filepath.isRelative()) { filepath.setFile(dbFolder, entry->url()); @@ -665,8 +661,7 @@ DatabaseWidget* DatabaseTabWidget::currentDatabaseWidget() Database* db = indexDatabase(currentIndex()); if (db) { return m_dbList[db].dbWidget; - } - else { + } else { return nullptr; } } @@ -678,8 +673,7 @@ bool DatabaseTabWidget::hasLockableDatabases() const i.next(); DatabaseWidget::Mode mode = i.value().dbWidget->currentMode(); - if ((mode == DatabaseWidget::ViewMode || mode == DatabaseWidget::EditMode) - && i.value().dbWidget->dbHasKey()) { + if ((mode == DatabaseWidget::ViewMode || mode == DatabaseWidget::EditMode) && i.value().dbWidget->dbHasKey()) { return true; } } @@ -704,10 +698,12 @@ void DatabaseTabWidget::lockDatabases() if (dbWidget->currentMode() == DatabaseWidget::EditMode && dbWidget->isEditWidgetModified()) { QMessageBox::StandardButton result = - MessageBox::question( - this, tr("Lock database"), - tr("Can't lock the database as you are currently editing it.\nPlease press cancel to finish your changes or discard them."), - QMessageBox::Discard | QMessageBox::Cancel, QMessageBox::Cancel); + MessageBox::question(this, + tr("Lock database"), + tr("Can't lock the database as you are currently editing it.\nPlease press cancel " + "to finish your changes or discard them."), + QMessageBox::Discard | QMessageBox::Cancel, + QMessageBox::Cancel); if (result == QMessageBox::Cancel) { continue; } @@ -715,20 +711,20 @@ void DatabaseTabWidget::lockDatabases() if (m_dbList[db].modified) { QMessageBox::StandardButton result = - MessageBox::question( - this, tr("Lock database"), - tr("This database has been modified.\nDo you want to save the database before locking it?\nOtherwise your changes are lost."), - QMessageBox::Save | QMessageBox::Discard | QMessageBox::Cancel, QMessageBox::Cancel); + MessageBox::question(this, + tr("Lock database"), + tr("This database has been modified.\nDo you want to save the database before " + "locking it?\nOtherwise your changes are lost."), + QMessageBox::Save | QMessageBox::Discard | QMessageBox::Cancel, + QMessageBox::Cancel); if (result == QMessageBox::Save) { if (!saveDatabase(db)) { continue; } - } - else if (result == QMessageBox::Discard) { + } else if (result == QMessageBox::Discard) { m_dbList[db].modified = false; m_dbList[db].dbWidget->databaseSaved(); - } - else if (result == QMessageBox::Cancel) { + } else if (result == QMessageBox::Cancel) { continue; } } @@ -785,8 +781,7 @@ void DatabaseTabWidget::updateLastDatabases(const QString& filename) { if (!config()->get("RememberLastDatabases").toBool()) { config()->set("LastDatabases", QVariant()); - } - else { + } else { QStringList lastDatabases = config()->get("LastDatabases", QVariant()).toStringList(); lastDatabases.prepend(filename); lastDatabases.removeDuplicates(); @@ -851,7 +846,7 @@ void DatabaseTabWidget::performGlobalAutoType() if (unlockedDatabases.size() > 0) { autoType()->performGlobalAutoType(unlockedDatabases); - } else if (m_dbList.size() > 0){ + } else if (m_dbList.size() > 0) { m_dbPendingLock = indexDatabaseManagerStruct(0).dbWidget; m_dbPendingLock->showUnlockDialog(); } diff --git a/src/gui/DatabaseTabWidget.h b/src/gui/DatabaseTabWidget.h index 38f9b8474..f4cdf2953 100644 --- a/src/gui/DatabaseTabWidget.h +++ b/src/gui/DatabaseTabWidget.h @@ -19,9 +19,9 @@ #ifndef KEEPASSX_DATABASETABWIDGET_H #define KEEPASSX_DATABASETABWIDGET_H +#include #include #include -#include #include "gui/DatabaseWidget.h" #include "gui/MessageWidget.h" @@ -52,8 +52,7 @@ class DatabaseTabWidget : public QTabWidget public: explicit DatabaseTabWidget(QWidget* parent = nullptr); ~DatabaseTabWidget() override; - void openDatabase(const QString& fileName, const QString& pw = QString(), - const QString& keyFile = QString()); + void openDatabase(const QString& fileName, const QString& pw = QString(), const QString& keyFile = QString()); void mergeDatabase(const QString& fileName); DatabaseWidget* currentDatabaseWidget(); bool hasLockableDatabases() const; diff --git a/src/gui/DatabaseWidget.cpp b/src/gui/DatabaseWidget.cpp index bc8fc3f70..7ee317ad0 100644 --- a/src/gui/DatabaseWidget.cpp +++ b/src/gui/DatabaseWidget.cpp @@ -19,18 +19,18 @@ #include "DatabaseWidget.h" #include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include #include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include #include "autotype/AutoType.h" #include "core/Config.h" @@ -43,15 +43,15 @@ #include "gui/ChangeMasterKeyWidget.h" #include "gui/Clipboard.h" #include "gui/CloneDialog.h" -#include "gui/SetupTotpDialog.h" -#include "gui/TotpDialog.h" #include "gui/DatabaseOpenWidget.h" #include "gui/DatabaseSettingsWidget.h" #include "gui/DetailsWidget.h" #include "gui/KeePass1OpenWidget.h" #include "gui/MessageBox.h" -#include "gui/UnlockDatabaseWidget.h" +#include "gui/SetupTotpDialog.h" +#include "gui/TotpDialog.h" #include "gui/UnlockDatabaseDialog.h" +#include "gui/UnlockDatabaseWidget.h" #include "gui/entry/EditEntryWidget.h" #include "gui/entry/EntryView.h" #include "gui/group/EditGroupWidget.h" @@ -91,15 +91,13 @@ DatabaseWidget::DatabaseWidget(Database* db, QWidget* parent) m_groupView = new GroupView(db, m_mainSplitter); m_groupView->setObjectName("groupView"); m_groupView->setContextMenuPolicy(Qt::CustomContextMenu); - connect(m_groupView, SIGNAL(customContextMenuRequested(QPoint)), - SLOT(emitGroupContextMenuRequested(QPoint))); + connect(m_groupView, SIGNAL(customContextMenuRequested(QPoint)), SLOT(emitGroupContextMenuRequested(QPoint))); m_entryView = new EntryView(rightHandSideWidget); m_entryView->setObjectName("entryView"); m_entryView->setContextMenuPolicy(Qt::CustomContextMenu); m_entryView->setGroup(db->rootGroup()); - connect(m_entryView, SIGNAL(customContextMenuRequested(QPoint)), - SLOT(emitEntryContextMenuRequested(QPoint))); + connect(m_entryView, SIGNAL(customContextMenuRequested(QPoint)), SLOT(emitEntryContextMenuRequested(QPoint))); // Add a notification for when we are searching m_searchingLabel = new QLabel(); @@ -114,11 +112,12 @@ DatabaseWidget::DatabaseWidget(Database* db, QWidget* parent) m_detailsView->hide(); connect(this, SIGNAL(pressedEntry(Entry*)), m_detailsView, SLOT(setEntry(Entry*))); connect(this, SIGNAL(pressedGroup(Group*)), m_detailsView, SLOT(setGroup(Group*))); - connect(this, SIGNAL(currentModeChanged(DatabaseWidget::Mode)), - m_detailsView, SLOT(setDatabaseMode(DatabaseWidget::Mode))); + connect(this, + SIGNAL(currentModeChanged(DatabaseWidget::Mode)), + m_detailsView, + SLOT(setDatabaseMode(DatabaseWidget::Mode))); connect(m_detailsView, SIGNAL(errorOccurred(QString)), this, SLOT(showErrorMessage(QString))); - auto* vLayout = new QVBoxLayout(rightHandSideWidget); vLayout->setMargin(0); vLayout->addWidget(m_searchingLabel); @@ -184,12 +183,13 @@ DatabaseWidget::DatabaseWidget(Database* db, QWidget* parent) addWidget(m_keepass1OpenWidget); addWidget(m_unlockDatabaseWidget); - connect(m_mainSplitter, SIGNAL(splitterMoved(int,int)), SIGNAL(mainSplitterSizesChanged())); - connect(m_detailSplitter, SIGNAL(splitterMoved(int,int)), SIGNAL(detailSplitterSizesChanged())); + connect(m_mainSplitter, SIGNAL(splitterMoved(int, int)), SIGNAL(mainSplitterSizesChanged())); + connect(m_detailSplitter, SIGNAL(splitterMoved(int, int)), SIGNAL(detailSplitterSizesChanged())); connect(m_entryView, SIGNAL(viewStateChanged()), SIGNAL(entryViewStateChanged())); connect(m_groupView, SIGNAL(groupChanged(Group*)), this, SLOT(onGroupChanged(Group*))); connect(m_groupView, SIGNAL(groupChanged(Group*)), SIGNAL(groupChanged())); - connect(m_entryView, SIGNAL(entryActivated(Entry*, EntryModel::ModelColumn)), + connect(m_entryView, + SIGNAL(entryActivated(Entry*, EntryModel::ModelColumn)), SLOT(entryActivationSignalReceived(Entry*, EntryModel::ModelColumn))); connect(m_entryView, SIGNAL(entrySelectionChanged()), SIGNAL(entrySelectionChanged())); connect(m_editEntryWidget, SIGNAL(editFinished(bool)), SLOT(switchToView(bool))); @@ -203,7 +203,7 @@ DatabaseWidget::DatabaseWidget(Database* db, QWidget* parent) connect(m_keepass1OpenWidget, SIGNAL(editFinished(bool)), SLOT(openDatabase(bool))); connect(m_csvImportWizard, SIGNAL(importFinished(bool)), SLOT(csvImportFinished(bool))); connect(m_unlockDatabaseWidget, SIGNAL(editFinished(bool)), SLOT(unlockDatabase(bool))); - connect(m_unlockDatabaseDialog, SIGNAL(unlockDone(bool)), SLOT(unlockDatabase(bool))); + connect(m_unlockDatabaseDialog, SIGNAL(unlockDone(bool)), SLOT(unlockDatabase(bool))); connect(&m_fileWatcher, SIGNAL(fileChanged(QString)), this, SLOT(onWatchedFileChanged())); connect(&m_fileWatchTimer, SIGNAL(timeout()), this, SLOT(reloadDatabaseFile())); connect(&m_fileWatchUnblockTimer, SIGNAL(timeout()), this, SLOT(unblockAutoReload())); @@ -226,7 +226,10 @@ DatabaseWidget::DatabaseWidget(Database* db, QWidget* parent) #ifdef WITH_XC_SSHAGENT if (config()->get("SSHAgent", false).toBool()) { - connect(this, SIGNAL(currentModeChanged(DatabaseWidget::Mode)), SSHAgent::instance(), SLOT(databaseModeChanged(DatabaseWidget::Mode))); + connect(this, + SIGNAL(currentModeChanged(DatabaseWidget::Mode)), + SSHAgent::instance(), + SLOT(databaseModeChanged(DatabaseWidget::Mode))); connect(this, SIGNAL(closeRequest()), SSHAgent::instance(), SLOT(databaseModeChanged())); } #endif @@ -242,18 +245,13 @@ DatabaseWidget::Mode DatabaseWidget::currentMode() const { if (currentWidget() == nullptr) { return DatabaseWidget::None; - } - else if (currentWidget() == m_csvImportWizard) { + } else if (currentWidget() == m_csvImportWizard) { return DatabaseWidget::ImportMode; - } - else if (currentWidget() == m_mainWidget) { + } else if (currentWidget() == m_mainWidget) { return DatabaseWidget::ViewMode; - } - else if (currentWidget() == m_unlockDatabaseWidget || - currentWidget() == m_databaseOpenWidget) { + } else if (currentWidget() == m_unlockDatabaseWidget || currentWidget() == m_databaseOpenWidget) { return DatabaseWidget::LockedMode; - } - else { + } else { return DatabaseWidget::EditMode; } } @@ -267,8 +265,7 @@ bool DatabaseWidget::isEditWidgetModified() const { if (currentWidget() == m_editEntryWidget) { return m_editEntryWidget->hasBeenModified(); - } - else { + } else { // other edit widget don't have a hasBeenModified() method yet // assume that they already have been modified return true; @@ -290,7 +287,7 @@ QList DatabaseWidget::detailSplitterSizes() const return m_detailSplitter->sizes(); } -void DatabaseWidget::setDetailSplitterSizes(const QList &sizes) +void DatabaseWidget::setDetailSplitterSizes(const QList& sizes) { m_detailSplitter->setSizes(sizes); } @@ -392,8 +389,7 @@ void DatabaseWidget::setIconFromParent() if (m_newParent->iconUuid().isNull()) { m_newEntry->setIcon(m_newParent->iconNumber()); - } - else { + } else { m_newEntry->setIcon(m_newParent->iconUuid()); } } @@ -461,7 +457,6 @@ void DatabaseWidget::setupTotp() setupTotpDialog->open(); } - void DatabaseWidget::deleteEntries() { const QModelIndexList selected = m_entryView->selectionModel()->selectedRows(); @@ -482,17 +477,13 @@ void DatabaseWidget::deleteEntries() QString prompt; if (selected.size() == 1) { prompt = tr("Do you really want to delete the entry \"%1\" for good?") - .arg(selectedEntries.first()->title().toHtmlEscaped()); - } - else { + .arg(selectedEntries.first()->title().toHtmlEscaped()); + } else { prompt = tr("Do you really want to delete %n entry(s) for good?", "", selected.size()); } QMessageBox::StandardButton result = MessageBox::question( - this, - tr("Delete entry(s)?", "", selected.size()), - prompt, - QMessageBox::Yes | QMessageBox::No); + this, tr("Delete entry(s)?", "", selected.size()), prompt, QMessageBox::Yes | QMessageBox::No); if (result == QMessageBox::Yes) { for (Entry* entry : asConst(selectedEntries)) { @@ -500,21 +491,17 @@ void DatabaseWidget::deleteEntries() } refreshSearch(); } - } - else { + } else { QString prompt; if (selected.size() == 1) { prompt = tr("Do you really want to move entry \"%1\" to the recycle bin?") - .arg(selectedEntries.first()->title().toHtmlEscaped()); + .arg(selectedEntries.first()->title().toHtmlEscaped()); } else { prompt = tr("Do you really want to move %n entry(s) to the recycle bin?", "", selected.size()); } QMessageBox::StandardButton result = MessageBox::question( - this, - tr("Move entry(s) to recycle bin?", "", selected.size()), - prompt, - QMessageBox::Yes | QMessageBox::No); + this, tr("Move entry(s) to recycle bin?", "", selected.size()), prompt, QMessageBox::Yes | QMessageBox::No); if (result == QMessageBox::No) { return; @@ -528,7 +515,7 @@ void DatabaseWidget::deleteEntries() void DatabaseWidget::setFocus() { - m_entryView->setFocus(); + m_entryView->setFocus(); } void DatabaseWidget::copyTitle() @@ -594,7 +581,8 @@ void DatabaseWidget::copyAttribute(QAction* action) return; } - setClipboardTextAndMinimize(currentEntry->resolveMultiplePlaceholders(currentEntry->attributes()->value(action->data().toString()))); + setClipboardTextAndMinimize( + currentEntry->resolveMultiplePlaceholders(currentEntry->attributes()->value(action->data().toString()))); } void DatabaseWidget::setClipboardTextAndMinimize(const QString& text) @@ -653,8 +641,7 @@ void DatabaseWidget::openUrlForEntry(Entry* entry) tr("Do you really want to execute the following command?

%1
") .arg(cmdTruncated.toHtmlEscaped()), QMessageBox::Yes | QMessageBox::No, - this - ); + this); msgbox.setDefaultButton(QMessageBox::No); QCheckBox* checkbox = new QCheckBox(tr("Remember my choice"), &msgbox); @@ -662,8 +649,8 @@ void DatabaseWidget::openUrlForEntry(Entry* entry) bool remember = false; QObject::connect(checkbox, &QCheckBox::stateChanged, [&](int state) { if (static_cast(state) == Qt::CheckState::Checked) { - remember = true; - } + remember = true; + } }); int result = msgbox.exec(); @@ -672,12 +659,10 @@ void DatabaseWidget::openUrlForEntry(Entry* entry) } if (remember) { - entry->attributes()->set(EntryAttributes::RememberCmdExecAttr, - result == QMessageBox::Yes ? "1" : "0"); + entry->attributes()->set(EntryAttributes::RememberCmdExecAttr, result == QMessageBox::Yes ? "1" : "0"); } } - } - else { + } else { QUrl url = QUrl::fromUserInput(urlString); QDesktopServices::openUrl(url); } @@ -709,15 +694,14 @@ void DatabaseWidget::deleteGroup() bool isRecycleBinSubgroup = Tools::hasChild(currentGroup, m_db->metadata()->recycleBin()); if (inRecycleBin || isRecycleBin || isRecycleBinSubgroup || !m_db->metadata()->recycleBinEnabled()) { QMessageBox::StandardButton result = MessageBox::question( - this, tr("Delete group?"), - tr("Do you really want to delete the group \"%1\" for good?") - .arg(currentGroup->name().toHtmlEscaped()), + this, + tr("Delete group?"), + tr("Do you really want to delete the group \"%1\" for good?").arg(currentGroup->name().toHtmlEscaped()), QMessageBox::Yes | QMessageBox::No); if (result == QMessageBox::Yes) { delete currentGroup; } - } - else { + } else { m_db->recycleGroup(currentGroup); } } @@ -760,8 +744,7 @@ void DatabaseWidget::csvImportFinished(bool accepted) { if (!accepted) { emit closeRequest(); - } - else { + } else { setCurrentWidget(m_mainWidget); } } @@ -852,8 +835,7 @@ void DatabaseWidget::updateMasterKey(bool accepted) m_messageWidget->showMessage(tr("Unable to calculate master key"), MessageWidget::Error); return; } - } - else if (!m_db->hasKey()) { + } else if (!m_db->hasKey()) { emit closeRequest(); return; } @@ -875,8 +857,7 @@ void DatabaseWidget::openDatabase(bool accepted) delete m_keepass1OpenWidget; m_keepass1OpenWidget = nullptr; m_fileWatcher.addPath(m_filePath); - } - else { + } else { m_fileWatcher.removePath(m_filePath); if (m_databaseOpenWidget->database()) { delete m_databaseOpenWidget->database(); @@ -960,10 +941,10 @@ void DatabaseWidget::entryActivationSignalReceived(Entry* entry, EntryModel::Mod } break; // TODO: switch to 'Notes' tab in details view/pane - //case EntryModel::Notes: + // case EntryModel::Notes: // break; // TODO: switch to 'Attachments' tab in details view/pane - //case EntryModel::Attachments: + // case EntryModel::Attachments: // break; default: switchToEntryEdit(entry); @@ -1018,8 +999,7 @@ void DatabaseWidget::switchToOpenDatabase(const QString& filePath) } } -void DatabaseWidget::switchToOpenDatabase(const QString& filePath, const QString& password, - const QString& keyFile) +void DatabaseWidget::switchToOpenDatabase(const QString& filePath, const QString& password, const QString& keyFile) { updateFilePath(filePath); switchToOpenDatabase(filePath); @@ -1047,9 +1027,7 @@ void DatabaseWidget::switchToOpenMergeDatabase(const QString& filePath) setCurrentWidget(m_databaseOpenMergeWidget); } - -void DatabaseWidget::switchToOpenMergeDatabase(const QString& filePath, const QString& password, - const QString& keyFile) +void DatabaseWidget::switchToOpenMergeDatabase(const QString& filePath, const QString& password, const QString& keyFile) { switchToOpenMergeDatabase(filePath); m_databaseOpenMergeWidget->enterKey(password, keyFile); @@ -1072,7 +1050,8 @@ void DatabaseWidget::databaseSaved() m_databaseModified = false; } -void DatabaseWidget::refreshSearch() { +void DatabaseWidget::refreshSearch() +{ if (isInSearchMode()) { search(m_lastSearchText); } @@ -1080,8 +1059,7 @@ void DatabaseWidget::refreshSearch() { void DatabaseWidget::search(const QString& searchtext) { - if (searchtext.isEmpty()) - { + if (searchtext.isEmpty()) { endSearch(); return; } @@ -1100,8 +1078,7 @@ void DatabaseWidget::search(const QString& searchtext) // Display a label detailing our search results if (searchResult.size() > 0) { m_searchingLabel->setText(tr("Search Results (%1)").arg(searchResult.size())); - } - else { + } else { m_searchingLabel->setText(tr("No Results")); } @@ -1138,8 +1115,7 @@ QString DatabaseWidget::getCurrentSearch() void DatabaseWidget::endSearch() { - if (isInSearchMode()) - { + if (isInSearchMode()) { emit listModeAboutToActivate(); // Show the normal entry view of the current group @@ -1217,8 +1193,7 @@ void DatabaseWidget::lock() if (m_groupView->currentGroup()) { m_groupBeforeLock = m_groupView->currentGroup()->uuid(); - } - else { + } else { m_groupBeforeLock = m_db->rootGroup()->uuid(); } @@ -1235,7 +1210,7 @@ void DatabaseWidget::lock() replaceDatabase(newDb); } -void DatabaseWidget::updateFilePath(const QString &filePath) +void DatabaseWidget::updateFilePath(const QString& filePath) { if (!m_filePath.isEmpty()) { m_fileWatcher.removePath(m_filePath); @@ -1282,11 +1257,13 @@ void DatabaseWidget::reloadDatabaseFile() return; } - if (! config()->get("AutoReloadOnChange").toBool()) { + if (!config()->get("AutoReloadOnChange").toBool()) { // Ask if we want to reload the db - QMessageBox::StandardButton mb = MessageBox::question(this, tr("File has changed"), - tr("The database file has changed. Do you want to load the changes?"), - QMessageBox::Yes | QMessageBox::No); + QMessageBox::StandardButton mb = + MessageBox::question(this, + tr("File has changed"), + tr("The database file has changed. Do you want to load the changes?"), + QMessageBox::Yes | QMessageBox::No); if (mb == QMessageBox::No) { // Notify everyone the database does not match the file @@ -1305,10 +1282,12 @@ void DatabaseWidget::reloadDatabaseFile() if (db != nullptr) { if (m_databaseModified) { // Ask if we want to merge changes into new database - QMessageBox::StandardButton mb = MessageBox::question(this, tr("Merge Request"), - tr("The database file has changed and you have unsaved changes.\n" - "Do you want to merge your changes?"), - QMessageBox::Yes | QMessageBox::No); + QMessageBox::StandardButton mb = + MessageBox::question(this, + tr("Merge Request"), + tr("The database file has changed and you have unsaved changes.\n" + "Do you want to merge your changes?"), + QMessageBox::Yes | QMessageBox::No); if (mb == QMessageBox::Yes) { // Merge the old database into the new one @@ -1324,8 +1303,7 @@ void DatabaseWidget::reloadDatabaseFile() Uuid groupBeforeReload; if (m_groupView && m_groupView->currentGroup()) { groupBeforeReload = m_groupView->currentGroup()->uuid(); - } - else { + } else { groupBeforeReload = m_db->rootGroup()->uuid(); } @@ -1336,12 +1314,12 @@ void DatabaseWidget::reloadDatabaseFile() replaceDatabase(db); restoreGroupEntryFocus(groupBeforeReload, entryBeforeReload); - } } else { m_messageWidget->showMessage( tr("Could not open the new database file while attempting to autoreload this database.") - .append("\n").append(file.errorString()), + .append("\n") + .append(file.errorString()), MessageWidget::Error); // HACK: Directly calling the database's signal // Mark db as modified since existing data may differ from file or file was deleted @@ -1383,17 +1361,16 @@ void DatabaseWidget::restoreGroupEntryFocus(Uuid groupUuid, Uuid entryUuid) } if (restoredGroup != nullptr) { - m_groupView->setCurrentGroup(restoredGroup); + m_groupView->setCurrentGroup(restoredGroup); - const QList entries = restoredGroup->entries(); - for (Entry* entry : entries) { - if (entry->uuid() == entryUuid) { - m_entryView->setCurrentEntry(entry); - break; - } - } + const QList entries = restoredGroup->entries(); + for (Entry* entry : entries) { + if (entry->uuid() == entryUuid) { + m_entryView->setCurrentEntry(entry); + break; + } + } } - } bool DatabaseWidget::isGroupSelected() const @@ -1441,7 +1418,6 @@ bool DatabaseWidget::currentEntryHasUrl() return !currentEntry->resolveMultiplePlaceholders(currentEntry->url()).isEmpty(); } - bool DatabaseWidget::currentEntryHasTotp() { Entry* currentEntry = m_entryView->currentEntry(); @@ -1462,11 +1438,13 @@ bool DatabaseWidget::currentEntryHasNotes() return !currentEntry->resolveMultiplePlaceholders(currentEntry->notes()).isEmpty(); } -GroupView* DatabaseWidget::groupView() { +GroupView* DatabaseWidget::groupView() +{ return m_groupView; } -EntryView* DatabaseWidget::entryView() { +EntryView* DatabaseWidget::entryView() +{ return m_entryView; } @@ -1489,7 +1467,10 @@ void DatabaseWidget::closeUnlockDialog() m_unlockDatabaseDialog->close(); } -void DatabaseWidget::showMessage(const QString& text, MessageWidget::MessageType type, bool showClosebutton, int autoHideTimeout) +void DatabaseWidget::showMessage(const QString& text, + MessageWidget::MessageType type, + bool showClosebutton, + int autoHideTimeout) { m_messageWidget->setCloseButtonVisible(showClosebutton); m_messageWidget->showMessage(text, type, autoHideTimeout); @@ -1514,14 +1495,15 @@ bool DatabaseWidget::isRecycleBinSelected() const void DatabaseWidget::emptyRecycleBin() { - if(!isRecycleBinSelected()) { + if (!isRecycleBinSelected()) { return; } - QMessageBox::StandardButton result = MessageBox::question( - this, tr("Empty recycle bin?"), - tr("Are you sure you want to permanently delete everything from your recycle bin?"), - QMessageBox::Yes | QMessageBox::No); + QMessageBox::StandardButton result = + MessageBox::question(this, + tr("Empty recycle bin?"), + tr("Are you sure you want to permanently delete everything from your recycle bin?"), + QMessageBox::Yes | QMessageBox::No); if (result == QMessageBox::Yes) { m_db->emptyRecycleBin(); diff --git a/src/gui/DatabaseWidget.h b/src/gui/DatabaseWidget.h index 464a543ab..ca1bfc14a 100644 --- a/src/gui/DatabaseWidget.h +++ b/src/gui/DatabaseWidget.h @@ -19,16 +19,16 @@ #ifndef KEEPASSX_DATABASEWIDGET_H #define KEEPASSX_DATABASEWIDGET_H +#include #include #include -#include #include #include "core/Uuid.h" -#include "gui/entry/EntryModel.h" #include "gui/MessageWidget.h" #include "gui/csvImport/CsvImportWizard.h" +#include "gui/entry/EntryModel.h" class ChangeMasterKeyWidget; class DatabaseOpenWidget; @@ -51,7 +51,8 @@ class DetailsWidget; class UnlockDatabaseDialog; class QFileSystemWatcher; -namespace Ui { +namespace Ui +{ class SearchWidget; } @@ -82,7 +83,7 @@ public: void setCurrentWidget(QWidget* widget); DatabaseWidget::Mode currentMode() const; void lock(); - void updateFilePath(const QString &filePath); + void updateFilePath(const QString& filePath); int numberOfSelectedEntries() const; QStringList customEntryAttributes() const; bool isGroupSelected() const; @@ -176,7 +177,9 @@ public slots: void setSearchLimitGroup(bool state); void endSearch(); - void showMessage(const QString& text, MessageWidget::MessageType type, bool showClosebutton = true, + void showMessage(const QString& text, + MessageWidget::MessageType type, + bool showClosebutton = true, int autoHideTimeout = MessageWidget::DefaultAutoHideTimeout); void showErrorMessage(const QString& errorMessage); void hideMessage(); diff --git a/src/gui/DatabaseWidgetStateSync.cpp b/src/gui/DatabaseWidgetStateSync.cpp index 9b89412ea..1a1fae7af 100644 --- a/src/gui/DatabaseWidgetStateSync.cpp +++ b/src/gui/DatabaseWidgetStateSync.cpp @@ -82,20 +82,13 @@ void DatabaseWidgetStateSync::setActive(DatabaseWidget* dbWidget) m_blockUpdates = false; - connect(m_activeDbWidget, SIGNAL(mainSplitterSizesChanged()), - SLOT(updateSplitterSizes())); - connect(m_activeDbWidget, SIGNAL(detailSplitterSizesChanged()), - SLOT(updateSplitterSizes())); - connect(m_activeDbWidget, SIGNAL(entryViewStateChanged()), - SLOT(updateViewState())); - connect(m_activeDbWidget, SIGNAL(listModeActivated()), - SLOT(restoreListView())); - connect(m_activeDbWidget, SIGNAL(searchModeActivated()), - SLOT(restoreSearchView())); - connect(m_activeDbWidget, SIGNAL(listModeAboutToActivate()), - SLOT(blockUpdates())); - connect(m_activeDbWidget, SIGNAL(searchModeAboutToActivate()), - SLOT(blockUpdates())); + connect(m_activeDbWidget, SIGNAL(mainSplitterSizesChanged()), SLOT(updateSplitterSizes())); + connect(m_activeDbWidget, SIGNAL(detailSplitterSizesChanged()), SLOT(updateSplitterSizes())); + connect(m_activeDbWidget, SIGNAL(entryViewStateChanged()), SLOT(updateViewState())); + connect(m_activeDbWidget, SIGNAL(listModeActivated()), SLOT(restoreListView())); + connect(m_activeDbWidget, SIGNAL(searchModeActivated()), SLOT(restoreSearchView())); + connect(m_activeDbWidget, SIGNAL(listModeAboutToActivate()), SLOT(blockUpdates())); + connect(m_activeDbWidget, SIGNAL(searchModeAboutToActivate()), SLOT(blockUpdates())); } } diff --git a/src/gui/DetailsWidget.cpp b/src/gui/DetailsWidget.cpp index fcf8ecb5f..234d7e612 100644 --- a/src/gui/DetailsWidget.cpp +++ b/src/gui/DetailsWidget.cpp @@ -20,16 +20,17 @@ #include "ui_DetailsWidget.h" #include -#include #include +#include #include "core/Config.h" #include "core/FilePath.h" -#include "gui/Clipboard.h" #include "entry/EntryAttachmentsModel.h" +#include "gui/Clipboard.h" -namespace { -constexpr int GeneralTabIndex = 0; +namespace +{ + constexpr int GeneralTabIndex = 0; } DetailsWidget::DetailsWidget(QWidget* parent) @@ -87,8 +88,7 @@ void DetailsWidget::setEntry(Entry* selectedEntry) setVisible(!config()->get("GUI/HideDetailsView").toBool()); m_ui->stackedWidget->setCurrentWidget(m_ui->pageEntry); - const int tabIndex = m_ui->entryTabWidget->isTabEnabled(m_selectedTabEntry) ? m_selectedTabEntry - : GeneralTabIndex; + const int tabIndex = m_ui->entryTabWidget->isTabEnabled(m_selectedTabEntry) ? m_selectedTabEntry : GeneralTabIndex; Q_ASSERT(m_ui->entryTabWidget->isTabEnabled(GeneralTabIndex)); m_ui->entryTabWidget->setCurrentIndex(tabIndex); } @@ -108,8 +108,7 @@ void DetailsWidget::setGroup(Group* selectedGroup) setVisible(!config()->get("GUI/HideDetailsView").toBool()); m_ui->stackedWidget->setCurrentWidget(m_ui->pageGroup); - const int tabIndex = m_ui->groupTabWidget->isTabEnabled(m_selectedTabGroup) ? m_selectedTabGroup - : GeneralTabIndex; + const int tabIndex = m_ui->groupTabWidget->isTabEnabled(m_selectedTabGroup) ? m_selectedTabGroup : GeneralTabIndex; Q_ASSERT(m_ui->groupTabWidget->isTabEnabled(GeneralTabIndex)); m_ui->groupTabWidget->setCurrentIndex(tabIndex); } @@ -188,8 +187,8 @@ void DetailsWidget::updateEntryGeneralTab() } const TimeInfo entryTime = m_currentEntry->timeInfo(); - const QString expires = entryTime.expires() ? entryTime.expiryTime().toString(Qt::DefaultLocaleShortDate) - : tr("Never"); + const QString expires = + entryTime.expires() ? entryTime.expiryTime().toString(Qt::DefaultLocaleShortDate) : tr("Never"); m_ui->entryExpirationLabel->setText(expires); } @@ -238,8 +237,8 @@ void DetailsWidget::updateEntryAutotypeTab() const AutoTypeAssociations* autotypeAssociations = m_currentEntry->autoTypeAssociations(); const auto associations = autotypeAssociations->getAll(); for (const auto& assoc : associations) { - const QString sequence = assoc.sequence.isEmpty() ? m_currentEntry->effectiveAutoTypeSequence() - : assoc.sequence; + const QString sequence = + assoc.sequence.isEmpty() ? m_currentEntry->effectiveAutoTypeSequence() : assoc.sequence; items.append(new QTreeWidgetItem(m_ui->entryAutotypeTree, {assoc.window, sequence})); } @@ -264,8 +263,8 @@ void DetailsWidget::updateGroupGeneralTab() m_ui->groupAutotypeLabel->setText(autotypeText); const TimeInfo groupTime = m_currentGroup->timeInfo(); - const QString expiresText = groupTime.expires() ? groupTime.expiryTime().toString(Qt::DefaultLocaleShortDate) - : tr("Never"); + const QString expiresText = + groupTime.expires() ? groupTime.expiryTime().toString(Qt::DefaultLocaleShortDate) : tr("Never"); m_ui->groupExpirationLabel->setText(expiresText); } diff --git a/src/gui/DetailsWidget.h b/src/gui/DetailsWidget.h index abec33400..3a4c277d9 100644 --- a/src/gui/DetailsWidget.h +++ b/src/gui/DetailsWidget.h @@ -22,7 +22,8 @@ #include -namespace Ui { +namespace Ui +{ class DetailsWidget; } diff --git a/src/gui/DialogyWidget.cpp b/src/gui/DialogyWidget.cpp index d8e05a911..2c0bf35e3 100644 --- a/src/gui/DialogyWidget.cpp +++ b/src/gui/DialogyWidget.cpp @@ -33,29 +33,27 @@ void DialogyWidget::keyPressEvent(QKeyEvent* e) if (!clickButton(QDialogButtonBox::Cancel)) { e->ignore(); } - } - else + } else #endif - if (!e->modifiers() || (e->modifiers() & Qt::KeypadModifier && e->key() == Qt::Key_Enter)) { + if (!e->modifiers() || (e->modifiers() & Qt::KeypadModifier && e->key() == Qt::Key_Enter)) { switch (e->key()) { - case Qt::Key_Enter: - case Qt::Key_Return: - if (!clickButton(QDialogButtonBox::Ok)) { + case Qt::Key_Enter: + case Qt::Key_Return: + if (!clickButton(QDialogButtonBox::Ok)) { + e->ignore(); + } + break; + case Qt::Key_Escape: + if (!clickButton(QDialogButtonBox::Cancel)) { + if (!clickButton(QDialogButtonBox::Close)) { e->ignore(); } - break; - case Qt::Key_Escape: - if (!clickButton(QDialogButtonBox::Cancel)) { - if (!clickButton(QDialogButtonBox::Close)) { - e->ignore(); - } - } - break; - default: - e->ignore(); + } + break; + default: + e->ignore(); } - } - else { + } else { e->ignore(); } } diff --git a/src/gui/DragTabBar.cpp b/src/gui/DragTabBar.cpp index a19031a8d..c40cceb75 100644 --- a/src/gui/DragTabBar.cpp +++ b/src/gui/DragTabBar.cpp @@ -42,8 +42,7 @@ void DragTabBar::dragEnterEvent(QDragEnterEvent* event) m_tabSwitchTimer->start(QApplication::doubleClickInterval() * 2); } event->setAccepted(true); - } - else { + } else { QTabBar::dragEnterEvent(event); } } @@ -55,14 +54,12 @@ void DragTabBar::dragMoveEvent(QDragMoveEvent* event) if (tab != -1) { if (tab == currentIndex()) { m_tabSwitchTimer->stop(); - } - else if (tab != m_tabSwitchIndex) { + } else if (tab != m_tabSwitchIndex) { m_tabSwitchIndex = tab; m_tabSwitchTimer->start(QApplication::doubleClickInterval() * 2); } event->setAccepted(true); - } - else { + } else { m_tabSwitchIndex = -1; m_tabSwitchTimer->stop(); QTabBar::dragMoveEvent(event); diff --git a/src/gui/EditWidget.cpp b/src/gui/EditWidget.cpp index 5f05a428a..ce80c03b6 100644 --- a/src/gui/EditWidget.cpp +++ b/src/gui/EditWidget.cpp @@ -18,8 +18,8 @@ #include "EditWidget.h" #include "ui_EditWidget.h" -#include #include +#include #include "core/FilePath.h" @@ -38,8 +38,7 @@ EditWidget::EditWidget(QWidget* parent) headlineLabel()->setFont(headerLabelFont); headlineLabel()->setTextFormat(Qt::PlainText); - connect(m_ui->categoryList, SIGNAL(categoryChanged(int)), - m_ui->stackedWidget, SLOT(setCurrentIndex(int))); + connect(m_ui->categoryList, SIGNAL(categoryChanged(int)), m_ui->stackedWidget, SLOT(setCurrentIndex(int))); connect(m_ui->buttonBox, SIGNAL(accepted()), SIGNAL(accepted())); connect(m_ui->buttonBox, SIGNAL(rejected()), SIGNAL(rejected())); @@ -103,8 +102,7 @@ void EditWidget::setReadOnly(bool readOnly) if (readOnly) { m_ui->buttonBox->setStandardButtons(QDialogButtonBox::Close); - } - else { + } else { m_ui->buttonBox->setStandardButtons(QDialogButtonBox::Ok | QDialogButtonBox::Cancel | QDialogButtonBox::Apply); // Find and connect the apply button QPushButton* applyButton = m_ui->buttonBox->button(QDialogButtonBox::Apply); diff --git a/src/gui/EditWidget.h b/src/gui/EditWidget.h index 38179a773..f0d157c49 100644 --- a/src/gui/EditWidget.h +++ b/src/gui/EditWidget.h @@ -20,15 +20,16 @@ #define KEEPASSX_EDITWIDGET_H #include -#include #include +#include #include "gui/DialogyWidget.h" #include "gui/MessageWidget.h" class QLabel; -namespace Ui { +namespace Ui +{ class EditWidget; } diff --git a/src/gui/EditWidgetIcons.cpp b/src/gui/EditWidgetIcons.cpp index e02ad952f..0d2c63a6d 100644 --- a/src/gui/EditWidgetIcons.cpp +++ b/src/gui/EditWidgetIcons.cpp @@ -20,8 +20,8 @@ #include "ui_EditWidgetIcons.h" #include -#include #include +#include #include "core/Config.h" #include "core/Group.h" @@ -31,8 +31,8 @@ #include "gui/MessageBox.h" #ifdef WITH_XC_NETWORKING -#include #include "core/AsyncTask.h" +#include #undef MessageBox #endif @@ -54,24 +54,24 @@ EditWidgetIcons::EditWidgetIcons(QWidget* parent) m_ui->defaultIconsView->setModel(m_defaultIconModel); m_ui->customIconsView->setModel(m_customIconModel); - connect(m_ui->defaultIconsView, SIGNAL(clicked(QModelIndex)), - this, SLOT(updateRadioButtonDefaultIcons())); - connect(m_ui->customIconsView, SIGNAL(clicked(QModelIndex)), - this, SLOT(updateRadioButtonCustomIcons())); - connect(m_ui->defaultIconsRadio, SIGNAL(toggled(bool)), - this, SLOT(updateWidgetsDefaultIcons(bool))); - connect(m_ui->customIconsRadio, SIGNAL(toggled(bool)), - this, SLOT(updateWidgetsCustomIcons(bool))); + connect(m_ui->defaultIconsView, SIGNAL(clicked(QModelIndex)), this, SLOT(updateRadioButtonDefaultIcons())); + connect(m_ui->customIconsView, SIGNAL(clicked(QModelIndex)), this, SLOT(updateRadioButtonCustomIcons())); + connect(m_ui->defaultIconsRadio, SIGNAL(toggled(bool)), this, SLOT(updateWidgetsDefaultIcons(bool))); + connect(m_ui->customIconsRadio, SIGNAL(toggled(bool)), this, SLOT(updateWidgetsCustomIcons(bool))); connect(m_ui->addButton, SIGNAL(clicked()), SLOT(addCustomIconFromFile())); connect(m_ui->deleteButton, SIGNAL(clicked()), SLOT(removeCustomIcon())); connect(m_ui->faviconButton, SIGNAL(clicked()), SLOT(downloadFavicon())); connect(m_ui->defaultIconsRadio, SIGNAL(toggled(bool)), this, SIGNAL(widgetUpdated())); connect(m_ui->defaultIconsRadio, SIGNAL(toggled(bool)), this, SIGNAL(widgetUpdated())); - connect(m_ui->defaultIconsView->selectionModel(), SIGNAL(selectionChanged(const QItemSelection&, const QItemSelection&)), - this, SIGNAL(widgetUpdated())); - connect(m_ui->customIconsView->selectionModel(), SIGNAL(selectionChanged(const QItemSelection&, const QItemSelection&)), - this, SIGNAL(widgetUpdated())); + connect(m_ui->defaultIconsView->selectionModel(), + SIGNAL(selectionChanged(const QItemSelection&, const QItemSelection&)), + this, + SIGNAL(widgetUpdated())); + connect(m_ui->customIconsView->selectionModel(), + SIGNAL(selectionChanged(const QItemSelection&, const QItemSelection&)), + this, + SIGNAL(widgetUpdated())); m_ui->faviconButton->setVisible(false); } @@ -111,7 +111,10 @@ void EditWidgetIcons::reset() m_currentUuid = Uuid(); } -void EditWidgetIcons::load(const Uuid& currentUuid, Database* database, const IconStruct& iconStruct, const QString& url) +void EditWidgetIcons::load(const Uuid& currentUuid, + Database* database, + const IconStruct& iconStruct, + const QString& url) { Q_ASSERT(database); Q_ASSERT(!currentUuid.isNull()); @@ -173,8 +176,8 @@ void EditWidgetIcons::downloadFavicon() emit messageEditEntry(tr("Unable to fetch favicon."), MessageWidget::Error); } } else { - emit messageEditEntry(tr("Unable to fetch favicon.") + "\n" + - tr("Hint: You can enable Google as a fallback under Tools>Settings>Security"), + emit messageEditEntry(tr("Unable to fetch favicon.") + "\n" + + tr("Hint: You can enable Google as a fallback under Tools>Settings>Security"), MessageWidget::Error); } @@ -183,14 +186,15 @@ void EditWidgetIcons::downloadFavicon() } #ifdef WITH_XC_NETWORKING -namespace { -std::size_t writeCurlResponse(char* ptr, std::size_t size, std::size_t nmemb, void* data) +namespace { - QByteArray* response = static_cast(data); - std::size_t realsize = size * nmemb; - response->append(ptr, realsize); - return realsize; -} + std::size_t writeCurlResponse(char* ptr, std::size_t size, std::size_t nmemb, void* data) + { + QByteArray* response = static_cast(data); + std::size_t realsize = size * nmemb; + response->append(ptr, realsize); + return realsize; + } } QImage EditWidgetIcons::fetchFavicon(const QUrl& url) @@ -213,14 +217,13 @@ QImage EditWidgetIcons::fetchFavicon(const QUrl& url) #ifdef Q_OS_WIN const QDir appDir = QFileInfo(QCoreApplication::applicationFilePath()).absoluteDir(); if (appDir.exists("ssl\\certs")) { - curl_easy_setopt(curl, CURLOPT_CAINFO, (appDir.absolutePath() + "\\ssl\\certs\\ca-bundle.crt").toLatin1().data()); + curl_easy_setopt( + curl, CURLOPT_CAINFO, (appDir.absolutePath() + "\\ssl\\certs\\ca-bundle.crt").toLatin1().data()); } #endif // Perform the request in another thread - CURLcode result = AsyncTask::runAndWaitForFuture([curl]() { - return curl_easy_perform(curl); - }); + CURLcode result = AsyncTask::runAndWaitForFuture([curl]() { return curl_easy_perform(curl); }); if (result == CURLE_OK) { image.loadFromData(imagedata); @@ -236,11 +239,9 @@ QImage EditWidgetIcons::fetchFavicon(const QUrl& url) void EditWidgetIcons::addCustomIconFromFile() { if (m_database) { - QString filter = QString("%1 (%2);;%3 (*)").arg(tr("Images"), - Tools::imageReaderFilter(), tr("All files")); + QString filter = QString("%1 (%2);;%3 (*)").arg(tr("Images"), Tools::imageReaderFilter(), tr("All files")); - QString filename = QFileDialog::getOpenFileName( - this, tr("Select Image"), "", filter); + QString filename = QFileDialog::getOpenFileName(this, tr("Select Image"), "", filter); if (!filename.isEmpty()) { auto icon = QImage(filename); if (!icon.isNull()) { @@ -313,11 +314,14 @@ void EditWidgetIcons::removeCustomIcon() int iconUseCount = entriesWithSameIcon.size() + groupsWithSameIcon.size(); if (iconUseCount > 0) { - QMessageBox::StandardButton ans = MessageBox::question(this, tr("Confirm Delete"), - tr("This icon is used by %n entry(s), and will be replaced " - "by the default icon. Are you sure you want to delete it?", - "", iconUseCount), - QMessageBox::Yes | QMessageBox::No); + QMessageBox::StandardButton ans = + MessageBox::question(this, + tr("Confirm Delete"), + tr("This icon is used by %n entry(s), and will be replaced " + "by the default icon. Are you sure you want to delete it?", + "", + iconUseCount), + QMessageBox::Yes | QMessageBox::No); if (ans == QMessageBox::No) { // Early out, nothing is changed @@ -335,7 +339,6 @@ void EditWidgetIcons::removeCustomIcon() } } - // Remove the icon from history entries for (Entry* entry : asConst(historyEntriesWithSameIcon)) { entry->setUpdateTimeinfo(false); diff --git a/src/gui/EditWidgetIcons.h b/src/gui/EditWidgetIcons.h index 0f875a8a3..858537ab5 100644 --- a/src/gui/EditWidgetIcons.h +++ b/src/gui/EditWidgetIcons.h @@ -19,9 +19,9 @@ #ifndef KEEPASSX_EDITWIDGETICONS_H #define KEEPASSX_EDITWIDGETICONS_H -#include #include #include +#include #include "config-keepassx.h" #include "core/Global.h" @@ -32,7 +32,8 @@ class Database; class DefaultIconModel; class CustomIconModel; -namespace Ui { +namespace Ui +{ class EditWidgetIcons; } diff --git a/src/gui/EditWidgetProperties.cpp b/src/gui/EditWidgetProperties.cpp index a06928c46..fa5da054d 100644 --- a/src/gui/EditWidgetProperties.cpp +++ b/src/gui/EditWidgetProperties.cpp @@ -16,8 +16,8 @@ */ #include "EditWidgetProperties.h" -#include "ui_EditWidgetProperties.h" #include "MessageBox.h" +#include "ui_EditWidgetProperties.h" EditWidgetProperties::EditWidgetProperties(QWidget* parent) : QWidget(parent) @@ -29,7 +29,8 @@ EditWidgetProperties::EditWidgetProperties(QWidget* parent) m_ui->removeCustomDataButton->setEnabled(false); m_ui->customDataTable->setModel(m_customDataModel); - connect(m_ui->customDataTable->selectionModel(), SIGNAL(selectionChanged(QItemSelection, QItemSelection)), + connect(m_ui->customDataTable->selectionModel(), + SIGNAL(selectionChanged(QItemSelection, QItemSelection)), SLOT(toggleRemoveButton(QItemSelection))); connect(m_ui->removeCustomDataButton, SIGNAL(clicked()), SLOT(removeSelectedPluginData())); } @@ -41,12 +42,9 @@ EditWidgetProperties::~EditWidgetProperties() void EditWidgetProperties::setFields(const TimeInfo& timeInfo, const Uuid& uuid) { static const QString timeFormat("d MMM yyyy HH:mm:ss"); - m_ui->modifiedEdit->setText( - timeInfo.lastModificationTime().toLocalTime().toString(timeFormat)); - m_ui->createdEdit->setText( - timeInfo.creationTime().toLocalTime().toString(timeFormat)); - m_ui->accessedEdit->setText( - timeInfo.lastAccessTime().toLocalTime().toString(timeFormat)); + m_ui->modifiedEdit->setText(timeInfo.lastModificationTime().toLocalTime().toString(timeFormat)); + m_ui->createdEdit->setText(timeInfo.creationTime().toLocalTime().toString(timeFormat)); + m_ui->accessedEdit->setText(timeInfo.lastAccessTime().toLocalTime().toString(timeFormat)); m_ui->uuidEdit->setText(uuid.toHex()); } @@ -66,10 +64,11 @@ const CustomData* EditWidgetProperties::customData() const void EditWidgetProperties::removeSelectedPluginData() { if (QMessageBox::Yes != MessageBox::question(this, - tr("Delete plugin data?"), - tr("Do you really want to delete the selected plugin data?\n" - "This may cause the affected plugins to malfunction."), - QMessageBox::Yes | QMessageBox::Cancel, QMessageBox::Cancel)) { + tr("Delete plugin data?"), + tr("Do you really want to delete the selected plugin data?\n" + "This may cause the affected plugins to malfunction."), + QMessageBox::Yes | QMessageBox::Cancel, + QMessageBox::Cancel)) { return; } @@ -95,9 +94,8 @@ void EditWidgetProperties::updateModel() m_customDataModel->setHorizontalHeaderLabels({tr("Key"), tr("Value")}); for (const QString& key : m_customData->keys()) { - m_customDataModel->appendRow(QList() - << new QStandardItem(key) - << new QStandardItem(m_customData->value(key))); + m_customDataModel->appendRow(QList() << new QStandardItem(key) + << new QStandardItem(m_customData->value(key))); } m_ui->removeCustomDataButton->setEnabled(false); diff --git a/src/gui/EditWidgetProperties.h b/src/gui/EditWidgetProperties.h index a1fd198d7..e6bb2ed7c 100644 --- a/src/gui/EditWidgetProperties.h +++ b/src/gui/EditWidgetProperties.h @@ -18,16 +18,17 @@ #ifndef KEEPASSX_EDITWIDGETPROPERTIES_H #define KEEPASSX_EDITWIDGETPROPERTIES_H -#include #include #include +#include #include #include "core/CustomData.h" #include "core/TimeInfo.h" #include "core/Uuid.h" -namespace Ui { +namespace Ui +{ class EditWidgetProperties; } diff --git a/src/gui/FileDialog.cpp b/src/gui/FileDialog.cpp index 9f3caf6da..d58f52928 100644 --- a/src/gui/FileDialog.cpp +++ b/src/gui/FileDialog.cpp @@ -21,22 +21,23 @@ FileDialog* FileDialog::m_instance(nullptr); -QString FileDialog::getOpenFileName(QWidget* parent, const QString& caption, QString dir, - const QString& filter, QString* selectedFilter, +QString FileDialog::getOpenFileName(QWidget* parent, + const QString& caption, + QString dir, + const QString& filter, + QString* selectedFilter, QFileDialog::Options options) { if (!m_nextFileName.isEmpty()) { QString result = m_nextFileName; m_nextFileName.clear(); return result; - } - else { + } else { if (dir.isEmpty()) { dir = config()->get("LastDir").toString(); } - QString result = QFileDialog::getOpenFileName(parent, caption, dir, filter, - selectedFilter, options); + QString result = QFileDialog::getOpenFileName(parent, caption, dir, filter, selectedFilter, options); // on Mac OS X the focus is lost after closing the native dialog if (parent) { @@ -48,22 +49,23 @@ QString FileDialog::getOpenFileName(QWidget* parent, const QString& caption, QSt } } -QStringList FileDialog::getOpenFileNames(QWidget *parent, const QString &caption, QString dir, - const QString &filter, QString *selectedFilter, - QFileDialog::Options options) +QStringList FileDialog::getOpenFileNames(QWidget* parent, + const QString& caption, + QString dir, + const QString& filter, + QString* selectedFilter, + QFileDialog::Options options) { if (!m_nextFileNames.isEmpty()) { QStringList results = m_nextFileNames; m_nextFileNames.clear(); return results; - } - else { + } else { if (dir.isEmpty()) { dir = config()->get("LastDir").toString(); } - QStringList results = QFileDialog::getOpenFileNames(parent, caption, dir, filter, - selectedFilter, options); + QStringList results = QFileDialog::getOpenFileNames(parent, caption, dir, filter, selectedFilter, options); // on Mac OS X the focus is lost after closing the native dialog if (parent) { @@ -77,16 +79,19 @@ QStringList FileDialog::getOpenFileNames(QWidget *parent, const QString &caption } } -QString FileDialog::getSaveFileName(QWidget* parent, const QString& caption, QString dir, - const QString& filter, QString* selectedFilter, - QFileDialog::Options options, const QString& defaultExtension) +QString FileDialog::getSaveFileName(QWidget* parent, + const QString& caption, + QString dir, + const QString& filter, + QString* selectedFilter, + QFileDialog::Options options, + const QString& defaultExtension) { if (!m_nextFileName.isEmpty()) { QString result = m_nextFileName; m_nextFileName.clear(); return result; - } - else { + } else { if (dir.isEmpty()) { dir = config()->get("LastDir").toString(); } @@ -95,8 +100,7 @@ QString FileDialog::getSaveFileName(QWidget* parent, const QString& caption, QSt #if defined(Q_OS_MAC) || defined(Q_OS_WIN) Q_UNUSED(defaultExtension); // the native dialogs on these platforms already append the file extension - result = QFileDialog::getSaveFileName(parent, caption, dir, filter, - selectedFilter, options); + result = QFileDialog::getSaveFileName(parent, caption, dir, filter, selectedFilter, options); #else QFileDialog dialog(parent, caption, dir, filter); dialog.setAcceptMode(QFileDialog::AcceptSave); @@ -126,15 +130,14 @@ QString FileDialog::getSaveFileName(QWidget* parent, const QString& caption, QSt } } -QString FileDialog::getExistingDirectory(QWidget *parent, const QString &caption, QString dir, - QFileDialog::Options options) +QString +FileDialog::getExistingDirectory(QWidget* parent, const QString& caption, QString dir, QFileDialog::Options options) { if (!m_nextDirName.isEmpty()) { QString result = m_nextDirName; m_nextDirName.clear(); return result; - } - else { + } else { if (dir.isEmpty()) { dir = config()->get("LastDir").toString(); } @@ -156,12 +159,12 @@ void FileDialog::setNextFileName(const QString& fileName) m_nextFileName = fileName; } -void FileDialog::setNextFileNames(const QStringList &fileNames) +void FileDialog::setNextFileNames(const QStringList& fileNames) { m_nextFileNames = fileNames; } -void FileDialog::setNextDirName(const QString &dirName) +void FileDialog::setNextDirName(const QString& dirName) { m_nextDirName = dirName; } @@ -175,7 +178,8 @@ FileDialog::FileDialog() { } -void FileDialog::saveLastDir(QString dir) { +void FileDialog::saveLastDir(QString dir) +{ if (!dir.isEmpty() && !m_forgetLastDir) { config()->set("LastDir", QFileInfo(dir).absolutePath()); } diff --git a/src/gui/FileDialog.h b/src/gui/FileDialog.h index 9a57a9218..4862dcfda 100644 --- a/src/gui/FileDialog.h +++ b/src/gui/FileDialog.h @@ -23,18 +23,29 @@ class FileDialog { public: - QString getOpenFileName(QWidget* parent = nullptr, const QString& caption = QString(), - QString dir = QString(), const QString& filter = QString(), - QString* selectedFilter = nullptr, QFileDialog::Options options = 0); - QStringList getOpenFileNames(QWidget* parent = nullptr, const QString& caption = QString(), - QString dir = QString(), const QString& filter = QString(), - QString* selectedFilter = nullptr, QFileDialog::Options options = 0); - QString getSaveFileName(QWidget* parent = nullptr, const QString& caption = QString(), - QString dir = QString(), const QString& filter = QString(), - QString* selectedFilter = nullptr, QFileDialog::Options options = 0, + QString getOpenFileName(QWidget* parent = nullptr, + const QString& caption = QString(), + QString dir = QString(), + const QString& filter = QString(), + QString* selectedFilter = nullptr, + QFileDialog::Options options = 0); + QStringList getOpenFileNames(QWidget* parent = nullptr, + const QString& caption = QString(), + QString dir = QString(), + const QString& filter = QString(), + QString* selectedFilter = nullptr, + QFileDialog::Options options = 0); + QString getSaveFileName(QWidget* parent = nullptr, + const QString& caption = QString(), + QString dir = QString(), + const QString& filter = QString(), + QString* selectedFilter = nullptr, + QFileDialog::Options options = 0, const QString& defaultExtension = QString()); - QString getExistingDirectory(QWidget* parent = nullptr, const QString& caption = QString(), - QString dir = QString(), QFileDialog::Options options = QFileDialog::ShowDirsOnly); + QString getExistingDirectory(QWidget* parent = nullptr, + const QString& caption = QString(), + QString dir = QString(), + QFileDialog::Options options = QFileDialog::ShowDirsOnly); void setNextForgetDialog(); /** @@ -61,7 +72,8 @@ private: Q_DISABLE_COPY(FileDialog) }; -inline FileDialog* fileDialog() { +inline FileDialog* fileDialog() +{ return FileDialog::instance(); } diff --git a/src/gui/Font.h b/src/gui/Font.h index bfc3d7d36..076c42770 100644 --- a/src/gui/Font.h +++ b/src/gui/Font.h @@ -24,8 +24,11 @@ class Font { public: static QFont fixedFont(); + private: - Font() {} + Font() + { + } }; #endif // KEEPASSX_FONT_H diff --git a/src/gui/IconModels.cpp b/src/gui/IconModels.cpp index 1c181eae2..48868284b 100644 --- a/src/gui/IconModels.cpp +++ b/src/gui/IconModels.cpp @@ -28,8 +28,7 @@ int DefaultIconModel::rowCount(const QModelIndex& parent) const { if (!parent.isValid()) { return DatabaseIcons::IconCount; - } - else { + } else { return 0; } } @@ -69,8 +68,7 @@ int CustomIconModel::rowCount(const QModelIndex& parent) const { if (!parent.isValid()) { return m_icons.size(); - } - else { + } else { return 0; } } @@ -101,8 +99,7 @@ QModelIndex CustomIconModel::indexFromUuid(const Uuid& uuid) const int idx = m_iconsOrder.indexOf(uuid); if (idx > -1) { return index(idx, 0); - } - else { + } else { return QModelIndex(); } } diff --git a/src/gui/KeePass1OpenWidget.cpp b/src/gui/KeePass1OpenWidget.cpp index 915864241..4a54aaf3a 100644 --- a/src/gui/KeePass1OpenWidget.cpp +++ b/src/gui/KeePass1OpenWidget.cpp @@ -20,11 +20,11 @@ #include #include -#include "ui_DatabaseOpenWidget.h" #include "core/Database.h" #include "core/Metadata.h" #include "format/KeePass1Reader.h" #include "gui/MessageBox.h" +#include "ui_DatabaseOpenWidget.h" KeePass1OpenWidget::KeePass1OpenWidget(QWidget* parent) : DatabaseOpenWidget(parent) @@ -49,8 +49,8 @@ void KeePass1OpenWidget::openDatabase() QFile file(m_filename); if (!file.open(QIODevice::ReadOnly)) { - m_ui->messageWidget->showMessage( tr("Unable to open the database.").append("\n") - .append(file.errorString()), MessageWidget::Error); + m_ui->messageWidget->showMessage(tr("Unable to open the database.").append("\n").append(file.errorString()), + MessageWidget::Error); return; } if (m_db) { @@ -63,10 +63,9 @@ void KeePass1OpenWidget::openDatabase() if (m_db) { m_db->metadata()->setName(QFileInfo(m_filename).completeBaseName()); emit editFinished(true); - } - else { - m_ui->messageWidget->showMessage(tr("Unable to open the database.").append("\n") - .append(reader.errorString()), MessageWidget::Error); + } else { + m_ui->messageWidget->showMessage(tr("Unable to open the database.").append("\n").append(reader.errorString()), + MessageWidget::Error); m_ui->editPassword->clear(); } diff --git a/src/gui/LineEdit.cpp b/src/gui/LineEdit.cpp index 148dc3d17..3e7574476 100644 --- a/src/gui/LineEdit.cpp +++ b/src/gui/LineEdit.cpp @@ -31,8 +31,8 @@ LineEdit::LineEdit(QWidget* parent) m_clearButton->setObjectName("clearButton"); QIcon icon; - QString iconNameDirected = QString("edit-clear-locationbar-").append( - (layoutDirection() == Qt::LeftToRight) ? "rtl" : "ltr"); + QString iconNameDirected = + QString("edit-clear-locationbar-").append((layoutDirection() == Qt::LeftToRight) ? "rtl" : "ltr"); icon = QIcon::fromTheme(iconNameDirected); if (icon.isNull()) { icon = QIcon::fromTheme("edit-clear"); @@ -48,8 +48,8 @@ LineEdit::LineEdit(QWidget* parent) connect(m_clearButton, SIGNAL(clicked()), this, SLOT(clear())); connect(this, SIGNAL(textChanged(QString)), this, SLOT(updateCloseButton(QString))); int frameWidth = style()->pixelMetric(QStyle::PM_DefaultFrameWidth); - setStyleSheet(QString("QLineEdit { padding-right: %1px; } ") - .arg(m_clearButton->sizeHint().width() + frameWidth + 1)); + setStyleSheet( + QString("QLineEdit { padding-right: %1px; } ").arg(m_clearButton->sizeHint().width() + frameWidth + 1)); QSize msz = minimumSizeHint(); setMinimumSize(qMax(msz.width(), m_clearButton->sizeHint().height() + frameWidth * 2 + 2), qMax(msz.height(), m_clearButton->sizeHint().height() + frameWidth * 2 + 2)); @@ -63,8 +63,7 @@ void LineEdit::resizeEvent(QResizeEvent* event) if (layoutDirection() == Qt::LeftToRight) { m_clearButton->move(rect().right() - frameWidth - sz.width(), y); - } - else { + } else { m_clearButton->move(rect().left() + frameWidth, y); } diff --git a/src/gui/MainWindow.cpp b/src/gui/MainWindow.cpp index 8549d8f82..95bdd3fa0 100644 --- a/src/gui/MainWindow.cpp +++ b/src/gui/MainWindow.cpp @@ -33,8 +33,8 @@ #include "core/Metadata.h" #include "format/KeePass2Writer.h" #include "gui/AboutDialog.h" -#include "gui/DatabaseWidget.h" #include "gui/DatabaseRepairWidget.h" +#include "gui/DatabaseWidget.h" #include "gui/FileDialog.h" #include "gui/MessageBox.h" #include "gui/SearchWidget.h" @@ -45,65 +45,72 @@ #endif #ifdef WITH_XC_BROWSER -#include "browser/NativeMessagingHost.h" -#include "browser/BrowserSettings.h" #include "browser/BrowserOptionDialog.h" +#include "browser/BrowserSettings.h" +#include "browser/NativeMessagingHost.h" #endif #if defined(Q_OS_UNIX) && !defined(Q_OS_MAC) && !defined(QT_NO_DBUS) +#include "gui/MainWindowAdaptor.h" #include #include -#include "gui/MainWindowAdaptor.h" #endif -#include "gui/SettingsWidget.h" #include "gui/PasswordGeneratorWidget.h" +#include "gui/SettingsWidget.h" #ifdef WITH_XC_BROWSER -class BrowserPlugin: public ISettingsPage +class BrowserPlugin : public ISettingsPage { - public: - BrowserPlugin(DatabaseTabWidget* tabWidget) { - m_nativeMessagingHost = QSharedPointer(new NativeMessagingHost(tabWidget)); - } +public: + BrowserPlugin(DatabaseTabWidget* tabWidget) + { + m_nativeMessagingHost = QSharedPointer(new NativeMessagingHost(tabWidget)); + } - ~BrowserPlugin() { + ~BrowserPlugin() + { + } - } + QString name() override + { + return QObject::tr("Browser Integration"); + } - QString name() override - { - return QObject::tr("Browser Integration"); - } + QIcon icon() override + { + return FilePath::instance()->icon("apps", "internet-web-browser"); + } - QIcon icon() override - { - return FilePath::instance()->icon("apps", "internet-web-browser"); - } + QWidget* createWidget() override + { + BrowserOptionDialog* dlg = new BrowserOptionDialog(); + QObject::connect(dlg, + SIGNAL(removeSharedEncryptionKeys()), + m_nativeMessagingHost.data(), + SLOT(removeSharedEncryptionKeys())); + QObject::connect( + dlg, SIGNAL(removeStoredPermissions()), m_nativeMessagingHost.data(), SLOT(removeStoredPermissions())); + return dlg; + } - QWidget* createWidget() override { - BrowserOptionDialog* dlg = new BrowserOptionDialog(); - QObject::connect(dlg, SIGNAL(removeSharedEncryptionKeys()), m_nativeMessagingHost.data(), SLOT(removeSharedEncryptionKeys())); - QObject::connect(dlg, SIGNAL(removeStoredPermissions()), m_nativeMessagingHost.data(), SLOT(removeStoredPermissions())); - return dlg; - } + void loadSettings(QWidget* widget) override + { + qobject_cast(widget)->loadSettings(); + } - void loadSettings(QWidget* widget) override - { - qobject_cast(widget)->loadSettings(); + void saveSettings(QWidget* widget) override + { + qobject_cast(widget)->saveSettings(); + if (BrowserSettings::isEnabled()) { + m_nativeMessagingHost->run(); + } else { + m_nativeMessagingHost->stop(); } + } - void saveSettings(QWidget* widget) override - { - qobject_cast(widget)->saveSettings(); - if (BrowserSettings::isEnabled()) { - m_nativeMessagingHost->run(); - } else { - m_nativeMessagingHost->stop(); - } - } - private: - QSharedPointer m_nativeMessagingHost; +private: + QSharedPointer m_nativeMessagingHost; }; #endif @@ -116,7 +123,7 @@ MainWindow::MainWindow() , m_appExiting(false) { m_ui->setupUi(this); - + #if defined(Q_OS_UNIX) && !defined(Q_OS_MAC) && !defined(QT_NO_DBUS) new MainWindowAdaptor(this); QDBusConnection dbus = QDBusConnection::sessionBus(); @@ -129,7 +136,7 @@ MainWindow::MainWindow() m_ui->toolBar->setContextMenuPolicy(Qt::PreventContextMenu); // Setup the search widget in the toolbar - SearchWidget *search = new SearchWidget(); + SearchWidget* search = new SearchWidget(); search->connectSignals(m_actionMultiplexer); m_searchWidgetAction = m_ui->toolBar->addWidget(search); m_searchWidgetAction->setEnabled(false); @@ -149,8 +156,10 @@ MainWindow::MainWindow() setWindowIcon(filePath()->applicationIcon()); m_ui->globalMessageWidget->setHidden(true); connect(m_ui->globalMessageWidget, &MessageWidget::linkActivated, &MessageWidget::openHttpUrl); - connect(m_ui->globalMessageWidget, SIGNAL(showAnimationStarted()), m_ui->globalMessageWidgetContainer, SLOT(show())); - connect(m_ui->globalMessageWidget, SIGNAL(hideAnimationFinished()), m_ui->globalMessageWidgetContainer, SLOT(hide())); + connect( + m_ui->globalMessageWidget, SIGNAL(showAnimationStarted()), m_ui->globalMessageWidgetContainer, SLOT(show())); + connect( + m_ui->globalMessageWidget, SIGNAL(hideAnimationFinished()), m_ui->globalMessageWidgetContainer, SLOT(hide())); m_clearHistoryAction = new QAction(tr("Clear history"), m_ui->menuFile); m_lastDatabasesActions = new QActionGroup(m_ui->menuRecentDatabases); @@ -159,14 +168,13 @@ MainWindow::MainWindow() connect(m_ui->menuRecentDatabases, SIGNAL(aboutToShow()), this, SLOT(updateLastDatabasesMenu())); m_copyAdditionalAttributeActions = new QActionGroup(m_ui->menuEntryCopyAttribute); - m_actionMultiplexer.connect(m_copyAdditionalAttributeActions, SIGNAL(triggered(QAction*)), - SLOT(copyAttribute(QAction*))); - connect(m_ui->menuEntryCopyAttribute, SIGNAL(aboutToShow()), - this, SLOT(updateCopyAttributesMenu())); + m_actionMultiplexer.connect( + m_copyAdditionalAttributeActions, SIGNAL(triggered(QAction*)), SLOT(copyAttribute(QAction*))); + connect(m_ui->menuEntryCopyAttribute, SIGNAL(aboutToShow()), this, SLOT(updateCopyAttributesMenu())); Qt::Key globalAutoTypeKey = static_cast(config()->get("GlobalAutoTypeKey").toInt()); - Qt::KeyboardModifiers globalAutoTypeModifiers = static_cast( - config()->get("GlobalAutoTypeModifiers").toInt()); + Qt::KeyboardModifiers globalAutoTypeModifiers = + static_cast(config()->get("GlobalAutoTypeModifiers").toInt()); if (globalAutoTypeKey > 0 && globalAutoTypeModifiers > 0) { autoType()->registerGlobalShortcut(globalAutoTypeKey, globalAutoTypeModifiers); } @@ -174,8 +182,7 @@ MainWindow::MainWindow() m_ui->actionEntryAutoType->setVisible(autoType()->isAvailable()); m_inactivityTimer = new InactivityTimer(this); - connect(m_inactivityTimer, SIGNAL(inactivityDetected()), - this, SLOT(lockDatabasesAfterInactivity())); + connect(m_inactivityTimer, SIGNAL(inactivityDetected()), this, SLOT(lockDatabasesAfterInactivity())); applySettingsChanges(); m_ui->actionDatabaseNew->setShortcut(Qt::CTRL + Qt::SHIFT + Qt::Key_N); @@ -229,35 +236,26 @@ MainWindow::MainWindow() m_ui->actionAbout->setIcon(filePath()->icon("actions", "help-about")); - m_actionMultiplexer.connect(SIGNAL(currentModeChanged(DatabaseWidget::Mode)), - this, SLOT(setMenuActionState(DatabaseWidget::Mode))); - m_actionMultiplexer.connect(SIGNAL(groupChanged()), - this, SLOT(setMenuActionState())); - m_actionMultiplexer.connect(SIGNAL(entrySelectionChanged()), - this, SLOT(setMenuActionState())); - m_actionMultiplexer.connect(SIGNAL(groupContextMenuRequested(QPoint)), - this, SLOT(showGroupContextMenu(QPoint))); - m_actionMultiplexer.connect(SIGNAL(entryContextMenuRequested(QPoint)), - this, SLOT(showEntryContextMenu(QPoint))); + m_actionMultiplexer.connect( + SIGNAL(currentModeChanged(DatabaseWidget::Mode)), this, SLOT(setMenuActionState(DatabaseWidget::Mode))); + m_actionMultiplexer.connect(SIGNAL(groupChanged()), this, SLOT(setMenuActionState())); + m_actionMultiplexer.connect(SIGNAL(entrySelectionChanged()), this, SLOT(setMenuActionState())); + m_actionMultiplexer.connect(SIGNAL(groupContextMenuRequested(QPoint)), this, SLOT(showGroupContextMenu(QPoint))); + m_actionMultiplexer.connect(SIGNAL(entryContextMenuRequested(QPoint)), this, SLOT(showEntryContextMenu(QPoint))); // Notify search when the active database changes or gets locked - connect(m_ui->tabWidget, SIGNAL(activateDatabaseChanged(DatabaseWidget*)), - search, SLOT(databaseChanged(DatabaseWidget*))); - connect(m_ui->tabWidget, SIGNAL(databaseLocked(DatabaseWidget*)), - search, SLOT(databaseChanged())); + connect(m_ui->tabWidget, + SIGNAL(activateDatabaseChanged(DatabaseWidget*)), + search, + SLOT(databaseChanged(DatabaseWidget*))); + connect(m_ui->tabWidget, SIGNAL(databaseLocked(DatabaseWidget*)), search, SLOT(databaseChanged())); - connect(m_ui->tabWidget, SIGNAL(tabNameChanged()), - SLOT(updateWindowTitle())); - connect(m_ui->tabWidget, SIGNAL(currentChanged(int)), - SLOT(updateWindowTitle())); - connect(m_ui->tabWidget, SIGNAL(currentChanged(int)), - SLOT(databaseTabChanged(int))); - connect(m_ui->tabWidget, SIGNAL(currentChanged(int)), - SLOT(setMenuActionState())); - connect(m_ui->tabWidget, SIGNAL(databaseLocked(DatabaseWidget*)), - SLOT(databaseStatusChanged(DatabaseWidget*))); - connect(m_ui->tabWidget, SIGNAL(databaseUnlocked(DatabaseWidget*)), - SLOT(databaseStatusChanged(DatabaseWidget*))); + connect(m_ui->tabWidget, SIGNAL(tabNameChanged()), SLOT(updateWindowTitle())); + connect(m_ui->tabWidget, SIGNAL(currentChanged(int)), SLOT(updateWindowTitle())); + connect(m_ui->tabWidget, SIGNAL(currentChanged(int)), SLOT(databaseTabChanged(int))); + connect(m_ui->tabWidget, SIGNAL(currentChanged(int)), SLOT(setMenuActionState())); + connect(m_ui->tabWidget, SIGNAL(databaseLocked(DatabaseWidget*)), SLOT(databaseStatusChanged(DatabaseWidget*))); + connect(m_ui->tabWidget, SIGNAL(databaseUnlocked(DatabaseWidget*)), SLOT(databaseStatusChanged(DatabaseWidget*))); connect(m_ui->stackedWidget, SIGNAL(currentChanged(int)), SLOT(setMenuActionState())); connect(m_ui->stackedWidget, SIGNAL(currentChanged(int)), SLOT(updateWindowTitle())); connect(m_ui->settingsWidget, SIGNAL(accepted()), SLOT(applySettingsChanges())); @@ -265,73 +263,42 @@ MainWindow::MainWindow() connect(m_ui->settingsWidget, SIGNAL(accepted()), SLOT(switchToDatabases())); connect(m_ui->settingsWidget, SIGNAL(rejected()), SLOT(switchToDatabases())); - connect(m_ui->actionDatabaseNew, SIGNAL(triggered()), m_ui->tabWidget, - SLOT(newDatabase())); - connect(m_ui->actionDatabaseOpen, SIGNAL(triggered()), m_ui->tabWidget, - SLOT(openDatabase())); - connect(m_ui->actionDatabaseSave, SIGNAL(triggered()), m_ui->tabWidget, - SLOT(saveDatabase())); - connect(m_ui->actionDatabaseSaveAs, SIGNAL(triggered()), m_ui->tabWidget, - SLOT(saveDatabaseAs())); - connect(m_ui->actionDatabaseClose, SIGNAL(triggered()), m_ui->tabWidget, - SLOT(closeDatabase())); - connect(m_ui->actionDatabaseMerge, SIGNAL(triggered()), m_ui->tabWidget, - SLOT(mergeDatabase())); - connect(m_ui->actionChangeMasterKey, SIGNAL(triggered()), m_ui->tabWidget, - SLOT(changeMasterKey())); - connect(m_ui->actionChangeDatabaseSettings, SIGNAL(triggered()), m_ui->tabWidget, - SLOT(changeDatabaseSettings())); - connect(m_ui->actionImportCsv, SIGNAL(triggered()), m_ui->tabWidget, - SLOT(importCsv())); - connect(m_ui->actionImportKeePass1, SIGNAL(triggered()), m_ui->tabWidget, - SLOT(importKeePass1Database())); - connect(m_ui->actionRepairDatabase, SIGNAL(triggered()), this, - SLOT(repairDatabase())); - connect(m_ui->actionExportCsv, SIGNAL(triggered()), m_ui->tabWidget, - SLOT(exportToCsv())); - connect(m_ui->actionLockDatabases, SIGNAL(triggered()), m_ui->tabWidget, - SLOT(lockDatabases())); + connect(m_ui->actionDatabaseNew, SIGNAL(triggered()), m_ui->tabWidget, SLOT(newDatabase())); + connect(m_ui->actionDatabaseOpen, SIGNAL(triggered()), m_ui->tabWidget, SLOT(openDatabase())); + connect(m_ui->actionDatabaseSave, SIGNAL(triggered()), m_ui->tabWidget, SLOT(saveDatabase())); + connect(m_ui->actionDatabaseSaveAs, SIGNAL(triggered()), m_ui->tabWidget, SLOT(saveDatabaseAs())); + connect(m_ui->actionDatabaseClose, SIGNAL(triggered()), m_ui->tabWidget, SLOT(closeDatabase())); + connect(m_ui->actionDatabaseMerge, SIGNAL(triggered()), m_ui->tabWidget, SLOT(mergeDatabase())); + connect(m_ui->actionChangeMasterKey, SIGNAL(triggered()), m_ui->tabWidget, SLOT(changeMasterKey())); + connect(m_ui->actionChangeDatabaseSettings, SIGNAL(triggered()), m_ui->tabWidget, SLOT(changeDatabaseSettings())); + connect(m_ui->actionImportCsv, SIGNAL(triggered()), m_ui->tabWidget, SLOT(importCsv())); + connect(m_ui->actionImportKeePass1, SIGNAL(triggered()), m_ui->tabWidget, SLOT(importKeePass1Database())); + connect(m_ui->actionRepairDatabase, SIGNAL(triggered()), this, SLOT(repairDatabase())); + connect(m_ui->actionExportCsv, SIGNAL(triggered()), m_ui->tabWidget, SLOT(exportToCsv())); + connect(m_ui->actionLockDatabases, SIGNAL(triggered()), m_ui->tabWidget, SLOT(lockDatabases())); connect(m_ui->actionQuit, SIGNAL(triggered()), SLOT(appExit())); - m_actionMultiplexer.connect(m_ui->actionEntryNew, SIGNAL(triggered()), - SLOT(createEntry())); - m_actionMultiplexer.connect(m_ui->actionEntryClone, SIGNAL(triggered()), - SLOT(cloneEntry())); - m_actionMultiplexer.connect(m_ui->actionEntryEdit, SIGNAL(triggered()), - SLOT(switchToEntryEdit())); - m_actionMultiplexer.connect(m_ui->actionEntryDelete, SIGNAL(triggered()), - SLOT(deleteEntries())); + m_actionMultiplexer.connect(m_ui->actionEntryNew, SIGNAL(triggered()), SLOT(createEntry())); + m_actionMultiplexer.connect(m_ui->actionEntryClone, SIGNAL(triggered()), SLOT(cloneEntry())); + m_actionMultiplexer.connect(m_ui->actionEntryEdit, SIGNAL(triggered()), SLOT(switchToEntryEdit())); + m_actionMultiplexer.connect(m_ui->actionEntryDelete, SIGNAL(triggered()), SLOT(deleteEntries())); - m_actionMultiplexer.connect(m_ui->actionEntryTotp, SIGNAL(triggered()), - SLOT(showTotp())); - m_actionMultiplexer.connect(m_ui->actionEntrySetupTotp, SIGNAL(triggered()), - SLOT(setupTotp())); + m_actionMultiplexer.connect(m_ui->actionEntryTotp, SIGNAL(triggered()), SLOT(showTotp())); + m_actionMultiplexer.connect(m_ui->actionEntrySetupTotp, SIGNAL(triggered()), SLOT(setupTotp())); - m_actionMultiplexer.connect(m_ui->actionEntryCopyTotp, SIGNAL(triggered()), - SLOT(copyTotp())); - m_actionMultiplexer.connect(m_ui->actionEntryCopyTitle, SIGNAL(triggered()), - SLOT(copyTitle())); - m_actionMultiplexer.connect(m_ui->actionEntryCopyUsername, SIGNAL(triggered()), - SLOT(copyUsername())); - m_actionMultiplexer.connect(m_ui->actionEntryCopyPassword, SIGNAL(triggered()), - SLOT(copyPassword())); - m_actionMultiplexer.connect(m_ui->actionEntryCopyURL, SIGNAL(triggered()), - SLOT(copyURL())); - m_actionMultiplexer.connect(m_ui->actionEntryCopyNotes, SIGNAL(triggered()), - SLOT(copyNotes())); - m_actionMultiplexer.connect(m_ui->actionEntryAutoType, SIGNAL(triggered()), - SLOT(performAutoType())); - m_actionMultiplexer.connect(m_ui->actionEntryOpenUrl, SIGNAL(triggered()), - SLOT(openUrl())); + m_actionMultiplexer.connect(m_ui->actionEntryCopyTotp, SIGNAL(triggered()), SLOT(copyTotp())); + m_actionMultiplexer.connect(m_ui->actionEntryCopyTitle, SIGNAL(triggered()), SLOT(copyTitle())); + m_actionMultiplexer.connect(m_ui->actionEntryCopyUsername, SIGNAL(triggered()), SLOT(copyUsername())); + m_actionMultiplexer.connect(m_ui->actionEntryCopyPassword, SIGNAL(triggered()), SLOT(copyPassword())); + m_actionMultiplexer.connect(m_ui->actionEntryCopyURL, SIGNAL(triggered()), SLOT(copyURL())); + m_actionMultiplexer.connect(m_ui->actionEntryCopyNotes, SIGNAL(triggered()), SLOT(copyNotes())); + m_actionMultiplexer.connect(m_ui->actionEntryAutoType, SIGNAL(triggered()), SLOT(performAutoType())); + m_actionMultiplexer.connect(m_ui->actionEntryOpenUrl, SIGNAL(triggered()), SLOT(openUrl())); - m_actionMultiplexer.connect(m_ui->actionGroupNew, SIGNAL(triggered()), - SLOT(createGroup())); - m_actionMultiplexer.connect(m_ui->actionGroupEdit, SIGNAL(triggered()), - SLOT(switchToGroupEdit())); - m_actionMultiplexer.connect(m_ui->actionGroupDelete, SIGNAL(triggered()), - SLOT(deleteGroup())); - m_actionMultiplexer.connect(m_ui->actionGroupEmptyRecycleBin, SIGNAL(triggered()), - SLOT(emptyRecycleBin())); + m_actionMultiplexer.connect(m_ui->actionGroupNew, SIGNAL(triggered()), SLOT(createGroup())); + m_actionMultiplexer.connect(m_ui->actionGroupEdit, SIGNAL(triggered()), SLOT(switchToGroupEdit())); + m_actionMultiplexer.connect(m_ui->actionGroupDelete, SIGNAL(triggered()), SLOT(deleteGroup())); + m_actionMultiplexer.connect(m_ui->actionGroupEmptyRecycleBin, SIGNAL(triggered()), SLOT(emptyRecycleBin())); connect(m_ui->actionSettings, SIGNAL(triggered()), SLOT(switchToSettings())); connect(m_ui->actionPasswordGenerator, SIGNAL(toggled(bool)), SLOT(switchToPasswordGen(bool))); @@ -349,9 +316,15 @@ MainWindow::MainWindow() setUnifiedTitleAndToolBarOnMac(true); #endif - connect(m_ui->tabWidget, SIGNAL(messageGlobal(QString,MessageWidget::MessageType)), this, SLOT(displayGlobalMessage(QString, MessageWidget::MessageType))); + connect(m_ui->tabWidget, + SIGNAL(messageGlobal(QString, MessageWidget::MessageType)), + this, + SLOT(displayGlobalMessage(QString, MessageWidget::MessageType))); connect(m_ui->tabWidget, SIGNAL(messageDismissGlobal()), this, SLOT(hideGlobalMessage())); - connect(m_ui->tabWidget, SIGNAL(messageTab(QString,MessageWidget::MessageType)), this, SLOT(displayTabMessage(QString, MessageWidget::MessageType))); + connect(m_ui->tabWidget, + SIGNAL(messageTab(QString, MessageWidget::MessageType)), + this, + SLOT(displayTabMessage(QString, MessageWidget::MessageType))); connect(m_ui->tabWidget, SIGNAL(messageDismissTab()), this, SLOT(hideTabMessage())); m_screenLockListener = new ScreenLockListener(this); @@ -360,15 +333,17 @@ MainWindow::MainWindow() updateTrayIcon(); if (config()->hasAccessError()) { - m_ui->globalMessageWidget->showMessage( - tr("Access error for config file %1").arg(config()->getFileName()), MessageWidget::Error); + m_ui->globalMessageWidget->showMessage(tr("Access error for config file %1").arg(config()->getFileName()), + MessageWidget::Error); } #ifndef KEEPASSXC_BUILD_TYPE_RELEASE - m_ui->globalMessageWidget->showMessage(tr("WARNING: You are using an unstable build of KeePassXC!\n" - "There is a high risk of corruption, maintain a backup of your databases.\n" - "This version is not meant for production use."), - MessageWidget::Warning, -1); + m_ui->globalMessageWidget->showMessage( + tr("WARNING: You are using an unstable build of KeePassXC!\n" + "There is a high risk of corruption, maintain a backup of your databases.\n" + "This version is not meant for production use."), + MessageWidget::Warning, + -1); #endif } @@ -461,7 +436,7 @@ void MainWindow::setMenuActionState(DatabaseWidget::Mode mode) switch (mode) { case DatabaseWidget::ViewMode: { - //bool inSearch = dbWidget->isInSearchMode(); + // bool inSearch = dbWidget->isInSearchMode(); bool singleEntrySelected = dbWidget->numberOfSelectedEntries() == 1; bool entriesSelected = dbWidget->numberOfSelectedEntries() > 0; bool groupSelected = dbWidget->isGroupSelected(); @@ -533,8 +508,7 @@ void MainWindow::setMenuActionState(DatabaseWidget::Mode mode) Q_ASSERT(false); } m_ui->actionDatabaseClose->setEnabled(true); - } - else { + } else { const QList entryActions = m_ui->menuEntries->actions(); for (QAction* action : entryActions) { action->setEnabled(false); @@ -629,8 +603,7 @@ void MainWindow::switchToDatabases() { if (m_ui->tabWidget->currentIndex() == -1) { m_ui->stackedWidget->setCurrentIndex(WelcomeScreen); - } - else { + } else { m_ui->stackedWidget->setCurrentIndex(DatabaseTabScreen); } } @@ -644,13 +617,13 @@ void MainWindow::switchToSettings() void MainWindow::switchToPasswordGen(bool enabled) { if (enabled == true) { - m_ui->passwordGeneratorWidget->loadSettings(); - m_ui->passwordGeneratorWidget->regeneratePassword(); - m_ui->passwordGeneratorWidget->setStandaloneMode(true); - m_ui->stackedWidget->setCurrentIndex(PasswordGeneratorScreen); + m_ui->passwordGeneratorWidget->loadSettings(); + m_ui->passwordGeneratorWidget->regeneratePassword(); + m_ui->passwordGeneratorWidget->setStandaloneMode(true); + m_ui->stackedWidget->setCurrentIndex(PasswordGeneratorScreen); } else { - m_ui->passwordGeneratorWidget->saveSettings(); - switchToDatabases(); + m_ui->passwordGeneratorWidget->saveSettings(); + switchToDatabases(); } } @@ -689,7 +662,7 @@ void MainWindow::switchToImportCsv() switchToDatabases(); } -void MainWindow::databaseStatusChanged(DatabaseWidget *) +void MainWindow::databaseStatusChanged(DatabaseWidget*) { updateTrayIcon(); } @@ -698,8 +671,7 @@ void MainWindow::databaseTabChanged(int tabIndex) { if (tabIndex != -1 && m_ui->stackedWidget->currentIndex() == WelcomeScreen) { m_ui->stackedWidget->setCurrentIndex(DatabaseTabScreen); - } - else if (tabIndex == -1 && m_ui->stackedWidget->currentIndex() == DatabaseTabScreen) { + } else if (tabIndex == -1 && m_ui->stackedWidget->currentIndex() == DatabaseTabScreen) { m_ui->stackedWidget->setCurrentIndex(WelcomeScreen); } @@ -714,10 +686,8 @@ void MainWindow::closeEvent(QCloseEvent* event) return; } - bool minimizeOnClose = isTrayIconEnabled() && - config()->get("GUI/MinimizeOnClose").toBool(); - if (minimizeOnClose && !m_appExitCalled) - { + bool minimizeOnClose = isTrayIconEnabled() && config()->get("GUI/MinimizeOnClose").toBool(); + if (minimizeOnClose && !m_appExitCalled) { event->ignore(); hideWindow(); @@ -736,8 +706,7 @@ void MainWindow::closeEvent(QCloseEvent* event) event->accept(); QApplication::quit(); - } - else { + } else { event->ignore(); } } @@ -746,8 +715,7 @@ void MainWindow::changeEvent(QEvent* event) { if ((event->type() == QEvent::WindowStateChange) && isMinimized()) { if (isTrayIconEnabled() && m_trayIcon && m_trayIcon->isVisible() - && config()->get("GUI/MinimizeToTray").toBool()) - { + && config()->get("GUI/MinimizeToTray").toBool()) { event->ignore(); QTimer::singleShot(0, this, SLOT(hide())); } @@ -755,8 +723,7 @@ void MainWindow::changeEvent(QEvent* event) if (config()->get("security/lockdatabaseminimize").toBool()) { m_ui->tabWidget->lockDatabases(); } - } - else { + } else { QMainWindow::changeEvent(event); } } @@ -775,20 +742,18 @@ bool MainWindow::saveLastDatabases() bool openPreviousDatabasesOnStartup = config()->get("OpenPreviousDatabasesOnStartup").toBool(); if (openPreviousDatabasesOnStartup) { - connect(m_ui->tabWidget, SIGNAL(databaseWithFileClosed(QString)), - this, SLOT(rememberOpenDatabases(QString))); + connect(m_ui->tabWidget, SIGNAL(databaseWithFileClosed(QString)), this, SLOT(rememberOpenDatabases(QString))); } if (!m_ui->tabWidget->closeAllDatabases()) { accept = false; - } - else { + } else { accept = true; } if (openPreviousDatabasesOnStartup) { - disconnect(m_ui->tabWidget, SIGNAL(databaseWithFileClosed(QString)), - this, SLOT(rememberOpenDatabases(QString))); + disconnect( + m_ui->tabWidget, SIGNAL(databaseWithFileClosed(QString)), this, SLOT(rememberOpenDatabases(QString))); config()->set("LastOpenedDatabases", m_openDatabases); } @@ -813,24 +778,23 @@ void MainWindow::updateTrayIcon() #else menu->addAction(m_ui->actionQuit); - connect(m_trayIcon, SIGNAL(activated(QSystemTrayIcon::ActivationReason)), + connect(m_trayIcon, + SIGNAL(activated(QSystemTrayIcon::ActivationReason)), SLOT(trayIconTriggered(QSystemTrayIcon::ActivationReason))); #endif connect(actionToggle, SIGNAL(triggered()), SLOT(toggleWindow())); m_trayIcon->setContextMenu(menu); - + m_trayIcon->setIcon(filePath()->trayIcon()); m_trayIcon->show(); } if (m_ui->tabWidget->hasLockableDatabases()) { m_trayIcon->setIcon(filePath()->trayIconUnlocked()); - } - else { + } else { m_trayIcon->setIcon(filePath()->trayIconLocked()); } - } - else { + } else { if (m_trayIcon) { m_trayIcon->hide(); delete m_trayIcon; @@ -853,8 +817,7 @@ void MainWindow::setShortcut(QAction* action, QKeySequence::StandardKey standard { if (!QKeySequence::keyBindings(standard).isEmpty()) { action->setShortcuts(standard); - } - else if (fallback != 0) { + } else if (fallback != 0) { action->setShortcut(QKeySequence(fallback)); } } @@ -874,8 +837,7 @@ void MainWindow::applySettingsChanges() m_inactivityTimer->setInactivityTimeout(timeout); if (config()->get("security/lockdatabaseidle").toBool()) { m_inactivityTimer->activate(); - } - else { + } else { m_inactivityTimer->deactivate(); } @@ -919,11 +881,10 @@ void MainWindow::toggleWindow() // and https://bugreports.qt.io/browse/QTBUG-58723 // check for !isVisible(), because isNativeMenuBar() does not work with appmenu-qt5 if (!m_ui->menubar->isVisible()) { - QDBusMessage msg = QDBusMessage::createMethodCall( - "com.canonical.AppMenu.Registrar", - "/com/canonical/AppMenu/Registrar", - "com.canonical.AppMenu.Registrar", - "RegisterWindow"); + QDBusMessage msg = QDBusMessage::createMethodCall("com.canonical.AppMenu.Registrar", + "/com/canonical/AppMenu/Registrar", + "com.canonical.AppMenu.Registrar", + "RegisterWindow"); QList args; args << QVariant::fromValue(static_cast(winId())) << QVariant::fromValue(QDBusObjectPath("/MenuBar/1")); @@ -947,8 +908,7 @@ void MainWindow::lockDatabasesAfterInactivity() void MainWindow::repairDatabase() { QString filter = QString("%1 (*.kdbx);;%2 (*)").arg(tr("KeePass 2 Database"), tr("All files")); - QString fileName = fileDialog()->getOpenFileName(this, tr("Open database"), QString(), - filter); + QString fileName = fileDialog()->getOpenFileName(this, tr("Open database"), QString(), filter); if (fileName.isEmpty()) { return; } @@ -959,17 +919,20 @@ void MainWindow::repairDatabase() connect(dbRepairWidget, SIGNAL(error()), dialog.data(), SLOT(reject())); dbRepairWidget->load(fileName); if (dialog->exec() == QDialog::Accepted && dbRepairWidget->database()) { - QString saveFileName = fileDialog()->getSaveFileName(this, tr("Save repaired database"), QString(), + QString saveFileName = fileDialog()->getSaveFileName(this, + tr("Save repaired database"), + QString(), tr("KeePass 2 Database").append(" (*.kdbx)"), - nullptr, 0, "kdbx"); + nullptr, + 0, + "kdbx"); if (!saveFileName.isEmpty()) { KeePass2Writer writer; writer.writeDatabase(saveFileName, dbRepairWidget->database()); if (writer.hasError()) { - displayGlobalMessage( - tr("Writing the database failed.").append("\n").append(writer.errorString()), - MessageWidget::Error); + displayGlobalMessage(tr("Writing the database failed.").append("\n").append(writer.errorString()), + MessageWidget::Error); } } } @@ -977,18 +940,21 @@ void MainWindow::repairDatabase() bool MainWindow::isTrayIconEnabled() const { - return config()->get("GUI/ShowTrayIcon").toBool() - && QSystemTrayIcon::isSystemTrayAvailable(); + return config()->get("GUI/ShowTrayIcon").toBool() && QSystemTrayIcon::isSystemTrayAvailable(); } -void MainWindow::displayGlobalMessage(const QString& text, MessageWidget::MessageType type, bool showClosebutton, +void MainWindow::displayGlobalMessage(const QString& text, + MessageWidget::MessageType type, + bool showClosebutton, int autoHideTimeout) { m_ui->globalMessageWidget->setCloseButtonVisible(showClosebutton); m_ui->globalMessageWidget->showMessage(text, type, autoHideTimeout); } -void MainWindow::displayTabMessage(const QString& text, MessageWidget::MessageType type, bool showClosebutton, +void MainWindow::displayTabMessage(const QString& text, + MessageWidget::MessageType type, + bool showClosebutton, int autoHideTimeout) { m_ui->tabWidget->currentDatabaseWidget()->showMessage(text, type, showClosebutton, autoHideTimeout); @@ -1008,8 +974,10 @@ void MainWindow::hideTabMessage() void MainWindow::showYubiKeyPopup() { - displayGlobalMessage(tr("Please touch the button on your YubiKey!"), MessageWidget::Information, - false, MessageWidget::DisableAutoHide); + displayGlobalMessage(tr("Please touch the button on your YubiKey!"), + MessageWidget::Information, + false, + MessageWidget::DisableAutoHide); setEnabled(false); } @@ -1030,7 +998,7 @@ void MainWindow::bringToFront() void MainWindow::handleScreenLock() { - if (config()->get("security/lockdatabasescreenlock").toBool()){ + if (config()->get("security/lockdatabasescreenlock").toBool()) { lockDatabasesAfterInactivity(); } } @@ -1038,7 +1006,7 @@ void MainWindow::handleScreenLock() QStringList MainWindow::kdbxFilesFromUrls(const QList& urls) { QStringList kdbxFiles; - for (const QUrl& url: urls) { + for (const QUrl& url : urls) { const QFileInfo fInfo(url.toLocalFile()); const bool isKdbxFile = fInfo.isFile() && fInfo.suffix().toLower() == "kdbx"; if (isKdbxFile) { @@ -1068,7 +1036,7 @@ void MainWindow::dropEvent(QDropEvent* event) if (!kdbxFiles.isEmpty()) { event->acceptProposedAction(); } - for (const QString& kdbxFile: kdbxFiles) { + for (const QString& kdbxFile : kdbxFiles) { openDatabase(kdbxFile); } } diff --git a/src/gui/MainWindow.h b/src/gui/MainWindow.h index 5ce695234..08e264e76 100644 --- a/src/gui/MainWindow.h +++ b/src/gui/MainWindow.h @@ -23,12 +23,13 @@ #include #include -#include "core/SignalMultiplexer.h" #include "core/ScreenLockListener.h" -#include "gui/DatabaseWidget.h" +#include "core/SignalMultiplexer.h" #include "gui/Application.h" +#include "gui/DatabaseWidget.h" -namespace Ui { +namespace Ui +{ class MainWindow; } @@ -37,7 +38,7 @@ class InactivityTimer; class MainWindow : public QMainWindow { Q_OBJECT - + #if defined(Q_OS_UNIX) && !defined(Q_OS_MAC) && !defined(QT_NO_DBUS) Q_CLASSINFO("D-Bus Interface", "org.keepassxc.KeePassXC.MainWindow") #endif @@ -55,12 +56,15 @@ public: }; public slots: - void openDatabase(const QString& fileName, const QString& pw = QString(), - const QString& keyFile = QString()); + void openDatabase(const QString& fileName, const QString& pw = QString(), const QString& keyFile = QString()); void appExit(); - void displayGlobalMessage(const QString& text, MessageWidget::MessageType type, bool showClosebutton = true, + void displayGlobalMessage(const QString& text, + MessageWidget::MessageType type, + bool showClosebutton = true, int autoHideTimeout = MessageWidget::DefaultAutoHideTimeout); - void displayTabMessage(const QString& text, MessageWidget::MessageType type, bool showClosebutton = true, + void displayTabMessage(const QString& text, + MessageWidget::MessageType type, + bool showClosebutton = true, int autoHideTimeout = MessageWidget::DefaultAutoHideTimeout); void hideGlobalMessage(); void showYubiKeyPopup(); @@ -86,7 +90,7 @@ private slots: void switchToKeePass1Database(); void switchToImportCsv(); void closePasswordGen(); - void databaseStatusChanged(DatabaseWidget *dbWidget); + void databaseStatusChanged(DatabaseWidget* dbWidget); void databaseTabChanged(int tabIndex); void openRecentDatabase(QAction* action); void clearLastDatabases(); @@ -137,7 +141,8 @@ private: bool m_appExiting; }; -#define KEEPASSXC_MAIN_WINDOW (qobject_cast(qApp) ? \ - qobject_cast(qobject_cast(qApp)->mainWindow()) : nullptr) +#define KEEPASSXC_MAIN_WINDOW \ + (qobject_cast(qApp) ? qobject_cast(qobject_cast(qApp)->mainWindow()) \ + : nullptr) #endif // KEEPASSX_MAINWINDOW_H diff --git a/src/gui/MessageBox.cpp b/src/gui/MessageBox.cpp index 40912b7e9..7aba6a2a6 100644 --- a/src/gui/MessageBox.cpp +++ b/src/gui/MessageBox.cpp @@ -20,14 +20,14 @@ QMessageBox::StandardButton MessageBox::m_nextAnswer(QMessageBox::NoButton); QMessageBox::StandardButton MessageBox::critical(QWidget* parent, - const QString& title, const QString& text, + const QString& title, + const QString& text, QMessageBox::StandardButtons buttons, QMessageBox::StandardButton defaultButton) { if (m_nextAnswer == QMessageBox::NoButton) { return QMessageBox::critical(parent, title, text, buttons, defaultButton); - } - else { + } else { QMessageBox::StandardButton returnButton = m_nextAnswer; m_nextAnswer = QMessageBox::NoButton; return returnButton; @@ -35,14 +35,14 @@ QMessageBox::StandardButton MessageBox::critical(QWidget* parent, } QMessageBox::StandardButton MessageBox::information(QWidget* parent, - const QString& title, const QString& text, + const QString& title, + const QString& text, QMessageBox::StandardButtons buttons, QMessageBox::StandardButton defaultButton) { if (m_nextAnswer == QMessageBox::NoButton) { return QMessageBox::information(parent, title, text, buttons, defaultButton); - } - else { + } else { QMessageBox::StandardButton returnButton = m_nextAnswer; m_nextAnswer = QMessageBox::NoButton; return returnButton; @@ -50,14 +50,14 @@ QMessageBox::StandardButton MessageBox::information(QWidget* parent, } QMessageBox::StandardButton MessageBox::question(QWidget* parent, - const QString& title, const QString& text, + const QString& title, + const QString& text, QMessageBox::StandardButtons buttons, QMessageBox::StandardButton defaultButton) { if (m_nextAnswer == QMessageBox::NoButton) { return QMessageBox::question(parent, title, text, buttons, defaultButton); - } - else { + } else { QMessageBox::StandardButton returnButton = m_nextAnswer; m_nextAnswer = QMessageBox::NoButton; return returnButton; @@ -65,14 +65,14 @@ QMessageBox::StandardButton MessageBox::question(QWidget* parent, } QMessageBox::StandardButton MessageBox::warning(QWidget* parent, - const QString& title, const QString& text, + const QString& title, + const QString& text, QMessageBox::StandardButtons buttons, QMessageBox::StandardButton defaultButton) { if (m_nextAnswer == QMessageBox::NoButton) { return QMessageBox::warning(parent, title, text, buttons, defaultButton); - } - else { + } else { QMessageBox::StandardButton returnButton = m_nextAnswer; m_nextAnswer = QMessageBox::NoButton; return returnButton; diff --git a/src/gui/MessageBox.h b/src/gui/MessageBox.h index 1ea4022ca..c6cdaa28c 100644 --- a/src/gui/MessageBox.h +++ b/src/gui/MessageBox.h @@ -24,19 +24,23 @@ class MessageBox { public: static QMessageBox::StandardButton critical(QWidget* parent, - const QString& title, const QString& text, + const QString& title, + const QString& text, QMessageBox::StandardButtons buttons = QMessageBox::Ok, QMessageBox::StandardButton defaultButton = QMessageBox::NoButton); static QMessageBox::StandardButton information(QWidget* parent, - const QString& title, const QString& text, + const QString& title, + const QString& text, QMessageBox::StandardButtons buttons = QMessageBox::Ok, QMessageBox::StandardButton defaultButton = QMessageBox::NoButton); static QMessageBox::StandardButton question(QWidget* parent, - const QString& title, const QString& text, + const QString& title, + const QString& text, QMessageBox::StandardButtons buttons = QMessageBox::Ok, QMessageBox::StandardButton defaultButton = QMessageBox::NoButton); static QMessageBox::StandardButton warning(QWidget* parent, - const QString& title, const QString& text, + const QString& title, + const QString& text, QMessageBox::StandardButtons buttons = QMessageBox::Ok, QMessageBox::StandardButton defaultButton = QMessageBox::NoButton); diff --git a/src/gui/MessageWidget.cpp b/src/gui/MessageWidget.cpp index f40e5aad0..5b18a583d 100644 --- a/src/gui/MessageWidget.cpp +++ b/src/gui/MessageWidget.cpp @@ -18,8 +18,8 @@ #include "MessageWidget.h" -#include #include +#include #include const int MessageWidget::DefaultAutoHideTimeout = 6000; @@ -45,7 +45,7 @@ void MessageWidget::showMessage(const QString& text, MessageWidget::MessageType showMessage(text, type, m_autoHideTimeout); } -void MessageWidget::showMessage(const QString &text, KMessageWidget::MessageType type, int autoHideTimeout) +void MessageWidget::showMessage(const QString& text, KMessageWidget::MessageType type, int autoHideTimeout) { setMessageType(type); setText(text); diff --git a/src/gui/PasswordEdit.cpp b/src/gui/PasswordEdit.cpp index b084f9cf0..94125acfe 100644 --- a/src/gui/PasswordEdit.cpp +++ b/src/gui/PasswordEdit.cpp @@ -42,7 +42,7 @@ void PasswordEdit::enableVerifyMode(PasswordEdit* basePasswordEdit) m_basePasswordEdit = basePasswordEdit; updateStylesheet(); - + connect(m_basePasswordEdit, SIGNAL(textChanged(QString)), SLOT(autocompletePassword(QString))); connect(m_basePasswordEdit, SIGNAL(textChanged(QString)), SLOT(updateStylesheet())); connect(this, SIGNAL(textChanged(QString)), SLOT(updateStylesheet())); @@ -54,13 +54,12 @@ void PasswordEdit::setShowPassword(bool show) { setEchoMode(show ? QLineEdit::Normal : QLineEdit::Password); // if I have a parent, I'm the child - if (m_basePasswordEdit){ + if (m_basePasswordEdit) { if (config()->get("security/passwordsrepeat").toBool()) { setEnabled(!show); setReadOnly(show); setText(m_basePasswordEdit->text()); - } - else { + } else { // This fix a bug when the QLineEdit is disabled while switching config if (isEnabled() == false) { setEnabled(true); @@ -86,8 +85,7 @@ void PasswordEdit::updateStylesheet() if (m_basePasswordEdit->text().startsWith(text())) { stylesheet = stylesheet.arg(CorrectSoFarColor.name()); - } - else { + } else { stylesheet = stylesheet.arg(ErrorColor.name()); } } diff --git a/src/gui/PasswordGeneratorWidget.cpp b/src/gui/PasswordGeneratorWidget.cpp index 7a93f86bd..3d8ebf7be 100644 --- a/src/gui/PasswordGeneratorWidget.cpp +++ b/src/gui/PasswordGeneratorWidget.cpp @@ -19,13 +19,13 @@ #include "PasswordGeneratorWidget.h" #include "ui_PasswordGeneratorWidget.h" -#include #include #include +#include #include "core/Config.h" -#include "core/PasswordGenerator.h" #include "core/FilePath.h" +#include "core/PasswordGenerator.h" #include "gui/Clipboard.h" PasswordGeneratorWidget::PasswordGeneratorWidget(QWidget* parent) @@ -96,16 +96,22 @@ void PasswordGeneratorWidget::loadSettings() m_ui->checkBoxLower->setChecked(config()->get("generator/LowerCase", PasswordGenerator::DefaultLower).toBool()); m_ui->checkBoxUpper->setChecked(config()->get("generator/UpperCase", PasswordGenerator::DefaultUpper).toBool()); m_ui->checkBoxNumbers->setChecked(config()->get("generator/Numbers", PasswordGenerator::DefaultNumbers).toBool()); - m_ui->checkBoxSpecialChars->setChecked(config()->get("generator/SpecialChars", PasswordGenerator::DefaultSpecial).toBool()); + m_ui->checkBoxSpecialChars->setChecked( + config()->get("generator/SpecialChars", PasswordGenerator::DefaultSpecial).toBool()); m_ui->checkBoxExtASCII->setChecked(config()->get("generator/EASCII", PasswordGenerator::DefaultEASCII).toBool()); - m_ui->checkBoxExcludeAlike->setChecked(config()->get("generator/ExcludeAlike", PasswordGenerator::DefaultLookAlike).toBool()); - m_ui->checkBoxEnsureEvery->setChecked(config()->get("generator/EnsureEvery", PasswordGenerator::DefaultFromEveryGroup).toBool()); + m_ui->checkBoxExcludeAlike->setChecked( + config()->get("generator/ExcludeAlike", PasswordGenerator::DefaultLookAlike).toBool()); + m_ui->checkBoxEnsureEvery->setChecked( + config()->get("generator/EnsureEvery", PasswordGenerator::DefaultFromEveryGroup).toBool()); m_ui->spinBoxLength->setValue(config()->get("generator/Length", PasswordGenerator::DefaultLength).toInt()); // Diceware config - m_ui->spinBoxWordCount->setValue(config()->get("generator/WordCount", PassphraseGenerator::DefaultWordCount).toInt()); - m_ui->editWordSeparator->setText(config()->get("generator/WordSeparator", PassphraseGenerator::DefaultSeparator).toString()); - m_ui->comboBoxWordList->setCurrentText(config()->get("generator/WordList", PassphraseGenerator::DefaultWordList).toString()); + m_ui->spinBoxWordCount->setValue( + config()->get("generator/WordCount", PassphraseGenerator::DefaultWordCount).toInt()); + m_ui->editWordSeparator->setText( + config()->get("generator/WordSeparator", PassphraseGenerator::DefaultSeparator).toString()); + m_ui->comboBoxWordList->setCurrentText( + config()->get("generator/WordList", PassphraseGenerator::DefaultWordList).toString()); // Password or diceware? m_ui->tabWidget->setCurrentIndex(config()->get("generator/Type", 0).toInt()); @@ -275,8 +281,7 @@ void PasswordGeneratorWidget::colorStrengthIndicator(double entropy) // Take the existing stylesheet and convert the text and background color to arguments QString style = m_ui->entropyProgressBar->styleSheet(); QRegularExpression re("(QProgressBar::chunk\\s*\\{.*?background-color:)[^;]+;", - QRegularExpression::CaseInsensitiveOption | - QRegularExpression::DotMatchesEverythingOption); + QRegularExpression::CaseInsensitiveOption | QRegularExpression::DotMatchesEverythingOption); style.replace(re, "\\1 %1;"); // Set the color and background based on entropy diff --git a/src/gui/PasswordGeneratorWidget.h b/src/gui/PasswordGeneratorWidget.h index ed4414377..84d5484b9 100644 --- a/src/gui/PasswordGeneratorWidget.h +++ b/src/gui/PasswordGeneratorWidget.h @@ -19,14 +19,15 @@ #ifndef KEEPASSX_PASSWORDGENERATORWIDGET_H #define KEEPASSX_PASSWORDGENERATORWIDGET_H -#include #include #include +#include -#include "core/PasswordGenerator.h" #include "core/PassphraseGenerator.h" +#include "core/PasswordGenerator.h" -namespace Ui { +namespace Ui +{ class PasswordGeneratorWidget; } @@ -55,7 +56,7 @@ public slots: void regeneratePassword(); void applyPassword(); void copyPassword(); - + signals: void appliedPassword(const QString& password); void dialogTerminated(); diff --git a/src/gui/SearchWidget.cpp b/src/gui/SearchWidget.cpp index bf961ecbb..c84ba8582 100644 --- a/src/gui/SearchWidget.cpp +++ b/src/gui/SearchWidget.cpp @@ -172,7 +172,6 @@ void SearchWidget::setLimitGroup(bool state) updateLimitGroup(); } - void SearchWidget::searchFocus() { m_ui->searchEdit->setFocus(); diff --git a/src/gui/SearchWidget.h b/src/gui/SearchWidget.h index 2441ef60b..1d95c664b 100644 --- a/src/gui/SearchWidget.h +++ b/src/gui/SearchWidget.h @@ -25,7 +25,8 @@ #include "core/SignalMultiplexer.h" #include "gui/DatabaseWidget.h" -namespace Ui { +namespace Ui +{ class SearchWidget; } diff --git a/src/gui/SettingsWidget.cpp b/src/gui/SettingsWidget.cpp index 56b1b2a38..be2f4cd44 100644 --- a/src/gui/SettingsWidget.cpp +++ b/src/gui/SettingsWidget.cpp @@ -20,32 +20,35 @@ #include "ui_SettingsWidgetGeneral.h" #include "ui_SettingsWidgetSecurity.h" -#include "config-keepassx.h" #include "autotype/AutoType.h" +#include "config-keepassx.h" #include "core/Config.h" -#include "core/Translator.h" #include "core/FilePath.h" #include "core/Global.h" +#include "core/Translator.h" class SettingsWidget::ExtraPage { - public: - ExtraPage(ISettingsPage* page, QWidget* widget): settingsPage(page), widget(widget) - {} +public: + ExtraPage(ISettingsPage* page, QWidget* widget) + : settingsPage(page) + , widget(widget) + { + } - void loadSettings() const - { - settingsPage->loadSettings(widget); - } + void loadSettings() const + { + settingsPage->loadSettings(widget); + } - void saveSettings() const - { - settingsPage->saveSettings(widget); - } + void saveSettings() const + { + settingsPage->saveSettings(widget); + } - private: - QSharedPointer settingsPage; - QWidget* widget; +private: + QSharedPointer settingsPage; + QWidget* widget; }; SettingsWidget::SettingsWidget(QWidget* parent) @@ -72,15 +75,16 @@ SettingsWidget::SettingsWidget(QWidget* parent) connect(this, SIGNAL(apply()), SLOT(saveSettings())); connect(this, SIGNAL(rejected()), SLOT(reject())); - connect(m_generalUi->autoSaveAfterEveryChangeCheckBox, SIGNAL(toggled(bool)), - this, SLOT(enableAutoSaveOnExit(bool))); - connect(m_generalUi->systrayShowCheckBox, SIGNAL(toggled(bool)), - this, SLOT(enableSystray(bool))); + connect( + m_generalUi->autoSaveAfterEveryChangeCheckBox, SIGNAL(toggled(bool)), this, SLOT(enableAutoSaveOnExit(bool))); + connect(m_generalUi->systrayShowCheckBox, SIGNAL(toggled(bool)), this, SLOT(enableSystray(bool))); - connect(m_secUi->clearClipboardCheckBox, SIGNAL(toggled(bool)), - m_secUi->clearClipboardSpinBox, SLOT(setEnabled(bool))); - connect(m_secUi->lockDatabaseIdleCheckBox, SIGNAL(toggled(bool)), - m_secUi->lockDatabaseIdleSpinBox, SLOT(setEnabled(bool))); + connect( + m_secUi->clearClipboardCheckBox, SIGNAL(toggled(bool)), m_secUi->clearClipboardSpinBox, SLOT(setEnabled(bool))); + connect(m_secUi->lockDatabaseIdleCheckBox, + SIGNAL(toggled(bool)), + m_secUi->lockDatabaseIdleSpinBox, + SLOT(setEnabled(bool))); #ifndef WITH_XC_NETWORKING m_secUi->privacy->setVisible(false); @@ -103,8 +107,7 @@ void SettingsWidget::loadSettings() { if (config()->hasAccessError()) { - showMessage( - tr("Access error for config file %1").arg(config()->getFileName()), MessageWidget::Error); + showMessage(tr("Access error for config file %1").arg(config()->getFileName()), MessageWidget::Error); } #ifdef QT_DEBUG @@ -127,7 +130,7 @@ void SettingsWidget::loadSettings() m_generalUi->ignoreGroupExpansionCheckBox->setChecked(config()->get("IgnoreGroupExpansion").toBool()); m_generalUi->languageComboBox->clear(); - QList > languages = Translator::availableLanguages(); + QList> languages = Translator::availableLanguages(); for (int i = 0; i < languages.size(); i++) { m_generalUi->languageComboBox->addItem(languages[i].second, languages[i].first); } @@ -146,7 +149,8 @@ void SettingsWidget::loadSettings() if (autoType()->isAvailable()) { m_globalAutoTypeKey = static_cast(config()->get("GlobalAutoTypeKey").toInt()); - m_globalAutoTypeModifiers = static_cast(config()->get("GlobalAutoTypeModifiers").toInt()); + m_globalAutoTypeModifiers = + static_cast(config()->get("GlobalAutoTypeModifiers").toInt()); if (m_globalAutoTypeKey > 0 && m_globalAutoTypeModifiers > 0) { m_generalUi->autoTypeShortcutWidget->setShortcut(m_globalAutoTypeKey, m_globalAutoTypeModifiers); } @@ -154,7 +158,6 @@ void SettingsWidget::loadSettings() m_generalUi->autoTypeDelaySpinBox->setValue(config()->get("AutoTypeDelay").toInt()); } - m_secUi->clearClipboardCheckBox->setChecked(config()->get("security/clearclipboard").toBool()); m_secUi->clearClipboardSpinBox->setValue(config()->get("security/clearclipboardtimeout").toInt()); @@ -170,8 +173,7 @@ void SettingsWidget::loadSettings() m_secUi->passwordRepeatCheckBox->setChecked(config()->get("security/passwordsrepeat").toBool()); m_secUi->hideNotesCheckBox->setChecked(config()->get("security/hidenotes").toBool()); - - for (const ExtraPage& page: asConst(m_extraPages)) { + for (const ExtraPage& page : asConst(m_extraPages)) { page.loadSettings(); } @@ -182,8 +184,7 @@ void SettingsWidget::saveSettings() { if (config()->hasAccessError()) { - showMessage( - tr("Access error for config file %1").arg(config()->getFileName()), MessageWidget::Error); + showMessage(tr("Access error for config file %1").arg(config()->getFileName()), MessageWidget::Error); // We prevent closing the settings page if we could not write to // the config file. return; @@ -192,23 +193,17 @@ void SettingsWidget::saveSettings() config()->set("SingleInstance", m_generalUi->singleInstanceCheckBox->isChecked()); config()->set("RememberLastDatabases", m_generalUi->rememberLastDatabasesCheckBox->isChecked()); config()->set("RememberLastKeyFiles", m_generalUi->rememberLastKeyFilesCheckBox->isChecked()); - config()->set("OpenPreviousDatabasesOnStartup", - m_generalUi->openPreviousDatabasesOnStartupCheckBox->isChecked()); - config()->set("AutoSaveAfterEveryChange", - m_generalUi->autoSaveAfterEveryChangeCheckBox->isChecked()); + config()->set("OpenPreviousDatabasesOnStartup", m_generalUi->openPreviousDatabasesOnStartupCheckBox->isChecked()); + config()->set("AutoSaveAfterEveryChange", m_generalUi->autoSaveAfterEveryChangeCheckBox->isChecked()); config()->set("AutoSaveOnExit", m_generalUi->autoSaveOnExitCheckBox->isChecked()); config()->set("BackupBeforeSave", m_generalUi->backupBeforeSaveCheckBox->isChecked()); config()->set("UseAtomicSaves", m_generalUi->useAtomicSavesCheckBox->isChecked()); config()->set("AutoReloadOnChange", m_generalUi->autoReloadOnChangeCheckBox->isChecked()); config()->set("MinimizeOnCopy", m_generalUi->minimizeOnCopyCheckBox->isChecked()); - config()->set("UseGroupIconOnEntryCreation", - m_generalUi->useGroupIconOnEntryCreationCheckBox->isChecked()); - config()->set("IgnoreGroupExpansion", - m_generalUi->ignoreGroupExpansionCheckBox->isChecked()); - config()->set("AutoTypeEntryTitleMatch", - m_generalUi->autoTypeEntryTitleMatchCheckBox->isChecked()); - config()->set("AutoTypeEntryURLMatch", - m_generalUi->autoTypeEntryURLMatchCheckBox->isChecked()); + config()->set("UseGroupIconOnEntryCreation", m_generalUi->useGroupIconOnEntryCreationCheckBox->isChecked()); + config()->set("IgnoreGroupExpansion", m_generalUi->ignoreGroupExpansionCheckBox->isChecked()); + config()->set("AutoTypeEntryTitleMatch", m_generalUi->autoTypeEntryTitleMatchCheckBox->isChecked()); + config()->set("AutoTypeEntryURLMatch", m_generalUi->autoTypeEntryURLMatchCheckBox->isChecked()); int currentLangIndex = m_generalUi->languageComboBox->currentIndex(); config()->set("GUI/Language", m_generalUi->languageComboBox->itemData(currentLangIndex).toString()); @@ -224,8 +219,7 @@ void SettingsWidget::saveSettings() if (autoType()->isAvailable()) { config()->set("GlobalAutoTypeKey", m_generalUi->autoTypeShortcutWidget->key()); - config()->set("GlobalAutoTypeModifiers", - static_cast(m_generalUi->autoTypeShortcutWidget->modifiers())); + config()->set("GlobalAutoTypeModifiers", static_cast(m_generalUi->autoTypeShortcutWidget->modifiers())); config()->set("AutoTypeDelay", m_generalUi->autoTypeDelaySpinBox->value()); } config()->set("security/clearclipboard", m_secUi->clearClipboardCheckBox->isChecked()); @@ -253,7 +247,7 @@ void SettingsWidget::saveSettings() config()->set("LastDir", ""); } - for (const ExtraPage& page: asConst(m_extraPages)) { + for (const ExtraPage& page : asConst(m_extraPages)) { page.saveSettings(); } } @@ -264,7 +258,6 @@ void SettingsWidget::reject() if (m_globalAutoTypeKey > 0 && m_globalAutoTypeModifiers > 0) { autoType()->registerGlobalShortcut(m_globalAutoTypeKey, m_globalAutoTypeModifiers); } - } void SettingsWidget::enableAutoSaveOnExit(bool checked) diff --git a/src/gui/SettingsWidget.h b/src/gui/SettingsWidget.h index 27566037d..d6a1a7e63 100644 --- a/src/gui/SettingsWidget.h +++ b/src/gui/SettingsWidget.h @@ -21,19 +21,23 @@ #include "gui/EditWidget.h" -namespace Ui { +namespace Ui +{ class SettingsWidgetGeneral; class SettingsWidgetSecurity; } -class ISettingsPage { +class ISettingsPage +{ public: - virtual ~ISettingsPage() {} + virtual ~ISettingsPage() + { + } virtual QString name() = 0; virtual QIcon icon() = 0; - virtual QWidget * createWidget() = 0; - virtual void loadSettings(QWidget * widget) = 0; - virtual void saveSettings(QWidget * widget) = 0; + virtual QWidget* createWidget() = 0; + virtual void loadSettings(QWidget* widget) = 0; + virtual void saveSettings(QWidget* widget) = 0; }; class SettingsWidget : public EditWidget @@ -43,7 +47,7 @@ class SettingsWidget : public EditWidget public: explicit SettingsWidget(QWidget* parent = nullptr); ~SettingsWidget(); - void addSettingsPage(ISettingsPage * page); + void addSettingsPage(ISettingsPage* page); void loadSettings(); private slots: diff --git a/src/gui/SetupTotpDialog.cpp b/src/gui/SetupTotpDialog.cpp index 52d63f0ef..ef7ee9e7c 100644 --- a/src/gui/SetupTotpDialog.cpp +++ b/src/gui/SetupTotpDialog.cpp @@ -17,9 +17,8 @@ */ #include "SetupTotpDialog.h" -#include "ui_SetupTotpDialog.h" #include "totp/totp.h" - +#include "ui_SetupTotpDialog.h" SetupTotpDialog::SetupTotpDialog(DatabaseWidget* parent, Entry* entry) : QDialog(parent) @@ -40,7 +39,6 @@ SetupTotpDialog::SetupTotpDialog(DatabaseWidget* parent, Entry* entry) connect(m_ui->radioCustom, SIGNAL(toggled(bool)), SLOT(toggleCustom(bool))); } - void SetupTotpDialog::setupTotp() { quint8 digits; @@ -86,17 +84,16 @@ void SetupTotpDialog::toggleCustom(bool status) m_ui->stepSpinBox->setEnabled(status); } - void SetupTotpDialog::setSeed(QString value) { m_ui->seedEdit->setText(value); } -void SetupTotpDialog::setSettings(quint8 digits) { +void SetupTotpDialog::setSettings(quint8 digits) +{ quint8 step = m_ui->stepSpinBox->value(); - bool isDefault = ((step == Totp::defaultStep) && - (digits == Totp::defaultDigits)); + bool isDefault = ((step == Totp::defaultStep) && (digits == Totp::defaultDigits)); bool isSteam = (digits == Totp::ENCODER_STEAM); if (isSteam) { diff --git a/src/gui/SetupTotpDialog.h b/src/gui/SetupTotpDialog.h index 9e90e9686..7c34bb5f1 100644 --- a/src/gui/SetupTotpDialog.h +++ b/src/gui/SetupTotpDialog.h @@ -19,13 +19,14 @@ #ifndef KEEPASSX_SETUPTOTPDIALOG_H #define KEEPASSX_SETUPTOTPDIALOG_H +#include "core/Database.h" +#include "core/Entry.h" +#include "gui/DatabaseWidget.h" #include #include -#include "core/Entry.h" -#include "core/Database.h" -#include "gui/DatabaseWidget.h" -namespace Ui { +namespace Ui +{ class SetupTotpDialog; } diff --git a/src/gui/TotpDialog.cpp b/src/gui/TotpDialog.cpp index 1529db0dc..75cf6a482 100644 --- a/src/gui/TotpDialog.cpp +++ b/src/gui/TotpDialog.cpp @@ -22,7 +22,6 @@ #include "core/Config.h" #include "gui/Clipboard.h" - TotpDialog::TotpDialog(DatabaseWidget* parent, Entry* entry) : QDialog(parent) , m_ui(new Ui::TotpDialog()) @@ -68,7 +67,6 @@ void TotpDialog::updateProgressBar() } } - void TotpDialog::updateSeconds() { uint epoch = QDateTime::currentDateTime().toTime_t() - 1; diff --git a/src/gui/TotpDialog.h b/src/gui/TotpDialog.h index ce21a66fd..e002cb82a 100644 --- a/src/gui/TotpDialog.h +++ b/src/gui/TotpDialog.h @@ -19,15 +19,16 @@ #ifndef KEEPASSX_TOTPDIALOG_H #define KEEPASSX_TOTPDIALOG_H +#include "core/Database.h" +#include "core/Entry.h" +#include "gui/DatabaseWidget.h" #include #include #include #include -#include "core/Entry.h" -#include "core/Database.h" -#include "gui/DatabaseWidget.h" -namespace Ui { +namespace Ui +{ class TotpDialog; } diff --git a/src/gui/UnlockDatabaseDialog.cpp b/src/gui/UnlockDatabaseDialog.cpp index cea5918a9..3d900f523 100644 --- a/src/gui/UnlockDatabaseDialog.cpp +++ b/src/gui/UnlockDatabaseDialog.cpp @@ -30,7 +30,7 @@ UnlockDatabaseDialog::UnlockDatabaseDialog(QWidget* parent) connect(m_view, SIGNAL(editFinished(bool)), this, SLOT(complete(bool))); } -void UnlockDatabaseDialog::setFilePath(const QString &filePath) +void UnlockDatabaseDialog::setFilePath(const QString& filePath) { m_view->load(filePath); } diff --git a/src/gui/UnlockDatabaseDialog.h b/src/gui/UnlockDatabaseDialog.h index 7dec06765..95d6ce238 100644 --- a/src/gui/UnlockDatabaseDialog.h +++ b/src/gui/UnlockDatabaseDialog.h @@ -32,7 +32,7 @@ class UnlockDatabaseDialog : public QDialog Q_OBJECT public: explicit UnlockDatabaseDialog(QWidget* parent = nullptr); - void setFilePath(const QString &filePath); + void setFilePath(const QString& filePath); void clearForms(); Database* database(); diff --git a/src/gui/UnlockDatabaseWidget.cpp b/src/gui/UnlockDatabaseWidget.cpp index a777d493e..ffd2bf225 100644 --- a/src/gui/UnlockDatabaseWidget.cpp +++ b/src/gui/UnlockDatabaseWidget.cpp @@ -17,9 +17,9 @@ #include "UnlockDatabaseWidget.h" -#include "ui_DatabaseOpenWidget.h" #include "core/Database.h" #include "gui/MessageBox.h" +#include "ui_DatabaseOpenWidget.h" UnlockDatabaseWidget::UnlockDatabaseWidget(QWidget* parent) : DatabaseOpenWidget(parent) diff --git a/src/gui/WelcomeWidget.cpp b/src/gui/WelcomeWidget.cpp index ed9d025a9..7bb4484c7 100644 --- a/src/gui/WelcomeWidget.cpp +++ b/src/gui/WelcomeWidget.cpp @@ -20,8 +20,8 @@ #include "ui_WelcomeWidget.h" #include "config-keepassx.h" -#include "core/FilePath.h" #include "core/Config.h" +#include "core/FilePath.h" WelcomeWidget::WelcomeWidget(QWidget* parent) : QWidget(parent) @@ -48,8 +48,10 @@ WelcomeWidget::WelcomeWidget(QWidget* parent) connect(m_ui->buttonOpenDatabase, SIGNAL(clicked()), SIGNAL(openDatabase())); connect(m_ui->buttonImportKeePass1, SIGNAL(clicked()), SIGNAL(importKeePass1Database())); connect(m_ui->buttonImportCSV, SIGNAL(clicked()), SIGNAL(importCsv())); - connect(m_ui->recentListWidget, SIGNAL(itemActivated(QListWidgetItem*)), this, - SLOT(openDatabaseFromFile(QListWidgetItem*))); + connect(m_ui->recentListWidget, + SIGNAL(itemActivated(QListWidgetItem*)), + this, + SLOT(openDatabaseFromFile(QListWidgetItem*))); } WelcomeWidget::~WelcomeWidget() @@ -58,10 +60,10 @@ WelcomeWidget::~WelcomeWidget() void WelcomeWidget::openDatabaseFromFile(QListWidgetItem* item) { - if (item->text().isEmpty()) { - return; - } - emit openDatabaseFile(item->text()); + if (item->text().isEmpty()) { + return; + } + emit openDatabaseFile(item->text()); } void WelcomeWidget::refreshLastDatabases() @@ -69,7 +71,7 @@ void WelcomeWidget::refreshLastDatabases() m_ui->recentListWidget->clear(); const QStringList lastDatabases = config()->get("LastDatabases", QVariant()).toStringList(); for (const QString& database : lastDatabases) { - QListWidgetItem *itm = new QListWidgetItem; + QListWidgetItem* itm = new QListWidgetItem; itm->setText(database); m_ui->recentListWidget->addItem(itm); } diff --git a/src/gui/WelcomeWidget.h b/src/gui/WelcomeWidget.h index 71ceda354..1b2483437 100644 --- a/src/gui/WelcomeWidget.h +++ b/src/gui/WelcomeWidget.h @@ -19,10 +19,11 @@ #ifndef KEEPASSX_WELCOMEWIDGET_H #define KEEPASSX_WELCOMEWIDGET_H -#include #include +#include -namespace Ui { +namespace Ui +{ class WelcomeWidget; } diff --git a/src/gui/csvImport/CsvImportWidget.cpp b/src/gui/csvImport/CsvImportWidget.cpp index c2c2aa03e..f90f46366 100644 --- a/src/gui/csvImport/CsvImportWidget.cpp +++ b/src/gui/csvImport/CsvImportWidget.cpp @@ -27,24 +27,19 @@ #include "gui/MessageBox.h" #include "gui/MessageWidget.h" -//I wanted to make the CSV import GUI future-proof, so if one day you need entries -//to have a new field, all you have to do is uncomment a row or two here, and the GUI will follow: -//dynamic generation of comboBoxes, labels, placement and so on. Try it for immense fun! -const QStringList CsvImportWidget::m_columnHeader = QStringList() - << QObject::tr("Group") - << QObject::tr("Title") - << QObject::tr("Username") - << QObject::tr("Password") - << QObject::tr("URL") - << QObject::tr("Notes") - << QObject::tr("Last Modified") - << QObject::tr("Created") -// << QObject::tr("Future field1") -// << QObject::tr("Future field2") -// << QObject::tr("Future field3") +// I wanted to make the CSV import GUI future-proof, so if one day you need entries +// to have a new field, all you have to do is uncomment a row or two here, and the GUI will follow: +// dynamic generation of comboBoxes, labels, placement and so on. Try it for immense fun! +const QStringList CsvImportWidget::m_columnHeader = + QStringList() << QObject::tr("Group") << QObject::tr("Title") << QObject::tr("Username") << QObject::tr("Password") + << QObject::tr("URL") << QObject::tr("Notes") << QObject::tr("Last Modified") + << QObject::tr("Created") + // << QObject::tr("Future field1") + // << QObject::tr("Future field2") + // << QObject::tr("Future field3") ; -CsvImportWidget::CsvImportWidget(QWidget *parent) +CsvImportWidget::CsvImportWidget(QWidget* parent) : QWidget(parent) , m_ui(new Ui::CsvImportWidget()) , m_parserModel(new CsvParserModel(this)) @@ -53,10 +48,24 @@ CsvImportWidget::CsvImportWidget(QWidget *parent) { m_ui->setupUi(this); - m_ui->comboBoxCodec->addItems(QStringList() <<"UTF-8" <<"Windows-1252" <<"UTF-16" <<"UTF-16LE"); - m_ui->comboBoxFieldSeparator->addItems(QStringList() <<"," <<";" <<"-" <<":" <<"."); - m_ui->comboBoxTextQualifier->addItems(QStringList() <<"\"" <<"'" <<":" <<"." <<"|"); - m_ui->comboBoxComment->addItems(QStringList() <<"#" <<";" <<":" <<"@"); + m_ui->comboBoxCodec->addItems(QStringList() << "UTF-8" + << "Windows-1252" + << "UTF-16" + << "UTF-16LE"); + m_ui->comboBoxFieldSeparator->addItems(QStringList() << "," + << ";" + << "-" + << ":" + << "."); + m_ui->comboBoxTextQualifier->addItems(QStringList() << "\"" + << "'" + << ":" + << "." + << "|"); + m_ui->comboBoxComment->addItems(QStringList() << "#" + << ";" + << ":" + << "@"); m_ui->tableViewFields->setSelectionMode(QAbstractItemView::NoSelection); m_ui->tableViewFields->setFocusPolicy(Qt::NoFocus); m_ui->messageWidget->setHidden(true); @@ -77,14 +86,14 @@ CsvImportWidget::CsvImportWidget(QWidget *parent) m_comboMapper->setMapping(combo, i); connect(combo, SIGNAL(currentIndexChanged(int)), m_comboMapper, SLOT(map())); - //layout labels and combo fields in column-first order + // layout labels and combo fields in column-first order int combo_rows = 1 + (m_columnHeader.count() - 1) / 2; int x = i % combo_rows; int y = 2 * (i / combo_rows); m_ui->gridLayout_combos->addWidget(label, x, y); - m_ui->gridLayout_combos->addWidget(combo, x, y+1); - QSpacerItem *item = new QSpacerItem(1,1, QSizePolicy::Expanding, QSizePolicy::Fixed); - m_ui->gridLayout_combos->addItem(item, x, y+2); + m_ui->gridLayout_combos->addWidget(combo, x, y + 1); + QSpacerItem* item = new QSpacerItem(1, 1, QSizePolicy::Expanding, QSizePolicy::Fixed); + m_ui->gridLayout_combos->addItem(item, x, y + 2); } m_parserModel->setHeaderLabels(m_columnHeader); @@ -103,22 +112,27 @@ CsvImportWidget::CsvImportWidget(QWidget *parent) connect(m_ui->buttonBox, SIGNAL(rejected()), this, SLOT(reject())); } -void CsvImportWidget::comboChanged(int comboId) { +void CsvImportWidget::comboChanged(int comboId) +{ QComboBox* currentSender = qobject_cast(m_comboMapper->mapping(comboId)); if (currentSender->currentIndex() != -1) - //this line is the one that actually updates GUI table + // this line is the one that actually updates GUI table m_parserModel->mapColumns(currentSender->currentIndex(), comboId); updateTableview(); } -void CsvImportWidget::skippedChanged(int rows) { +void CsvImportWidget::skippedChanged(int rows) +{ m_parserModel->setSkippedRows(rows); updateTableview(); } -CsvImportWidget::~CsvImportWidget() {} +CsvImportWidget::~CsvImportWidget() +{ +} -void CsvImportWidget::configParser() { +void CsvImportWidget::configParser() +{ m_parserModel->setBackslashSyntax(m_ui->checkBoxBackslash->isChecked()); m_parserModel->setComment(m_ui->comboBoxComment->currentText().at(0)); m_parserModel->setTextQualifier(m_ui->comboBoxTextQualifier->currentText().at(0)); @@ -126,7 +140,8 @@ void CsvImportWidget::configParser() { m_parserModel->setFieldSeparator(m_ui->comboBoxFieldSeparator->currentText().at(0)); } -void CsvImportWidget::updateTableview() { +void CsvImportWidget::updateTableview() +{ m_ui->tableViewFields->resizeRowsToContents(); m_ui->tableViewFields->resizeColumnsToContents(); @@ -134,7 +149,8 @@ void CsvImportWidget::updateTableview() { m_ui->tableViewFields->horizontalHeader()->setSectionResizeMode(c, QHeaderView::Stretch); } -void CsvImportWidget::updatePreview() { +void CsvImportWidget::updatePreview() +{ int minSkip = 0; if (m_ui->checkBoxFieldNames->isChecked()) @@ -159,7 +175,7 @@ void CsvImportWidget::updatePreview() { } m_comboModel->setStringList(list); - int j=1; + int j = 1; for (QComboBox* b : m_combos) { if (j < m_parserModel->getCsvCols()) b->setCurrentIndex(j); @@ -169,8 +185,9 @@ void CsvImportWidget::updatePreview() { } } -void CsvImportWidget::load(const QString& filename, Database* const db) { - //QApplication::processEvents(); +void CsvImportWidget::load(const QString& filename, Database* const db) +{ + // QApplication::processEvents(); m_db = db; m_parserModel->setFilename(filename); m_ui->labelFilename->setText(filename); @@ -180,29 +197,28 @@ void CsvImportWidget::load(const QString& filename, Database* const db) { parse(); } -void CsvImportWidget::parse() { +void CsvImportWidget::parse() +{ configParser(); QApplication::setOverrideCursor(Qt::WaitCursor); - //QApplication::processEvents(); + // QApplication::processEvents(); bool good = m_parserModel->parse(); updatePreview(); QApplication::restoreOverrideCursor(); if (!good) - m_ui->messageWidget->showMessage(tr("Error(s) detected in CSV file!").append("\n") - .append(formatStatusText()), MessageWidget::Warning); + m_ui->messageWidget->showMessage(tr("Error(s) detected in CSV file!").append("\n").append(formatStatusText()), + MessageWidget::Warning); else m_ui->messageWidget->setHidden(true); QWidget::adjustSize(); } - -QString CsvImportWidget::formatStatusText() const { +QString CsvImportWidget::formatStatusText() const +{ QString text = m_parserModel->getStatus(); int items = text.count('\n'); if (items > 2) { - return text.section('\n', 0, 1) - .append("\n") - .append(tr("[%n more message(s) skipped]", "", items - 2)); + return text.section('\n', 0, 1).append("\n").append(tr("[%n more message(s) skipped]", "", items - 2)); } if (items == 1) { text.append(QString("\n")); @@ -210,11 +226,12 @@ QString CsvImportWidget::formatStatusText() const { return text; } -void CsvImportWidget::writeDatabase() { +void CsvImportWidget::writeDatabase() +{ setRootGroup(); for (int r = 0; r < m_parserModel->rowCount(); ++r) { - //use validity of second column as a GO/NOGO for all others fields + // use validity of second column as a GO/NOGO for all others fields if (not m_parserModel->data(m_parserModel->index(r, 1)).isValid()) continue; Entry* entry = new Entry(); @@ -230,7 +247,8 @@ void CsvImportWidget::writeDatabase() { if (m_parserModel->data(m_parserModel->index(r, 6)).isValid()) { qint64 lastModified = m_parserModel->data(m_parserModel->index(r, 6)).toString().toLongLong(); if (lastModified) { - timeInfo.setLastModificationTime(QDateTime::fromMSecsSinceEpoch(lastModified * 1000).toTimeSpec(Qt::UTC)); + timeInfo.setLastModificationTime( + QDateTime::fromMSecsSinceEpoch(lastModified * 1000).toTimeSpec(Qt::UTC)); } } if (m_parserModel->data(m_parserModel->index(r, 7)).isValid()) { @@ -247,35 +265,37 @@ void CsvImportWidget::writeDatabase() { KeePass2Writer writer; writer.writeDatabase(&buffer, m_db); if (writer.hasError()) - MessageBox::warning(this, tr("Error"), tr("CSV import: writer has errors:\n%1") - .arg(writer.errorString()), QMessageBox::Ok, QMessageBox::Ok); + MessageBox::warning(this, + tr("Error"), + tr("CSV import: writer has errors:\n%1").arg(writer.errorString()), + QMessageBox::Ok, + QMessageBox::Ok); emit editFinished(true); } - -void CsvImportWidget::setRootGroup() { +void CsvImportWidget::setRootGroup() +{ QString groupLabel; QStringList groupList; - bool is_root = false; + bool is_root = false; bool is_empty = false; bool is_label = false; for (int r = 0; r < m_parserModel->rowCount(); ++r) { - //use validity of second column as a GO/NOGO for all others fields + // use validity of second column as a GO/NOGO for all others fields if (not m_parserModel->data(m_parserModel->index(r, 1)).isValid()) continue; groupLabel = m_parserModel->data(m_parserModel->index(r, 0)).toString(); - //check if group name is either "root", "" (empty) or some other label + // check if group name is either "root", "" (empty) or some other label groupList = groupLabel.split("/", QString::SkipEmptyParts); if (groupList.isEmpty()) is_empty = true; + else if (not groupList.first().compare("Root", Qt::CaseSensitive)) + is_root = true; + else if (not groupLabel.compare("")) + is_empty = true; else - if (not groupList.first().compare("Root", Qt::CaseSensitive)) - is_root = true; - else if (not groupLabel.compare("")) - is_empty = true; - else - is_label = true; + is_label = true; groupList.clear(); } @@ -286,21 +306,22 @@ void CsvImportWidget::setRootGroup() { m_db->rootGroup()->setName("Root"); } -Group *CsvImportWidget::splitGroups(QString label) { - //extract group names from nested path provided in "label" - Group *current = m_db->rootGroup(); +Group* CsvImportWidget::splitGroups(QString label) +{ + // extract group names from nested path provided in "label" + Group* current = m_db->rootGroup(); if (label.isEmpty()) return current; QStringList groupList = label.split("/", QString::SkipEmptyParts); - //avoid the creation of a subgroup with the same name as Root + // avoid the creation of a subgroup with the same name as Root if (m_db->rootGroup()->name() == "Root" && groupList.first() == "Root") groupList.removeFirst(); for (const QString& groupName : groupList) { - Group *children = hasChildren(current, groupName); + Group* children = hasChildren(current, groupName); if (children == nullptr) { - Group *brandNew = new Group(); + Group* brandNew = new Group(); brandNew->setParent(current); brandNew->setName(groupName); brandNew->setUuid(Uuid::random()); @@ -313,15 +334,17 @@ Group *CsvImportWidget::splitGroups(QString label) { return current; } -Group* CsvImportWidget::hasChildren(Group* current, QString groupName) { - //returns the group whose name is "groupName" and is child of "current" group - for (Group * group : current->children()) { +Group* CsvImportWidget::hasChildren(Group* current, QString groupName) +{ + // returns the group whose name is "groupName" and is child of "current" group + for (Group* group : current->children()) { if (group->name() == groupName) return group; } return nullptr; } -void CsvImportWidget::reject() { +void CsvImportWidget::reject() +{ emit editFinished(false); } diff --git a/src/gui/csvImport/CsvImportWidget.h b/src/gui/csvImport/CsvImportWidget.h index 463a92c5c..3823fcb2c 100644 --- a/src/gui/csvImport/CsvImportWidget.h +++ b/src/gui/csvImport/CsvImportWidget.h @@ -19,20 +19,20 @@ #ifndef KEEPASSX_CSVIMPORTWIDGET_H #define KEEPASSX_CSVIMPORTWIDGET_H -#include -#include -#include -#include -#include #include +#include +#include +#include +#include #include +#include #include "core/Metadata.h" #include "gui/csvImport/CsvParserModel.h" #include "keys/PasswordKey.h" - -namespace Ui { +namespace Ui +{ class CsvImportWidget; } diff --git a/src/gui/csvImport/CsvImportWizard.cpp b/src/gui/csvImport/CsvImportWizard.cpp index e9a8f4984..d1d152154 100644 --- a/src/gui/csvImport/CsvImportWizard.cpp +++ b/src/gui/csvImport/CsvImportWizard.cpp @@ -23,8 +23,7 @@ #include "gui/MessageBox.h" - -CsvImportWizard::CsvImportWizard(QWidget *parent) +CsvImportWizard::CsvImportWizard(QWidget* parent) : DialogyWidget(parent) { m_layout = new QGridLayout(this); @@ -34,7 +33,8 @@ CsvImportWizard::CsvImportWizard(QWidget *parent) } CsvImportWizard::~CsvImportWizard() -{} +{ +} void CsvImportWizard::load(const QString& filename, Database* database) { diff --git a/src/gui/csvImport/CsvImportWizard.h b/src/gui/csvImport/CsvImportWizard.h index b6414c0c9..9c11e9d11 100644 --- a/src/gui/csvImport/CsvImportWizard.h +++ b/src/gui/csvImport/CsvImportWizard.h @@ -21,8 +21,8 @@ #include "CsvImportWidget.h" -#include #include +#include #include "core/Database.h" #include "gui/ChangeMasterKeyWidget.h" @@ -35,9 +35,9 @@ class CsvImportWizard : public DialogyWidget Q_OBJECT public: - explicit CsvImportWizard(QWidget *parent = nullptr); + explicit CsvImportWizard(QWidget* parent = nullptr); ~CsvImportWizard(); - void load(const QString& filename, Database *database); + void load(const QString& filename, Database* database); void keyFinished(bool accepted, CompositeKey key); signals: @@ -49,7 +49,7 @@ private slots: private: Database* m_db; CsvImportWidget* m_parse; - QGridLayout *m_layout; + QGridLayout* m_layout; }; -#endif //KEEPASSX_CSVIMPORTWIZARD_H +#endif // KEEPASSX_CSVIMPORTWIZARD_H diff --git a/src/gui/csvImport/CsvParserModel.cpp b/src/gui/csvImport/CsvParserModel.cpp index eb2793f86..e69ea1853 100644 --- a/src/gui/csvImport/CsvParserModel.cpp +++ b/src/gui/csvImport/CsvParserModel.cpp @@ -18,27 +18,32 @@ #include "CsvParserModel.h" -CsvParserModel::CsvParserModel(QObject *parent) +CsvParserModel::CsvParserModel(QObject* parent) : QAbstractTableModel(parent) , m_skipped(0) -{} +{ +} CsvParserModel::~CsvParserModel() -{} +{ +} -void CsvParserModel::setFilename(const QString& filename) { +void CsvParserModel::setFilename(const QString& filename) +{ m_filename = filename; } -QString CsvParserModel::getFileInfo(){ +QString CsvParserModel::getFileInfo() +{ QString a(tr("%1, %2, %3", "file info: bytes, rows, columns") - .arg(tr("%n byte(s)", nullptr, getFileSize())) - .arg(tr("%n row(s)", nullptr, getCsvRows())) - .arg(tr("%n column(s)", nullptr, qMax(0, getCsvCols() - 1)))); + .arg(tr("%n byte(s)", nullptr, getFileSize())) + .arg(tr("%n row(s)", nullptr, getCsvRows())) + .arg(tr("%n column(s)", nullptr, qMax(0, getCsvCols() - 1)))); return a; } -bool CsvParserModel::parse() { +bool CsvParserModel::parse() +{ bool r; beginResetModel(); m_columnMap.clear(); @@ -49,13 +54,14 @@ bool CsvParserModel::parse() { r = CsvParser::parse(&csv); } for (int i = 0; i < columnCount(); ++i) - m_columnMap.insert(i,0); + m_columnMap.insert(i, 0); addEmptyColumn(); endResetModel(); return r; } -void CsvParserModel::addEmptyColumn() { +void CsvParserModel::addEmptyColumn() +{ for (int i = 0; i < m_table.size(); ++i) { CsvRow r = m_table.at(i); r.prepend(QString("")); @@ -63,65 +69,68 @@ void CsvParserModel::addEmptyColumn() { } } -void CsvParserModel::mapColumns(int csvColumn, int dbColumn) { +void CsvParserModel::mapColumns(int csvColumn, int dbColumn) +{ if ((csvColumn < 0) || (dbColumn < 0)) return; beginResetModel(); if (csvColumn >= getCsvCols()) - m_columnMap[dbColumn] = 0; //map to the empty column + m_columnMap[dbColumn] = 0; // map to the empty column else m_columnMap[dbColumn] = csvColumn; endResetModel(); } -void CsvParserModel::setSkippedRows(int skipped) { +void CsvParserModel::setSkippedRows(int skipped) +{ m_skipped = skipped; - QModelIndex topLeft = createIndex(skipped,0); - QModelIndex bottomRight = createIndex(m_skipped+rowCount(), columnCount()); + QModelIndex topLeft = createIndex(skipped, 0); + QModelIndex bottomRight = createIndex(m_skipped + rowCount(), columnCount()); emit dataChanged(topLeft, bottomRight); emit layoutChanged(); } -void CsvParserModel::setHeaderLabels(QStringList l) { +void CsvParserModel::setHeaderLabels(QStringList l) +{ m_columnHeader = l; } -int CsvParserModel::rowCount(const QModelIndex &parent) const { +int CsvParserModel::rowCount(const QModelIndex& parent) const +{ if (parent.isValid()) return 0; return getCsvRows(); } -int CsvParserModel::columnCount(const QModelIndex &parent) const { +int CsvParserModel::columnCount(const QModelIndex& parent) const +{ if (parent.isValid()) return 0; return m_columnHeader.size(); } -QVariant CsvParserModel::data(const QModelIndex &index, int role) const { - if ((index.column() >= m_columnHeader.size()) - || (index.row()+m_skipped >= rowCount()) - || !index.isValid()) { +QVariant CsvParserModel::data(const QModelIndex& index, int role) const +{ + if ((index.column() >= m_columnHeader.size()) || (index.row() + m_skipped >= rowCount()) || !index.isValid()) { return QVariant(); } if (role == Qt::DisplayRole) - return m_table.at(index.row()+m_skipped).at(m_columnMap[index.column()]); + return m_table.at(index.row() + m_skipped).at(m_columnMap[index.column()]); return QVariant(); } -QVariant CsvParserModel::headerData(int section, Qt::Orientation orientation, int role) const { +QVariant CsvParserModel::headerData(int section, Qt::Orientation orientation, int role) const +{ if (role == Qt::DisplayRole) { if (orientation == Qt::Horizontal) { if ((section < 0) || (section >= m_columnHeader.size())) return QVariant(); return m_columnHeader.at(section); } else if (orientation == Qt::Vertical) { - if (section+m_skipped >= rowCount()) + if (section + m_skipped >= rowCount()) return QVariant(); - return QString::number(section+1); + return QString::number(section + 1); } } return QVariant(); } - - diff --git a/src/gui/csvImport/CsvParserModel.h b/src/gui/csvImport/CsvParserModel.h index b092092ba..7a13b0d1b 100644 --- a/src/gui/csvImport/CsvParserModel.h +++ b/src/gui/csvImport/CsvParserModel.h @@ -30,7 +30,7 @@ class CsvParserModel : public QAbstractTableModel, public CsvParser Q_OBJECT public: - explicit CsvParserModel(QObject *parent = nullptr); + explicit CsvParserModel(QObject* parent = nullptr); ~CsvParserModel(); void setFilename(const QString& filename); QString getFileInfo(); @@ -39,9 +39,9 @@ public: void setHeaderLabels(QStringList l); void mapColumns(int csvColumn, int dbColumn); - int rowCount(const QModelIndex &parent = QModelIndex()) const override; - int columnCount(const QModelIndex &parent = QModelIndex()) const override; - QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const override; + int rowCount(const QModelIndex& parent = QModelIndex()) const override; + int columnCount(const QModelIndex& parent = QModelIndex()) const override; + QVariant data(const QModelIndex& index, int role = Qt::DisplayRole) const override; QVariant headerData(int section, Qt::Orientation orientation, int role) const override; public slots: @@ -51,11 +51,10 @@ private: int m_skipped; QString m_filename; QStringList m_columnHeader; - //first column of model must be empty (aka combobox row "Not present in CSV file") + // first column of model must be empty (aka combobox row "Not present in CSV file") void addEmptyColumn(); - //mapping CSV columns to keepassx columns + // mapping CSV columns to keepassx columns QMap m_columnMap; }; -#endif //KEEPASSX_CSVPARSERMODEL_H - +#endif // KEEPASSX_CSVPARSERMODEL_H diff --git a/src/gui/entry/AutoTypeAssociationsModel.cpp b/src/gui/entry/AutoTypeAssociationsModel.cpp index 442453de0..59d2c84ff 100644 --- a/src/gui/entry/AutoTypeAssociationsModel.cpp +++ b/src/gui/entry/AutoTypeAssociationsModel.cpp @@ -49,7 +49,7 @@ void AutoTypeAssociationsModel::setAutoTypeAssociations(AutoTypeAssociations* au endResetModel(); } -void AutoTypeAssociationsModel::setEntry(const Entry *entry) +void AutoTypeAssociationsModel::setEntry(const Entry* entry) { m_entry = entry; } @@ -58,8 +58,7 @@ int AutoTypeAssociationsModel::rowCount(const QModelIndex& parent) const { if (!m_autoTypeAssociations || parent.isValid()) { return 0; - } - else { + } else { return m_autoTypeAssociations->size(); } } @@ -76,12 +75,10 @@ QVariant AutoTypeAssociationsModel::headerData(int section, Qt::Orientation orie if ((orientation == Qt::Horizontal) && (role == Qt::DisplayRole)) { if (section == 0) { return tr("Window"); - } - else { + } else { return tr("Sequence"); } - } - else { + } else { return QVariant(); } } @@ -100,16 +97,14 @@ QVariant AutoTypeAssociationsModel::data(const QModelIndex& index, int role) con window = m_entry->resolveMultiplePlaceholders(window); } return window; - } - else { + } else { QString sequence = m_autoTypeAssociations->get(index.row()).sequence; if (sequence.isEmpty()) { sequence = tr("Default sequence"); } return sequence; } - } - else { + } else { return QVariant(); } } diff --git a/src/gui/entry/AutoTypeMatchModel.cpp b/src/gui/entry/AutoTypeMatchModel.cpp index 6a370dea5..1a6a6ba3b 100644 --- a/src/gui/entry/AutoTypeMatchModel.cpp +++ b/src/gui/entry/AutoTypeMatchModel.cpp @@ -163,12 +163,11 @@ void AutoTypeMatchModel::entryDataChanged(Entry* entry) for (int row = 0; row < m_matches.size(); ++row) { AutoTypeMatch match = m_matches[row]; if (match.entry == entry) { - emit dataChanged(index(row, 0), index(row, columnCount()-1)); + emit dataChanged(index(row, 0), index(row, columnCount() - 1)); } } } - void AutoTypeMatchModel::entryAboutToRemove(Entry* entry) { for (int row = 0; row < m_matches.size(); ++row) { diff --git a/src/gui/entry/AutoTypeMatchView.cpp b/src/gui/entry/AutoTypeMatchView.cpp index 67f38c79e..a0667b310 100644 --- a/src/gui/entry/AutoTypeMatchView.cpp +++ b/src/gui/entry/AutoTypeMatchView.cpp @@ -43,7 +43,8 @@ AutoTypeMatchView::AutoTypeMatchView(QWidget* parent) header()->setDefaultSectionSize(150); connect(this, SIGNAL(doubleClicked(QModelIndex)), SLOT(emitMatchActivated(QModelIndex))); - connect(selectionModel(), SIGNAL(selectionChanged(QItemSelection,QItemSelection)), SIGNAL(matchSelectionChanged())); + connect( + selectionModel(), SIGNAL(selectionChanged(QItemSelection, QItemSelection)), SIGNAL(matchSelectionChanged())); } void AutoTypeMatchView::keyPressEvent(QKeyEvent* event) diff --git a/src/gui/entry/EditEntryWidget.cpp b/src/gui/entry/EditEntryWidget.cpp index 8163a648c..eee4ec2ac 100644 --- a/src/gui/entry/EditEntryWidget.cpp +++ b/src/gui/entry/EditEntryWidget.cpp @@ -19,19 +19,19 @@ #include "EditEntryWidget.h" #include "ui_EditEntryWidgetAdvanced.h" #include "ui_EditEntryWidgetAutoType.h" -#include "ui_EditEntryWidgetSSHAgent.h" #include "ui_EditEntryWidgetHistory.h" #include "ui_EditEntryWidgetMain.h" +#include "ui_EditEntryWidgetSSHAgent.h" +#include #include +#include +#include +#include +#include #include #include -#include -#include #include -#include -#include -#include #include "autotype/AutoType.h" #include "core/Config.h" @@ -46,12 +46,12 @@ #include "sshagent/OpenSSHKey.h" #include "sshagent/SSHAgent.h" #endif +#include "gui/Clipboard.h" #include "gui/EditWidgetIcons.h" #include "gui/EditWidgetProperties.h" #include "gui/FileDialog.h" -#include "gui/MessageBox.h" -#include "gui/Clipboard.h" #include "gui/Font.h" +#include "gui/MessageBox.h" #include "gui/entry/AutoTypeAssociationsModel.h" #include "gui/entry/EntryAttachmentsModel.h" #include "gui/entry/EntryAttributesModel.h" @@ -100,9 +100,11 @@ EditEntryWidget::EditEntryWidget(QWidget* parent) connect(this, SIGNAL(accepted()), SLOT(acceptEntry())); connect(this, SIGNAL(rejected()), SLOT(cancel())); connect(this, SIGNAL(apply()), SLOT(commitEntry())); - connect(m_iconsWidget, SIGNAL(messageEditEntry(QString, MessageWidget::MessageType)), SLOT(showMessage(QString, MessageWidget::MessageType))); + connect(m_iconsWidget, + SIGNAL(messageEditEntry(QString, MessageWidget::MessageType)), + SLOT(showMessage(QString, MessageWidget::MessageType))); connect(m_iconsWidget, SIGNAL(messageEditEntryDismiss()), SLOT(hideMessage())); - + m_mainUi->passwordGenerator->layout()->setContentsMargins(0, 0, 0, 0); } @@ -127,7 +129,7 @@ void EditEntryWidget::setupMain() m_mainUi->expirePresets->setMenu(createPresetsMenu()); connect(m_mainUi->expirePresets->menu(), SIGNAL(triggered(QAction*)), this, SLOT(useExpiryPreset(QAction*))); - QAction *action = new QAction(this); + QAction* action = new QAction(this); action->setShortcut(Qt::CTRL | Qt::Key_Return); connect(action, SIGNAL(triggered()), this, SLOT(commitEntry())); this->addAction(action); @@ -144,9 +146,10 @@ void EditEntryWidget::setupAdvanced() m_advancedUi->attachmentsWidget->setReadOnly(false); m_advancedUi->attachmentsWidget->setButtonsVisible(true); - connect(m_advancedUi->attachmentsWidget, &EntryAttachmentsWidget::errorOccurred, this, [this](const QString &error) { - showMessage(error, MessageWidget::Error); - }); + connect(m_advancedUi->attachmentsWidget, + &EntryAttachmentsWidget::errorOccurred, + this, + [this](const QString& error) { showMessage(error, MessageWidget::Error); }); m_attributesModel->setEntryAttributes(m_entryAttributes); m_advancedUi->attributesView->setModel(m_attributesModel); @@ -156,7 +159,7 @@ void EditEntryWidget::setupAdvanced() connect(m_advancedUi->protectAttributeButton, SIGNAL(toggled(bool)), SLOT(protectCurrentAttribute(bool))); connect(m_advancedUi->revealAttributeButton, SIGNAL(clicked(bool)), SLOT(revealCurrentAttribute())); connect(m_advancedUi->attributesView->selectionModel(), - SIGNAL(currentChanged(QModelIndex,QModelIndex)), + SIGNAL(currentChanged(QModelIndex, QModelIndex)), SLOT(updateCurrentAttribute())); connect(m_advancedUi->fgColorButton, SIGNAL(clicked()), SLOT(pickColor())); connect(m_advancedUi->bgColorButton, SIGNAL(clicked()), SLOT(pickColor())); @@ -178,24 +181,25 @@ void EditEntryWidget::setupAutoType() m_autoTypeUi->assocView->setModel(m_autoTypeAssocModel); m_autoTypeUi->assocView->setColumnHidden(1, true); connect(m_autoTypeUi->enableButton, SIGNAL(toggled(bool)), SLOT(updateAutoTypeEnabled())); - connect(m_autoTypeUi->customSequenceButton, SIGNAL(toggled(bool)), - m_autoTypeUi->sequenceEdit, SLOT(setEnabled(bool))); - connect(m_autoTypeUi->customWindowSequenceButton, SIGNAL(toggled(bool)), - m_autoTypeUi->windowSequenceEdit, SLOT(setEnabled(bool))); + connect( + m_autoTypeUi->customSequenceButton, SIGNAL(toggled(bool)), m_autoTypeUi->sequenceEdit, SLOT(setEnabled(bool))); + connect(m_autoTypeUi->customWindowSequenceButton, + SIGNAL(toggled(bool)), + m_autoTypeUi->windowSequenceEdit, + SLOT(setEnabled(bool))); connect(m_autoTypeUi->assocAddButton, SIGNAL(clicked()), SLOT(insertAutoTypeAssoc())); connect(m_autoTypeUi->assocRemoveButton, SIGNAL(clicked()), SLOT(removeAutoTypeAssoc())); - connect(m_autoTypeUi->assocView->selectionModel(), SIGNAL(currentRowChanged(QModelIndex,QModelIndex)), + connect(m_autoTypeUi->assocView->selectionModel(), + SIGNAL(currentRowChanged(QModelIndex, QModelIndex)), SLOT(updateAutoTypeEnabled())); connect(m_autoTypeAssocModel, SIGNAL(modelReset()), SLOT(updateAutoTypeEnabled())); - connect(m_autoTypeUi->assocView->selectionModel(), SIGNAL(currentRowChanged(QModelIndex,QModelIndex)), + connect(m_autoTypeUi->assocView->selectionModel(), + SIGNAL(currentRowChanged(QModelIndex, QModelIndex)), SLOT(loadCurrentAssoc(QModelIndex))); connect(m_autoTypeAssocModel, SIGNAL(modelReset()), SLOT(clearCurrentAssoc())); - connect(m_autoTypeUi->windowTitleCombo, SIGNAL(editTextChanged(QString)), - SLOT(applyCurrentAssoc())); - connect(m_autoTypeUi->customWindowSequenceButton, SIGNAL(toggled(bool)), - SLOT(applyCurrentAssoc())); - connect(m_autoTypeUi->windowSequenceEdit, SIGNAL(textChanged(QString)), - SLOT(applyCurrentAssoc())); + connect(m_autoTypeUi->windowTitleCombo, SIGNAL(editTextChanged(QString)), SLOT(applyCurrentAssoc())); + connect(m_autoTypeUi->customWindowSequenceButton, SIGNAL(toggled(bool)), SLOT(applyCurrentAssoc())); + connect(m_autoTypeUi->windowSequenceEdit, SIGNAL(textChanged(QString)), SLOT(applyCurrentAssoc())); } void EditEntryWidget::setupProperties() @@ -217,11 +221,10 @@ void EditEntryWidget::setupHistory() m_historyUi->historyView->setModel(m_sortModel); m_historyUi->historyView->setRootIsDecorated(false); - connect(m_historyUi->historyView, SIGNAL(activated(QModelIndex)), - SLOT(histEntryActivated(QModelIndex))); + connect(m_historyUi->historyView, SIGNAL(activated(QModelIndex)), SLOT(histEntryActivated(QModelIndex))); connect(m_historyUi->historyView->selectionModel(), - SIGNAL(currentChanged(QModelIndex,QModelIndex)), - SLOT(updateHistoryButtons(QModelIndex,QModelIndex))); + SIGNAL(currentChanged(QModelIndex, QModelIndex)), + SLOT(updateHistoryButtons(QModelIndex, QModelIndex))); connect(m_historyUi->showButton, SIGNAL(clicked()), SLOT(showHistoryEntry())); connect(m_historyUi->restoreButton, SIGNAL(clicked()), SLOT(restoreHistoryEntry())); connect(m_historyUi->deleteButton, SIGNAL(clicked()), SLOT(deleteHistoryEntry())); @@ -261,7 +264,7 @@ void EditEntryWidget::setupEntryUpdate() connect(m_autoTypeUi->windowTitleCombo, SIGNAL(currentIndexChanged(int)), this, SLOT(setUnsavedChanges())); connect(m_autoTypeUi->windowTitleCombo, SIGNAL(editTextChanged(const QString&)), this, SLOT(setUnsavedChanges())); - // Properties and History tabs don't need extra connections +// Properties and History tabs don't need extra connections #ifdef WITH_XC_SSHAGENT // SSH Agent tab @@ -269,12 +272,14 @@ void EditEntryWidget::setupEntryUpdate() connect(m_sshAgentUi->attachmentRadioButton, SIGNAL(toggled(bool)), this, SLOT(setUnsavedChanges())); connect(m_sshAgentUi->externalFileRadioButton, SIGNAL(toggled(bool)), this, SLOT(setUnsavedChanges())); connect(m_sshAgentUi->attachmentComboBox, SIGNAL(currentIndexChanged(int)), this, SLOT(setUnsavedChanges())); - connect(m_sshAgentUi->attachmentComboBox, SIGNAL(editTextChanged(const QString&)), this, SLOT(setUnsavedChanges())); + connect( + m_sshAgentUi->attachmentComboBox, SIGNAL(editTextChanged(const QString&)), this, SLOT(setUnsavedChanges())); connect(m_sshAgentUi->externalFileEdit, SIGNAL(textChanged(const QString&)), this, SLOT(setUnsavedChanges())); connect(m_sshAgentUi->publicKeyEdit, SIGNAL(textChanged()), this, SLOT(setUnsavedChanges())); connect(m_sshAgentUi->addKeyToAgentCheckBox, SIGNAL(stateChanged(int)), this, SLOT(setUnsavedChanges())); connect(m_sshAgentUi->removeKeyFromAgentCheckBox, SIGNAL(stateChanged(int)), this, SLOT(setUnsavedChanges())); - connect(m_sshAgentUi->requireUserConfirmationCheckBox, SIGNAL(stateChanged(int)), this, SLOT(setUnsavedChanges())); + connect( + m_sshAgentUi->requireUserConfirmationCheckBox, SIGNAL(stateChanged(int)), this, SLOT(setUnsavedChanges())); connect(m_sshAgentUi->lifetimeCheckBox, SIGNAL(stateChanged(int)), this, SLOT(setUnsavedChanges())); connect(m_sshAgentUi->lifetimeSpinBox, SIGNAL(valueChanged(int)), this, SLOT(setUnsavedChanges())); } @@ -307,8 +312,7 @@ void EditEntryWidget::updateHistoryButtons(const QModelIndex& current, const QMo m_historyUi->showButton->setEnabled(true); m_historyUi->restoreButton->setEnabled(true); m_historyUi->deleteButton->setEnabled(true); - } - else { + } else { m_historyUi->showButton->setEnabled(false); m_historyUi->restoreButton->setEnabled(false); m_historyUi->deleteButton->setEnabled(false); @@ -622,14 +626,12 @@ QString EditEntryWidget::entryTitle() const { if (m_entry) { return m_entry->title(); - } - else { + } else { return QString(); } } -void EditEntryWidget::loadEntry(Entry* entry, bool create, bool history, const QString& parentName, - Database* database) +void EditEntryWidget::loadEntry(Entry* entry, bool create, bool history, const QString& parentName, Database* database) { m_entry = entry; m_database = database; @@ -638,14 +640,11 @@ void EditEntryWidget::loadEntry(Entry* entry, bool create, bool history, const Q if (history) { setHeadline(QString("%1 > %2").arg(parentName, tr("Entry history"))); - } - else { + } else { if (create) { setHeadline(QString("%1 > %2").arg(parentName, tr("Add entry"))); - } - else { - setHeadline(QString("%1 > %2 > %3").arg(parentName, - entry->title(), tr("Edit entry"))); + } else { + setHeadline(QString("%1 > %2 > %3").arg(parentName, entry->title(), tr("Edit entry"))); } } @@ -684,8 +683,7 @@ void EditEntryWidget::setForms(const Entry* entry, bool restore) QAbstractItemView::EditTriggers editTriggers; if (m_history) { editTriggers = QAbstractItemView::NoEditTriggers; - } - else { + } else { editTriggers = QAbstractItemView::DoubleClicked; } m_advancedUi->attributesView->setEditTriggers(editTriggers); @@ -714,8 +712,7 @@ void EditEntryWidget::setForms(const Entry* entry, bool restore) if (m_attributesModel->rowCount() != 0) { m_advancedUi->attributesView->setCurrentIndex(m_attributesModel->index(0, 0)); - } - else { + } else { m_advancedUi->attributesEdit->setPlainText(""); m_advancedUi->attributesEdit->setEnabled(false); } @@ -734,8 +731,7 @@ void EditEntryWidget::setForms(const Entry* entry, bool restore) m_autoTypeUi->enableButton->setChecked(entry->autoTypeEnabled()); if (entry->defaultAutoTypeSequence().isEmpty()) { m_autoTypeUi->inheritSequenceButton->setChecked(true); - } - else { + } else { m_autoTypeUi->customSequenceButton->setChecked(true); } m_autoTypeUi->sequenceEdit->setText(entry->effectiveAutoTypeSequence()); @@ -767,8 +763,7 @@ void EditEntryWidget::setForms(const Entry* entry, bool restore) } if (m_historyModel->rowCount() > 0) { m_historyUi->deleteAllButton->setEnabled(true); - } - else { + } else { m_historyUi->deleteAllButton->setEnabled(false); } @@ -797,11 +792,13 @@ bool EditEntryWidget::commitEntry() } // Ask the user to apply the generator password, if open - if (m_mainUi->togglePasswordGeneratorButton->isChecked() && - m_mainUi->passwordGenerator->getGeneratedPassword() != m_mainUi->passwordEdit->text()) { - auto answer = MessageBox::question(this, tr("Apply generated password?"), - tr("Do you want to apply the generated password to this entry?"), - QMessageBox::Yes | QMessageBox::No, QMessageBox::Yes); + if (m_mainUi->togglePasswordGeneratorButton->isChecked() + && m_mainUi->passwordGenerator->getGeneratedPassword() != m_mainUi->passwordEdit->text()) { + auto answer = MessageBox::question(this, + tr("Apply generated password?"), + tr("Do you want to apply the generated password to this entry?"), + QMessageBox::Yes | QMessageBox::No, + QMessageBox::Yes); if (answer == QMessageBox::Yes) { m_mainUi->passwordGenerator->applyPassword(); } @@ -812,8 +809,7 @@ bool EditEntryWidget::commitEntry() if (m_advancedUi->attributesView->currentIndex().isValid() && m_advancedUi->attributesEdit->isEnabled()) { QString key = m_attributesModel->keyByIndex(m_advancedUi->attributesView->currentIndex()); - m_entryAttributes->set(key, m_advancedUi->attributesEdit->toPlainText(), - m_entryAttributes->isProtected(key)); + m_entryAttributes->set(key, m_advancedUi->attributesEdit->toPlainText(), m_entryAttributes->isProtected(key)); } m_currentAttribute = QPersistentModelIndex(); @@ -879,15 +875,13 @@ void EditEntryWidget::updateEntryData(Entry* entry) const entry->setNotes(m_mainUi->notesEdit->toPlainText()); - if (m_advancedUi->fgColorCheckBox->isChecked() && - m_advancedUi->fgColorButton->property("color").isValid()) { + if (m_advancedUi->fgColorCheckBox->isChecked() && m_advancedUi->fgColorButton->property("color").isValid()) { entry->setForegroundColor(QColor(m_advancedUi->fgColorButton->property("color").toString())); } else { entry->setForegroundColor(QColor()); } - if (m_advancedUi->bgColorCheckBox->isChecked() && - m_advancedUi->bgColorButton->property("color").isValid()) { + if (m_advancedUi->bgColorCheckBox->isChecked() && m_advancedUi->bgColorButton->property("color").isValid()) { entry->setBackgroundColor(QColor(m_advancedUi->bgColorButton->property("color").toString())); } else { entry->setBackgroundColor(QColor()); @@ -922,13 +916,14 @@ void EditEntryWidget::cancel() return; } - if (!m_entry->iconUuid().isNull() && - !m_database->metadata()->containsCustomIcon(m_entry->iconUuid())) { + if (!m_entry->iconUuid().isNull() && !m_database->metadata()->containsCustomIcon(m_entry->iconUuid())) { m_entry->setIcon(Entry::DefaultIconNumber); } if (!m_saved) { - auto result = MessageBox::question(this, QString(), tr("Entry has unsaved changes"), + auto result = MessageBox::question(this, + QString(), + tr("Entry has unsaved changes"), QMessageBox::Cancel | QMessageBox::Save | QMessageBox::Discard, QMessageBox::Cancel); if (result == QMessageBox::Cancel) { @@ -1032,8 +1027,11 @@ void EditEntryWidget::removeCurrentAttribute() QModelIndex index = m_advancedUi->attributesView->currentIndex(); if (index.isValid()) { - if (MessageBox::question(this, tr("Confirm Remove"), tr("Are you sure you want to remove this attribute?"), - QMessageBox::Yes | QMessageBox::No) == QMessageBox::Yes) { + if (MessageBox::question(this, + tr("Confirm Remove"), + tr("Are you sure you want to remove this attribute?"), + QMessageBox::Yes | QMessageBox::No) + == QMessageBox::Yes) { m_entryAttributes->remove(m_attributesModel->keyByIndex(index)); setUnsavedChanges(true); } @@ -1049,9 +1047,9 @@ void EditEntryWidget::updateCurrentAttribute() // Save changes to the currently selected attribute if editing is enabled if (m_currentAttribute.isValid() && m_advancedUi->attributesEdit->isEnabled()) { QString currKey = m_attributesModel->keyByIndex(m_currentAttribute); - m_entryAttributes->set(currKey, m_advancedUi->attributesEdit->toPlainText(), - m_entryAttributes->isProtected(currKey)); - } + m_entryAttributes->set( + currKey, m_advancedUi->attributesEdit->toPlainText(), m_entryAttributes->isProtected(currKey)); + } } displayAttribute(newIndex, m_entryAttributes->isProtected(newKey)); @@ -1071,8 +1069,7 @@ void EditEntryWidget::displayAttribute(QModelIndex index, bool showProtected) m_advancedUi->attributesEdit->setEnabled(false); m_advancedUi->revealAttributeButton->setEnabled(true); m_advancedUi->protectAttributeButton->setChecked(true); - } - else { + } else { m_advancedUi->attributesEdit->setPlainText(m_entryAttributes->value(key)); m_advancedUi->attributesEdit->setEnabled(true); m_advancedUi->revealAttributeButton->setEnabled(false); @@ -1083,8 +1080,7 @@ void EditEntryWidget::displayAttribute(QModelIndex index, bool showProtected) m_advancedUi->protectAttributeButton->setEnabled(!m_history); m_advancedUi->editAttributeButton->setEnabled(!m_history); m_advancedUi->removeAttributeButton->setEnabled(!m_history); - } - else { + } else { m_advancedUi->attributesEdit->setPlainText(""); m_advancedUi->attributesEdit->setEnabled(false); m_advancedUi->revealAttributeButton->setEnabled(false); @@ -1117,7 +1113,7 @@ void EditEntryWidget::protectCurrentAttribute(bool state) void EditEntryWidget::revealCurrentAttribute() { - if (! m_advancedUi->attributesEdit->isEnabled()) { + if (!m_advancedUi->attributesEdit->isEnabled()) { QModelIndex index = m_advancedUi->attributesView->currentIndex(); if (index.isValid()) { bool oldBlockSignals = m_advancedUi->attributesEdit->blockSignals(true); @@ -1253,8 +1249,7 @@ void EditEntryWidget::deleteAllHistoryEntries() m_historyModel->deleteAll(); if (m_historyModel->rowCount() > 0) { m_historyUi->deleteAllButton->setEnabled(true); - } - else { + } else { m_historyUi->deleteAllButton->setEnabled(false); } setUnsavedChanges(true); diff --git a/src/gui/entry/EditEntryWidget.h b/src/gui/entry/EditEntryWidget.h index 863d6505b..814d2cc7d 100644 --- a/src/gui/entry/EditEntryWidget.h +++ b/src/gui/entry/EditEntryWidget.h @@ -22,8 +22,8 @@ #include #include -#include "gui/EditWidget.h" #include "config-keepassx.h" +#include "gui/EditWidget.h" class AutoTypeAssociations; class AutoTypeAssociationsModel; @@ -43,7 +43,8 @@ class QStackedLayout; class OpenSSHKey; #endif -namespace Ui { +namespace Ui +{ class EditEntryWidgetAdvanced; class EditEntryWidgetAutoType; class EditEntryWidgetSSHAgent; @@ -60,8 +61,7 @@ public: explicit EditEntryWidget(QWidget* parent = nullptr); ~EditEntryWidget(); - void loadEntry(Entry* entry, bool create, bool history, const QString& parentName, - Database* database); + void loadEntry(Entry* entry, bool create, bool history, const QString& parentName, Database* database); void createPresetsMenu(QMenu* expirePresetsMenu); QString entryTitle() const; diff --git a/src/gui/entry/EditEntryWidget_p.h b/src/gui/entry/EditEntryWidget_p.h index 0e37c1fe8..0ba01cd51 100644 --- a/src/gui/entry/EditEntryWidget_p.h +++ b/src/gui/entry/EditEntryWidget_p.h @@ -24,7 +24,8 @@ class AttributesListView : public QListView { public: - explicit AttributesListView(QWidget* parent = 0) : QListView(parent) + explicit AttributesListView(QWidget* parent = 0) + : QListView(parent) { setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Expanding); } diff --git a/src/gui/entry/EntryAttachmentsModel.cpp b/src/gui/entry/EntryAttachmentsModel.cpp index 608744841..8f04a2629 100644 --- a/src/gui/entry/EntryAttachmentsModel.cpp +++ b/src/gui/entry/EntryAttachmentsModel.cpp @@ -26,8 +26,7 @@ EntryAttachmentsModel::EntryAttachmentsModel(QObject* parent) : QAbstractListModel(parent) , m_entryAttachments(nullptr) { - m_headers << tr("Name") - << tr("Size"); + m_headers << tr("Name") << tr("Size"); } void EntryAttachmentsModel::setEntryAttachments(EntryAttachments* entryAttachments) @@ -57,8 +56,7 @@ int EntryAttachmentsModel::rowCount(const QModelIndex& parent) const { if (!m_entryAttachments || parent.isValid()) { return 0; - } - else { + } else { return m_entryAttachments->keys().size(); } } @@ -115,7 +113,7 @@ QString EntryAttachmentsModel::keyByIndex(const QModelIndex& index) const void EntryAttachmentsModel::attachmentChange(const QString& key) { int row = m_entryAttachments->keys().indexOf(key); - emit dataChanged(index(row, 0), index(row, columnCount()-1)); + emit dataChanged(index(row, 0), index(row, columnCount() - 1)); } void EntryAttachmentsModel::attachmentAboutToAdd(const QString& key) diff --git a/src/gui/entry/EntryAttachmentsModel.h b/src/gui/entry/EntryAttachmentsModel.h index fa8d35548..18a02c7c6 100644 --- a/src/gui/entry/EntryAttachmentsModel.h +++ b/src/gui/entry/EntryAttachmentsModel.h @@ -27,7 +27,8 @@ class EntryAttachmentsModel : public QAbstractListModel Q_OBJECT public: - enum Columns { + enum Columns + { NameColumn, SizeColumn, ColumnsCount diff --git a/src/gui/entry/EntryAttachmentsWidget.cpp b/src/gui/entry/EntryAttachmentsWidget.cpp index d420d9d65..c1897d898 100644 --- a/src/gui/entry/EntryAttachmentsWidget.cpp +++ b/src/gui/entry/EntryAttachmentsWidget.cpp @@ -16,9 +16,8 @@ #include "gui/FileDialog.h" #include "gui/MessageBox.h" - -EntryAttachmentsWidget::EntryAttachmentsWidget(QWidget* parent) : - QWidget(parent) +EntryAttachmentsWidget::EntryAttachmentsWidget(QWidget* parent) + : QWidget(parent) , m_ui(new Ui::EntryAttachmentsWidget) , m_entryAttachments(new EntryAttachments(this)) , m_attachmentsModel(new EntryAttachmentsModel(this)) @@ -44,7 +43,8 @@ EntryAttachmentsWidget::EntryAttachmentsWidget(QWidget* parent) : connect(this, SIGNAL(readOnlyChanged(bool)), SLOT(updateButtonsEnabled())); connect(m_attachmentsModel, SIGNAL(modelReset()), SLOT(updateButtonsEnabled())); - connect(m_ui->attachmentsView->selectionModel(), SIGNAL(selectionChanged(QItemSelection,QItemSelection)), + connect(m_ui->attachmentsView->selectionModel(), + SIGNAL(selectionChanged(QItemSelection, QItemSelection)), SLOT(updateButtonsEnabled())); connect(m_ui->attachmentsView, SIGNAL(doubleClicked(QModelIndex)), SLOT(openAttachment(QModelIndex))); @@ -163,11 +163,11 @@ void EntryAttachmentsWidget::removeSelectedAttachments() } const QString question = tr("Are you sure you want to remove %n attachment(s)?", "", indexes.count()); - QMessageBox::StandardButton answer = MessageBox::question(this, tr("Confirm remove"), - question, QMessageBox::Yes | QMessageBox::No); + QMessageBox::StandardButton answer = + MessageBox::question(this, tr("Confirm remove"), question, QMessageBox::Yes | QMessageBox::No); if (answer == QMessageBox::Yes) { QStringList keys; - for (const QModelIndex& index: indexes) { + for (const QModelIndex& index : indexes) { keys.append(m_attachmentsModel->keyByIndex(index)); } m_entryAttachments->remove(keys); @@ -183,7 +183,7 @@ void EntryAttachmentsWidget::saveSelectedAttachments() } QString defaultDirPath = config()->get("LastAttachmentDir").toString(); - const bool dirExists = !defaultDirPath.isEmpty() && QDir(defaultDirPath).exists(); + const bool dirExists = !defaultDirPath.isEmpty() && QDir(defaultDirPath).exists(); if (!dirExists) { defaultDirPath = QStandardPaths::writableLocation(QStandardPaths::DocumentsLocation); } @@ -203,13 +203,16 @@ void EntryAttachmentsWidget::saveSelectedAttachments() config()->set("LastAttachmentDir", QFileInfo(saveDir.absolutePath()).absolutePath()); QStringList errors; - for (const QModelIndex& index: indexes) { + for (const QModelIndex& index : indexes) { const QString filename = m_attachmentsModel->keyByIndex(index); const QString attachmentPath = saveDir.absoluteFilePath(filename); if (QFileInfo::exists(attachmentPath)) { - const QString question(tr("Are you sure you want to overwrite the existing file \"%1\" with the attachment?")); - auto answer = MessageBox::question(this, tr("Confirm overwrite"), question.arg(filename), + const QString question( + tr("Are you sure you want to overwrite the existing file \"%1\" with the attachment?")); + auto answer = MessageBox::question(this, + tr("Confirm overwrite"), + question.arg(filename), QMessageBox::Yes | QMessageBox::No | QMessageBox::Cancel); if (answer == QMessageBox::No) { continue; @@ -252,7 +255,7 @@ void EntryAttachmentsWidget::openSelectedAttachments() } QStringList errors; - for (const QModelIndex& index: indexes) { + for (const QModelIndex& index : indexes) { QString errorMessage; if (!openAttachment(index, errorMessage)) { const QString filename = m_attachmentsModel->keyByIndex(index); @@ -284,7 +287,7 @@ bool EntryAttachmentsWidget::insertAttachments(const QStringList& filenames, QSt } QStringList errors; - for (const QString &filename: filenames) { + for (const QString& filename : filenames) { QByteArray data; QFile file(filename); const QFileInfo fInfo(filename); @@ -313,9 +316,7 @@ bool EntryAttachmentsWidget::openAttachment(const QModelIndex& index, QString& e QScopedPointer tmpFile(new QTemporaryFile(tmpFileTemplate, this)); - const bool saveOk = tmpFile->open() - && tmpFile->write(attachmentData) == attachmentData.size() - && tmpFile->flush(); + const bool saveOk = tmpFile->open() && tmpFile->write(attachmentData) == attachmentData.size() && tmpFile->flush(); if (!saveOk) { errorMessage = QString("%1 - %2").arg(filename, tmpFile->errorString()); return false; @@ -351,7 +352,7 @@ bool EntryAttachmentsWidget::eventFilter(QObject* watched, QEvent* e) dropEv->acceptProposedAction(); QStringList filenames; const QList urls = mimeData->urls(); - for (const QUrl& url: urls) { + for (const QUrl& url : urls) { const QFileInfo fInfo(url.toLocalFile()); if (fInfo.isFile()) { filenames.append(fInfo.absoluteFilePath()); diff --git a/src/gui/entry/EntryAttachmentsWidget.h b/src/gui/entry/EntryAttachmentsWidget.h index 590060ae1..8859536dd 100644 --- a/src/gui/entry/EntryAttachmentsWidget.h +++ b/src/gui/entry/EntryAttachmentsWidget.h @@ -4,8 +4,9 @@ #include #include -namespace Ui { -class EntryAttachmentsWidget; +namespace Ui +{ + class EntryAttachmentsWidget; } class QByteArray; diff --git a/src/gui/entry/EntryAttributesModel.cpp b/src/gui/entry/EntryAttributesModel.cpp index 1b1eab220..ddb31d624 100644 --- a/src/gui/entry/EntryAttributesModel.cpp +++ b/src/gui/entry/EntryAttributesModel.cpp @@ -46,9 +46,9 @@ void EntryAttributesModel::setEntryAttributes(EntryAttributes* entryAttributes) connect(m_entryAttributes, SIGNAL(added(QString)), SLOT(attributeAdd())); connect(m_entryAttributes, SIGNAL(aboutToBeRemoved(QString)), SLOT(attributeAboutToRemove(QString))); connect(m_entryAttributes, SIGNAL(removed(QString)), SLOT(attributeRemove())); - connect(m_entryAttributes, SIGNAL(aboutToRename(QString,QString)), - SLOT(attributeAboutToRename(QString,QString))); - connect(m_entryAttributes, SIGNAL(renamed(QString,QString)), SLOT(attributeRename(QString,QString))); + connect( + m_entryAttributes, SIGNAL(aboutToRename(QString, QString)), SLOT(attributeAboutToRename(QString, QString))); + connect(m_entryAttributes, SIGNAL(renamed(QString, QString)), SLOT(attributeRename(QString, QString))); connect(m_entryAttributes, SIGNAL(aboutToBeReset()), SLOT(aboutToReset())); connect(m_entryAttributes, SIGNAL(reset()), SLOT(reset())); } @@ -60,8 +60,7 @@ int EntryAttributesModel::rowCount(const QModelIndex& parent) const { if (!m_entryAttributes || parent.isValid()) { return 0; - } - else { + } else { return m_attributes.size(); } } @@ -77,8 +76,7 @@ QVariant EntryAttributesModel::headerData(int section, Qt::Orientation orientati { if ((orientation == Qt::Horizontal) && (role == Qt::DisplayRole) && (section == 0)) { return tr("Name"); - } - else { + } else { return QVariant(); } } @@ -94,16 +92,14 @@ QVariant EntryAttributesModel::data(const QModelIndex& index, int role) const bool EntryAttributesModel::setData(const QModelIndex& index, const QVariant& value, int role) { - if (!index.isValid() || role != Qt::EditRole || value.type() != QVariant::String - || value.toString().isEmpty()) { + if (!index.isValid() || role != Qt::EditRole || value.type() != QVariant::String || value.toString().isEmpty()) { return false; } QString oldKey = m_attributes.at(index.row()); QString newKey = value.toString(); - if (EntryAttributes::isDefaultAttribute(newKey) - || m_entryAttributes->keys().contains(newKey)) { + if (EntryAttributes::isDefaultAttribute(newKey) || m_entryAttributes->keys().contains(newKey)) { return false; } m_entryAttributes->rename(oldKey, newKey); @@ -115,8 +111,7 @@ Qt::ItemFlags EntryAttributesModel::flags(const QModelIndex& index) const { if (!index.isValid()) { return Qt::NoItemFlags; - } - else { + } else { return QAbstractItemModel::flags(index) | Qt::ItemIsEditable; } } @@ -127,8 +122,7 @@ QModelIndex EntryAttributesModel::indexByKey(const QString& key) const if (row == -1) { return QModelIndex(); - } - else { + } else { return index(row, 0); } } @@ -137,8 +131,7 @@ QString EntryAttributesModel::keyByIndex(const QModelIndex& index) const { if (!index.isValid()) { return QString(); - } - else { + } else { return m_attributes.at(index.row()); } } @@ -147,7 +140,7 @@ void EntryAttributesModel::attributeChange(const QString& key) { int row = m_attributes.indexOf(key); Q_ASSERT(row != -1); - emit dataChanged(index(row, 0), index(row, columnCount()-1)); + emit dataChanged(index(row, 0), index(row, columnCount() - 1)); } void EntryAttributesModel::attributeAboutToAdd(const QString& key) @@ -194,8 +187,7 @@ void EntryAttributesModel::attributeAboutToRename(const QString& oldKey, const Q bool result = beginMoveRows(QModelIndex(), oldRow, oldRow, QModelIndex(), newRow); Q_UNUSED(result); Q_ASSERT(result); - } - else { + } else { m_nextRenameDataChange = true; } } @@ -208,8 +200,7 @@ void EntryAttributesModel::attributeRename(const QString& oldKey, const QString& if (!m_nextRenameDataChange) { endMoveRows(); - } - else { + } else { m_nextRenameDataChange = false; QModelIndex keyIndex = index(m_attributes.indexOf(newKey), 0); diff --git a/src/gui/entry/EntryHistoryModel.cpp b/src/gui/entry/EntryHistoryModel.cpp index 21f0aec43..aaec3de62 100644 --- a/src/gui/entry/EntryHistoryModel.cpp +++ b/src/gui/entry/EntryHistoryModel.cpp @@ -41,8 +41,7 @@ int EntryHistoryModel::rowCount(const QModelIndex& parent) const { if (!parent.isValid()) { return m_historyEntries.count(); - } - else { + } else { return 0; } } @@ -61,8 +60,7 @@ QVariant EntryHistoryModel::data(const QModelIndex& index, int role) const case 0: if (role == Qt::DisplayRole) { return lastModificationLocalTime.toString(Qt::SystemLocaleShortDate); - } - else { + } else { return lastModificationLocalTime; } case 1: diff --git a/src/gui/entry/EntryModel.cpp b/src/gui/entry/EntryModel.cpp index 6f7ebf6af..927095903 100644 --- a/src/gui/entry/EntryModel.cpp +++ b/src/gui/entry/EntryModel.cpp @@ -17,12 +17,12 @@ #include "EntryModel.h" +#include #include #include #include -#include -#include #include +#include #include "core/DatabaseIcons.h" #include "core/Entry.h" @@ -192,7 +192,9 @@ QVariant EntryModel::data(const QModelIndex& index, int role) const return result; case Expires: // Display either date of expiry or 'Never' - result = entry->timeInfo().expires() ? entry->timeInfo().expiryTime().toLocalTime().toString(EntryModel::DateFormat) : tr("Never"); + result = entry->timeInfo().expires() + ? entry->timeInfo().expiryTime().toLocalTime().toString(EntryModel::DateFormat) + : tr("Never"); return result; case Created: result = entry->timeInfo().creationTime().toLocalTime().toString(EntryModel::DateFormat); @@ -426,7 +428,7 @@ void EntryModel::entryRemoved() void EntryModel::entryDataChanged(Entry* entry) { int row = m_entries.indexOf(entry); - emit dataChanged(index(row, 0), index(row, columnCount()-1)); + emit dataChanged(index(row, 0), index(row, columnCount() - 1)); } void EntryModel::severConnections() diff --git a/src/gui/entry/EntryView.cpp b/src/gui/entry/EntryView.cpp index 19978a808..8c573e9ea 100644 --- a/src/gui/entry/EntryView.cpp +++ b/src/gui/entry/EntryView.cpp @@ -50,7 +50,8 @@ EntryView::EntryView(QWidget* parent) setDefaultDropAction(Qt::MoveAction); connect(this, SIGNAL(doubleClicked(QModelIndex)), SLOT(emitEntryActivated(QModelIndex))); - connect(selectionModel(), SIGNAL(selectionChanged(QItemSelection,QItemSelection)), SIGNAL(entrySelectionChanged())); + connect( + selectionModel(), SIGNAL(selectionChanged(QItemSelection, QItemSelection)), SIGNAL(entrySelectionChanged())); connect(m_model, SIGNAL(switchedToListMode()), SLOT(switchToListMode())); connect(m_model, SIGNAL(switchedToSearchMode()), SLOT(switchToSearchMode())); connect(m_model, SIGNAL(usernamesHiddenChanged()), SIGNAL(viewStateChanged())); @@ -330,7 +331,7 @@ void EntryView::showHeaderMenu(const QPoint& position) /** * Toggle visibility of column referenced by triggering action */ -void EntryView::toggleColumnVisibility(QAction *action) +void EntryView::toggleColumnVisibility(QAction* action) { // Verify action carries a column index as data. Since QVariant.toInt() // below will accept anything that's interpretable as int, perform a type @@ -443,7 +444,8 @@ void EntryView::fillRemainingWidth(bool lastColumnOnly) } // Add remaining width to last column - header()->resizeSection(header()->logicalIndex(lastColumnIndex), header()->sectionSize(lastColumnIndex) + (header()->width() - width)); + header()->resizeSection(header()->logicalIndex(lastColumnIndex), + header()->sectionSize(lastColumnIndex) + (header()->width() - width)); } void EntryView::resetFixedColumns() @@ -451,4 +453,3 @@ void EntryView::resetFixedColumns() header()->setSectionResizeMode(EntryModel::Paperclip, QHeaderView::Fixed); header()->resizeSection(EntryModel::Paperclip, header()->minimumSectionSize()); } - diff --git a/src/gui/entry/EntryView.h b/src/gui/entry/EntryView.h index a8422c563..3d166c482 100644 --- a/src/gui/entry/EntryView.h +++ b/src/gui/entry/EntryView.h @@ -68,7 +68,7 @@ private slots: void switchToListMode(); void switchToSearchMode(); void showHeaderMenu(const QPoint& position); - void toggleColumnVisibility(QAction *action); + void toggleColumnVisibility(QAction* action); void fitColumnsToWindow(); void fitColumnsToContents(); void resetViewToDefaults(); @@ -76,7 +76,7 @@ private slots: private: void fillRemainingWidth(bool lastColumnOnly); void resetFixedColumns(); - + EntryModel* const m_model; SortFilterHideProxyModel* const m_sortModel; bool m_inSearchMode; diff --git a/src/gui/group/EditGroupWidget.cpp b/src/gui/group/EditGroupWidget.cpp index 9ffd31a5e..2abfa5544 100644 --- a/src/gui/group/EditGroupWidget.cpp +++ b/src/gui/group/EditGroupWidget.cpp @@ -18,8 +18,8 @@ #include "EditGroupWidget.h" #include "ui_EditGroupWidgetMain.h" -#include "core/Metadata.h" #include "core/FilePath.h" +#include "core/Metadata.h" #include "gui/EditWidgetIcons.h" #include "gui/EditWidgetProperties.h" @@ -39,14 +39,18 @@ EditGroupWidget::EditGroupWidget(QWidget* parent) addPage(tr("Properties"), FilePath::instance()->icon("actions", "document-properties"), m_editWidgetProperties); connect(m_mainUi->expireCheck, SIGNAL(toggled(bool)), m_mainUi->expireDatePicker, SLOT(setEnabled(bool))); - connect(m_mainUi->autoTypeSequenceCustomRadio, SIGNAL(toggled(bool)), - m_mainUi->autoTypeSequenceCustomEdit, SLOT(setEnabled(bool))); + connect(m_mainUi->autoTypeSequenceCustomRadio, + SIGNAL(toggled(bool)), + m_mainUi->autoTypeSequenceCustomEdit, + SLOT(setEnabled(bool))); connect(this, SIGNAL(apply()), SLOT(apply())); connect(this, SIGNAL(accepted()), SLOT(save())); connect(this, SIGNAL(rejected()), SLOT(cancel())); - connect(m_editGroupWidgetIcons, SIGNAL(messageEditEntry(QString, MessageWidget::MessageType)), SLOT(showMessage(QString, MessageWidget::MessageType))); + connect(m_editGroupWidgetIcons, + SIGNAL(messageEditEntry(QString, MessageWidget::MessageType)), + SLOT(showMessage(QString, MessageWidget::MessageType))); connect(m_editGroupWidgetIcons, SIGNAL(messageEditEntryDismiss()), SLOT(hideMessage())); } @@ -61,16 +65,14 @@ void EditGroupWidget::loadGroup(Group* group, bool create, Database* database) if (create) { setHeadline(tr("Add group")); - } - else { + } else { setHeadline(tr("Edit group")); } if (m_group->parentGroup()) { addTriStateItems(m_mainUi->searchComboBox, m_group->parentGroup()->resolveSearchingEnabled()); addTriStateItems(m_mainUi->autotypeComboBox, m_group->parentGroup()->resolveAutoTypeEnabled()); - } - else { + } else { addTriStateItems(m_mainUi->searchComboBox, true); addTriStateItems(m_mainUi->autotypeComboBox, true); } @@ -83,8 +85,7 @@ void EditGroupWidget::loadGroup(Group* group, bool create, Database* database) m_mainUi->autotypeComboBox->setCurrentIndex(indexFromTriState(group->autoTypeEnabled())); if (group->defaultAutoTypeSequence().isEmpty()) { m_mainUi->autoTypeSequenceInherit->setChecked(true); - } - else { + } else { m_mainUi->autoTypeSequenceCustomRadio->setChecked(true); } m_mainUi->autoTypeSequenceCustomEdit->setText(group->effectiveAutoTypeSequence()); @@ -123,8 +124,7 @@ void EditGroupWidget::apply() if (m_mainUi->autoTypeSequenceInherit->isChecked()) { m_group->setDefaultAutoTypeSequence(QString()); - } - else { + } else { m_group->setDefaultAutoTypeSequence(m_mainUi->autoTypeSequenceCustomEdit->text()); } @@ -132,19 +132,16 @@ void EditGroupWidget::apply() if (iconStruct.number < 0) { m_group->setIcon(Group::DefaultIconNumber); - } - else if (iconStruct.uuid.isNull()) { + } else if (iconStruct.uuid.isNull()) { m_group->setIcon(iconStruct.number); - } - else { + } else { m_group->setIcon(iconStruct.uuid); } } void EditGroupWidget::cancel() { - if (!m_group->iconUuid().isNull() && - !m_database->metadata()->containsCustomIcon(m_group->iconUuid())) { + if (!m_group->iconUuid().isNull() && !m_database->metadata()->containsCustomIcon(m_group->iconUuid())) { m_group->setIcon(Entry::DefaultIconNumber); } @@ -164,8 +161,7 @@ void EditGroupWidget::addTriStateItems(QComboBox* comboBox, bool inheritDefault) QString inheritDefaultString; if (inheritDefault) { inheritDefaultString = tr("Enable"); - } - else { + } else { inheritDefaultString = tr("Disable"); } diff --git a/src/gui/group/EditGroupWidget.h b/src/gui/group/EditGroupWidget.h index 2d1844934..8f13ef337 100644 --- a/src/gui/group/EditGroupWidget.h +++ b/src/gui/group/EditGroupWidget.h @@ -27,7 +27,8 @@ class EditWidgetIcons; class EditWidgetProperties; -namespace Ui { +namespace Ui +{ class EditGroupWidgetMain; class EditWidget; } diff --git a/src/gui/group/GroupModel.cpp b/src/gui/group/GroupModel.cpp index 87eacf275..ad268c466 100644 --- a/src/gui/group/GroupModel.cpp +++ b/src/gui/group/GroupModel.cpp @@ -44,11 +44,11 @@ void GroupModel::changeDatabase(Database* newDb) m_db = newDb; connect(m_db, SIGNAL(groupDataChanged(Group*)), SLOT(groupDataChanged(Group*))); - connect(m_db, SIGNAL(groupAboutToAdd(Group*,int)), SLOT(groupAboutToAdd(Group*,int))); + connect(m_db, SIGNAL(groupAboutToAdd(Group*, int)), SLOT(groupAboutToAdd(Group*, int))); connect(m_db, SIGNAL(groupAdded()), SLOT(groupAdded())); connect(m_db, SIGNAL(groupAboutToRemove(Group*)), SLOT(groupAboutToRemove(Group*))); connect(m_db, SIGNAL(groupRemoved()), SLOT(groupRemoved())); - connect(m_db, SIGNAL(groupAboutToMove(Group*,Group*,int)), SLOT(groupAboutToMove(Group*,Group*,int))); + connect(m_db, SIGNAL(groupAboutToMove(Group*, Group*, int)), SLOT(groupAboutToMove(Group*, Group*, int))); connect(m_db, SIGNAL(groupMoved()), SLOT(groupMoved())); endResetModel(); @@ -59,8 +59,7 @@ int GroupModel::rowCount(const QModelIndex& parent) const if (!parent.isValid()) { // we have exactly 1 root item return 1; - } - else { + } else { const Group* group = groupFromIndex(parent); return group->children().size(); } @@ -83,8 +82,7 @@ QModelIndex GroupModel::index(int row, int column, const QModelIndex& parent) co if (!parent.isValid()) { group = m_db->rootGroup(); - } - else { + } else { group = groupFromIndex(parent)->children().at(row); } @@ -107,14 +105,12 @@ QModelIndex GroupModel::parent(Group* group) const if (!parentGroup) { // index is already the root group return QModelIndex(); - } - else { + } else { const Group* grandParentGroup = parentGroup->parentGroup(); if (!grandParentGroup) { // parent is the root group return createIndex(0, 0, parentGroup); - } - else { + } else { return createIndex(grandParentGroup->children().indexOf(parentGroup), 0, parentGroup); } } @@ -130,23 +126,19 @@ QVariant GroupModel::data(const QModelIndex& index, int role) const if (role == Qt::DisplayRole) { return group->name(); - } - else if (role == Qt::DecorationRole) { + } else if (role == Qt::DecorationRole) { if (group->isExpired()) { return databaseIcons()->iconPixmap(DatabaseIcons::ExpiredIconIndex); - } - else { + } else { return group->iconScaledPixmap(); } - } - else if (role == Qt::FontRole) { + } else if (role == Qt::FontRole) { QFont font; if (group->isExpired()) { font.setStrikeOut(true); } return font; - } - else { + } else { return QVariant(); } } @@ -166,8 +158,7 @@ QModelIndex GroupModel::index(Group* group) const if (!group->parentGroup()) { row = 0; - } - else { + } else { row = group->parentGroup()->children().indexOf(group); } @@ -190,17 +181,18 @@ Qt::ItemFlags GroupModel::flags(const QModelIndex& modelIndex) const { if (!modelIndex.isValid()) { return Qt::NoItemFlags; - } - else if (modelIndex == index(0, 0)) { + } else if (modelIndex == index(0, 0)) { return QAbstractItemModel::flags(modelIndex) | Qt::ItemIsDropEnabled; - } - else { + } else { return QAbstractItemModel::flags(modelIndex) | Qt::ItemIsDropEnabled | Qt::ItemIsDragEnabled; } } -bool GroupModel::dropMimeData(const QMimeData* data, Qt::DropAction action, - int row, int column, const QModelIndex& parent) +bool GroupModel::dropMimeData(const QMimeData* data, + Qt::DropAction action, + int row, + int column, + const QModelIndex& parent) { Q_UNUSED(column); @@ -229,7 +221,6 @@ bool GroupModel::dropMimeData(const QMimeData* data, Qt::DropAction action, QByteArray encoded = data->data(isGroup ? types.at(0) : types.at(1)); QDataStream stream(&encoded, QIODevice::ReadOnly); - Group* parentGroup = groupFromIndex(parent); if (isGroup) { @@ -258,8 +249,7 @@ bool GroupModel::dropMimeData(const QMimeData* data, Qt::DropAction action, Group* group; if (action == Qt::MoveAction) { group = dragGroup; - } - else { + } else { group = dragGroup->clone(); } @@ -272,8 +262,7 @@ bool GroupModel::dropMimeData(const QMimeData* data, Qt::DropAction action, } group->setParent(parentGroup, row); - } - else { + } else { if (row != -1) { return false; } @@ -296,8 +285,7 @@ bool GroupModel::dropMimeData(const QMimeData* data, Qt::DropAction action, Entry* entry; if (action == Qt::MoveAction) { entry = dragEntry; - } - else { + } else { entry = dragEntry->clone(Entry::CloneNewUuid | Entry::CloneResetTimeInfo); } @@ -305,10 +293,8 @@ bool GroupModel::dropMimeData(const QMimeData* data, Qt::DropAction action, Database* targetDb = parentGroup->database(); Uuid customIcon = entry->iconUuid(); - if (sourceDb != targetDb && !customIcon.isNull() - && !targetDb->metadata()->containsCustomIcon(customIcon)) { - targetDb->metadata()->addCustomIcon(customIcon, - sourceDb->metadata()->customIcon(customIcon)); + if (sourceDb != targetDb && !customIcon.isNull() && !targetDb->metadata()->containsCustomIcon(customIcon)) { + targetDb->metadata()->addCustomIcon(customIcon, sourceDb->metadata()->customIcon(customIcon)); } entry->setGroup(parentGroup); @@ -355,8 +341,7 @@ QMimeData* GroupModel::mimeData(const QModelIndexList& indexes) const if (seenGroups.isEmpty()) { delete data; return nullptr; - } - else { + } else { data->setData(mimeTypes().at(0), encoded); return data; } diff --git a/src/gui/group/GroupModel.h b/src/gui/group/GroupModel.h index 899aa3fd1..ca5370d78 100644 --- a/src/gui/group/GroupModel.h +++ b/src/gui/group/GroupModel.h @@ -41,8 +41,8 @@ public: QVariant headerData(int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const override; Qt::DropActions supportedDropActions() const override; Qt::ItemFlags flags(const QModelIndex& modelIndex) const override; - bool dropMimeData(const QMimeData* data, Qt::DropAction action, int row, int column, - const QModelIndex& parent) override; + bool + dropMimeData(const QMimeData* data, Qt::DropAction action, int row, int column, const QModelIndex& parent) override; QStringList mimeTypes() const override; QMimeData* mimeData(const QModelIndexList& indexes) const override; diff --git a/src/gui/group/GroupView.cpp b/src/gui/group/GroupView.cpp index 82d01e31c..fd6748006 100644 --- a/src/gui/group/GroupView.cpp +++ b/src/gui/group/GroupView.cpp @@ -36,10 +36,10 @@ GroupView::GroupView(Database* db, QWidget* parent) connect(this, SIGNAL(expanded(QModelIndex)), this, SLOT(expandedChanged(QModelIndex))); connect(this, SIGNAL(collapsed(QModelIndex)), this, SLOT(expandedChanged(QModelIndex))); - connect(m_model, SIGNAL(rowsInserted(QModelIndex,int,int)), SLOT(syncExpandedState(QModelIndex,int,int))); + connect(m_model, SIGNAL(rowsInserted(QModelIndex, int, int)), SLOT(syncExpandedState(QModelIndex, int, int))); connect(m_model, SIGNAL(modelReset()), SLOT(modelReset())); - connect(selectionModel(), SIGNAL(currentChanged(QModelIndex,QModelIndex)), SLOT(emitGroupChanged())); + connect(selectionModel(), SIGNAL(currentChanged(QModelIndex, QModelIndex)), SLOT(emitGroupChanged())); connect(this, SIGNAL(clicked(QModelIndex)), SLOT(emitGroupPressed(QModelIndex))); @@ -60,8 +60,7 @@ void GroupView::dragMoveEvent(QDragMoveEvent* event) { if (event->keyboardModifiers() & Qt::ControlModifier) { event->setDropAction(Qt::CopyAction); - } - else { + } else { event->setDropAction(Qt::MoveAction); } @@ -69,7 +68,7 @@ void GroupView::dragMoveEvent(QDragMoveEvent* event) // entries may only be dropped on groups if (event->isAccepted() && event->mimeData()->hasFormat("application/x-keepassx-entry") - && (dropIndicatorPosition() == AboveItem || dropIndicatorPosition() == BelowItem)) { + && (dropIndicatorPosition() == AboveItem || dropIndicatorPosition() == BelowItem)) { event->ignore(); } } @@ -78,8 +77,7 @@ Group* GroupView::currentGroup() { if (currentIndex() == QModelIndex()) { return nullptr; - } - else { + } else { return m_model->groupFromIndex(currentIndex()); } } diff --git a/src/gui/widgets/ElidedLabel.cpp b/src/gui/widgets/ElidedLabel.cpp index 1642bdec8..03d2b5565 100644 --- a/src/gui/widgets/ElidedLabel.cpp +++ b/src/gui/widgets/ElidedLabel.cpp @@ -17,11 +17,12 @@ #include "ElidedLabel.h" -#include #include +#include -namespace { -const QString htmlLinkTemplate("%2"); +namespace +{ + const QString htmlLinkTemplate("%2"); } ElidedLabel::ElidedLabel(QWidget* parent, Qt::WindowFlags f) diff --git a/src/gui/widgets/ElidedLabel.h b/src/gui/widgets/ElidedLabel.h index c7694b5a1..5dd14891d 100644 --- a/src/gui/widgets/ElidedLabel.h +++ b/src/gui/widgets/ElidedLabel.h @@ -29,8 +29,8 @@ class ElidedLabel : public QLabel Q_PROPERTY(QString rawText READ rawText WRITE setRawText NOTIFY rawTextChanged) Q_PROPERTY(QString url READ url WRITE setUrl NOTIFY urlChanged) public: - explicit ElidedLabel(QWidget *parent=nullptr, Qt::WindowFlags f=Qt::WindowFlags()); - explicit ElidedLabel(const QString &text, QWidget *parent=nullptr, Qt::WindowFlags f=Qt::WindowFlags()); + explicit ElidedLabel(QWidget* parent = nullptr, Qt::WindowFlags f = Qt::WindowFlags()); + explicit ElidedLabel(const QString& text, QWidget* parent = nullptr, Qt::WindowFlags f = Qt::WindowFlags()); Qt::TextElideMode elideMode() const; QString rawText() const; diff --git a/src/keys/ChallengeResponseKey.h b/src/keys/ChallengeResponseKey.h index 698846a03..702ee2511 100644 --- a/src/keys/ChallengeResponseKey.h +++ b/src/keys/ChallengeResponseKey.h @@ -24,7 +24,9 @@ class ChallengeResponseKey { public: - virtual ~ChallengeResponseKey() {} + virtual ~ChallengeResponseKey() + { + } virtual QByteArray rawKey() const = 0; virtual bool challenge(const QByteArray& challenge) = 0; }; diff --git a/src/keys/CompositeKey.cpp b/src/keys/CompositeKey.cpp index 6391819b5..3bce1559a 100644 --- a/src/keys/CompositeKey.cpp +++ b/src/keys/CompositeKey.cpp @@ -22,8 +22,8 @@ #include #include "core/Global.h" -#include "crypto/kdf/AesKdf.h" #include "crypto/CryptoHash.h" +#include "crypto/kdf/AesKdf.h" CompositeKey::CompositeKey() { diff --git a/src/keys/CompositeKey.h b/src/keys/CompositeKey.h index fe93a38b4..50d9dbd37 100644 --- a/src/keys/CompositeKey.h +++ b/src/keys/CompositeKey.h @@ -20,12 +20,12 @@ #define KEEPASSX_COMPOSITEKEY_H #include -#include #include +#include #include "crypto/kdf/Kdf.h" -#include "keys/Key.h" #include "keys/ChallengeResponseKey.h" +#include "keys/Key.h" class CompositeKey : public Key { @@ -41,7 +41,7 @@ public: QByteArray rawKey() const override; QByteArray rawKey(const QByteArray* transformSeed, bool* ok = nullptr) const; bool transform(const Kdf& kdf, QByteArray& result) const Q_REQUIRED_RESULT; - bool challenge(const QByteArray& seed, QByteArray &result) const; + bool challenge(const QByteArray& seed, QByteArray& result) const; void addKey(const Key& key); void addChallengeResponseKey(QSharedPointer key); diff --git a/src/keys/FileKey.cpp b/src/keys/FileKey.cpp index 26db40d85..b491fc51e 100644 --- a/src/keys/FileKey.cpp +++ b/src/keys/FileKey.cpp @@ -347,8 +347,7 @@ bool FileKey::loadHashed(QIODevice* device) return false; } cryptoHash.addData(buffer); - } - while (!buffer.isEmpty()); + } while (!buffer.isEmpty()); m_key = cryptoHash.result(); diff --git a/src/keys/FileKey.h b/src/keys/FileKey.h index 2aa48909b..3f04edede 100644 --- a/src/keys/FileKey.h +++ b/src/keys/FileKey.h @@ -25,10 +25,11 @@ class QIODevice; -class FileKey: public Key +class FileKey : public Key { public: - enum Type { + enum Type + { None, Hashed, KeePass2XML, diff --git a/src/keys/Key.h b/src/keys/Key.h index 2172f5702..4014e3907 100644 --- a/src/keys/Key.h +++ b/src/keys/Key.h @@ -23,7 +23,9 @@ class Key { public: - virtual ~Key() {} + virtual ~Key() + { + } virtual QByteArray rawKey() const = 0; virtual Key* clone() const = 0; }; diff --git a/src/keys/YkChallengeResponseKey.cpp b/src/keys/YkChallengeResponseKey.cpp index ac50a5bba..913e2d32a 100644 --- a/src/keys/YkChallengeResponseKey.cpp +++ b/src/keys/YkChallengeResponseKey.cpp @@ -23,16 +23,16 @@ #include "crypto/Random.h" #include "gui/MainWindow.h" -#include -#include -#include #include #include +#include #include +#include +#include YkChallengeResponseKey::YkChallengeResponseKey(int slot, bool blocking) - : m_slot(slot), - m_blocking(blocking) + : m_slot(slot) + , m_blocking(blocking) { if (KEEPASSXC_MAIN_WINDOW) { connect(this, SIGNAL(userInteractionRequired()), KEEPASSXC_MAIN_WINDOW, SLOT(showYubiKeyPopup())); @@ -64,9 +64,8 @@ bool YkChallengeResponseKey::challenge(const QByteArray& challenge, unsigned ret emit userInteractionRequired(); } - QFuture future = QtConcurrent::run([this, challenge]() { - return YubiKey::instance()->challenge(m_slot, true, challenge, m_key); - }); + QFuture future = QtConcurrent::run( + [this, challenge]() { return YubiKey::instance()->challenge(m_slot, true, challenge, m_key); }); QEventLoop loop; QFutureWatcher watcher; @@ -99,9 +98,8 @@ QString YkChallengeResponseKey::getName() const YubiKey::instance()->getSerial(serial); - return fmt.arg(QString::number(serial), - QString::number(m_slot), - (m_blocking) ? QObject::tr("Press") : QObject::tr("Passive")); + return fmt.arg( + QString::number(serial), QString::number(m_slot), (m_blocking) ? QObject::tr("Press") : QObject::tr("Passive")); } bool YkChallengeResponseKey::isBlocking() const diff --git a/src/keys/YkChallengeResponseKey.h b/src/keys/YkChallengeResponseKey.h index 2816602a4..912896e9d 100644 --- a/src/keys/YkChallengeResponseKey.h +++ b/src/keys/YkChallengeResponseKey.h @@ -29,7 +29,6 @@ class YkChallengeResponseKey : public QObject, public ChallengeResponseKey Q_OBJECT public: - YkChallengeResponseKey(int slot = -1, bool blocking = false); QByteArray rawKey() const; diff --git a/src/keys/drivers/YubiKey.cpp b/src/keys/drivers/YubiKey.cpp index 4b98a6e48..b94916197 100644 --- a/src/keys/drivers/YubiKey.cpp +++ b/src/keys/drivers/YubiKey.cpp @@ -21,12 +21,12 @@ #include #include -#include #include #include +#include -#include "core/Tools.h" #include "core/Global.h" +#include "core/Tools.h" #include "crypto/Random.h" #include "YubiKey.h" @@ -36,7 +36,10 @@ #define m_yk (static_cast(m_yk_void)) #define m_ykds (static_cast(m_ykds_void)) -YubiKey::YubiKey() : m_yk_void(NULL), m_ykds_void(NULL), m_mutex(QMutex::Recursive) +YubiKey::YubiKey() + : m_yk_void(NULL) + , m_ykds_void(NULL) + , m_mutex(QMutex::Recursive) { } @@ -188,8 +191,8 @@ YubiKey::ChallengeResult YubiKey::challenge(int slot, bool mayBlock, const QByte paddedChallenge.append(QByteArray(padLen, padLen)); } - const unsigned char *c; - unsigned char *r; + const unsigned char* c; + unsigned char* r; c = reinterpret_cast(paddedChallenge.constData()); r = reinterpret_cast(response.data()); diff --git a/src/keys/drivers/YubiKey.h b/src/keys/drivers/YubiKey.h index 328688f08..39085546b 100644 --- a/src/keys/drivers/YubiKey.h +++ b/src/keys/drivers/YubiKey.h @@ -19,8 +19,8 @@ #ifndef KEEPASSX_YUBIKEY_H #define KEEPASSX_YUBIKEY_H -#include #include +#include /** * Singleton class to manage the interface to the hardware @@ -30,7 +30,13 @@ class YubiKey : public QObject Q_OBJECT public: - enum ChallengeResult { ERROR = -1, SUCCESS = 0, WOULDBLOCK, ALREADY_RUNNING }; + enum ChallengeResult + { + ERROR = -1, + SUCCESS = 0, + WOULDBLOCK, + ALREADY_RUNNING + }; /** * @brief YubiKey::instance - get instance of singleton diff --git a/src/keys/drivers/YubiKeyStub.cpp b/src/keys/drivers/YubiKeyStub.cpp index 9f6314f0e..3cff04965 100644 --- a/src/keys/drivers/YubiKeyStub.cpp +++ b/src/keys/drivers/YubiKeyStub.cpp @@ -23,7 +23,9 @@ #include "YubiKey.h" -YubiKey::YubiKey() : m_yk_void(NULL), m_ykds_void(NULL) +YubiKey::YubiKey() + : m_yk_void(NULL) + , m_ykds_void(NULL) { } diff --git a/src/main.cpp b/src/main.cpp index b3b607f25..13c22858a 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -59,22 +59,24 @@ int main(int argc, char** argv) // QStandardPaths::writableLocation(QDesktopServices::DataLocation) QCommandLineParser parser; - parser.setApplicationDescription(QCoreApplication::translate("main", "KeePassXC - cross-platform password manager")); - parser.addPositionalArgument("filename", QCoreApplication::translate("main", "filenames of the password databases to open (*.kdbx)"), "[filename(s)]"); + parser.setApplicationDescription( + QCoreApplication::translate("main", "KeePassXC - cross-platform password manager")); + parser.addPositionalArgument( + "filename", + QCoreApplication::translate("main", "filenames of the password databases to open (*.kdbx)"), + "[filename(s)]"); - QCommandLineOption configOption("config", - QCoreApplication::translate("main", "path to a custom config file"), - "config"); - QCommandLineOption keyfileOption("keyfile", - QCoreApplication::translate("main", "key file of the database"), - "keyfile"); + QCommandLineOption configOption( + "config", QCoreApplication::translate("main", "path to a custom config file"), "config"); + QCommandLineOption keyfileOption( + "keyfile", QCoreApplication::translate("main", "key file of the database"), "keyfile"); QCommandLineOption pwstdinOption("pw-stdin", QCoreApplication::translate("main", "read password of the database from stdin")); // This is needed under Windows where clients send --parent-window parameter with Native Messaging connect method QCommandLineOption parentWindowOption(QStringList() << "pw" << "parent-window", - QCoreApplication::translate("main", "Parent window handle"), - "handle"); + QCoreApplication::translate("main", "Parent window handle"), + "handle"); parser.addHelpOption(); parser.addVersionOption(); @@ -90,15 +92,16 @@ int main(int argc, char** argv) if (!fileNames.isEmpty()) { app.sendFileNamesToRunningInstance(fileNames); } - qWarning() << QCoreApplication::translate("Main", "Another instance of KeePassXC is already running.").toUtf8().constData(); + qWarning() << QCoreApplication::translate("Main", "Another instance of KeePassXC is already running.") + .toUtf8() + .constData(); return 0; } QApplication::setQuitOnLastWindowClosed(false); if (!Crypto::init()) { - QString error = QCoreApplication::translate("Main", - "Fatal error while testing the cryptographic functions."); + QString error = QCoreApplication::translate("Main", "Fatal error while testing the cryptographic functions."); error.append("\n"); error.append(Crypto::errorString()); MessageBox::critical(nullptr, QCoreApplication::translate("Main", "KeePassXC - Error"), error); @@ -126,7 +129,7 @@ int main(int argc, char** argv) // start minimized if configured bool minimizeOnStartup = config()->get("GUI/MinimizeOnStartup").toBool(); - bool minimizeToTray = config()->get("GUI/MinimizeToTray").toBool(); + bool minimizeToTray = config()->get("GUI/MinimizeToTray").toBool(); #ifndef Q_OS_LINUX if (minimizeOnStartup) { #else @@ -143,7 +146,7 @@ int main(int argc, char** argv) if (config()->get("OpenPreviousDatabasesOnStartup").toBool()) { const QStringList fileNames = config()->get("LastOpenedDatabases").toStringList(); - for (const QString& filename: fileNames) { + for (const QString& filename : fileNames) { if (!filename.isEmpty() && QFile::exists(filename)) { mainWindow.openDatabase(filename); } @@ -151,7 +154,7 @@ int main(int argc, char** argv) } const bool pwstdin = parser.isSet(pwstdinOption); - for (const QString& filename: fileNames) { + for (const QString& filename : fileNames) { QString password; if (pwstdin) { // we always need consume a line of STDIN if --pw-stdin is set to clear out the diff --git a/src/proxy/NativeMessagingHost.cpp b/src/proxy/NativeMessagingHost.cpp old mode 100755 new mode 100644 index c5ce60ea9..61b1687fb --- a/src/proxy/NativeMessagingHost.cpp +++ b/src/proxy/NativeMessagingHost.cpp @@ -15,20 +15,25 @@ * along with this program. If not, see . */ -#include #include "NativeMessagingHost.h" +#include -NativeMessagingHost::NativeMessagingHost() : NativeMessagingBase() +NativeMessagingHost::NativeMessagingHost() + : NativeMessagingBase() { m_localSocket = new QLocalSocket(); m_localSocket->connectToServer(getLocalServerPath()); #ifdef Q_OS_WIN m_running.store(true); - m_future = QtConcurrent::run(this, static_cast(&NativeMessagingHost::readNativeMessages)); + m_future = + QtConcurrent::run(this, static_cast(&NativeMessagingHost::readNativeMessages)); #endif connect(m_localSocket, SIGNAL(readyRead()), this, SLOT(newLocalMessage())); connect(m_localSocket, SIGNAL(disconnected()), this, SLOT(deleteSocket())); - connect(m_localSocket, SIGNAL(stateChanged(QLocalSocket::LocalSocketState)), this, SLOT(socketStateChanged(QLocalSocket::LocalSocketState))); + connect(m_localSocket, + SIGNAL(stateChanged(QLocalSocket::LocalSocketState)), + this, + SLOT(socketStateChanged(QLocalSocket::LocalSocketState))); } NativeMessagingHost::~NativeMessagingHost() @@ -45,7 +50,7 @@ void NativeMessagingHost::readLength() if (!std::cin.eof() && length > 0) { readStdIn(length); } else { - QCoreApplication::quit(); + QCoreApplication::quit(); } } @@ -81,7 +86,7 @@ void NativeMessagingHost::newLocalMessage() QByteArray arr = m_localSocket->readAll(); if (!arr.isEmpty()) { - sendReply(arr); + sendReply(arr); } } diff --git a/src/proxy/NativeMessagingHost.h b/src/proxy/NativeMessagingHost.h old mode 100755 new mode 100644 index 41f3ed753..faf9d908f --- a/src/proxy/NativeMessagingHost.h +++ b/src/proxy/NativeMessagingHost.h @@ -37,7 +37,7 @@ private: void readStdIn(const quint32 length); private: - QLocalSocket* m_localSocket; + QLocalSocket* m_localSocket; }; #endif // NATIVEMESSAGINGHOST_H diff --git a/src/proxy/keepassxc-proxy.cpp b/src/proxy/keepassxc-proxy.cpp index 9509c1eab..d75f841c0 100644 --- a/src/proxy/keepassxc-proxy.cpp +++ b/src/proxy/keepassxc-proxy.cpp @@ -16,9 +16,9 @@ * along with this program. If not, see . */ +#include "NativeMessagingHost.h" #include #include -#include "NativeMessagingHost.h" #ifndef Q_OS_WIN #include @@ -26,13 +26,15 @@ #include // (C) Gist: https://gist.github.com/azadkuh/a2ac6869661ebd3f8588 -void ignoreUnixSignals(std::initializer_list ignoreSignals) { +void ignoreUnixSignals(std::initializer_list ignoreSignals) +{ for (int sig : ignoreSignals) { signal(sig, SIG_IGN); } } -void catchUnixSignals(std::initializer_list quitSignals) { +void catchUnixSignals(std::initializer_list quitSignals) +{ auto handler = [](int sig) -> void { std::cerr << sig; QCoreApplication::quit(); @@ -46,8 +48,8 @@ void catchUnixSignals(std::initializer_list quitSignals) { struct sigaction sa; sa.sa_handler = handler; - sa.sa_mask = blocking_mask; - sa.sa_flags = 0; + sa.sa_mask = blocking_mask; + sa.sa_flags = 0; for (auto sig : quitSignals) { sigaction(sig, &sa, nullptr); @@ -55,7 +57,7 @@ void catchUnixSignals(std::initializer_list quitSignals) { } #endif -int main(int argc, char *argv[]) +int main(int argc, char* argv[]) { QCoreApplication a(argc, argv); #if defined(Q_OS_UNIX) || defined(Q_OS_LINUX) diff --git a/src/sshagent/ASN1Key.cpp b/src/sshagent/ASN1Key.cpp index c46b8fa0b..9197cade0 100644 --- a/src/sshagent/ASN1Key.cpp +++ b/src/sshagent/ASN1Key.cpp @@ -19,10 +19,11 @@ #include "ASN1Key.h" #include -namespace { - constexpr quint8 TAG_INT = 0x02; - constexpr quint8 TAG_SEQUENCE = 0x30; - constexpr quint8 KEY_ZERO = 0x0; +namespace +{ + constexpr quint8 TAG_INT = 0x02; + constexpr quint8 TAG_SEQUENCE = 0x30; + constexpr quint8 KEY_ZERO = 0x0; bool nextTag(BinaryStream& stream, quint8& tag, quint32& len) { @@ -103,7 +104,8 @@ namespace { mpi_invm(u, q, p); iqmp_hex.resize((bap.length() + 1) * 2); - gcry_mpi_print(GCRYMPI_FMT_HEX, reinterpret_cast(iqmp_hex.data()), iqmp_hex.length(), nullptr, u); + gcry_mpi_print( + GCRYMPI_FMT_HEX, reinterpret_cast(iqmp_hex.data()), iqmp_hex.length(), nullptr, u); gcry_mpi_release(u); gcry_mpi_release(p); @@ -121,7 +123,7 @@ bool ASN1Key::parseDSA(QByteArray& ba, OpenSSHKey& key) return false; } - QByteArray p,q,g,y,x; + QByteArray p, q, g, y, x; readInt(stream, p); readInt(stream, q); readInt(stream, g); @@ -156,7 +158,7 @@ bool ASN1Key::parseRSA(QByteArray& ba, OpenSSHKey& key) return false; } - QByteArray n,e,d,p,q,dp,dq,qinv; + QByteArray n, e, d, p, q, dp, dq, qinv; readInt(stream, n); readInt(stream, e); readInt(stream, d); diff --git a/src/sshagent/AgentSettingsPage.cpp b/src/sshagent/AgentSettingsPage.cpp index 70fa04bde..1f04d61b1 100644 --- a/src/sshagent/AgentSettingsPage.cpp +++ b/src/sshagent/AgentSettingsPage.cpp @@ -27,7 +27,6 @@ AgentSettingsPage::AgentSettingsPage(DatabaseTabWidget* tabWidget) AgentSettingsPage::~AgentSettingsPage() { - } QString AgentSettingsPage::name() diff --git a/src/sshagent/AgentSettingsPage.h b/src/sshagent/AgentSettingsPage.h index f9d1be3f9..1cd4d9a57 100644 --- a/src/sshagent/AgentSettingsPage.h +++ b/src/sshagent/AgentSettingsPage.h @@ -19,8 +19,8 @@ #ifndef AGENTSETTINGSPAGE_H #define AGENTSETTINGSPAGE_H -#include "gui/SettingsWidget.h" #include "gui/DatabaseTabWidget.h" +#include "gui/SettingsWidget.h" class AgentSettingsPage : public ISettingsPage { diff --git a/src/sshagent/AgentSettingsWidget.cpp b/src/sshagent/AgentSettingsWidget.cpp index 81b6808fe..10a09f9da 100644 --- a/src/sshagent/AgentSettingsWidget.cpp +++ b/src/sshagent/AgentSettingsWidget.cpp @@ -17,8 +17,8 @@ */ #include "AgentSettingsWidget.h" -#include "ui_AgentSettingsWidget.h" #include "core/Config.h" +#include "ui_AgentSettingsWidget.h" AgentSettingsWidget::AgentSettingsWidget(QWidget* parent) : QWidget(parent) diff --git a/src/sshagent/AgentSettingsWidget.h b/src/sshagent/AgentSettingsWidget.h index 90d1b1973..8667be657 100644 --- a/src/sshagent/AgentSettingsWidget.h +++ b/src/sshagent/AgentSettingsWidget.h @@ -19,10 +19,11 @@ #ifndef AGENTSETTINGSWIDGET_H #define AGENTSETTINGSWIDGET_H -#include #include +#include -namespace Ui { +namespace Ui +{ class AgentSettingsWidget; } diff --git a/src/sshagent/BinaryStream.cpp b/src/sshagent/BinaryStream.cpp index b9ed236fd..2aa8ac1c7 100644 --- a/src/sshagent/BinaryStream.cpp +++ b/src/sshagent/BinaryStream.cpp @@ -23,7 +23,6 @@ BinaryStream::BinaryStream(QObject* parent) : QObject(parent) , m_timeout(-1) { - } BinaryStream::BinaryStream(QIODevice* device) @@ -31,7 +30,6 @@ BinaryStream::BinaryStream(QIODevice* device) , m_timeout(-1) , m_device(device) { - } BinaryStream::BinaryStream(QByteArray* ba, QObject* parent) @@ -105,7 +103,7 @@ bool BinaryStream::read(QByteArray& ba) bool BinaryStream::read(quint32& i) { - if (read(reinterpret_cast(&i), sizeof(i))) { + if (read(reinterpret_cast(&i), sizeof(i))) { i = qFromBigEndian(i); return true; } @@ -115,7 +113,7 @@ bool BinaryStream::read(quint32& i) bool BinaryStream::read(quint16& i) { - if (read(reinterpret_cast(&i), sizeof(i))) { + if (read(reinterpret_cast(&i), sizeof(i))) { i = qFromBigEndian(i); return true; } @@ -125,24 +123,24 @@ bool BinaryStream::read(quint16& i) bool BinaryStream::read(quint8& i) { - return read(reinterpret_cast(&i), sizeof(i)); + return read(reinterpret_cast(&i), sizeof(i)); } bool BinaryStream::readString(QByteArray& ba) { - quint32 length; + quint32 length; - if (!read(length)) { - return false; - } + if (!read(length)) { + return false; + } - ba.resize(length); + ba.resize(length); - if (!read(ba.data(), ba.length())) { - return false; - } + if (!read(ba.data(), ba.length())) { + return false; + } - return true; + return true; } bool BinaryStream::readString(QString& str) @@ -157,7 +155,6 @@ bool BinaryStream::readString(QString& str) return true; } - bool BinaryStream::write(const char* ptr, qint64 size) { if (m_device->write(ptr, size) < 0) { @@ -186,18 +183,18 @@ bool BinaryStream::write(const QByteArray& ba) bool BinaryStream::write(quint32 i) { i = qToBigEndian(i); - return write(reinterpret_cast(&i), sizeof(i)); + return write(reinterpret_cast(&i), sizeof(i)); } bool BinaryStream::write(quint16 i) { i = qToBigEndian(i); - return write(reinterpret_cast(&i), sizeof(i)); + return write(reinterpret_cast(&i), sizeof(i)); } bool BinaryStream::write(quint8 i) { - return write(reinterpret_cast(&i), sizeof(i)); + return write(reinterpret_cast(&i), sizeof(i)); } bool BinaryStream::writeString(const QByteArray& ba) diff --git a/src/sshagent/BinaryStream.h b/src/sshagent/BinaryStream.h index c61010180..fa9ded81a 100644 --- a/src/sshagent/BinaryStream.h +++ b/src/sshagent/BinaryStream.h @@ -19,9 +19,9 @@ #ifndef BINARYSTREAM_H #define BINARYSTREAM_H -#include -#include #include +#include +#include class BinaryStream : QObject { diff --git a/src/sshagent/KeeAgentSettings.cpp b/src/sshagent/KeeAgentSettings.cpp index 218e98acb..ac6a381bf 100644 --- a/src/sshagent/KeeAgentSettings.cpp +++ b/src/sshagent/KeeAgentSettings.cpp @@ -30,13 +30,11 @@ KeeAgentSettings::KeeAgentSettings() , m_saveAttachmentToTempFile(false) , m_fileName(QString()) { - } bool KeeAgentSettings::operator==(KeeAgentSettings& other) { - return (m_allowUseOfSshKey == other.m_allowUseOfSshKey - && m_addAtDatabaseOpen == other.m_addAtDatabaseOpen + return (m_allowUseOfSshKey == other.m_allowUseOfSshKey && m_addAtDatabaseOpen == other.m_addAtDatabaseOpen && m_removeAtDatabaseClose == other.m_removeAtDatabaseClose && m_useConfirmConstraintWhenAdding == other.m_useConfirmConstraintWhenAdding && m_useLifetimeConstraintWhenAdding == other.m_useLifetimeConstraintWhenAdding diff --git a/src/sshagent/KeeAgentSettings.h b/src/sshagent/KeeAgentSettings.h index 4022750d1..484dee88d 100644 --- a/src/sshagent/KeeAgentSettings.h +++ b/src/sshagent/KeeAgentSettings.h @@ -19,8 +19,8 @@ #ifndef KEEAGENTSETTINGS_H #define KEEAGENTSETTINGS_H -#include #include +#include class KeeAgentSettings { @@ -31,7 +31,7 @@ public: bool operator!=(KeeAgentSettings& other); bool isDefault(); - bool fromXml(const QByteArray &ba); + bool fromXml(const QByteArray& ba); QByteArray toXml(); bool allowUseOfSshKey() const; diff --git a/src/sshagent/OpenSSHKey.cpp b/src/sshagent/OpenSSHKey.cpp index ccc7606f0..c80708c08 100644 --- a/src/sshagent/OpenSSHKey.cpp +++ b/src/sshagent/OpenSSHKey.cpp @@ -18,10 +18,10 @@ #include "OpenSSHKey.h" #include "ASN1Key.h" +#include "crypto/SymmetricCipher.h" +#include #include #include -#include -#include "crypto/SymmetricCipher.h" const QString OpenSSHKey::TYPE_DSA = "DSA PRIVATE KEY"; const QString OpenSSHKey::TYPE_RSA = "RSA PRIVATE KEY"; @@ -30,7 +30,7 @@ const QString OpenSSHKey::TYPE_OPENSSH = "OPENSSH PRIVATE KEY"; // bcrypt_pbkdf.cpp int bcrypt_pbkdf(const QByteArray& pass, const QByteArray& salt, QByteArray& key, quint32 rounds); -OpenSSHKey::OpenSSHKey(QObject *parent) +OpenSSHKey::OpenSSHKey(QObject* parent) : QObject(parent) , m_type(QString()) , m_cipherName(QString("none")) @@ -43,7 +43,6 @@ OpenSSHKey::OpenSSHKey(QObject *parent) , m_comment(QString()) , m_error(QString()) { - } OpenSSHKey::OpenSSHKey(const OpenSSHKey& other) @@ -58,7 +57,6 @@ OpenSSHKey::OpenSSHKey(const OpenSSHKey& other) , m_comment(other.m_comment) , m_error(other.m_error) { - } bool OpenSSHKey::operator==(const OpenSSHKey& other) const diff --git a/src/sshagent/OpenSSHKey.h b/src/sshagent/OpenSSHKey.h index e06af2201..cd162796d 100644 --- a/src/sshagent/OpenSSHKey.h +++ b/src/sshagent/OpenSSHKey.h @@ -19,8 +19,8 @@ #ifndef OPENSSHKEY_H #define OPENSSHKEY_H -#include #include "BinaryStream.h" +#include class OpenSSHKey : QObject { diff --git a/src/sshagent/SSHAgent.cpp b/src/sshagent/SSHAgent.cpp index 973e03054..e8639f5d2 100644 --- a/src/sshagent/SSHAgent.cpp +++ b/src/sshagent/SSHAgent.cpp @@ -28,7 +28,8 @@ SSHAgent* SSHAgent::m_instance; -SSHAgent::SSHAgent(QObject* parent) : QObject(parent) +SSHAgent::SSHAgent(QObject* parent) + : QObject(parent) { #ifndef Q_OS_WIN m_socketPath = QProcessEnvironment::systemEnvironment().value("SSH_AUTH_SOCK"); @@ -108,7 +109,8 @@ bool SSHAgent::sendMessage(const QByteArray& in, QByteArray& out) return false; } - QByteArray mapName = (QString("SSHAgentRequest") + reinterpret_cast(QThread::currentThreadId())).toLatin1(); + QByteArray mapName = + (QString("SSHAgentRequest") + reinterpret_cast(QThread::currentThreadId())).toLatin1(); HANDLE handle = CreateFileMappingA(INVALID_HANDLE_VALUE, NULL, PAGE_READWRITE, 0, AGENT_MAX_MSGLEN, mapName.data()); @@ -125,8 +127,8 @@ bool SSHAgent::sendMessage(const QByteArray& in, QByteArray& out) return false; } - quint32 *requestLength = reinterpret_cast(ptr); - void *requestData = reinterpret_cast(reinterpret_cast(ptr) + 4); + quint32* requestLength = reinterpret_cast(ptr); + void* requestData = reinterpret_cast(reinterpret_cast(ptr) + 4); *requestLength = qToBigEndian(in.length()); memcpy(requestData, in.data(), in.length()); @@ -157,7 +159,6 @@ bool SSHAgent::sendMessage(const QByteArray& in, QByteArray& out) #endif } - bool SSHAgent::addIdentity(OpenSSHKey& key, quint32 lifetime, bool confirm) { if (!isAgentRunning()) { @@ -186,8 +187,8 @@ bool SSHAgent::addIdentity(OpenSSHKey& key, quint32 lifetime, bool confirm) } if (responseData.length() < 1 || static_cast(responseData[0]) != SSH_AGENT_SUCCESS) { - m_error = tr("Agent refused this identity. Possible reasons include:") - + "\n" + tr("The key has already been added."); + m_error = + tr("Agent refused this identity. Possible reasons include:") + "\n" + tr("The key has already been added."); if (lifetime > 0) { m_error += "\n" + tr("Restricted lifetime is not supported by the agent (check options)."); diff --git a/src/sshagent/SSHAgent.h b/src/sshagent/SSHAgent.h index adb08cad6..b12f32b27 100644 --- a/src/sshagent/SSHAgent.h +++ b/src/sshagent/SSHAgent.h @@ -19,9 +19,9 @@ #ifndef AGENTCLIENT_H #define AGENTCLIENT_H -#include -#include #include "OpenSSHKey.h" +#include +#include #include "gui/DatabaseWidget.h" @@ -46,16 +46,16 @@ public slots: void databaseModeChanged(DatabaseWidget::Mode mode = DatabaseWidget::LockedMode); private: - const quint8 SSH_AGENT_FAILURE = 5; - const quint8 SSH_AGENT_SUCCESS = 6; - const quint8 SSH_AGENTC_REQUEST_IDENTITIES = 11; - const quint8 SSH_AGENT_IDENTITIES_ANSWER = 12; - const quint8 SSH_AGENTC_ADD_IDENTITY = 17; - const quint8 SSH_AGENTC_REMOVE_IDENTITY = 18; - const quint8 SSH_AGENTC_ADD_ID_CONSTRAINED = 25; + const quint8 SSH_AGENT_FAILURE = 5; + const quint8 SSH_AGENT_SUCCESS = 6; + const quint8 SSH_AGENTC_REQUEST_IDENTITIES = 11; + const quint8 SSH_AGENT_IDENTITIES_ANSWER = 12; + const quint8 SSH_AGENTC_ADD_IDENTITY = 17; + const quint8 SSH_AGENTC_REMOVE_IDENTITY = 18; + const quint8 SSH_AGENTC_ADD_ID_CONSTRAINED = 25; - const quint8 SSH_AGENT_CONSTRAIN_LIFETIME = 1; - const quint8 SSH_AGENT_CONSTRAIN_CONFIRM = 2; + const quint8 SSH_AGENT_CONSTRAIN_LIFETIME = 1; + const quint8 SSH_AGENT_CONSTRAIN_CONFIRM = 2; explicit SSHAgent(QObject* parent = nullptr); ~SSHAgent(); diff --git a/src/sshagent/includes.h b/src/sshagent/includes.h index c6bb4d32e..23b4aeeb6 100644 --- a/src/sshagent/includes.h +++ b/src/sshagent/includes.h @@ -8,7 +8,6 @@ #endif #include - #ifdef _WIN32 #include @@ -16,5 +15,5 @@ typedef uint32_t u_int32_t; typedef uint16_t u_int16_t; typedef uint8_t u_int8_t; -#define bzero(p,s) memset(p, 0, s) +#define bzero(p, s) memset(p, 0, s) #endif diff --git a/src/streams/HashedBlockStream.cpp b/src/streams/HashedBlockStream.cpp index dd323a6d5..753bdecc6 100644 --- a/src/streams/HashedBlockStream.cpp +++ b/src/streams/HashedBlockStream.cpp @@ -26,7 +26,7 @@ const QSysInfo::Endian HashedBlockStream::ByteOrder = QSysInfo::LittleEndian; HashedBlockStream::HashedBlockStream(QIODevice* baseDevice) : LayeredStream(baseDevice) - , m_blockSize(1024*1024) + , m_blockSize(1024 * 1024) { init(); } @@ -94,8 +94,7 @@ qint64 HashedBlockStream::readData(char* data, qint64 maxSize) { if (m_error) { return -1; - } - else if (m_eof) { + } else if (m_eof) { return 0; } @@ -107,8 +106,7 @@ qint64 HashedBlockStream::readData(char* data, qint64 maxSize) if (!readHashedBlock()) { if (m_error) { return -1; - } - else { + } else { return maxSize - bytesRemaining; } } @@ -204,8 +202,7 @@ qint64 HashedBlockStream::writeData(const char* data, qint64 maxSize) if (!writeHashedBlock()) { if (m_error) { return -1; - } - else { + } else { return maxSize - bytesRemaining; } } @@ -227,8 +224,7 @@ bool HashedBlockStream::writeHashedBlock() QByteArray hash; if (!m_buffer.isEmpty()) { hash = CryptoHash::hash(m_buffer, CryptoHash::Sha256); - } - else { + } else { hash.fill(0, 32); } @@ -257,6 +253,7 @@ bool HashedBlockStream::writeHashedBlock() return true; } -bool HashedBlockStream::atEnd() const { +bool HashedBlockStream::atEnd() const +{ return m_eof; } diff --git a/src/streams/HmacBlockStream.h b/src/streams/HmacBlockStream.h index 592cf844c..c10c96746 100644 --- a/src/streams/HmacBlockStream.h +++ b/src/streams/HmacBlockStream.h @@ -22,9 +22,9 @@ #include "streams/LayeredStream.h" -class HmacBlockStream: public LayeredStream +class HmacBlockStream : public LayeredStream { -Q_OBJECT + Q_OBJECT public: explicit HmacBlockStream(QIODevice* baseDevice, QByteArray key); diff --git a/src/streams/LayeredStream.cpp b/src/streams/LayeredStream.cpp index 9f7783bd3..9b1545850 100644 --- a/src/streams/LayeredStream.cpp +++ b/src/streams/LayeredStream.cpp @@ -47,17 +47,13 @@ bool LayeredStream::open(QIODevice::OpenMode mode) if (readMode && writeMode) { qWarning("LayeredStream::open: Reading and writing at the same time is not supported."); return false; - } - else if (!readMode && !writeMode) { + } else if (!readMode && !writeMode) { qWarning("LayeredStream::open: Must be opened in read or write mode."); return false; - } - else if ((readMode && !m_baseDevice->isReadable()) || - (writeMode && !m_baseDevice->isWritable())) { + } else if ((readMode && !m_baseDevice->isReadable()) || (writeMode && !m_baseDevice->isWritable())) { qWarning("LayeredStream::open: Base device is not opened correctly."); return false; - } - else { + } else { if (mode & QIODevice::Append) { qWarning("LayeredStream::open: QIODevice::Append is not supported."); mode = mode & ~QIODevice::Append; diff --git a/src/streams/SymmetricCipherStream.cpp b/src/streams/SymmetricCipherStream.cpp index 78476c618..f6957622d 100644 --- a/src/streams/SymmetricCipherStream.cpp +++ b/src/streams/SymmetricCipherStream.cpp @@ -17,8 +17,10 @@ #include "SymmetricCipherStream.h" -SymmetricCipherStream::SymmetricCipherStream(QIODevice* baseDevice, SymmetricCipher::Algorithm algo, - SymmetricCipher::Mode mode, SymmetricCipher::Direction direction) +SymmetricCipherStream::SymmetricCipherStream(QIODevice* baseDevice, + SymmetricCipher::Algorithm algo, + SymmetricCipher::Mode mode, + SymmetricCipher::Direction direction) : LayeredStream(baseDevice) , m_cipher(new SymmetricCipher(algo, mode, direction)) , m_bufferPos(0) @@ -57,7 +59,6 @@ void SymmetricCipherStream::resetInternalState() bool SymmetricCipherStream::open(QIODevice::OpenMode mode) { return m_isInitialized && LayeredStream::open(mode); - } bool SymmetricCipherStream::reset() @@ -100,8 +101,7 @@ qint64 SymmetricCipherStream::readData(char* data, qint64 maxSize) if (!readBlock()) { if (m_error) { return -1; - } - else { + } else { return maxSize - bytesRemaining; } } @@ -125,8 +125,7 @@ bool SymmetricCipherStream::readBlock() if (m_bufferFilling) { newData.resize(blockSize() - m_buffer.size()); - } - else { + } else { m_buffer.clear(); newData.resize(blockSize()); } @@ -144,8 +143,7 @@ bool SymmetricCipherStream::readBlock() if (!m_streamCipher && m_buffer.size() != blockSize()) { m_bufferFilling = true; return false; - } - else { + } else { if (!m_cipher->processInPlace(m_buffer)) { m_error = true; setErrorString(m_cipher->errorString()); @@ -178,8 +176,7 @@ bool SymmetricCipherStream::readBlock() } else { return m_buffer.size() > 0; } - } - else { + } else { return true; } } @@ -209,8 +206,7 @@ qint64 SymmetricCipherStream::writeData(const char* data, qint64 maxSize) if (!writeBlock(false)) { if (m_error) { return -1; - } - else { + } else { return maxSize - bytesRemaining; } } @@ -242,14 +238,14 @@ bool SymmetricCipherStream::writeBlock(bool lastBlock) m_error = true; setErrorString(m_baseDevice->errorString()); return false; - } - else { + } else { m_buffer.clear(); return true; } } -int SymmetricCipherStream::blockSize() const { +int SymmetricCipherStream::blockSize() const +{ if (m_streamCipher) { return 1024; } diff --git a/src/streams/SymmetricCipherStream.h b/src/streams/SymmetricCipherStream.h index b68dba01f..4f8feaa33 100644 --- a/src/streams/SymmetricCipherStream.h +++ b/src/streams/SymmetricCipherStream.h @@ -29,8 +29,10 @@ class SymmetricCipherStream : public LayeredStream Q_OBJECT public: - SymmetricCipherStream(QIODevice* baseDevice, SymmetricCipher::Algorithm algo, - SymmetricCipher::Mode mode, SymmetricCipher::Direction direction); + SymmetricCipherStream(QIODevice* baseDevice, + SymmetricCipher::Algorithm algo, + SymmetricCipher::Mode mode, + SymmetricCipher::Direction direction); ~SymmetricCipherStream(); bool init(const QByteArray& key, const QByteArray& iv); bool open(QIODevice::OpenMode mode) override; diff --git a/src/totp/totp.cpp b/src/totp/totp.cpp index f102335aa..d187bd0f6 100644 --- a/src/totp/totp.cpp +++ b/src/totp/totp.cpp @@ -40,9 +40,9 @@ const quint8 Totp::defaultDigits = 6; */ const quint8 Totp::ENCODER_STEAM = 254; -const Totp::Encoder Totp::defaultEncoder = { "", "", "0123456789", 0, 0, false }; +const Totp::Encoder Totp::defaultEncoder = {"", "", "0123456789", 0, 0, false}; const QMap Totp::encoders{ - { Totp::ENCODER_STEAM, { "steam", "S", "23456789BCDFGHJKMNPQRTVWXY", 5, 30, true } }, + {Totp::ENCODER_STEAM, {"steam", "S", "23456789BCDFGHJKMNPQRTVWXY", 5, 30, true}}, }; /** @@ -53,7 +53,7 @@ const QMap Totp::encoders{ * in Entry::totpSeed() */ const QMap Totp::shortNameToEncoder{ - { "S", Totp::ENCODER_STEAM }, + {"S", Totp::ENCODER_STEAM}, }; /** * These map the "encoder=" URL parameter of the "otp" field to our internal encoder number @@ -61,7 +61,7 @@ const QMap Totp::shortNameToEncoder{ * in the corresponding Encoder */ const QMap Totp::nameToEncoder{ - { "steam", Totp::ENCODER_STEAM }, + {"steam", Totp::ENCODER_STEAM}, }; Totp::Totp() @@ -129,9 +129,9 @@ QString Totp::parseOtpString(QString key, quint8& digits, quint8& step) } QString Totp::generateTotp(const QByteArray key, - quint64 time, - const quint8 numDigits = defaultDigits, - const quint8 step = defaultStep) + quint64 time, + const quint8 numDigits = defaultDigits, + const quint8 step = defaultStep) { quint64 current = qToBigEndian(time / step); @@ -177,12 +177,12 @@ QString Totp::generateTotp(const QByteArray key, // See: https://github.com/google/google-authenticator/wiki/Key-Uri-Format QUrl Totp::generateOtpString(const QString& secret, - const QString& type, - const QString& issuer, - const QString& username, - const QString& algorithm, - quint8 digits, - quint8 step) + const QString& type, + const QString& issuer, + const QString& username, + const QString& algorithm, + quint8 digits, + quint8 step) { QUrl keyUri; keyUri.setScheme("otpauth"); diff --git a/src/totp/totp.h b/src/totp/totp.h index 7d4c78c1d..1c159e290 100644 --- a/src/totp/totp.h +++ b/src/totp/totp.h @@ -19,9 +19,9 @@ #ifndef QTOTP_H #define QTOTP_H -#include -#include #include +#include +#include class QUrl; diff --git a/tests/FailDevice.cpp b/tests/FailDevice.cpp index 5a25db282..33e000cfd 100644 --- a/tests/FailDevice.cpp +++ b/tests/FailDevice.cpp @@ -35,8 +35,7 @@ qint64 FailDevice::readData(char* data, qint64 len) if (m_readCount >= m_failAfter) { setErrorString("FAILDEVICE"); return -1; - } - else { + } else { qint64 result = QBuffer::readData(data, len); if (result != -1) { m_readCount += result; @@ -51,8 +50,7 @@ qint64 FailDevice::writeData(const char* data, qint64 len) if (m_writeCount >= m_failAfter) { setErrorString("FAILDEVICE"); return -1; - } - else { + } else { qint64 result = QBuffer::writeData(data, len); if (result != -1) { m_writeCount += result; diff --git a/tests/TestAutoType.cpp b/tests/TestAutoType.cpp index 5eaed66a1..f59625d89 100644 --- a/tests/TestAutoType.cpp +++ b/tests/TestAutoType.cpp @@ -21,12 +21,12 @@ #include -#include "core/Config.h" -#include "core/FilePath.h" -#include "crypto/Crypto.h" #include "autotype/AutoType.h" #include "autotype/AutoTypePlatformPlugin.h" #include "autotype/test/AutoTypeTestInterface.h" +#include "core/Config.h" +#include "core/FilePath.h" +#include "crypto/Crypto.h" #include "gui/MessageBox.h" QTEST_GUILESS_MAIN(TestAutoType) @@ -94,10 +94,10 @@ void TestAutoType::init() m_entry4 = new Entry(); m_entry4->setGroup(m_group); m_entry4->setPassword("custom_attr"); - m_entry4->attributes()->set("CUSTOM","Attribute",false); - m_entry4->attributes()->set("CustomAttrFirst","AttrValueFirst",false); - m_entry4->attributes()->set("CustomAttrSecond","AttrValueSecond",false); - m_entry4->attributes()->set("CustomAttrThird","AttrValueThird",false); + m_entry4->attributes()->set("CUSTOM", "Attribute", false); + m_entry4->attributes()->set("CustomAttrFirst", "AttrValueFirst", false); + m_entry4->attributes()->set("CustomAttrSecond", "AttrValueSecond", false); + m_entry4->attributes()->set("CustomAttrThird", "AttrValueThird", false); association.window = "//^CustomAttr1$//"; association.sequence = "{PASSWORD}:{S:CUSTOM}"; m_entry4->autoTypeAssociations()->add(association); @@ -143,9 +143,7 @@ void TestAutoType::testSingleAutoType() QCOMPARE(m_test->actionCount(), 14); QCOMPARE(m_test->actionChars(), - QString("myuser%1mypass%2") - .arg(m_test->keyToString(Qt::Key_Tab)) - .arg(m_test->keyToString(Qt::Key_Enter))); + QString("myuser%1mypass%2").arg(m_test->keyToString(Qt::Key_Tab)).arg(m_test->keyToString(Qt::Key_Enter))); } void TestAutoType::testGlobalAutoTypeWithNoMatch() @@ -162,10 +160,7 @@ void TestAutoType::testGlobalAutoTypeWithOneMatch() m_test->setActiveWindowTitle("custom window"); m_autoType->performGlobalAutoType(m_dbList); - QCOMPARE(m_test->actionChars(), - QString("%1association%2") - .arg(m_entry1->username()) - .arg(m_entry1->password())); + QCOMPARE(m_test->actionChars(), QString("%1association%2").arg(m_entry1->username()).arg(m_entry1->password())); } void TestAutoType::testGlobalAutoTypeTitleMatch() @@ -175,8 +170,7 @@ void TestAutoType::testGlobalAutoTypeTitleMatch() m_test->setActiveWindowTitle("An Entry Title!"); m_autoType->performGlobalAutoType(m_dbList); - QCOMPARE(m_test->actionChars(), - QString("%1%2").arg(m_entry2->password(), m_test->keyToString(Qt::Key_Enter))); + QCOMPARE(m_test->actionChars(), QString("%1%2").arg(m_entry2->password(), m_test->keyToString(Qt::Key_Enter))); } void TestAutoType::testGlobalAutoTypeUrlMatch() @@ -186,8 +180,7 @@ void TestAutoType::testGlobalAutoTypeUrlMatch() m_test->setActiveWindowTitle("Dummy - http://example.org/ - "); m_autoType->performGlobalAutoType(m_dbList); - QCOMPARE(m_test->actionChars(), - QString("%1%2").arg(m_entry5->password(), m_test->keyToString(Qt::Key_Enter))); + QCOMPARE(m_test->actionChars(), QString("%1%2").arg(m_entry5->password(), m_test->keyToString(Qt::Key_Enter))); } void TestAutoType::testGlobalAutoTypeUrlSubdomainMatch() @@ -197,8 +190,7 @@ void TestAutoType::testGlobalAutoTypeUrlSubdomainMatch() m_test->setActiveWindowTitle("Dummy - http://sub.example.org/ - "); m_autoType->performGlobalAutoType(m_dbList); - QCOMPARE(m_test->actionChars(), - QString("%1%2").arg(m_entry5->password(), m_test->keyToString(Qt::Key_Enter))); + QCOMPARE(m_test->actionChars(), QString("%1%2").arg(m_entry5->password(), m_test->keyToString(Qt::Key_Enter))); } void TestAutoType::testGlobalAutoTypeTitleMatchDisabled() @@ -274,7 +266,8 @@ void TestAutoType::testGlobalAutoTypeRegExp() void TestAutoType::testAutoTypeSyntaxChecks() { // Huge sequence - QVERIFY(AutoType::checkSyntax("{word 23}{F1 23}{~ 23}{% 23}{^}{F12}{(}{) 23}{[}{[}{]}{Delay=23}{+}{SUBTRACT}~+%@fixedstring")); + QVERIFY(AutoType::checkSyntax( + "{word 23}{F1 23}{~ 23}{% 23}{^}{F12}{(}{) 23}{[}{[}{]}{Delay=23}{+}{SUBTRACT}~+%@fixedstring")); QVERIFY(AutoType::checkSyntax("{NUMPAD1 3}")); @@ -327,7 +320,7 @@ void TestAutoType::testAutoTypeEffectiveSequences() QPointer group1 = new Group(); group1->setParent(rootGroup); group1->setDefaultAutoTypeSequence(sequenceG1); - + // Child group with inherit QPointer group2 = new Group(); group2->setParent(group1); diff --git a/tests/TestCryptoHash.cpp b/tests/TestCryptoHash.cpp index 914bcf193..ac6cd7c7b 100644 --- a/tests/TestCryptoHash.cpp +++ b/tests/TestCryptoHash.cpp @@ -46,14 +46,17 @@ void TestCryptoHash::test() CryptoHash cryptoHash2(CryptoHash::Sha512); QCOMPARE(cryptoHash2.result(), - QByteArray::fromHex("cf83e1357eefb8bdf1542850d66d8007d620e4050b5715dc83f4a921d36ce9ce47d0d13c5d85f2b0ff8318d2877eec2f63b931bd47417a81a538327af927da3e")); + QByteArray::fromHex("cf83e1357eefb8bdf1542850d66d8007d620e4050b5715dc83f4a921d36ce9ce47d0d13c5d85f2b0ff831" + "8d2877eec2f63b931bd47417a81a538327af927da3e")); QByteArray result3 = CryptoHash::hash(source2, CryptoHash::Sha512); - QCOMPARE(result3, QByteArray::fromHex("0d41b612584ed39ff72944c29494573e40f4bb95283455fae2e0be1e3565aa9f48057d59e6ffd777970e282871c25a549a2763e5b724794f312c97021c42f91d")); + QCOMPARE(result3, QByteArray::fromHex("0d41b612584ed39ff72944c29494573e40f4bb95283455fae2e0be1e3565aa9f48057d59e6ff" + "d777970e282871c25a549a2763e5b724794f312c97021c42f91d")); CryptoHash cryptoHash4(CryptoHash::Sha512); cryptoHash4.addData(QString("KeePa").toLatin1()); cryptoHash4.addData(QString("ssX").toLatin1()); QCOMPARE(cryptoHash4.result(), - QByteArray::fromHex("0d41b612584ed39ff72944c29494573e40f4bb95283455fae2e0be1e3565aa9f48057d59e6ffd777970e282871c25a549a2763e5b724794f312c97021c42f91d")); + QByteArray::fromHex("0d41b612584ed39ff72944c29494573e40f4bb95283455fae2e0be1e3565aa9f48057d59e6ffd777970e2" + "82871c25a549a2763e5b724794f312c97021c42f91d")); } diff --git a/tests/TestCsvExporter.cpp b/tests/TestCsvExporter.cpp index b85dbf268..732e2636d 100644 --- a/tests/TestCsvExporter.cpp +++ b/tests/TestCsvExporter.cpp @@ -26,7 +26,8 @@ QTEST_GUILESS_MAIN(TestCsvExporter) -const QString TestCsvExporter::ExpectedHeaderLine = QString("\"Group\",\"Title\",\"Username\",\"Password\",\"URL\",\"Notes\"\n"); +const QString TestCsvExporter::ExpectedHeaderLine = + QString("\"Group\",\"Title\",\"Username\",\"Password\",\"URL\",\"Notes\"\n"); void TestCsvExporter::init() { @@ -63,7 +64,9 @@ void TestCsvExporter::testExport() QVERIFY(buffer.open(QIODevice::ReadWrite)); m_csvExporter->exportDatabase(&buffer, m_db); - QString expectedResult = QString().append(ExpectedHeaderLine).append("\"Test Group Name\",\"Test Entry Title\",\"Test Username\",\"Test Password\",\"http://test.url\",\"Test Notes\"\n"); + QString expectedResult = + QString().append(ExpectedHeaderLine).append("\"Test Group Name\",\"Test Entry Title\",\"Test Username\",\"Test " + "Password\",\"http://test.url\",\"Test Notes\"\n"); QCOMPARE(QString::fromUtf8(buffer.buffer().constData()), expectedResult); } @@ -94,5 +97,8 @@ void TestCsvExporter::testNestedGroups() QVERIFY(buffer.open(QIODevice::ReadWrite)); m_csvExporter->exportDatabase(&buffer, m_db); - QCOMPARE(QString::fromUtf8(buffer.buffer().constData()), QString().append(ExpectedHeaderLine).append("\"Test Group Name/Test Sub Group Name\",\"Test Entry Title\",\"\",\"\",\"\",\"\"\n")); + QCOMPARE(QString::fromUtf8(buffer.buffer().constData()), + QString() + .append(ExpectedHeaderLine) + .append("\"Test Group Name/Test Sub Group Name\",\"Test Entry Title\",\"\",\"\",\"\",\"\"\n")); } diff --git a/tests/TestCsvParser.cpp b/tests/TestCsvParser.cpp index 705ef48c3..46d254098 100644 --- a/tests/TestCsvParser.cpp +++ b/tests/TestCsvParser.cpp @@ -44,7 +44,8 @@ void TestCsvParser::cleanup() } /****************** TEST CASES ******************/ -void TestCsvParser::testMissingQuote() { +void TestCsvParser::testMissingQuote() +{ parser->setTextQualifier(':'); QTextStream out(file.data()); out << "A,B\n:BM,1"; @@ -54,7 +55,8 @@ void TestCsvParser::testMissingQuote() { QWARN(parser->getStatus().toLatin1()); } -void TestCsvParser::testMalformed() { +void TestCsvParser::testMalformed() +{ parser->setTextQualifier(':'); QTextStream out(file.data()); out << "A,B,C\n:BM::,1,:2:"; @@ -64,11 +66,12 @@ void TestCsvParser::testMalformed() { QWARN(parser->getStatus().toLatin1()); } -void TestCsvParser::testBackslashSyntax() { +void TestCsvParser::testBackslashSyntax() +{ parser->setBackslashSyntax(true); parser->setTextQualifier(QChar('X')); QTextStream out(file.data()); - //attended result: one"\t\"wo + // attended result: one"\t\"wo out << "Xone\\\"\\\\t\\\\\\\"w\noX\n" << "X13X,X2\\X,X,\"\"3\"X\r" << "3,X\"4\"X,,\n" @@ -88,7 +91,8 @@ void TestCsvParser::testBackslashSyntax() { QVERIFY(t.size() == 4); } -void TestCsvParser::testQuoted() { +void TestCsvParser::testQuoted() +{ QTextStream out(file.data()); out << "ro,w,\"end, of \"\"\"\"\"\"row\"\"\"\"\"\n" << "2\n"; @@ -101,25 +105,28 @@ void TestCsvParser::testQuoted() { QVERIFY(t.size() == 2); } -void TestCsvParser::testEmptySimple() { +void TestCsvParser::testEmptySimple() +{ QTextStream out(file.data()); - out <<""; + out << ""; QVERIFY(parser->parse(file.data())); t = parser->getCsvTable(); QVERIFY(t.size() == 0); } -void TestCsvParser::testEmptyQuoted() { +void TestCsvParser::testEmptyQuoted() +{ QTextStream out(file.data()); - out <<"\"\""; + out << "\"\""; QVERIFY(parser->parse(file.data())); t = parser->getCsvTable(); QVERIFY(t.size() == 0); } -void TestCsvParser::testEmptyNewline() { +void TestCsvParser::testEmptyNewline() +{ QTextStream out(file.data()); - out <<"\"\n\""; + out << "\"\n\""; QVERIFY(parser->parse(file.data())); t = parser->getCsvTable(); QVERIFY(t.size() == 0); @@ -197,7 +204,8 @@ void TestCsvParser::testComments() QVERIFY(t.at(0).at(1) == "text #1!"); } -void TestCsvParser::testColumns() { +void TestCsvParser::testColumns() +{ QTextStream out(file.data()); out << "1,2\n" << ",,,,,,,,,a\n" @@ -207,7 +215,8 @@ void TestCsvParser::testColumns() { QVERIFY(parser->getCsvCols() == 10); } -void TestCsvParser::testSimple() { +void TestCsvParser::testSimple() +{ QTextStream out(file.data()); out << ",,2\r,2,3\n" << "A,,B\"\n" @@ -229,7 +238,8 @@ void TestCsvParser::testSimple() { QVERIFY(t.at(3).at(2) == ""); } -void TestCsvParser::testSeparator() { +void TestCsvParser::testSeparator() +{ parser->setFieldSeparator('\t'); QTextStream out(file.data()); out << "\t\t2\r\t2\t3\n" @@ -296,7 +306,8 @@ void TestCsvParser::testReparsing() QVERIFY(t.size() == 2); } -void TestCsvParser::testQualifier() { +void TestCsvParser::testQualifier() +{ parser->setTextQualifier(QChar('X')); QTextStream out(file.data()); out << "X1X,X2XX,X,\"\"3\"\"\"X\r" @@ -313,11 +324,12 @@ void TestCsvParser::testQualifier() { QVERIFY(t.at(1).at(3) == ""); } -void TestCsvParser::testUnicode() { - //QString m("Texte en fran\u00e7ais"); - //CORRECT QString g("\u20AC"); - //CORRECT QChar g(0x20AC); - //ERROR QChar g("\u20AC"); +void TestCsvParser::testUnicode() +{ + // QString m("Texte en fran\u00e7ais"); + // CORRECT QString g("\u20AC"); + // CORRECT QChar g(0x20AC); + // ERROR QChar g("\u20AC"); parser->setFieldSeparator(QChar('A')); QTextStream out(file.data()); out.setCodec("UTF-8"); diff --git a/tests/TestCsvParser.h b/tests/TestCsvParser.h index f8c327d63..9db091666 100644 --- a/tests/TestCsvParser.h +++ b/tests/TestCsvParser.h @@ -19,10 +19,10 @@ #ifndef KEEPASSX_TESTCSVPARSER_H #define KEEPASSX_TESTCSVPARSER_H -#include #include -#include +#include #include +#include #include "core/CsvParser.h" @@ -33,7 +33,6 @@ class TestCsvParser : public QObject Q_OBJECT public: - private slots: void init(); void cleanup(); diff --git a/tests/TestDatabase.cpp b/tests/TestDatabase.cpp index 4aae91dc2..51304b1fb 100644 --- a/tests/TestDatabase.cpp +++ b/tests/TestDatabase.cpp @@ -23,10 +23,10 @@ #include #include "config-keepassx-tests.h" -#include "crypto/Crypto.h" -#include "keys/PasswordKey.h" #include "core/Metadata.h" +#include "crypto/Crypto.h" #include "format/KeePass2Writer.h" +#include "keys/PasswordKey.h" QTEST_GUILESS_MAIN(TestDatabase) @@ -46,7 +46,7 @@ void TestDatabase::testEmptyRecycleBinOnDisabled() QSignalSpy spyModified(db, SIGNAL(modifiedImmediate())); db->emptyRecycleBin(); - //The database must be unmodified in this test after emptying the recycle bin. + // The database must be unmodified in this test after emptying the recycle bin. QCOMPARE(spyModified.count(), 0); delete db; @@ -63,7 +63,7 @@ void TestDatabase::testEmptyRecycleBinOnNotCreated() QSignalSpy spyModified(db, SIGNAL(modifiedImmediate())); db->emptyRecycleBin(); - //The database must be unmodified in this test after emptying the recycle bin. + // The database must be unmodified in this test after emptying the recycle bin. QCOMPARE(spyModified.count(), 0); delete db; @@ -80,7 +80,7 @@ void TestDatabase::testEmptyRecycleBinOnEmpty() QSignalSpy spyModified(db, SIGNAL(modifiedImmediate())); db->emptyRecycleBin(); - //The database must be unmodified in this test after emptying the recycle bin. + // The database must be unmodified in this test after emptying the recycle bin. QCOMPARE(spyModified.count(), 0); delete db; diff --git a/tests/TestDeletedObjects.cpp b/tests/TestDeletedObjects.cpp index ee9d8de2c..50ff18450 100644 --- a/tests/TestDeletedObjects.cpp +++ b/tests/TestDeletedObjects.cpp @@ -18,10 +18,10 @@ #include "TestDeletedObjects.h" #include "TestGlobal.h" -#include "crypto/Crypto.h" -#include "format/KeePass2.h" -#include "format/KdbxXmlReader.h" #include "config-keepassx-tests.h" +#include "crypto/Crypto.h" +#include "format/KdbxXmlReader.h" +#include "format/KeePass2.h" QTEST_GUILESS_MAIN(TestDeletedObjects) @@ -42,7 +42,7 @@ void TestDeletedObjects::createAndDelete(Database* db, int delObjectsSize) g->setUuid(gUuid); delete g; QCOMPARE(db->deletedObjects().size(), ++delObjectsSize); - QCOMPARE(db->deletedObjects().at(delObjectsSize-1).uuid, gUuid); + QCOMPARE(db->deletedObjects().at(delObjectsSize - 1).uuid, gUuid); QCOMPARE(rootChildrenCount, root->children().size()); Group* g1 = new Group(); @@ -66,10 +66,10 @@ void TestDeletedObjects::createAndDelete(Database* db, int delObjectsSize) delObjectsSize += 4; QCOMPARE(db->deletedObjects().size(), delObjectsSize); - QCOMPARE(db->deletedObjects().at(delObjectsSize-4).uuid, e1Uuid); - QCOMPARE(db->deletedObjects().at(delObjectsSize-3).uuid, e2Uuid); - QCOMPARE(db->deletedObjects().at(delObjectsSize-2).uuid, g2Uuid); - QCOMPARE(db->deletedObjects().at(delObjectsSize-1).uuid, g1Uuid); + QCOMPARE(db->deletedObjects().at(delObjectsSize - 4).uuid, e1Uuid); + QCOMPARE(db->deletedObjects().at(delObjectsSize - 3).uuid, e2Uuid); + QCOMPARE(db->deletedObjects().at(delObjectsSize - 2).uuid, g2Uuid); + QCOMPARE(db->deletedObjects().at(delObjectsSize - 1).uuid, g1Uuid); QCOMPARE(rootChildrenCount, root->children().size()); Entry* e3 = new Entry(); @@ -80,7 +80,7 @@ void TestDeletedObjects::createAndDelete(Database* db, int delObjectsSize) delete e3; QCOMPARE(db->deletedObjects().size(), ++delObjectsSize); - QCOMPARE(db->deletedObjects().at(delObjectsSize-1).uuid, e3Uuid); + QCOMPARE(db->deletedObjects().at(delObjectsSize - 1).uuid, e3Uuid); QCOMPARE(rootChildrenCount, root->children().size()); } @@ -143,8 +143,8 @@ void TestDeletedObjects::testDatabaseChange() delObjectsSize += 2; QCOMPARE(db->deletedObjects().size(), delObjectsSize); QCOMPARE(db2->deletedObjects().size(), delObjectsSize2); - QCOMPARE(db->deletedObjects().at(delObjectsSize-2).uuid, e1Uuid); - QCOMPARE(db->deletedObjects().at(delObjectsSize-1).uuid, g1Uuid); + QCOMPARE(db->deletedObjects().at(delObjectsSize - 2).uuid, e1Uuid); + QCOMPARE(db->deletedObjects().at(delObjectsSize - 1).uuid, g1Uuid); Group* group = new Group(); Entry* entry = new Entry(); diff --git a/tests/TestEntry.cpp b/tests/TestEntry.cpp index c088fc01f..6ece366ba 100644 --- a/tests/TestEntry.cpp +++ b/tests/TestEntry.cpp @@ -337,52 +337,78 @@ void TestEntry::testResolveReferencePlaceholders() tstEntry->setGroup(root); tstEntry->setUuid(Uuid::random()); - QCOMPARE(tstEntry->resolveMultiplePlaceholders(QString("{REF:T@I:%1}").arg(entry1->uuid().toHex())), entry1->title()); + QCOMPARE(tstEntry->resolveMultiplePlaceholders(QString("{REF:T@I:%1}").arg(entry1->uuid().toHex())), + entry1->title()); QCOMPARE(tstEntry->resolveMultiplePlaceholders(QString("{REF:T@T:%1}").arg(entry1->title())), entry1->title()); QCOMPARE(tstEntry->resolveMultiplePlaceholders(QString("{REF:T@U:%1}").arg(entry1->username())), entry1->title()); QCOMPARE(tstEntry->resolveMultiplePlaceholders(QString("{REF:T@P:%1}").arg(entry1->password())), entry1->title()); QCOMPARE(tstEntry->resolveMultiplePlaceholders(QString("{REF:T@A:%1}").arg(entry1->url())), entry1->title()); QCOMPARE(tstEntry->resolveMultiplePlaceholders(QString("{REF:T@N:%1}").arg(entry1->notes())), entry1->title()); - QCOMPARE(tstEntry->resolveMultiplePlaceholders(QString("{REF:T@O:%1}").arg(entry1->attributes()->value("CustomAttribute1"))), entry1->title()); + QCOMPARE(tstEntry->resolveMultiplePlaceholders( + QString("{REF:T@O:%1}").arg(entry1->attributes()->value("CustomAttribute1"))), + entry1->title()); - QCOMPARE(tstEntry->resolveMultiplePlaceholders(QString("{REF:T@I:%1}").arg(entry1->uuid().toHex())), entry1->title()); + QCOMPARE(tstEntry->resolveMultiplePlaceholders(QString("{REF:T@I:%1}").arg(entry1->uuid().toHex())), + entry1->title()); QCOMPARE(tstEntry->resolveMultiplePlaceholders(QString("{REF:T@T:%1}").arg(entry1->title())), entry1->title()); - QCOMPARE(tstEntry->resolveMultiplePlaceholders(QString("{REF:U@U:%1}").arg(entry1->username())), entry1->username()); - QCOMPARE(tstEntry->resolveMultiplePlaceholders(QString("{REF:P@P:%1}").arg(entry1->password())), entry1->password()); + QCOMPARE(tstEntry->resolveMultiplePlaceholders(QString("{REF:U@U:%1}").arg(entry1->username())), + entry1->username()); + QCOMPARE(tstEntry->resolveMultiplePlaceholders(QString("{REF:P@P:%1}").arg(entry1->password())), + entry1->password()); QCOMPARE(tstEntry->resolveMultiplePlaceholders(QString("{REF:A@A:%1}").arg(entry1->url())), entry1->url()); QCOMPARE(tstEntry->resolveMultiplePlaceholders(QString("{REF:N@N:%1}").arg(entry1->notes())), entry1->notes()); - QCOMPARE(tstEntry->resolveMultiplePlaceholders(QString("{REF:T@I:%1}").arg(entry2->uuid().toHex())), entry2->title()); + QCOMPARE(tstEntry->resolveMultiplePlaceholders(QString("{REF:T@I:%1}").arg(entry2->uuid().toHex())), + entry2->title()); QCOMPARE(tstEntry->resolveMultiplePlaceholders(QString("{REF:T@T:%1}").arg(entry2->title())), entry2->title()); QCOMPARE(tstEntry->resolveMultiplePlaceholders(QString("{REF:T@U:%1}").arg(entry2->username())), entry2->title()); QCOMPARE(tstEntry->resolveMultiplePlaceholders(QString("{REF:T@P:%1}").arg(entry2->password())), entry2->title()); QCOMPARE(tstEntry->resolveMultiplePlaceholders(QString("{REF:T@A:%1}").arg(entry2->url())), entry2->title()); QCOMPARE(tstEntry->resolveMultiplePlaceholders(QString("{REF:T@N:%1}").arg(entry2->notes())), entry2->title()); - QCOMPARE(tstEntry->resolveMultiplePlaceholders(QString("{REF:T@O:%1}").arg(entry2->attributes()->value("CustomAttribute2"))), entry2->title()); + QCOMPARE(tstEntry->resolveMultiplePlaceholders( + QString("{REF:T@O:%1}").arg(entry2->attributes()->value("CustomAttribute2"))), + entry2->title()); QCOMPARE(tstEntry->resolveMultiplePlaceholders(QString("{REF:T@T:%1}").arg(entry2->title())), entry2->title()); - QCOMPARE(tstEntry->resolveMultiplePlaceholders(QString("{REF:U@U:%1}").arg(entry2->username())), entry2->username()); - QCOMPARE(tstEntry->resolveMultiplePlaceholders(QString("{REF:P@P:%1}").arg(entry2->password())), entry2->password()); + QCOMPARE(tstEntry->resolveMultiplePlaceholders(QString("{REF:U@U:%1}").arg(entry2->username())), + entry2->username()); + QCOMPARE(tstEntry->resolveMultiplePlaceholders(QString("{REF:P@P:%1}").arg(entry2->password())), + entry2->password()); QCOMPARE(tstEntry->resolveMultiplePlaceholders(QString("{REF:A@A:%1}").arg(entry2->url())), entry2->url()); QCOMPARE(tstEntry->resolveMultiplePlaceholders(QString("{REF:N@N:%1}").arg(entry2->notes())), entry2->notes()); - QCOMPARE(tstEntry->resolveMultiplePlaceholders(QString("{REF:T@I:%1}").arg(entry3->uuid().toHex())), entry3->attributes()->value("AttributeTitle")); - QCOMPARE(tstEntry->resolveMultiplePlaceholders(QString("{REF:U@I:%1}").arg(entry3->uuid().toHex())), entry3->attributes()->value("AttributeUsername")); - QCOMPARE(tstEntry->resolveMultiplePlaceholders(QString("{REF:P@I:%1}").arg(entry3->uuid().toHex())), entry3->attributes()->value("AttributePassword")); - QCOMPARE(tstEntry->resolveMultiplePlaceholders(QString("{REF:A@I:%1}").arg(entry3->uuid().toHex())), entry3->attributes()->value("AttributeUrl")); - QCOMPARE(tstEntry->resolveMultiplePlaceholders(QString("{REF:N@I:%1}").arg(entry3->uuid().toHex())), entry3->attributes()->value("AttributeNotes")); + QCOMPARE(tstEntry->resolveMultiplePlaceholders(QString("{REF:T@I:%1}").arg(entry3->uuid().toHex())), + entry3->attributes()->value("AttributeTitle")); + QCOMPARE(tstEntry->resolveMultiplePlaceholders(QString("{REF:U@I:%1}").arg(entry3->uuid().toHex())), + entry3->attributes()->value("AttributeUsername")); + QCOMPARE(tstEntry->resolveMultiplePlaceholders(QString("{REF:P@I:%1}").arg(entry3->uuid().toHex())), + entry3->attributes()->value("AttributePassword")); + QCOMPARE(tstEntry->resolveMultiplePlaceholders(QString("{REF:A@I:%1}").arg(entry3->uuid().toHex())), + entry3->attributes()->value("AttributeUrl")); + QCOMPARE(tstEntry->resolveMultiplePlaceholders(QString("{REF:N@I:%1}").arg(entry3->uuid().toHex())), + entry3->attributes()->value("AttributeNotes")); - QCOMPARE(tstEntry->resolveMultiplePlaceholders(QString("{REF:T@I:%1}").arg(entry3->uuid().toHex().toUpper())), entry3->attributes()->value("AttributeTitle")); - QCOMPARE(tstEntry->resolveMultiplePlaceholders(QString("{REF:U@I:%1}").arg(entry3->uuid().toHex().toUpper())), entry3->attributes()->value("AttributeUsername")); - QCOMPARE(tstEntry->resolveMultiplePlaceholders(QString("{REF:P@I:%1}").arg(entry3->uuid().toHex().toUpper())), entry3->attributes()->value("AttributePassword")); - QCOMPARE(tstEntry->resolveMultiplePlaceholders(QString("{REF:A@I:%1}").arg(entry3->uuid().toHex().toUpper())), entry3->attributes()->value("AttributeUrl")); - QCOMPARE(tstEntry->resolveMultiplePlaceholders(QString("{REF:N@I:%1}").arg(entry3->uuid().toHex().toUpper())), entry3->attributes()->value("AttributeNotes")); + QCOMPARE(tstEntry->resolveMultiplePlaceholders(QString("{REF:T@I:%1}").arg(entry3->uuid().toHex().toUpper())), + entry3->attributes()->value("AttributeTitle")); + QCOMPARE(tstEntry->resolveMultiplePlaceholders(QString("{REF:U@I:%1}").arg(entry3->uuid().toHex().toUpper())), + entry3->attributes()->value("AttributeUsername")); + QCOMPARE(tstEntry->resolveMultiplePlaceholders(QString("{REF:P@I:%1}").arg(entry3->uuid().toHex().toUpper())), + entry3->attributes()->value("AttributePassword")); + QCOMPARE(tstEntry->resolveMultiplePlaceholders(QString("{REF:A@I:%1}").arg(entry3->uuid().toHex().toUpper())), + entry3->attributes()->value("AttributeUrl")); + QCOMPARE(tstEntry->resolveMultiplePlaceholders(QString("{REF:N@I:%1}").arg(entry3->uuid().toHex().toUpper())), + entry3->attributes()->value("AttributeNotes")); - QCOMPARE(tstEntry->resolveMultiplePlaceholders(QString("{REF:t@i:%1}").arg(entry3->uuid().toHex().toLower())), entry3->attributes()->value("AttributeTitle")); - QCOMPARE(tstEntry->resolveMultiplePlaceholders(QString("{REF:u@i:%1}").arg(entry3->uuid().toHex().toLower())), entry3->attributes()->value("AttributeUsername")); - QCOMPARE(tstEntry->resolveMultiplePlaceholders(QString("{REF:p@i:%1}").arg(entry3->uuid().toHex().toLower())), entry3->attributes()->value("AttributePassword")); - QCOMPARE(tstEntry->resolveMultiplePlaceholders(QString("{REF:a@i:%1}").arg(entry3->uuid().toHex().toLower())), entry3->attributes()->value("AttributeUrl")); - QCOMPARE(tstEntry->resolveMultiplePlaceholders(QString("{REF:n@i:%1}").arg(entry3->uuid().toHex().toLower())), entry3->attributes()->value("AttributeNotes")); + QCOMPARE(tstEntry->resolveMultiplePlaceholders(QString("{REF:t@i:%1}").arg(entry3->uuid().toHex().toLower())), + entry3->attributes()->value("AttributeTitle")); + QCOMPARE(tstEntry->resolveMultiplePlaceholders(QString("{REF:u@i:%1}").arg(entry3->uuid().toHex().toLower())), + entry3->attributes()->value("AttributeUsername")); + QCOMPARE(tstEntry->resolveMultiplePlaceholders(QString("{REF:p@i:%1}").arg(entry3->uuid().toHex().toLower())), + entry3->attributes()->value("AttributePassword")); + QCOMPARE(tstEntry->resolveMultiplePlaceholders(QString("{REF:a@i:%1}").arg(entry3->uuid().toHex().toLower())), + entry3->attributes()->value("AttributeUrl")); + QCOMPARE(tstEntry->resolveMultiplePlaceholders(QString("{REF:n@i:%1}").arg(entry3->uuid().toHex().toLower())), + entry3->attributes()->value("AttributeNotes")); } void TestEntry::testResolveNonIdPlaceholdersToUuid() @@ -420,37 +446,36 @@ void TestEntry::testResolveNonIdPlaceholdersToUuid() const Entry* referencedEntry = nullptr; QString newEntryNotesRaw("{REF:I@%1:%2}"); - switch(searchIn.toLatin1()) { - case 'T': - referencedEntry = referencedEntryTitle; - newEntryNotesRaw = newEntryNotesRaw.arg(searchIn, referencedEntry->title()); - break; - case 'U': - referencedEntry = referencedEntryUsername; - newEntryNotesRaw = newEntryNotesRaw.arg(searchIn, referencedEntry->username()); - break; - case 'P': - referencedEntry = referencedEntryPassword; - newEntryNotesRaw = newEntryNotesRaw.arg(searchIn, referencedEntry->password()); - break; - case 'A': - referencedEntry = referencedEntryUrl; - newEntryNotesRaw = newEntryNotesRaw.arg(searchIn, referencedEntry->url()); - break; - case 'N': - referencedEntry = referencedEntryNotes; - newEntryNotesRaw = newEntryNotesRaw.arg(searchIn, referencedEntry->notes()); - break; - default: - break; + switch (searchIn.toLatin1()) { + case 'T': + referencedEntry = referencedEntryTitle; + newEntryNotesRaw = newEntryNotesRaw.arg(searchIn, referencedEntry->title()); + break; + case 'U': + referencedEntry = referencedEntryUsername; + newEntryNotesRaw = newEntryNotesRaw.arg(searchIn, referencedEntry->username()); + break; + case 'P': + referencedEntry = referencedEntryPassword; + newEntryNotesRaw = newEntryNotesRaw.arg(searchIn, referencedEntry->password()); + break; + case 'A': + referencedEntry = referencedEntryUrl; + newEntryNotesRaw = newEntryNotesRaw.arg(searchIn, referencedEntry->url()); + break; + case 'N': + referencedEntry = referencedEntryNotes; + newEntryNotesRaw = newEntryNotesRaw.arg(searchIn, referencedEntry->notes()); + break; + default: + break; } auto* newEntry = new Entry(); newEntry->setGroup(root); newEntry->setNotes(newEntryNotesRaw); - const QString newEntryNotesResolved = - newEntry->resolveMultiplePlaceholders(newEntry->notes()); + const QString newEntryNotesResolved = newEntry->resolveMultiplePlaceholders(newEntry->notes()); QCOMPARE(newEntryNotesResolved, QString(referencedEntry->uuid().toHex())); } } diff --git a/tests/TestEntryModel.cpp b/tests/TestEntryModel.cpp index d290507f1..6bc65db48 100644 --- a/tests/TestEntryModel.cpp +++ b/tests/TestEntryModel.cpp @@ -20,7 +20,6 @@ #include -#include "modeltest.h" #include "core/DatabaseIcons.h" #include "core/Entry.h" #include "core/Group.h" @@ -28,9 +27,10 @@ #include "gui/IconModels.h" #include "gui/SortFilterHideProxyModel.h" #include "gui/entry/AutoTypeAssociationsModel.h" -#include "gui/entry/EntryModel.h" #include "gui/entry/EntryAttachmentsModel.h" #include "gui/entry/EntryAttributesModel.h" +#include "gui/entry/EntryModel.h" +#include "modeltest.h" QTEST_GUILESS_MAIN(TestEntryModel) @@ -61,7 +61,7 @@ void TestEntryModel::test() QCOMPARE(model->rowCount(), 2); - QSignalSpy spyDataChanged(model, SIGNAL(dataChanged(QModelIndex,QModelIndex))); + QSignalSpy spyDataChanged(model, SIGNAL(dataChanged(QModelIndex, QModelIndex))); entry1->setTitle("changed"); QCOMPARE(spyDataChanged.count(), 1); @@ -71,10 +71,10 @@ void TestEntryModel::test() QCOMPARE(model->data(index1).toString(), entry1->title()); QCOMPARE(model->data(index2).toString(), entry2->title()); - QSignalSpy spyAboutToAdd(model, SIGNAL(rowsAboutToBeInserted(QModelIndex,int,int))); - QSignalSpy spyAdded(model, SIGNAL(rowsInserted(QModelIndex,int,int))); - QSignalSpy spyAboutToRemove(model, SIGNAL(rowsAboutToBeRemoved(QModelIndex,int,int))); - QSignalSpy spyRemoved(model, SIGNAL(rowsRemoved(QModelIndex,int,int))); + QSignalSpy spyAboutToAdd(model, SIGNAL(rowsAboutToBeInserted(QModelIndex, int, int))); + QSignalSpy spyAdded(model, SIGNAL(rowsInserted(QModelIndex, int, int))); + QSignalSpy spyAboutToRemove(model, SIGNAL(rowsAboutToBeRemoved(QModelIndex, int, int))); + QSignalSpy spyRemoved(model, SIGNAL(rowsRemoved(QModelIndex, int, int))); Entry* entry3 = new Entry(); entry3->setGroup(group1); @@ -113,11 +113,11 @@ void TestEntryModel::testAttachmentsModel() model->setEntryAttachments(entryAttachments); QCOMPARE(model->rowCount(), 0); - QSignalSpy spyDataChanged(model, SIGNAL(dataChanged(QModelIndex,QModelIndex))); - QSignalSpy spyAboutToAdd(model, SIGNAL(rowsAboutToBeInserted(QModelIndex,int,int))); - QSignalSpy spyAdded(model, SIGNAL(rowsInserted(QModelIndex,int,int))); - QSignalSpy spyAboutToRemove(model, SIGNAL(rowsAboutToBeRemoved(QModelIndex,int,int))); - QSignalSpy spyRemoved(model, SIGNAL(rowsRemoved(QModelIndex,int,int))); + QSignalSpy spyDataChanged(model, SIGNAL(dataChanged(QModelIndex, QModelIndex))); + QSignalSpy spyAboutToAdd(model, SIGNAL(rowsAboutToBeInserted(QModelIndex, int, int))); + QSignalSpy spyAdded(model, SIGNAL(rowsInserted(QModelIndex, int, int))); + QSignalSpy spyAboutToRemove(model, SIGNAL(rowsAboutToBeRemoved(QModelIndex, int, int))); + QSignalSpy spyRemoved(model, SIGNAL(rowsRemoved(QModelIndex, int, int))); entryAttachments->set("first", QByteArray("123")); @@ -158,11 +158,11 @@ void TestEntryModel::testAttributesModel() model->setEntryAttributes(entryAttributes); QCOMPARE(model->rowCount(), 0); - QSignalSpy spyDataChanged(model, SIGNAL(dataChanged(QModelIndex,QModelIndex))); - QSignalSpy spyAboutToAdd(model, SIGNAL(rowsAboutToBeInserted(QModelIndex,int,int))); - QSignalSpy spyAdded(model, SIGNAL(rowsInserted(QModelIndex,int,int))); - QSignalSpy spyAboutToRemove(model, SIGNAL(rowsAboutToBeRemoved(QModelIndex,int,int))); - QSignalSpy spyRemoved(model, SIGNAL(rowsRemoved(QModelIndex,int,int))); + QSignalSpy spyDataChanged(model, SIGNAL(dataChanged(QModelIndex, QModelIndex))); + QSignalSpy spyAboutToAdd(model, SIGNAL(rowsAboutToBeInserted(QModelIndex, int, int))); + QSignalSpy spyAdded(model, SIGNAL(rowsInserted(QModelIndex, int, int))); + QSignalSpy spyAboutToRemove(model, SIGNAL(rowsAboutToBeRemoved(QModelIndex, int, int))); + QSignalSpy spyRemoved(model, SIGNAL(rowsRemoved(QModelIndex, int, int))); entryAttributes->set("first", "123"); @@ -294,7 +294,7 @@ void TestEntryModel::testProxyModel() * additional columns 'Password', 'Notes', 'Expires', 'Created', 'Modified', * 'Accessed', 'Paperclip' and 'Attachments' */ - QSignalSpy spyColumnRemove(modelProxy, SIGNAL(columnsAboutToBeRemoved(QModelIndex,int,int))); + QSignalSpy spyColumnRemove(modelProxy, SIGNAL(columnsAboutToBeRemoved(QModelIndex, int, int))); modelProxy->hideColumn(0, true); QCOMPARE(modelProxy->columnCount(), 11); QVERIFY(spyColumnRemove.size() >= 1); @@ -316,7 +316,7 @@ void TestEntryModel::testProxyModel() * additional columns 'Password', 'Notes', 'Expires', 'Created', 'Modified', * 'Accessed', 'Paperclip' and 'Attachments' */ - QSignalSpy spyColumnInsert(modelProxy, SIGNAL(columnsAboutToBeInserted(QModelIndex,int,int))); + QSignalSpy spyColumnInsert(modelProxy, SIGNAL(columnsAboutToBeInserted(QModelIndex, int, int))); modelProxy->hideColumn(0, false); QCOMPARE(modelProxy->columnCount(), 12); QVERIFY(spyColumnInsert.size() >= 1); diff --git a/tests/TestEntrySearcher.cpp b/tests/TestEntrySearcher.cpp index 25d83e4d2..659f7a489 100644 --- a/tests/TestEntrySearcher.cpp +++ b/tests/TestEntrySearcher.cpp @@ -136,6 +136,7 @@ void TestEntrySearcher::testAllAttributesAreSearched() entry->setUrl("testUrl"); entry->setNotes("testNote"); - m_searchResult = m_entrySearcher.search("testTitle testUsername testUrl testNote", m_groupRoot, Qt::CaseInsensitive); + m_searchResult = + m_entrySearcher.search("testTitle testUsername testUrl testNote", m_groupRoot, Qt::CaseInsensitive); QCOMPARE(m_searchResult.count(), 1); } diff --git a/tests/TestEntrySearcher.h b/tests/TestEntrySearcher.h index 3965c22e0..17d486c22 100644 --- a/tests/TestEntrySearcher.h +++ b/tests/TestEntrySearcher.h @@ -15,7 +15,6 @@ * along with this program. If not, see . */ - #ifndef KEEPASSX_TESTENTRYSEARCHER_H #define KEEPASSX_TESTENTRYSEARCHER_H diff --git a/tests/TestGlobal.h b/tests/TestGlobal.h index 017fbd5f9..788bd8a13 100644 --- a/tests/TestGlobal.h +++ b/tests/TestGlobal.h @@ -18,52 +18,48 @@ #ifndef KEEPASSXC_TESTGLOBAL_H #define KEEPASSXC_TESTGLOBAL_H -#include "core/Uuid.h" #include "core/Group.h" +#include "core/Uuid.h" -#include #include +#include -namespace QTest { - -template<> -inline char* toString(const Uuid& uuid) +namespace QTest { - QByteArray ba = "Uuid("; - ba += uuid.toHex().toLatin1().constData(); - ba += ")"; - return qstrdup(ba.constData()); -} -template<> -inline char* toString(const Group::TriState& triState) -{ - QString value; - - if (triState == Group::Inherit) { - value = "null"; - } else if (triState == Group::Enable) { - value = "true"; - } else { - value = "false"; + template <> inline char* toString(const Uuid& uuid) + { + QByteArray ba = "Uuid("; + ba += uuid.toHex().toLatin1().constData(); + ba += ")"; + return qstrdup(ba.constData()); } - return qstrdup(value.toLocal8Bit().constData()); -} + template <> inline char* toString(const Group::TriState& triState) + { + QString value; -} // namespace QTest + if (triState == Group::Inherit) { + value = "null"; + } else if (triState == Group::Enable) { + value = "true"; + } else { + value = "false"; + } + return qstrdup(value.toLocal8Bit().constData()); + } -namespace Test { +} // namespace QTest -inline QDateTime datetime(int year, int month, int day, int hour, int min, int second) +namespace Test { - return QDateTime( - QDate(year, month, day), - QTime(hour, min, second), - Qt::UTC); -} -} // namespace Test + inline QDateTime datetime(int year, int month, int day, int hour, int min, int second) + { + return QDateTime(QDate(year, month, day), QTime(hour, min, second), Qt::UTC); + } -#endif //KEEPASSXC_TESTGLOBAL_H +} // namespace Test + +#endif // KEEPASSXC_TESTGLOBAL_H diff --git a/tests/TestGroup.cpp b/tests/TestGroup.cpp index d9eb2c765..0058c7119 100644 --- a/tests/TestGroup.cpp +++ b/tests/TestGroup.cpp @@ -391,11 +391,12 @@ void TestGroup::testClone() // Making sure the new modification date is not the same. QTest::qSleep(1); - QScopedPointer clonedGroupResetTimeInfo(originalGroup->clone(Entry::CloneNoFlags, - Group::CloneNewUuid | Group::CloneResetTimeInfo)); + QScopedPointer clonedGroupResetTimeInfo( + originalGroup->clone(Entry::CloneNoFlags, Group::CloneNewUuid | Group::CloneResetTimeInfo)); QCOMPARE(clonedGroupResetTimeInfo->entries().size(), 0); QVERIFY(clonedGroupResetTimeInfo->uuid() != originalGroup->uuid()); - QVERIFY(clonedGroupResetTimeInfo->timeInfo().lastModificationTime() != originalGroup->timeInfo().lastModificationTime()); + QVERIFY(clonedGroupResetTimeInfo->timeInfo().lastModificationTime() + != originalGroup->timeInfo().lastModificationTime()); } void TestGroup::testCopyCustomIcons() diff --git a/tests/TestGroup.h b/tests/TestGroup.h index 11abfe129..f11cbf6f7 100644 --- a/tests/TestGroup.h +++ b/tests/TestGroup.h @@ -19,8 +19,8 @@ #ifndef KEEPASSX_TESTGROUP_H #define KEEPASSX_TESTGROUP_H -#include #include "core/Database.h" +#include class TestGroup : public QObject { diff --git a/tests/TestGroupModel.cpp b/tests/TestGroupModel.cpp index f9f55e247..ecdc24052 100644 --- a/tests/TestGroupModel.cpp +++ b/tests/TestGroupModel.cpp @@ -20,9 +20,9 @@ #include -#include "modeltest.h" #include "crypto/Crypto.h" #include "gui/group/GroupModel.h" +#include "modeltest.h" QTEST_GUILESS_MAIN(TestGroupModel) @@ -76,18 +76,18 @@ void TestGroupModel::test() QCOMPARE(model->data(index12).toString(), QString("group12")); QCOMPARE(model->data(index121).toString(), QString("group121")); - QSignalSpy spy1(model, SIGNAL(dataChanged(QModelIndex,QModelIndex))); + QSignalSpy spy1(model, SIGNAL(dataChanged(QModelIndex, QModelIndex))); group11->setName("test"); group121->setIcon(4); QCOMPARE(spy1.count(), 2); QCOMPARE(model->data(index11).toString(), QString("test")); - QSignalSpy spyAboutToAdd(model, SIGNAL(rowsAboutToBeInserted(QModelIndex,int,int))); - QSignalSpy spyAdded(model, SIGNAL(rowsInserted(QModelIndex,int,int))); - QSignalSpy spyAboutToRemove(model, SIGNAL(rowsAboutToBeRemoved(QModelIndex,int,int))); - QSignalSpy spyRemoved(model, SIGNAL(rowsRemoved(QModelIndex,int,int))); - QSignalSpy spyAboutToMove(model, SIGNAL(rowsAboutToBeMoved(QModelIndex,int,int,QModelIndex,int))); - QSignalSpy spyMoved(model, SIGNAL(rowsMoved(QModelIndex,int,int,QModelIndex,int))); + QSignalSpy spyAboutToAdd(model, SIGNAL(rowsAboutToBeInserted(QModelIndex, int, int))); + QSignalSpy spyAdded(model, SIGNAL(rowsInserted(QModelIndex, int, int))); + QSignalSpy spyAboutToRemove(model, SIGNAL(rowsAboutToBeRemoved(QModelIndex, int, int))); + QSignalSpy spyRemoved(model, SIGNAL(rowsRemoved(QModelIndex, int, int))); + QSignalSpy spyAboutToMove(model, SIGNAL(rowsAboutToBeMoved(QModelIndex, int, int, QModelIndex, int))); + QSignalSpy spyMoved(model, SIGNAL(rowsMoved(QModelIndex, int, int, QModelIndex, int))); Group* group2 = new Group(); group2->setObjectName("group2"); diff --git a/tests/TestKdbx2.cpp b/tests/TestKdbx2.cpp index c0a0b3074..76d5d81b4 100644 --- a/tests/TestKdbx2.cpp +++ b/tests/TestKdbx2.cpp @@ -18,12 +18,12 @@ #include "TestKdbx2.h" #include "TestGlobal.h" +#include "config-keepassx-tests.h" +#include "core/Metadata.h" #include "crypto/Crypto.h" -#include "keys/PasswordKey.h" #include "format/KeePass2Reader.h" #include "format/KeePass2Writer.h" -#include "core/Metadata.h" -#include "config-keepassx-tests.h" +#include "keys/PasswordKey.h" #include diff --git a/tests/TestKdbx2.h b/tests/TestKdbx2.h index 9b5f5c5ff..9eb0e415e 100644 --- a/tests/TestKdbx2.h +++ b/tests/TestKdbx2.h @@ -24,7 +24,7 @@ class Database; class TestKdbx2 : public QObject { -Q_OBJECT + Q_OBJECT private slots: void initTestCase(); diff --git a/tests/TestKdbx3.cpp b/tests/TestKdbx3.cpp index 5312bcf01..6df13d380 100644 --- a/tests/TestKdbx3.cpp +++ b/tests/TestKdbx3.cpp @@ -18,16 +18,15 @@ #include "TestKdbx3.h" #include "TestGlobal.h" +#include "config-keepassx-tests.h" #include "core/Metadata.h" -#include "keys/PasswordKey.h" -#include "format/KeePass2.h" -#include "format/KeePass2Reader.h" -#include "format/KeePass2Writer.h" #include "format/KdbxXmlReader.h" #include "format/KdbxXmlWriter.h" +#include "format/KeePass2.h" +#include "format/KeePass2Reader.h" #include "format/KeePass2Repair.h" -#include "config-keepassx-tests.h" - +#include "format/KeePass2Writer.h" +#include "keys/PasswordKey.h" QTEST_GUILESS_MAIN(TestKdbx3) @@ -63,8 +62,11 @@ void TestKdbx3::writeXml(QBuffer* buf, Database* db, bool& hasError, QString& er errorString = writer.errorString(); } -void TestKdbx3::readKdbx(QIODevice* device, CompositeKey const& key, QScopedPointer& db, - bool& hasError, QString& errorString) +void TestKdbx3::readKdbx(QIODevice* device, + CompositeKey const& key, + QScopedPointer& db, + bool& hasError, + QString& errorString) { KeePass2Reader reader; db.reset(reader.readDatabase(device, key)); @@ -75,8 +77,11 @@ void TestKdbx3::readKdbx(QIODevice* device, CompositeKey const& key, QScopedPoin QCOMPARE(reader.version(), KeePass2::FILE_VERSION_3_1 & KeePass2::FILE_VERSION_CRITICAL_MASK); } -void TestKdbx3::readKdbx(const QString& path, CompositeKey const& key, QScopedPointer& db, - bool& hasError, QString& errorString) +void TestKdbx3::readKdbx(const QString& path, + CompositeKey const& key, + QScopedPointer& db, + bool& hasError, + QString& errorString) { KeePass2Reader reader; db.reset(reader.readDatabase(path, key)); diff --git a/tests/TestKdbx3.h b/tests/TestKdbx3.h index 07c1c5503..298cefc6b 100644 --- a/tests/TestKdbx3.h +++ b/tests/TestKdbx3.h @@ -22,7 +22,7 @@ class TestKdbx3 : public TestKeePass2Format { -Q_OBJECT + Q_OBJECT private slots: void testNonAscii(); @@ -39,12 +39,17 @@ protected: Database* readXml(const QString& path, bool strictMode, bool& hasError, QString& errorString) override; void writeXml(QBuffer* buf, Database* db, bool& hasError, QString& errorString) override; - void readKdbx(QIODevice* device, CompositeKey const& key, QScopedPointer& db, - bool& hasError, QString& errorString) override; - void readKdbx(const QString& path, CompositeKey const& key, QScopedPointer& db, - bool& hasError, QString& errorString) override; + void readKdbx(QIODevice* device, + CompositeKey const& key, + QScopedPointer& db, + bool& hasError, + QString& errorString) override; + void readKdbx(const QString& path, + CompositeKey const& key, + QScopedPointer& db, + bool& hasError, + QString& errorString) override; void writeKdbx(QIODevice* device, Database* db, bool& hasError, QString& errorString) override; - }; #endif // KEEPASSXC_TEST_KDBX3_H diff --git a/tests/TestKdbx4.cpp b/tests/TestKdbx4.cpp index 1d50b8e7f..53207a049 100644 --- a/tests/TestKdbx4.cpp +++ b/tests/TestKdbx4.cpp @@ -18,17 +18,16 @@ #include "TestKdbx4.h" #include "TestGlobal.h" +#include "config-keepassx-tests.h" #include "core/Metadata.h" -#include "keys/PasswordKey.h" -#include "keys/FileKey.h" -#include "mock/MockChallengeResponseKey.h" +#include "format/KdbxXmlReader.h" +#include "format/KdbxXmlWriter.h" #include "format/KeePass2.h" #include "format/KeePass2Reader.h" #include "format/KeePass2Writer.h" -#include "format/KdbxXmlReader.h" -#include "format/KdbxXmlWriter.h" -#include "config-keepassx-tests.h" - +#include "keys/FileKey.h" +#include "keys/PasswordKey.h" +#include "mock/MockChallengeResponseKey.h" QTEST_GUILESS_MAIN(TestKdbx4) @@ -66,8 +65,11 @@ void TestKdbx4::writeXml(QBuffer* buf, Database* db, bool& hasError, QString& er errorString = writer.errorString(); } -void TestKdbx4::readKdbx(QIODevice* device, CompositeKey const& key, QScopedPointer& db, - bool& hasError, QString& errorString) +void TestKdbx4::readKdbx(QIODevice* device, + CompositeKey const& key, + QScopedPointer& db, + bool& hasError, + QString& errorString) { KeePass2Reader reader; db.reset(reader.readDatabase(device, key)); @@ -78,8 +80,11 @@ void TestKdbx4::readKdbx(QIODevice* device, CompositeKey const& key, QScopedPoin QCOMPARE(reader.version(), KeePass2::FILE_VERSION_4); } -void TestKdbx4::readKdbx(const QString& path, CompositeKey const& key, QScopedPointer& db, - bool& hasError, QString& errorString) +void TestKdbx4::readKdbx(const QString& path, + CompositeKey const& key, + QScopedPointer& db, + bool& hasError, + QString& errorString) { KeePass2Reader reader; db.reset(reader.readDatabase(path, key)); @@ -139,7 +144,7 @@ void TestKdbx4::testFormat400Upgrade() QScopedPointer sourceDb(new Database()); sourceDb->changeKdf(fastKdf(sourceDb->kdf())); sourceDb->metadata()->setName("Wubba lubba dub dub"); - QCOMPARE(sourceDb->kdf()->uuid(), KeePass2::KDF_AES_KDBX3); // default is legacy AES-KDF + QCOMPARE(sourceDb->kdf()->uuid(), KeePass2::KDF_AES_KDBX3); // default is legacy AES-KDF CompositeKey key; key.addKey(PasswordKey("I am in great pain, please help me!")); @@ -156,7 +161,8 @@ void TestKdbx4::testFormat400Upgrade() sourceDb->metadata()->customData()->set("CustomPublicData", "Hey look, I turned myself into a pickle!"); if (addCustomData) { // this, however, should - sourceDb->rootGroup()->customData()->set("CustomGroupData", "I just killed my family! I don't care who they were!"); + sourceDb->rootGroup()->customData()->set("CustomGroupData", + "I just killed my family! I don't care who they were!"); } KeePass2Writer writer; @@ -305,16 +311,18 @@ void TestKdbx4::testUpgradeMasterKeyIntegrity_data() QTest::addColumn("upgradeAction"); QTest::addColumn("expectedVersion"); - QTest::newRow("Upgrade: none") << QString("none") << KeePass2::FILE_VERSION_3; - QTest::newRow("Upgrade: none (meta-customdata)") << QString("meta-customdata") << KeePass2::FILE_VERSION_3; - QTest::newRow("Upgrade: none (explicit kdf-aes-kdbx3)") << QString("kdf-aes-kdbx3") << KeePass2::FILE_VERSION_3; - QTest::newRow("Upgrade (explicit): kdf-argon2") << QString("kdf-argon2") << KeePass2::FILE_VERSION_4; - QTest::newRow("Upgrade (explicit): kdf-aes-kdbx4") << QString("kdf-aes-kdbx4") << KeePass2::FILE_VERSION_4; - QTest::newRow("Upgrade (implicit): public-customdata") << QString("public-customdata") << KeePass2::FILE_VERSION_4; - QTest::newRow("Upgrade (implicit): rootgroup-customdata") << QString("rootgroup-customdata") << KeePass2::FILE_VERSION_4; - QTest::newRow("Upgrade (implicit): group-customdata") << QString("group-customdata") << KeePass2::FILE_VERSION_4; - QTest::newRow("Upgrade (implicit): rootentry-customdata") << QString("rootentry-customdata") << KeePass2::FILE_VERSION_4; - QTest::newRow("Upgrade (implicit): entry-customdata") << QString("entry-customdata") << KeePass2::FILE_VERSION_4; + QTest::newRow("Upgrade: none") << QString("none") << KeePass2::FILE_VERSION_3; + QTest::newRow("Upgrade: none (meta-customdata)") << QString("meta-customdata") << KeePass2::FILE_VERSION_3; + QTest::newRow("Upgrade: none (explicit kdf-aes-kdbx3)") << QString("kdf-aes-kdbx3") << KeePass2::FILE_VERSION_3; + QTest::newRow("Upgrade (explicit): kdf-argon2") << QString("kdf-argon2") << KeePass2::FILE_VERSION_4; + QTest::newRow("Upgrade (explicit): kdf-aes-kdbx4") << QString("kdf-aes-kdbx4") << KeePass2::FILE_VERSION_4; + QTest::newRow("Upgrade (implicit): public-customdata") << QString("public-customdata") << KeePass2::FILE_VERSION_4; + QTest::newRow("Upgrade (implicit): rootgroup-customdata") << QString("rootgroup-customdata") + << KeePass2::FILE_VERSION_4; + QTest::newRow("Upgrade (implicit): group-customdata") << QString("group-customdata") << KeePass2::FILE_VERSION_4; + QTest::newRow("Upgrade (implicit): rootentry-customdata") << QString("rootentry-customdata") + << KeePass2::FILE_VERSION_4; + QTest::newRow("Upgrade (implicit): entry-customdata") << QString("entry-customdata") << KeePass2::FILE_VERSION_4; } void TestKdbx4::testCustomData() @@ -335,8 +343,8 @@ void TestKdbx4::testCustomData() const QString customDataKey2 = "CD2"; const QString customData1 = "abcäöü"; const QString customData2 = "Hello World"; - const int dataSize = customDataKey1.toUtf8().size() + customDataKey1.toUtf8().size() + - customData1.toUtf8().size() + customData2.toUtf8().size(); + const int dataSize = customDataKey1.toUtf8().size() + customDataKey1.toUtf8().size() + customData1.toUtf8().size() + + customData2.toUtf8().size(); // test custom database data db.metadata()->customData()->set(customDataKey1, customData1); @@ -413,10 +421,7 @@ QSharedPointer TestKdbx4::fastKdf(QSharedPointer kdf) kdf->setRounds(1); if (kdf->uuid() == KeePass2::KDF_ARGON2) { - kdf->processParameters({ - {KeePass2::KDFPARAM_ARGON2_MEMORY, 1024}, - {KeePass2::KDFPARAM_ARGON2_PARALLELISM, 1} - }); + kdf->processParameters({{KeePass2::KDFPARAM_ARGON2_MEMORY, 1024}, {KeePass2::KDFPARAM_ARGON2_PARALLELISM, 1}}); } return kdf; diff --git a/tests/TestKdbx4.h b/tests/TestKdbx4.h index e278ebb02..1b677b4ab 100644 --- a/tests/TestKdbx4.h +++ b/tests/TestKdbx4.h @@ -22,7 +22,7 @@ class TestKdbx4 : public TestKeePass2Format { -Q_OBJECT + Q_OBJECT private slots: void testFormat400(); @@ -39,10 +39,16 @@ protected: Database* readXml(const QString& path, bool strictMode, bool& hasError, QString& errorString) override; void writeXml(QBuffer* buf, Database* db, bool& hasError, QString& errorString) override; - void readKdbx(const QString& path, CompositeKey const& key, QScopedPointer& db, - bool& hasError, QString& errorString) override; - void readKdbx(QIODevice* device, CompositeKey const& key, QScopedPointer& db, - bool& hasError, QString& errorString) override; + void readKdbx(const QString& path, + CompositeKey const& key, + QScopedPointer& db, + bool& hasError, + QString& errorString) override; + void readKdbx(QIODevice* device, + CompositeKey const& key, + QScopedPointer& db, + bool& hasError, + QString& errorString) override; void writeKdbx(QIODevice* device, Database* db, bool& hasError, QString& errorString) override; QSharedPointer fastKdf(QSharedPointer kdf); diff --git a/tests/TestKeePass1Reader.cpp b/tests/TestKeePass1Reader.cpp index 892f746e4..3cf95286d 100644 --- a/tests/TestKeePass1Reader.cpp +++ b/tests/TestKeePass1Reader.cpp @@ -133,8 +133,7 @@ void TestKeePass1Reader::testGroupExpanded() { QCOMPARE(m_db->rootGroup()->children().at(0)->isExpanded(), true); QCOMPARE(m_db->rootGroup()->children().at(0)->children().at(0)->isExpanded(), true); - QCOMPARE(m_db->rootGroup()->children().at(0)->children().at(0)->children().at(0)->isExpanded(), - false); + QCOMPARE(m_db->rootGroup()->children().at(0)->children().at(0)->children().at(0)->isExpanded(), false); } void TestKeePass1Reader::testAutoType() diff --git a/tests/TestKeePass2Format.cpp b/tests/TestKeePass2Format.cpp index 266047bec..9dac07691 100644 --- a/tests/TestKeePass2Format.cpp +++ b/tests/TestKeePass2Format.cpp @@ -20,8 +20,8 @@ #include "core/Metadata.h" #include "crypto/Crypto.h" -#include "keys/PasswordKey.h" #include "format/KdbxXmlReader.h" +#include "keys/PasswordKey.h" #include "FailDevice.h" #include "config-keepassx-tests.h" @@ -402,11 +402,15 @@ void TestKeePass2Format::testXmlInvalidXmlChars() { QScopedPointer dbWrite(new Database()); - QString strPlainInvalid = QString().append(QChar(0x02)).append(QChar(0x19)) - .append(QChar(0xFFFE)).append(QChar(0xFFFF)); - QString strPlainValid = QString().append(QChar(0x09)).append(QChar(0x0A)) - .append(QChar(0x20)).append(QChar(0xD7FF)) - .append(QChar(0xE000)).append(QChar(0xFFFD)); + QString strPlainInvalid = + QString().append(QChar(0x02)).append(QChar(0x19)).append(QChar(0xFFFE)).append(QChar(0xFFFF)); + QString strPlainValid = QString() + .append(QChar(0x09)) + .append(QChar(0x0A)) + .append(QChar(0x20)) + .append(QChar(0xD7FF)) + .append(QChar(0xE000)) + .append(QChar(0xFFFD)); // U+10437 in UTF-16: D801 DC37 // high low surrogate QString strSingleHighSurrogate1 = QString().append(QChar(0xD801)); @@ -416,8 +420,8 @@ void TestKeePass2Format::testXmlInvalidXmlChars() QString strSingleLowSurrogate2 = QString().append(QChar((0x31))).append(QChar(0xDC37)).append(QChar(0x32)); QString strLowLowSurrogate = QString().append(QChar(0xDC37)).append(QChar(0xDC37)); QString strSurrogateValid1 = QString().append(QChar(0xD801)).append(QChar(0xDC37)); - QString strSurrogateValid2 = QString().append(QChar(0x31)).append(QChar(0xD801)).append(QChar(0xDC37)) - .append(QChar(0x32)); + QString strSurrogateValid2 = + QString().append(QChar(0x31)).append(QChar(0xD801)).append(QChar(0xDC37)).append(QChar(0x32)); auto entry = new Entry(); entry->setUuid(Uuid::random()); @@ -532,7 +536,8 @@ void TestKeePass2Format::testKdbxAttachments() void TestKeePass2Format::testKdbxNonAsciiPasswords() { - QCOMPARE(m_kdbxTargetDb->rootGroup()->entries()[0]->password(), m_kdbxSourceDb->rootGroup()->entries()[0]->password()); + QCOMPARE(m_kdbxTargetDb->rootGroup()->entries()[0]->password(), + m_kdbxSourceDb->rootGroup()->entries()[0]->password()); } void TestKeePass2Format::testKdbxDeviceFailure() diff --git a/tests/TestKeePass2Format.h b/tests/TestKeePass2Format.h index 13426cb9c..d29fa2c13 100644 --- a/tests/TestKeePass2Format.h +++ b/tests/TestKeePass2Format.h @@ -18,9 +18,9 @@ #ifndef KEEPASSXC_TESTKEEPASS2FORMAT_H #define KEEPASSXC_TESTKEEPASS2FORMAT_H +#include #include #include -#include #include #include "core/Database.h" @@ -30,7 +30,7 @@ */ class TestKeePass2Format : public QObject { -Q_OBJECT + Q_OBJECT private slots: void initTestCase(); @@ -71,10 +71,16 @@ protected: virtual Database* readXml(const QString& path, bool strictMode, bool& hasError, QString& errorString) = 0; virtual void writeXml(QBuffer* buf, Database* db, bool& hasError, QString& errorString) = 0; - virtual void readKdbx(QIODevice* device, CompositeKey const& key, QScopedPointer& db, - bool& hasError, QString& errorString) = 0; - virtual void readKdbx(const QString& path, CompositeKey const& key, QScopedPointer& db, - bool& hasError, QString& errorString) = 0; + virtual void readKdbx(QIODevice* device, + CompositeKey const& key, + QScopedPointer& db, + bool& hasError, + QString& errorString) = 0; + virtual void readKdbx(const QString& path, + CompositeKey const& key, + QScopedPointer& db, + bool& hasError, + QString& errorString) = 0; virtual void writeKdbx(QIODevice* device, Database* db, bool& hasError, QString& errorString) = 0; QScopedPointer m_xmlDb; diff --git a/tests/TestKeePass2RandomStream.cpp b/tests/TestKeePass2RandomStream.cpp index edb95b6c6..3f5443532 100644 --- a/tests/TestKeePass2RandomStream.cpp +++ b/tests/TestKeePass2RandomStream.cpp @@ -35,7 +35,6 @@ void TestKeePass2RandomStream::test() const QByteArray key("\x11\x22\x33\x44\x55\x66\x77\x88"); const int Size = 128; - SymmetricCipher cipher(SymmetricCipher::Salsa20, SymmetricCipher::Stream, SymmetricCipher::Encrypt); QVERIFY(cipher.init(CryptoHash::hash(key, CryptoHash::Sha256), KeePass2::INNER_STREAM_SALSA20_IV)); @@ -55,7 +54,6 @@ void TestKeePass2RandomStream::test() cipherData[i] = data[i] ^ cipherPad[i]; } - KeePass2RandomStream randomStream(KeePass2::ProtectedStreamAlgo::Salsa20); bool ok; QVERIFY(randomStream.init(key)); @@ -72,13 +70,11 @@ void TestKeePass2RandomStream::test() randomStreamData.append(randomStream.process(data.mid(64, 64), &ok)); QVERIFY(ok); - SymmetricCipher cipherEncrypt(SymmetricCipher::Salsa20, SymmetricCipher::Stream, SymmetricCipher::Encrypt); QVERIFY(cipherEncrypt.init(CryptoHash::hash(key, CryptoHash::Sha256), KeePass2::INNER_STREAM_SALSA20_IV)); QByteArray cipherDataEncrypt = cipherEncrypt.process(data, &ok); QVERIFY(ok); - QCOMPARE(randomStreamData.size(), Size); QCOMPARE(cipherData, cipherDataEncrypt); QCOMPARE(randomStreamData, cipherData); diff --git a/tests/TestKeys.cpp b/tests/TestKeys.cpp index e2b7010b1..e5cc75c2c 100644 --- a/tests/TestKeys.cpp +++ b/tests/TestKeys.cpp @@ -26,8 +26,8 @@ #include "core/Metadata.h" #include "core/Tools.h" #include "crypto/Crypto.h" -#include "crypto/kdf/AesKdf.h" #include "crypto/CryptoHash.h" +#include "crypto/kdf/AesKdf.h" #include "format/KeePass2Reader.h" #include "format/KeePass2Writer.h" #include "keys/FileKey.h" @@ -231,7 +231,8 @@ void TestKeys::benchmarkTransformKey() kdf.setSeed(seed); kdf.setRounds(1e6); - QBENCHMARK { + QBENCHMARK + { Q_UNUSED(compositeKey.transform(kdf, result)); }; } diff --git a/tests/TestMerge.cpp b/tests/TestMerge.cpp index 8f38a2f85..e490da8d5 100644 --- a/tests/TestMerge.cpp +++ b/tests/TestMerge.cpp @@ -560,7 +560,6 @@ void TestMerge::testResolveGroupConflictOlder() delete dbSource; } - Database* TestMerge::createTestDatabase() { Database* db = new Database(); diff --git a/tests/TestModified.cpp b/tests/TestModified.cpp index 0bf2c5b3a..0a9f0cfa2 100644 --- a/tests/TestModified.cpp +++ b/tests/TestModified.cpp @@ -141,7 +141,6 @@ void TestModified::testGroupSets() root->setIcon(root->iconUuid()); QCOMPARE(spyModified.count(), spyCount); - group->setUuid(Uuid::random()); QCOMPARE(spyModified.count(), ++spyCount); group->setUuid(group->uuid()); @@ -306,7 +305,7 @@ void TestModified::testHistoryItems() entry->setTitle("b"); entry->endUpdate(); QCOMPARE(entry->historyItems().size(), ++historyItemsSize); - auto *historyEntry = entry->historyItems().at(historyItemsSize - 1); + auto* historyEntry = entry->historyItems().at(historyItemsSize - 1); QCOMPARE(historyEntry->title(), QString("a")); QCOMPARE(historyEntry->uuid(), entry->uuid()); QCOMPARE(historyEntry->tags(), entry->tags()); @@ -475,7 +474,6 @@ void TestModified::testHistoryMaxSize() QCOMPARE(entry1->attachments()->attachmentsSize(), 6000 + key.size()); QCOMPARE(entry1->historyItems().size(), 4); - auto entry2 = new Entry(); entry2->setGroup(db->rootGroup()); QCOMPARE(entry2->historyItems().size(), 0); diff --git a/tests/TestOpenSSHKey.cpp b/tests/TestOpenSSHKey.cpp index 8ac129866..cad591bdc 100644 --- a/tests/TestOpenSSHKey.cpp +++ b/tests/TestOpenSSHKey.cpp @@ -17,8 +17,8 @@ #include "TestOpenSSHKey.h" #include "TestGlobal.h" -#include "sshagent/OpenSSHKey.h" #include "crypto/Crypto.h" +#include "sshagent/OpenSSHKey.h" QTEST_GUILESS_MAIN(TestOpenSSHKey) @@ -30,17 +30,15 @@ void TestOpenSSHKey::initTestCase() void TestOpenSSHKey::testParse() { // mixed line endings and missing ones are intentional, we only require 3 lines total - const QString keyString = QString( - "\r\n\r" - "-----BEGIN OPENSSH PRIVATE KEY-----\n" - "b3BlbnNzaC1rZXktdjEAAAAABG5vbmUAAAAEbm9uZQAAAAAAAAABAAAAMwAAAAtzc2gtZW" - "QyNTUxOQAAACDdlO5F2kF2WzedrBAHBi9wBHeISzXZ0IuIqrp0EzeazAAAAKjgCfj94An4" - "/QAAAAtzc2gtZWQyNTUxOQAAACDdlO5F2kF2WzedrBAHBi9wBHeISzXZ0IuIqrp0EzeazA" - "AAAEBe1iilZFho8ZGAliiSj5URvFtGrgvmnEKdiLZow5hOR92U7kXaQXZbN52sEAcGL3AE" - "d4hLNdnQi4iqunQTN5rMAAAAH29wZW5zc2hrZXktdGVzdC1wYXJzZUBrZWVwYXNzeGMBAg" - "MEBQY=\r" - "-----END OPENSSH PRIVATE KEY-----\r\n\r" - ); + const QString keyString = QString("\r\n\r" + "-----BEGIN OPENSSH PRIVATE KEY-----\n" + "b3BlbnNzaC1rZXktdjEAAAAABG5vbmUAAAAEbm9uZQAAAAAAAAABAAAAMwAAAAtzc2gtZW" + "QyNTUxOQAAACDdlO5F2kF2WzedrBAHBi9wBHeISzXZ0IuIqrp0EzeazAAAAKjgCfj94An4" + "/QAAAAtzc2gtZWQyNTUxOQAAACDdlO5F2kF2WzedrBAHBi9wBHeISzXZ0IuIqrp0EzeazA" + "AAAEBe1iilZFho8ZGAliiSj5URvFtGrgvmnEKdiLZow5hOR92U7kXaQXZbN52sEAcGL3AE" + "d4hLNdnQi4iqunQTN5rMAAAAH29wZW5zc2hrZXktdGVzdC1wYXJzZUBrZWVwYXNzeGMBAg" + "MEBQY=\r" + "-----END OPENSSH PRIVATE KEY-----\r\n\r"); const QByteArray keyData = keyString.toLatin1(); @@ -64,20 +62,18 @@ void TestOpenSSHKey::testParse() void TestOpenSSHKey::testParseDSA() { - const QString keyString = QString( - "-----BEGIN DSA PRIVATE KEY-----\n" - "MIIBuwIBAAKBgQCudjbvSh8JxQOr2laCqZM1t4kNWBETVOXz5vgk9iw6Z5opB9/k\n" - "g4nFc1PVq7fdAIc8W/5WCAjugKcxPb9PIHfcwY2fimmiPWFK68/eHKLoCuIn2wxB\n" - "63ig2hAhx5U5aYG9QHkNCaT6VX7rc19nToSeZXlpja4x54/DaQaqOEWYsQIVAOer\n" - "UQWfccz7KXUu6+x7heGob6I3AoGAVDRFJIlL0DI/4nePIcgwgwbfgs2ojSu21g4w\n" - "dQoXvqU34XydPgPQ985XIIuiDkaomRw4yYd/Sh4ZapFcrP++iJ1V+WS6kLcWPHMq\n" - "poYwk8mq6GLbPFLEjr+n6HgX5ln15n3i4WAopNH7mEl0glY9L0rxmcN0XOpqw6Ux\n" - "ETGEfAwCgYAiOeYwblMkkTIGtVx5NvNsOlfrBYL4GqUP9oQMO5I+xLZLWQIf+7Jp\n" - "8t6mwxSBz0RHjNVQ11vZowNjq3587aLy57bVwf2lIm9KSvS6z9HoNbHgQimcBorR\n" - "J9l9RUrj7TnsZgiVw66j2r34nHRHRtggiO+qrMtw7MJc0Q7jiuTmzgIVAMXbk0T9\n" - "nBfSLWQz/L8RexU2GR4e\n" - "-----END DSA PRIVATE KEY-----\n" - ); + const QString keyString = QString("-----BEGIN DSA PRIVATE KEY-----\n" + "MIIBuwIBAAKBgQCudjbvSh8JxQOr2laCqZM1t4kNWBETVOXz5vgk9iw6Z5opB9/k\n" + "g4nFc1PVq7fdAIc8W/5WCAjugKcxPb9PIHfcwY2fimmiPWFK68/eHKLoCuIn2wxB\n" + "63ig2hAhx5U5aYG9QHkNCaT6VX7rc19nToSeZXlpja4x54/DaQaqOEWYsQIVAOer\n" + "UQWfccz7KXUu6+x7heGob6I3AoGAVDRFJIlL0DI/4nePIcgwgwbfgs2ojSu21g4w\n" + "dQoXvqU34XydPgPQ985XIIuiDkaomRw4yYd/Sh4ZapFcrP++iJ1V+WS6kLcWPHMq\n" + "poYwk8mq6GLbPFLEjr+n6HgX5ln15n3i4WAopNH7mEl0glY9L0rxmcN0XOpqw6Ux\n" + "ETGEfAwCgYAiOeYwblMkkTIGtVx5NvNsOlfrBYL4GqUP9oQMO5I+xLZLWQIf+7Jp\n" + "8t6mwxSBz0RHjNVQ11vZowNjq3587aLy57bVwf2lIm9KSvS6z9HoNbHgQimcBorR\n" + "J9l9RUrj7TnsZgiVw66j2r34nHRHRtggiO+qrMtw7MJc0Q7jiuTmzgIVAMXbk0T9\n" + "nBfSLWQz/L8RexU2GR4e\n" + "-----END DSA PRIVATE KEY-----\n"); const QByteArray keyData = keyString.toLatin1(); @@ -92,38 +88,36 @@ void TestOpenSSHKey::testParseDSA() void TestOpenSSHKey::testDecryptAES128CBC() { - const QString keyString = QString( - "-----BEGIN RSA PRIVATE KEY-----\n" - "Proc-Type: 4,ENCRYPTED\n" - "DEK-Info: AES-128-CBC,804E4D214D1263FF94E3743FE799DBB4\n" - "\n" - "lM9TDfOTbiRhaGGDh7Hn+rqw8CCWcYBZYu7smyYLdnWKXKPmbne8CQFZBAS1FJwZ\n" - "6Mj6n075yFGyzN9/OfeqKiUA4adlbwLbGwB+yyKsC2FlsvRIEr4hup02WWM47vHj\n" - "DS4TRmNkE7MKFLhpNCyt5OGGM45s+/lwVTw51K0Hm99TBd72IrX4jfY9ZxAVbL3l\n" - "aTohL8x6oOTe7q318QgJoFi+DjJhDWLGLLJ7fBqD2imz2fmrY4j8Jpw2sDe1rj82\n" - "gMqqNG3FrfN0S4uYlWYH5pAh+BUcB1UdmTU/rV5wJMK1oUytmZv/J2+X/0k3Y93F\n" - "aw6JWOy28OizW+TQXvv8gREWsp5PEclqUZhhGQbVbCQCiDOxg+xiXNySdRH1IqjR\n" - "zQiKgD4SPzkxQekExPaIQT/KutWZdMNYybEqooCx8YyeDoN31z7Wa2rv6OulOn/j\n" - "wJFvyd2PT/6brHKI4ky8RYroDf4FbVYKfyEW5CSAg2OyL/tY/kSPgy/k0WT7fDwq\n" - "dPSuYM9yeWNL6kAhDqDOv8+s3xvOVEljktBvQvItQwVLmHszC3E2AcnaxzdblKPu\n" - "e3+mBT80NXHjERK2ht+/9JYseK1ujNbNAaG8SbKfU3FF0VlyJ0QW6TuIEdpNnymT\n" - "0fm0cDfKNaoeJIFnBRZhgIOJAic9DM0cTe/vSG69DaUYsaQPp36al7Fbux3GpFHS\n" - "OtJEySYGro/6zvJ9dDIEfIGZjA3RaMt6+DuyJZXQdT2RNXa9j60xW7dXh0En4n82\n" - "JUKTxYhDPLS5c8BzpJqoopxpKwElmrJ7Y3xpd6z2vIlD8ftuZrkk6siTMNQ2s7MI\n" - "Xl332O+0H4k7uSfczHPOOw36TFhNjGQAP0b7O+0/RVG0ttOIoAn7ZkX3nfdbtG5B\n" - "DWKvDaopvrcC2/scQ5uLUnqnBiGw1XiYpdg5ang7knHNzHZAIekVaYYZigpCAKp+\n" - "OtoaDeUEzqFhYVmF8ad1fgvC9ZUsuxS4XUHCKl0H6CJcvW9MJPVbveqYoK+j9qKd\n" - "iMIkQBP1kE2rzGZVGUkZTpM9LVD9nP0nsbr6E8BatFcNgRirsg2BTJglNpXlCmY6\n" - "ldzJ/ELBbzoXIn+0wTGai0o4eBPx55baef69JfPuZqEB9pLNE+mHstrqIwcfqYu4\n" - "M+Vzun1QshRMj9a1PVkIHfs1fLeebI4QCHO0vJlc9K4iYPM4rsDNO3YaAgGRuARS\n" - "f3McGiGFxkv5zxe8i05ZBnn+exE77jpRKxd223jAMe2wu4WiFB7ZVo4Db6b5Oo2T\n" - "TPh3VuY7TNMEKkcUi+mGLKjroocQ5j8WQYlfnyOaTalUVQDzOTNb67QIIoiszR0U\n" - "+AXGyxHj0QtotZFoPME+AbS9Zqy3SgSOuIzPBPU5zS4uoKNdD5NPE5YAuafCjsDy\n" - "MT4DVy+cPOQYUK022S7T2nsA1btmvUvD5LL2Mc8VuKsWOn/7FKZua6OCfipt6oX0\n" - "1tzYrw0/ALK+CIdVdYIiPPfxGZkr+JSLOOg7u50tpmen9GzxgNTv63miygwUAIDF\n" - "u0GbQwOueoA453/N75FcXOgrbqTdivyadUbRP+l7YJk/SfIytyJMOigejp+Z1lzF\n" - "-----END RSA PRIVATE KEY-----\n" - ); + const QString keyString = QString("-----BEGIN RSA PRIVATE KEY-----\n" + "Proc-Type: 4,ENCRYPTED\n" + "DEK-Info: AES-128-CBC,804E4D214D1263FF94E3743FE799DBB4\n" + "\n" + "lM9TDfOTbiRhaGGDh7Hn+rqw8CCWcYBZYu7smyYLdnWKXKPmbne8CQFZBAS1FJwZ\n" + "6Mj6n075yFGyzN9/OfeqKiUA4adlbwLbGwB+yyKsC2FlsvRIEr4hup02WWM47vHj\n" + "DS4TRmNkE7MKFLhpNCyt5OGGM45s+/lwVTw51K0Hm99TBd72IrX4jfY9ZxAVbL3l\n" + "aTohL8x6oOTe7q318QgJoFi+DjJhDWLGLLJ7fBqD2imz2fmrY4j8Jpw2sDe1rj82\n" + "gMqqNG3FrfN0S4uYlWYH5pAh+BUcB1UdmTU/rV5wJMK1oUytmZv/J2+X/0k3Y93F\n" + "aw6JWOy28OizW+TQXvv8gREWsp5PEclqUZhhGQbVbCQCiDOxg+xiXNySdRH1IqjR\n" + "zQiKgD4SPzkxQekExPaIQT/KutWZdMNYybEqooCx8YyeDoN31z7Wa2rv6OulOn/j\n" + "wJFvyd2PT/6brHKI4ky8RYroDf4FbVYKfyEW5CSAg2OyL/tY/kSPgy/k0WT7fDwq\n" + "dPSuYM9yeWNL6kAhDqDOv8+s3xvOVEljktBvQvItQwVLmHszC3E2AcnaxzdblKPu\n" + "e3+mBT80NXHjERK2ht+/9JYseK1ujNbNAaG8SbKfU3FF0VlyJ0QW6TuIEdpNnymT\n" + "0fm0cDfKNaoeJIFnBRZhgIOJAic9DM0cTe/vSG69DaUYsaQPp36al7Fbux3GpFHS\n" + "OtJEySYGro/6zvJ9dDIEfIGZjA3RaMt6+DuyJZXQdT2RNXa9j60xW7dXh0En4n82\n" + "JUKTxYhDPLS5c8BzpJqoopxpKwElmrJ7Y3xpd6z2vIlD8ftuZrkk6siTMNQ2s7MI\n" + "Xl332O+0H4k7uSfczHPOOw36TFhNjGQAP0b7O+0/RVG0ttOIoAn7ZkX3nfdbtG5B\n" + "DWKvDaopvrcC2/scQ5uLUnqnBiGw1XiYpdg5ang7knHNzHZAIekVaYYZigpCAKp+\n" + "OtoaDeUEzqFhYVmF8ad1fgvC9ZUsuxS4XUHCKl0H6CJcvW9MJPVbveqYoK+j9qKd\n" + "iMIkQBP1kE2rzGZVGUkZTpM9LVD9nP0nsbr6E8BatFcNgRirsg2BTJglNpXlCmY6\n" + "ldzJ/ELBbzoXIn+0wTGai0o4eBPx55baef69JfPuZqEB9pLNE+mHstrqIwcfqYu4\n" + "M+Vzun1QshRMj9a1PVkIHfs1fLeebI4QCHO0vJlc9K4iYPM4rsDNO3YaAgGRuARS\n" + "f3McGiGFxkv5zxe8i05ZBnn+exE77jpRKxd223jAMe2wu4WiFB7ZVo4Db6b5Oo2T\n" + "TPh3VuY7TNMEKkcUi+mGLKjroocQ5j8WQYlfnyOaTalUVQDzOTNb67QIIoiszR0U\n" + "+AXGyxHj0QtotZFoPME+AbS9Zqy3SgSOuIzPBPU5zS4uoKNdD5NPE5YAuafCjsDy\n" + "MT4DVy+cPOQYUK022S7T2nsA1btmvUvD5LL2Mc8VuKsWOn/7FKZua6OCfipt6oX0\n" + "1tzYrw0/ALK+CIdVdYIiPPfxGZkr+JSLOOg7u50tpmen9GzxgNTv63miygwUAIDF\n" + "u0GbQwOueoA453/N75FcXOgrbqTdivyadUbRP+l7YJk/SfIytyJMOigejp+Z1lzF\n" + "-----END RSA PRIVATE KEY-----\n"); const QByteArray keyData = keyString.toLatin1(); @@ -140,35 +134,33 @@ void TestOpenSSHKey::testDecryptAES128CBC() void TestOpenSSHKey::testParseRSA() { - const QString keyString = QString( - "-----BEGIN RSA PRIVATE KEY-----\n" - "MIIEpAIBAAKCAQEAsCHtJicDPWnvHSIKbnTZaJkIB9vgE0pmLdK580JUqBuonVbB\n" - "y1QTy0ZQ7/TtqvLPgwPK88TR46OLO/QGCzo2+XxgJ85uy0xfuyUYRmSuw0drsErN\n" - "mH8vU91lSBxsGDp9LtBbgHKoR23vMWZ34IxFRc55XphrIH48ijsMaL6bXBwF/3tD\n" - "9T3lm2MpP1huyVNnIY9+GRRWCy4f9LMj/UGu/n4RtwwfpOZBBRwYkq5QkzA9lPm/\n" - "VzF3MP1rKTMkvAw+Nfb383mkmc6MRnsa6uh6iDa9aVB7naegM13UJQX/PY1Ks6pO\n" - "XDpy/MQ7iCh+HmYNq5dRmARyaNl9xIXJNhz1cQIDAQABAoIBAQCnEUc1LUQxeM5K\n" - "wANNCqE+SgoIClPdeHC7fmrLh1ttqe6ib6ybBUFRS31yXs0hnfefunVEDKlaV8K2\n" - "N52UAMAsngFHQNRvGh6kEWeZPd9Xc+N98TZbNCjcT+DGKc+Om8wqH5DrodZlCq4c\n" - "GaoT4HnE4TjWtZTH2XXrWF9I66PKFWf070R44nvyVcvaZi4pC2YmURRPuGF6K1iK\n" - "dH8zM6HHG1UGu2W6hLNn+K01IulG0Lb8eWNaNYMmtQWaxyp7I2IWkkecUs3nCuiR\n" - "byFOoomCjdh8r9yZFvwxjGUhgtkALN9GCU0Mwve+s11IB2gevruN+q9/Qejbyfdm\n" - "IlgLAeTRAoGBANRcVzW9CYeobCf+U9hKJFEOur8XO+J2mTMaELA0EjWpTJFAeIT7\n" - "KeRpCRG4/vOSklxxRF6vP1EACA4Z+5BlN+FTipHHs+bSEgqkPZiiANDH7Zot5Iqv\n" - "1q0fRyldNRZNZK7DWp08BPNVWGA/EnEuKJiURxnxBaxNXbUyMCdjxvMvAoGBANRT\n" - "utbrqS/bAa/DcHKn3V6DRqBl3TDOfvCNjiKC84a67F2uXgzLIdMktr4d1NyCZVJd\n" - "7/zVgWORLIdg1eAi6rYGoOvNV39wwga7CF+m9sBY0wAaKYCELe6L26r4aQHVCX6n\n" - "rnIgUv+4o4itmU2iP0r3wlmDC9pDRQP82vfvQPlfAoGASwhleANW/quvq2HdViq8\n" - "Mje2HBalfhrRfpDTHK8JUBSFjTzuWG42GxJRtgVbb8x2ElujAKGDCaetMO5VSGu7\n" - "Fs5hw6iAFCpdXY0yhl+XUi2R8kwM2EPQ4lKO3jqkq0ClNmqn9a5jQWcCVt9yMLNS\n" - "fLbHeI8EpiCf34ngIcrLXNkCgYEAzlcEZuKkC46xB+dNew8pMTUwSKZVm53BfPKD\n" - "44QRN6imFbBjU9mAaJnwQbfp6dWKs834cGPolyM4++MeVfB42iZ88ksesgmZdUMD\n" - "szkl6O0pOJs0I+HQZVdjRbadDZvD22MHQ3+oST1dJ3FVXz3Cdo9qPuT8esMO6f4r\n" - "qfDH2s8CgYAXC/lWWHQ//PGP0pH4oiEXisx1K0X1u0xMGgrChxBRGRiKZUwNMIvJ\n" - "TqUu7IKizK19cLHF/NBvxHYHFw+m7puNjn6T1RtRCUjRZT7Dx1VHfVosL9ih5DA8\n" - "tpbZA5KGKcvHtB5DDgT0MHwzBZnb4Q//Rhovzn+HXZPsJTTgHHy3NQ==\n" - "-----END RSA PRIVATE KEY-----\n" - ); + const QString keyString = QString("-----BEGIN RSA PRIVATE KEY-----\n" + "MIIEpAIBAAKCAQEAsCHtJicDPWnvHSIKbnTZaJkIB9vgE0pmLdK580JUqBuonVbB\n" + "y1QTy0ZQ7/TtqvLPgwPK88TR46OLO/QGCzo2+XxgJ85uy0xfuyUYRmSuw0drsErN\n" + "mH8vU91lSBxsGDp9LtBbgHKoR23vMWZ34IxFRc55XphrIH48ijsMaL6bXBwF/3tD\n" + "9T3lm2MpP1huyVNnIY9+GRRWCy4f9LMj/UGu/n4RtwwfpOZBBRwYkq5QkzA9lPm/\n" + "VzF3MP1rKTMkvAw+Nfb383mkmc6MRnsa6uh6iDa9aVB7naegM13UJQX/PY1Ks6pO\n" + "XDpy/MQ7iCh+HmYNq5dRmARyaNl9xIXJNhz1cQIDAQABAoIBAQCnEUc1LUQxeM5K\n" + "wANNCqE+SgoIClPdeHC7fmrLh1ttqe6ib6ybBUFRS31yXs0hnfefunVEDKlaV8K2\n" + "N52UAMAsngFHQNRvGh6kEWeZPd9Xc+N98TZbNCjcT+DGKc+Om8wqH5DrodZlCq4c\n" + "GaoT4HnE4TjWtZTH2XXrWF9I66PKFWf070R44nvyVcvaZi4pC2YmURRPuGF6K1iK\n" + "dH8zM6HHG1UGu2W6hLNn+K01IulG0Lb8eWNaNYMmtQWaxyp7I2IWkkecUs3nCuiR\n" + "byFOoomCjdh8r9yZFvwxjGUhgtkALN9GCU0Mwve+s11IB2gevruN+q9/Qejbyfdm\n" + "IlgLAeTRAoGBANRcVzW9CYeobCf+U9hKJFEOur8XO+J2mTMaELA0EjWpTJFAeIT7\n" + "KeRpCRG4/vOSklxxRF6vP1EACA4Z+5BlN+FTipHHs+bSEgqkPZiiANDH7Zot5Iqv\n" + "1q0fRyldNRZNZK7DWp08BPNVWGA/EnEuKJiURxnxBaxNXbUyMCdjxvMvAoGBANRT\n" + "utbrqS/bAa/DcHKn3V6DRqBl3TDOfvCNjiKC84a67F2uXgzLIdMktr4d1NyCZVJd\n" + "7/zVgWORLIdg1eAi6rYGoOvNV39wwga7CF+m9sBY0wAaKYCELe6L26r4aQHVCX6n\n" + "rnIgUv+4o4itmU2iP0r3wlmDC9pDRQP82vfvQPlfAoGASwhleANW/quvq2HdViq8\n" + "Mje2HBalfhrRfpDTHK8JUBSFjTzuWG42GxJRtgVbb8x2ElujAKGDCaetMO5VSGu7\n" + "Fs5hw6iAFCpdXY0yhl+XUi2R8kwM2EPQ4lKO3jqkq0ClNmqn9a5jQWcCVt9yMLNS\n" + "fLbHeI8EpiCf34ngIcrLXNkCgYEAzlcEZuKkC46xB+dNew8pMTUwSKZVm53BfPKD\n" + "44QRN6imFbBjU9mAaJnwQbfp6dWKs834cGPolyM4++MeVfB42iZ88ksesgmZdUMD\n" + "szkl6O0pOJs0I+HQZVdjRbadDZvD22MHQ3+oST1dJ3FVXz3Cdo9qPuT8esMO6f4r\n" + "qfDH2s8CgYAXC/lWWHQ//PGP0pH4oiEXisx1K0X1u0xMGgrChxBRGRiKZUwNMIvJ\n" + "TqUu7IKizK19cLHF/NBvxHYHFw+m7puNjn6T1RtRCUjRZT7Dx1VHfVosL9ih5DA8\n" + "tpbZA5KGKcvHtB5DDgT0MHwzBZnb4Q//Rhovzn+HXZPsJTTgHHy3NQ==\n" + "-----END RSA PRIVATE KEY-----\n"); const QByteArray keyData = keyString.toLatin1(); @@ -183,16 +175,14 @@ void TestOpenSSHKey::testParseRSA() void TestOpenSSHKey::testDecryptAES256CBC() { - const QString keyString = QString( - "-----BEGIN OPENSSH PRIVATE KEY-----\n" - "b3BlbnNzaC1rZXktdjEAAAAACmFlczI1Ni1jYmMAAAAGYmNyeXB0AAAAGAAAABD2A0agtd\n" - "oGtJiI9JvIxYbTAAAAEAAAAAEAAAAzAAAAC3NzaC1lZDI1NTE5AAAAIDPvDXmi0w1rdMoX\n" - "fOeyZ0Q/v+wqq/tPFgJwxnW5ADtfAAAAsC3UPsf035hrF5SgZ48p55iDFPiyGfZC/C3vQx\n" - "+THzpQo8DTUmFokdPn8wvDYGQoIcr9q0RzJuKV87eMQf3zzvZfJthtLYBlt330Deivv9AQ\n" - "MbKdhPZ4SfwRvv0grgT2EVId3GQAPgSVBhXYQTOf2CdmbXV4kieFLTmSsBMy+v6Qn5Rqur\n" - "PDWBwuLQgamcVDZuhrkUEqIVJZU2zAiRU2oAXsw/XOgFV6+Y5UZmLwWJQZ\n" - "-----END OPENSSH PRIVATE KEY-----\n" - ); + const QString keyString = QString("-----BEGIN OPENSSH PRIVATE KEY-----\n" + "b3BlbnNzaC1rZXktdjEAAAAACmFlczI1Ni1jYmMAAAAGYmNyeXB0AAAAGAAAABD2A0agtd\n" + "oGtJiI9JvIxYbTAAAAEAAAAAEAAAAzAAAAC3NzaC1lZDI1NTE5AAAAIDPvDXmi0w1rdMoX\n" + "fOeyZ0Q/v+wqq/tPFgJwxnW5ADtfAAAAsC3UPsf035hrF5SgZ48p55iDFPiyGfZC/C3vQx\n" + "+THzpQo8DTUmFokdPn8wvDYGQoIcr9q0RzJuKV87eMQf3zzvZfJthtLYBlt330Deivv9AQ\n" + "MbKdhPZ4SfwRvv0grgT2EVId3GQAPgSVBhXYQTOf2CdmbXV4kieFLTmSsBMy+v6Qn5Rqur\n" + "PDWBwuLQgamcVDZuhrkUEqIVJZU2zAiRU2oAXsw/XOgFV6+Y5UZmLwWJQZ\n" + "-----END OPENSSH PRIVATE KEY-----\n"); const QByteArray keyData = keyString.toLatin1(); @@ -217,16 +207,14 @@ void TestOpenSSHKey::testDecryptAES256CBC() void TestOpenSSHKey::testDecryptAES256CTR() { - const QString keyString = QString( - "-----BEGIN OPENSSH PRIVATE KEY-----\n" - "b3BlbnNzaC1rZXktdjEAAAAACmFlczI1Ni1jdHIAAAAGYmNyeXB0AAAAGAAAABAMhIAypt\n" - "WP4tZJBmMwq0tTAAAAEAAAAAEAAAAzAAAAC3NzaC1lZDI1NTE5AAAAIErNsS8ROy43XoWC\n" - "nO9Sn2lEFBJYcDVtRPM1t6WB7W7OAAAAsFKXMOlPILoTmMj2JmcqzjaYAhaCezx18HDp76\n" - "VrNxaZTd0T28EGFSkzrReeewpJWy/bWlhLoXR5fRyOSSto+iMg/pibIvIJMrD5sqxlxr/e\n" - "c5lSeSZUzIK8Rv+ou/3EFDcY5jp8hVXqA4qNtoM/3fV52vmwlNje5d1V5Gsr4U8443+i+p\n" - "swqksozfatkynk51uR/9QFoOJKlsL/Z3LkK1S/apYz/K331iU1f5ozFELf\n" - "-----END OPENSSH PRIVATE KEY-----\n" - ); + const QString keyString = QString("-----BEGIN OPENSSH PRIVATE KEY-----\n" + "b3BlbnNzaC1rZXktdjEAAAAACmFlczI1Ni1jdHIAAAAGYmNyeXB0AAAAGAAAABAMhIAypt\n" + "WP4tZJBmMwq0tTAAAAEAAAAAEAAAAzAAAAC3NzaC1lZDI1NTE5AAAAIErNsS8ROy43XoWC\n" + "nO9Sn2lEFBJYcDVtRPM1t6WB7W7OAAAAsFKXMOlPILoTmMj2JmcqzjaYAhaCezx18HDp76\n" + "VrNxaZTd0T28EGFSkzrReeewpJWy/bWlhLoXR5fRyOSSto+iMg/pibIvIJMrD5sqxlxr/e\n" + "c5lSeSZUzIK8Rv+ou/3EFDcY5jp8hVXqA4qNtoM/3fV52vmwlNje5d1V5Gsr4U8443+i+p\n" + "swqksozfatkynk51uR/9QFoOJKlsL/Z3LkK1S/apYz/K331iU1f5ozFELf\n" + "-----END OPENSSH PRIVATE KEY-----\n"); const QByteArray keyData = keyString.toLatin1(); diff --git a/tests/TestRandom.cpp b/tests/TestRandom.cpp index 7575e3a58..07d1c683a 100644 --- a/tests/TestRandom.cpp +++ b/tests/TestRandom.cpp @@ -20,7 +20,6 @@ #include "core/Endian.h" #include "core/Global.h" - QTEST_GUILESS_MAIN(TestRandom) void TestRandom::initTestCase() @@ -70,7 +69,6 @@ void TestRandom::testUIntRange() QCOMPARE(randomGen()->randomUIntRange(100, 200), 142U); } - RandomBackendTest::RandomBackendTest() : m_bytesIndex(0) { diff --git a/tests/TestSymmetricCipher.cpp b/tests/TestSymmetricCipher.cpp index a5159e0d6..bec894c06 100644 --- a/tests/TestSymmetricCipher.cpp +++ b/tests/TestSymmetricCipher.cpp @@ -51,8 +51,7 @@ void TestSymmetricCipher::testAes128CbcEncryption() QVERIFY(ok); QBuffer buffer; - SymmetricCipherStream stream(&buffer, SymmetricCipher::Aes128, SymmetricCipher::Cbc, - SymmetricCipher::Encrypt); + SymmetricCipherStream stream(&buffer, SymmetricCipher::Aes128, SymmetricCipher::Cbc, SymmetricCipher::Encrypt); QVERIFY(stream.init(key, iv)); buffer.open(QIODevice::WriteOnly); QVERIFY(stream.open(QIODevice::WriteOnly)); @@ -98,8 +97,7 @@ void TestSymmetricCipher::testAes128CbcDecryption() // padded with 16 0x10 bytes QByteArray cipherTextPadded = cipherText + QByteArray::fromHex("55e21d7100b988ffec32feeafaf23538"); QBuffer buffer(&cipherTextPadded); - SymmetricCipherStream stream(&buffer, SymmetricCipher::Aes128, SymmetricCipher::Cbc, - SymmetricCipher::Decrypt); + SymmetricCipherStream stream(&buffer, SymmetricCipher::Aes128, SymmetricCipher::Cbc, SymmetricCipher::Decrypt); QVERIFY(stream.init(key, iv)); buffer.open(QIODevice::ReadOnly); QVERIFY(stream.open(QIODevice::ReadOnly)); @@ -132,13 +130,11 @@ void TestSymmetricCipher::testAes256CbcEncryption() QVERIFY(cipher.init(key, iv)); QCOMPARE(cipher.blockSize(), 16); - QCOMPARE(cipher.process(plainText, &ok), - cipherText); + QCOMPARE(cipher.process(plainText, &ok), cipherText); QVERIFY(ok); QBuffer buffer; - SymmetricCipherStream stream(&buffer, SymmetricCipher::Aes256, SymmetricCipher::Cbc, - SymmetricCipher::Encrypt); + SymmetricCipherStream stream(&buffer, SymmetricCipher::Aes256, SymmetricCipher::Cbc, SymmetricCipher::Encrypt); QVERIFY(stream.init(key, iv)); buffer.open(QIODevice::WriteOnly); QVERIFY(stream.open(QIODevice::WriteOnly)); @@ -179,33 +175,27 @@ void TestSymmetricCipher::testAes256CbcDecryption() QVERIFY(cipher.init(key, iv)); QCOMPARE(cipher.blockSize(), 16); - QCOMPARE(cipher.process(cipherText, &ok), - plainText); + QCOMPARE(cipher.process(cipherText, &ok), plainText); QVERIFY(ok); // padded with 16 0x16 bytes QByteArray cipherTextPadded = cipherText + QByteArray::fromHex("3a3aa5e0213db1a9901f9036cf5102d2"); QBuffer buffer(&cipherTextPadded); - SymmetricCipherStream stream(&buffer, SymmetricCipher::Aes256, SymmetricCipher::Cbc, - SymmetricCipher::Decrypt); + SymmetricCipherStream stream(&buffer, SymmetricCipher::Aes256, SymmetricCipher::Cbc, SymmetricCipher::Decrypt); QVERIFY(stream.init(key, iv)); buffer.open(QIODevice::ReadOnly); QVERIFY(stream.open(QIODevice::ReadOnly)); - QCOMPARE(stream.read(10), - plainText.left(10)); + QCOMPARE(stream.read(10), plainText.left(10)); buffer.reset(); QVERIFY(stream.reset()); - QCOMPARE(stream.read(20), - plainText.left(20)); + QCOMPARE(stream.read(20), plainText.left(20)); buffer.reset(); QVERIFY(stream.reset()); - QCOMPARE(stream.read(16), - plainText.left(16)); + QCOMPARE(stream.read(16), plainText.left(16)); buffer.reset(); QVERIFY(stream.reset()); - QCOMPARE(stream.read(100), - plainText); + QCOMPARE(stream.read(100), plainText); } void TestSymmetricCipher::testAes256CtrEncryption() @@ -224,8 +214,7 @@ void TestSymmetricCipher::testAes256CtrEncryption() QVERIFY(cipher.init(key, ctr)); QCOMPARE(cipher.blockSize(), 16); - QCOMPARE(cipher.process(plainText, &ok), - cipherText); + QCOMPARE(cipher.process(plainText, &ok), cipherText); QVERIFY(ok); } @@ -243,8 +232,7 @@ void TestSymmetricCipher::testAes256CtrDecryption() QVERIFY(cipher.init(key, ctr)); QCOMPARE(cipher.blockSize(), 16); - QCOMPARE(cipher.process(cipherText, &ok), - plainText); + QCOMPARE(cipher.process(cipherText, &ok), plainText); QVERIFY(ok); } @@ -252,39 +240,31 @@ void TestSymmetricCipher::testTwofish256CbcEncryption() { // NIST MCT Known-Answer Tests (cbc_e_m.txt) // https://www.schneier.com/code/twofish-kat.zip - - QVector keys { - QByteArray::fromHex("0000000000000000000000000000000000000000000000000000000000000000"), - QByteArray::fromHex("D0A260EB41755B19374BABF259A79DB3EA7162E65490B03B1AE4871FB35EF23B"), - QByteArray::fromHex("8D55E4849A4DED08D89881E6708EDD26BEEE942073DFB3790B2798B240ACD74A"), - QByteArray::fromHex("606EFDC2066A837AF0430EBE4CF1F21071CCB236C33B4B9D82404FDB05C74621"), - QByteArray::fromHex("B119AA9485CEEEB4CC778AF21121E54DE4BDBA3498C61C8FD9004AA0C71909C3") - }; - QVector ivs { - QByteArray::fromHex("00000000000000000000000000000000"), - QByteArray::fromHex("EA7162E65490B03B1AE4871FB35EF23B"), - QByteArray::fromHex("549FF6C6274F034211C31FADF3F22571"), - QByteArray::fromHex("CF222616B0E4F8E48967D769456B916B"), - QByteArray::fromHex("957108025BFD57125B40057BC2DE4FE2") - }; - QVector plainTexts { - QByteArray::fromHex("00000000000000000000000000000000"), - QByteArray::fromHex("D0A260EB41755B19374BABF259A79DB3"), - QByteArray::fromHex("5DF7846FDB38B611EFD32A1429294095"), - QByteArray::fromHex("ED3B19469C276E7228DB8F583C7F2F36"), - QByteArray::fromHex("D177575683A46DCE3C34844C5DD0175D") - }; - QVector cipherTexts { - QByteArray::fromHex("EA7162E65490B03B1AE4871FB35EF23B"), - QByteArray::fromHex("549FF6C6274F034211C31FADF3F22571"), - QByteArray::fromHex("CF222616B0E4F8E48967D769456B916B"), - QByteArray::fromHex("957108025BFD57125B40057BC2DE4FE2"), - QByteArray::fromHex("6F725C5950133F82EF021A94CADC8508") - }; - + + QVector keys{QByteArray::fromHex("0000000000000000000000000000000000000000000000000000000000000000"), + QByteArray::fromHex("D0A260EB41755B19374BABF259A79DB3EA7162E65490B03B1AE4871FB35EF23B"), + QByteArray::fromHex("8D55E4849A4DED08D89881E6708EDD26BEEE942073DFB3790B2798B240ACD74A"), + QByteArray::fromHex("606EFDC2066A837AF0430EBE4CF1F21071CCB236C33B4B9D82404FDB05C74621"), + QByteArray::fromHex("B119AA9485CEEEB4CC778AF21121E54DE4BDBA3498C61C8FD9004AA0C71909C3")}; + QVector ivs{QByteArray::fromHex("00000000000000000000000000000000"), + QByteArray::fromHex("EA7162E65490B03B1AE4871FB35EF23B"), + QByteArray::fromHex("549FF6C6274F034211C31FADF3F22571"), + QByteArray::fromHex("CF222616B0E4F8E48967D769456B916B"), + QByteArray::fromHex("957108025BFD57125B40057BC2DE4FE2")}; + QVector plainTexts{QByteArray::fromHex("00000000000000000000000000000000"), + QByteArray::fromHex("D0A260EB41755B19374BABF259A79DB3"), + QByteArray::fromHex("5DF7846FDB38B611EFD32A1429294095"), + QByteArray::fromHex("ED3B19469C276E7228DB8F583C7F2F36"), + QByteArray::fromHex("D177575683A46DCE3C34844C5DD0175D")}; + QVector cipherTexts{QByteArray::fromHex("EA7162E65490B03B1AE4871FB35EF23B"), + QByteArray::fromHex("549FF6C6274F034211C31FADF3F22571"), + QByteArray::fromHex("CF222616B0E4F8E48967D769456B916B"), + QByteArray::fromHex("957108025BFD57125B40057BC2DE4FE2"), + QByteArray::fromHex("6F725C5950133F82EF021A94CADC8508")}; + SymmetricCipher cipher(SymmetricCipher::Twofish, SymmetricCipher::Cbc, SymmetricCipher::Encrypt); bool ok; - + for (int i = 0; i < keys.size(); ++i) { QVERIFY(cipher.init(keys[i], ivs[i])); QByteArray ptNext = plainTexts[i]; @@ -297,14 +277,14 @@ void TestSymmetricCipher::testTwofish256CbcEncryption() break; ptNext = ctPrev; ctPrev = ctCur; - + ctCur = cipher.process(ptNext, &ok); if (!ok) break; ptNext = ctPrev; ctPrev = ctCur; } - + QVERIFY(ok); QCOMPARE(ctCur, cipherTexts[i]); } @@ -314,39 +294,31 @@ void TestSymmetricCipher::testTwofish256CbcDecryption() { // NIST MCT Known-Answer Tests (cbc_d_m.txt) // https://www.schneier.com/code/twofish-kat.zip - - QVector keys { - QByteArray::fromHex("0000000000000000000000000000000000000000000000000000000000000000"), - QByteArray::fromHex("1B1FE8F5A911CD4C0D800EDCE8ED0A942CBA6271A1044F90C30BA8FE91E1C163"), - QByteArray::fromHex("EBA31FF8D2A24FDD769A937353E23257294A33394E4D17A668060AD8230811A1"), - QByteArray::fromHex("1DCF1915C389AB273F80F897BF008F058ED89F58A95C1BE523C4B11295ED2D0F"), - QByteArray::fromHex("491B9A66D3ED4EF19F02180289D5B1A1C2596AE568540A95DC5244198A9B8869") - }; - QVector ivs { - QByteArray::fromHex("00000000000000000000000000000000"), - QByteArray::fromHex("1B1FE8F5A911CD4C0D800EDCE8ED0A94"), - QByteArray::fromHex("F0BCF70D7BB382917B1A9DAFBB0F38C3"), - QByteArray::fromHex("F66C06ED112BE4FA491A6BE4ECE2BD52"), - QByteArray::fromHex("54D483731064E5D6A082E09536D53EA4") - }; - QVector plainTexts { - QByteArray::fromHex("2CBA6271A1044F90C30BA8FE91E1C163"), - QByteArray::fromHex("05F05148EF495836AB0DA226B2E9D0C2"), - QByteArray::fromHex("A792AC61E7110C434BC2BBCAB6E53CAE"), - QByteArray::fromHex("4C81F5BDC1081170FF96F50B1F76A566"), - QByteArray::fromHex("BD959F5B787037631A37051EA5F369F8") - }; - QVector cipherTexts { - QByteArray::fromHex("00000000000000000000000000000000"), - QByteArray::fromHex("2CBA6271A1044F90C30BA8FE91E1C163"), - QByteArray::fromHex("05F05148EF495836AB0DA226B2E9D0C2"), - QByteArray::fromHex("A792AC61E7110C434BC2BBCAB6E53CAE"), - QByteArray::fromHex("4C81F5BDC1081170FF96F50B1F76A566") - }; - + + QVector keys{QByteArray::fromHex("0000000000000000000000000000000000000000000000000000000000000000"), + QByteArray::fromHex("1B1FE8F5A911CD4C0D800EDCE8ED0A942CBA6271A1044F90C30BA8FE91E1C163"), + QByteArray::fromHex("EBA31FF8D2A24FDD769A937353E23257294A33394E4D17A668060AD8230811A1"), + QByteArray::fromHex("1DCF1915C389AB273F80F897BF008F058ED89F58A95C1BE523C4B11295ED2D0F"), + QByteArray::fromHex("491B9A66D3ED4EF19F02180289D5B1A1C2596AE568540A95DC5244198A9B8869")}; + QVector ivs{QByteArray::fromHex("00000000000000000000000000000000"), + QByteArray::fromHex("1B1FE8F5A911CD4C0D800EDCE8ED0A94"), + QByteArray::fromHex("F0BCF70D7BB382917B1A9DAFBB0F38C3"), + QByteArray::fromHex("F66C06ED112BE4FA491A6BE4ECE2BD52"), + QByteArray::fromHex("54D483731064E5D6A082E09536D53EA4")}; + QVector plainTexts{QByteArray::fromHex("2CBA6271A1044F90C30BA8FE91E1C163"), + QByteArray::fromHex("05F05148EF495836AB0DA226B2E9D0C2"), + QByteArray::fromHex("A792AC61E7110C434BC2BBCAB6E53CAE"), + QByteArray::fromHex("4C81F5BDC1081170FF96F50B1F76A566"), + QByteArray::fromHex("BD959F5B787037631A37051EA5F369F8")}; + QVector cipherTexts{QByteArray::fromHex("00000000000000000000000000000000"), + QByteArray::fromHex("2CBA6271A1044F90C30BA8FE91E1C163"), + QByteArray::fromHex("05F05148EF495836AB0DA226B2E9D0C2"), + QByteArray::fromHex("A792AC61E7110C434BC2BBCAB6E53CAE"), + QByteArray::fromHex("4C81F5BDC1081170FF96F50B1F76A566")}; + SymmetricCipher cipher(SymmetricCipher::Twofish, SymmetricCipher::Cbc, SymmetricCipher::Decrypt); bool ok; - + for (int i = 0; i < keys.size(); ++i) { cipher.init(keys[i], ivs[i]); QByteArray ctNext = cipherTexts[i]; @@ -357,13 +329,13 @@ void TestSymmetricCipher::testTwofish256CbcDecryption() if (!ok) break; ctNext = ptCur; - + ptCur = cipher.process(ctNext, &ok); if (!ok) break; ctNext = ptCur; } - + QVERIFY(ok); QCOMPARE(ptCur, plainTexts[i]); } @@ -437,8 +409,8 @@ void TestSymmetricCipher::testChaCha20() SymmetricCipher cipher(SymmetricCipher::ChaCha20, SymmetricCipher::Stream, SymmetricCipher::Encrypt); QVERIFY(cipher.init(key, iv)); QCOMPARE(cipher.process(QByteArray(64, 0), &ok), - QByteArray::fromHex( - "76b8e0ada0f13d90405d6ae55386bd28bdd219b8a08ded1aa836efcc8b770dc7da41597c5157488d7724e03fb8d84a376a43b8f41518a11cc387b669b2ee6586")); + QByteArray::fromHex("76b8e0ada0f13d90405d6ae55386bd28bdd219b8a08ded1aa836efcc8b770dc7da41597c5157488d7" + "724e03fb8d84a376a43b8f41518a11cc387b669b2ee6586")); QVERIFY(ok); } @@ -448,8 +420,8 @@ void TestSymmetricCipher::testChaCha20() SymmetricCipher cipher(SymmetricCipher::ChaCha20, SymmetricCipher::Stream, SymmetricCipher::Encrypt); QVERIFY(cipher.init(key, iv)); QCOMPARE(cipher.process(QByteArray(64, 0), &ok), - QByteArray::fromHex( - "4540f05a9f1fb296d7736e7b208e3c96eb4fe1834688d2604f450952ed432d41bbe2a0b6ea7566d2a5d1e7e20d42af2c53d792b1c43fea817e9ad275ae546963")); + QByteArray::fromHex("4540f05a9f1fb296d7736e7b208e3c96eb4fe1834688d2604f450952ed432d41bbe2a0b6ea7566d2a" + "5d1e7e20d42af2c53d792b1c43fea817e9ad275ae546963")); QVERIFY(ok); } @@ -459,8 +431,8 @@ void TestSymmetricCipher::testChaCha20() SymmetricCipher cipher(SymmetricCipher::ChaCha20, SymmetricCipher::Stream, SymmetricCipher::Encrypt); QVERIFY(cipher.init(key, iv)); QCOMPARE(cipher.process(QByteArray(60, 0), &ok), - QByteArray::fromHex( - "de9cba7bf3d69ef5e786dc63973f653a0b49e015adbff7134fcb7df137821031e85a050278a7084527214f73efc7fa5b5277062eb7a0433e445f41e3")); + QByteArray::fromHex("de9cba7bf3d69ef5e786dc63973f653a0b49e015adbff7134fcb7df137821031e85a050278a708452" + "7214f73efc7fa5b5277062eb7a0433e445f41e3")); QVERIFY(ok); } @@ -470,8 +442,8 @@ void TestSymmetricCipher::testChaCha20() SymmetricCipher cipher(SymmetricCipher::ChaCha20, SymmetricCipher::Stream, SymmetricCipher::Encrypt); QVERIFY(cipher.init(key, iv)); QCOMPARE(cipher.process(QByteArray(64, 0), &ok), - QByteArray::fromHex( - "ef3fdfd6c61578fbf5cf35bd3dd33b8009631634d21e42ac33960bd138e50d32111e4caf237ee53ca8ad6426194a88545ddc497a0b466e7d6bbdb0041b2f586b")); + QByteArray::fromHex("ef3fdfd6c61578fbf5cf35bd3dd33b8009631634d21e42ac33960bd138e50d32111e4caf237ee53ca" + "8ad6426194a88545ddc497a0b466e7d6bbdb0041b2f586b")); QVERIFY(ok); } } @@ -485,8 +457,7 @@ void TestSymmetricCipher::testPadding() QBuffer buffer; buffer.open(QIODevice::ReadWrite); - SymmetricCipherStream streamEnc(&buffer, SymmetricCipher::Aes256, SymmetricCipher::Cbc, - SymmetricCipher::Encrypt); + SymmetricCipherStream streamEnc(&buffer, SymmetricCipher::Aes256, SymmetricCipher::Cbc, SymmetricCipher::Encrypt); QVERIFY(streamEnc.init(key, iv)); streamEnc.open(QIODevice::WriteOnly); streamEnc.write(plainText); @@ -495,8 +466,7 @@ void TestSymmetricCipher::testPadding() // make sure padding is written QCOMPARE(buffer.buffer().size(), 16); - SymmetricCipherStream streamDec(&buffer, SymmetricCipher::Aes256, SymmetricCipher::Cbc, - SymmetricCipher::Decrypt); + SymmetricCipherStream streamDec(&buffer, SymmetricCipher::Aes256, SymmetricCipher::Cbc, SymmetricCipher::Decrypt); QVERIFY(streamDec.init(key, iv)); streamDec.open(QIODevice::ReadOnly); QByteArray decrypted = streamDec.readAll(); @@ -510,8 +480,7 @@ void TestSymmetricCipher::testStreamReset() QBuffer buffer; QVERIFY(buffer.open(QIODevice::WriteOnly)); - SymmetricCipherStream writer(&buffer, SymmetricCipher::Aes256, SymmetricCipher::Cbc, - SymmetricCipher::Encrypt); + SymmetricCipherStream writer(&buffer, SymmetricCipher::Aes256, SymmetricCipher::Cbc, SymmetricCipher::Encrypt); QVERIFY(writer.init(key, iv)); QVERIFY(writer.open(QIODevice::WriteOnly)); QCOMPARE(writer.write(QByteArray(4, 'Z')), qint64(4)); diff --git a/tests/TestTotp.cpp b/tests/TestTotp.cpp index 02af663a1..a91ae00b3 100644 --- a/tests/TestTotp.cpp +++ b/tests/TestTotp.cpp @@ -81,64 +81,55 @@ void TestTotp::testTotpCode() void TestTotp::testEncoderData() { - for (quint8 key: Totp::encoders.keys()) { + for (quint8 key : Totp::encoders.keys()) { const Totp::Encoder& enc = Totp::encoders.value(key); - QVERIFY2(enc.digits != 0, - qPrintable(QString("Custom encoders cannot have zero-value for digits field: %1(%2)") - .arg(enc.name) - .arg(key))); + QVERIFY2( + enc.digits != 0, + qPrintable( + QString("Custom encoders cannot have zero-value for digits field: %1(%2)").arg(enc.name).arg(key))); QVERIFY2(!enc.name.isEmpty(), - qPrintable(QString("Custom encoders must have a name: %1(%2)") - .arg(enc.name) - .arg(key))); + qPrintable(QString("Custom encoders must have a name: %1(%2)").arg(enc.name).arg(key))); QVERIFY2(!enc.shortName.isEmpty(), - qPrintable(QString("Custom encoders must have a shortName: %1(%2)") - .arg(enc.name) - .arg(key))); + qPrintable(QString("Custom encoders must have a shortName: %1(%2)").arg(enc.name).arg(key))); QVERIFY2(Totp::shortNameToEncoder.contains(enc.shortName), - qPrintable(QString("No shortNameToEncoder entry found for custom encoder: %1(%2) %3") - .arg(enc.name) - .arg(key) - .arg(enc.shortName))); + qPrintable(QString("No shortNameToEncoder entry found for custom encoder: %1(%2) %3") + .arg(enc.name) + .arg(key) + .arg(enc.shortName))); QVERIFY2(Totp::shortNameToEncoder[enc.shortName] == key, - qPrintable(QString("shortNameToEncoder doesn't reference this custome encoder: %1(%2) %3") - .arg(enc.name) - .arg(key) - .arg(enc.shortName))); + qPrintable(QString("shortNameToEncoder doesn't reference this custome encoder: %1(%2) %3") + .arg(enc.name) + .arg(key) + .arg(enc.shortName))); QVERIFY2(Totp::nameToEncoder.contains(enc.name), - qPrintable(QString("No nameToEncoder entry found for custom encoder: %1(%2) %3") - .arg(enc.name) - .arg(key) - .arg(enc.shortName))); + qPrintable(QString("No nameToEncoder entry found for custom encoder: %1(%2) %3") + .arg(enc.name) + .arg(key) + .arg(enc.shortName))); QVERIFY2(Totp::nameToEncoder[enc.name] == key, - qPrintable(QString("nameToEncoder doesn't reference this custome encoder: %1(%2) %3") - .arg(enc.name) - .arg(key) - .arg(enc.shortName))); + qPrintable(QString("nameToEncoder doesn't reference this custome encoder: %1(%2) %3") + .arg(enc.name) + .arg(key) + .arg(enc.shortName))); } - for (const QString & key: Totp::nameToEncoder.keys()) { + for (const QString& key : Totp::nameToEncoder.keys()) { quint8 value = Totp::nameToEncoder.value(key); QVERIFY2(Totp::encoders.contains(value), - qPrintable(QString("No custom encoder found for encoder named %1(%2)") - .arg(value) - .arg(key))); + qPrintable(QString("No custom encoder found for encoder named %1(%2)").arg(value).arg(key))); QVERIFY2(Totp::encoders[value].name == key, - qPrintable(QString("nameToEncoder doesn't reference the right custom encoder: %1(%2)") - .arg(value) - .arg(key))); + qPrintable( + QString("nameToEncoder doesn't reference the right custom encoder: %1(%2)").arg(value).arg(key))); } - for (const QString & key: Totp::shortNameToEncoder.keys()) { + for (const QString& key : Totp::shortNameToEncoder.keys()) { quint8 value = Totp::shortNameToEncoder.value(key); QVERIFY2(Totp::encoders.contains(value), - qPrintable(QString("No custom encoder found for short-name encoder %1(%2)") - .arg(value) - .arg(key))); - QVERIFY2(Totp::encoders[value].shortName == key, - qPrintable(QString("shortNameToEncoder doesn't reference the right custom encoder: %1(%2)") - .arg(value) - .arg(key))); + qPrintable(QString("No custom encoder found for short-name encoder %1(%2)").arg(value).arg(key))); + QVERIFY2( + Totp::encoders[value].shortName == key, + qPrintable( + QString("shortNameToEncoder doesn't reference the right custom encoder: %1(%2)").arg(value).arg(key))); } } @@ -153,7 +144,6 @@ void TestTotp::testSteamTotp() QCOMPARE(digits, quint8(Totp::ENCODER_STEAM)); QCOMPARE(step, quint8(30)); - QByteArray seed = QString("63BEDWCQZKTQWPESARIERL5DTTQFCJTK").toLatin1(); // These time/value pairs were created by running the Steam Guard function of the diff --git a/tests/TestWildcardMatcher.cpp b/tests/TestWildcardMatcher.cpp index e5d1d117d..b7b92fdd7 100644 --- a/tests/TestWildcardMatcher.cpp +++ b/tests/TestWildcardMatcher.cpp @@ -70,8 +70,7 @@ void TestWildcardMatcher::verifyMatchResult(QString pattern, bool expected) { if (expected) { verifyMatch(pattern); - } - else { + } else { verifyNoMatch(pattern); } } diff --git a/tests/TestYkChallengeResponseKey.cpp b/tests/TestYkChallengeResponseKey.cpp index 276ba7325..126d00315 100644 --- a/tests/TestYkChallengeResponseKey.cpp +++ b/tests/TestYkChallengeResponseKey.cpp @@ -40,9 +40,7 @@ void TestYubiKeyChalResp::init() void TestYubiKeyChalResp::detectDevices() { - connect(YubiKey::instance(), SIGNAL(detected(int,bool)), - SLOT(ykDetected(int,bool)), - Qt::QueuedConnection); + connect(YubiKey::instance(), SIGNAL(detected(int, bool)), SLOT(ykDetected(int, bool)), Qt::QueuedConnection); QtConcurrent::run(YubiKey::instance(), &YubiKey::detect); // need to wait for the hardware (that's hopefully plugged in)... diff --git a/tests/TestYkChallengeResponseKey.h b/tests/TestYkChallengeResponseKey.h index 82223ec35..81253cc90 100644 --- a/tests/TestYkChallengeResponseKey.h +++ b/tests/TestYkChallengeResponseKey.h @@ -24,7 +24,7 @@ #include "keys/YkChallengeResponseKey.h" -class TestYubiKeyChalResp: public QObject +class TestYubiKeyChalResp : public QObject { Q_OBJECT diff --git a/tests/gui/TemporaryFile.cpp b/tests/gui/TemporaryFile.cpp index 7c7a1c5d4..b6d20848b 100644 --- a/tests/gui/TemporaryFile.cpp +++ b/tests/gui/TemporaryFile.cpp @@ -56,7 +56,7 @@ void TemporaryFile::close() #endif } -qint64 TemporaryFile::write(const char *data, qint64 maxSize) +qint64 TemporaryFile::write(const char* data, qint64 maxSize) { #ifdef Q_OS_WIN return m_file.write(data, maxSize); @@ -65,7 +65,7 @@ qint64 TemporaryFile::write(const char *data, qint64 maxSize) #endif } -qint64 TemporaryFile::write(const QByteArray &byteArray) +qint64 TemporaryFile::write(const QByteArray& byteArray) { #ifdef Q_OS_WIN return m_file.write(byteArray); diff --git a/tests/gui/TemporaryFile.h b/tests/gui/TemporaryFile.h index f1cff3ef4..8a98d9235 100644 --- a/tests/gui/TemporaryFile.h +++ b/tests/gui/TemporaryFile.h @@ -19,8 +19,8 @@ #ifndef KEEPASSX_TEMPORARYFILE_H #define KEEPASSX_TEMPORARYFILE_H -#include #include +#include #include /** @@ -48,8 +48,8 @@ public: bool open(); void close(); - qint64 write(const char *data, qint64 maxSize); - qint64 write(const QByteArray &byteArray); + qint64 write(const char* data, qint64 maxSize); + qint64 write(const QByteArray& byteArray); QString fileName() const; QString filePath() const; diff --git a/tests/gui/TestGui.cpp b/tests/gui/TestGui.cpp index c736ea485..0fe49eb9d 100644 --- a/tests/gui/TestGui.cpp +++ b/tests/gui/TestGui.cpp @@ -21,22 +21,22 @@ #include #include -#include -#include -#include -#include -#include #include -#include -#include +#include #include +#include +#include +#include +#include +#include +#include +#include +#include +#include #include +#include #include #include -#include -#include -#include -#include #include "config-keepassx-tests.h" #include "core/Config.h" @@ -48,21 +48,21 @@ #include "crypto/Crypto.h" #include "crypto/kdf/AesKdf.h" #include "format/KeePass2Reader.h" +#include "gui/CloneDialog.h" #include "gui/DatabaseTabWidget.h" #include "gui/DatabaseWidget.h" -#include "gui/CloneDialog.h" -#include "gui/PasswordEdit.h" -#include "gui/TotpDialog.h" -#include "gui/SetupTotpDialog.h" #include "gui/FileDialog.h" #include "gui/MainWindow.h" #include "gui/MessageBox.h" +#include "gui/PasswordEdit.h" #include "gui/SearchWidget.h" +#include "gui/SetupTotpDialog.h" +#include "gui/TotpDialog.h" #include "gui/entry/EditEntryWidget.h" #include "gui/entry/EntryView.h" +#include "gui/group/EditGroupWidget.h" #include "gui/group/GroupModel.h" #include "gui/group/GroupView.h" -#include "gui/group/EditGroupWidget.h" #include "keys/PasswordKey.h" void TestGui::initTestCase() @@ -228,7 +228,7 @@ void TestGui::testAutoreloadDatabase() // the General group contains one entry from the new db data QCOMPARE(m_db->rootGroup()->findChildByName("General")->entries().size(), 1); - QVERIFY(! m_tabWidget->tabText(m_tabWidget->currentIndex()).endsWith("*")); + QVERIFY(!m_tabWidget->tabText(m_tabWidget->currentIndex()).endsWith("*")); // Reset the state cleanup(); @@ -252,7 +252,7 @@ void TestGui::testAutoreloadDatabase() cleanup(); init(); - // Test accepting a merge of edits into autoreload + // Test accepting a merge of edits into autoreload // Turn on autoload so we only get one messagebox (for the merge) config()->set("AutoReloadOnChange", true); @@ -559,17 +559,17 @@ void TestGui::testPasswordEntryEntropy() editNewPassword->setText(""); QTest::keyClicks(editNewPassword, "correcthorsebatterystaple"); - QCOMPARE(entropyLabel->text(), QString("Entropy: 47.98 bit")); + QCOMPARE(entropyLabel->text(), QString("Entropy: 47.98 bit")); QCOMPARE(strengthLabel->text(), QString("Password Quality: Weak")); editNewPassword->setText(""); QTest::keyClicks(editNewPassword, "YQC3kbXbjC652dTDH"); - QCOMPARE(entropyLabel->text(), QString("Entropy: 95.83 bit")); + QCOMPARE(entropyLabel->text(), QString("Entropy: 95.83 bit")); QCOMPARE(strengthLabel->text(), QString("Password Quality: Good")); editNewPassword->setText(""); QTest::keyClicks(editNewPassword, "Bs5ZFfthWzR8DGFEjaCM6bGqhmCT4km"); - QCOMPARE(entropyLabel->text(), QString("Entropy: 174.59 bit")); + QCOMPARE(entropyLabel->text(), QString("Entropy: 174.59 bit")); QCOMPARE(strengthLabel->text(), QString("Password Quality: Excellent")); } @@ -613,7 +613,7 @@ void TestGui::testDicewareEntryEntropy() QLabel* entropyLabel = editEntryWidget->findChild("entropyLabel"); QLabel* strengthLabel = editEntryWidget->findChild("strengthLabel"); - QCOMPARE(entropyLabel->text(), QString("Entropy: 77.55 bit")); + QCOMPARE(entropyLabel->text(), QString("Entropy: 77.55 bit")); QCOMPARE(strengthLabel->text(), QString("Password Quality: Good")); } @@ -726,7 +726,7 @@ void TestGui::testSearch() QTest::mouseClick(searchTextEdit, Qt::LeftButton); QTRY_VERIFY(searchTextEdit->hasFocus()); // Test password copy - QClipboard *clipboard = QApplication::clipboard(); + QClipboard* clipboard = QApplication::clipboard(); QTest::keyClick(searchTextEdit, Qt::Key_C, Qt::ControlModifier); QModelIndex searchedItem = entryView->model()->index(0, 1); Entry* searchedEntry = entryView->entryFromIndex(searchedItem); @@ -744,7 +744,7 @@ void TestGui::testSearch() QModelIndex rootGroupIndex = groupView->model()->index(0, 0); clickIndex(groupView->model()->index(0, 0, rootGroupIndex), groupView, Qt::LeftButton); QCOMPARE(groupView->currentGroup()->name(), QString("General")); - + searchWidget->setLimitGroup(false); QTRY_COMPARE(entryView->model()->rowCount(), 2); searchWidget->setLimitGroup(true); @@ -822,7 +822,8 @@ void TestGui::testDeleteEntry() QCOMPARE(groupView->currentGroup(), m_db->rootGroup()); QModelIndex rootGroupIndex = groupView->model()->index(0, 0); clickIndex(groupView->model()->index(groupView->model()->rowCount(rootGroupIndex) - 1, 0, rootGroupIndex), - groupView, Qt::LeftButton); + groupView, + Qt::LeftButton); QCOMPARE(groupView->currentGroup()->name(), m_db->metadata()->recycleBin()->name()); clickIndex(entryView->model()->index(0, 1), entryView, Qt::LeftButton); @@ -843,8 +844,7 @@ void TestGui::testDeleteEntry() QCOMPARE(entryView->model()->rowCount(), 0); QCOMPARE(m_db->metadata()->recycleBin()->entries().size(), 0); - clickIndex(groupView->model()->index(0, 0), - groupView, Qt::LeftButton); + clickIndex(groupView->model()->index(0, 0), groupView, Qt::LeftButton); QCOMPARE(groupView->currentGroup(), m_db->rootGroup()); } @@ -860,9 +860,9 @@ void TestGui::testCloneEntry() triggerAction("actionEntryClone"); - CloneDialog* cloneDialog = m_dbWidget->findChild("CloneDialog"); - QDialogButtonBox* cloneButtonBox = cloneDialog->findChild("buttonBox"); - QTest::mouseClick(cloneButtonBox->button(QDialogButtonBox::Ok), Qt::LeftButton); + CloneDialog* cloneDialog = m_dbWidget->findChild("CloneDialog"); + QDialogButtonBox* cloneButtonBox = cloneDialog->findChild("buttonBox"); + QTest::mouseClick(cloneButtonBox->button(QDialogButtonBox::Ok), Qt::LeftButton); QCOMPARE(entryView->model()->rowCount(), 2); Entry* entryClone = entryView->entryFromIndex(entryView->model()->index(1, 1)); @@ -909,7 +909,7 @@ void TestGui::testEntryPlaceholders() QCOMPARE(entry->url(), QString("{TITLE}.{USERNAME}")); // Test password copy - QClipboard *clipboard = QApplication::clipboard(); + QClipboard* clipboard = QApplication::clipboard(); m_dbWidget->copyURL(); QTRY_COMPARE(clipboard->text(), QString("test.john")); } @@ -941,22 +941,19 @@ void TestGui::testDragAndDropGroup() QAbstractItemModel* groupModel = m_dbWidget->findChild("groupView")->model(); QModelIndex rootIndex = groupModel->index(0, 0); - dragAndDropGroup(groupModel->index(0, 0, rootIndex), - groupModel->index(1, 0, rootIndex), - -1, true, "Windows", 0); + dragAndDropGroup(groupModel->index(0, 0, rootIndex), groupModel->index(1, 0, rootIndex), -1, true, "Windows", 0); // dropping parent on child is supposed to fail dragAndDropGroup(groupModel->index(0, 0, rootIndex), groupModel->index(0, 0, groupModel->index(0, 0, rootIndex)), - -1, false, "NewDatabase", 0); + -1, + false, + "NewDatabase", + 0); - dragAndDropGroup(groupModel->index(1, 0, rootIndex), - rootIndex, - 0, true, "NewDatabase", 0); + dragAndDropGroup(groupModel->index(1, 0, rootIndex), rootIndex, 0, true, "NewDatabase", 0); - dragAndDropGroup(groupModel->index(0, 0, rootIndex), - rootIndex, - -1, true, "NewDatabase", 4); + dragAndDropGroup(groupModel->index(0, 0, rootIndex), rootIndex, -1, true, "NewDatabase", 4); } void TestGui::testSaveAs() @@ -1034,7 +1031,6 @@ void TestGui::testKeePass1Import() MessageBox::setNextAnswer(QMessageBox::No); triggerAction("actionDatabaseClose"); Tools::wait(100); - } void TestGui::testDatabaseLocking() @@ -1059,7 +1055,7 @@ void TestGui::testDatabaseLocking() void TestGui::testDragAndDropKdbxFiles() { - const int openedDatabasesCount = m_tabWidget->count(); + const int openedDatabasesCount = m_tabWidget->count(); const QString badDatabaseFilePath(QString(KEEPASSX_TEST_DATA_DIR).append("/NotDatabase.notkdbx")); QMimeData badMimeData; @@ -1183,8 +1179,12 @@ void TestGui::triggerAction(const QString& name) action->trigger(); } -void TestGui::dragAndDropGroup(const QModelIndex& sourceIndex, const QModelIndex& targetIndex, int row, - bool expectedResult, const QString& expectedParentName, int expectedPos) +void TestGui::dragAndDropGroup(const QModelIndex& sourceIndex, + const QModelIndex& targetIndex, + int row, + bool expectedResult, + const QString& expectedParentName, + int expectedPos) { QVERIFY(sourceIndex.isValid()); QVERIFY(targetIndex.isValid()); @@ -1203,7 +1203,9 @@ void TestGui::dragAndDropGroup(const QModelIndex& sourceIndex, const QModelIndex QCOMPARE(group->parentGroup()->children().indexOf(group), expectedPos); } -void TestGui::clickIndex(const QModelIndex& index, QAbstractItemView* view, Qt::MouseButton button, +void TestGui::clickIndex(const QModelIndex& index, + QAbstractItemView* view, + Qt::MouseButton button, Qt::KeyboardModifiers stateKey) { QTest::mouseClick(view->viewport(), button, stateKey, view->visualRect(index).center()); diff --git a/tests/gui/TestGui.h b/tests/gui/TestGui.h index e7232ccab..2a3708c42 100644 --- a/tests/gui/TestGui.h +++ b/tests/gui/TestGui.h @@ -69,9 +69,15 @@ private: int addCannedEntries(); void checkDatabase(QString dbFileName = ""); void triggerAction(const QString& name); - void dragAndDropGroup(const QModelIndex& sourceIndex, const QModelIndex& targetIndex, int row, - bool expectedResult, const QString& expectedParentName, int expectedPos); - void clickIndex(const QModelIndex& index, QAbstractItemView* view, Qt::MouseButton button, + void dragAndDropGroup(const QModelIndex& sourceIndex, + const QModelIndex& targetIndex, + int row, + bool expectedResult, + const QString& expectedParentName, + int expectedPos); + void clickIndex(const QModelIndex& index, + QAbstractItemView* view, + Qt::MouseButton button, Qt::KeyboardModifiers stateKey = 0); QPointer m_mainWindow; diff --git a/tests/mock/MockChallengeResponseKey.h b/tests/mock/MockChallengeResponseKey.h index af795d935..011b06e5d 100644 --- a/tests/mock/MockChallengeResponseKey.h +++ b/tests/mock/MockChallengeResponseKey.h @@ -37,4 +37,4 @@ private: QByteArray m_secret; }; -#endif //KEEPASSXC_MOCKCHALLENGERESPONSEKEY_H +#endif // KEEPASSXC_MOCKCHALLENGERESPONSEKEY_H