Performed project-wide code formatting

* Updated format CMake command to properly
ignore new directories and files
* Added output when command is run
* Resolves #2623
This commit is contained in:
Jonathan White 2019-01-20 09:50:20 -05:00
parent c74664097b
commit 7e1b16250c
68 changed files with 591 additions and 542 deletions

View file

@ -15,10 +15,11 @@
set(EXCLUDED_DIRS set(EXCLUDED_DIRS
# third-party directories # third-party directories
zxcvbn/ src/zxcvbn/
streams/QtIOCompressor
# objective-c directories # objective-c directories
autotype/mac) src/touchid/
src/autotype/mac/
src/gui/macutils/)
set(EXCLUDED_FILES set(EXCLUDED_FILES
# third-party files # third-party files
@ -37,7 +38,7 @@ set(EXCLUDED_FILES
core/ScreenLockListenerMac.h core/ScreenLockListenerMac.h
core/ScreenLockListenerMac.cpp) core/ScreenLockListenerMac.cpp)
file(GLOB_RECURSE ALL_SOURCE_FILES *.cpp *.h) file(GLOB_RECURSE ALL_SOURCE_FILES RELATIVE ${CMAKE_SOURCE_DIR} src/*.cpp src/*.h tests/*.cpp tests/*.h)
foreach(SOURCE_FILE ${ALL_SOURCE_FILES}) foreach(SOURCE_FILE ${ALL_SOURCE_FILES})
foreach(EXCLUDED_DIR ${EXCLUDED_DIRS}) foreach(EXCLUDED_DIR ${EXCLUDED_DIRS})
string(FIND ${SOURCE_FILE} ${EXCLUDED_DIR} SOURCE_FILE_EXCLUDED) string(FIND ${SOURCE_FILE} ${EXCLUDED_DIR} SOURCE_FILE_EXCLUDED)
@ -52,7 +53,12 @@ foreach(SOURCE_FILE ${ALL_SOURCE_FILES})
endforeach() endforeach()
endforeach() endforeach()
add_custom_target( add_custom_target(format)
format foreach(SOURCE_FILE ${ALL_SOURCE_FILES})
COMMAND echo ${ALL_SOURCE_FILES} | xargs clang-format -style=file -i add_custom_command(
) TARGET format
PRE_BUILD
COMMAND echo Formatting ${SOURCE_FILE}
COMMAND clang-format -style=file -i \"${SOURCE_FILE}\"
WORKING_DIRECTORY ${CMAKE_SOURCE_DIR})
endforeach()

View file

@ -77,7 +77,8 @@ bool BrowserService::isDatabaseOpened() const
return false; return false;
} }
return dbWidget->currentMode() == DatabaseWidget::Mode::ViewMode || dbWidget->currentMode() == DatabaseWidget::Mode::EditMode; return dbWidget->currentMode() == DatabaseWidget::Mode::ViewMode
|| dbWidget->currentMode() == DatabaseWidget::Mode::EditMode;
} }
bool BrowserService::openDatabase(bool triggerUnlock) bool BrowserService::openDatabase(bool triggerUnlock)
@ -91,7 +92,8 @@ bool BrowserService::openDatabase(bool triggerUnlock)
return false; return false;
} }
if (dbWidget->currentMode() == DatabaseWidget::Mode::ViewMode || dbWidget->currentMode() == DatabaseWidget::Mode::EditMode) { if (dbWidget->currentMode() == DatabaseWidget::Mode::ViewMode
|| dbWidget->currentMode() == DatabaseWidget::Mode::EditMode) {
return true; return true;
} }
@ -114,7 +116,8 @@ void BrowserService::lockDatabase()
return; return;
} }
if (dbWidget->currentMode() == DatabaseWidget::Mode::ViewMode || dbWidget->currentMode() == DatabaseWidget::Mode::EditMode) { if (dbWidget->currentMode() == DatabaseWidget::Mode::ViewMode
|| dbWidget->currentMode() == DatabaseWidget::Mode::EditMode) {
dbWidget->lock(); dbWidget->lock();
} }
} }
@ -289,9 +292,12 @@ QJsonArray BrowserService::findMatchingEntries(const QString& id,
return result; return result;
} }
void BrowserService::addEntry(const QString& id, const QString& login, void BrowserService::addEntry(const QString& id,
const QString& password, const QString& url, const QString& login,
const QString& submitUrl, const QString& realm, const QString& password,
const QString& url,
const QString& submitUrl,
const QString& realm,
QSharedPointer<Database> selectedDb) QSharedPointer<Database> selectedDb)
{ {
if (thread() != QThread::currentThread()) { if (thread() != QThread::currentThread()) {
@ -392,12 +398,13 @@ void BrowserService::updateEntry(const QString& id,
MessageBox::Button dialogResult = MessageBox::No; MessageBox::Button dialogResult = MessageBox::No;
if (!browserSettings()->alwaysAllowUpdate()) { if (!browserSettings()->alwaysAllowUpdate()) {
raiseWindow(); raiseWindow();
dialogResult = MessageBox::question(nullptr, dialogResult = MessageBox::question(
nullptr,
tr("KeePassXC: Update Entry"), tr("KeePassXC: Update Entry"),
tr("Do you want to update the information in %1 - %2?") tr("Do you want to update the information in %1 - %2?").arg(QUrl(url).host(), username),
.arg(QUrl(url).host(), username),
MessageBox::Save | MessageBox::Cancel, MessageBox::Save | MessageBox::Cancel,
MessageBox::Cancel, MessageBox::Raise); MessageBox::Cancel,
MessageBox::Raise);
} }
if (browserSettings()->alwaysAllowUpdate() || dialogResult == MessageBox::Save) { if (browserSettings()->alwaysAllowUpdate() || dialogResult == MessageBox::Save) {
@ -680,10 +687,7 @@ QJsonObject BrowserService::prepareEntry(const Entry* entry)
} }
BrowserService::Access BrowserService::Access
BrowserService::checkAccess(const Entry* entry, BrowserService::checkAccess(const Entry* entry, const QString& host, const QString& submitHost, const QString& realm)
const QString& host,
const QString& submitHost,
const QString& realm)
{ {
BrowserEntryConfig config; BrowserEntryConfig config;
if (!config.load(entry)) { if (!config.load(entry)) {
@ -844,9 +848,9 @@ QSharedPointer<Database> BrowserService::selectedDatabase()
for (int i = 0;; ++i) { for (int i = 0;; ++i) {
auto* dbWidget = m_dbTabWidget->databaseWidgetFromIndex(i); auto* dbWidget = m_dbTabWidget->databaseWidgetFromIndex(i);
// Add only open databases // Add only open databases
if (dbWidget && dbWidget->database()->hasKey() && if (dbWidget && dbWidget->database()->hasKey()
(dbWidget->currentMode() == DatabaseWidget::Mode::ViewMode || && (dbWidget->currentMode() == DatabaseWidget::Mode::ViewMode
dbWidget->currentMode() == DatabaseWidget::Mode::EditMode)) { || dbWidget->currentMode() == DatabaseWidget::Mode::EditMode)) {
databaseWidgets.push_back(dbWidget); databaseWidgets.push_back(dbWidget);
continue; continue;
} }
@ -919,8 +923,8 @@ bool BrowserService::checkLegacySettings()
bool legacySettingsFound = false; bool legacySettingsFound = false;
QList<Entry*> entries = db->rootGroup()->entriesRecursive(); QList<Entry*> entries = db->rootGroup()->entriesRecursive();
for (const auto& e : entries) { for (const auto& e : entries) {
if ((e->attributes()->contains(KEEPASSHTTP_NAME) || e->attributes()->contains(KEEPASSXCBROWSER_NAME)) || if ((e->attributes()->contains(KEEPASSHTTP_NAME) || e->attributes()->contains(KEEPASSXCBROWSER_NAME))
(e->title() == KEEPASSHTTP_NAME || e->title().contains(KEEPASSXCBROWSER_NAME, Qt::CaseInsensitive))) { || (e->title() == KEEPASSHTTP_NAME || e->title().contains(KEEPASSXCBROWSER_NAME, Qt::CaseInsensitive))) {
legacySettingsFound = true; legacySettingsFound = true;
break; break;
} }

View file

@ -102,10 +102,7 @@ private:
const QString& submitHost, const QString& submitHost,
const QString& realm); const QString& realm);
QJsonObject prepareEntry(const Entry* entry); QJsonObject prepareEntry(const Entry* entry);
Access checkAccess(const Entry* entry, Access checkAccess(const Entry* entry, const QString& host, const QString& submitHost, const QString& realm);
const QString& host,
const QString& submitHost,
const QString& realm);
Group* findCreateAddEntryGroup(QSharedPointer<Database> selectedDb = {}); Group* findCreateAddEntryGroup(QSharedPointer<Database> selectedDb = {});
int int
sortPriority(const Entry* entry, const QString& host, const QString& submitUrl, const QString& baseSubmitUrl) const; sortPriority(const Entry* entry, const QString& host, const QString& submitUrl, const QString& baseSubmitUrl) const;

View file

@ -41,8 +41,7 @@ const QCommandLineOption Command::QuietOption =
<< "quiet", << "quiet",
QObject::tr("Silence password prompt and other secondary outputs.")); QObject::tr("Silence password prompt and other secondary outputs."));
const QCommandLineOption Command::KeyFileOption = const QCommandLineOption Command::KeyFileOption = QCommandLineOption(QStringList() << "k"
QCommandLineOption(QStringList() << "k"
<< "key-file", << "key-file",
QObject::tr("Key file of the database."), QObject::tr("Key file of the database."),
QObject::tr("path")); QObject::tr("path"));

View file

@ -52,7 +52,6 @@ FILE* DEVNULL = fopen("nul", "w");
FILE* DEVNULL = fopen("/dev/null", "w"); FILE* DEVNULL = fopen("/dev/null", "w");
#endif #endif
void setStdinEcho(bool enable = true) void setStdinEcho(bool enable = true)
{ {
#ifdef Q_OS_WIN #ifdef Q_OS_WIN

View file

@ -229,8 +229,7 @@ namespace Bootstrap
#ifdef WITH_XC_SSHAGENT #ifdef WITH_XC_SSHAGENT
// OpenSSH for Windows ssh-agent service is running as LocalSystem // OpenSSH for Windows ssh-agent service is running as LocalSystem
if (!AddAccessAllowedAce( if (!AddAccessAllowedAce(pACL,
pACL,
ACL_REVISION, ACL_REVISION,
PROCESS_QUERY_INFORMATION | PROCESS_DUP_HANDLE, // just enough for ssh-agent PROCESS_QUERY_INFORMATION | PROCESS_DUP_HANDLE, // just enough for ssh-agent
pLocalSystemSid // known LocalSystem sid pLocalSystemSid // known LocalSystem sid

View file

@ -28,11 +28,11 @@
#include "keys/PasswordKey.h" #include "keys/PasswordKey.h"
#include <QFile> #include <QFile>
#include <QFileInfo>
#include <QSaveFile> #include <QSaveFile>
#include <QTemporaryFile> #include <QTemporaryFile>
#include <QTimer> #include <QTimer>
#include <QXmlStreamReader> #include <QXmlStreamReader>
#include <QFileInfo>
QHash<QUuid, QPointer<Database>> Database::s_uuidMap; QHash<QUuid, QPointer<Database>> Database::s_uuidMap;
QHash<QString, QPointer<Database>> Database::s_filePathMap; QHash<QString, QPointer<Database>> Database::s_filePathMap;

View file

@ -25,10 +25,10 @@
#include <QPointer> #include <QPointer>
#include "config-keepassx.h" #include "config-keepassx.h"
#include "crypto/kdf/AesKdf.h"
#include "crypto/kdf/Kdf.h" #include "crypto/kdf/Kdf.h"
#include "format/KeePass2.h" #include "format/KeePass2.h"
#include "keys/CompositeKey.h" #include "keys/CompositeKey.h"
#include "crypto/kdf/AesKdf.h"
class Entry; class Entry;
enum class EntryReferenceType; enum class EntryReferenceType;
@ -66,7 +66,10 @@ public:
~Database() override; ~Database() override;
bool open(QSharedPointer<const CompositeKey> key, QString* error = nullptr, bool readOnly = false); bool open(QSharedPointer<const CompositeKey> key, QString* error = nullptr, bool readOnly = false);
bool open(const QString& filePath, QSharedPointer<const CompositeKey> key, QString* error = nullptr, bool readOnly = false); bool open(const QString& filePath,
QSharedPointer<const CompositeKey> key,
QString* error = nullptr,
bool readOnly = false);
bool save(QString* error = nullptr, bool atomic = true, bool backup = false); bool save(QString* error = nullptr, bool atomic = true, bool backup = false);
bool save(const QString& filePath, QString* error = nullptr, bool atomic = true, bool backup = false); bool save(const QString& filePath, QString* error = nullptr, bool atomic = true, bool backup = false);
@ -103,7 +106,9 @@ public:
bool hasKey() const; bool hasKey() const;
QSharedPointer<const CompositeKey> key() const; QSharedPointer<const CompositeKey> key() const;
bool setKey(const QSharedPointer<const CompositeKey>& key, bool updateChangedTime = true, bool updateTransformSalt = false); bool setKey(const QSharedPointer<const CompositeKey>& key,
bool updateChangedTime = true,
bool updateTransformSalt = false);
QByteArray challengeResponseKey() const; QByteArray challengeResponseKey() const;
bool challengeMasterSeed(const QByteArray& masterSeed); bool challengeMasterSeed(const QByteArray& masterSeed);
bool verifyKey(const QSharedPointer<CompositeKey>& key) const; bool verifyKey(const QSharedPointer<CompositeKey>& key) const;

View file

@ -726,15 +726,13 @@ Entry* Entry::clone(CloneFlags flags) const
entry->m_attachments->copyDataFrom(m_attachments); entry->m_attachments->copyDataFrom(m_attachments);
if (flags & CloneUserAsRef) { if (flags & CloneUserAsRef) {
entry->m_attributes->set( entry->m_attributes->set(EntryAttributes::UserNameKey,
EntryAttributes::UserNameKey,
buildReference(uuid(), EntryAttributes::UserNameKey), buildReference(uuid(), EntryAttributes::UserNameKey),
m_attributes->isProtected(EntryAttributes::UserNameKey)); m_attributes->isProtected(EntryAttributes::UserNameKey));
} }
if (flags & ClonePassAsRef) { if (flags & ClonePassAsRef) {
entry->m_attributes->set( entry->m_attributes->set(EntryAttributes::PasswordKey,
EntryAttributes::PasswordKey,
buildReference(uuid(), EntryAttributes::PasswordKey), buildReference(uuid(), EntryAttributes::PasswordKey),
m_attributes->isProtected(EntryAttributes::PasswordKey)); m_attributes->isProtected(EntryAttributes::PasswordKey));
} }

View file

@ -97,10 +97,10 @@ bool EntrySearcher::searchEntryImpl(const QString& searchString, Entry* entry)
break; break;
default: default:
// Terms without a specific field try to match title, username, url, and notes // Terms without a specific field try to match title, username, url, and notes
found = term->regex.match(entry->resolvePlaceholder(entry->title())).hasMatch() || found = term->regex.match(entry->resolvePlaceholder(entry->title())).hasMatch()
term->regex.match(entry->resolvePlaceholder(entry->username())).hasMatch() || || term->regex.match(entry->resolvePlaceholder(entry->username())).hasMatch()
term->regex.match(entry->resolvePlaceholder(entry->url())).hasMatch() || || term->regex.match(entry->resolvePlaceholder(entry->url())).hasMatch()
term->regex.match(entry->notes()).hasMatch(); || term->regex.match(entry->notes()).hasMatch();
} }
// Short circuit if we failed to match or we matched and are excluding this term // Short circuit if we failed to match or we matched and are excluding this term

View file

@ -19,8 +19,8 @@
#ifndef KEEPASSX_ENTRYSEARCHER_H #ifndef KEEPASSX_ENTRYSEARCHER_H
#define KEEPASSX_ENTRYSEARCHER_H #define KEEPASSX_ENTRYSEARCHER_H
#include <QString>
#include <QRegularExpression> #include <QRegularExpression>
#include <QString>
class Group; class Group;
class Entry; class Entry;
@ -39,7 +39,8 @@ public:
private: private:
bool searchEntryImpl(const QString& searchString, Entry* entry); bool searchEntryImpl(const QString& searchString, Entry* entry);
enum class Field { enum class Field
{
Undefined, Undefined,
Title, Title,
Username, Username,

View file

@ -29,7 +29,7 @@ namespace
{ {
const int FileChangeDelay = 500; const int FileChangeDelay = 500;
const int TimerResolution = 100; const int TimerResolution = 100;
} } // namespace
DelayingFileWatcher::DelayingFileWatcher(QObject* parent) DelayingFileWatcher::DelayingFileWatcher(QObject* parent)
: QObject(parent) : QObject(parent)

View file

@ -58,11 +58,13 @@ class BulkFileWatcher : public QObject
{ {
Q_OBJECT Q_OBJECT
enum Signal { enum Signal
{
Created, Created,
Updated, Updated,
Removed Removed
}; };
public: public:
explicit BulkFileWatcher(QObject* parent = nullptr); explicit BulkFileWatcher(QObject* parent = nullptr);
@ -71,7 +73,6 @@ public:
void removePath(const QString& path); void removePath(const QString& path);
void addPath(const QString& path); void addPath(const QString& path);
void ignoreFileChanges(const QString& path); void ignoreFileChanges(const QString& path);
signals: signals:

View file

@ -554,7 +554,8 @@ QList<Entry*> Group::entriesRecursive(bool includeHistoryItems) const
QList<Entry*> Group::referencesRecursive(const Entry* entry) const QList<Entry*> Group::referencesRecursive(const Entry* entry) const
{ {
auto entries = entriesRecursive(); auto entries = entriesRecursive();
return QtConcurrent::blockingFiltered(entries, [entry](const Entry* e) { return e->hasReferencesTo(entry->uuid()); }); return QtConcurrent::blockingFiltered(entries,
[entry](const Entry* e) { return e->hasReferencesTo(entry->uuid()); });
} }
Entry* Group::findEntryByUuid(const QUuid& uuid) const Entry* Group::findEntryByUuid(const QUuid& uuid) const

View file

@ -17,8 +17,8 @@
#include "ScreenLockListenerMac.h" #include "ScreenLockListenerMac.h"
#include <QMutexLocker>
#include <CoreFoundation/CoreFoundation.h> #include <CoreFoundation/CoreFoundation.h>
#include <QMutexLocker>
ScreenLockListenerMac* ScreenLockListenerMac::instance() ScreenLockListenerMac* ScreenLockListenerMac::instance()
{ {
@ -32,8 +32,10 @@ ScreenLockListenerMac* ScreenLockListenerMac::instance()
return m_ptr; return m_ptr;
} }
void ScreenLockListenerMac::notificationCenterCallBack(CFNotificationCenterRef, void*, void ScreenLockListenerMac::notificationCenterCallBack(CFNotificationCenterRef,
CFStringRef, const void*, void*,
CFStringRef,
const void*,
CFDictionaryRef) CFDictionaryRef)
{ {
instance()->onSignalReception(); instance()->onSignalReception();

View file

@ -24,19 +24,21 @@
#include "ScreenLockListenerPrivate.h" #include "ScreenLockListenerPrivate.h"
class ScreenLockListenerMac: public ScreenLockListenerPrivate { class ScreenLockListenerMac : public ScreenLockListenerPrivate
{
Q_OBJECT Q_OBJECT
public: public:
static ScreenLockListenerMac* instance(); static ScreenLockListenerMac* instance();
static void notificationCenterCallBack(CFNotificationCenterRef center, void* observer, static void notificationCenterCallBack(CFNotificationCenterRef center,
CFStringRef name, const void* object, void* observer,
CFStringRef name,
const void* object,
CFDictionaryRef userInfo); CFDictionaryRef userInfo);
private: private:
ScreenLockListenerMac(QWidget* parent = nullptr); ScreenLockListenerMac(QWidget* parent = nullptr);
void onSignalReception(); void onSignalReception();
}; };
#endif // SCREENLOCKLISTENERMAC_H #endif // SCREENLOCKLISTENERMAC_H

View file

@ -118,6 +118,7 @@ bool TimeInfo::operator!=(const TimeInfo& other) const
bool TimeInfo::equals(const TimeInfo& other, CompareItemOptions options) const bool TimeInfo::equals(const TimeInfo& other, CompareItemOptions options) const
{ {
// clang-format off
if (::compare(m_lastModificationTime, other.m_lastModificationTime, options) != 0) { if (::compare(m_lastModificationTime, other.m_lastModificationTime, options) != 0) {
return false; return false;
} }
@ -137,4 +138,5 @@ bool TimeInfo::equals(const TimeInfo& other, CompareItemOptions options) const
return false; return false;
} }
return true; return true;
// clang-format on
} }

View file

@ -208,7 +208,8 @@ namespace Tools
return regex; return regex;
} }
QString uuidToHex(const QUuid& uuid) { QString uuidToHex(const QUuid& uuid)
{
return QString::fromLatin1(uuid.toRfc4122().toHex()); return QString::fromLatin1(uuid.toRfc4122().toHex());
} }
@ -216,7 +217,6 @@ namespace Tools
: raw(nullptr) : raw(nullptr)
, size(0) , size(0)
{ {
} }
Buffer::~Buffer() Buffer::~Buffer()
@ -229,7 +229,8 @@ namespace Tools
if (size > 0) { if (size > 0) {
free(raw); free(raw);
} }
raw = nullptr; size = 0; raw = nullptr;
size = 0;
} }
QByteArray Buffer::content() const QByteArray Buffer::content() const

View file

@ -47,8 +47,7 @@ void Translator::installTranslators()
#ifdef QT_DEBUG #ifdef QT_DEBUG
QString("%1/share/translations").arg(KEEPASSX_BINARY_DIR), QString("%1/share/translations").arg(KEEPASSX_BINARY_DIR),
#endif #endif
filePath()->dataPath("translations") filePath()->dataPath("translations")};
};
bool translationsLoaded = false; bool translationsLoaded = false;
for (const QString& path : paths) { for (const QString& path : paths) {

View file

@ -27,6 +27,6 @@ namespace ASN1Key
bool parseDSA(QByteArray& ba, OpenSSHKey& key); bool parseDSA(QByteArray& ba, OpenSSHKey& key);
bool parsePrivateRSA(QByteArray& ba, OpenSSHKey& key); bool parsePrivateRSA(QByteArray& ba, OpenSSHKey& key);
bool parsePublicRSA(QByteArray& ba, OpenSSHKey& key); bool parsePublicRSA(QByteArray& ba, OpenSSHKey& key);
} } // namespace ASN1Key
#endif // KEEPASSXC_ASN1KEY_H #endif // KEEPASSXC_ASN1KEY_H

View file

@ -68,7 +68,7 @@ QByteArray binarySerialize(const QString& type, const QList<QByteArray>& data)
} }
return buffer; return buffer;
} }
} } // namespace
// bcrypt_pbkdf.cpp // bcrypt_pbkdf.cpp
int bcrypt_pbkdf(const QByteArray& pass, const QByteArray& salt, QByteArray& key, quint32 rounds); int bcrypt_pbkdf(const QByteArray& pass, const QByteArray& salt, QByteArray& key, quint32 rounds);
@ -95,7 +95,9 @@ OpenSSHKey OpenSSHKey::generate(bool secure)
Tools::Map<Index, gcry_mpi_t, &gcry_mpi_release> mpi; Tools::Map<Index, gcry_mpi_t, &gcry_mpi_release> mpi;
Tools::Map<Index, gcry_sexp_t, &gcry_sexp_release> sexp; Tools::Map<Index, gcry_sexp_t, &gcry_sexp_release> sexp;
gcry_error_t rc = GPG_ERR_NO_ERROR; gcry_error_t rc = GPG_ERR_NO_ERROR;
rc = gcry_sexp_build(&sexp[Params], NULL, secure ? "(genkey (rsa (nbits 4:2048)))" : "(genkey (rsa (transient-key) (nbits 4:2048)))"); rc = gcry_sexp_build(&sexp[Params],
NULL,
secure ? "(genkey (rsa (nbits 4:2048)))" : "(genkey (rsa (transient-key) (nbits 4:2048)))");
if (rc != GPG_ERR_NO_ERROR) { if (rc != GPG_ERR_NO_ERROR) {
qWarning() << "Could not create ssh key" << gcry_err_code(rc); qWarning() << "Could not create ssh key" << gcry_err_code(rc);
return OpenSSHKey(); return OpenSSHKey();

View file

@ -68,6 +68,7 @@ bool Kdbx4Reader::readDatabaseImpl(QIODevice* device,
return false; return false;
} }
// clang-format off
QByteArray hmacKey = KeePass2::hmacKey(m_masterSeed, db->transformedMasterKey()); QByteArray hmacKey = KeePass2::hmacKey(m_masterSeed, 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)")); raiseError(tr("Wrong key or database file is corrupt. (HMAC mismatch)"));
@ -93,6 +94,7 @@ bool Kdbx4Reader::readDatabaseImpl(QIODevice* device,
raiseError(cipherStream.errorString()); raiseError(cipherStream.errorString());
return false; return false;
} }
// clang-format on
QIODevice* xmlDevice = nullptr; QIODevice* xmlDevice = nullptr;
QScopedPointer<QtIOCompressor> ioCompressor; QScopedPointer<QtIOCompressor> ioCompressor;

View file

@ -56,7 +56,8 @@ KeePass1Reader::KeePass1Reader()
{ {
} }
QSharedPointer<Database> KeePass1Reader::readDatabase(QIODevice* device, const QString& password, QIODevice* keyfileDevice) QSharedPointer<Database>
KeePass1Reader::readDatabase(QIODevice* device, const QString& password, QIODevice* keyfileDevice)
{ {
m_error = false; m_error = false;
m_errorStr.clear(); m_errorStr.clear();
@ -248,7 +249,8 @@ QSharedPointer<Database> KeePass1Reader::readDatabase(QIODevice* device, const Q
return db; return db;
} }
QSharedPointer<Database> KeePass1Reader::readDatabase(QIODevice* device, const QString& password, const QString& keyfileName) QSharedPointer<Database>
KeePass1Reader::readDatabase(QIODevice* device, const QString& password, const QString& keyfileName)
{ {
QScopedPointer<QFile> keyFile; QScopedPointer<QFile> keyFile;
if (!keyfileName.isEmpty()) { if (!keyfileName.isEmpty()) {
@ -262,7 +264,8 @@ QSharedPointer<Database> KeePass1Reader::readDatabase(QIODevice* device, const Q
return QSharedPointer<Database>(readDatabase(device, password, keyFile.data())); return QSharedPointer<Database>(readDatabase(device, password, keyFile.data()));
} }
QSharedPointer<Database> KeePass1Reader::readDatabase(const QString& filename, const QString& password, const QString& keyfileName) QSharedPointer<Database>
KeePass1Reader::readDatabase(const QString& filename, const QString& password, const QString& keyfileName)
{ {
QFile dbFile(filename); QFile dbFile(filename);
if (!dbFile.open(QFile::ReadOnly)) { if (!dbFile.open(QFile::ReadOnly)) {
@ -290,7 +293,8 @@ QString KeePass1Reader::errorString()
return m_errorStr; 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<PasswordEncoding> encodings = {Windows1252, Latin1, UTF8}; const QList<PasswordEncoding> encodings = {Windows1252, Latin1, UTF8};

View file

@ -248,7 +248,8 @@ void ApplicationSettingsWidget::saveSettings()
config()->set("GUI/MovableToolbar", m_generalUi->toolbarMovableCheckBox->isChecked()); config()->set("GUI/MovableToolbar", m_generalUi->toolbarMovableCheckBox->isChecked());
int currentToolButtonStyleIndex = m_generalUi->toolButtonStyleComboBox->currentIndex(); int currentToolButtonStyleIndex = m_generalUi->toolButtonStyleComboBox->currentIndex();
config()->set("GUI/ToolButtonStyle", m_generalUi->toolButtonStyleComboBox->itemData(currentToolButtonStyleIndex).toString()); config()->set("GUI/ToolButtonStyle",
m_generalUi->toolButtonStyleComboBox->itemData(currentToolButtonStyleIndex).toString());
config()->set("GUI/ShowTrayIcon", m_generalUi->systrayShowCheckBox->isChecked()); config()->set("GUI/ShowTrayIcon", m_generalUi->systrayShowCheckBox->isChecked());
config()->set("GUI/DarkTrayIcon", m_generalUi->systrayDarkIconCheckBox->isChecked()); config()->set("GUI/DarkTrayIcon", m_generalUi->systrayDarkIconCheckBox->isChecked());
@ -329,4 +330,3 @@ void ApplicationSettingsWidget::enableToolbarSettings(bool checked)
m_generalUi->toolButtonStyleComboBox->setEnabled(!checked); m_generalUi->toolButtonStyleComboBox->setEnabled(!checked);
m_generalUi->toolButtonStyleLabel->setEnabled(!checked); m_generalUi->toolButtonStyleLabel->setEnabled(!checked);
} }

View file

@ -202,8 +202,7 @@ void DatabaseOpenWidget::openDatabase()
bool ok = m_db->open(m_filename, masterKey, &error, false); bool ok = m_db->open(m_filename, masterKey, &error, false);
QApplication::restoreOverrideCursor(); QApplication::restoreOverrideCursor();
if (!ok) { if (!ok) {
m_ui->messageWidget->showMessage( m_ui->messageWidget->showMessage(tr("Unable to open the database:\n%1").arg(error),
tr("Unable to open the database:\n%1").arg(error),
MessageWidget::MessageType::Error); MessageWidget::MessageType::Error);
return; return;
} }
@ -232,8 +231,7 @@ void DatabaseOpenWidget::openDatabase()
} }
emit dialogFinished(true); emit dialogFinished(true);
} else { } else {
m_ui->messageWidget->showMessage(tr("Unable to open the database:\n%1").arg(error), m_ui->messageWidget->showMessage(tr("Unable to open the database:\n%1").arg(error), MessageWidget::Error);
MessageWidget::Error);
m_ui->editPassword->setText(""); m_ui->editPassword->setText("");
#ifdef WITH_XC_TOUCHID #ifdef WITH_XC_TOUCHID

View file

@ -31,12 +31,12 @@
#include "core/Tools.h" #include "core/Tools.h"
#include "format/CsvExporter.h" #include "format/CsvExporter.h"
#include "gui/Clipboard.h" #include "gui/Clipboard.h"
#include "gui/DatabaseOpenDialog.h"
#include "gui/DatabaseWidget.h" #include "gui/DatabaseWidget.h"
#include "gui/DatabaseWidgetStateSync.h" #include "gui/DatabaseWidgetStateSync.h"
#include "gui/DragTabBar.h" #include "gui/DragTabBar.h"
#include "gui/FileDialog.h" #include "gui/FileDialog.h"
#include "gui/MessageBox.h" #include "gui/MessageBox.h"
#include "gui/DatabaseOpenDialog.h"
#include "gui/entry/EntryView.h" #include "gui/entry/EntryView.h"
#include "gui/group/GroupView.h" #include "gui/group/GroupView.h"
#ifdef Q_OS_MACOS #ifdef Q_OS_MACOS
@ -54,12 +54,15 @@ DatabaseTabWidget::DatabaseTabWidget(QWidget* parent)
setTabBar(tabBar); setTabBar(tabBar);
setDocumentMode(true); setDocumentMode(true);
// clang-format off
connect(this, SIGNAL(tabCloseRequested(int)), SLOT(closeDatabaseTab(int))); connect(this, SIGNAL(tabCloseRequested(int)), SLOT(closeDatabaseTab(int)));
connect(this, SIGNAL(currentChanged(int)), SLOT(emitActivateDatabaseChanged())); 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(globalShortcutTriggered()), SLOT(performGlobalAutoType()));
connect(autoType(), SIGNAL(autotypePerformed()), SLOT(relockPendingDatabase())); connect(autoType(), SIGNAL(autotypePerformed()), SLOT(relockPendingDatabase()));
connect(autoType(), SIGNAL(autotypeRejected()), SLOT(relockPendingDatabase())); connect(autoType(), SIGNAL(autotypeRejected()), SLOT(relockPendingDatabase()));
// clang-format on
} }
DatabaseTabWidget::~DatabaseTabWidget() DatabaseTabWidget::~DatabaseTabWidget()
@ -187,7 +190,8 @@ void DatabaseTabWidget::addDatabaseTab(DatabaseWidget* dbWidget, bool inBackgrou
} }
connect(dbWidget, SIGNAL(databaseFilePathChanged(QString, QString)), SLOT(updateTabName())); connect(dbWidget, SIGNAL(databaseFilePathChanged(QString, QString)), SLOT(updateTabName()));
connect(dbWidget, SIGNAL(requestOpenDatabase(QString,bool,QString)), SLOT(addDatabaseTab(QString,bool,QString))); connect(
dbWidget, SIGNAL(requestOpenDatabase(QString, bool, QString)), SLOT(addDatabaseTab(QString, bool, QString)));
connect(dbWidget, SIGNAL(closeRequest()), SLOT(closeDatabaseTabFromSender())); connect(dbWidget, SIGNAL(closeRequest()), SLOT(closeDatabaseTabFromSender()));
connect(dbWidget, SIGNAL(databaseModified()), SLOT(updateTabName())); connect(dbWidget, SIGNAL(databaseModified()), SLOT(updateTabName()));
connect(dbWidget, SIGNAL(databaseSaved()), SLOT(updateTabName())); connect(dbWidget, SIGNAL(databaseSaved()), SLOT(updateTabName()));
@ -520,7 +524,6 @@ void DatabaseTabWidget::lockDatabases()
// If we locked a database without a file close the tab // If we locked a database without a file close the tab
closeDatabaseTab(dbWidget); closeDatabaseTab(dbWidget);
} }
} }
} }
@ -542,7 +545,8 @@ void DatabaseTabWidget::unlockDatabaseInDialog(DatabaseWidget* dbWidget, Databas
* @param intent intent for unlocking * @param intent intent for unlocking
* @param file path of the database to be unlocked * @param file path of the database to be unlocked
*/ */
void DatabaseTabWidget::unlockDatabaseInDialog(DatabaseWidget* dbWidget, DatabaseOpenDialog::Intent intent, void DatabaseTabWidget::unlockDatabaseInDialog(DatabaseWidget* dbWidget,
DatabaseOpenDialog::Intent intent,
const QString& filePath) const QString& filePath)
{ {
m_databaseOpenDialog->setTargetDatabaseWidget(dbWidget); m_databaseOpenDialog->setTargetDatabaseWidget(dbWidget);

View file

@ -18,11 +18,11 @@
#ifndef KEEPASSX_DATABASETABWIDGET_H #ifndef KEEPASSX_DATABASETABWIDGET_H
#define KEEPASSX_DATABASETABWIDGET_H #define KEEPASSX_DATABASETABWIDGET_H
#include "gui/MessageWidget.h"
#include "DatabaseOpenDialog.h" #include "DatabaseOpenDialog.h"
#include "gui/MessageWidget.h"
#include <QTabWidget>
#include <QPointer> #include <QPointer>
#include <QTabWidget>
class Database; class Database;
class DatabaseWidget; class DatabaseWidget;

View file

@ -32,8 +32,8 @@
#include <QSplitter> #include <QSplitter>
#include "autotype/AutoType.h" #include "autotype/AutoType.h"
#include "core/Database.h"
#include "core/Config.h" #include "core/Config.h"
#include "core/Database.h"
#include "core/EntrySearcher.h" #include "core/EntrySearcher.h"
#include "core/FilePath.h" #include "core/FilePath.h"
#include "core/FileWatcher.h" #include "core/FileWatcher.h"
@ -42,18 +42,18 @@
#include "core/Metadata.h" #include "core/Metadata.h"
#include "core/Tools.h" #include "core/Tools.h"
#include "format/KeePass2Reader.h" #include "format/KeePass2Reader.h"
#include "gui/FileDialog.h"
#include "gui/Clipboard.h" #include "gui/Clipboard.h"
#include "gui/CloneDialog.h" #include "gui/CloneDialog.h"
#include "gui/DatabaseOpenWidget.h"
#include "gui/DatabaseOpenDialog.h" #include "gui/DatabaseOpenDialog.h"
#include "gui/dbsettings/DatabaseSettingsDialog.h" #include "gui/DatabaseOpenWidget.h"
#include "gui/EntryPreviewWidget.h" #include "gui/EntryPreviewWidget.h"
#include "gui/FileDialog.h"
#include "gui/KeePass1OpenWidget.h" #include "gui/KeePass1OpenWidget.h"
#include "gui/MessageBox.h" #include "gui/MessageBox.h"
#include "gui/TotpDialog.h" #include "gui/TotpDialog.h"
#include "gui/TotpSetupDialog.h"
#include "gui/TotpExportSettingsDialog.h" #include "gui/TotpExportSettingsDialog.h"
#include "gui/TotpSetupDialog.h"
#include "gui/dbsettings/DatabaseSettingsDialog.h"
#include "gui/entry/EditEntryWidget.h" #include "gui/entry/EditEntryWidget.h"
#include "gui/entry/EntryView.h" #include "gui/entry/EntryView.h"
#include "gui/group/EditGroupWidget.h" #include "gui/group/EditGroupWidget.h"
@ -465,7 +465,8 @@ void DatabaseWidget::deleteSelectedEntries()
this, this,
tr("Replace references to entry?"), tr("Replace references to entry?"),
tr("Entry \"%1\" has %2 reference(s). " tr("Entry \"%1\" has %2 reference(s). "
"Do you want to overwrite references with values, skip this entry, or delete anyway?", "", "Do you want to overwrite references with values, skip this entry, or delete anyway?",
"",
references.size()) references.size())
.arg((*it)->title().toHtmlEscaped()) .arg((*it)->title().toHtmlEscaped())
.arg(references.size()), .arg(references.size()),
@ -590,8 +591,7 @@ void DatabaseWidget::copyAttribute(QAction* action)
Entry* currentEntry = m_entryView->currentEntry(); Entry* currentEntry = m_entryView->currentEntry();
if (currentEntry) { if (currentEntry) {
setClipboardTextAndMinimize( setClipboardTextAndMinimize(
currentEntry->resolveMultiplePlaceholders( currentEntry->resolveMultiplePlaceholders(currentEntry->attributes()->value(action->data().toString())));
currentEntry->attributes()->value(action->data().toString())));
} }
} }
@ -707,10 +707,10 @@ void DatabaseWidget::deleteGroup()
bool isRecycleBin = recycleBin && (currentGroup == recycleBin); bool isRecycleBin = recycleBin && (currentGroup == recycleBin);
bool isRecycleBinSubgroup = recycleBin && currentGroup->findGroupByUuid(recycleBin->uuid()); bool isRecycleBinSubgroup = recycleBin && currentGroup->findGroupByUuid(recycleBin->uuid());
if (inRecycleBin || isRecycleBin || isRecycleBinSubgroup || !m_db->metadata()->recycleBinEnabled()) { if (inRecycleBin || isRecycleBin || isRecycleBinSubgroup || !m_db->metadata()->recycleBinEnabled()) {
auto result = MessageBox::question(this, auto result = MessageBox::question(
this,
tr("Delete group"), tr("Delete group"),
tr("Do you really want to delete the group \"%1\" for good?") tr("Do you really want to delete the group \"%1\" for good?").arg(currentGroup->name().toHtmlEscaped()),
.arg(currentGroup->name().toHtmlEscaped()),
MessageBox::Delete | MessageBox::Cancel, MessageBox::Delete | MessageBox::Cancel,
MessageBox::Cancel); MessageBox::Cancel);
@ -815,7 +815,10 @@ void DatabaseWidget::switchToGroupEdit(Group* group, bool create)
void DatabaseWidget::connectDatabaseSignals() void DatabaseWidget::connectDatabaseSignals()
{ {
// relayed Database events // relayed Database events
connect(m_db.data(), SIGNAL(filePathChanged(QString,QString)), SIGNAL(databaseFilePathChanged(QString,QString))); connect(m_db.data(),
SIGNAL(filePathChanged(QString, QString)),
SIGNAL(databaseFilePathChanged(QString, QString)));
connect(m_db.data(), SIGNAL(databaseModified()), SIGNAL(databaseModified())); connect(m_db.data(), SIGNAL(databaseModified()), SIGNAL(databaseModified()));
connect(m_db.data(), SIGNAL(databaseModified()), SLOT(onDatabaseModified())); connect(m_db.data(), SIGNAL(databaseModified()), SLOT(onDatabaseModified()));
connect(m_db.data(), SIGNAL(databaseSaved()), SIGNAL(databaseSaved())); connect(m_db.data(), SIGNAL(databaseSaved()), SIGNAL(databaseSaved()));
@ -1208,9 +1211,11 @@ bool DatabaseWidget::lock()
clipboard()->clearCopiedText(); clipboard()->clearCopiedText();
if (currentMode() == DatabaseWidget::Mode::EditMode) { if (currentMode() == DatabaseWidget::Mode::EditMode) {
auto result = MessageBox::question(this, tr("Lock Database?"), auto result = MessageBox::question(this,
tr("Lock Database?"),
tr("You are editing an entry. Discard changes and lock anyway?"), tr("You are editing an entry. Discard changes and lock anyway?"),
MessageBox::Discard | MessageBox::Cancel, MessageBox::Cancel); MessageBox::Discard | MessageBox::Cancel,
MessageBox::Cancel);
if (result == MessageBox::Cancel) { if (result == MessageBox::Cancel) {
return false; return false;
} }
@ -1228,8 +1233,11 @@ bool DatabaseWidget::lock()
} else { } else {
msg = tr("Database was modified.\nSave changes?"); msg = tr("Database was modified.\nSave changes?");
} }
auto result = MessageBox::question(this, tr("Save changes?"), msg, auto result = MessageBox::question(this,
MessageBox::Save | MessageBox::Discard | MessageBox::Cancel, MessageBox::Save); tr("Save changes?"),
msg,
MessageBox::Save | MessageBox::Discard | MessageBox::Cancel,
MessageBox::Save);
if (result == MessageBox::Save) { if (result == MessageBox::Save) {
if (!save()) { if (!save()) {
return false; return false;
@ -1306,7 +1314,8 @@ void DatabaseWidget::reloadDatabaseFile()
if (db->open(database()->key(), &error, true)) { if (db->open(database()->key(), &error, true)) {
if (m_db->isModified()) { if (m_db->isModified()) {
// Ask if we want to merge changes into new database // Ask if we want to merge changes into new database
auto result = MessageBox::question(this, auto result = MessageBox::question(
this,
tr("Merge Request"), tr("Merge Request"),
tr("The database file has changed and you have unsaved changes.\nDo you want to merge your changes?"), tr("The database file has changed and you have unsaved changes.\nDo you want to merge your changes?"),
MessageBox::Merge | MessageBox::Cancel, MessageBox::Merge | MessageBox::Cancel,
@ -1336,8 +1345,7 @@ void DatabaseWidget::reloadDatabaseFile()
m_db->setReadOnly(isReadOnly); m_db->setReadOnly(isReadOnly);
restoreGroupEntryFocus(groupBeforeReload, entryBeforeReload); restoreGroupEntryFocus(groupBeforeReload, entryBeforeReload);
} else { } else {
showMessage( showMessage(tr("Could not open the new database file while attempting to autoreload.\nError: %1").arg(error),
tr("Could not open the new database file while attempting to autoreload.\nError: %1").arg(error),
MessageWidget::Error); MessageWidget::Error);
// Mark db as modified since existing data may differ from file or file was deleted // Mark db as modified since existing data may differ from file or file was deleted
m_db->markAsModified(); m_db->markAsModified();
@ -1525,12 +1533,16 @@ bool DatabaseWidget::saveAs()
while (true) { while (true) {
QString oldFilePath = m_db->filePath(); QString oldFilePath = m_db->filePath();
if (!QFileInfo(oldFilePath).exists()) { if (!QFileInfo(oldFilePath).exists()) {
oldFilePath = QDir::toNativeSeparators(config()->get("LastDir", QDir::homePath()).toString() oldFilePath = QDir::toNativeSeparators(config()->get("LastDir", QDir::homePath()).toString() + "/"
+ "/" + tr("Passwords").append(".kdbx")); + tr("Passwords").append(".kdbx"));
} }
QString newFilePath = fileDialog()->getSaveFileName( QString newFilePath = fileDialog()->getSaveFileName(this,
this, tr("Save database as"), oldFilePath, tr("Save database as"),
tr("KeePass 2 Database").append(" (*.kdbx)"), nullptr, nullptr, "kdbx"); oldFilePath,
tr("KeePass 2 Database").append(" (*.kdbx)"),
nullptr,
nullptr,
"kdbx");
if (!newFilePath.isEmpty()) { if (!newFilePath.isEmpty()) {
// Ensure we don't recurse back into this function // Ensure we don't recurse back into this function
@ -1550,8 +1562,10 @@ bool DatabaseWidget::saveAs()
} }
} }
void DatabaseWidget::showMessage(const QString& text, MessageWidget::MessageType type, void DatabaseWidget::showMessage(const QString& text,
bool showClosebutton, int autoHideTimeout) MessageWidget::MessageType type,
bool showClosebutton,
int autoHideTimeout)
{ {
m_messageWidget->setCloseButtonVisible(showClosebutton); m_messageWidget->setCloseButtonVisible(showClosebutton);
m_messageWidget->showMessage(text, type, autoHideTimeout); m_messageWidget->showMessage(text, type, autoHideTimeout);
@ -1580,7 +1594,8 @@ void DatabaseWidget::emptyRecycleBin()
return; return;
} }
auto result = MessageBox::question(this, auto result =
MessageBox::question(this,
tr("Empty recycle bin?"), tr("Empty recycle bin?"),
tr("Are you sure you want to permanently delete everything from your recycle bin?"), tr("Are you sure you want to permanently delete everything from your recycle bin?"),
MessageBox::Empty | MessageBox::Cancel, MessageBox::Empty | MessageBox::Cancel,

View file

@ -25,7 +25,6 @@
#include <QTimer> #include <QTimer>
#include "DatabaseOpenDialog.h" #include "DatabaseOpenDialog.h"
#include "gui/entry/EntryModel.h"
#include "gui/MessageWidget.h" #include "gui/MessageWidget.h"
#include "gui/csvImport/CsvImportWizard.h" #include "gui/csvImport/CsvImportWizard.h"
#include "gui/entry/EntryModel.h" #include "gui/entry/EntryModel.h"

View file

@ -30,8 +30,8 @@
#include "gui/MessageBox.h" #include "gui/MessageBox.h"
#ifdef WITH_XC_NETWORKING #ifdef WITH_XC_NETWORKING
#include <QtNetwork>
#include <QNetworkAccessManager> #include <QNetworkAccessManager>
#include <QtNetwork>
#endif #endif
IconStruct::IconStruct() IconStruct::IconStruct()
@ -417,7 +417,6 @@ void EditWidgetIcons::removeCustomIcon()
int iconUseCount = entriesWithSameIcon.size() + groupsWithSameIcon.size(); int iconUseCount = entriesWithSameIcon.size() + groupsWithSameIcon.size();
if (iconUseCount > 0) { if (iconUseCount > 0) {
auto result = MessageBox::question(this, auto result = MessageBox::question(this,
tr("Confirm Delete"), tr("Confirm Delete"),
tr("This icon is used by %n entry(s), and will be replaced " tr("This icon is used by %n entry(s), and will be replaced "

View file

@ -18,9 +18,9 @@
#include "EditWidgetProperties.h" #include "EditWidgetProperties.h"
#include "ui_EditWidgetProperties.h" #include "ui_EditWidgetProperties.h"
#include "MessageBox.h"
#include "core/CustomData.h" #include "core/CustomData.h"
#include "core/TimeInfo.h" #include "core/TimeInfo.h"
#include "MessageBox.h"
#include <QUuid> #include <QUuid>
@ -105,8 +105,8 @@ void EditWidgetProperties::update()
m_ui->removeCustomDataButton->setEnabled(false); m_ui->removeCustomDataButton->setEnabled(false);
} else { } else {
for (const QString& key : m_customData->keys()) { for (const QString& key : m_customData->keys()) {
m_customDataModel->appendRow(QList<QStandardItem*>() << new QStandardItem(key) m_customDataModel->appendRow(QList<QStandardItem*>()
<< new QStandardItem(m_customData->value(key))); << new QStandardItem(key) << new QStandardItem(m_customData->value(key)));
} }
m_ui->removeCustomDataButton->setEnabled(!m_customData->isEmpty()); m_ui->removeCustomDataButton->setEnabled(!m_customData->isEmpty());
} }

View file

@ -30,7 +30,8 @@
#include "keeshare/KeeShare.h" #include "keeshare/KeeShare.h"
#endif #endif
namespace { namespace
{
constexpr int GeneralTabIndex = 0; constexpr int GeneralTabIndex = 0;
} }

View file

@ -193,7 +193,8 @@ QString FileDialog::getSaveFileName(QWidget* parent,
} }
} }
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()) { if (!m_nextDirName.isEmpty()) {
QString result = m_nextDirName; QString result = m_nextDirName;

View file

@ -29,12 +29,14 @@ public:
const QString& filter = QString(), const QString& filter = QString(),
QString* selectedFilter = nullptr, QString* selectedFilter = nullptr,
QFileDialog::Options options = 0); QFileDialog::Options options = 0);
QStringList getOpenFileNames(QWidget* parent = nullptr, QStringList getOpenFileNames(QWidget* parent = nullptr,
const QString& caption = QString(), const QString& caption = QString(),
QString dir = QString(), QString dir = QString(),
const QString& filter = QString(), const QString& filter = QString(),
QString* selectedFilter = nullptr, QString* selectedFilter = nullptr,
QFileDialog::Options options = 0); QFileDialog::Options options = 0);
QString getFileName(QWidget* parent = nullptr, QString getFileName(QWidget* parent = nullptr,
const QString& caption = QString(), const QString& caption = QString(),
QString dir = QString(), QString dir = QString(),
@ -43,6 +45,7 @@ public:
QFileDialog::Options options = 0, QFileDialog::Options options = 0,
const QString& defaultExtension = QString(), const QString& defaultExtension = QString(),
const QString& defaultName = QString()); const QString& defaultName = QString());
QString getSaveFileName(QWidget* parent = nullptr, QString getSaveFileName(QWidget* parent = nullptr,
const QString& caption = QString(), const QString& caption = QString(),
QString dir = QString(), QString dir = QString(),
@ -51,6 +54,7 @@ public:
QFileDialog::Options options = 0, QFileDialog::Options options = 0,
const QString& defaultExtension = QString(), const QString& defaultExtension = QString(),
const QString& defaultName = QString()); const QString& defaultName = QString());
QString getExistingDirectory(QWidget* parent = nullptr, QString getExistingDirectory(QWidget* parent = nullptr,
const QString& caption = QString(), const QString& caption = QString(),
QString dir = QString(), QString dir = QString(),

View file

@ -1,6 +1,7 @@
/* /*
* This file was generated by qdbusxml2cpp version 0.8 * This file was generated by qdbusxml2cpp version 0.8
* Command line was: qdbusxml2cpp -c MainWindowAdaptor -a MainWindowAdaptor.h:MainWindowAdaptor.cpp org.keepassxc.MainWindow.xml * Command line was: qdbusxml2cpp -c MainWindowAdaptor -a MainWindowAdaptor.h:MainWindowAdaptor.cpp
* org.keepassxc.MainWindow.xml
* *
* qdbusxml2cpp is Copyright (C) 2015 The Qt Company Ltd. * qdbusxml2cpp is Copyright (C) 2015 The Qt Company Ltd.
* *
@ -9,10 +10,10 @@
*/ */
#include "MainWindowAdaptor.h" #include "MainWindowAdaptor.h"
#include <QtCore/QMetaObject>
#include <QtCore/QByteArray> #include <QtCore/QByteArray>
#include <QtCore/QList> #include <QtCore/QList>
#include <QtCore/QMap> #include <QtCore/QMap>
#include <QtCore/QMetaObject>
#include <QtCore/QString> #include <QtCore/QString>
#include <QtCore/QStringList> #include <QtCore/QStringList>
#include <QtCore/QVariant> #include <QtCore/QVariant>
@ -58,6 +59,6 @@ void MainWindowAdaptor::openDatabase(const QString &fileName, const QString &pw)
void MainWindowAdaptor::openDatabase(const QString& fileName, const QString& pw, const QString& keyFile) void MainWindowAdaptor::openDatabase(const QString& fileName, const QString& pw, const QString& keyFile)
{ {
QMetaObject::invokeMethod(parent(), "openDatabase", Q_ARG(QString, fileName), Q_ARG(QString, pw), Q_ARG(QString, keyFile)); QMetaObject::invokeMethod(
parent(), "openDatabase", Q_ARG(QString, fileName), Q_ARG(QString, pw), Q_ARG(QString, keyFile));
} }

View file

@ -1,6 +1,7 @@
/* /*
* This file was generated by qdbusxml2cpp version 0.8 * This file was generated by qdbusxml2cpp version 0.8
* Command line was: qdbusxml2cpp -c MainWindowAdaptor -a MainWindowAdaptor.h:MainWindowAdaptor.cpp org.keepassxc.MainWindow.xml * Command line was: qdbusxml2cpp -c MainWindowAdaptor -a MainWindowAdaptor.h:MainWindowAdaptor.cpp
* org.keepassxc.MainWindow.xml
* *
* qdbusxml2cpp is Copyright (C) 2015 The Qt Company Ltd. * qdbusxml2cpp is Copyright (C) 2015 The Qt Company Ltd.
* *
@ -30,7 +31,8 @@ class MainWindowAdaptor: public QDBusAbstractAdaptor
{ {
Q_OBJECT Q_OBJECT
Q_CLASSINFO("D-Bus Interface", "org.keepassxc.MainWindow") Q_CLASSINFO("D-Bus Interface", "org.keepassxc.MainWindow")
Q_CLASSINFO("D-Bus Introspection", "" Q_CLASSINFO("D-Bus Introspection",
""
" <interface name=\"org.keepassxc.MainWindow\">\n" " <interface name=\"org.keepassxc.MainWindow\">\n"
" <method name=\"openDatabase\">\n" " <method name=\"openDatabase\">\n"
" <arg direction=\"in\" type=\"s\" name=\"fileName\"/>\n" " <arg direction=\"in\" type=\"s\" name=\"fileName\"/>\n"

View file

@ -20,19 +20,15 @@
MessageBox::Button MessageBox::m_nextAnswer(MessageBox::NoButton); MessageBox::Button MessageBox::m_nextAnswer(MessageBox::NoButton);
QMap<QAbstractButton*, MessageBox::Button> QMap<QAbstractButton*, MessageBox::Button> MessageBox::m_addedButtonLookup =
MessageBox::m_addedButtonLookup =
QMap<QAbstractButton*, MessageBox::Button>(); QMap<QAbstractButton*, MessageBox::Button>();
QMap<MessageBox::Button, std::pair<QString, QMessageBox::ButtonRole>> QMap<MessageBox::Button, std::pair<QString, QMessageBox::ButtonRole>> MessageBox::m_buttonDefs =
MessageBox::m_buttonDefs =
QMap<MessageBox::Button, std::pair<QString, QMessageBox::ButtonRole>>(); QMap<MessageBox::Button, std::pair<QString, QMessageBox::ButtonRole>>();
void MessageBox::initializeButtonDefs() void MessageBox::initializeButtonDefs()
{ {
m_buttonDefs = m_buttonDefs = QMap<Button, std::pair<QString, QMessageBox::ButtonRole>>{
QMap<Button, std::pair<QString, QMessageBox::ButtonRole>>
{
// Reimplementation of Qt StandardButtons // Reimplementation of Qt StandardButtons
{Ok, {stdButtonText(QMessageBox::Ok), QMessageBox::ButtonRole::AcceptRole}}, {Ok, {stdButtonText(QMessageBox::Ok), QMessageBox::ButtonRole::AcceptRole}},
{Open, {stdButtonText(QMessageBox::Open), QMessageBox::ButtonRole::AcceptRole}}, {Open, {stdButtonText(QMessageBox::Open), QMessageBox::ButtonRole::AcceptRole}},

View file

@ -19,14 +19,15 @@
#ifndef KEEPASSX_MESSAGEBOX_H #ifndef KEEPASSX_MESSAGEBOX_H
#define KEEPASSX_MESSAGEBOX_H #define KEEPASSX_MESSAGEBOX_H
#include <QMap>
#include <QMessageBox> #include <QMessageBox>
#include <QPushButton> #include <QPushButton>
#include <QMap>
class MessageBox class MessageBox
{ {
public: public:
enum Button : uint64_t { enum Button : uint64_t
{
// Reimplementation of Qt StandardButtons // Reimplementation of Qt StandardButtons
NoButton = 0, NoButton = 0,
Ok = 1 << 1, Ok = 1 << 1,
@ -63,7 +64,8 @@ public:
Last = Merge, Last = Merge,
}; };
enum Action { enum Action
{
None = 0, None = 0,
Raise = 1, Raise = 1,
}; };
@ -112,9 +114,6 @@ private:
Action action = MessageBox::None); Action action = MessageBox::None);
static QString stdButtonText(QMessageBox::StandardButton button); static QString stdButtonText(QMessageBox::StandardButton button);
}; };
#endif // KEEPASSX_MESSAGEBOX_H #endif // KEEPASSX_MESSAGEBOX_H

View file

@ -17,8 +17,8 @@
*/ */
#include "SearchWidget.h" #include "SearchWidget.h"
#include "ui_SearchWidget.h"
#include "ui_SearchHelpWidget.h" #include "ui_SearchHelpWidget.h"
#include "ui_SearchWidget.h"
#include <QKeyEvent> #include <QKeyEvent>
#include <QMenu> #include <QMenu>

View file

@ -16,9 +16,9 @@
* along with this program. If not, see <http://www.gnu.org/licenses/>. * along with this program. If not, see <http://www.gnu.org/licenses/>.
*/ */
#include <QKeyEvent>
#include "WelcomeWidget.h" #include "WelcomeWidget.h"
#include "ui_WelcomeWidget.h" #include "ui_WelcomeWidget.h"
#include <QKeyEvent>
#include "config-keepassx.h" #include "config-keepassx.h"
#include "core/Config.h" #include "core/Config.h"
@ -78,7 +78,8 @@ void WelcomeWidget::refreshLastDatabases()
} }
} }
void WelcomeWidget::keyPressEvent(QKeyEvent *event) { void WelcomeWidget::keyPressEvent(QKeyEvent* event)
{
if (m_ui->recentListWidget->hasFocus() && (event->key() == Qt::Key_Return || event->key() == Qt::Key_Enter)) { if (m_ui->recentListWidget->hasFocus() && (event->key() == Qt::Key_Return || event->key() == Qt::Key_Enter)) {
openDatabaseFromFile(m_ui->recentListWidget->currentItem()); openDatabaseFromFile(m_ui->recentListWidget->currentItem());
} }

View file

@ -29,10 +29,10 @@
#include "keeshare/DatabaseSettingsPageKeeShare.h" #include "keeshare/DatabaseSettingsPageKeeShare.h"
#endif #endif
#include "core/Global.h"
#include "core/Config.h" #include "core/Config.h"
#include "core/Database.h" #include "core/Database.h"
#include "core/FilePath.h" #include "core/FilePath.h"
#include "core/Global.h"
#include "touchid/TouchID.h" #include "touchid/TouchID.h"
class DatabaseSettingsDialog::ExtraPage class DatabaseSettingsDialog::ExtraPage
@ -51,6 +51,7 @@ public:
{ {
settingsPage->saveSettings(widget); settingsPage->saveSettings(widget);
} }
private: private:
QSharedPointer<IDatabaseSettingsPage> settingsPage; QSharedPointer<IDatabaseSettingsPage> settingsPage;
QWidget* widget; QWidget* widget;

View file

@ -138,7 +138,6 @@ void EditEntryWidget::setupMain()
m_mainUi->fetchFaviconButton->setVisible(false); m_mainUi->fetchFaviconButton->setVisible(false);
#endif #endif
connect(m_mainUi->togglePasswordButton, SIGNAL(toggled(bool)), m_mainUi->passwordEdit, SLOT(setShowPassword(bool))); connect(m_mainUi->togglePasswordButton, SIGNAL(toggled(bool)), m_mainUi->passwordEdit, SLOT(setShowPassword(bool)));
connect(m_mainUi->togglePasswordGeneratorButton, SIGNAL(toggled(bool)), SLOT(togglePasswordGeneratorButton(bool))); connect(m_mainUi->togglePasswordGeneratorButton, SIGNAL(toggled(bool)), SLOT(togglePasswordGeneratorButton(bool)));
#ifdef WITH_XC_NETWORKING #ifdef WITH_XC_NETWORKING
@ -309,8 +308,8 @@ void EditEntryWidget::setupEntryUpdate()
connect(m_sshAgentUi->externalFileEdit, SIGNAL(textChanged(QString)), this, SLOT(setUnsavedChanges())); connect(m_sshAgentUi->externalFileEdit, SIGNAL(textChanged(QString)), this, SLOT(setUnsavedChanges()));
connect(m_sshAgentUi->addKeyToAgentCheckBox, SIGNAL(stateChanged(int)), 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->removeKeyFromAgentCheckBox, SIGNAL(stateChanged(int)), this, SLOT(setUnsavedChanges()));
connect(m_sshAgentUi->requireUserConfirmationCheckBox, SIGNAL(stateChanged(int)), connect(
this, SLOT(setUnsavedChanges())); m_sshAgentUi->requireUserConfirmationCheckBox, SIGNAL(stateChanged(int)), this, SLOT(setUnsavedChanges()));
connect(m_sshAgentUi->lifetimeCheckBox, 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())); connect(m_sshAgentUi->lifetimeSpinBox, SIGNAL(valueChanged(int)), this, SLOT(setUnsavedChanges()));
} }
@ -370,7 +369,9 @@ void EditEntryWidget::setupSSHAgent()
connect(m_sshAgentUi->decryptButton, SIGNAL(clicked()), SLOT(decryptPrivateKey())); connect(m_sshAgentUi->decryptButton, SIGNAL(clicked()), SLOT(decryptPrivateKey()));
connect(m_sshAgentUi->copyToClipboardButton, SIGNAL(clicked()), SLOT(copyPublicKey())); connect(m_sshAgentUi->copyToClipboardButton, SIGNAL(clicked()), SLOT(copyPublicKey()));
connect(m_advancedUi->attachmentsWidget->entryAttachments(), SIGNAL(entryAttachmentsModified()), SLOT(updateSSHAgentAttachments())); connect(m_advancedUi->attachmentsWidget->entryAttachments(),
SIGNAL(entryAttachmentsModified()),
SLOT(updateSSHAgentAttachments()));
addPage(tr("SSH Agent"), FilePath::instance()->icon("apps", "utilities-terminal"), m_sshAgentWidget); addPage(tr("SSH Agent"), FilePath::instance()->icon("apps", "utilities-terminal"), m_sshAgentWidget);
} }
@ -591,8 +592,8 @@ void EditEntryWidget::addKeyToAgent()
lifetime = m_sshAgentUi->lifetimeSpinBox->value(); lifetime = m_sshAgentUi->lifetimeSpinBox->value();
} }
if (!SSHAgent::instance()->addIdentity(key, m_sshAgentUi->removeKeyFromAgentCheckBox->isChecked(), if (!SSHAgent::instance()->addIdentity(
static_cast<quint32>(lifetime), confirm)) { key, m_sshAgentUi->removeKeyFromAgentCheckBox->isChecked(), static_cast<quint32>(lifetime), confirm)) {
showMessage(SSHAgent::instance()->errorString(), MessageWidget::Error); showMessage(SSHAgent::instance()->errorString(), MessageWidget::Error);
return; return;
} }
@ -662,7 +663,11 @@ QString EditEntryWidget::entryTitle() const
} }
} }
void EditEntryWidget::loadEntry(Entry* entry, bool create, bool history, const QString& parentName, QSharedPointer<Database> database) void EditEntryWidget::loadEntry(Entry* entry,
bool create,
bool history,
const QString& parentName,
QSharedPointer<Database> database)
{ {
m_entry = entry; m_entry = entry;
m_db = std::move(database); m_db = std::move(database);

View file

@ -21,9 +21,8 @@
#include <QButtonGroup> #include <QButtonGroup>
#include <QModelIndex> #include <QModelIndex>
#include <QScopedPointer>
#include <QButtonGroup>
#include <QPointer> #include <QPointer>
#include <QScopedPointer>
#include "config-keepassx.h" #include "config-keepassx.h"
#include "gui/EditWidget.h" #include "gui/EditWidget.h"
@ -64,8 +63,8 @@ public:
explicit EditEntryWidget(QWidget* parent = nullptr); explicit EditEntryWidget(QWidget* parent = nullptr);
~EditEntryWidget() override; ~EditEntryWidget() override;
void loadEntry(Entry* entry, bool create, bool history, const QString& parentName, void
QSharedPointer<Database> database); loadEntry(Entry* entry, bool create, bool history, const QString& parentName, QSharedPointer<Database> database);
QString entryTitle() const; QString entryTitle() const;
void clear(); void clear();

View file

@ -223,11 +223,8 @@ void EntryAttachmentsWidget::saveSelectedAttachments()
const QString questionText( const QString questionText(
tr("Are you sure you want to overwrite the existing file \"%1\" with the attachment?")); tr("Are you sure you want to overwrite the existing file \"%1\" with the attachment?"));
auto result = MessageBox::question(this, auto result = MessageBox::question(
tr("Confirm overwrite"), this, tr("Confirm overwrite"), questionText.arg(filename), buttons, MessageBox::Cancel);
questionText.arg(filename),
buttons,
MessageBox::Cancel);
if (result == MessageBox::Skip) { if (result == MessageBox::Skip) {
continue; continue;

View file

@ -18,8 +18,8 @@
#ifndef KEEPASSXC_POPUPHELPWIDGET_H #ifndef KEEPASSXC_POPUPHELPWIDGET_H
#define KEEPASSXC_POPUPHELPWIDGET_H #define KEEPASSXC_POPUPHELPWIDGET_H
#include <QPointer>
#include <QFrame> #include <QFrame>
#include <QPointer>
class PopupHelpWidget : public QFrame class PopupHelpWidget : public QFrame
{ {
@ -44,5 +44,4 @@ private:
Qt::Corner m_corner; Qt::Corner m_corner;
}; };
#endif // KEEPASSXC_POPUPHELPWIDGET_H #endif // KEEPASSXC_POPUPHELPWIDGET_H

View file

@ -367,8 +367,8 @@ ShareObserver::Result ShareObserver::importSingedContainerInto(const KeeShareSet
case UntrustedForever: case UntrustedForever:
case TrustedForever: { case TrustedForever: {
bool found = false; bool found = false;
const auto trusted = trust.first == TrustedForever ? KeeShareSettings::Trust::Trusted const auto trusted =
: KeeShareSettings::Trust::Untrusted; trust.first == TrustedForever ? KeeShareSettings::Trust::Trusted : KeeShareSettings::Trust::Untrusted;
for (KeeShareSettings::ScopedCertificate& scopedCertificate : foreign.certificates) { for (KeeShareSettings::ScopedCertificate& scopedCertificate : foreign.certificates) {
if (scopedCertificate.certificate.key == trust.second.key && scopedCertificate.path == reference.path) { if (scopedCertificate.certificate.key == trust.second.key && scopedCertificate.path == reference.path) {
scopedCertificate.certificate.signer = trust.second.signer; scopedCertificate.certificate.signer = trust.second.signer;
@ -454,8 +454,8 @@ ShareObserver::Result ShareObserver::importUnsignedContainerInto(const KeeShareS
case UntrustedForever: case UntrustedForever:
case TrustedForever: { case TrustedForever: {
bool found = false; bool found = false;
const auto trusted = trust.first == TrustedForever ? KeeShareSettings::Trust::Trusted const auto trusted =
: KeeShareSettings::Trust::Untrusted; trust.first == TrustedForever ? KeeShareSettings::Trust::Trusted : KeeShareSettings::Trust::Untrusted;
for (KeeShareSettings::ScopedCertificate& scopedCertificate : foreign.certificates) { for (KeeShareSettings::ScopedCertificate& scopedCertificate : foreign.certificates) {
if (scopedCertificate.certificate.key == trust.second.key && scopedCertificate.path == reference.path) { if (scopedCertificate.certificate.key == trust.second.key && scopedCertificate.path == reference.path) {
scopedCertificate.certificate.signer = trust.second.signer; scopedCertificate.certificate.signer = trust.second.signer;

View file

@ -67,9 +67,8 @@ bool YkChallengeResponseKey::challenge(const QByteArray& challenge, unsigned int
emit userInteractionRequired(); emit userInteractionRequired();
} }
auto result = AsyncTask::runAndWaitForFuture([this, challenge]() { auto result = AsyncTask::runAndWaitForFuture(
return YubiKey::instance()->challenge(m_slot, true, challenge, m_key); [this, challenge]() { return YubiKey::instance()->challenge(m_slot, true, challenge, m_key); });
});
if (m_blocking) { if (m_blocking) {
emit userConfirmed(); emit userConfirmed();

View file

@ -18,10 +18,10 @@
#include "SSHAgent.h" #include "SSHAgent.h"
#include "crypto/ssh/OpenSSHKey.h"
#include "crypto/ssh/BinaryStream.h"
#include "sshagent/KeeAgentSettings.h"
#include "core/Config.h" #include "core/Config.h"
#include "crypto/ssh/BinaryStream.h"
#include "crypto/ssh/OpenSSHKey.h"
#include "sshagent/KeeAgentSettings.h"
#include <QtNetwork> #include <QtNetwork>
@ -371,8 +371,8 @@ void SSHAgent::databaseModeChanged()
lifetime = static_cast<quint32>(settings.lifetimeConstraintDuration()); lifetime = static_cast<quint32>(settings.lifetimeConstraintDuration());
} }
if (!addIdentity(key, settings.removeAtDatabaseClose(), if (!addIdentity(
lifetime, settings.useConfirmConstraintWhenAdding())) { key, settings.removeAtDatabaseClose(), lifetime, settings.useConfirmConstraintWhenAdding())) {
emit error(m_error); emit error(m_error);
} }
} }

View file

@ -19,12 +19,12 @@
#ifndef KEEPASSXC_SSHAGENT_H #ifndef KEEPASSXC_SSHAGENT_H
#define KEEPASSXC_SSHAGENT_H #define KEEPASSXC_SSHAGENT_H
#include <QList>
#include <QHash> #include <QHash>
#include <QList>
#include <QtCore> #include <QtCore>
#include "gui/DatabaseWidget.h"
#include "crypto/ssh/OpenSSHKey.h" #include "crypto/ssh/OpenSSHKey.h"
#include "gui/DatabaseWidget.h"
class SSHAgent : public QObject class SSHAgent : public QObject
{ {

View file

@ -284,7 +284,8 @@ void TestCli::testClip()
// TOTP with timeout // TOTP with timeout
Utils::Test::setNextPassword("a"); Utils::Test::setNextPassword("a");
future = QtConcurrent::run(&clipCmd, &Clip::execute, QStringList{"clip", m_dbFile->fileName(), "/Sample Entry", "1", "-t"}); future = QtConcurrent::run(
&clipCmd, &Clip::execute, QStringList{"clip", m_dbFile->fileName(), "/Sample Entry", "1", "-t"});
QTRY_VERIFY_WITH_TIMEOUT(isTOTP(clipboard->text()), 500); QTRY_VERIFY_WITH_TIMEOUT(isTOTP(clipboard->text()), 500);
QTRY_COMPARE_WITH_TIMEOUT(clipboard->text(), QString(""), 1500); QTRY_COMPARE_WITH_TIMEOUT(clipboard->text(), QString(""), 1500);
@ -314,7 +315,8 @@ void TestCli::testCreate()
m_stderrFile->reset(); m_stderrFile->reset();
m_stdoutFile->reset(); m_stdoutFile->reset();
QCOMPARE(m_stdoutFile->readLine(), QByteArray("Insert password to encrypt database (Press enter to leave blank): \n")); QCOMPARE(m_stdoutFile->readLine(),
QByteArray("Insert password to encrypt database (Press enter to leave blank): \n"));
QCOMPARE(m_stdoutFile->readLine(), QByteArray("Successfully created new database.\n")); QCOMPARE(m_stdoutFile->readLine(), QByteArray("Successfully created new database.\n"));
Utils::Test::setNextPassword("a"); Utils::Test::setNextPassword("a");
@ -332,7 +334,6 @@ void TestCli::testCreate()
QString errorMessage = QString("File " + databaseFilename + " already exists.\n"); QString errorMessage = QString("File " + databaseFilename + " already exists.\n");
QCOMPARE(m_stderrFile->readAll(), errorMessage.toUtf8()); QCOMPARE(m_stderrFile->readAll(), errorMessage.toUtf8());
// Testing with keyfile creation // Testing with keyfile creation
QString databaseFilename2 = testDir->path() + "testCreate2.kdbx"; QString databaseFilename2 = testDir->path() + "testCreate2.kdbx";
QString keyfilePath = testDir->path() + "keyfile.txt"; QString keyfilePath = testDir->path() + "keyfile.txt";
@ -343,14 +344,14 @@ void TestCli::testCreate()
m_stdoutFile->seek(pos); m_stdoutFile->seek(pos);
m_stderrFile->seek(errPos); m_stderrFile->seek(errPos);
QCOMPARE(m_stdoutFile->readLine(), QByteArray("Insert password to encrypt database (Press enter to leave blank): \n")); QCOMPARE(m_stdoutFile->readLine(),
QByteArray("Insert password to encrypt database (Press enter to leave blank): \n"));
QCOMPARE(m_stdoutFile->readLine(), QByteArray("Successfully created new database.\n")); QCOMPARE(m_stdoutFile->readLine(), QByteArray("Successfully created new database.\n"));
Utils::Test::setNextPassword("a"); Utils::Test::setNextPassword("a");
auto db2 = QSharedPointer<Database>(Utils::unlockDatabase(databaseFilename2, keyfilePath, Utils::DEVNULL)); auto db2 = QSharedPointer<Database>(Utils::unlockDatabase(databaseFilename2, keyfilePath, Utils::DEVNULL));
QVERIFY(db2); QVERIFY(db2);
// Testing with existing keyfile // Testing with existing keyfile
QString databaseFilename3 = testDir->path() + "testCreate3.kdbx"; QString databaseFilename3 = testDir->path() + "testCreate3.kdbx";
pos = m_stdoutFile->pos(); pos = m_stdoutFile->pos();
@ -360,7 +361,8 @@ void TestCli::testCreate()
m_stdoutFile->seek(pos); m_stdoutFile->seek(pos);
m_stderrFile->seek(errPos); m_stderrFile->seek(errPos);
QCOMPARE(m_stdoutFile->readLine(), QByteArray("Insert password to encrypt database (Press enter to leave blank): \n")); QCOMPARE(m_stdoutFile->readLine(),
QByteArray("Insert password to encrypt database (Press enter to leave blank): \n"));
QCOMPARE(m_stdoutFile->readLine(), QByteArray("Successfully created new database.\n")); QCOMPARE(m_stdoutFile->readLine(), QByteArray("Successfully created new database.\n"));
Utils::Test::setNextPassword("a"); Utils::Test::setNextPassword("a");
@ -681,7 +683,8 @@ void TestCli::testList()
Utils::Test::setNextPassword("a"); Utils::Test::setNextPassword("a");
listCmd.execute({"ls", "-q", m_dbFile->fileName()}); listCmd.execute({"ls", "-q", m_dbFile->fileName()});
m_stdoutFile->seek(pos); m_stdoutFile->seek(pos);
QCOMPARE(m_stdoutFile->readAll(), QByteArray("Sample Entry\n" QCOMPARE(m_stdoutFile->readAll(),
QByteArray("Sample Entry\n"
"General/\n" "General/\n"
"Windows/\n" "Windows/\n"
"Network/\n" "Network/\n"
@ -689,7 +692,6 @@ void TestCli::testList()
"eMail/\n" "eMail/\n"
"Homebanking/\n")); "Homebanking/\n"));
pos = m_stdoutFile->pos(); pos = m_stdoutFile->pos();
Utils::Test::setNextPassword("a"); Utils::Test::setNextPassword("a");
listCmd.execute({"ls", "-R", m_dbFile->fileName()}); listCmd.execute({"ls", "-R", m_dbFile->fileName()});
@ -1018,7 +1020,8 @@ void TestCli::testShow()
Utils::Test::setNextPassword("a"); Utils::Test::setNextPassword("a");
showCmd.execute({"show", m_dbFile->fileName(), "-q", "/Sample Entry"}); showCmd.execute({"show", m_dbFile->fileName(), "-q", "/Sample Entry"});
m_stdoutFile->seek(pos); m_stdoutFile->seek(pos);
QCOMPARE(m_stdoutFile->readAll(), QByteArray("Title: Sample Entry\n" QCOMPARE(m_stdoutFile->readAll(),
QByteArray("Title: Sample Entry\n"
"UserName: User Name\n" "UserName: User Name\n"
"Password: Password\n" "Password: Password\n"
"URL: http://www.somesite.com/\n" "URL: http://www.somesite.com/\n"

View file

@ -177,7 +177,8 @@ void TestEntrySearcher::testAllAttributesAreSearched()
void TestEntrySearcher::testSearchTermParser() void TestEntrySearcher::testSearchTermParser()
{ {
// Test standard search terms // Test standard search terms
auto terms = m_entrySearcher.parseSearchTerms("-test \"quoted \\\"string\\\"\" user:user pass:\"test me\" noquote "); auto terms =
m_entrySearcher.parseSearchTerms("-test \"quoted \\\"string\\\"\" user:user pass:\"test me\" noquote ");
QCOMPARE(terms.length(), 5); QCOMPARE(terms.length(), 5);

View file

@ -35,7 +35,8 @@ protected:
void initTestCaseImpl() override; void initTestCaseImpl() override;
QSharedPointer<Database> readXml(QBuffer* buf, bool strictMode, bool& hasError, QString& errorString) override; QSharedPointer<Database> readXml(QBuffer* buf, bool strictMode, bool& hasError, QString& errorString) override;
QSharedPointer<Database> readXml(const QString& path, bool strictMode, bool& hasError, QString& errorString) override; QSharedPointer<Database>
readXml(const QString& path, bool strictMode, bool& hasError, QString& errorString) override;
void writeXml(QBuffer* buf, Database* db, bool& hasError, QString& errorString) override; void writeXml(QBuffer* buf, Database* db, bool& hasError, QString& errorString) override;
void readKdbx(QIODevice* device, void readKdbx(QIODevice* device,

View file

@ -36,7 +36,8 @@ protected:
void initTestCaseImpl() override; void initTestCaseImpl() override;
QSharedPointer<Database> readXml(QBuffer* buf, bool strictMode, bool& hasError, QString& errorString) override; QSharedPointer<Database> readXml(QBuffer* buf, bool strictMode, bool& hasError, QString& errorString) override;
QSharedPointer<Database> readXml(const QString& path, bool strictMode, bool& hasError, QString& errorString) override; QSharedPointer<Database>
readXml(const QString& path, bool strictMode, bool& hasError, QString& errorString) override;
void writeXml(QBuffer* buf, Database* db, bool& hasError, QString& errorString) override; void writeXml(QBuffer* buf, Database* db, bool& hasError, QString& errorString) override;
void readKdbx(const QString& path, void readKdbx(const QString& path,

View file

@ -68,7 +68,8 @@ protected:
virtual void initTestCaseImpl() = 0; virtual void initTestCaseImpl() = 0;
virtual QSharedPointer<Database> readXml(QBuffer* buf, bool strictMode, bool& hasError, QString& errorString) = 0; virtual QSharedPointer<Database> readXml(QBuffer* buf, bool strictMode, bool& hasError, QString& errorString) = 0;
virtual QSharedPointer<Database> readXml(const QString& path, bool strictMode, bool& hasError, QString& errorString) = 0; virtual QSharedPointer<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 writeXml(QBuffer* buf, Database* db, bool& hasError, QString& errorString) = 0;
virtual void readKdbx(QIODevice* device, virtual void readKdbx(QIODevice* device,

View file

@ -145,11 +145,8 @@ void TestSharing::testCertificateSerialization()
const OpenSSHKey& key = stubkey(); const OpenSSHKey& key = stubkey();
KeeShareSettings::ScopedCertificate original; KeeShareSettings::ScopedCertificate original;
original.path = "/path"; original.path = "/path";
original.certificate = KeeShareSettings::Certificate original.certificate = KeeShareSettings::Certificate{OpenSSHKey::serializeToBinary(OpenSSHKey::Public, key),
{ "Some <!> &#_\"\" weird string"};
OpenSSHKey::serializeToBinary(OpenSSHKey::Public, key),
"Some <!> &#_\"\" weird string"
};
original.trust = trusted; original.trust = trusted;
QString buffer; QString buffer;
@ -230,10 +227,12 @@ void TestSharing::testReferenceSerialization_data()
QTest::addColumn<QString>("path"); QTest::addColumn<QString>("path");
QTest::addColumn<QUuid>("uuid"); QTest::addColumn<QUuid>("uuid");
QTest::addColumn<int>("type"); QTest::addColumn<int>("type");
QTest::newRow("1") << "Password" << "/some/path" << QUuid::createUuid() << int(KeeShareSettings::Inactive); QTest::newRow("1") << "Password"
QTest::newRow("2") << "" << "" << QUuid() << int(KeeShareSettings::SynchronizeWith); << "/some/path" << QUuid::createUuid() << int(KeeShareSettings::Inactive);
QTest::newRow("3") << "" << "/some/path" << QUuid() << int(KeeShareSettings::ExportTo); QTest::newRow("2") << ""
<< "" << QUuid() << int(KeeShareSettings::SynchronizeWith);
QTest::newRow("3") << ""
<< "/some/path" << QUuid() << int(KeeShareSettings::ExportTo);
} }
void TestSharing::testSettingsSerialization() void TestSharing::testSettingsSerialization()
@ -277,11 +276,8 @@ void TestSharing::testSettingsSerialization_data()
const OpenSSHKey& sshKey0 = stubkey(0); const OpenSSHKey& sshKey0 = stubkey(0);
KeeShareSettings::ScopedCertificate certificate0; KeeShareSettings::ScopedCertificate certificate0;
certificate0.path = "/path/0"; certificate0.path = "/path/0";
certificate0.certificate = KeeShareSettings::Certificate certificate0.certificate = KeeShareSettings::Certificate{OpenSSHKey::serializeToBinary(OpenSSHKey::Public, sshKey0),
{ "Some <!> &#_\"\" weird string"};
OpenSSHKey::serializeToBinary(OpenSSHKey::Public, sshKey0),
"Some <!> &#_\"\" weird string"
};
certificate0.trust = KeeShareSettings::Trust::Trusted; certificate0.trust = KeeShareSettings::Trust::Trusted;
KeeShareSettings::Key key0; KeeShareSettings::Key key0;
@ -290,11 +286,8 @@ void TestSharing::testSettingsSerialization_data()
const OpenSSHKey& sshKey1 = stubkey(1); const OpenSSHKey& sshKey1 = stubkey(1);
KeeShareSettings::ScopedCertificate certificate1; KeeShareSettings::ScopedCertificate certificate1;
certificate1.path = "/path/1"; certificate1.path = "/path/1";
certificate1.certificate = KeeShareSettings::Certificate certificate1.certificate =
{ KeeShareSettings::Certificate{OpenSSHKey::serializeToBinary(OpenSSHKey::Public, sshKey1), "Another "};
OpenSSHKey::serializeToBinary(OpenSSHKey::Public, sshKey1),
"Another "
};
certificate1.trust = KeeShareSettings::Trust::Untrusted; certificate1.trust = KeeShareSettings::Trust::Untrusted;
QTest::addColumn<bool>("importing"); QTest::addColumn<bool>("importing");
@ -302,11 +295,16 @@ void TestSharing::testSettingsSerialization_data()
QTest::addColumn<KeeShareSettings::Certificate>("ownCertificate"); QTest::addColumn<KeeShareSettings::Certificate>("ownCertificate");
QTest::addColumn<KeeShareSettings::Key>("ownKey"); QTest::addColumn<KeeShareSettings::Key>("ownKey");
QTest::addColumn<QList<KeeShareSettings::ScopedCertificate>>("foreignCertificates"); QTest::addColumn<QList<KeeShareSettings::ScopedCertificate>>("foreignCertificates");
QTest::newRow("1") << false << false << KeeShareSettings::Certificate() << KeeShareSettings::Key() << QList<KeeShareSettings::ScopedCertificate>(); QTest::newRow("1") << false << false << KeeShareSettings::Certificate() << KeeShareSettings::Key()
QTest::newRow("2") << true << false << KeeShareSettings::Certificate() << KeeShareSettings::Key() << QList<KeeShareSettings::ScopedCertificate>(); << QList<KeeShareSettings::ScopedCertificate>();
QTest::newRow("3") << true << true << KeeShareSettings::Certificate() << KeeShareSettings::Key() << QList<KeeShareSettings::ScopedCertificate>({ certificate0, certificate1 }); QTest::newRow("2") << true << false << KeeShareSettings::Certificate() << KeeShareSettings::Key()
QTest::newRow("4") << false << true << certificate0.certificate << key0 << QList<KeeShareSettings::ScopedCertificate>(); << QList<KeeShareSettings::ScopedCertificate>();
QTest::newRow("5") << false << false << certificate0.certificate << key0 << QList<KeeShareSettings::ScopedCertificate>({ certificate1 }); QTest::newRow("3") << true << true << KeeShareSettings::Certificate() << KeeShareSettings::Key()
<< QList<KeeShareSettings::ScopedCertificate>({certificate0, certificate1});
QTest::newRow("4") << false << true << certificate0.certificate << key0
<< QList<KeeShareSettings::ScopedCertificate>();
QTest::newRow("5") << false << false << certificate0.certificate << key0
<< QList<KeeShareSettings::ScopedCertificate>({certificate1});
} }
const OpenSSHKey& TestSharing::stubkey(int index) const OpenSSHKey& TestSharing::stubkey(int index)