From acb203e13a5135de006127ed6f27018d94a0309d Mon Sep 17 00:00:00 2001 From: Anne Jan Brouwer Date: Mon, 23 Nov 2015 22:55:42 +0100 Subject: [PATCH 01/13] Naming conventions --- mainwindow.cpp | 2 +- mainwindow.h | 2 +- Info.plist => qtpass.plist | 0 qtpass.pro | 2 +- trayicon.cpp | 14 +++++++------- trayicon.h | 4 ++-- 6 files changed, 12 insertions(+), 12 deletions(-) rename Info.plist => qtpass.plist (100%) diff --git a/mainwindow.cpp b/mainwindow.cpp index aac760416..d27744313 100644 --- a/mainwindow.cpp +++ b/mainwindow.cpp @@ -1534,7 +1534,7 @@ void MainWindow::initTrayIcon() } if(QSystemTrayIcon::isSystemTrayAvailable() == true) { // Setup tray icon - this->tray = new trayIcon(this); + this->tray = new TrayIcon(this); if(tray == NULL){ qDebug() << "Allocating tray icon failed."; } diff --git a/mainwindow.h b/mainwindow.h index 587d2a749..91cca8cc1 100644 --- a/mainwindow.h +++ b/mainwindow.h @@ -127,7 +127,7 @@ private slots: QHash profiles; QString profile; bool startupPhase; - trayIcon *tray; + TrayIcon *tray; bool useTrayIcon; bool hideOnClose; bool startMinimized; diff --git a/Info.plist b/qtpass.plist similarity index 100% rename from Info.plist rename to qtpass.plist diff --git a/qtpass.pro b/qtpass.pro index 53d9efc04..fbf2c5477 100644 --- a/qtpass.pro +++ b/qtpass.pro @@ -113,7 +113,7 @@ win32 { LIBS += -lmpr } else:macx { ICON = artwork/icon.icns - QMAKE_INFO_PLIST = Info.plist + QMAKE_INFO_PLIST = qtpass.plist } else:bsd { LIBS += -L/usr/local/lib } diff --git a/trayicon.cpp b/trayicon.cpp index 8dace210c..feaa1e9f9 100644 --- a/trayicon.cpp +++ b/trayicon.cpp @@ -1,6 +1,6 @@ #include "trayicon.h" -trayIcon::trayIcon(QMainWindow *parent) +TrayIcon::TrayIcon(QMainWindow *parent) { parentwin = parent; @@ -16,7 +16,7 @@ trayIcon::trayIcon(QMainWindow *parent) } -void trayIcon::setVisible(bool visible) +void TrayIcon::setVisible(bool visible) { if(visible == true) { parentwin->show(); @@ -25,7 +25,7 @@ void trayIcon::setVisible(bool visible) } } -void trayIcon::createActions() +void TrayIcon::createActions() { // minimizeAction = new QAction(tr("Mi&nimize"), this); // connect(minimizeAction, SIGNAL(triggered()), this, SLOT(hide())); @@ -41,7 +41,7 @@ void trayIcon::createActions() } -void trayIcon::createTrayIcon() +void TrayIcon::createTrayIcon() { trayIconMenu = new QMenu(this); // trayIconMenu->addAction(minimizeAction); @@ -54,7 +54,7 @@ void trayIcon::createTrayIcon() sysTrayIcon->setContextMenu(trayIconMenu); } -void trayIcon::showHideParent() +void TrayIcon::showHideParent() { if(parentwin->isVisible() == true) { parentwin->hide(); @@ -63,7 +63,7 @@ void trayIcon::showHideParent() } } -void trayIcon::iconActivated(QSystemTrayIcon::ActivationReason reason) +void TrayIcon::iconActivated(QSystemTrayIcon::ActivationReason reason) { switch (reason) { case QSystemTrayIcon::Trigger: @@ -78,7 +78,7 @@ void trayIcon::iconActivated(QSystemTrayIcon::ActivationReason reason) } } -void trayIcon::showMessage(QString title, QString msg, int time) +void TrayIcon::showMessage(QString title, QString msg, int time) { sysTrayIcon->showMessage(title, msg, QSystemTrayIcon::Information, time); } diff --git a/trayicon.h b/trayicon.h index b8ea411d3..b05cf768a 100644 --- a/trayicon.h +++ b/trayicon.h @@ -8,11 +8,11 @@ #include #include -class trayIcon : public QWidget +class TrayIcon : public QWidget { Q_OBJECT public: - explicit trayIcon(QMainWindow *parent); + explicit TrayIcon(QMainWindow *parent); void showMessage(QString title, QString msg, int time); void setVisible(bool visible); From 8d615a02074b2cc0ec3c4a8ccfe89cca81b73b10 Mon Sep 17 00:00:00 2001 From: Anne Jan Brouwer Date: Mon, 23 Nov 2015 23:28:59 +0100 Subject: [PATCH 02/13] linthub test --- .linthub.yml | 12 ++++++++++++ util.cpp | 12 ++++++++---- 2 files changed, 20 insertions(+), 4 deletions(-) create mode 100644 .linthub.yml diff --git a/.linthub.yml b/.linthub.yml new file mode 100644 index 000000000..0866734ab --- /dev/null +++ b/.linthub.yml @@ -0,0 +1,12 @@ +platform: linux | osx +build: +- qmake +- make +analyzers: + - cpplint: true + include: ["*.cpp", "*.h", "*.hpp", "*.c"] + path: . + filters: + - -whitespace + - +whitespace/braces + style: google diff --git a/util.cpp b/util.cpp index 218c61a62..5b2dd1e41 100644 --- a/util.cpp +++ b/util.cpp @@ -22,7 +22,8 @@ void Util::initialiseEnvironment() // TODO checks here QString path = _env.value("PATH"); - if (!path.contains("/usr/local/MacGPG2/bin") && QFile("/usr/local/MacGPG2/bin").exists()) { + if (!path.contains("/usr/local/MacGPG2/bin") + && QFile("/usr/local/MacGPG2/bin").exists()) { path += ":/usr/local/MacGPG2/bin"; } if (!path.contains("/usr/local/bin")) { @@ -46,9 +47,11 @@ QString Util::findPasswordStore() path = _env.value("PASSWORD_STORE_DIR"); } else { #ifdef Q_OS_WIN - path = QDir::homePath() + QDir::separator() + "password-store" + QDir::separator(); + path = QDir::homePath() + QDir::separator() + + "password-store" + QDir::separator(); #else - path = QDir::homePath() + QDir::separator() + ".password-store" + QDir::separator(); + path = QDir::homePath() + QDir::separator() + + ".password-store" + QDir::separator(); #endif } return Util::normalizeFolderPath(path); @@ -117,7 +120,8 @@ QString Util::findBinaryInPath(QString binary) */ bool Util::checkConfig(QString passStore, QString passExecutable, QString gpgExecutable) { - return !QFile(passStore + ".gpg-id").exists() || (!QFile(passExecutable).exists() && !QFile(gpgExecutable).exists()); + return !QFile(passStore + ".gpg-id").exists() + || (!QFile(passExecutable).exists() && !QFile(gpgExecutable).exists()); } From 95a68a47e10d59cc2d229ad4492264d6a93206f9 Mon Sep 17 00:00:00 2001 From: Anne Jan Brouwer Date: Mon, 23 Nov 2015 23:33:27 +0100 Subject: [PATCH 03/13] markdown added to lint --- .linthub.yml | 1 + 1 file changed, 1 insertion(+) diff --git a/.linthub.yml b/.linthub.yml index 0866734ab..d170b14ea 100644 --- a/.linthub.yml +++ b/.linthub.yml @@ -10,3 +10,4 @@ analyzers: - -whitespace - +whitespace/braces style: google + - markdownlint: true From 281d8efd8fc55d847cf356954c3b33853c4e2a35 Mon Sep 17 00:00:00 2001 From: Anne Jan Brouwer Date: Mon, 23 Nov 2015 23:48:56 +0100 Subject: [PATCH 04/13] uncrustify --- configdialog.cpp | 216 +++++++------ configdialog.h | 7 +- keygendialog.cpp | 50 ++- keygendialog.h | 1 - main.cpp | 8 +- mainwindow.cpp | 699 ++++++++++++++++++++---------------------- mainwindow.h | 22 +- passworddialog.cpp | 42 ++- progressindicator.cpp | 36 +-- progressindicator.h | 92 +++--- singleapplication.cpp | 87 +++--- singleapplication.h | 22 +- storemodel.cpp | 27 +- trayicon.cpp | 70 ++--- trayicon.h | 4 +- usersdialog.cpp | 32 +- usersdialog.h | 7 +- util.cpp | 39 ++- 18 files changed, 728 insertions(+), 733 deletions(-) diff --git a/configdialog.cpp b/configdialog.cpp index 690449088..6d61db86d 100644 --- a/configdialog.cpp +++ b/configdialog.cpp @@ -44,7 +44,8 @@ ConfigDialog::~ConfigDialog() * @brief ConfigDialog::setPassPath * @param path */ -void ConfigDialog::setPassPath(QString path) { +void ConfigDialog::setPassPath(QString path) +{ ui->passPath->setText(path); } @@ -52,7 +53,8 @@ void ConfigDialog::setPassPath(QString path) { * @brief ConfigDialog::setGitPath * @param path */ -void ConfigDialog::setGitPath(QString path) { +void ConfigDialog::setGitPath(QString path) +{ ui->gitPath->setText(path); if (path.isEmpty()) { useGit(false); @@ -66,7 +68,8 @@ void ConfigDialog::setGitPath(QString path) { * @brief ConfigDialog::setGpgPath * @param path */ -void ConfigDialog::setGpgPath(QString path) { +void ConfigDialog::setGpgPath(QString path) +{ ui->gpgPath->setText(path); } @@ -74,7 +77,8 @@ void ConfigDialog::setGpgPath(QString path) { * @brief ConfigDialog::setStorePath * @param path */ -void ConfigDialog::setStorePath(QString path) { +void ConfigDialog::setStorePath(QString path) +{ ui->storePath->setText(path); } @@ -82,7 +86,8 @@ void ConfigDialog::setStorePath(QString path) { * @brief ConfigDialog::getPassPath * @return */ -QString ConfigDialog::getPassPath() { +QString ConfigDialog::getPassPath() +{ return ui->passPath->text(); } @@ -90,7 +95,8 @@ QString ConfigDialog::getPassPath() { * @brief ConfigDialog::getGitPath * @return */ -QString ConfigDialog::getGitPath() { +QString ConfigDialog::getGitPath() +{ return ui->gitPath->text(); } @@ -98,7 +104,8 @@ QString ConfigDialog::getGitPath() { * @brief ConfigDialog::getGpgPath * @return */ -QString ConfigDialog::getGpgPath() { +QString ConfigDialog::getGpgPath() +{ return ui->gpgPath->text(); } @@ -106,7 +113,8 @@ QString ConfigDialog::getGpgPath() { * @brief ConfigDialog::getStorePath * @return */ -QString ConfigDialog::getStorePath() { +QString ConfigDialog::getStorePath() +{ return ui->storePath->text(); } @@ -114,7 +122,8 @@ QString ConfigDialog::getStorePath() { * @brief ConfigDialog::usePass * @return */ -bool ConfigDialog::usePass() { +bool ConfigDialog::usePass() +{ return ui->radioButtonPass->isChecked(); } @@ -122,7 +131,8 @@ bool ConfigDialog::usePass() { * @brief ConfigDialog::usePass * @param pass */ -void ConfigDialog::usePass(bool usePass) { +void ConfigDialog::usePass(bool usePass) +{ if (usePass) { ui->radioButtonNative->setChecked(false); ui->radioButtonPass->setChecked(true); @@ -152,7 +162,8 @@ void ConfigDialog::on_radioButtonPass_clicked() /** * @brief ConfigDialog::setGroupBoxState */ -void ConfigDialog::setGroupBoxState() { +void ConfigDialog::setGroupBoxState() +{ if (ui->radioButtonPass->isChecked()) { ui->groupBoxNative->setEnabled(false); ui->groupBoxPass->setEnabled(true); @@ -166,13 +177,13 @@ void ConfigDialog::setGroupBoxState() { * @brief ConfigDialog::selectExecutable * @return */ -QString ConfigDialog::selectExecutable() { +QString ConfigDialog::selectExecutable() +{ QFileDialog dialog(this); dialog.setFileMode(QFileDialog::ExistingFile); dialog.setOption(QFileDialog::ReadOnly); - if (dialog.exec()) { + if (dialog.exec()) return dialog.selectedFiles().first(); - } else return ""; } @@ -180,14 +191,14 @@ QString ConfigDialog::selectExecutable() { * @brief ConfigDialog::selectFolder * @return */ -QString ConfigDialog::selectFolder() { +QString ConfigDialog::selectFolder() +{ QFileDialog dialog(this); dialog.setFileMode(QFileDialog::Directory); dialog.setFilter(QDir::NoFilter); dialog.setOption(QFileDialog::ShowDirsOnly); - if (dialog.exec()) { + if (dialog.exec()) return dialog.selectedFiles().first(); - } else return ""; } @@ -212,9 +223,8 @@ void ConfigDialog::on_toolButtonGit_clicked() void ConfigDialog::on_toolButtonGpg_clicked() { QString gpg = selectExecutable(); - if (!gpg.isEmpty()) { + if (!gpg.isEmpty()) ui->gpgPath->setText(gpg); - } } /** @@ -223,9 +233,8 @@ void ConfigDialog::on_toolButtonGpg_clicked() void ConfigDialog::on_toolButtonPass_clicked() { QString pass = selectExecutable(); - if (!pass.isEmpty()) { + if (!pass.isEmpty()) ui->passPath->setText(pass); - } } /** @@ -234,9 +243,8 @@ void ConfigDialog::on_toolButtonPass_clicked() void ConfigDialog::on_toolButtonStore_clicked() { QString store = selectFolder(); - if (!store.isEmpty()) { // TODO call check + if (!store.isEmpty()) // TODO call check ui->storePath->setText(store); - } } /** @@ -448,7 +456,7 @@ void ConfigDialog::genKey(QString batch, QDialog *dialog) */ void ConfigDialog::setProfiles(QHash profiles, QString profile) { - //qDebug() << profiles; + // qDebug() << profiles; if (profiles.contains("")) { profiles.remove(""); // remove weird "" key value pairs @@ -462,10 +470,9 @@ void ConfigDialog::setProfiles(QHash profiles, QString profile if (!i.value().isEmpty() && !i.key().isEmpty()) { ui->profileTable->setItem(n, 0, new QTableWidgetItem(i.key())); ui->profileTable->setItem(n, 1, new QTableWidgetItem(i.value())); - //qDebug() << "naam:" + i.key(); - if (i.key() == profile) { + // qDebug() << "naam:" + i.key(); + if (i.key() == profile) ui->profileTable->selectRow(n); - } } n++; } @@ -480,9 +487,9 @@ QHash ConfigDialog::getProfiles() QHash profiles; // Check? for (int i = 0; i < ui->profileTable->rowCount(); i++) { - QTableWidgetItem* pathItem = ui->profileTable->item(i, 1); + QTableWidgetItem *pathItem = ui->profileTable->item(i, 1); if (0 != pathItem) { - QTableWidgetItem* item = ui->profileTable->item(i, 0); + QTableWidgetItem *item = ui->profileTable->item(i, 0); if (item == 0) { qDebug() << "empty name, shoud fix in frontend"; continue; @@ -511,26 +518,24 @@ void ConfigDialog::on_addButton_clicked() */ void ConfigDialog::on_deleteButton_clicked() { - QSet selectedRows; //we use a set to prevent doubles - QList itemList = ui->profileTable->selectedItems(); + QSet selectedRows; // we use a set to prevent doubles + QList itemList = ui->profileTable->selectedItems(); if (itemList.count() == 0) { QMessageBox::warning(this, tr("No profile selected"), - tr("No profile selected to delete")); + tr("No profile selected to delete")); return; } - QTableWidgetItem * item; - foreach(item, itemList) - selectedRows.insert(item->row()); - //get a list, and sort it big to small + QTableWidgetItem *item; + foreach (item, itemList) + selectedRows.insert(item->row()); + // get a list, and sort it big to small QList rows = selectedRows.toList(); qSort(rows.begin(), rows.end()); - //now actually do the removing: - foreach(int row, rows) { - ui->profileTable->removeRow(row); - } - if (ui->profileTable->rowCount() < 1) { + // now actually do the removing: + foreach (int row, rows) + ui->profileTable->removeRow(row); + if (ui->profileTable->rowCount() < 1) ui->deleteButton->setEnabled(false); - } } void ConfigDialog::criticalMessage(const QString &title, const QString &text) @@ -543,14 +548,15 @@ void ConfigDialog::criticalMessage(const QString &title, const QString &text) */ void ConfigDialog::wizard() { - //mainWindow->checkConfig(); + // mainWindow->checkConfig(); bool clean = false; QString gpg = ui->gpgPath->text(); - //QString gpg = mainWindow->getGpgExecutable(); - if(!QFile(gpg).exists()){ + // QString gpg = mainWindow->getGpgExecutable(); + if (!QFile(gpg).exists()) { criticalMessage(tr("GnuPG not found"), - tr("Please install GnuPG on your system.
Install gpg using your favorite package manager
or download it from GnuPG.org")); + tr( + "Please install GnuPG on your system.
Install gpg using your favorite package manager
or download it from GnuPG.org")); clean = true; } @@ -558,9 +564,8 @@ void ConfigDialog::wizard() qDebug() << names; if (QFile(gpg).exists() && names.empty()) { KeygenDialog d(this); - if (!d.exec()) { + if (!d.exec()) return; - } } QString passStore = ui->storePath->text(); @@ -568,27 +573,29 @@ void ConfigDialog::wizard() if (!QFile(passStore).exists()) { // TODO pass version? if (QMessageBox::question(this, tr("Create password-store?"), - tr("Would you like to create a password-store at %1?").arg(passStore), - QMessageBox::Yes | QMessageBox::No) == QMessageBox::Yes) { - QDir().mkdir(passStore); + tr("Would you like to create a password-store at %1?").arg( + passStore), + QMessageBox::Yes | QMessageBox::No) == QMessageBox::Yes) { + QDir().mkdir(passStore); #ifdef Q_OS_WIN - SetFileAttributes(passStore.toStdWString().c_str(), FILE_ATTRIBUTE_HIDDEN); + SetFileAttributes(passStore.toStdWString().c_str(), FILE_ATTRIBUTE_HIDDEN); #endif - if(useGit()) { - mainWindow->executePassGitInit(); - } - mainWindow->userDialog(passStore); + if (useGit()) + mainWindow->executePassGitInit(); + mainWindow->userDialog(passStore); } } - if(!QFile(passStore + ".gpg-id").exists()){ + if (!QFile(passStore + ".gpg-id").exists()) { qDebug() << ".gpg-id file does not exist"; if (!clean) { criticalMessage(tr("Password store not initialised"), - tr("The folder %1 doesn't seem to be a password store or is not yet initialised.").arg(passStore)); + tr( + "The folder %1 doesn't seem to be a password store or is not yet initialised.").arg( + passStore)); } - while(!QFile(passStore).exists()) { + while (!QFile(passStore).exists()) { on_toolButtonStore_clicked(); // allow user to cancel if (passStore == ui->storePath->text()) @@ -608,7 +615,8 @@ void ConfigDialog::wizard() * @brief ConfigDialog::useTrayIcon * @return */ -bool ConfigDialog::useTrayIcon() { +bool ConfigDialog::useTrayIcon() +{ return ui->checkBoxUseTrayIcon->isChecked(); } @@ -616,7 +624,8 @@ bool ConfigDialog::useTrayIcon() { * @brief ConfigDialog::hideOnClose * @return */ -bool ConfigDialog::hideOnClose() { +bool ConfigDialog::hideOnClose() +{ return ui->checkBoxHideOnClose->isEnabled() && ui->checkBoxHideOnClose->isChecked(); } @@ -624,7 +633,8 @@ bool ConfigDialog::hideOnClose() { * @brief ConfigDialog::useTrayIcon * @param useSystray */ -void ConfigDialog::useTrayIcon(bool useSystray) { +void ConfigDialog::useTrayIcon(bool useSystray) +{ ui->checkBoxUseTrayIcon->setChecked(useSystray); ui->checkBoxHideOnClose->setEnabled(useSystray); ui->checkBoxStartMinimized->setEnabled(useSystray); @@ -638,14 +648,16 @@ void ConfigDialog::useTrayIcon(bool useSystray) { * @brief ConfigDialog::hideOnClose * @param hideOnClose */ -void ConfigDialog::hideOnClose(bool hideOnClose) { +void ConfigDialog::hideOnClose(bool hideOnClose) +{ ui->checkBoxHideOnClose->setChecked(hideOnClose); } /** * @brief ConfigDialog::on_checkBoxUseTrayIcon_clicked */ -void ConfigDialog::on_checkBoxUseTrayIcon_clicked() { +void ConfigDialog::on_checkBoxUseTrayIcon_clicked() +{ if (ui->checkBoxUseTrayIcon->isChecked()) { ui->checkBoxHideOnClose->setEnabled(true); ui->checkBoxStartMinimized->setEnabled(true); @@ -659,7 +671,8 @@ void ConfigDialog::on_checkBoxUseTrayIcon_clicked() { * @brief ConfigDialog::closeEvent * @param event */ -void ConfigDialog::closeEvent(QCloseEvent *event) { +void ConfigDialog::closeEvent(QCloseEvent *event) +{ // TODO save window size or something? event->accept(); } @@ -712,7 +725,8 @@ void ConfigDialog::on_toolButtonPwgen_clicked() * @brief ConfigDialog::getPwgenPath * @return */ -QString ConfigDialog::getPwgenPath() { +QString ConfigDialog::getPwgenPath() +{ return ui->pwgenPath->text(); } @@ -744,10 +758,10 @@ void ConfigDialog::on_checkBoxUsePwgen_clicked() * @brief ConfigDialog::usePwgen * @param usePwgen */ -void ConfigDialog::usePwgen(bool usePwgen) { - if (ui->pwgenPath->text().isEmpty()) { +void ConfigDialog::usePwgen(bool usePwgen) +{ + if (ui->pwgenPath->text().isEmpty()) usePwgen = false; - } ui->checkBoxUsePwgen->setChecked(usePwgen); on_checkBoxUsePwgen_clicked(); } @@ -756,7 +770,8 @@ void ConfigDialog::usePwgen(bool usePwgen) { * @brief ConfigDialog::useSymbols * @param useSymbols */ -void ConfigDialog::useSymbols(bool useSymbols) { +void ConfigDialog::useSymbols(bool useSymbols) +{ ui->checkBoxUseSymbols->setChecked(useSymbols); } @@ -764,11 +779,13 @@ void ConfigDialog::useSymbols(bool useSymbols) { * @brief ConfigDialog::setPasswordLength * @param pwLen */ -void ConfigDialog::setPasswordLength(int pwLen) { +void ConfigDialog::setPasswordLength(int pwLen) +{ ui->spinBoxPasswordLength->setValue(pwLen); } -void ConfigDialog::setPasswordChars(QString pwChars) { +void ConfigDialog::setPasswordChars(QString pwChars) +{ ui->lineEditPasswordChars->setText(pwChars); } @@ -776,7 +793,8 @@ void ConfigDialog::setPasswordChars(QString pwChars) { * @brief ConfigDialog::usePwgen * @return */ -bool ConfigDialog::usePwgen() { +bool ConfigDialog::usePwgen() +{ return ui->checkBoxUsePwgen->isChecked(); } @@ -784,7 +802,8 @@ bool ConfigDialog::usePwgen() { * @brief ConfigDialog::useSymbols * @return */ -bool ConfigDialog::useSymbols() { +bool ConfigDialog::useSymbols() +{ return ui->checkBoxUseSymbols->isChecked(); } @@ -792,7 +811,8 @@ bool ConfigDialog::useSymbols() { * @brief ConfigDialog::getPasswordLength * @return */ -int ConfigDialog::getPasswordLength() { +int ConfigDialog::getPasswordLength() +{ return ui->spinBoxPasswordLength->value(); } @@ -800,7 +820,8 @@ int ConfigDialog::getPasswordLength() { * @brief ConfigDialog::getPasswordChars * @return */ -QString ConfigDialog::getPasswordChars() { +QString ConfigDialog::getPasswordChars() +{ return ui->lineEditPasswordChars->text(); } @@ -808,7 +829,8 @@ QString ConfigDialog::getPasswordChars() { * @brief ConfigDialog::startMinimized * @return */ -bool ConfigDialog::startMinimized() { +bool ConfigDialog::startMinimized() +{ return ui->checkBoxStartMinimized->isChecked(); } @@ -816,14 +838,16 @@ bool ConfigDialog::startMinimized() { * @brief ConfigDialog::startMinimized * @param startMinimized */ -void ConfigDialog::startMinimized(bool startMinimized) { +void ConfigDialog::startMinimized(bool startMinimized) +{ ui->checkBoxStartMinimized->setChecked(startMinimized); } /** * @brief ConfigDialog::on_checkBoxUseTemplate_clicked */ -void ConfigDialog::on_checkBoxUseTemplate_clicked() { +void ConfigDialog::on_checkBoxUseTemplate_clicked() +{ ui->plainTextEditTemplate->setEnabled(ui->checkBoxUseTemplate->isChecked()); ui->checkBoxTemplateAllFields->setEnabled(ui->checkBoxUseTemplate->isChecked()); } @@ -832,16 +856,18 @@ void ConfigDialog::on_checkBoxUseTemplate_clicked() { * @brief ConfigDialog::useTemplate * @param useTemplate */ -void ConfigDialog::useTemplate(bool useTemplate) { - ui->checkBoxUseTemplate->setChecked(useTemplate); - on_checkBoxUseTemplate_clicked(); +void ConfigDialog::useTemplate(bool useTemplate) +{ + ui->checkBoxUseTemplate->setChecked(useTemplate); + on_checkBoxUseTemplate_clicked(); } /** * @brief ConfigDialog::useTemplate * @return */ -bool ConfigDialog::useTemplate() { +bool ConfigDialog::useTemplate() +{ return ui->checkBoxUseTemplate->isChecked(); } @@ -849,7 +875,8 @@ bool ConfigDialog::useTemplate() { * @brief ConfigDialog::setTemplate * @param passTemplate */ -void ConfigDialog::setTemplate(QString passTemplate) { +void ConfigDialog::setTemplate(QString passTemplate) +{ ui->plainTextEditTemplate->setPlainText(passTemplate); } @@ -857,7 +884,8 @@ void ConfigDialog::setTemplate(QString passTemplate) { * @brief ConfigDialog::getTemplate * @return */ -QString ConfigDialog::getTemplate() { +QString ConfigDialog::getTemplate() +{ return ui->plainTextEditTemplate->toPlainText(); } @@ -865,7 +893,8 @@ QString ConfigDialog::getTemplate() { * @brief ConfigDialog::autoPull * @param autoPull */ -void ConfigDialog::autoPull(bool autoPull) { +void ConfigDialog::autoPull(bool autoPull) +{ ui->checkBoxAutoPull->setChecked(autoPull); } @@ -873,7 +902,8 @@ void ConfigDialog::autoPull(bool autoPull) { * @brief ConfigDialog::autoPush * @param autoPush */ -void ConfigDialog::autoPush(bool autoPush) { +void ConfigDialog::autoPush(bool autoPush) +{ ui->checkBoxAutoPush->setChecked(autoPush); } @@ -881,7 +911,8 @@ void ConfigDialog::autoPush(bool autoPush) { * @brief ConfigDialog::autoPull * @return */ -bool ConfigDialog::autoPull() { +bool ConfigDialog::autoPull() +{ return ui->checkBoxAutoPull->isChecked(); } @@ -889,7 +920,8 @@ bool ConfigDialog::autoPull() { * @brief ConfigDialog::autoPush * @return */ -bool ConfigDialog::autoPush() { +bool ConfigDialog::autoPush() +{ return ui->checkBoxAutoPush->isChecked(); } @@ -897,7 +929,8 @@ bool ConfigDialog::autoPush() { * @brief ConfigDialog::templateAllFields * @return */ -bool ConfigDialog::templateAllFields() { +bool ConfigDialog::templateAllFields() +{ return ui->checkBoxTemplateAllFields->isChecked(); } @@ -905,6 +938,7 @@ bool ConfigDialog::templateAllFields() { * @brief ConfigDialog::templateAllFields * @param templateAll */ -void ConfigDialog::templateAllFields(bool templateAll) { +void ConfigDialog::templateAllFields(bool templateAll) +{ ui->checkBoxTemplateAllFields->setChecked(templateAll); } diff --git a/configdialog.h b/configdialog.h index d18cd0ab5..7cc2fa123 100644 --- a/configdialog.h +++ b/configdialog.h @@ -8,7 +8,6 @@ #include namespace Ui { - struct UserInfo; class ConfigDialog; @@ -39,7 +38,7 @@ class ConfigDialog : public QDialog QString getGitPath(); QString getGpgPath(); QString getStorePath(); - QHash getProfiles(); + QHash getProfiles(); bool usePass(); MainWindow::clipBoardType useClipboard(); bool useAutoclear(); @@ -106,8 +105,8 @@ private slots: void setGroupBoxState(); QString selectExecutable(); QString selectFolder(); - // QMessageBox::critical with hack to avoid crashes with - // Qt 5.4.1 when QApplication::exec was not yet called +// QMessageBox::critical with hack to avoid crashes with +// Qt 5.4.1 when QApplication::exec was not yet called void criticalMessage(const QString &title, const QString &text); MainWindow *mainWindow; }; diff --git a/keygendialog.cpp b/keygendialog.cpp index 64d31a610..64ae1ca81 100644 --- a/keygendialog.cpp +++ b/keygendialog.cpp @@ -22,11 +22,10 @@ void KeygenDialog::on_passphrase1_textChanged(const QString &arg1) if (ui->passphrase1->text() == ui->passphrase2->text()) { ui->buttonBox->setEnabled(true); replace("Passphrase", arg1); - if (arg1 == "") { + if (arg1 == "") no_protection(true); - } else { + else no_protection(false); - } } else { ui->buttonBox->setEnabled(false); } @@ -66,13 +65,12 @@ void KeygenDialog::on_name_textChanged(const QString &arg1) void KeygenDialog::replace(QString key, QString value) { QStringList clear; - QString expert = ui->plainTextEdit->toPlainText(); - QStringList lines = expert.split(QRegExp("[\r\n]"),QString::SkipEmptyParts); + QString expert = ui->plainTextEdit->toPlainText(); + QStringList lines = expert.split(QRegExp("[\r\n]"), QString::SkipEmptyParts); foreach (QString line, lines) { line.replace(QRegExp(key+":.*"), key + ": " + value); - if (key == "Passphrase") { + if (key == "Passphrase") line.replace("%no-protection", "Passphrase: " + value); - } clear.append(line); } ui->plainTextEdit->setPlainText(clear.join("\n")); @@ -82,25 +80,22 @@ void KeygenDialog::replace(QString key, QString value) * @brief KeygenDialog::no_protection * @param enable */\ -void KeygenDialog::no_protection(bool enable) + void KeygenDialog::no_protection(bool enable) { QStringList clear; - QString expert = ui->plainTextEdit->toPlainText(); - QStringList lines = expert.split(QRegExp("[\r\n]"),QString::SkipEmptyParts); + QString expert = ui->plainTextEdit->toPlainText(); + QStringList lines = expert.split(QRegExp("[\r\n]"), QString::SkipEmptyParts); foreach (QString line, lines) { bool remove = false; if (!enable) { - if (line.indexOf("%no-protection") == 0) { + if (line.indexOf("%no-protection") == 0) remove = true; - } } else { - if (line.indexOf("Passphrase") == 0) { + if (line.indexOf("Passphrase") == 0) line = "%no-protection"; - } } - if (!remove) { + if (!remove) clear.append(line); - } } ui->plainTextEdit->setPlainText(clear.join("\n")); } @@ -111,37 +106,36 @@ void KeygenDialog::no_protection(bool enable) */ void KeygenDialog::done(int r) { - if(QDialog::Accepted == r) // ok was pressed - { + if (QDialog::Accepted == r) { // ok was pressed ui->widget->setEnabled(false); ui->buttonBox->setEnabled(false); ui->checkBox->setEnabled(false); ui->plainTextEdit->setEnabled(false); - QProgressIndicator* pi = new QProgressIndicator(); + QProgressIndicator *pi = new QProgressIndicator(); pi->startAnimation(); pi->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding); ui->frame->hide(); - ui->label->setText(QString("This operation can take some minutes.
") + - "We need to generate a lot of random bytes. It is a good idea to perform " - "some other action (type on the keyboard, move the mouse, utilize the " - "disks) during the prime generation; this gives the random number " - "generator a better chance to gain enough entropy."); + ui->label->setText(QString( + "This operation can take some minutes.
") + +"We need to generate a lot of random bytes. It is a good idea to perform " + "some other action (type on the keyboard, move the mouse, utilize the " + "disks) during the prime generation; this gives the random number " + "generator a better chance to gain enough entropy."); this->layout()->addWidget(pi); this->show(); dialog->genKey(ui->plainTextEdit->toPlainText(), this); - } - else // cancel, close or exc was pressed - { + } else { // cancel, close or exc was pressed QDialog::done(r); return; } } -void KeygenDialog::closeEvent(QCloseEvent *event) { +void KeygenDialog::closeEvent(QCloseEvent *event) +{ // TODO save window size or somethign event->accept(); } diff --git a/keygendialog.h b/keygendialog.h index 01f4a39a2..4058108ee 100644 --- a/keygendialog.h +++ b/keygendialog.h @@ -33,7 +33,6 @@ private slots: void done(int r); void no_protection(bool enable); ConfigDialog *dialog; - }; #endif // KEYGENDIALOG_H diff --git a/main.cpp b/main.cpp index c645fd100..2fc6f3bca 100644 --- a/main.cpp +++ b/main.cpp @@ -7,9 +7,8 @@ int main(int argc, char *argv[]) // check for stupid apple psid or whatever flag QString text = ""; for (int i = 1; i < argc; ++i) { - if (i > 1) { + if (i > 1) text += " "; - } text += argv[i]; } #if SINGLE_APP @@ -18,9 +17,8 @@ int main(int argc, char *argv[]) name = qgetenv("USERNAME"); SingleApplication app(argc, argv, name + "QtPass"); if (app.isRunning()) { - if (text.length() > 0) { + if (text.length() > 0) app.sendMessage(text); - } return 0; } #else @@ -40,7 +38,7 @@ int main(int argc, char *argv[]) // locale = "ar_MA"; translator.load(QString(":localization/localization_") + locale + QString(".qm")); app.installTranslator(&translator); - app.setLayoutDirection(QObject::tr("LTR")=="RTL" ? Qt::RightToLeft : Qt::LeftToRight); + app.setLayoutDirection(QObject::tr("LTR") == "RTL" ? Qt::RightToLeft : Qt::LeftToRight); MainWindow w; diff --git a/mainwindow.cpp b/mainwindow.cpp index d27744313..7d816c34c 100644 --- a/mainwindow.cpp +++ b/mainwindow.cpp @@ -34,9 +34,11 @@ MainWindow::MainWindow(QWidget *parent) : keygen(NULL), tray(NULL) { -// connect(process.data(), SIGNAL(readyReadStandardOutput()), this, SLOT(readyRead())); - connect(process.data(), SIGNAL(error(QProcess::ProcessError)), this, SLOT(processError(QProcess::ProcessError))); - connect(process.data(), SIGNAL(finished(int, QProcess::ExitStatus)), this, SLOT(processFinished(int, QProcess::ExitStatus))); +// connect(process.data(), SIGNAL(readyReadStandardOutput()), this, SLOT(readyRead())); + connect(process.data(), SIGNAL(error(QProcess::ProcessError)), this, + SLOT(processError(QProcess::ProcessError))); + connect(process.data(), SIGNAL(finished(int, QProcess::ExitStatus)), this, + SLOT(processFinished(int, QProcess::ExitStatus))); ui->setupUi(this); enableUiElements(true); wrapperRunning = false; @@ -55,7 +57,8 @@ MainWindow::MainWindow(QWidget *parent) : QTimer::singleShot(10, this, SLOT(focusInput())); } -void MainWindow::focusInput() { +void MainWindow::focusInput() +{ ui->lineEdit->selectAll(); ui->lineEdit->setFocus(); } @@ -75,22 +78,25 @@ MainWindow::~MainWindow() #endif } -QSettings &MainWindow::getSettings() { +QSettings &MainWindow::getSettings() +{ if (!settings) { - QString portable_ini = QCoreApplication::applicationDirPath() + QDir::separator() + "qtpass.ini"; - //qDebug() << "Settings file: " + portable_ini; + QString portable_ini = QCoreApplication::applicationDirPath() + QDir::separator() + + "qtpass.ini"; + // qDebug() << "Settings file: " + portable_ini; if (QFile(portable_ini).exists()) { - // qDebug() << "Settings file exists, loading it in"; + // qDebug() << "Settings file exists, loading it in"; settings.reset(new QSettings(portable_ini, QSettings::IniFormat)); } else { - //qDebug() << "Settings file does not exist, use defaults"; + // qDebug() << "Settings file does not exist, use defaults"; settings.reset(new QSettings("IJHack", "QtPass")); } } return *settings; } -void MainWindow::mountWebDav() { +void MainWindow::mountWebDav() +{ #ifdef Q_OS_WIN char dst[20] = {0}; NETRESOURCEA netres; @@ -99,26 +105,32 @@ void MainWindow::mountWebDav() { netres.lpLocalName = 0; netres.lpRemoteName = webDavUrl.toUtf8().data(); DWORD size = sizeof(dst); - DWORD r = WNetUseConnectionA(reinterpret_cast(effectiveWinId()), &netres, webDavPassword.toUtf8().constData(), - webDavUser.toUtf8().constData(), CONNECT_TEMPORARY | CONNECT_INTERACTIVE | CONNECT_REDIRECT, - dst, &size, 0); + DWORD r = WNetUseConnectionA( + reinterpret_cast(effectiveWinId()), &netres, webDavPassword.toUtf8().constData(), + webDavUser.toUtf8().constData(), CONNECT_TEMPORARY | CONNECT_INTERACTIVE | CONNECT_REDIRECT, + dst, &size, 0); if (r == NO_ERROR) { passStore = dst; } else { char message[256] = {0}; FormatMessageA(FORMAT_MESSAGE_FROM_SYSTEM, 0, r, 0, message, sizeof(message), 0); ui->textBrowser->setTextColor(Qt::red); - ui->textBrowser->setText(tr("Failed to connect WebDAV:\n") + message + " (0x" + QString::number(r, 16) + ")"); + ui->textBrowser->setText(tr( + "Failed to connect WebDAV:\n") + message + " (0x" + + QString::number(r, 16) + ")"); } #else - fusedav.start("fusedav -o nonempty -u \"" + webDavUser + "\" " + webDavUrl + " \"" + passStore + '"'); + fusedav.start( + "fusedav -o nonempty -u \"" + webDavUser + "\" " + webDavUrl + " \"" + passStore + '"'); fusedav.waitForStarted(); if (fusedav.state() == QProcess::Running) { QString pwd = webDavPassword; bool ok = true; if (pwd.isEmpty()) { pwd = QInputDialog::getText(this, tr("QtPass WebDAV password"), - tr("Enter password to connect to WebDAV:"), QLineEdit::Password, "", &ok); + tr( + "Enter password to connect to WebDAV:"), QLineEdit::Password, "", + &ok); } if (ok && !pwd.isEmpty()) { fusedav.write(pwd.toUtf8() + '\n'); @@ -130,12 +142,10 @@ void MainWindow::mountWebDav() { } QString error = fusedav.readAllStandardError(); int prompt = error.indexOf("Password:"); - if (prompt >= 0) { + if (prompt >= 0) error.remove(0, prompt + 10); - } - if (fusedav.state() != QProcess::Running) { + if (fusedav.state() != QProcess::Running) error = tr("fusedav exited unexpectedly\n") + error; - } if (error.size() > 0) { ui->textBrowser->setTextColor(Qt::red); ui->textBrowser->setText(tr("Failed to start fusedav to connect WebDAV:\n") + error); @@ -146,27 +156,27 @@ void MainWindow::mountWebDav() { /** * @brief MainWindow::checkConfig */ -bool MainWindow::checkConfig() { - +bool MainWindow::checkConfig() +{ QSettings &settings(getSettings()); QString version = settings.value("version").toString(); if (freshStart) { - settings.beginGroup( "mainwindow" ); - restoreGeometry(settings.value( "geometry", saveGeometry() ).toByteArray()); - restoreState(settings.value( "savestate", saveState() ).toByteArray()); - move(settings.value( "pos", pos() ).toPoint()); - resize(settings.value( "size", size() ).toSize()); + settings.beginGroup("mainwindow"); + restoreGeometry(settings.value("geometry", saveGeometry()).toByteArray()); + restoreState(settings.value("savestate", saveState()).toByteArray()); + move(settings.value("pos", pos()).toPoint()); + resize(settings.value("size", size()).toSize()); QList splitter = ui->splitter->sizes(); int left = settings.value("splitterLeft", splitter[0]).toInt(); - int right= settings.value("splitterRight", splitter[1]).toInt(); + int right = settings.value("splitterRight", splitter[1]).toInt(); if (left > 0 || right > 0) { splitter[0] = left; splitter[1] = right; ui->splitter->setSizes(splitter); } - if ( settings.value( "maximized", isMaximized() ).toBool() ) + if (settings.value("maximized", isMaximized()).toBool()) showMaximized(); settings.endGroup(); } @@ -174,12 +184,11 @@ bool MainWindow::checkConfig() { usePass = (settings.value("usePass") == "true"); useClipboard = CLIPBOARD_NEVER; - if (settings.value("useClipboard") == "true" || - settings.value("useClipboard") == "1") { + if (settings.value("useClipboard") == "true" + || settings.value("useClipboard") == "1") useClipboard = CLIPBOARD_ALWAYS; - } else if (settings.value("useClipboard") == "2") { + else if (settings.value("useClipboard") == "2") useClipboard = CLIPBOARD_ON_DEMAND; - } useAutoclear = (settings.value("useAutoclear") == "true"); autoclearSeconds = settings.value("autoclearSeconds").toInt(); useAutoclearPanel = (settings.value("useAutoclearPanel") == "true"); @@ -196,24 +205,20 @@ bool MainWindow::checkConfig() { passStore = Util::normalizeFolderPath(passStore); passExecutable = settings.value("passExecutable").toString(); - if (passExecutable.isEmpty()) { + if (passExecutable.isEmpty()) passExecutable = Util::findBinaryInPath("pass"); - } gitExecutable = settings.value("gitExecutable").toString(); - if (gitExecutable.isEmpty()) { + if (gitExecutable.isEmpty()) gitExecutable = Util::findBinaryInPath("git"); - } gpgExecutable = settings.value("gpgExecutable").toString(); - if (gpgExecutable.isEmpty()) { + if (gpgExecutable.isEmpty()) gpgExecutable = Util::findBinaryInPath("gpg2"); - } pwgenExecutable = settings.value("pwgenExecutable").toString(); - if (pwgenExecutable.isEmpty()) { + if (pwgenExecutable.isEmpty()) pwgenExecutable = Util::findBinaryInPath("pwgen"); - } gpgHome = settings.value("gpgHome").toString(); @@ -225,9 +230,8 @@ bool MainWindow::checkConfig() { profile = settings.value("profile").toString(); settings.beginGroup("profiles"); QStringList keys = settings.childKeys(); - foreach (QString key, keys) { - profiles[key] = settings.value(key).toString(); - } + foreach (QString key, keys) + profiles[key] = settings.value(key).toString(); settings.endGroup(); useGit = (settings.value("useGit") == "true"); @@ -257,46 +261,44 @@ bool MainWindow::checkConfig() { useTemplate = settings.value("useTemplate").toBool(); templateAllFields = settings.value("templateAllFields").toBool(); - //qDebug() << version; + // qDebug() << version; // Config updates if (version.isEmpty()) { qDebug() << "assuming fresh install"; - if (autoclearSeconds < 5) { + if (autoclearSeconds < 5) autoclearSeconds = 10; - } - if (autoclearPanelSeconds < 5) { + if (autoclearPanelSeconds < 5) autoclearPanelSeconds = 10; - } passwordLength = 16; - passwordChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890~!@#$%^&*()_-+={}[]|:;<>,.?"; - if (!pwgenExecutable.isEmpty()) { + passwordChars + = + "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890~!@#$%^&*()_-+={}[]|:;<>,.?"; + if (!pwgenExecutable.isEmpty()) usePwgen = true; - } else { + else usePwgen = false; - } passTemplate = "login\nurl"; } else { -// QStringList ver = version.split("."); -// qDebug() << ver; -// if (ver[0] == "0" && ver[1] == "8") { -// // upgrade to 0.9 -// } - if (passwordChars.isEmpty()) { - passwordChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890~!@#$%^&*()_-+={}[]|:;<>,.?"; - } - if (passTemplate.isEmpty()) { +// QStringList ver = version.split("."); +// qDebug() << ver; +// if (ver[0] == "0" && ver[1] == "8") { +//// upgrade to 0.9 +// } + if (passwordChars.isEmpty()) + passwordChars + = + "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890~!@#$%^&*()_-+={}[]|:;<>,.?"; + if (passTemplate.isEmpty()) passTemplate = "login\nurl"; - } } settings.setValue("version", VERSION); if (Util::checkConfig(passStore, passExecutable, gpgExecutable)) { config(); - if (freshStart && Util::checkConfig(passStore, passExecutable, gpgExecutable)) { + if (freshStart && Util::checkConfig(passStore, passExecutable, gpgExecutable)) return false; - } } freshStart = false; @@ -304,9 +306,8 @@ bool MainWindow::checkConfig() { // TODO: this needs to be before we try to access the store, // but it would be better to do it after the Window is shown, // as the long delay it can cause is irritating otherwise. - if (useWebDav) { + if (useWebDav) mountWebDav(); - } model.setNameFilters(QStringList() << "*.gpg"); model.setNameFilterDisables(false); @@ -326,13 +327,13 @@ bool MainWindow::checkConfig() { ui->treeView->setIndentation(15); ui->treeView->setHorizontalScrollBarPolicy(Qt::ScrollBarAsNeeded); ui->treeView->setContextMenuPolicy(Qt::CustomContextMenu); - connect(ui->treeView, SIGNAL(customContextMenuRequested(const QPoint&)), - this, SLOT(showContextMenu(const QPoint&))); + connect(ui->treeView, SIGNAL(customContextMenuRequested(const QPoint &)), + this, SLOT(showContextMenu(const QPoint &))); ui->textBrowser->setOpenExternalLinks(true); ui->textBrowser->setContextMenuPolicy(Qt::CustomContextMenu); - connect(ui->textBrowser, SIGNAL(customContextMenuRequested(const QPoint&)), - this, SLOT(showBrowserContextMenu(const QPoint&))); + connect(ui->textBrowser, SIGNAL(customContextMenuRequested(const QPoint &)), + this, SLOT(showBrowserContextMenu(const QPoint &))); updateProfileBox(); @@ -344,20 +345,18 @@ bool MainWindow::checkConfig() { } #ifdef __APPLE__ // If it exists, add the gpgtools to PATH - if (QFile("/usr/local/MacGPG2/bin").exists()) { + if (QFile("/usr/local/MacGPG2/bin").exists()) env.replaceInStrings("PATH=", "PATH=/usr/local/MacGPG2/bin:"); - } // Add missing /usr/local/bin - if (env.filter("/usr/local/bin").isEmpty()) { + if (env.filter("/usr/local/bin").isEmpty()) env.replaceInStrings("PATH=", "PATH=/usr/local/bin:"); - } + #endif - //QMessageBox::information(this, "env", env.join("\n")); + // QMessageBox::information(this, "env", env.join("\n")); updateEnv(); - if (!useGit || (gitExecutable.isEmpty() && passExecutable.isEmpty())) - { + if (!useGit || (gitExecutable.isEmpty() && passExecutable.isEmpty())) { ui->pushButton->hide(); ui->updateButton->hide(); } else { @@ -372,7 +371,8 @@ bool MainWindow::checkConfig() { /** * @brief MainWindow::config */ -void MainWindow::config() { +void MainWindow::config() +{ QScopedPointer d(new ConfigDialog(this)); d->setModal(true); @@ -407,9 +407,8 @@ void MainWindow::config() { d->templateAllFields(templateAllFields); d->autoPull(autoPull); d->autoPush(autoPush); - if (startupPhase) { + if (startupPhase) d->wizard(); // does shit - } if (d->exec()) { if (d->result() == QDialog::Accepted) { passExecutable = d->getPassPath(); @@ -450,15 +449,15 @@ void MainWindow::config() { settings.setValue("passStore", passStore); settings.setValue("usePass", usePass ? "true" : "false"); switch (useClipboard) { - case CLIPBOARD_ALWAYS: - settings.setValue("useClipboard", "true"); - break; - case CLIPBOARD_ON_DEMAND: - settings.setValue("useClipboard", "2"); - break; - default: - settings.setValue("useClipboard", "false"); - break; + case CLIPBOARD_ALWAYS: + settings.setValue("useClipboard", "true"); + break; + case CLIPBOARD_ON_DEMAND: + settings.setValue("useClipboard", "2"); + break; + default: + settings.setValue("useClipboard", "false"); + break; } settings.setValue("useAutoclear", useAutoclear ? "true" : "false"); settings.setValue("autoclearSeconds", autoclearSeconds); @@ -489,10 +488,9 @@ void MainWindow::config() { QHashIterator i(profiles); while (i.hasNext()) { i.next(); - //qDebug() << i.key() + "|" + i.value(); - if (i.key() == profile) { + // qDebug() << i.key() + "|" + i.value(); + if (i.key() == profile) profileExists = true; - } settings.setValue(i.key(), i.value()); } if (!profileExists) { @@ -506,23 +504,20 @@ void MainWindow::config() { updateProfileBox(); ui->treeView->setRootIndex(proxyModel.mapFromSource(model.setRootPath(passStore))); - if (freshStart && Util::checkConfig(passStore, passExecutable, gpgExecutable)) { + if (freshStart && Util::checkConfig(passStore, passExecutable, gpgExecutable)) config(); - } updateEnv(); - if (!useGit || (gitExecutable.isEmpty() && passExecutable.isEmpty())) - { + if (!useGit || (gitExecutable.isEmpty() && passExecutable.isEmpty())) { ui->pushButton->hide(); ui->updateButton->hide(); } else { ui->pushButton->show(); ui->updateButton->show(); } - if (useTrayIcon && tray == NULL) { + if (useTrayIcon && tray == NULL) initTrayIcon(); - } else if (!useTrayIcon && tray != NULL) { + else if (!useTrayIcon && tray != NULL) destroyTrayIcon(); - } } freshStart = false; } @@ -535,11 +530,10 @@ void MainWindow::on_updateButton_clicked() { ui->statusBar->showMessage(tr("Updating password-store"), 2000); currentAction = GIT; - if (usePass) { + if (usePass) executePass("git pull"); - } else { + else executeWrapper(gitExecutable, "pull"); - } } /** @@ -549,19 +543,17 @@ void MainWindow::on_pushButton_clicked() { ui->statusBar->showMessage(tr("Updating password-store"), 2000); currentAction = GIT; - if (usePass) { + if (usePass) executePass("git push"); - } else { + else executeWrapper(gitExecutable, "push"); - } } QString MainWindow::getDir(const QModelIndex &index, bool forPass) { QString abspath = QDir(passStore).absolutePath() + '/'; - if (!index.isValid()) { + if (!index.isValid()) return forPass ? "" : abspath; - } QFileInfo info = model.fileInfo(proxyModel.mapToSource(index)); QString filePath = (info.isFile() ? info.absolutePath() : info.absoluteFilePath()) + '/'; if (forPass) { @@ -573,9 +565,8 @@ QString MainWindow::getDir(const QModelIndex &index, bool forPass) QString MainWindow::getFile(const QModelIndex &index, bool forPass) { - if (!index.isValid() || !model.fileInfo(proxyModel.mapToSource(index)).isFile()) { + if (!index.isValid() || !model.fileInfo(proxyModel.mapToSource(index)).isFile()) return QString(); - } QString filePath = model.filePath(proxyModel.mapToSource(index)); if (forPass) { filePath.replace(QRegExp("\\.gpg$"), ""); @@ -594,13 +585,13 @@ void MainWindow::on_treeView_clicked(const QModelIndex &index) lastDecrypt = "Could not decrypt"; setClippedPassword(""); QString file = getFile(index, usePass); - if (!file.isEmpty()){ + if (!file.isEmpty()) { currentAction = GPG; - if (usePass) { + if (usePass) executePass("show \"" + file + '"'); - } else { - executeWrapper(gpgExecutable , "-d --quiet --yes --no-encrypt-to --batch --use-agent \"" + file + '"'); - } + else + executeWrapper(gpgExecutable, + "-d --quiet --yes --no-encrypt-to --batch --use-agent \"" + file + '"'); } else { ui->editButton->setEnabled(false); ui->deleteButton->setEnabled(true); @@ -611,20 +602,21 @@ void MainWindow::on_treeView_clicked(const QModelIndex &index) * @brief MainWindow::executePass * @param args */ -void MainWindow::executePass(QString args, QString input) { +void MainWindow::executePass(QString args, QString input) +{ executeWrapper(passExecutable, args, input); } /** * @brief MainWindow::executePassGitInit */ -void MainWindow::executePassGitInit() { +void MainWindow::executePassGitInit() +{ qDebug() << "Pass git init called"; - if (usePass) { + if (usePass) executePass("git init"); - } else { + else executeWrapper("git", "init \"" + passStore + '"'); - } } /** @@ -632,8 +624,9 @@ void MainWindow::executePassGitInit() { * @param app * @param args */ -void MainWindow::executeWrapper(QString app, QString args, QString input) { - //qDebug() << app + " " + args; +void MainWindow::executeWrapper(QString app, QString args, QString input) +{ + // qDebug() << app + " " + args; // Happens a lot if e.g. git binary is not set. // This will result in bogus "QProcess::FailedToStart" messages, // also hiding legitimate errors from the gpg commands. @@ -666,46 +659,44 @@ void MainWindow::executeWrapper(QString app, QString args, QString input) { autoclearTimer = NULL; } process->start('"' + app + "\" " + args); - if (!input.isEmpty()) { + if (!input.isEmpty()) process->write(input.toUtf8()); - } process->closeWriteChannel(); } /** * @brief MainWindow::readyRead */ -void MainWindow::readyRead(bool finished = false) { - if (currentAction == PWGEN) { +void MainWindow::readyRead(bool finished = false) +{ + if (currentAction == PWGEN) return; - } QString output = ""; QString error = process->readAllStandardError(); if (currentAction != GPG_INTERNAL) { output = process->readAllStandardOutput(); if (finished && currentAction == GPG) { lastDecrypt = output; - QStringList tokens = output.split("\n"); + QStringList tokens = output.split("\n"); if (useClipboard != CLIPBOARD_NEVER && !output.isEmpty()) { setClippedPassword(tokens[0]); if (useClipboard == CLIPBOARD_ALWAYS) copyPasswordToClipboard(); if (useAutoclearPanel) { - QTimer::singleShot(1000*autoclearPanelSeconds, \ - this, \ - SLOT(clearPanel())); + QTimer::singleShot(1000*autoclearPanelSeconds, \ + this, \ + SLOT(clearPanel())); } if (hidePassword && !useTemplate) { tokens[0] = "***" + tr("Password hidden") + "***"; output = tokens.join("\n"); } - if (hideContent) { + if (hideContent) output = "***" + tr("Content hidden") + "***"; - } } if (useTemplate) { - while(ui->formLayout->count() > 0){ + while (ui->formLayout->count() > 0) { QLayoutItem *item = ui->formLayout->takeAt(0); delete item->widget(); delete item; @@ -713,9 +704,8 @@ void MainWindow::readyRead(bool finished = false) { QLineEdit *pass = new QLineEdit(); pass->setText(tokens[0]); tokens.pop_front(); - if (hidePassword) { + if (hidePassword) pass->setEchoMode(QLineEdit::Password); - } pass->setReadOnly(true); ui->formLayout->addRow(pass); @@ -726,9 +716,8 @@ void MainWindow::readyRead(bool finished = false) { QString field = token.left(colon); if (templateAllFields || passTemplate.contains(field)) { QString value = token.right(token.length()-colon-1); - if (!passTemplate.contains(field) && value.startsWith("//")) { - continue; // colon is probably from a url - } + if (!passTemplate.contains(field) && value.startsWith("//")) + continue; // colon is probably from a url QLineEdit *line = new QLineEdit(); line->setObjectName(field); line->setText(value); @@ -739,29 +728,28 @@ void MainWindow::readyRead(bool finished = false) { } } } - if (ui->formLayout->count() == 0) { + if (ui->formLayout->count() == 0) ui->verticalLayoutPassword->setSpacing(0); - } else { + else ui->verticalLayoutPassword->setSpacing(6); - } output = tokens.join("\n"); } else { clearTemplateWidgets(); } if (useAutoclearPanel) { - autoclearPass = output; - autoclearTimer = new QTimer(this); - autoclearTimer->setSingleShot(true); - autoclearTimer->setInterval(1000*autoclearPanelSeconds); - connect(autoclearTimer, SIGNAL(timeout()), this, SLOT(clearPanel())); - autoclearTimer->start(); + autoclearPass = output; + autoclearTimer = new QTimer(this); + autoclearTimer->setSingleShot(true); + autoclearTimer->setInterval(1000*autoclearPanelSeconds); + connect(autoclearTimer, SIGNAL(timeout()), this, SLOT(clearPanel())); + autoclearTimer->start(); } } output.replace(QRegExp("<"), "<"); output.replace(QRegExp(">"), ">"); } else { - //qDebug() << process->readAllStandardOutput(); - //qDebug() << process->readAllStandardError(); + // qDebug() << process->readAllStandardOutput(); + // qDebug() << process->readAllStandardError(); if (finished && 0 != keygen) { qDebug() << "Keygen Done"; keygen->close(); @@ -781,9 +769,8 @@ void MainWindow::readyRead(bool finished = false) { output.replace(QRegExp("((?:https?|ftp)://\\S+)"), "\\1"); output.replace(QRegExp("\n"), "
"); - if (!ui->textBrowser->toPlainText().isEmpty()) { + if (!ui->textBrowser->toPlainText().isEmpty()) output = ui->textBrowser->toHtml() + output; - } ui->textBrowser->setHtml(output); } @@ -806,7 +793,7 @@ void MainWindow::clearClipboard() */ void MainWindow::clearPanel() { - while(ui->formLayout->count() > 0){ + while (ui->formLayout->count() > 0) { QLayoutItem *item = ui->formLayout->takeAt(0); delete item->widget(); delete item; @@ -820,14 +807,14 @@ void MainWindow::clearPanel() * @param exitCode * @param exitStatus */ -void MainWindow::processFinished(int exitCode, QProcess::ExitStatus exitStatus) { +void MainWindow::processFinished(int exitCode, QProcess::ExitStatus exitStatus) +{ wrapperRunning = false; bool error = exitStatus != QProcess::NormalExit || exitCode > 0; readyRead(true); enableUiElements(true); - if (!error && currentAction == EDIT) { + if (!error && currentAction == EDIT) on_treeView_clicked(ui->treeView->currentIndex()); - } if (!execQueue->isEmpty()) { execQueueItem item = execQueue->dequeue(); executeWrapper(item.app, item.args, item.input); @@ -839,7 +826,8 @@ void MainWindow::processFinished(int exitCode, QProcess::ExitStatus exitStatus) * @brief MainWindow::enableUiElements * @param state */ -void MainWindow::enableUiElements(bool state) { +void MainWindow::enableUiElements(bool state) +{ ui->updateButton->setEnabled(state); ui->treeView->setEnabled(state); ui->lineEdit->setEnabled(state); @@ -861,24 +849,24 @@ void MainWindow::processError(QProcess::ProcessError error) { QString errorString; switch (error) { - case QProcess::FailedToStart: - errorString = tr("QProcess::FailedToStart"); - break; - case QProcess::Crashed: - errorString = tr("QProcess::Crashed"); - break; - case QProcess::Timedout: - errorString = tr("QProcess::Timedout"); - break; - case QProcess::ReadError: - errorString = tr("QProcess::ReadError"); - break; - case QProcess::WriteError: - errorString = tr("QProcess::WriteError"); - break; - case QProcess::UnknownError: - errorString = tr("QProcess::UnknownError"); - break; + case QProcess::FailedToStart: + errorString = tr("QProcess::FailedToStart"); + break; + case QProcess::Crashed: + errorString = tr("QProcess::Crashed"); + break; + case QProcess::Timedout: + errorString = tr("QProcess::Timedout"); + break; + case QProcess::ReadError: + errorString = tr("QProcess::ReadError"); + break; + case QProcess::WriteError: + errorString = tr("QProcess::WriteError"); + break; + case QProcess::UnknownError: + errorString = tr("QProcess::UnknownError"); + break; } ui->textBrowser->setTextColor(Qt::red); ui->textBrowser->setText(errorString); @@ -890,7 +878,8 @@ void MainWindow::processError(QProcess::ProcessError error) * @brief MainWindow::setPassExecutable * @param path */ -void MainWindow::setPassExecutable(QString path) { +void MainWindow::setPassExecutable(QString path) +{ passExecutable = path; } @@ -898,7 +887,8 @@ void MainWindow::setPassExecutable(QString path) { * @brief MainWindow::setGitExecutable * @param path */ -void MainWindow::setGitExecutable(QString path) { +void MainWindow::setGitExecutable(QString path) +{ gitExecutable = path; } @@ -906,7 +896,8 @@ void MainWindow::setGitExecutable(QString path) { * @brief MainWindow::setGpgExecutable * @param path */ -void MainWindow::setGpgExecutable(QString path) { +void MainWindow::setGpgExecutable(QString path) +{ gpgExecutable = path; } @@ -914,7 +905,8 @@ void MainWindow::setGpgExecutable(QString path) { * @brief MainWindow::getGpgExecutable * @return */ -QString MainWindow::getGpgExecutable() { +QString MainWindow::getGpgExecutable() +{ return gpgExecutable; } @@ -966,17 +958,16 @@ void MainWindow::selectFirstFile() * @param parentIndex * @return QModelIndex */ -QModelIndex MainWindow::firstFile(QModelIndex parentIndex) { +QModelIndex MainWindow::firstFile(QModelIndex parentIndex) +{ QModelIndex index = parentIndex; int numRows = proxyModel.rowCount(parentIndex); for (int row = 0; row < numRows; ++row) { index = proxyModel.index(row, 0, parentIndex); - if (model.fileInfo(proxyModel.mapToSource(index)).isFile()) { + if (model.fileInfo(proxyModel.mapToSource(index)).isFile()) return index; - } - if (proxyModel.hasChildren(index)) { + if (proxyModel.hasChildren(index)) return firstFile(index); - } } return index; } @@ -996,7 +987,8 @@ void MainWindow::on_clearButton_clicked() */ QStringList MainWindow::getRecipientList(QString for_file) { - QDir gpgIdPath(QFileInfo(for_file.startsWith(passStore) ? for_file : passStore + for_file).absoluteDir()); + QDir gpgIdPath(QFileInfo(for_file.startsWith( + passStore) ? for_file : passStore + for_file).absoluteDir()); bool found = false; while (gpgIdPath.exists() && gpgIdPath.absolutePath().startsWith(passStore)) { @@ -1004,21 +996,18 @@ QStringList MainWindow::getRecipientList(QString for_file) found = true; break; } - if (!gpgIdPath.cdUp()) { + if (!gpgIdPath.cdUp()) break; - } } QFile gpgId(found ? gpgIdPath.absoluteFilePath(".gpg-id") : passStore + ".gpg-id"); - if (!gpgId.open(QIODevice::ReadOnly | QIODevice::Text)) { + if (!gpgId.open(QIODevice::ReadOnly | QIODevice::Text)) return QStringList(); - } QStringList recipients; while (!gpgId.atEnd()) { QString recipient(gpgId.readLine()); recipient = recipient.trimmed(); - if (!recipient.isEmpty()) { + if (!recipient.isEmpty()) recipients += recipient; - } } return recipients; } @@ -1035,13 +1024,9 @@ QString MainWindow::getRecipientString(QString for_file, QString separator, int QString recipients_str; QStringList recipients_list = getRecipientList(for_file); if (count) - { *count = recipients_list.size(); - } foreach (const QString recipient, recipients_list) - { recipients_str += separator + '"' + recipient + '"'; - } return recipients_str; } @@ -1067,13 +1052,11 @@ void MainWindow::setPassword(QString file, bool overwrite, bool isNew = false) return; } QString newValue = d.getPassword(); - if (newValue.isEmpty()) { + if (newValue.isEmpty()) return; - } - if (newValue.right(1) != "\n") { + if (newValue.right(1) != "\n") newValue += "\n"; - } currentAction = EDIT; if (usePass) { @@ -1083,22 +1066,25 @@ void MainWindow::setPassword(QString file, bool overwrite, bool isNew = false) QString recipients = getRecipientString(file, " -r "); if (recipients.isEmpty()) { QMessageBox::critical(this, tr("Can not edit"), - tr("Could not read encryption key to use, .gpg-id file missing or invalid.")); + tr( + "Could not read encryption key to use, .gpg-id file missing or invalid.")); return; } QString force(overwrite ? " --yes " : " "); - executeWrapper(gpgExecutable , force + "--batch -eq --output \"" + file + "\" " + recipients + " -", newValue); + executeWrapper(gpgExecutable, + force + "--batch -eq --output \"" + file + "\" " + recipients + " -", + newValue); if (!useWebDav && useGit) { - if (!overwrite) { + if (!overwrite) executeWrapper(gitExecutable, "add \"" + file + '"'); - } QString path = file; path.replace(QRegExp("\\.gpg$"), ""); path.replace(QRegExp("^" + passStore), ""); - executeWrapper(gitExecutable, "commit \"" + file + "\" -m \"" + (overwrite ? "Edit" : "Add") + " for " + path + " using QtPass.\""); - if (autoPush) { + executeWrapper(gitExecutable, + "commit \"" + file + "\" -m \"" + (overwrite ? "Edit" : "Add") + " for " + path + + " using QtPass.\""); + if (autoPush) on_pushButton_clicked(); - } } } } @@ -1111,15 +1097,16 @@ void MainWindow::on_addButton_clicked() bool ok; QString dir = getDir(ui->treeView->currentIndex(), usePass); QString file = QInputDialog::getText(this, tr("New file"), - tr("New password file, will be placed in folder %1:").arg(QDir::separator() + getDir(ui->treeView->currentIndex(), true)), QLineEdit::Normal, - "", &ok); - if (!ok || file.isEmpty()) { + tr("New password file, will be placed in folder %1:").arg( + QDir::separator() + + getDir( + ui->treeView->currentIndex(), true)), QLineEdit::Normal, + "", &ok); + if (!ok || file.isEmpty()) return; - } file = dir + file; - if (!usePass) { + if (!usePass) file += ".gpg"; - } lastDecrypt = ""; setPassword(file, false, true); } @@ -1135,23 +1122,26 @@ void MainWindow::on_deleteButton_clicked() if (fileOrFolder.isFile()) { file = getFile(ui->treeView->currentIndex(), usePass); if (QMessageBox::question(this, tr("Delete password?"), - tr("Are you sure you want to delete %1?").arg(QDir::separator() + getFile(ui->treeView->currentIndex(), true)), - QMessageBox::Yes | QMessageBox::No) != QMessageBox::Yes) { - return; - } + tr("Are you sure you want to delete %1?").arg(QDir::separator() + + getFile(ui-> + treeView-> + currentIndex(), + true)), + QMessageBox::Yes | QMessageBox::No) != QMessageBox::Yes) + return; if (usePass) { currentAction = DELETE; executePass("rm -f \"" + file + '"'); - if (useGit && autoPush) { + if (useGit && autoPush) on_pushButton_clicked(); - } } else { if (useGit) { executeWrapper(gitExecutable, "rm -f \"" + file + '"'); - executeWrapper(gitExecutable, "commit \"" + file + "\" -m \" Remove for " + getFile(ui->treeView->currentIndex(), true) + " using QtPass.\""); - if (autoPush) { + executeWrapper(gitExecutable, + "commit \"" + file + "\" -m \" Remove for " + + getFile(ui->treeView->currentIndex(), true) + " using QtPass.\""); + if (autoPush) on_pushButton_clicked(); - } } else { QFile(file).remove(); } @@ -1159,23 +1149,26 @@ void MainWindow::on_deleteButton_clicked() } else { file = getDir(ui->treeView->currentIndex(), usePass); if (QMessageBox::question(this, tr("Delete folder?"), - tr("Are you sure you want to delete %1?").arg(QDir::separator() + getDir(ui->treeView->currentIndex(), true)), - QMessageBox::Yes | QMessageBox::No) != QMessageBox::Yes) { + tr("Are you sure you want to delete %1?").arg(QDir::separator() + + getDir(ui-> + treeView-> + currentIndex(), + true)), + QMessageBox::Yes | QMessageBox::No) != QMessageBox::Yes) return; - } if (usePass) { currentAction = DELETE; executePass("rm -r \"" + file + '"'); - if (useGit && autoPush) { + if (useGit && autoPush) on_pushButton_clicked(); - } } else { if (useGit) { executeWrapper(gitExecutable, "rm -rf \"" + file + '"'); - executeWrapper(gitExecutable, "commit \"" + file + "\" -m \" Remove for " + getFile(ui->treeView->currentIndex(), true) + " using QtPass.\""); - if (autoPush) { + executeWrapper(gitExecutable, + "commit \"" + file + "\" -m \" Remove for " + + getFile(ui->treeView->currentIndex(), true) + " using QtPass.\""); + if (autoPush) on_pushButton_clicked(); - } } else { #if QT_VERSION >= QT_VERSION_CHECK(5, 0, 0) QDir dir(file); @@ -1194,23 +1187,23 @@ void MainWindow::on_deleteButton_clicked() * @param dirName * @return */ -bool MainWindow::removeDir(const QString & dirName) +bool MainWindow::removeDir(const QString &dirName) { bool result = true; QDir dir(dirName); if (dir.exists(dirName)) { - Q_FOREACH(QFileInfo info, dir.entryInfoList(QDir::NoDotAndDotDot | QDir::System | QDir::Hidden | QDir::AllDirs | QDir::Files, QDir::DirsFirst)) { - if (info.isDir()) { + Q_FOREACH(QFileInfo info, + dir.entryInfoList(QDir::NoDotAndDotDot | QDir::System | QDir::Hidden + | QDir::AllDirs + | QDir::Files, QDir::DirsFirst)) { + if (info.isDir()) result = removeDir(info.absoluteFilePath()); - } - else { + else result = QFile::remove(info.absoluteFilePath()); - } - if (!result) { + if (!result) return result; - } } result = dir.rmdir(dirName); } @@ -1225,7 +1218,7 @@ void MainWindow::on_editButton_clicked() QString file = getFile(ui->treeView->currentIndex(), usePass); if (file.isEmpty()) { QMessageBox::critical(this, tr("Can not edit"), - tr("Selected password file does not exist, not able to edit")); + tr("Selected password file does not exist, not able to edit")); return; } setPassword(file, true); @@ -1243,26 +1236,24 @@ QList MainWindow::listKeys(QString keystring, bool secret) QList users; currentAction = GPG_INTERNAL; QString listopt = secret ? "--list-secret-keys " : "--list-keys "; - executeWrapper(gpgExecutable , "--no-tty --with-colons " + listopt + keystring); + executeWrapper(gpgExecutable, "--no-tty --with-colons " + listopt + keystring); process->waitForFinished(2000); - if (process->exitStatus() != QProcess::NormalExit) { + if (process->exitStatus() != QProcess::NormalExit) return users; - } - QStringList keys = QString(process->readAllStandardOutput()).split(QRegExp("[\r\n]"), QString::SkipEmptyParts); + QStringList keys = QString(process->readAllStandardOutput()).split(QRegExp( + "[\r\n]"), + QString::SkipEmptyParts); UserInfo current_user; foreach (QString key, keys) { QStringList props = key.split(':'); - if (props.size() < 10) { + if (props.size() < 10) continue; - } if (props[0] == (secret ? "sec" : "pub")) { if (!current_user.key_id.isEmpty()) - { users.append(current_user); - } current_user = UserInfo(); current_user.key_id = props[4]; - current_user.name = props[9].toUtf8(); + current_user.name = props[9].toUtf8(); current_user.validity = props[8][0].toLatin1(); current_user.created.setTime_t(props[5].toInt()); current_user.expiry.setTime_t(props[6].toInt()); @@ -1271,17 +1262,14 @@ QList MainWindow::listKeys(QString keystring, bool secret) } } if (!current_user.key_id.isEmpty()) - { users.append(current_user); - } return users; } void MainWindow::userDialog(QString dir) { - if (!dir.isEmpty()) { + if (!dir.isEmpty()) currentDir = dir; - } on_usersButton_clicked(); } @@ -1290,35 +1278,29 @@ void MainWindow::on_usersButton_clicked() QList users = listKeys(); if (users.size() == 0) { QMessageBox::critical(this, tr("Can not get key list"), - tr("Unable to get list of available gpg keys")); + tr("Unable to get list of available gpg keys")); return; } QList secret_keys = listKeys("", true); foreach (const UserInfo &sec, secret_keys) { - for (QList::iterator it = users.begin(); it != users.end(); ++it) { + for (QList::iterator it = users.begin(); it != users.end(); ++it) if (sec.key_id == it->key_id) it->have_secret = true; - } } QList selected_users; - QString dir = currentDir.isEmpty()?getDir(ui->treeView->currentIndex(), false):currentDir; + QString dir = currentDir.isEmpty() ? getDir(ui->treeView->currentIndex(), false) : currentDir; int count = 0; QString recipients = getRecipientString(dir.isEmpty() ? "" : dir, " ", &count); - if (!recipients.isEmpty()) { + if (!recipients.isEmpty()) selected_users = listKeys(recipients); - } foreach (const UserInfo &sel, selected_users) { - for (QList::iterator it = users.begin(); it != users.end(); ++it) { + for (QList::iterator it = users.begin(); it != users.end(); ++it) if (sel.key_id == it->key_id) it->enabled = true; - } } - if (count > selected_users.size()) - { + if (count > selected_users.size()) { // Some keys seem missing from keyring, add them separately QStringList recipients = getRecipientList(dir.isEmpty() ? "" : dir); - foreach (const QString recipient, recipients) - { - if (listKeys(recipient).size() < 1) - { + foreach (const QString recipient, recipients) { + if (listKeys(recipient).size() < 1) { UserInfo i; i.enabled = true; i.key_id = recipient; @@ -1339,13 +1321,12 @@ void MainWindow::on_usersButton_clicked() bool addFile = false; if (addGPGId) { QFileInfo checkFile(gpgIdFile); - if (!checkFile.exists() || !checkFile.isFile()) { + if (!checkFile.exists() || !checkFile.isFile()) addFile = true; - } } if (!gpgId.open(QIODevice::WriteOnly | QIODevice::Text)) { QMessageBox::critical(this, tr("Cannot update"), - tr("Failed to open .gpg-id for writing.")); + tr("Failed to open .gpg-id for writing.")); return; } bool secret_selected = false; @@ -1358,19 +1339,18 @@ void MainWindow::on_usersButton_clicked() gpgId.close(); if (!secret_selected) { QMessageBox::critical(this, tr("Check selected users!"), - tr("None of the selected keys have a secret key available.\n" - "You will not be able to decrypt any newly added passwords!")); + tr("None of the selected keys have a secret key available.\n" + "You will not be able to decrypt any newly added passwords!")); } - if (!useWebDav && useGit && !gitExecutable.isEmpty()){ - if (addFile) { + if (!useWebDav && useGit && !gitExecutable.isEmpty()) { + if (addFile) executeWrapper(gitExecutable, "add \"" + gpgIdFile + '"'); - } QString path = gpgIdFile; path.replace(QRegExp("\\.gpg$"), ""); - executeWrapper(gitExecutable, "commit \"" + gpgIdFile + "\" -m \"Added "+ path + " using QtPass.\""); - if (autoPush) { + executeWrapper(gitExecutable, + "commit \"" + gpgIdFile + "\" -m \"Added "+ path + " using QtPass.\""); + if (autoPush) on_pushButton_clicked(); - } } } @@ -1419,10 +1399,10 @@ void MainWindow::updateEnv() QStringList store = env.filter("PASSWORD_STORE_DIR"); // put PASSWORD_STORE_DIR in env if (store.isEmpty()) { - //qDebug() << "Added PASSWORD_STORE_DIR"; + // qDebug() << "Added PASSWORD_STORE_DIR"; env.append("PASSWORD_STORE_DIR=" + passStore); } else { - //qDebug() << "Update PASSWORD_STORE_DIR with " + passStore; + // qDebug() << "Update PASSWORD_STORE_DIR with " + passStore; env.replaceInStrings(store.first(), "PASSWORD_STORE_DIR=" + passStore); } } @@ -1436,13 +1416,11 @@ QStringList MainWindow::getSecretKeys() QList keys = listKeys("", true); QStringList names; - if (keys.size() == 0) { + if (keys.size() == 0) return names; - } - foreach (const UserInfo &sec, keys) { + foreach (const UserInfo &sec, keys) names << sec.name; - } return names; } @@ -1456,38 +1434,34 @@ void MainWindow::generateKeyPair(QString batch, QDialog *keygenWindow) keygen = keygenWindow; ui->statusBar->showMessage(tr("Generating GPG key pair"), 60000); currentAction = GPG_INTERNAL; - executeWrapper(gpgExecutable , "--gen-key --no-tty --batch", batch); + executeWrapper(gpgExecutable, "--gen-key --no-tty --batch", batch); } - /** * @brief MainWindow::updateProfileBox */ void MainWindow::updateProfileBox() { - //qDebug() << profiles.size(); + // qDebug() << profiles.size(); if (profiles.isEmpty()) { ui->profileBox->hide(); } else { ui->profileBox->show(); - if (profiles.size() < 2) { + if (profiles.size() < 2) ui->profileBox->setEnabled(false); - } else { + else ui->profileBox->setEnabled(true); - } ui->profileBox->clear(); QHashIterator i(profiles); while (i.hasNext()) { i.next(); - if (!i.key().isEmpty()) { + if (!i.key().isEmpty()) ui->profileBox->addItem(i.key()); - } } } int index = ui->profileBox->findText(profile); - if ( index != -1 ) { // -1 for not found - ui->profileBox->setCurrentIndex(index); - } + if (index != -1) // -1 for not found + ui->profileBox->setCurrentIndex(index); } /** @@ -1496,9 +1470,8 @@ void MainWindow::updateProfileBox() */ void MainWindow::on_profileBox_currentIndexChanged(QString name) { - if (startupPhase || name == profile) { + if (startupPhase || name == profile) return; - } profile = name; passStore = profiles[name]; @@ -1513,10 +1486,10 @@ void MainWindow::on_profileBox_currentIndexChanged(QString name) QStringList store = env.filter("PASSWORD_STORE_DIR"); // put PASSWORD_STORE_DIR in env if (store.isEmpty()) { - //qDebug() << "Added PASSWORD_STORE_DIR"; + // qDebug() << "Added PASSWORD_STORE_DIR"; env.append("PASSWORD_STORE_DIR=" + passStore); } else { - //qDebug() << "Update PASSWORD_STORE_DIR"; + // qDebug() << "Update PASSWORD_STORE_DIR"; env.replaceInStrings(store.first(), "PASSWORD_STORE_DIR=" + passStore); } @@ -1528,16 +1501,15 @@ void MainWindow::on_profileBox_currentIndexChanged(QString name) */ void MainWindow::initTrayIcon() { - if(tray != NULL){ + if (tray != NULL) { qDebug() << "Creating tray icon again?"; return; } - if(QSystemTrayIcon::isSystemTrayAvailable() == true) { + if (QSystemTrayIcon::isSystemTrayAvailable() == true) { // Setup tray icon this->tray = new TrayIcon(this); - if(tray == NULL){ + if (tray == NULL) qDebug() << "Allocating tray icon failed."; - } } else { qDebug() << "No tray icon for this OS possibly also not show options?"; } @@ -1548,7 +1520,7 @@ void MainWindow::initTrayIcon() */ void MainWindow::destroyTrayIcon() { - if(tray == NULL){ + if (tray == NULL) { qDebug() << "Destroy non existing tray icon?"; return; } @@ -1566,13 +1538,13 @@ void MainWindow::closeEvent(QCloseEvent *event) this->hide(); event->ignore(); } else { - settings->beginGroup( "mainwindow" ); - settings->setValue( "geometry", saveGeometry() ); - settings->setValue( "savestate", saveState() ); - settings->setValue( "maximized", isMaximized() ); - if ( !isMaximized() ) { - settings->setValue( "pos", pos() ); - settings->setValue( "size", size() ); + settings->beginGroup("mainwindow"); + settings->setValue("geometry", saveGeometry()); + settings->setValue("savestate", saveState()); + settings->setValue("maximized", isMaximized()); + if (!isMaximized()) { + settings->setValue("pos", pos()); + settings->setValue("size", size()); } settings->setValue("splitterLeft", ui->splitter->sizes()[0]); settings->setValue("splitterRight", ui->splitter->sizes()[1]); @@ -1590,9 +1562,9 @@ void MainWindow::on_copyPasswordButton_clicked() * @brief MainWindow::showContextMenu * @param pos */ -void MainWindow::showContextMenu(const QPoint& pos) +void MainWindow::showContextMenu(const QPoint &pos) { - QModelIndex index = ui->treeView->indexAt(pos); + QModelIndex index = ui->treeView->indexAt(pos); bool selected = true; if (!index.isValid()) { ui->treeView->clearSelection(); @@ -1610,25 +1582,25 @@ void MainWindow::showContextMenu(const QPoint& pos) QMenu contextMenu; if (!selected || fileOrFolder.isDir()) { - QAction* addFolder = contextMenu.addAction(tr("Add folder")); - QAction* addPassword = contextMenu.addAction(tr("Add password")); - QAction* users = contextMenu.addAction(tr("Users")); + QAction *addFolder = contextMenu.addAction(tr("Add folder")); + QAction *addPassword = contextMenu.addAction(tr("Add password")); + QAction *users = contextMenu.addAction(tr("Users")); connect(addFolder, SIGNAL(triggered()), this, SLOT(addFolder())); connect(addPassword, SIGNAL(triggered()), this, SLOT(on_addButton_clicked())); connect(users, SIGNAL(triggered()), this, SLOT(on_usersButton_clicked())); } else if (fileOrFolder.isFile()) { - QAction* edit = contextMenu.addAction(tr("Edit")); + QAction *edit = contextMenu.addAction(tr("Edit")); connect(edit, SIGNAL(triggered()), this, SLOT(editPassword())); } if (selected) { - //if (useClipboard != CLIPBOARD_NEVER) { - // contextMenu.addSeparator(); - // QAction* copyItem = contextMenu.addAction(tr("Copy Password")); - // if (getClippedPassword().length() == 0) copyItem->setEnabled(false); - // connect(copyItem, SIGNAL(triggered()), this, SLOT(copyPasswordToClipboard())); - //} + // if (useClipboard != CLIPBOARD_NEVER) { + // contextMenu.addSeparator(); + // QAction* copyItem = contextMenu.addAction(tr("Copy Password")); + // if (getClippedPassword().length() == 0) copyItem->setEnabled(false); + // connect(copyItem, SIGNAL(triggered()), this, SLOT(copyPasswordToClipboard())); + // } contextMenu.addSeparator(); - QAction* deleteItem = contextMenu.addAction(tr("Delete")); + QAction *deleteItem = contextMenu.addAction(tr("Delete")); connect(deleteItem, SIGNAL(triggered()), this, SLOT(on_deleteButton_clicked())); } @@ -1639,18 +1611,18 @@ void MainWindow::showContextMenu(const QPoint& pos) * @brief MainWindow::showContextMenu * @param pos */ -void MainWindow::showBrowserContextMenu(const QPoint& pos) +void MainWindow::showBrowserContextMenu(const QPoint &pos) { QMenu *contextMenu = ui->textBrowser->createStandardContextMenu(pos); if (useClipboard != CLIPBOARD_NEVER) { contextMenu->addSeparator(); - QAction* copyItem = contextMenu->addAction(tr("Copy Password")); + QAction *copyItem = contextMenu->addAction(tr("Copy Password")); if (getClippedPassword().length() == 0) copyItem->setEnabled(false); connect(copyItem, \ - SIGNAL(triggered()), \ - this, \ - SLOT(copyPasswordToClipboard())); + SIGNAL(triggered()), \ + this, \ + SLOT(copyPasswordToClipboard())); } QPoint globalPos = ui->textBrowser->viewport()->mapToGlobal(pos); @@ -1665,13 +1637,16 @@ void MainWindow::addFolder() bool ok; QString dir = getDir(ui->treeView->currentIndex(), false); QString newdir = QInputDialog::getText(this, tr("New file"), - tr("New folder, will be placed in folder %1:").arg(QDir::separator() + getDir(ui->treeView->currentIndex(), true)), QLineEdit::Normal, - "", &ok); - if (!ok || newdir.isEmpty()) { + tr("New folder, will be placed in folder %1:").arg(QDir:: + separator() + + + getDir( + ui->treeView->currentIndex(), true)), QLineEdit::Normal, + "", &ok); + if (!ok || newdir.isEmpty()) return; - } newdir.prepend(dir); - //qDebug() << newdir; + // qDebug() << newdir; QDir().mkdir(newdir); // TODO add to git? } @@ -1681,25 +1656,23 @@ void MainWindow::addFolder() */ void MainWindow::editPassword() { - if (useGit && autoPull) { + if (useGit && autoPull) on_updateButton_clicked(); - } waitFor(30); // TODO move to editbutton stuff possibly? currentDir = getDir(ui->treeView->currentIndex(), false); lastDecrypt = "Could not decrypt"; QString file = getFile(ui->treeView->currentIndex(), usePass); - if (!file.isEmpty()){ + if (!file.isEmpty()) { currentAction = GPG; - if (usePass) { + if (usePass) executePass('"' + file + '"'); - } else { - executeWrapper(gpgExecutable , "-d --quiet --yes --no-encrypt-to --batch --use-agent \"" + file + '"'); - } - process->waitForFinished(30000); // long wait (passphrase stuff) - if (process->exitStatus() == QProcess::NormalExit) { + else + executeWrapper(gpgExecutable, + "-d --quiet --yes --no-encrypt-to --batch --use-agent \"" + file + '"'); + process->waitForFinished(30000); // long wait (passphrase stuff) + if (process->exitStatus() == QProcess::NormalExit) on_editButton_clicked(); - } } } @@ -1707,31 +1680,31 @@ void MainWindow::editPassword() * @brief MainWindow::generatePassword * @return */ -QString MainWindow::generatePassword() { +QString MainWindow::generatePassword() +{ QString passwd; if (usePwgen) { waitFor(2); - QString args = (useSymbols?"--symbols -1 ":"-1 ") + QString::number(passwordLength); + QString args = (useSymbols ? "--symbols -1 " : "-1 ") + QString::number(passwordLength); currentAction = PWGEN; executeWrapper(pwgenExecutable, args); process->waitForFinished(1000); - if (process->exitStatus() == QProcess::NormalExit) { + if (process->exitStatus() == QProcess::NormalExit) passwd = QString(process->readAllStandardOutput()).remove(QRegExp("[\\n\\r]")); - } else { + else qDebug() << "pwgen fail"; - } } else { int length = passwordChars.length(); if (length > 0) { - for(int i=0; iatEnd() || !execQueue->isEmpty()) { current = QDateTime::currentDateTime(); if (stop < current.toTime_t()) { QMessageBox::critical(this, tr("Timed out"), - tr("Can't start process, previous one is still running!")); + tr("Can't start process, previous one is still running!")); return; } Util::qSleep(100); @@ -1761,7 +1734,7 @@ void MainWindow::waitFor(int seconds) */ void MainWindow::clearTemplateWidgets() { - while(ui->formLayout->count() > 0){ + while (ui->formLayout->count() > 0) { QLayoutItem *item = ui->formLayout->takeAt(0); delete item->widget(); delete item; @@ -1781,8 +1754,8 @@ void MainWindow::copyPasswordToClipboard() ui->statusBar->showMessage(tr("Password copied to clipboard"), 3000); if (useAutoclear) { QTimer::singleShot(1000*autoclearSeconds, \ - this, \ - SLOT(clearClipboard())); + this, \ + SLOT(clearClipboard())); } } } @@ -1791,16 +1764,16 @@ void MainWindow::copyPasswordToClipboard() * @brief Mainwindow::setClippedPassword - set the stored clipped password * @return none */ -void MainWindow::setClippedPassword(const QString & pass) +void MainWindow::setClippedPassword(const QString &pass) { clippedPass = pass; - if (clippedPass.length() == 0) { + if (clippedPass.length() == 0) ui->copyPasswordButton->setEnabled(false); - } else { + else ui->copyPasswordButton->setEnabled(true); - } } -const QString &MainWindow::getClippedPassword() { +const QString &MainWindow::getClippedPassword() +{ return clippedPass; } diff --git a/mainwindow.h b/mainwindow.h index 91cca8cc1..85fdfbdf2 100644 --- a/mainwindow.h +++ b/mainwindow.h @@ -32,12 +32,16 @@ class MainWindow : public QMainWindow { Q_OBJECT -enum actionType { GPG, GIT, EDIT, DELETE, GPG_INTERNAL, PWGEN }; + enum actionType { + GPG, GIT, EDIT, DELETE, GPG_INTERNAL, PWGEN + }; public: - enum clipBoardType { CLIPBOARD_NEVER = 0, - CLIPBOARD_ALWAYS = 1, - CLIPBOARD_ON_DEMAND = 2 }; + enum clipBoardType { + CLIPBOARD_NEVER = 0, + CLIPBOARD_ALWAYS = 1, + CLIPBOARD_ON_DEMAND = 2 + }; explicit MainWindow(QWidget *parent = 0); ~MainWindow(); @@ -46,7 +50,7 @@ enum actionType { GPG, GIT, EDIT, DELETE, GPG_INTERNAL, PWGEN }; void setGpgExecutable(QString); QString getGpgExecutable(); bool checkConfig(); - void setApp(SingleApplication* app); + void setApp(SingleApplication *app); void setText(QString); QStringList getSecretKeys(); void generateKeyPair(QString, QDialog *); @@ -78,8 +82,8 @@ private slots: void messageAvailable(QString message); void on_profileBox_currentIndexChanged(QString); void on_copyPasswordButton_clicked(); - void showContextMenu(const QPoint& pos); - void showBrowserContextMenu(const QPoint& pos); + void showContextMenu(const QPoint &pos); + void showBrowserContextMenu(const QPoint &pos); void addFolder(); void editPassword(); void focusInput(); @@ -159,10 +163,10 @@ private slots: void updateProfileBox(); void initTrayIcon(); void destroyTrayIcon(); - bool removeDir(const QString & dirName); + bool removeDir(const QString &dirName); void waitFor(int); void clearTemplateWidgets(); - void setClippedPassword(const QString & pass); + void setClippedPassword(const QString &pass); const QString &getClippedPassword(); }; diff --git a/passworddialog.cpp b/passworddialog.cpp index e8199d8a8..6b939d3a3 100644 --- a/passworddialog.cpp +++ b/passworddialog.cpp @@ -10,7 +10,7 @@ PasswordDialog::PasswordDialog(MainWindow *parent) : { mainWindow = parent; templating = false; - allFields = false; + allFields = false; ui->setupUi(this); } @@ -21,11 +21,10 @@ PasswordDialog::~PasswordDialog() void PasswordDialog::on_checkBoxShow_stateChanged(int arg1) { - if (arg1) { + if (arg1) ui->lineEditPassword->setEchoMode(QLineEdit::Normal); - } else { + else ui->lineEditPassword->setEchoMode(QLineEdit::Password); - } } void PasswordDialog::on_createPasswordButton_clicked() @@ -37,23 +36,22 @@ void PasswordDialog::on_createPasswordButton_clicked() void PasswordDialog::setPassword(QString password) { - QStringList tokens = password.split("\n"); + QStringList tokens = password.split("\n"); ui->lineEditPassword->setText(tokens[0]); tokens.pop_front(); if (templating) { QWidget *previous = ui->checkBoxShow; for (int i = 0; i < ui->formLayout->rowCount(); i++) { QLayoutItem *item = ui->formLayout->itemAt(i, QFormLayout::FieldRole); - if (item == NULL) { + if (item == NULL) continue; - } QWidget *widget = item->widget(); for (int j = 0; j < tokens.length(); j++) { QString token = tokens.at(j); if (token.startsWith(widget->objectName()+':')) { tokens.removeAt(j); QString value = token.remove(0, widget->objectName().length()+1); - ((QLineEdit*)widget)->setText(value); + ((QLineEdit *)widget)->setText(value); } } previous = widget; @@ -65,9 +63,8 @@ void PasswordDialog::setPassword(QString password) int colon = token.indexOf(':'); QString field = token.left(colon); QString value = token.right(token.length()-colon-1); - if (!passTemplate.contains(field) && value.startsWith("//")) { - continue; // colon is probably from a url - } + if (!passTemplate.contains(field) && value.startsWith("//")) + continue; // colon is probably from a url QLineEdit *line = new QLineEdit(); line->setObjectName(field); line->setText(value); @@ -88,27 +85,25 @@ QString PasswordDialog::getPassword() QString passFile = ui->lineEditPassword->text() + "\n"; for (int i = 0; i < ui->formLayout->rowCount(); i++) { QLayoutItem *item = ui->formLayout->itemAt(i, QFormLayout::FieldRole); - if (item == NULL) { + if (item == NULL) continue; - } QWidget *widget = item->widget(); - QString text = ((QLineEdit*)widget)->text(); - if (text.isEmpty()) { + QString text = ((QLineEdit *)widget)->text(); + if (text.isEmpty()) continue; - } passFile += widget->objectName() + ":" + text + "\n"; } passFile += ui->plainTextEdit->toPlainText(); return passFile; } -void PasswordDialog::setTemplate(QString rawFields) { +void PasswordDialog::setTemplate(QString rawFields) +{ fields = rawFields.split('\n'); QWidget *previous = ui->checkBoxShow; foreach (QString field, fields) { - if (field.isEmpty()) { + if (field.isEmpty()) continue; - } QLineEdit *line = new QLineEdit(); line->setObjectName(field); ui->formLayout->addRow(new QLabel(field), line); @@ -117,14 +112,17 @@ void PasswordDialog::setTemplate(QString rawFields) { } } -void PasswordDialog::setFile(QString file) { +void PasswordDialog::setFile(QString file) +{ this->setWindowTitle(this->windowTitle()+" "+file); } -void PasswordDialog::templateAll(bool templateAll) { +void PasswordDialog::templateAll(bool templateAll) +{ allFields = templateAll; } -void PasswordDialog::useTemplate(bool useTemplate) { +void PasswordDialog::useTemplate(bool useTemplate) +{ templating = useTemplate; } diff --git a/progressindicator.cpp b/progressindicator.cpp index b3835f662..164bb8aa3 100644 --- a/progressindicator.cpp +++ b/progressindicator.cpp @@ -2,21 +2,21 @@ #include -QProgressIndicator::QProgressIndicator(QWidget* parent) - : QWidget(parent), - m_angle(0), - m_timerId(-1), - m_delay(40), - m_displayedWhenStopped(false), - m_color(Qt::black) +QProgressIndicator::QProgressIndicator(QWidget *parent) : + QWidget(parent), + m_angle(0), + m_timerId(-1), + m_delay(40), + m_displayedWhenStopped(false), + m_color(Qt::black) { setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed); setFocusPolicy(Qt::NoFocus); } -bool QProgressIndicator::isAnimated () const +bool QProgressIndicator::isAnimated() const { - return (m_timerId != -1); + return m_timerId != -1; } void QProgressIndicator::setDisplayedWhenStopped(bool state) @@ -60,7 +60,7 @@ void QProgressIndicator::setAnimationDelay(int delay) m_timerId = startTimer(m_delay); } -void QProgressIndicator::setColor(const QColor & color) +void QProgressIndicator::setColor(const QColor &color) { m_color = color; @@ -69,7 +69,7 @@ void QProgressIndicator::setColor(const QColor & color) QSize QProgressIndicator::sizeHint() const { - return QSize(20,20); + return QSize(20, 20); } int QProgressIndicator::heightForWidth(int w) const @@ -90,27 +90,27 @@ void QProgressIndicator::paintEvent(QPaintEvent * /*event*/) return; int width = qMin(this->width(), this->height()); - + QPainter p(this); p.setRenderHint(QPainter::Antialiasing); - + int outerRadius = (width-1)*0.5; int innerRadius = (width-1)*0.5*0.38; int capsuleHeight = outerRadius - innerRadius; - int capsuleWidth = (width > 32 ) ? capsuleHeight *.23 : capsuleHeight *.35; + int capsuleWidth = (width > 32) ? capsuleHeight *.23 : capsuleHeight *.35; int capsuleRadius = capsuleWidth/2; - for (int i=0; i<12; i++) - { + for (int i = 0; i < 12; i++) { QColor color = m_color; color.setAlphaF(1.0f - (i/12.0f)); p.setPen(Qt::NoPen); - p.setBrush(color); + p.setBrush(color); p.save(); p.translate(rect().center()); p.rotate(m_angle - i*30.0f); - p.drawRoundedRect(-capsuleWidth*0.5, -(innerRadius+capsuleHeight), capsuleWidth, capsuleHeight, capsuleRadius, capsuleRadius); + p.drawRoundedRect(-capsuleWidth*0.5, -(innerRadius+capsuleHeight), capsuleWidth, + capsuleHeight, capsuleRadius, capsuleRadius); p.restore(); } } diff --git a/progressindicator.h b/progressindicator.h index 65d80f768..46dfa37e5 100644 --- a/progressindicator.h +++ b/progressindicator.h @@ -4,13 +4,13 @@ #include #include -/*! +/*! \class QProgressIndicator - \brief The QProgressIndicator class lets an application display a progress indicator to show that a lengthy task is under way. + \brief The QProgressIndicator class lets an application display a progress indicator to show that a lengthy task is under way. Progress indicators are indeterminate and do nothing more than spin to show that the application is busy. \sa QProgressBar -*/ + */ class QProgressIndicator : public QWidget { Q_OBJECT @@ -18,64 +18,70 @@ class QProgressIndicator : public QWidget Q_PROPERTY(bool displayedWhenStopped READ isDisplayedWhenStopped WRITE setDisplayedWhenStopped) Q_PROPERTY(QColor color READ color WRITE setColor) public: - QProgressIndicator(QWidget* parent = 0); + QProgressIndicator(QWidget *parent = 0); - /*! Returns the delay between animation steps. - \return The number of milliseconds between animation steps. By default, the animation delay is set to 40 milliseconds. - \sa setAnimationDelay - */ - int animationDelay() const { return m_delay; } +/*! Returns the delay between animation steps. + \return The number of milliseconds between animation steps. By default, the animation delay is set to 40 milliseconds. + \sa setAnimationDelay + */ + int animationDelay() const + { + return m_delay; + } - /*! Returns a Boolean value indicating whether the component is currently animated. - \return Animation state. - \sa startAnimation stopAnimation - */ - bool isAnimated () const; +/*! Returns a Boolean value indicating whether the component is currently animated. + \return Animation state. + \sa startAnimation stopAnimation + */ + bool isAnimated() const; - /*! Returns a Boolean value indicating whether the receiver shows itself even when it is not animating. - \return Return true if the progress indicator shows itself even when it is not animating. By default, it returns false. - \sa setDisplayedWhenStopped - */ +/*! Returns a Boolean value indicating whether the receiver shows itself even when it is not animating. + \return Return true if the progress indicator shows itself even when it is not animating. By default, it returns false. + \sa setDisplayedWhenStopped + */ bool isDisplayedWhenStopped() const; - /*! Returns the color of the component. - \sa setColor - */ - const QColor & color() const { return m_color; } +/*! Returns the color of the component. + \sa setColor + */ + const QColor &color() const + { + return m_color; + } virtual QSize sizeHint() const; int heightForWidth(int w) const; public slots: - /*! Starts the spin animation. - \sa stopAnimation isAnimated - */ +/*! Starts the spin animation. + \sa stopAnimation isAnimated + */ void startAnimation(); - /*! Stops the spin animation. - \sa startAnimation isAnimated - */ +/*! Stops the spin animation. + \sa startAnimation isAnimated + */ void stopAnimation(); - /*! Sets the delay between animation steps. - Setting the \a delay to a value larger than 40 slows the animation, while setting the \a delay to a smaller value speeds it up. - \param delay The delay, in milliseconds. - \sa animationDelay - */ +/*! Sets the delay between animation steps. + Setting the \a delay to a value larger than 40 slows the animation, while setting the \a delay to a smaller value speeds it up. + \param delay The delay, in milliseconds. + \sa animationDelay + */ void setAnimationDelay(int delay); - /*! Sets whether the component hides itself when it is not animating. - \param state The animation state. Set false to hide the progress indicator when it is not animating; otherwise true. - \sa isDisplayedWhenStopped - */ +/*! Sets whether the component hides itself when it is not animating. + \param state The animation state. Set false to hide the progress indicator when it is not animating; otherwise true. + \sa isDisplayedWhenStopped + */ void setDisplayedWhenStopped(bool state); - /*! Sets the color of the components to the given color. - \sa color - */ - void setColor(const QColor & color); +/*! Sets the color of the components to the given color. + \sa color + */ + void setColor(const QColor &color); protected: - virtual void timerEvent(QTimerEvent * event); - virtual void paintEvent(QPaintEvent * event); + virtual void timerEvent(QTimerEvent *event); + virtual void paintEvent(QPaintEvent *event); private: int m_angle; int m_timerId; diff --git a/singleapplication.cpp b/singleapplication.cpp index 8573a8cce..52394d59b 100644 --- a/singleapplication.cpp +++ b/singleapplication.cpp @@ -8,25 +8,25 @@ * @param argv * @param uniqueKey */ -SingleApplication::SingleApplication(int &argc, char *argv[], const QString uniqueKey) : QApplication(argc, argv), _uniqueKey(uniqueKey) +SingleApplication::SingleApplication(int &argc, char *argv[], + const QString uniqueKey) : QApplication(argc, argv), + _uniqueKey(uniqueKey) { - sharedMemory.setKey(_uniqueKey); - if (sharedMemory.attach()) - _isRunning = true; - else - { - _isRunning = false; - // create shared memory. - if (!sharedMemory.create(1)) - { - qDebug("Unable to create single instance."); - return; - } - // create local server and listen to incomming messages from other instances. - localServer.reset(new QLocalServer(this)); - connect(localServer.data(), SIGNAL(newConnection()), this, SLOT(receiveMessage())); - localServer->listen(_uniqueKey); + sharedMemory.setKey(_uniqueKey); + if (sharedMemory.attach()) { + _isRunning = true; + } else { + _isRunning = false; + // create shared memory. + if (!sharedMemory.create(1)) { + qDebug("Unable to create single instance."); + return; } + // create local server and listen to incomming messages from other instances. + localServer.reset(new QLocalServer(this)); + connect(localServer.data(), SIGNAL(newConnection()), this, SLOT(receiveMessage())); + localServer->listen(_uniqueKey); + } } // public slots. @@ -36,16 +36,15 @@ SingleApplication::SingleApplication(int &argc, char *argv[], const QString uniq */ void SingleApplication::receiveMessage() { - QLocalSocket *localSocket = localServer->nextPendingConnection(); - if (!localSocket->waitForReadyRead(timeout)) - { - qDebug() << localSocket->errorString().toLatin1(); - return; - } - QByteArray byteArray = localSocket->readAll(); - QString message = QString::fromUtf8(byteArray.constData()); - emit messageAvailable(message); - localSocket->disconnectFromServer(); + QLocalSocket *localSocket = localServer->nextPendingConnection(); + if (!localSocket->waitForReadyRead(timeout)) { + qDebug() << localSocket->errorString().toLatin1(); + return; + } + QByteArray byteArray = localSocket->readAll(); + QString message = QString::fromUtf8(byteArray.constData()); + emit messageAvailable(message); + localSocket->disconnectFromServer(); } // public functions. @@ -55,7 +54,7 @@ void SingleApplication::receiveMessage() */ bool SingleApplication::isRunning() { - return _isRunning; + return _isRunning; } /** @@ -65,21 +64,19 @@ bool SingleApplication::isRunning() */ bool SingleApplication::sendMessage(const QString &message) { - if (!_isRunning) - return false; - QLocalSocket localSocket(this); - localSocket.connectToServer(_uniqueKey, QIODevice::WriteOnly); - if (!localSocket.waitForConnected(timeout)) - { - qDebug() << localSocket.errorString().toLatin1(); - return false; - } - localSocket.write(message.toUtf8()); - if (!localSocket.waitForBytesWritten(timeout)) - { - qDebug() << localSocket.errorString().toLatin1(); - return false; - } - localSocket.disconnectFromServer(); - return true; + if (!_isRunning) + return false; + QLocalSocket localSocket(this); + localSocket.connectToServer(_uniqueKey, QIODevice::WriteOnly); + if (!localSocket.waitForConnected(timeout)) { + qDebug() << localSocket.errorString().toLatin1(); + return false; + } + localSocket.write(message.toUtf8()); + if (!localSocket.waitForBytesWritten(timeout)) { + qDebug() << localSocket.errorString().toLatin1(); + return false; + } + localSocket.disconnectFromServer(); + return true; } diff --git a/singleapplication.h b/singleapplication.h index 966dc95c5..236fabc12 100644 --- a/singleapplication.h +++ b/singleapplication.h @@ -7,25 +7,25 @@ class SingleApplication : public QApplication { - Q_OBJECT + Q_OBJECT public: - SingleApplication(int &argc, char *argv[], const QString uniqueKey); + SingleApplication(int &argc, char *argv[], const QString uniqueKey); - bool isRunning(); - bool sendMessage(const QString &message); + bool isRunning(); + bool sendMessage(const QString &message); public slots: - void receiveMessage(); + void receiveMessage(); signals: - void messageAvailable(QString message); + void messageAvailable(QString message); private: - bool _isRunning; - QString _uniqueKey; - QSharedMemory sharedMemory; - QScopedPointer localServer; + bool _isRunning; + QString _uniqueKey; + QSharedMemory sharedMemory; + QScopedPointer localServer; - static const int timeout = 1000; + static const int timeout = 1000; }; #endif // SINGLE_APPLICATION_H diff --git a/storemodel.cpp b/storemodel.cpp index 3738236f7..c61195a42 100644 --- a/storemodel.cpp +++ b/storemodel.cpp @@ -15,8 +15,7 @@ StoreModel::StoreModel() * @param sourceParent * @return */ -bool StoreModel::filterAcceptsRow(int sourceRow, - const QModelIndex &sourceParent) const +bool StoreModel::filterAcceptsRow(int sourceRow, const QModelIndex &sourceParent) const { QModelIndex index = sourceModel()->index(sourceRow, 0, sourceParent); return ShowThis(index); @@ -30,28 +29,19 @@ bool StoreModel::filterAcceptsRow(int sourceRow, bool StoreModel::ShowThis(const QModelIndex index) const { bool retVal = false; - if (fs == NULL) { + if (fs == NULL) return retVal; - } - //Gives you the info for number of childs with a parent - if ( sourceModel()->rowCount(index) > 0 ) - { - for( int nChild = 0; nChild < sourceModel()->rowCount(index); nChild++) - { - QModelIndex childIndex = sourceModel()->index(nChild,0,index); + // Gives you the info for number of childs with a parent + if (sourceModel()->rowCount(index) > 0) { + for (int nChild = 0; nChild < sourceModel()->rowCount(index); nChild++) { + QModelIndex childIndex = sourceModel()->index(nChild, 0, index); if (!childIndex.isValid()) - { break; - } retVal = ShowThis(childIndex); if (retVal) - { break; - } } - } - else - { + } else { QModelIndex useIndex = sourceModel()->index(index.row(), 0, index.parent()); QString path = fs->filePath(useIndex); path.replace(QRegExp("\\.gpg$"), ""); @@ -66,7 +56,8 @@ bool StoreModel::ShowThis(const QModelIndex index) const * @param sourceModel * @param passStore */ -void StoreModel::setModelAndStore(QFileSystemModel *sourceModel, QString passStore) { +void StoreModel::setModelAndStore(QFileSystemModel *sourceModel, QString passStore) +{ fs = sourceModel; store = passStore; } diff --git a/trayicon.cpp b/trayicon.cpp index feaa1e9f9..4c1246dcc 100644 --- a/trayicon.cpp +++ b/trayicon.cpp @@ -2,65 +2,61 @@ TrayIcon::TrayIcon(QMainWindow *parent) { - parentwin = parent; + parentwin = parent; - createActions(); - createTrayIcon(); + createActions(); + createTrayIcon(); - sysTrayIcon->setIcon(QIcon(":/artwork/icon.png")); + sysTrayIcon->setIcon(QIcon(":/artwork/icon.png")); - sysTrayIcon->show(); - - QObject::connect(sysTrayIcon, SIGNAL(activated(QSystemTrayIcon::ActivationReason)), - this, SLOT(iconActivated(QSystemTrayIcon::ActivationReason))); + sysTrayIcon->show(); + QObject::connect(sysTrayIcon, SIGNAL(activated(QSystemTrayIcon::ActivationReason)), + this, SLOT(iconActivated(QSystemTrayIcon::ActivationReason))); } void TrayIcon::setVisible(bool visible) { - if(visible == true) { - parentwin->show(); - } else { - parentwin->hide(); - } + if (visible == true) + parentwin->show(); + else + parentwin->hide(); } void TrayIcon::createActions() { -// minimizeAction = new QAction(tr("Mi&nimize"), this); -// connect(minimizeAction, SIGNAL(triggered()), this, SLOT(hide())); +// minimizeAction = new QAction(tr("Mi&nimize"), this); +// connect(minimizeAction, SIGNAL(triggered()), this, SLOT(hide())); -// maximizeAction = new QAction(tr("Ma&ximize"), this); -// connect(maximizeAction, SIGNAL(triggered()), this, SLOT(showMaximized())); +// maximizeAction = new QAction(tr("Ma&ximize"), this); +// connect(maximizeAction, SIGNAL(triggered()), this, SLOT(showMaximized())); -// restoreAction = new QAction(tr("&Restore"), this); -// connect(restoreAction, SIGNAL(triggered()), this, SLOT(showNormal())); +// restoreAction = new QAction(tr("&Restore"), this); +// connect(restoreAction, SIGNAL(triggered()), this, SLOT(showNormal())); - quitAction = new QAction(tr("&Quit"), this); - connect(quitAction, SIGNAL(triggered()), qApp, SLOT(quit())); + quitAction = new QAction(tr("&Quit"), this); + connect(quitAction, SIGNAL(triggered()), qApp, SLOT(quit())); } - void TrayIcon::createTrayIcon() { - trayIconMenu = new QMenu(this); -// trayIconMenu->addAction(minimizeAction); -// trayIconMenu->addAction(maximizeAction); -// trayIconMenu->addAction(restoreAction); -// trayIconMenu->addSeparator(); - trayIconMenu->addAction(quitAction); - - sysTrayIcon = new QSystemTrayIcon(this); - sysTrayIcon->setContextMenu(trayIconMenu); + trayIconMenu = new QMenu(this); +// trayIconMenu->addAction(minimizeAction); +// trayIconMenu->addAction(maximizeAction); +// trayIconMenu->addAction(restoreAction); +// trayIconMenu->addSeparator(); + trayIconMenu->addAction(quitAction); + + sysTrayIcon = new QSystemTrayIcon(this); + sysTrayIcon->setContextMenu(trayIconMenu); } void TrayIcon::showHideParent() { - if(parentwin->isVisible() == true) { - parentwin->hide(); - } else { - parentwin->show(); - } + if (parentwin->isVisible() == true) + parentwin->hide(); + else + parentwin->show(); } void TrayIcon::iconActivated(QSystemTrayIcon::ActivationReason reason) @@ -68,7 +64,7 @@ void TrayIcon::iconActivated(QSystemTrayIcon::ActivationReason reason) switch (reason) { case QSystemTrayIcon::Trigger: case QSystemTrayIcon::DoubleClick: - showHideParent(); + showHideParent(); break; case QSystemTrayIcon::MiddleClick: showMessage("test", "test msg", 1000); diff --git a/trayicon.h b/trayicon.h index b05cf768a..3dde72abe 100644 --- a/trayicon.h +++ b/trayicon.h @@ -26,8 +26,8 @@ public slots: void createActions(); void createTrayIcon(); -// QAction *minimizeAction; -// QAction *maximizeAction; +// QAction *minimizeAction; +// QAction *maximizeAction; QAction *settingsAction; QAction *quitAction; diff --git a/usersdialog.cpp b/usersdialog.cpp index ffc4d9962..711833dfe 100644 --- a/usersdialog.cpp +++ b/usersdialog.cpp @@ -10,7 +10,8 @@ UsersDialog::UsersDialog(QWidget *parent) : ui->setupUi(this); connect(ui->buttonBox, SIGNAL(accepted()), this, SLOT(accept())); connect(ui->buttonBox, SIGNAL(rejected()), this, SLOT(reject())); - connect(ui->listWidget, SIGNAL(itemChanged(QListWidgetItem *)), this, SLOT(itemChange(QListWidgetItem *))); + connect(ui->listWidget, SIGNAL(itemChanged(QListWidgetItem *)), this, + SLOT(itemChange(QListWidgetItem *))); userList = NULL; } @@ -45,25 +46,25 @@ void UsersDialog::populateList(const QString &filter) for (QList::iterator it = userList->begin(); it != userList->end(); ++it) { UserInfo &user(*it); if (filter.isEmpty() || nameFilter.exactMatch(user.name)) { - if (user.validity == '-' && !ui->checkBox->isChecked()) { + if (user.validity == '-' && !ui->checkBox->isChecked()) continue; - } - if (user.expiry.toTime_t() > 0 && user.expiry.daysTo(QDateTime::currentDateTime()) > 0 && !ui->checkBox->isChecked()) { + if (user.expiry.toTime_t() > 0 + && user.expiry.daysTo(QDateTime::currentDateTime()) > 0 + && !ui->checkBox->isChecked()) continue; - } QString userText = user.name + "\n" + user.key_id; if (user.created.toTime_t() > 0) { - userText += " " + tr("created") + " " + user.created.toString(Qt::SystemLocaleShortDate); - - } - if (user.expiry.toTime_t() > 0) { - userText += " " + tr("expires") + " " + user.expiry.toString(Qt::SystemLocaleShortDate); + userText += " " + tr("created") + " " + user.created.toString( + Qt::SystemLocaleShortDate); } + if (user.expiry.toTime_t() > 0) + userText += " " + tr("expires") + " " + user.expiry.toString( + Qt::SystemLocaleShortDate); QListWidgetItem *item = new QListWidgetItem(userText, ui->listWidget); item->setCheckState(user.enabled ? Qt::Checked : Qt::Unchecked); item->setData(Qt::UserRole, QVariant::fromValue(&user)); if (user.have_secret) { - //item->setForeground(QColor(32, 74, 135)); + // item->setForeground(QColor(32, 74, 135)); item->setForeground(Qt::blue); QFont font; font.setFamily(font.defaultFamily()); @@ -72,7 +73,8 @@ void UsersDialog::populateList(const QString &filter) } else if (user.validity == '-') { item->setBackground(QColor(164, 0, 0)); item->setForeground(Qt::white); - } else if (user.expiry.toTime_t() > 0 && user.expiry.daysTo(QDateTime::currentDateTime()) > 0) { + } else if (user.expiry.toTime_t() > 0 + && user.expiry.daysTo(QDateTime::currentDateTime()) > 0) { item->setForeground(QColor(164, 0, 0)); } @@ -93,11 +95,13 @@ void UsersDialog::on_lineEdit_textChanged(const QString &filter) populateList(filter); } -void UsersDialog::closeEvent(QCloseEvent *event) { +void UsersDialog::closeEvent(QCloseEvent *event) +{ // TODO save window size or somethign event->accept(); } -void UsersDialog::on_checkBox_clicked() { +void UsersDialog::on_checkBox_clicked() +{ populateList(ui->lineEdit->text()); } diff --git a/usersdialog.h b/usersdialog.h index 5f3793be6..326af5b6a 100644 --- a/usersdialog.h +++ b/usersdialog.h @@ -14,7 +14,12 @@ class UsersDialog; class QListWidgetItem; struct UserInfo { - UserInfo() : validity('-'), have_secret(false), enabled(false) {} + UserInfo() : validity('-'), + have_secret(false), + enabled(false) + { + } + QString name; QString key_id; char validity; diff --git a/util.cpp b/util.cpp index 5b2dd1e41..498a08636 100644 --- a/util.cpp +++ b/util.cpp @@ -23,12 +23,10 @@ void Util::initialiseEnvironment() QString path = _env.value("PATH"); if (!path.contains("/usr/local/MacGPG2/bin") - && QFile("/usr/local/MacGPG2/bin").exists()) { + && QFile("/usr/local/MacGPG2/bin").exists()) path += ":/usr/local/MacGPG2/bin"; - } - if (!path.contains("/usr/local/bin")) { + if (!path.contains("/usr/local/bin")) path += ":/usr/local/bin"; - } _env.insert("PATH", path); #endif _envInitialised = true; @@ -48,10 +46,10 @@ QString Util::findPasswordStore() } else { #ifdef Q_OS_WIN path = QDir::homePath() + QDir::separator() - + "password-store" + QDir::separator(); + + "password-store" + QDir::separator(); #else path = QDir::homePath() + QDir::separator() - + ".password-store" + QDir::separator(); + + ".password-store" + QDir::separator(); #endif } return Util::normalizeFolderPath(path); @@ -62,14 +60,13 @@ QString Util::findPasswordStore() * @param path * @return */ -QString Util::normalizeFolderPath(QString path) { - if (!path.endsWith("/") && !path.endsWith(QDir::separator())) { +QString Util::normalizeFolderPath(QString path) +{ + if (!path.endsWith("/") && !path.endsWith(QDir::separator())) path += QDir::separator(); - } return path; } - QString Util::findBinaryInPath(QString binary) { initialiseEnvironment(); @@ -86,22 +83,21 @@ QString Util::findBinaryInPath(QString binary) entries = path.split(':'); if (entries.length() < 2) { #endif - entries = path.split(';'); + entries = path.split(';'); #ifndef Q_OS_WIN - } + } #endif - foreach(QString entry, entries) { + foreach (QString entry, entries) { QScopedPointer qfi(new QFileInfo(entry.append(binary))); #ifdef Q_OS_WIN - if (!qfi->exists()) { + if (!qfi->exists()) qfi.reset(new QFileInfo(entry.append(".exe"))); - } + #endif qDebug() << entry; - if (!qfi->isExecutable()) { + if (!qfi->isExecutable()) continue; - } ret = qfi->absoluteFilePath(); break; @@ -121,20 +117,21 @@ QString Util::findBinaryInPath(QString binary) bool Util::checkConfig(QString passStore, QString passExecutable, QString gpgExecutable) { return !QFile(passStore + ".gpg-id").exists() - || (!QFile(passExecutable).exists() && !QFile(gpgExecutable).exists()); + || (!QFile(passExecutable).exists() && !QFile(gpgExecutable).exists()); } - /** * @brief Util::qSleep * @param ms */\ -void Util::qSleep(int ms) + void Util::qSleep(int ms) { #ifdef Q_OS_WIN Sleep(uint(ms)); #else - struct timespec ts = { ms / 1000, (ms % 1000) * 1000 * 1000 }; + struct timespec ts = { + ms / 1000, (ms % 1000) * 1000 * 1000 + }; nanosleep(&ts, NULL); #endif } From 3e2246bce7a2ea6f03b75316e7ac1fe78a1fcbb9 Mon Sep 17 00:00:00 2001 From: Anne Jan Brouwer Date: Tue, 24 Nov 2015 00:12:22 +0100 Subject: [PATCH 05/13] md lint --- CONTRIBUTING.md | 8 +++++--- FAQ.md | 33 ++++++++++++++++++++++++--------- README.md | 31 +++++++++++++++++++++++-------- 3 files changed, 52 insertions(+), 20 deletions(-) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 150ba07a7..76ccd97b8 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -10,11 +10,13 @@ This document is stil in a very early stage and needs a lot more work. ## Translations -* Add you language to the `qtpass.pro` file under TRANSLATIONS and in the `resources.qrc` file. +* Add you language to the `qtpass.pro` file + under TRANSLATIONS and in the `resources.qrc` file. * Next run the command `lupdate qtpass.pro` which will create the localization files. -* Edit your file with (let's imagine your language is sv_SE (Swedish) `linguist localization/localization_sv_SE.ts` +* Edit your file with (let's imagine your language is sv_SE (Swedish) + `linguist localization/localization_sv_SE.ts` -Qt Linguist has very nice in-context translation options https://doc-snapshots.qt.io/qt5-5.6/linguist-translators.html +Qt Linguist has very nice in-context translation options [for translators](https://doc-snapshots.qt.io/qt5-5.6/linguist-translators.html) ## IRC diff --git a/FAQ.md b/FAQ.md index 3fbdd1c49..55e53a465 100644 --- a/FAQ.md +++ b/FAQ.md @@ -1,14 +1,18 @@ -#FAQ +# FAQ ## Issues ### Can't save a password -* Is folder initialised? Easiest way is to use the [Users] button and make sure you can encrypt for someone (eg. yourself) + +* Is folder initialised? Easiest way is to use the [Users] button + and make sure you can encrypt for someone (eg. yourself) * Are you using git? If not, make sure it is switched off. ### I have an issue with GNOME keyring + * Disable GNOME keyring * Create a `~/.gnupg/gpg-agent.conf` containing: + ``` enable-ssh-support write-env-file @@ -17,7 +21,8 @@ default-cache-ttl 600 max-cache-ttl 7200 ``` -Also, the following is useful to add to your .bashrc if you are using Yubikey NEO on Ubuntu: +Also, the following is useful to add to +your .bashrc if you are using Yubikey NEO on Ubuntu: ``` # OpenPGP applet support for YubiKey NEO @@ -31,28 +36,38 @@ fi * More info: [issue 60](https://github.com/IJHack/qtpass/issues/60) and [issue 73](https://github.com/IJHack/qtpass/issues/73) ### I don't get a passphrase / PIN dialog -* You'll need to install pinentry-qt (or -qt4 or -qt5 or even -gtk) and possibly set the full path to that executable in your `~/.gnupg/gpg-agent.conf` for example: `pinentry-program /usr/bin/pinentry-qt4` -* On some esotheric systems it might be necessary to create a symbolic link `/usr/bin/pinentry` to your pinentry application of choice eg: `ln -s /usr/bin/pinentry-qt5 /usr/bin/pinentry` + +* You'll need to install pinentry-qt (or -qt4 or -qt5 or even -gtk) and + possibly set the full path to that executable in your `~/.gnupg/gpg-agent.conf` + for example: `pinentry-program /usr/bin/pinentry-qt4` +* On some esotheric systems it might be necessary to create a symbolic + link `/usr/bin/pinentry` to your pinentry application of choice + eg: `ln -s /usr/bin/pinentry-qt5 /usr/bin/pinentry` ### Where can I ask for help? + * Create an [issue](https://github.com/IJHack/qtpass/) issues on github. * Send an email to [help@qtpass.org](help@qtpass.org) ### Can I import from KeePass, LastPass or X? -* Yes, check [passwordstore.org/#migration](http://www.passwordstore.org/#migration) for more info. + +* Yes, check [passwordstore.org/#migration](http://www.passwordstore.org/#migration) + for more info. ### I don't like the design, what gives? + * It's all on github, clone, change and send a pull request. * Open an issue and point out defects or better yet propose changes. ## How can I help improve QtPass? -###I would like to donate! +### I would like to donate! * Time: * Read [contributing](CONTRIBUTING.md) documentation. * Fork, clone hack and send a pull request. * Find an [issue](https://github.com/IJHack/qtpass/issues) to work on.. - * Participate in our bug bounty, you submit an issue and help us fix it, I send you a bounty. + * Participate in our bug bounty, you submit an issue and help us + fix it, I send you a bounty. * Money: -IJhack takes donations in [bitcoin](https://blockchain.info/address/146dqz8zXn9iNZMv5s7JVqwZKjrmumHBfb) + * IJhack takes donations in [bitcoin](https://blockchain.info/address/146dqz8zXn9iNZMv5s7JVqwZKjrmumHBfb) diff --git a/README.md b/README.md index d98eb10ed..ea3e7a768 100644 --- a/README.md +++ b/README.md @@ -1,29 +1,37 @@ -QtPass [![Build Status](https://travis-ci.org/IJHack/qtpass.svg?branch=master)](https://travis-ci.org/IJHack/qtpass) [![Build status](https://ci.appveyor.com/api/projects/status/9rjnj72rdir7u9eg/branch/master?svg=true)](https://ci.appveyor.com/project/annejan/qtpass/branch/master) +QtPass ====== -QtPass is a GUI for [pass](http://www.passwordstore.org/), the standard unix password manager. +[![Build Status](https://travis-ci.org/IJHack/qtpass.svg?branch=master)](https://travis-ci.org/IJHack/qtpass) +[![Build status](https://ci.appveyor.com/api/projects/status/9rjnj72rdir7u9eg/branch/master?svg=true)](https://ci.appveyor.com/project/annejan/qtpass/branch/master) +[![Coverity scan](https://scan.coverity.com/projects/5266/badge.svg)](https://scan.coverity.com/projects/ijhack-qtpass) + +QtPass is a GUI for [pass](http://www.passwordstore.org/), +the standard unix password manager. Features -------- + * Using pass or git and gpg2 directly * Configurable shoulder surfing protection options * Cross platform: Linux, BSD, OS X and Windows * Per-folder user selection for multi recipient encryption * Multiple profiles -Logo based on https://commons.wikimedia.org/wiki/File:Heart-padlock.svg by AnonMoos. +Logo based on [Heart-padlock by AnonMoos](https://commons.wikimedia.org/wiki/File:Heart-padlock.svg). Installation ------------ + On most systems all you need is: `qmake && make && make install` On Mac OS X: `qmake && make && macdeployqt QtPass.app` -* Currently seems to only work with MacGPG2 +Currently seems to only work with MacGPG2 Security considerations ----------------------- + Using this program will not magically keep your passwords secure against compromised computers even if you use it in combination with a smartcard. @@ -39,6 +47,7 @@ it installed (or at least one that knows how to use a smartcard). To get better protection out of use with a smartcard even against a targeted attack I can think of at least two options: + * The smartcard must require explicit confirmation for each decryption operation. Or if it just provides a counter for decrypted data you could at least notice an attack afterwards, though at quite some effort on your part. @@ -51,22 +60,28 @@ attack I can think of at least two options: Known issues ------------ -* Filtering (searching) breaks the tree/model sometimes -* Starting without a correctly set password-store folder give weird results in the tree view + +* Filtering (searching) breaks the tree/model sometimes +* Starting without a correctly set password-store folder + gives weird results in the tree view * On Mac OS X only the gpgtools MacGPG2 version works with passphrase or PIN Planned features ---------------- + * Re-encryption after users-change (optional of course) * Plugins based on field name, plugins follow same format as password files * Colour coding folders (possibly disabling folders you can't decrypt) * WebDAV (configuration) support * Optional table view of decrypted folder contents -* Opening of (basic auth) urls in default browser? Possibly with helper plugin for filling out forms? -* Some other form of remote storage that allows for accountability / auditing (web API to retrieve the .gpg files?) +* Opening of (basic auth) urls in default browser? + Possibly with helper plugin for filling out forms? +* Some other form of remote storage that allows for + accountability / auditing (web API to retrieve the .gpg files?) Further reading --------------- + [FAQ](FAQ.md) and [CONTRIBUTING](CONTRIBUTING.md) documentation. [Documentation](https://qtpass.org/) From b0f0b21bd33f6f9215f44c10da1d12c03704b418 Mon Sep 17 00:00:00 2001 From: Anne Jan Brouwer Date: Tue, 24 Nov 2015 00:16:36 +0100 Subject: [PATCH 06/13] clang-format --- configdialog.cpp | 856 ++++++------- configdialog.h | 175 ++- keygendialog.cpp | 183 ++- keygendialog.h | 31 +- main.cpp | 79 +- mainwindow.cpp | 2717 ++++++++++++++++++++--------------------- mainwindow.h | 264 ++-- passworddialog.cpp | 189 ++- passworddialog.h | 37 +- progressindicator.cpp | 147 +-- progressindicator.h | 136 ++- singleapplication.cpp | 94 +- singleapplication.h | 25 +- storemodel.cpp | 90 +- storemodel.h | 19 +- trayicon.cpp | 107 +- trayicon.h | 33 +- usersdialog.cpp | 155 ++- usersdialog.h | 49 +- util.cpp | 125 +- util.h | 19 +- 21 files changed, 2637 insertions(+), 2893 deletions(-) diff --git a/configdialog.cpp b/configdialog.cpp index 6d61db86d..bc6a3f125 100644 --- a/configdialog.cpp +++ b/configdialog.cpp @@ -13,440 +13,377 @@ * @brief ConfigDialog::ConfigDialog * @param parent */ -ConfigDialog::ConfigDialog(MainWindow *parent) : - QDialog(parent), - ui(new Ui::ConfigDialog) -{ - mainWindow = parent; - ui->setupUi(this); - ui->profileTable->verticalHeader()->hide(); - ui->profileTable->horizontalHeader()->setStretchLastSection(true); - ui->label->setText(ui->label->text() + VERSION); - ui->comboBoxClipboard->clear(); +ConfigDialog::ConfigDialog(MainWindow *parent) + : QDialog(parent), ui(new Ui::ConfigDialog) { + mainWindow = parent; + ui->setupUi(this); + ui->profileTable->verticalHeader()->hide(); + ui->profileTable->horizontalHeader()->setStretchLastSection(true); + ui->label->setText(ui->label->text() + VERSION); + ui->comboBoxClipboard->clear(); - ui->comboBoxClipboard->addItem(tr("No Clipboard")); - ui->comboBoxClipboard->addItem(tr("Always copy to clipboard")); - ui->comboBoxClipboard->addItem(tr("On-demand copy to clipboard")); - ui->comboBoxClipboard->setCurrentIndex(0); + ui->comboBoxClipboard->addItem(tr("No Clipboard")); + ui->comboBoxClipboard->addItem(tr("Always copy to clipboard")); + ui->comboBoxClipboard->addItem(tr("On-demand copy to clipboard")); + ui->comboBoxClipboard->setCurrentIndex(0); } /** * @brief ConfigDialog::~ConfigDialog */ -ConfigDialog::~ConfigDialog() -{ - mainWindow->setGitExecutable(ui->gitPath->text()); - mainWindow->setGpgExecutable(ui->gpgPath->text()); - mainWindow->setPassExecutable(ui->passPath->text()); +ConfigDialog::~ConfigDialog() { + mainWindow->setGitExecutable(ui->gitPath->text()); + mainWindow->setGpgExecutable(ui->gpgPath->text()); + mainWindow->setPassExecutable(ui->passPath->text()); } /** * @brief ConfigDialog::setPassPath * @param path */ -void ConfigDialog::setPassPath(QString path) -{ - ui->passPath->setText(path); -} +void ConfigDialog::setPassPath(QString path) { ui->passPath->setText(path); } /** * @brief ConfigDialog::setGitPath * @param path */ -void ConfigDialog::setGitPath(QString path) -{ - ui->gitPath->setText(path); - if (path.isEmpty()) { - useGit(false); - ui->checkBoxUseGit->setEnabled(false); - } else { - ui->checkBoxUseGit->setEnabled(true); - } +void ConfigDialog::setGitPath(QString path) { + ui->gitPath->setText(path); + if (path.isEmpty()) { + useGit(false); + ui->checkBoxUseGit->setEnabled(false); + } else { + ui->checkBoxUseGit->setEnabled(true); + } } /** * @brief ConfigDialog::setGpgPath * @param path */ -void ConfigDialog::setGpgPath(QString path) -{ - ui->gpgPath->setText(path); -} +void ConfigDialog::setGpgPath(QString path) { ui->gpgPath->setText(path); } /** * @brief ConfigDialog::setStorePath * @param path */ -void ConfigDialog::setStorePath(QString path) -{ - ui->storePath->setText(path); -} +void ConfigDialog::setStorePath(QString path) { ui->storePath->setText(path); } /** * @brief ConfigDialog::getPassPath * @return */ -QString ConfigDialog::getPassPath() -{ - return ui->passPath->text(); -} +QString ConfigDialog::getPassPath() { return ui->passPath->text(); } /** * @brief ConfigDialog::getGitPath * @return */ -QString ConfigDialog::getGitPath() -{ - return ui->gitPath->text(); -} +QString ConfigDialog::getGitPath() { return ui->gitPath->text(); } /** * @brief ConfigDialog::getGpgPath * @return */ -QString ConfigDialog::getGpgPath() -{ - return ui->gpgPath->text(); -} +QString ConfigDialog::getGpgPath() { return ui->gpgPath->text(); } /** * @brief ConfigDialog::getStorePath * @return */ -QString ConfigDialog::getStorePath() -{ - return ui->storePath->text(); -} +QString ConfigDialog::getStorePath() { return ui->storePath->text(); } /** * @brief ConfigDialog::usePass * @return */ -bool ConfigDialog::usePass() -{ - return ui->radioButtonPass->isChecked(); -} +bool ConfigDialog::usePass() { return ui->radioButtonPass->isChecked(); } /** * @brief ConfigDialog::usePass * @param pass */ -void ConfigDialog::usePass(bool usePass) -{ - if (usePass) { - ui->radioButtonNative->setChecked(false); - ui->radioButtonPass->setChecked(true); - } else { - ui->radioButtonNative->setChecked(true); - ui->radioButtonPass->setChecked(false); - } - setGroupBoxState(); +void ConfigDialog::usePass(bool usePass) { + if (usePass) { + ui->radioButtonNative->setChecked(false); + ui->radioButtonPass->setChecked(true); + } else { + ui->radioButtonNative->setChecked(true); + ui->radioButtonPass->setChecked(false); + } + setGroupBoxState(); } /** * @brief ConfigDialog::on_radioButtonNative_clicked */ -void ConfigDialog::on_radioButtonNative_clicked() -{ - setGroupBoxState(); -} +void ConfigDialog::on_radioButtonNative_clicked() { setGroupBoxState(); } /** * @brief ConfigDialog::on_radioButtonPass_clicked */ -void ConfigDialog::on_radioButtonPass_clicked() -{ - setGroupBoxState(); -} +void ConfigDialog::on_radioButtonPass_clicked() { setGroupBoxState(); } /** * @brief ConfigDialog::setGroupBoxState */ -void ConfigDialog::setGroupBoxState() -{ - if (ui->radioButtonPass->isChecked()) { - ui->groupBoxNative->setEnabled(false); - ui->groupBoxPass->setEnabled(true); - } else { - ui->groupBoxNative->setEnabled(true); - ui->groupBoxPass->setEnabled(false); - } +void ConfigDialog::setGroupBoxState() { + if (ui->radioButtonPass->isChecked()) { + ui->groupBoxNative->setEnabled(false); + ui->groupBoxPass->setEnabled(true); + } else { + ui->groupBoxNative->setEnabled(true); + ui->groupBoxPass->setEnabled(false); + } } /** * @brief ConfigDialog::selectExecutable * @return */ -QString ConfigDialog::selectExecutable() -{ - QFileDialog dialog(this); - dialog.setFileMode(QFileDialog::ExistingFile); - dialog.setOption(QFileDialog::ReadOnly); - if (dialog.exec()) - return dialog.selectedFiles().first(); - else return ""; +QString ConfigDialog::selectExecutable() { + QFileDialog dialog(this); + dialog.setFileMode(QFileDialog::ExistingFile); + dialog.setOption(QFileDialog::ReadOnly); + if (dialog.exec()) + return dialog.selectedFiles().first(); + else + return ""; } /** * @brief ConfigDialog::selectFolder * @return */ -QString ConfigDialog::selectFolder() -{ - QFileDialog dialog(this); - dialog.setFileMode(QFileDialog::Directory); - dialog.setFilter(QDir::NoFilter); - dialog.setOption(QFileDialog::ShowDirsOnly); - if (dialog.exec()) - return dialog.selectedFiles().first(); - else return ""; +QString ConfigDialog::selectFolder() { + QFileDialog dialog(this); + dialog.setFileMode(QFileDialog::Directory); + dialog.setFilter(QDir::NoFilter); + dialog.setOption(QFileDialog::ShowDirsOnly); + if (dialog.exec()) + return dialog.selectedFiles().first(); + else + return ""; } /** * @brief ConfigDialog::on_toolButtonGit_clicked */ -void ConfigDialog::on_toolButtonGit_clicked() -{ - QString git = selectExecutable(); - if (!git.isEmpty()) { - ui->gitPath->setText(git); - ui->checkBoxUseGit->setEnabled(true); - } else { - useGit(false); - ui->checkBoxUseGit->setEnabled(false); - } +void ConfigDialog::on_toolButtonGit_clicked() { + QString git = selectExecutable(); + if (!git.isEmpty()) { + ui->gitPath->setText(git); + ui->checkBoxUseGit->setEnabled(true); + } else { + useGit(false); + ui->checkBoxUseGit->setEnabled(false); + } } /** * @brief ConfigDialog::on_toolButtonGpg_clicked */ -void ConfigDialog::on_toolButtonGpg_clicked() -{ - QString gpg = selectExecutable(); - if (!gpg.isEmpty()) - ui->gpgPath->setText(gpg); +void ConfigDialog::on_toolButtonGpg_clicked() { + QString gpg = selectExecutable(); + if (!gpg.isEmpty()) + ui->gpgPath->setText(gpg); } /** * @brief ConfigDialog::on_toolButtonPass_clicked */ -void ConfigDialog::on_toolButtonPass_clicked() -{ - QString pass = selectExecutable(); - if (!pass.isEmpty()) - ui->passPath->setText(pass); +void ConfigDialog::on_toolButtonPass_clicked() { + QString pass = selectExecutable(); + if (!pass.isEmpty()) + ui->passPath->setText(pass); } /** * @brief ConfigDialog::on_toolButtonStore_clicked */ -void ConfigDialog::on_toolButtonStore_clicked() -{ - QString store = selectFolder(); - if (!store.isEmpty()) // TODO call check - ui->storePath->setText(store); +void ConfigDialog::on_toolButtonStore_clicked() { + QString store = selectFolder(); + if (!store.isEmpty()) // TODO call check + ui->storePath->setText(store); } /** * @brief ConfigDialog::on_comboBoxClipboard_activated */ -void ConfigDialog::on_comboBoxClipboard_activated() -{ - if (ui->comboBoxClipboard->currentIndex() > 0) { - ui->checkBoxAutoclear->setEnabled(true); - ui->checkBoxHidePassword->setEnabled(true); - ui->checkBoxHideContent->setEnabled(true); - if (ui->checkBoxAutoclear->isChecked()) { - ui->spinBoxAutoclearSeconds->setEnabled(true); - ui->labelSeconds->setEnabled(true); - } else { - ui->spinBoxAutoclearSeconds->setEnabled(false); - ui->labelSeconds->setEnabled(false); - } +void ConfigDialog::on_comboBoxClipboard_activated() { + if (ui->comboBoxClipboard->currentIndex() > 0) { + ui->checkBoxAutoclear->setEnabled(true); + ui->checkBoxHidePassword->setEnabled(true); + ui->checkBoxHideContent->setEnabled(true); + if (ui->checkBoxAutoclear->isChecked()) { + ui->spinBoxAutoclearSeconds->setEnabled(true); + ui->labelSeconds->setEnabled(true); } else { - ui->checkBoxAutoclear->setEnabled(false); - ui->spinBoxAutoclearSeconds->setEnabled(false); - ui->labelSeconds->setEnabled(false); - ui->checkBoxHidePassword->setEnabled(false); - ui->checkBoxHideContent->setEnabled(false); + ui->spinBoxAutoclearSeconds->setEnabled(false); + ui->labelSeconds->setEnabled(false); } + } else { + ui->checkBoxAutoclear->setEnabled(false); + ui->spinBoxAutoclearSeconds->setEnabled(false); + ui->labelSeconds->setEnabled(false); + ui->checkBoxHidePassword->setEnabled(false); + ui->checkBoxHideContent->setEnabled(false); + } } /** * @brief ConfigDialog::on_checkBoxAutoclearPanel_clicked */ -void ConfigDialog::on_checkBoxAutoclearPanel_clicked() -{ - if (ui->checkBoxAutoclearPanel->isChecked()) { - ui->spinBoxAutoclearPanelSeconds->setEnabled(true); - ui->labelPanelSeconds->setEnabled(true); - } else { - ui->spinBoxAutoclearPanelSeconds->setEnabled(false); - ui->labelPanelSeconds->setEnabled(false); - } +void ConfigDialog::on_checkBoxAutoclearPanel_clicked() { + if (ui->checkBoxAutoclearPanel->isChecked()) { + ui->spinBoxAutoclearPanelSeconds->setEnabled(true); + ui->labelPanelSeconds->setEnabled(true); + } else { + ui->spinBoxAutoclearPanelSeconds->setEnabled(false); + ui->labelPanelSeconds->setEnabled(false); + } } /** * @brief ConfigDialog::useClipboard */ -void ConfigDialog::useClipboard(MainWindow::clipBoardType useClipboard) -{ - ui->comboBoxClipboard->setCurrentIndex(static_cast(useClipboard)); - on_comboBoxClipboard_activated(); +void ConfigDialog::useClipboard(MainWindow::clipBoardType useClipboard) { + ui->comboBoxClipboard->setCurrentIndex(static_cast(useClipboard)); + on_comboBoxClipboard_activated(); } /** * @brief ConfigDialog::useAutoclear * @param useAutoclear */ -void ConfigDialog::useAutoclear(bool useAutoclear) -{ - ui->checkBoxAutoclear->setChecked(useAutoclear); - on_checkBoxAutoclear_clicked(); +void ConfigDialog::useAutoclear(bool useAutoclear) { + ui->checkBoxAutoclear->setChecked(useAutoclear); + on_checkBoxAutoclear_clicked(); } /** * @brief ConfigDialog::setAutoclear * @param seconds */ -void ConfigDialog::setAutoclear(int seconds) -{ - ui->spinBoxAutoclearSeconds->setValue(seconds); +void ConfigDialog::setAutoclear(int seconds) { + ui->spinBoxAutoclearSeconds->setValue(seconds); } /** * @brief ConfigDialog::useAutoclearPanel * @param useAutoclearPanel */ -void ConfigDialog::useAutoclearPanel(bool useAutoclearPanel) -{ - ui->checkBoxAutoclearPanel->setChecked(useAutoclearPanel); - on_checkBoxAutoclearPanel_clicked(); +void ConfigDialog::useAutoclearPanel(bool useAutoclearPanel) { + ui->checkBoxAutoclearPanel->setChecked(useAutoclearPanel); + on_checkBoxAutoclearPanel_clicked(); } /** * @brief ConfigDialog::setAutoclearPanel * @param seconds */ -void ConfigDialog::setAutoclearPanel(int seconds) -{ - ui->spinBoxAutoclearPanelSeconds->setValue(seconds); +void ConfigDialog::setAutoclearPanel(int seconds) { + ui->spinBoxAutoclearPanelSeconds->setValue(seconds); } /** * @brief ConfigDialog::useClipboard * @return */ -MainWindow::clipBoardType ConfigDialog::useClipboard() -{ - return static_cast(ui->comboBoxClipboard->currentIndex()); +MainWindow::clipBoardType ConfigDialog::useClipboard() { + return static_cast( + ui->comboBoxClipboard->currentIndex()); } /** * @brief ConfigDialog::useAutoclear * @return */ -bool ConfigDialog::useAutoclear() -{ - return ui->checkBoxAutoclear->isChecked(); -} +bool ConfigDialog::useAutoclear() { return ui->checkBoxAutoclear->isChecked(); } /** * @brief ConfigDialog::getAutoclear * @return */ -int ConfigDialog::getAutoclear() -{ - return ui->spinBoxAutoclearSeconds->value(); +int ConfigDialog::getAutoclear() { + return ui->spinBoxAutoclearSeconds->value(); } /** * @brief ConfigDialog::on_checkBoxAutoclear_clicked */ -void ConfigDialog::on_checkBoxAutoclear_clicked() -{ - on_comboBoxClipboard_activated(); +void ConfigDialog::on_checkBoxAutoclear_clicked() { + on_comboBoxClipboard_activated(); } /** * @brief ConfigDialog::useAutoclearPanel * @return */ -bool ConfigDialog::useAutoclearPanel() -{ - return ui->checkBoxAutoclearPanel->isChecked(); +bool ConfigDialog::useAutoclearPanel() { + return ui->checkBoxAutoclearPanel->isChecked(); } /** * @brief ConfigDialog::getAutoclearPanel * @return */ -int ConfigDialog::getAutoclearPanel() -{ - return ui->spinBoxAutoclearPanelSeconds->value(); +int ConfigDialog::getAutoclearPanel() { + return ui->spinBoxAutoclearPanelSeconds->value(); } /** * @brief ConfigDialog::hidePassword * @return */ -bool ConfigDialog::hidePassword() -{ - return ui->checkBoxHidePassword->isChecked(); +bool ConfigDialog::hidePassword() { + return ui->checkBoxHidePassword->isChecked(); } /** * @brief ConfigDialog::hideContent * @return */ -bool ConfigDialog::hideContent() -{ - return ui->checkBoxHideContent->isChecked(); +bool ConfigDialog::hideContent() { + return ui->checkBoxHideContent->isChecked(); } /** * @brief ConfigDialog::hidePassword * @param hidePassword */ -void ConfigDialog::hidePassword(bool hidePassword) -{ - ui->checkBoxHidePassword->setChecked(hidePassword); +void ConfigDialog::hidePassword(bool hidePassword) { + ui->checkBoxHidePassword->setChecked(hidePassword); } /** * @brief ConfigDialog::hideContent * @param hideContent */ -void ConfigDialog::hideContent(bool hideContent) -{ - ui->checkBoxHideContent->setChecked(hideContent); +void ConfigDialog::hideContent(bool hideContent) { + ui->checkBoxHideContent->setChecked(hideContent); } /** * @brief ConfigDialog::addGPGId * @return */ -bool ConfigDialog::addGPGId() -{ - return ui->checkBoxAddGPGId->isChecked(); -} +bool ConfigDialog::addGPGId() { return ui->checkBoxAddGPGId->isChecked(); } /** * @brief ConfigDialog::addGPGId * @param addGPGId */ -void ConfigDialog::addGPGId(bool addGPGId) -{ - ui->checkBoxAddGPGId->setChecked(addGPGId); +void ConfigDialog::addGPGId(bool addGPGId) { + ui->checkBoxAddGPGId->setChecked(addGPGId); } /** * @brief ConfigDialog::genKey * @param QString batch */ -void ConfigDialog::genKey(QString batch, QDialog *dialog) -{ - mainWindow->generateKeyPair(batch, dialog); +void ConfigDialog::genKey(QString batch, QDialog *dialog) { + mainWindow->generateKeyPair(batch, dialog); } /** @@ -454,491 +391,446 @@ void ConfigDialog::genKey(QString batch, QDialog *dialog) * @param profiles * @param profile */ -void ConfigDialog::setProfiles(QHash profiles, QString profile) -{ - // qDebug() << profiles; - if (profiles.contains("")) { - profiles.remove(""); - // remove weird "" key value pairs - } - - ui->profileTable->setRowCount(profiles.count()); - QHashIterator i(profiles); - int n = 0; - while (i.hasNext()) { - i.next(); - if (!i.value().isEmpty() && !i.key().isEmpty()) { - ui->profileTable->setItem(n, 0, new QTableWidgetItem(i.key())); - ui->profileTable->setItem(n, 1, new QTableWidgetItem(i.value())); - // qDebug() << "naam:" + i.key(); - if (i.key() == profile) - ui->profileTable->selectRow(n); - } - n++; +void ConfigDialog::setProfiles(QHash profiles, + QString profile) { + // qDebug() << profiles; + if (profiles.contains("")) { + profiles.remove(""); + // remove weird "" key value pairs + } + + ui->profileTable->setRowCount(profiles.count()); + QHashIterator i(profiles); + int n = 0; + while (i.hasNext()) { + i.next(); + if (!i.value().isEmpty() && !i.key().isEmpty()) { + ui->profileTable->setItem(n, 0, new QTableWidgetItem(i.key())); + ui->profileTable->setItem(n, 1, new QTableWidgetItem(i.value())); + // qDebug() << "naam:" + i.key(); + if (i.key() == profile) + ui->profileTable->selectRow(n); } + n++; + } } /** * @brief ConfigDialog::getProfiles * @return */ -QHash ConfigDialog::getProfiles() -{ - QHash profiles; - // Check? - for (int i = 0; i < ui->profileTable->rowCount(); i++) { - QTableWidgetItem *pathItem = ui->profileTable->item(i, 1); - if (0 != pathItem) { - QTableWidgetItem *item = ui->profileTable->item(i, 0); - if (item == 0) { - qDebug() << "empty name, shoud fix in frontend"; - continue; - } - profiles.insert(item->text(), - pathItem->text()); - } +QHash ConfigDialog::getProfiles() { + QHash profiles; + // Check? + for (int i = 0; i < ui->profileTable->rowCount(); i++) { + QTableWidgetItem *pathItem = ui->profileTable->item(i, 1); + if (0 != pathItem) { + QTableWidgetItem *item = ui->profileTable->item(i, 0); + if (item == 0) { + qDebug() << "empty name, shoud fix in frontend"; + continue; + } + profiles.insert(item->text(), pathItem->text()); } - return profiles; + } + return profiles; } /** * @brief ConfigDialog::on_addButton_clicked */ -void ConfigDialog::on_addButton_clicked() -{ - int n = ui->profileTable->rowCount(); - ui->profileTable->insertRow(n); - ui->profileTable->setItem(n, 1, new QTableWidgetItem(ui->storePath->text())); - ui->profileTable->selectRow(n); - ui->deleteButton->setEnabled(true); +void ConfigDialog::on_addButton_clicked() { + int n = ui->profileTable->rowCount(); + ui->profileTable->insertRow(n); + ui->profileTable->setItem(n, 1, new QTableWidgetItem(ui->storePath->text())); + ui->profileTable->selectRow(n); + ui->deleteButton->setEnabled(true); } /** * @brief ConfigDialog::on_deleteButton_clicked */ -void ConfigDialog::on_deleteButton_clicked() -{ - QSet selectedRows; // we use a set to prevent doubles - QList itemList = ui->profileTable->selectedItems(); - if (itemList.count() == 0) { - QMessageBox::warning(this, tr("No profile selected"), - tr("No profile selected to delete")); - return; - } - QTableWidgetItem *item; - foreach (item, itemList) - selectedRows.insert(item->row()); - // get a list, and sort it big to small - QList rows = selectedRows.toList(); - qSort(rows.begin(), rows.end()); - // now actually do the removing: - foreach (int row, rows) - ui->profileTable->removeRow(row); - if (ui->profileTable->rowCount() < 1) - ui->deleteButton->setEnabled(false); +void ConfigDialog::on_deleteButton_clicked() { + QSet selectedRows; // we use a set to prevent doubles + QList itemList = ui->profileTable->selectedItems(); + if (itemList.count() == 0) { + QMessageBox::warning(this, tr("No profile selected"), + tr("No profile selected to delete")); + return; + } + QTableWidgetItem *item; + foreach (item, itemList) + selectedRows.insert(item->row()); + // get a list, and sort it big to small + QList rows = selectedRows.toList(); + qSort(rows.begin(), rows.end()); + // now actually do the removing: + foreach (int row, rows) + ui->profileTable->removeRow(row); + if (ui->profileTable->rowCount() < 1) + ui->deleteButton->setEnabled(false); } -void ConfigDialog::criticalMessage(const QString &title, const QString &text) -{ - QMessageBox::critical(this, title, text, QMessageBox::Ok, QMessageBox::Ok); +void ConfigDialog::criticalMessage(const QString &title, const QString &text) { + QMessageBox::critical(this, title, text, QMessageBox::Ok, QMessageBox::Ok); } /** * @brief ConfigDialog::wizard */ -void ConfigDialog::wizard() -{ - // mainWindow->checkConfig(); - bool clean = false; - - QString gpg = ui->gpgPath->text(); - // QString gpg = mainWindow->getGpgExecutable(); - if (!QFile(gpg).exists()) { - criticalMessage(tr("GnuPG not found"), - tr( - "Please install GnuPG on your system.
Install gpg using your favorite package manager
or download it from GnuPG.org")); - clean = true; - } - - QStringList names = mainWindow->getSecretKeys(); - qDebug() << names; - if (QFile(gpg).exists() && names.empty()) { - KeygenDialog d(this); - if (!d.exec()) - return; - } - - QString passStore = ui->storePath->text(); - - if (!QFile(passStore).exists()) { - // TODO pass version? - if (QMessageBox::question(this, tr("Create password-store?"), - tr("Would you like to create a password-store at %1?").arg( - passStore), - QMessageBox::Yes | QMessageBox::No) == QMessageBox::Yes) { - QDir().mkdir(passStore); +void ConfigDialog::wizard() { + // mainWindow->checkConfig(); + bool clean = false; + + QString gpg = ui->gpgPath->text(); + // QString gpg = mainWindow->getGpgExecutable(); + if (!QFile(gpg).exists()) { + criticalMessage( + tr("GnuPG not found"), + tr("Please install GnuPG on your system.
Install " + "gpg using your favorite package manager
or download it " + "from GnuPG.org")); + clean = true; + } + + QStringList names = mainWindow->getSecretKeys(); + qDebug() << names; + if (QFile(gpg).exists() && names.empty()) { + KeygenDialog d(this); + if (!d.exec()) + return; + } + + QString passStore = ui->storePath->text(); + + if (!QFile(passStore).exists()) { + // TODO pass version? + if (QMessageBox::question( + this, tr("Create password-store?"), + tr("Would you like to create a password-store at %1?") + .arg(passStore), + QMessageBox::Yes | QMessageBox::No) == QMessageBox::Yes) { + QDir().mkdir(passStore); #ifdef Q_OS_WIN - SetFileAttributes(passStore.toStdWString().c_str(), FILE_ATTRIBUTE_HIDDEN); + SetFileAttributes(passStore.toStdWString().c_str(), + FILE_ATTRIBUTE_HIDDEN); #endif - if (useGit()) - mainWindow->executePassGitInit(); - mainWindow->userDialog(passStore); - } + if (useGit()) + mainWindow->executePassGitInit(); + mainWindow->userDialog(passStore); } + } + if (!QFile(passStore + ".gpg-id").exists()) { + qDebug() << ".gpg-id file does not exist"; + + if (!clean) { + criticalMessage(tr("Password store not initialised"), + tr("The folder %1 doesn't seem to be a password store or " + "is not yet initialised.") + .arg(passStore)); + } + while (!QFile(passStore).exists()) { + on_toolButtonStore_clicked(); + // allow user to cancel + if (passStore == ui->storePath->text()) + return; + passStore = ui->storePath->text(); + } if (!QFile(passStore + ".gpg-id").exists()) { - qDebug() << ".gpg-id file does not exist"; - - if (!clean) { - criticalMessage(tr("Password store not initialised"), - tr( - "The folder %1 doesn't seem to be a password store or is not yet initialised.").arg( - passStore)); - } - while (!QFile(passStore).exists()) { - on_toolButtonStore_clicked(); - // allow user to cancel - if (passStore == ui->storePath->text()) - return; - passStore = ui->storePath->text(); - } - if (!QFile(passStore + ".gpg-id").exists()) { - qDebug() << ".gpg-id file still does not exist :/"; - // appears not to be store - // init yes / no ? - mainWindow->userDialog(passStore); - } + qDebug() << ".gpg-id file still does not exist :/"; + // appears not to be store + // init yes / no ? + mainWindow->userDialog(passStore); } + } } /** * @brief ConfigDialog::useTrayIcon * @return */ -bool ConfigDialog::useTrayIcon() -{ - return ui->checkBoxUseTrayIcon->isChecked(); +bool ConfigDialog::useTrayIcon() { + return ui->checkBoxUseTrayIcon->isChecked(); } /** * @brief ConfigDialog::hideOnClose * @return */ -bool ConfigDialog::hideOnClose() -{ - return ui->checkBoxHideOnClose->isEnabled() && ui->checkBoxHideOnClose->isChecked(); +bool ConfigDialog::hideOnClose() { + return ui->checkBoxHideOnClose->isEnabled() && + ui->checkBoxHideOnClose->isChecked(); } /** * @brief ConfigDialog::useTrayIcon * @param useSystray */ -void ConfigDialog::useTrayIcon(bool useSystray) -{ - ui->checkBoxUseTrayIcon->setChecked(useSystray); - ui->checkBoxHideOnClose->setEnabled(useSystray); - ui->checkBoxStartMinimized->setEnabled(useSystray); - if (!useSystray) { - ui->checkBoxHideOnClose->setChecked(false); - ui->checkBoxStartMinimized->setChecked(false); - } +void ConfigDialog::useTrayIcon(bool useSystray) { + ui->checkBoxUseTrayIcon->setChecked(useSystray); + ui->checkBoxHideOnClose->setEnabled(useSystray); + ui->checkBoxStartMinimized->setEnabled(useSystray); + if (!useSystray) { + ui->checkBoxHideOnClose->setChecked(false); + ui->checkBoxStartMinimized->setChecked(false); + } } /** * @brief ConfigDialog::hideOnClose * @param hideOnClose */ -void ConfigDialog::hideOnClose(bool hideOnClose) -{ - ui->checkBoxHideOnClose->setChecked(hideOnClose); +void ConfigDialog::hideOnClose(bool hideOnClose) { + ui->checkBoxHideOnClose->setChecked(hideOnClose); } /** * @brief ConfigDialog::on_checkBoxUseTrayIcon_clicked */ -void ConfigDialog::on_checkBoxUseTrayIcon_clicked() -{ - if (ui->checkBoxUseTrayIcon->isChecked()) { - ui->checkBoxHideOnClose->setEnabled(true); - ui->checkBoxStartMinimized->setEnabled(true); - } else { - ui->checkBoxStartMinimized->setEnabled(false); - ui->checkBoxHideOnClose->setEnabled(false); - } +void ConfigDialog::on_checkBoxUseTrayIcon_clicked() { + if (ui->checkBoxUseTrayIcon->isChecked()) { + ui->checkBoxHideOnClose->setEnabled(true); + ui->checkBoxStartMinimized->setEnabled(true); + } else { + ui->checkBoxStartMinimized->setEnabled(false); + ui->checkBoxHideOnClose->setEnabled(false); + } } /** * @brief ConfigDialog::closeEvent * @param event */ -void ConfigDialog::closeEvent(QCloseEvent *event) -{ - // TODO save window size or something? - event->accept(); +void ConfigDialog::closeEvent(QCloseEvent *event) { + // TODO save window size or something? + event->accept(); } /** * @brief ConfigDialog::useGit * @param useGit */ -void ConfigDialog::useGit(bool useGit) -{ - ui->checkBoxUseGit->setChecked(useGit); - on_checkBoxUseGit_clicked(); +void ConfigDialog::useGit(bool useGit) { + ui->checkBoxUseGit->setChecked(useGit); + on_checkBoxUseGit_clicked(); } /** * @brief ConfigDialog::useGit * @return */ -bool ConfigDialog::useGit() -{ - return ui->checkBoxUseGit->isChecked(); -} +bool ConfigDialog::useGit() { return ui->checkBoxUseGit->isChecked(); } /** * @brief ConfigDialog::on_checkBoxUseGit_clicked */ -void ConfigDialog::on_checkBoxUseGit_clicked() -{ - ui->checkBoxAddGPGId->setEnabled(ui->checkBoxUseGit->isChecked()); - ui->checkBoxAutoPull->setEnabled(ui->checkBoxUseGit->isChecked()); - ui->checkBoxAutoPush->setEnabled(ui->checkBoxUseGit->isChecked()); +void ConfigDialog::on_checkBoxUseGit_clicked() { + ui->checkBoxAddGPGId->setEnabled(ui->checkBoxUseGit->isChecked()); + ui->checkBoxAutoPull->setEnabled(ui->checkBoxUseGit->isChecked()); + ui->checkBoxAutoPush->setEnabled(ui->checkBoxUseGit->isChecked()); } /** * @brief ConfigDialog::on_toolButtonPwgen_clicked */ -void ConfigDialog::on_toolButtonPwgen_clicked() -{ - QString pwgen = selectExecutable(); - if (!pwgen.isEmpty()) { - ui->pwgenPath->setText(pwgen); - ui->checkBoxUsePwgen->setEnabled(true); - } else { - ui->checkBoxUsePwgen->setEnabled(false); - ui->checkBoxUsePwgen->setChecked(false); - } +void ConfigDialog::on_toolButtonPwgen_clicked() { + QString pwgen = selectExecutable(); + if (!pwgen.isEmpty()) { + ui->pwgenPath->setText(pwgen); + ui->checkBoxUsePwgen->setEnabled(true); + } else { + ui->checkBoxUsePwgen->setEnabled(false); + ui->checkBoxUsePwgen->setChecked(false); + } } /** * @brief ConfigDialog::getPwgenPath * @return */ -QString ConfigDialog::getPwgenPath() -{ - return ui->pwgenPath->text(); -} +QString ConfigDialog::getPwgenPath() { return ui->pwgenPath->text(); } /** * @brief ConfigDialog::setPwgenPath * @param pwgen */ -void ConfigDialog::setPwgenPath(QString pwgen) -{ - ui->pwgenPath->setText(pwgen); - if (pwgen.isEmpty()) { - ui->checkBoxUsePwgen->setChecked(false); - ui->checkBoxUsePwgen->setEnabled(false); - } - on_checkBoxUsePwgen_clicked(); +void ConfigDialog::setPwgenPath(QString pwgen) { + ui->pwgenPath->setText(pwgen); + if (pwgen.isEmpty()) { + ui->checkBoxUsePwgen->setChecked(false); + ui->checkBoxUsePwgen->setEnabled(false); + } + on_checkBoxUsePwgen_clicked(); } /** * @brief ConfigDialog::on_checkBoxUsPwgen_clicked */ -void ConfigDialog::on_checkBoxUsePwgen_clicked() -{ - ui->checkBoxUseSymbols->setEnabled(ui->checkBoxUsePwgen->isChecked()); - ui->lineEditPasswordChars->setEnabled(!ui->checkBoxUsePwgen->isChecked()); - ui->labelPasswordChars->setEnabled(!ui->checkBoxUsePwgen->isChecked()); +void ConfigDialog::on_checkBoxUsePwgen_clicked() { + ui->checkBoxUseSymbols->setEnabled(ui->checkBoxUsePwgen->isChecked()); + ui->lineEditPasswordChars->setEnabled(!ui->checkBoxUsePwgen->isChecked()); + ui->labelPasswordChars->setEnabled(!ui->checkBoxUsePwgen->isChecked()); } /** * @brief ConfigDialog::usePwgen * @param usePwgen */ -void ConfigDialog::usePwgen(bool usePwgen) -{ - if (ui->pwgenPath->text().isEmpty()) - usePwgen = false; - ui->checkBoxUsePwgen->setChecked(usePwgen); - on_checkBoxUsePwgen_clicked(); +void ConfigDialog::usePwgen(bool usePwgen) { + if (ui->pwgenPath->text().isEmpty()) + usePwgen = false; + ui->checkBoxUsePwgen->setChecked(usePwgen); + on_checkBoxUsePwgen_clicked(); } /** * @brief ConfigDialog::useSymbols * @param useSymbols */ -void ConfigDialog::useSymbols(bool useSymbols) -{ - ui->checkBoxUseSymbols->setChecked(useSymbols); +void ConfigDialog::useSymbols(bool useSymbols) { + ui->checkBoxUseSymbols->setChecked(useSymbols); } /** * @brief ConfigDialog::setPasswordLength * @param pwLen */ -void ConfigDialog::setPasswordLength(int pwLen) -{ - ui->spinBoxPasswordLength->setValue(pwLen); +void ConfigDialog::setPasswordLength(int pwLen) { + ui->spinBoxPasswordLength->setValue(pwLen); } -void ConfigDialog::setPasswordChars(QString pwChars) -{ - ui->lineEditPasswordChars->setText(pwChars); +void ConfigDialog::setPasswordChars(QString pwChars) { + ui->lineEditPasswordChars->setText(pwChars); } /** * @brief ConfigDialog::usePwgen * @return */ -bool ConfigDialog::usePwgen() -{ - return ui->checkBoxUsePwgen->isChecked(); -} +bool ConfigDialog::usePwgen() { return ui->checkBoxUsePwgen->isChecked(); } /** * @brief ConfigDialog::useSymbols * @return */ -bool ConfigDialog::useSymbols() -{ - return ui->checkBoxUseSymbols->isChecked(); -} +bool ConfigDialog::useSymbols() { return ui->checkBoxUseSymbols->isChecked(); } /** * @brief ConfigDialog::getPasswordLength * @return */ -int ConfigDialog::getPasswordLength() -{ - return ui->spinBoxPasswordLength->value(); +int ConfigDialog::getPasswordLength() { + return ui->spinBoxPasswordLength->value(); } /** * @brief ConfigDialog::getPasswordChars * @return */ -QString ConfigDialog::getPasswordChars() -{ - return ui->lineEditPasswordChars->text(); +QString ConfigDialog::getPasswordChars() { + return ui->lineEditPasswordChars->text(); } /** * @brief ConfigDialog::startMinimized * @return */ -bool ConfigDialog::startMinimized() -{ - return ui->checkBoxStartMinimized->isChecked(); +bool ConfigDialog::startMinimized() { + return ui->checkBoxStartMinimized->isChecked(); } /** * @brief ConfigDialog::startMinimized * @param startMinimized */ -void ConfigDialog::startMinimized(bool startMinimized) -{ - ui->checkBoxStartMinimized->setChecked(startMinimized); +void ConfigDialog::startMinimized(bool startMinimized) { + ui->checkBoxStartMinimized->setChecked(startMinimized); } /** * @brief ConfigDialog::on_checkBoxUseTemplate_clicked */ -void ConfigDialog::on_checkBoxUseTemplate_clicked() -{ - ui->plainTextEditTemplate->setEnabled(ui->checkBoxUseTemplate->isChecked()); - ui->checkBoxTemplateAllFields->setEnabled(ui->checkBoxUseTemplate->isChecked()); +void ConfigDialog::on_checkBoxUseTemplate_clicked() { + ui->plainTextEditTemplate->setEnabled(ui->checkBoxUseTemplate->isChecked()); + ui->checkBoxTemplateAllFields->setEnabled( + ui->checkBoxUseTemplate->isChecked()); } /** * @brief ConfigDialog::useTemplate * @param useTemplate */ -void ConfigDialog::useTemplate(bool useTemplate) -{ - ui->checkBoxUseTemplate->setChecked(useTemplate); - on_checkBoxUseTemplate_clicked(); +void ConfigDialog::useTemplate(bool useTemplate) { + ui->checkBoxUseTemplate->setChecked(useTemplate); + on_checkBoxUseTemplate_clicked(); } /** * @brief ConfigDialog::useTemplate * @return */ -bool ConfigDialog::useTemplate() -{ - return ui->checkBoxUseTemplate->isChecked(); +bool ConfigDialog::useTemplate() { + return ui->checkBoxUseTemplate->isChecked(); } /** * @brief ConfigDialog::setTemplate * @param passTemplate */ -void ConfigDialog::setTemplate(QString passTemplate) -{ - ui->plainTextEditTemplate->setPlainText(passTemplate); +void ConfigDialog::setTemplate(QString passTemplate) { + ui->plainTextEditTemplate->setPlainText(passTemplate); } /** * @brief ConfigDialog::getTemplate * @return */ -QString ConfigDialog::getTemplate() -{ - return ui->plainTextEditTemplate->toPlainText(); +QString ConfigDialog::getTemplate() { + return ui->plainTextEditTemplate->toPlainText(); } /** * @brief ConfigDialog::autoPull * @param autoPull */ -void ConfigDialog::autoPull(bool autoPull) -{ - ui->checkBoxAutoPull->setChecked(autoPull); +void ConfigDialog::autoPull(bool autoPull) { + ui->checkBoxAutoPull->setChecked(autoPull); } /** * @brief ConfigDialog::autoPush * @param autoPush */ -void ConfigDialog::autoPush(bool autoPush) -{ - ui->checkBoxAutoPush->setChecked(autoPush); +void ConfigDialog::autoPush(bool autoPush) { + ui->checkBoxAutoPush->setChecked(autoPush); } /** * @brief ConfigDialog::autoPull * @return */ -bool ConfigDialog::autoPull() -{ - return ui->checkBoxAutoPull->isChecked(); -} +bool ConfigDialog::autoPull() { return ui->checkBoxAutoPull->isChecked(); } /** * @brief ConfigDialog::autoPush * @return */ -bool ConfigDialog::autoPush() -{ - return ui->checkBoxAutoPush->isChecked(); -} +bool ConfigDialog::autoPush() { return ui->checkBoxAutoPush->isChecked(); } /** * @brief ConfigDialog::templateAllFields * @return */ -bool ConfigDialog::templateAllFields() -{ - return ui->checkBoxTemplateAllFields->isChecked(); +bool ConfigDialog::templateAllFields() { + return ui->checkBoxTemplateAllFields->isChecked(); } /** * @brief ConfigDialog::templateAllFields * @param templateAll */ -void ConfigDialog::templateAllFields(bool templateAll) -{ - ui->checkBoxTemplateAllFields->setChecked(templateAll); +void ConfigDialog::templateAllFields(bool templateAll) { + ui->checkBoxTemplateAllFields->setChecked(templateAll); } diff --git a/configdialog.h b/configdialog.h index 7cc2fa123..e6b38ba43 100644 --- a/configdialog.h +++ b/configdialog.h @@ -13,102 +13,101 @@ struct UserInfo; class ConfigDialog; } -class ConfigDialog : public QDialog -{ - Q_OBJECT +class ConfigDialog : public QDialog { + Q_OBJECT public: - explicit ConfigDialog(MainWindow *parent); - ~ConfigDialog(); - void setPassPath(QString); - void setGitPath(QString); - void setGpgPath(QString); - void setStorePath(QString); - void setProfiles(QHash, QString); - void usePass(bool); - void useClipboard(MainWindow::clipBoardType); - void useAutoclear(bool); - void setAutoclear(int); - void useAutoclearPanel(bool); - void setAutoclearPanel(int); - void hidePassword(bool); - void hideContent(bool); - void addGPGId(bool); - QString getPassPath(); - QString getGitPath(); - QString getGpgPath(); - QString getStorePath(); - QHash getProfiles(); - bool usePass(); - MainWindow::clipBoardType useClipboard(); - bool useAutoclear(); - int getAutoclear(); - bool useAutoclearPanel(); - int getAutoclearPanel(); - bool hidePassword(); - bool hideContent(); - bool addGPGId(); - void wizard(); - void genKey(QString, QDialog *); - bool useTrayIcon(); - bool hideOnClose(); - bool startMinimized(); - void useTrayIcon(bool); - void hideOnClose(bool); - void startMinimized(bool); - void useGit(bool); - bool useGit(); - QString getPwgenPath(); - void setPwgenPath(QString); - void usePwgen(bool); - void useSymbols(bool); - void setPasswordLength(int); - void setPasswordChars(QString); - bool usePwgen(); - bool useSymbols(); - int getPasswordLength(); - QString getPasswordChars(); - bool useTemplate(); - void useTemplate(bool); - QString getTemplate(); - void setTemplate(QString); - void templateAllFields(bool); - bool templateAllFields(); - bool autoPull(); - void autoPull(bool); - bool autoPush(); - void autoPush(bool); + explicit ConfigDialog(MainWindow *parent); + ~ConfigDialog(); + void setPassPath(QString); + void setGitPath(QString); + void setGpgPath(QString); + void setStorePath(QString); + void setProfiles(QHash, QString); + void usePass(bool); + void useClipboard(MainWindow::clipBoardType); + void useAutoclear(bool); + void setAutoclear(int); + void useAutoclearPanel(bool); + void setAutoclearPanel(int); + void hidePassword(bool); + void hideContent(bool); + void addGPGId(bool); + QString getPassPath(); + QString getGitPath(); + QString getGpgPath(); + QString getStorePath(); + QHash getProfiles(); + bool usePass(); + MainWindow::clipBoardType useClipboard(); + bool useAutoclear(); + int getAutoclear(); + bool useAutoclearPanel(); + int getAutoclearPanel(); + bool hidePassword(); + bool hideContent(); + bool addGPGId(); + void wizard(); + void genKey(QString, QDialog *); + bool useTrayIcon(); + bool hideOnClose(); + bool startMinimized(); + void useTrayIcon(bool); + void hideOnClose(bool); + void startMinimized(bool); + void useGit(bool); + bool useGit(); + QString getPwgenPath(); + void setPwgenPath(QString); + void usePwgen(bool); + void useSymbols(bool); + void setPasswordLength(int); + void setPasswordChars(QString); + bool usePwgen(); + bool useSymbols(); + int getPasswordLength(); + QString getPasswordChars(); + bool useTemplate(); + void useTemplate(bool); + QString getTemplate(); + void setTemplate(QString); + void templateAllFields(bool); + bool templateAllFields(); + bool autoPull(); + void autoPull(bool); + bool autoPush(); + void autoPush(bool); protected: - void closeEvent(QCloseEvent *event); + void closeEvent(QCloseEvent *event); private slots: - void on_radioButtonNative_clicked(); - void on_radioButtonPass_clicked(); - void on_toolButtonGit_clicked(); - void on_toolButtonGpg_clicked(); - void on_toolButtonPwgen_clicked(); - void on_toolButtonPass_clicked(); - void on_toolButtonStore_clicked(); - void on_comboBoxClipboard_activated(); - void on_checkBoxAutoclear_clicked(); - void on_checkBoxAutoclearPanel_clicked(); - void on_addButton_clicked(); - void on_deleteButton_clicked(); - void on_checkBoxUseTrayIcon_clicked(); - void on_checkBoxUseGit_clicked(); - void on_checkBoxUsePwgen_clicked(); - void on_checkBoxUseTemplate_clicked(); + void on_radioButtonNative_clicked(); + void on_radioButtonPass_clicked(); + void on_toolButtonGit_clicked(); + void on_toolButtonGpg_clicked(); + void on_toolButtonPwgen_clicked(); + void on_toolButtonPass_clicked(); + void on_toolButtonStore_clicked(); + void on_comboBoxClipboard_activated(); + void on_checkBoxAutoclear_clicked(); + void on_checkBoxAutoclearPanel_clicked(); + void on_addButton_clicked(); + void on_deleteButton_clicked(); + void on_checkBoxUseTrayIcon_clicked(); + void on_checkBoxUseGit_clicked(); + void on_checkBoxUsePwgen_clicked(); + void on_checkBoxUseTemplate_clicked(); private: - QScopedPointer ui; - void setGroupBoxState(); - QString selectExecutable(); - QString selectFolder(); -// QMessageBox::critical with hack to avoid crashes with -// Qt 5.4.1 when QApplication::exec was not yet called - void criticalMessage(const QString &title, const QString &text); - MainWindow *mainWindow; + QScopedPointer ui; + void setGroupBoxState(); + QString selectExecutable(); + QString selectFolder(); + // QMessageBox::critical with hack to avoid crashes with + // Qt 5.4.1 when QApplication::exec was not yet called + void criticalMessage(const QString &title, const QString &text); + MainWindow *mainWindow; }; #endif // DIALOG_H diff --git a/keygendialog.cpp b/keygendialog.cpp index 64ae1ca81..6d0cb2635 100644 --- a/keygendialog.cpp +++ b/keygendialog.cpp @@ -4,57 +4,47 @@ #include #include -KeygenDialog::KeygenDialog(ConfigDialog *parent) : - QDialog(parent), - ui(new Ui::KeygenDialog) -{ - ui->setupUi(this); - dialog = parent; +KeygenDialog::KeygenDialog(ConfigDialog *parent) + : QDialog(parent), ui(new Ui::KeygenDialog) { + ui->setupUi(this); + dialog = parent; } -KeygenDialog::~KeygenDialog() -{ - delete ui; -} +KeygenDialog::~KeygenDialog() { delete ui; } -void KeygenDialog::on_passphrase1_textChanged(const QString &arg1) -{ - if (ui->passphrase1->text() == ui->passphrase2->text()) { - ui->buttonBox->setEnabled(true); - replace("Passphrase", arg1); - if (arg1 == "") - no_protection(true); - else - no_protection(false); - } else { - ui->buttonBox->setEnabled(false); - } +void KeygenDialog::on_passphrase1_textChanged(const QString &arg1) { + if (ui->passphrase1->text() == ui->passphrase2->text()) { + ui->buttonBox->setEnabled(true); + replace("Passphrase", arg1); + if (arg1 == "") + no_protection(true); + else + no_protection(false); + } else { + ui->buttonBox->setEnabled(false); + } } -void KeygenDialog::on_passphrase2_textChanged(const QString &arg1) -{ - on_passphrase1_textChanged(arg1); +void KeygenDialog::on_passphrase2_textChanged(const QString &arg1) { + on_passphrase1_textChanged(arg1); } -void KeygenDialog::on_checkBox_stateChanged(int arg1) -{ - if (arg1) { - ui->plainTextEdit->setReadOnly(false); - ui->plainTextEdit->setEnabled(true); - } else { - ui->plainTextEdit->setReadOnly(true); - ui->plainTextEdit->setEnabled(false); - } +void KeygenDialog::on_checkBox_stateChanged(int arg1) { + if (arg1) { + ui->plainTextEdit->setReadOnly(false); + ui->plainTextEdit->setEnabled(true); + } else { + ui->plainTextEdit->setReadOnly(true); + ui->plainTextEdit->setEnabled(false); + } } -void KeygenDialog::on_email_textChanged(const QString &arg1) -{ - replace("Name-Email", arg1); +void KeygenDialog::on_email_textChanged(const QString &arg1) { + replace("Name-Email", arg1); } -void KeygenDialog::on_name_textChanged(const QString &arg1) -{ - replace("Name-Real", arg1); +void KeygenDialog::on_name_textChanged(const QString &arg1) { + replace("Name-Real", arg1); } /** @@ -62,80 +52,77 @@ void KeygenDialog::on_name_textChanged(const QString &arg1) * @param key * @param value */ -void KeygenDialog::replace(QString key, QString value) -{ - QStringList clear; - QString expert = ui->plainTextEdit->toPlainText(); - QStringList lines = expert.split(QRegExp("[\r\n]"), QString::SkipEmptyParts); - foreach (QString line, lines) { - line.replace(QRegExp(key+":.*"), key + ": " + value); - if (key == "Passphrase") - line.replace("%no-protection", "Passphrase: " + value); - clear.append(line); - } - ui->plainTextEdit->setPlainText(clear.join("\n")); +void KeygenDialog::replace(QString key, QString value) { + QStringList clear; + QString expert = ui->plainTextEdit->toPlainText(); + QStringList lines = expert.split(QRegExp("[\r\n]"), QString::SkipEmptyParts); + foreach (QString line, lines) { + line.replace(QRegExp(key + ":.*"), key + ": " + value); + if (key == "Passphrase") + line.replace("%no-protection", "Passphrase: " + value); + clear.append(line); + } + ui->plainTextEdit->setPlainText(clear.join("\n")); } /** * @brief KeygenDialog::no_protection * @param enable - */\ - void KeygenDialog::no_protection(bool enable) -{ - QStringList clear; - QString expert = ui->plainTextEdit->toPlainText(); - QStringList lines = expert.split(QRegExp("[\r\n]"), QString::SkipEmptyParts); - foreach (QString line, lines) { - bool remove = false; - if (!enable) { - if (line.indexOf("%no-protection") == 0) - remove = true; - } else { - if (line.indexOf("Passphrase") == 0) - line = "%no-protection"; - } - if (!remove) - clear.append(line); + */ +void KeygenDialog::no_protection(bool enable) { + QStringList clear; + QString expert = ui->plainTextEdit->toPlainText(); + QStringList lines = expert.split(QRegExp("[\r\n]"), QString::SkipEmptyParts); + foreach (QString line, lines) { + bool remove = false; + if (!enable) { + if (line.indexOf("%no-protection") == 0) + remove = true; + } else { + if (line.indexOf("Passphrase") == 0) + line = "%no-protection"; } - ui->plainTextEdit->setPlainText(clear.join("\n")); + if (!remove) + clear.append(line); + } + ui->plainTextEdit->setPlainText(clear.join("\n")); } /** * @brief KeygenDialog::done * @param r */ -void KeygenDialog::done(int r) -{ - if (QDialog::Accepted == r) { // ok was pressed - ui->widget->setEnabled(false); - ui->buttonBox->setEnabled(false); - ui->checkBox->setEnabled(false); - ui->plainTextEdit->setEnabled(false); +void KeygenDialog::done(int r) { + if (QDialog::Accepted == r) { // ok was pressed + ui->widget->setEnabled(false); + ui->buttonBox->setEnabled(false); + ui->checkBox->setEnabled(false); + ui->plainTextEdit->setEnabled(false); - QProgressIndicator *pi = new QProgressIndicator(); - pi->startAnimation(); - pi->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding); + QProgressIndicator *pi = new QProgressIndicator(); + pi->startAnimation(); + pi->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding); - ui->frame->hide(); - ui->label->setText(QString( - "This operation can take some minutes.
") - +"We need to generate a lot of random bytes. It is a good idea to perform " - "some other action (type on the keyboard, move the mouse, utilize the " - "disks) during the prime generation; this gives the random number " - "generator a better chance to gain enough entropy."); + ui->frame->hide(); + ui->label->setText( + QString("This operation can take some minutes.
") + + "We need to generate a lot of random bytes. It is a good idea to " + "perform " + "some other action (type on the keyboard, move the mouse, utilize the " + "disks) during the prime generation; this gives the random number " + "generator a better chance to gain enough entropy."); - this->layout()->addWidget(pi); + this->layout()->addWidget(pi); - this->show(); - dialog->genKey(ui->plainTextEdit->toPlainText(), this); - } else { // cancel, close or exc was pressed - QDialog::done(r); - return; - } + this->show(); + dialog->genKey(ui->plainTextEdit->toPlainText(), this); + } else { // cancel, close or exc was pressed + QDialog::done(r); + return; + } } -void KeygenDialog::closeEvent(QCloseEvent *event) -{ - // TODO save window size or somethign - event->accept(); +void KeygenDialog::closeEvent(QCloseEvent *event) { + // TODO save window size or somethign + event->accept(); } diff --git a/keygendialog.h b/keygendialog.h index 4058108ee..0baa4f18c 100644 --- a/keygendialog.h +++ b/keygendialog.h @@ -9,30 +9,29 @@ namespace Ui { class KeygenDialog; } -class KeygenDialog : public QDialog -{ - Q_OBJECT +class KeygenDialog : public QDialog { + Q_OBJECT public: - explicit KeygenDialog(ConfigDialog *parent = 0); - ~KeygenDialog(); + explicit KeygenDialog(ConfigDialog *parent = 0); + ~KeygenDialog(); protected: - void closeEvent(QCloseEvent *event); + void closeEvent(QCloseEvent *event); private slots: - void on_passphrase1_textChanged(const QString &arg1); - void on_passphrase2_textChanged(const QString &arg1); - void on_checkBox_stateChanged(int arg1); - void on_email_textChanged(const QString &arg1); - void on_name_textChanged(const QString &arg1); + void on_passphrase1_textChanged(const QString &arg1); + void on_passphrase2_textChanged(const QString &arg1); + void on_checkBox_stateChanged(int arg1); + void on_email_textChanged(const QString &arg1); + void on_name_textChanged(const QString &arg1); private: - Ui::KeygenDialog *ui; - void replace(QString, QString); - void done(int r); - void no_protection(bool enable); - ConfigDialog *dialog; + Ui::KeygenDialog *ui; + void replace(QString, QString); + void done(int r); + void no_protection(bool enable); + ConfigDialog *dialog; }; #endif // KEYGENDIALOG_H diff --git a/main.cpp b/main.cpp index 2fc6f3bca..9c9c065b0 100644 --- a/main.cpp +++ b/main.cpp @@ -2,50 +2,51 @@ #include #include -int main(int argc, char *argv[]) -{ - // check for stupid apple psid or whatever flag - QString text = ""; - for (int i = 1; i < argc; ++i) { - if (i > 1) - text += " "; - text += argv[i]; - } +int main(int argc, char *argv[]) { + // check for stupid apple psid or whatever flag + QString text = ""; + for (int i = 1; i < argc; ++i) { + if (i > 1) + text += " "; + text += argv[i]; + } #if SINGLE_APP - QString name = qgetenv("USER"); - if (name.isEmpty()) - name = qgetenv("USERNAME"); - SingleApplication app(argc, argv, name + "QtPass"); - if (app.isRunning()) { - if (text.length() > 0) - app.sendMessage(text); - return 0; - } + QString name = qgetenv("USER"); + if (name.isEmpty()) + name = qgetenv("USERNAME"); + SingleApplication app(argc, argv, name + "QtPass"); + if (app.isRunning()) { + if (text.length() > 0) + app.sendMessage(text); + return 0; + } #else - QApplication app(argc, argv); + QApplication app(argc, argv); #endif - QCoreApplication::setOrganizationName("IJHack"); - QCoreApplication::setOrganizationDomain("ijhack.org"); - QCoreApplication::setApplicationName("QtPass"); - QCoreApplication::setApplicationVersion(VERSION); + QCoreApplication::setOrganizationName("IJHack"); + QCoreApplication::setOrganizationDomain("ijhack.org"); + QCoreApplication::setApplicationName("QtPass"); + QCoreApplication::setApplicationVersion(VERSION); - // Setup and load translator for localization - QTranslator translator; - QString locale = QLocale::system().name(); - // locale = "nl_NL"; - // locale = "he_IL"; - // locale = "ar_MA"; - translator.load(QString(":localization/localization_") + locale + QString(".qm")); - app.installTranslator(&translator); - app.setLayoutDirection(QObject::tr("LTR") == "RTL" ? Qt::RightToLeft : Qt::LeftToRight); + // Setup and load translator for localization + QTranslator translator; + QString locale = QLocale::system().name(); + // locale = "nl_NL"; + // locale = "he_IL"; + // locale = "ar_MA"; + translator.load(QString(":localization/localization_") + locale + + QString(".qm")); + app.installTranslator(&translator); + app.setLayoutDirection(QObject::tr("LTR") == "RTL" ? Qt::RightToLeft + : Qt::LeftToRight); - MainWindow w; + MainWindow w; - app.setActiveWindow(&w); - app.setWindowIcon(QIcon(":artwork/icon.png")); - w.setApp(&app); - w.setText(text); - w.show(); - return app.exec(); + app.setActiveWindow(&w); + app.setWindowIcon(QIcon(":artwork/icon.png")); + w.setApp(&app); + w.setText(text); + w.show(); + return app.exec(); } diff --git a/mainwindow.cpp b/mainwindow.cpp index 7d816c34c..fac1a4c2a 100644 --- a/mainwindow.cpp +++ b/mainwindow.cpp @@ -15,7 +15,7 @@ #include #include #ifdef Q_OS_WIN -#define WIN32_LEAN_AND_MEAN/*_KILLING_MACHINE*/ +#define WIN32_LEAN_AND_MEAN /*_KILLING_MACHINE*/ #define WIN32_EXTRA_LEAN #include #include @@ -26,597 +26,588 @@ * @brief MainWindow::MainWindow * @param parent */ -MainWindow::MainWindow(QWidget *parent) : - QMainWindow(parent), - ui(new Ui::MainWindow), - process(new QProcess(this)), - fusedav(this), - keygen(NULL), - tray(NULL) -{ -// connect(process.data(), SIGNAL(readyReadStandardOutput()), this, SLOT(readyRead())); - connect(process.data(), SIGNAL(error(QProcess::ProcessError)), this, - SLOT(processError(QProcess::ProcessError))); - connect(process.data(), SIGNAL(finished(int, QProcess::ExitStatus)), this, - SLOT(processFinished(int, QProcess::ExitStatus))); - ui->setupUi(this); - enableUiElements(true); - wrapperRunning = false; - execQueue = new QQueue; - ui->statusBar->showMessage(tr("Welcome to QtPass %1").arg(VERSION), 2000); - freshStart = true; - startupPhase = true; - if (!checkConfig()) { - // no working config - QApplication::quit(); - } - ui->copyPasswordButton->setEnabled(false); - setClippedPassword(""); - QtPass = NULL; - autoclearTimer = NULL; - QTimer::singleShot(10, this, SLOT(focusInput())); +MainWindow::MainWindow(QWidget *parent) + : QMainWindow(parent), ui(new Ui::MainWindow), process(new QProcess(this)), + fusedav(this), keygen(NULL), tray(NULL) { + // connect(process.data(), SIGNAL(readyReadStandardOutput()), this, + // SLOT(readyRead())); + connect(process.data(), SIGNAL(error(QProcess::ProcessError)), this, + SLOT(processError(QProcess::ProcessError))); + connect(process.data(), SIGNAL(finished(int, QProcess::ExitStatus)), this, + SLOT(processFinished(int, QProcess::ExitStatus))); + ui->setupUi(this); + enableUiElements(true); + wrapperRunning = false; + execQueue = new QQueue; + ui->statusBar->showMessage(tr("Welcome to QtPass %1").arg(VERSION), 2000); + freshStart = true; + startupPhase = true; + if (!checkConfig()) { + // no working config + QApplication::quit(); + } + ui->copyPasswordButton->setEnabled(false); + setClippedPassword(""); + QtPass = NULL; + autoclearTimer = NULL; + QTimer::singleShot(10, this, SLOT(focusInput())); } -void MainWindow::focusInput() -{ - ui->lineEdit->selectAll(); - ui->lineEdit->setFocus(); +void MainWindow::focusInput() { + ui->lineEdit->selectAll(); + ui->lineEdit->setFocus(); } /** * @brief MainWindow::~MainWindow */ -MainWindow::~MainWindow() -{ +MainWindow::~MainWindow() { #ifdef Q_OS_WIN - if (useWebDav) WNetCancelConnection2A(passStore.toUtf8().constData(), 0, 1); + if (useWebDav) + WNetCancelConnection2A(passStore.toUtf8().constData(), 0, 1); #else - if (fusedav.state() == QProcess::Running) { - fusedav.terminate(); - fusedav.waitForFinished(2000); - } + if (fusedav.state() == QProcess::Running) { + fusedav.terminate(); + fusedav.waitForFinished(2000); + } #endif } -QSettings &MainWindow::getSettings() -{ - if (!settings) { - QString portable_ini = QCoreApplication::applicationDirPath() + QDir::separator() - + "qtpass.ini"; - // qDebug() << "Settings file: " + portable_ini; - if (QFile(portable_ini).exists()) { - // qDebug() << "Settings file exists, loading it in"; - settings.reset(new QSettings(portable_ini, QSettings::IniFormat)); - } else { - // qDebug() << "Settings file does not exist, use defaults"; - settings.reset(new QSettings("IJHack", "QtPass")); - } +QSettings &MainWindow::getSettings() { + if (!settings) { + QString portable_ini = QCoreApplication::applicationDirPath() + + QDir::separator() + "qtpass.ini"; + // qDebug() << "Settings file: " + portable_ini; + if (QFile(portable_ini).exists()) { + // qDebug() << "Settings file exists, loading it in"; + settings.reset(new QSettings(portable_ini, QSettings::IniFormat)); + } else { + // qDebug() << "Settings file does not exist, use defaults"; + settings.reset(new QSettings("IJHack", "QtPass")); } - return *settings; + } + return *settings; } -void MainWindow::mountWebDav() -{ +void MainWindow::mountWebDav() { #ifdef Q_OS_WIN - char dst[20] = {0}; - NETRESOURCEA netres; - memset(&netres, 0, sizeof(netres)); - netres.dwType = RESOURCETYPE_DISK; - netres.lpLocalName = 0; - netres.lpRemoteName = webDavUrl.toUtf8().data(); - DWORD size = sizeof(dst); - DWORD r = WNetUseConnectionA( - reinterpret_cast(effectiveWinId()), &netres, webDavPassword.toUtf8().constData(), - webDavUser.toUtf8().constData(), CONNECT_TEMPORARY | CONNECT_INTERACTIVE | CONNECT_REDIRECT, - dst, &size, 0); - if (r == NO_ERROR) { - passStore = dst; - } else { - char message[256] = {0}; - FormatMessageA(FORMAT_MESSAGE_FROM_SYSTEM, 0, r, 0, message, sizeof(message), 0); - ui->textBrowser->setTextColor(Qt::red); - ui->textBrowser->setText(tr( - "Failed to connect WebDAV:\n") + message + " (0x" - + QString::number(r, 16) + ")"); - } + char dst[20] = {0}; + NETRESOURCEA netres; + memset(&netres, 0, sizeof(netres)); + netres.dwType = RESOURCETYPE_DISK; + netres.lpLocalName = 0; + netres.lpRemoteName = webDavUrl.toUtf8().data(); + DWORD size = sizeof(dst); + DWORD r = WNetUseConnectionA( + reinterpret_cast(effectiveWinId()), &netres, + webDavPassword.toUtf8().constData(), webDavUser.toUtf8().constData(), + CONNECT_TEMPORARY | CONNECT_INTERACTIVE | CONNECT_REDIRECT, dst, &size, + 0); + if (r == NO_ERROR) { + passStore = dst; + } else { + char message[256] = {0}; + FormatMessageA(FORMAT_MESSAGE_FROM_SYSTEM, 0, r, 0, message, + sizeof(message), 0); + ui->textBrowser->setTextColor(Qt::red); + ui->textBrowser->setText(tr("Failed to connect WebDAV:\n") + message + + " (0x" + QString::number(r, 16) + ")"); + } #else - fusedav.start( - "fusedav -o nonempty -u \"" + webDavUser + "\" " + webDavUrl + " \"" + passStore + '"'); - fusedav.waitForStarted(); - if (fusedav.state() == QProcess::Running) { - QString pwd = webDavPassword; - bool ok = true; - if (pwd.isEmpty()) { - pwd = QInputDialog::getText(this, tr("QtPass WebDAV password"), - tr( - "Enter password to connect to WebDAV:"), QLineEdit::Password, "", - &ok); - } - if (ok && !pwd.isEmpty()) { - fusedav.write(pwd.toUtf8() + '\n'); - fusedav.closeWriteChannel(); - fusedav.waitForFinished(2000); - } else { - fusedav.terminate(); - } + fusedav.start("fusedav -o nonempty -u \"" + webDavUser + "\" " + webDavUrl + + " \"" + passStore + '"'); + fusedav.waitForStarted(); + if (fusedav.state() == QProcess::Running) { + QString pwd = webDavPassword; + bool ok = true; + if (pwd.isEmpty()) { + pwd = QInputDialog::getText(this, tr("QtPass WebDAV password"), + tr("Enter password to connect to WebDAV:"), + QLineEdit::Password, "", &ok); } - QString error = fusedav.readAllStandardError(); - int prompt = error.indexOf("Password:"); - if (prompt >= 0) - error.remove(0, prompt + 10); - if (fusedav.state() != QProcess::Running) - error = tr("fusedav exited unexpectedly\n") + error; - if (error.size() > 0) { - ui->textBrowser->setTextColor(Qt::red); - ui->textBrowser->setText(tr("Failed to start fusedav to connect WebDAV:\n") + error); + if (ok && !pwd.isEmpty()) { + fusedav.write(pwd.toUtf8() + '\n'); + fusedav.closeWriteChannel(); + fusedav.waitForFinished(2000); + } else { + fusedav.terminate(); } + } + QString error = fusedav.readAllStandardError(); + int prompt = error.indexOf("Password:"); + if (prompt >= 0) + error.remove(0, prompt + 10); + if (fusedav.state() != QProcess::Running) + error = tr("fusedav exited unexpectedly\n") + error; + if (error.size() > 0) { + ui->textBrowser->setTextColor(Qt::red); + ui->textBrowser->setText( + tr("Failed to start fusedav to connect WebDAV:\n") + error); + } #endif } /** * @brief MainWindow::checkConfig */ -bool MainWindow::checkConfig() -{ - QSettings &settings(getSettings()); - - QString version = settings.value("version").toString(); - - if (freshStart) { - settings.beginGroup("mainwindow"); - restoreGeometry(settings.value("geometry", saveGeometry()).toByteArray()); - restoreState(settings.value("savestate", saveState()).toByteArray()); - move(settings.value("pos", pos()).toPoint()); - resize(settings.value("size", size()).toSize()); - QList splitter = ui->splitter->sizes(); - int left = settings.value("splitterLeft", splitter[0]).toInt(); - int right = settings.value("splitterRight", splitter[1]).toInt(); - if (left > 0 || right > 0) { - splitter[0] = left; - splitter[1] = right; - ui->splitter->setSizes(splitter); - } - if (settings.value("maximized", isMaximized()).toBool()) - showMaximized(); - settings.endGroup(); - } - - usePass = (settings.value("usePass") == "true"); - - useClipboard = CLIPBOARD_NEVER; - if (settings.value("useClipboard") == "true" - || settings.value("useClipboard") == "1") - useClipboard = CLIPBOARD_ALWAYS; - else if (settings.value("useClipboard") == "2") - useClipboard = CLIPBOARD_ON_DEMAND; - useAutoclear = (settings.value("useAutoclear") == "true"); - autoclearSeconds = settings.value("autoclearSeconds").toInt(); - useAutoclearPanel = (settings.value("useAutoclearPanel") == "true"); - autoclearPanelSeconds = settings.value("autoclearPanelSeconds").toInt(); - hidePassword = (settings.value("hidePassword") == "true"); - hideContent = (settings.value("hideContent") == "true"); - addGPGId = (settings.value("addGPGId") != "false"); - - passStore = settings.value("passStore").toString(); - if (passStore.isEmpty()) { - passStore = Util::findPasswordStore(); - settings.setValue("passStore", passStore); +bool MainWindow::checkConfig() { + QSettings &settings(getSettings()); + + QString version = settings.value("version").toString(); + + if (freshStart) { + settings.beginGroup("mainwindow"); + restoreGeometry(settings.value("geometry", saveGeometry()).toByteArray()); + restoreState(settings.value("savestate", saveState()).toByteArray()); + move(settings.value("pos", pos()).toPoint()); + resize(settings.value("size", size()).toSize()); + QList splitter = ui->splitter->sizes(); + int left = settings.value("splitterLeft", splitter[0]).toInt(); + int right = settings.value("splitterRight", splitter[1]).toInt(); + if (left > 0 || right > 0) { + splitter[0] = left; + splitter[1] = right; + ui->splitter->setSizes(splitter); } - passStore = Util::normalizeFolderPath(passStore); - - passExecutable = settings.value("passExecutable").toString(); - if (passExecutable.isEmpty()) - passExecutable = Util::findBinaryInPath("pass"); - - gitExecutable = settings.value("gitExecutable").toString(); - if (gitExecutable.isEmpty()) - gitExecutable = Util::findBinaryInPath("git"); - - gpgExecutable = settings.value("gpgExecutable").toString(); - if (gpgExecutable.isEmpty()) - gpgExecutable = Util::findBinaryInPath("gpg2"); - - pwgenExecutable = settings.value("pwgenExecutable").toString(); - if (pwgenExecutable.isEmpty()) - pwgenExecutable = Util::findBinaryInPath("pwgen"); - - gpgHome = settings.value("gpgHome").toString(); - - useWebDav = (settings.value("useWebDav") == "true"); - webDavUrl = settings.value("webDavUrl").toString(); - webDavUser = settings.value("webDavUser").toString(); - webDavPassword = settings.value("webDavPassword").toString(); - - profile = settings.value("profile").toString(); - settings.beginGroup("profiles"); - QStringList keys = settings.childKeys(); - foreach (QString key, keys) - profiles[key] = settings.value(key).toString(); + if (settings.value("maximized", isMaximized()).toBool()) + showMaximized(); settings.endGroup(); - - useGit = (settings.value("useGit") == "true"); - usePwgen = (settings.value("usePwgen") == "true"); - useSymbols = (settings.value("useSymbols") == "true"); - passwordLength = settings.value("passwordLength").toInt(); - passwordChars = settings.value("passwordChars").toString(); - - useTrayIcon = settings.value("useTrayIcon").toBool(); - hideOnClose = settings.value("hideOnClose").toBool(); - startMinimized = settings.value("startMinimized").toBool(); - - autoPull = settings.value("autoPull").toBool(); - autoPush = settings.value("autoPush").toBool(); - - if (useTrayIcon && tray == NULL) { - initTrayIcon(); - if (freshStart && startMinimized) { - // since we are still in constructor, can't directly hide - QTimer::singleShot(10, this, SLOT(hide())); - } - } else if (!useTrayIcon && tray != NULL) { - destroyTrayIcon(); - } - - passTemplate = settings.value("passTemplate").toString(); - useTemplate = settings.value("useTemplate").toBool(); - templateAllFields = settings.value("templateAllFields").toBool(); - - // qDebug() << version; - - // Config updates - if (version.isEmpty()) { - qDebug() << "assuming fresh install"; - if (autoclearSeconds < 5) - autoclearSeconds = 10; - if (autoclearPanelSeconds < 5) - autoclearPanelSeconds = 10; - passwordLength = 16; - passwordChars - = - "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890~!@#$%^&*()_-+={}[]|:;<>,.?"; - if (!pwgenExecutable.isEmpty()) - usePwgen = true; - else - usePwgen = false; - passTemplate = "login\nurl"; - } else { -// QStringList ver = version.split("."); -// qDebug() << ver; -// if (ver[0] == "0" && ver[1] == "8") { -//// upgrade to 0.9 -// } - if (passwordChars.isEmpty()) - passwordChars - = - "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890~!@#$%^&*()_-+={}[]|:;<>,.?"; - if (passTemplate.isEmpty()) - passTemplate = "login\nurl"; - } - - settings.setValue("version", VERSION); - - if (Util::checkConfig(passStore, passExecutable, gpgExecutable)) { - config(); - if (freshStart && Util::checkConfig(passStore, passExecutable, gpgExecutable)) - return false; - } - - freshStart = false; - - // TODO: this needs to be before we try to access the store, - // but it would be better to do it after the Window is shown, - // as the long delay it can cause is irritating otherwise. - if (useWebDav) - mountWebDav(); - - model.setNameFilters(QStringList() << "*.gpg"); - model.setNameFilterDisables(false); - - proxyModel.setSourceModel(&model); - proxyModel.setModelAndStore(&model, passStore); - selectionModel.reset(new QItemSelectionModel(&proxyModel)); - model.fetchMore(model.setRootPath(passStore)); - model.sort(0, Qt::AscendingOrder); - - ui->treeView->setModel(&proxyModel); - ui->treeView->setRootIndex(proxyModel.mapFromSource(model.setRootPath(passStore))); - ui->treeView->setColumnHidden(1, true); - ui->treeView->setColumnHidden(2, true); - ui->treeView->setColumnHidden(3, true); - ui->treeView->setHeaderHidden(true); - ui->treeView->setIndentation(15); - ui->treeView->setHorizontalScrollBarPolicy(Qt::ScrollBarAsNeeded); - ui->treeView->setContextMenuPolicy(Qt::CustomContextMenu); - connect(ui->treeView, SIGNAL(customContextMenuRequested(const QPoint &)), - this, SLOT(showContextMenu(const QPoint &))); - - ui->textBrowser->setOpenExternalLinks(true); - ui->textBrowser->setContextMenuPolicy(Qt::CustomContextMenu); - connect(ui->textBrowser, SIGNAL(customContextMenuRequested(const QPoint &)), - this, SLOT(showBrowserContextMenu(const QPoint &))); - - updateProfileBox(); - - env = QProcess::systemEnvironment(); - if (!gpgHome.isEmpty()) { - QDir absHome(gpgHome); - absHome.makeAbsolute(); - env << "GNUPGHOME=" + absHome.path(); + } + + usePass = (settings.value("usePass") == "true"); + + useClipboard = CLIPBOARD_NEVER; + if (settings.value("useClipboard") == "true" || + settings.value("useClipboard") == "1") + useClipboard = CLIPBOARD_ALWAYS; + else if (settings.value("useClipboard") == "2") + useClipboard = CLIPBOARD_ON_DEMAND; + useAutoclear = (settings.value("useAutoclear") == "true"); + autoclearSeconds = settings.value("autoclearSeconds").toInt(); + useAutoclearPanel = (settings.value("useAutoclearPanel") == "true"); + autoclearPanelSeconds = settings.value("autoclearPanelSeconds").toInt(); + hidePassword = (settings.value("hidePassword") == "true"); + hideContent = (settings.value("hideContent") == "true"); + addGPGId = (settings.value("addGPGId") != "false"); + + passStore = settings.value("passStore").toString(); + if (passStore.isEmpty()) { + passStore = Util::findPasswordStore(); + settings.setValue("passStore", passStore); + } + passStore = Util::normalizeFolderPath(passStore); + + passExecutable = settings.value("passExecutable").toString(); + if (passExecutable.isEmpty()) + passExecutable = Util::findBinaryInPath("pass"); + + gitExecutable = settings.value("gitExecutable").toString(); + if (gitExecutable.isEmpty()) + gitExecutable = Util::findBinaryInPath("git"); + + gpgExecutable = settings.value("gpgExecutable").toString(); + if (gpgExecutable.isEmpty()) + gpgExecutable = Util::findBinaryInPath("gpg2"); + + pwgenExecutable = settings.value("pwgenExecutable").toString(); + if (pwgenExecutable.isEmpty()) + pwgenExecutable = Util::findBinaryInPath("pwgen"); + + gpgHome = settings.value("gpgHome").toString(); + + useWebDav = (settings.value("useWebDav") == "true"); + webDavUrl = settings.value("webDavUrl").toString(); + webDavUser = settings.value("webDavUser").toString(); + webDavPassword = settings.value("webDavPassword").toString(); + + profile = settings.value("profile").toString(); + settings.beginGroup("profiles"); + QStringList keys = settings.childKeys(); + foreach (QString key, keys) + profiles[key] = settings.value(key).toString(); + settings.endGroup(); + + useGit = (settings.value("useGit") == "true"); + usePwgen = (settings.value("usePwgen") == "true"); + useSymbols = (settings.value("useSymbols") == "true"); + passwordLength = settings.value("passwordLength").toInt(); + passwordChars = settings.value("passwordChars").toString(); + + useTrayIcon = settings.value("useTrayIcon").toBool(); + hideOnClose = settings.value("hideOnClose").toBool(); + startMinimized = settings.value("startMinimized").toBool(); + + autoPull = settings.value("autoPull").toBool(); + autoPush = settings.value("autoPush").toBool(); + + if (useTrayIcon && tray == NULL) { + initTrayIcon(); + if (freshStart && startMinimized) { + // since we are still in constructor, can't directly hide + QTimer::singleShot(10, this, SLOT(hide())); } + } else if (!useTrayIcon && tray != NULL) { + destroyTrayIcon(); + } + + passTemplate = settings.value("passTemplate").toString(); + useTemplate = settings.value("useTemplate").toBool(); + templateAllFields = settings.value("templateAllFields").toBool(); + + // qDebug() << version; + + // Config updates + if (version.isEmpty()) { + qDebug() << "assuming fresh install"; + if (autoclearSeconds < 5) + autoclearSeconds = 10; + if (autoclearPanelSeconds < 5) + autoclearPanelSeconds = 10; + passwordLength = 16; + passwordChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz123456" + "7890~!@#$%^&*()_-+={}[]|:;<>,.?"; + if (!pwgenExecutable.isEmpty()) + usePwgen = true; + else + usePwgen = false; + passTemplate = "login\nurl"; + } else { + // QStringList ver = version.split("."); + // qDebug() << ver; + // if (ver[0] == "0" && ver[1] == "8") { + //// upgrade to 0.9 + // } + if (passwordChars.isEmpty()) + passwordChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234" + "567890~!@#$%^&*()_-+={}[]|:;<>,.?"; + if (passTemplate.isEmpty()) + passTemplate = "login\nurl"; + } + + settings.setValue("version", VERSION); + + if (Util::checkConfig(passStore, passExecutable, gpgExecutable)) { + config(); + if (freshStart && + Util::checkConfig(passStore, passExecutable, gpgExecutable)) + return false; + } + + freshStart = false; + + // TODO: this needs to be before we try to access the store, + // but it would be better to do it after the Window is shown, + // as the long delay it can cause is irritating otherwise. + if (useWebDav) + mountWebDav(); + + model.setNameFilters(QStringList() << "*.gpg"); + model.setNameFilterDisables(false); + + proxyModel.setSourceModel(&model); + proxyModel.setModelAndStore(&model, passStore); + selectionModel.reset(new QItemSelectionModel(&proxyModel)); + model.fetchMore(model.setRootPath(passStore)); + model.sort(0, Qt::AscendingOrder); + + ui->treeView->setModel(&proxyModel); + ui->treeView->setRootIndex( + proxyModel.mapFromSource(model.setRootPath(passStore))); + ui->treeView->setColumnHidden(1, true); + ui->treeView->setColumnHidden(2, true); + ui->treeView->setColumnHidden(3, true); + ui->treeView->setHeaderHidden(true); + ui->treeView->setIndentation(15); + ui->treeView->setHorizontalScrollBarPolicy(Qt::ScrollBarAsNeeded); + ui->treeView->setContextMenuPolicy(Qt::CustomContextMenu); + connect(ui->treeView, SIGNAL(customContextMenuRequested(const QPoint &)), + this, SLOT(showContextMenu(const QPoint &))); + + ui->textBrowser->setOpenExternalLinks(true); + ui->textBrowser->setContextMenuPolicy(Qt::CustomContextMenu); + connect(ui->textBrowser, SIGNAL(customContextMenuRequested(const QPoint &)), + this, SLOT(showBrowserContextMenu(const QPoint &))); + + updateProfileBox(); + + env = QProcess::systemEnvironment(); + if (!gpgHome.isEmpty()) { + QDir absHome(gpgHome); + absHome.makeAbsolute(); + env << "GNUPGHOME=" + absHome.path(); + } #ifdef __APPLE__ - // If it exists, add the gpgtools to PATH - if (QFile("/usr/local/MacGPG2/bin").exists()) - env.replaceInStrings("PATH=", "PATH=/usr/local/MacGPG2/bin:"); - // Add missing /usr/local/bin - if (env.filter("/usr/local/bin").isEmpty()) - env.replaceInStrings("PATH=", "PATH=/usr/local/bin:"); + // If it exists, add the gpgtools to PATH + if (QFile("/usr/local/MacGPG2/bin").exists()) + env.replaceInStrings("PATH=", "PATH=/usr/local/MacGPG2/bin:"); + // Add missing /usr/local/bin + if (env.filter("/usr/local/bin").isEmpty()) + env.replaceInStrings("PATH=", "PATH=/usr/local/bin:"); #endif - // QMessageBox::information(this, "env", env.join("\n")); + // QMessageBox::information(this, "env", env.join("\n")); - updateEnv(); + updateEnv(); - if (!useGit || (gitExecutable.isEmpty() && passExecutable.isEmpty())) { - ui->pushButton->hide(); - ui->updateButton->hide(); - } else { - ui->pushButton->show(); - ui->updateButton->show(); - } + if (!useGit || (gitExecutable.isEmpty() && passExecutable.isEmpty())) { + ui->pushButton->hide(); + ui->updateButton->hide(); + } else { + ui->pushButton->show(); + ui->updateButton->show(); + } - startupPhase = false; - return true; + startupPhase = false; + return true; } /** * @brief MainWindow::config */ -void MainWindow::config() -{ - QScopedPointer d(new ConfigDialog(this)); - d->setModal(true); - - // Automatically default to pass if it's available - usePass = freshStart ? QFile(passExecutable).exists() : usePass; - - d->setPassPath(passExecutable); - d->setGitPath(gitExecutable); - d->setGpgPath(gpgExecutable); - d->setStorePath(passStore); - d->usePass(usePass); - d->useClipboard(useClipboard); - d->useAutoclear(useAutoclear); - d->setAutoclear(autoclearSeconds); - d->useAutoclearPanel(useAutoclearPanel); - d->setAutoclearPanel(autoclearPanelSeconds); - d->hidePassword(hidePassword); - d->hideContent(hideContent); - d->addGPGId(addGPGId); - d->useTrayIcon(useTrayIcon); - d->hideOnClose(hideOnClose); - d->startMinimized(startMinimized); - d->setProfiles(profiles, profile); - d->useGit(useGit); - d->setPwgenPath(pwgenExecutable); - d->usePwgen(usePwgen); - d->useSymbols(useSymbols); - d->setPasswordLength(passwordLength); - d->setPasswordChars(passwordChars); - d->useTemplate(useTemplate); - d->setTemplate(passTemplate); - d->templateAllFields(templateAllFields); - d->autoPull(autoPull); - d->autoPush(autoPush); - if (startupPhase) - d->wizard(); // does shit - if (d->exec()) { - if (d->result() == QDialog::Accepted) { - passExecutable = d->getPassPath(); - gitExecutable = d->getGitPath(); - gpgExecutable = d->getGpgPath(); - passStore = Util::normalizeFolderPath(d->getStorePath()); - usePass = d->usePass(); - useClipboard = d->useClipboard(); - useAutoclear = d->useAutoclear(); - autoclearSeconds = d->getAutoclear(); - useAutoclearPanel = d->useAutoclearPanel(); - autoclearPanelSeconds = d->getAutoclearPanel(); - hidePassword = d->hidePassword(); - hideContent = d->hideContent(); - addGPGId = d->addGPGId(); - useTrayIcon = d->useTrayIcon(); - hideOnClose = d->hideOnClose(); - startMinimized = d->startMinimized(); - profiles = d->getProfiles(); - useGit = d->useGit(); - pwgenExecutable = d->getPwgenPath(); - usePwgen = d->usePwgen(); - useSymbols = d->useSymbols(); - passwordLength = d->getPasswordLength(); - passwordChars = d->getPasswordChars(); - useTemplate = d->useTemplate(); - passTemplate = d->getTemplate(); - templateAllFields = d->templateAllFields(); - autoPush = d->autoPush(); - autoPull = d->autoPull(); - - QSettings &settings(getSettings()); - - settings.setValue("version", VERSION); - settings.setValue("passExecutable", passExecutable); - settings.setValue("gitExecutable", gitExecutable); - settings.setValue("gpgExecutable", gpgExecutable); - settings.setValue("passStore", passStore); - settings.setValue("usePass", usePass ? "true" : "false"); - switch (useClipboard) { - case CLIPBOARD_ALWAYS: - settings.setValue("useClipboard", "true"); - break; - case CLIPBOARD_ON_DEMAND: - settings.setValue("useClipboard", "2"); - break; - default: - settings.setValue("useClipboard", "false"); - break; - } - settings.setValue("useAutoclear", useAutoclear ? "true" : "false"); - settings.setValue("autoclearSeconds", autoclearSeconds); - settings.setValue("useAutoclearPanel", useAutoclearPanel ? "true" : "false"); - settings.setValue("autoclearPanelSeconds", autoclearPanelSeconds); - settings.setValue("hidePassword", hidePassword ? "true" : "false"); - settings.setValue("hideContent", hideContent ? "true" : "false"); - settings.setValue("addGPGId", addGPGId ? "true" : "false"); - settings.setValue("useTrayIcon", useTrayIcon ? "true" : "false"); - settings.setValue("hideOnClose", hideOnClose ? "true" : "false"); - settings.setValue("startMinimized", startMinimized ? "true" : "false"); - settings.setValue("useGit", useGit ? "true" : "false"); - settings.setValue("pwgenExecutable", pwgenExecutable); - settings.setValue("usePwgen", usePwgen ? "true" : "false"); - settings.setValue("useSymbols", useSymbols ? "true" : "false"); - settings.setValue("passwordLength", passwordLength); - settings.setValue("passwordChars", passwordChars); - settings.setValue("useTemplate", useTemplate); - settings.setValue("passTemplate", passTemplate); - settings.setValue("templateAllFields", templateAllFields); - settings.setValue("autoPull", autoPull ? "true" : "false"); - settings.setValue("autoPush", autoPush ? "true" : "false"); - - if (!profiles.isEmpty()) { - settings.beginGroup("profiles"); - settings.remove(""); - bool profileExists = false; - QHashIterator i(profiles); - while (i.hasNext()) { - i.next(); - // qDebug() << i.key() + "|" + i.value(); - if (i.key() == profile) - profileExists = true; - settings.setValue(i.key(), i.value()); - } - if (!profileExists) { - // just take the last one - profile = i.key(); - } - settings.endGroup(); - } else { - settings.remove("profiles"); - } - updateProfileBox(); - ui->treeView->setRootIndex(proxyModel.mapFromSource(model.setRootPath(passStore))); - - if (freshStart && Util::checkConfig(passStore, passExecutable, gpgExecutable)) - config(); - updateEnv(); - if (!useGit || (gitExecutable.isEmpty() && passExecutable.isEmpty())) { - ui->pushButton->hide(); - ui->updateButton->hide(); - } else { - ui->pushButton->show(); - ui->updateButton->show(); - } - if (useTrayIcon && tray == NULL) - initTrayIcon(); - else if (!useTrayIcon && tray != NULL) - destroyTrayIcon(); +void MainWindow::config() { + QScopedPointer d(new ConfigDialog(this)); + d->setModal(true); + + // Automatically default to pass if it's available + usePass = freshStart ? QFile(passExecutable).exists() : usePass; + + d->setPassPath(passExecutable); + d->setGitPath(gitExecutable); + d->setGpgPath(gpgExecutable); + d->setStorePath(passStore); + d->usePass(usePass); + d->useClipboard(useClipboard); + d->useAutoclear(useAutoclear); + d->setAutoclear(autoclearSeconds); + d->useAutoclearPanel(useAutoclearPanel); + d->setAutoclearPanel(autoclearPanelSeconds); + d->hidePassword(hidePassword); + d->hideContent(hideContent); + d->addGPGId(addGPGId); + d->useTrayIcon(useTrayIcon); + d->hideOnClose(hideOnClose); + d->startMinimized(startMinimized); + d->setProfiles(profiles, profile); + d->useGit(useGit); + d->setPwgenPath(pwgenExecutable); + d->usePwgen(usePwgen); + d->useSymbols(useSymbols); + d->setPasswordLength(passwordLength); + d->setPasswordChars(passwordChars); + d->useTemplate(useTemplate); + d->setTemplate(passTemplate); + d->templateAllFields(templateAllFields); + d->autoPull(autoPull); + d->autoPush(autoPush); + if (startupPhase) + d->wizard(); // does shit + if (d->exec()) { + if (d->result() == QDialog::Accepted) { + passExecutable = d->getPassPath(); + gitExecutable = d->getGitPath(); + gpgExecutable = d->getGpgPath(); + passStore = Util::normalizeFolderPath(d->getStorePath()); + usePass = d->usePass(); + useClipboard = d->useClipboard(); + useAutoclear = d->useAutoclear(); + autoclearSeconds = d->getAutoclear(); + useAutoclearPanel = d->useAutoclearPanel(); + autoclearPanelSeconds = d->getAutoclearPanel(); + hidePassword = d->hidePassword(); + hideContent = d->hideContent(); + addGPGId = d->addGPGId(); + useTrayIcon = d->useTrayIcon(); + hideOnClose = d->hideOnClose(); + startMinimized = d->startMinimized(); + profiles = d->getProfiles(); + useGit = d->useGit(); + pwgenExecutable = d->getPwgenPath(); + usePwgen = d->usePwgen(); + useSymbols = d->useSymbols(); + passwordLength = d->getPasswordLength(); + passwordChars = d->getPasswordChars(); + useTemplate = d->useTemplate(); + passTemplate = d->getTemplate(); + templateAllFields = d->templateAllFields(); + autoPush = d->autoPush(); + autoPull = d->autoPull(); + + QSettings &settings(getSettings()); + + settings.setValue("version", VERSION); + settings.setValue("passExecutable", passExecutable); + settings.setValue("gitExecutable", gitExecutable); + settings.setValue("gpgExecutable", gpgExecutable); + settings.setValue("passStore", passStore); + settings.setValue("usePass", usePass ? "true" : "false"); + switch (useClipboard) { + case CLIPBOARD_ALWAYS: + settings.setValue("useClipboard", "true"); + break; + case CLIPBOARD_ON_DEMAND: + settings.setValue("useClipboard", "2"); + break; + default: + settings.setValue("useClipboard", "false"); + break; + } + settings.setValue("useAutoclear", useAutoclear ? "true" : "false"); + settings.setValue("autoclearSeconds", autoclearSeconds); + settings.setValue("useAutoclearPanel", + useAutoclearPanel ? "true" : "false"); + settings.setValue("autoclearPanelSeconds", autoclearPanelSeconds); + settings.setValue("hidePassword", hidePassword ? "true" : "false"); + settings.setValue("hideContent", hideContent ? "true" : "false"); + settings.setValue("addGPGId", addGPGId ? "true" : "false"); + settings.setValue("useTrayIcon", useTrayIcon ? "true" : "false"); + settings.setValue("hideOnClose", hideOnClose ? "true" : "false"); + settings.setValue("startMinimized", startMinimized ? "true" : "false"); + settings.setValue("useGit", useGit ? "true" : "false"); + settings.setValue("pwgenExecutable", pwgenExecutable); + settings.setValue("usePwgen", usePwgen ? "true" : "false"); + settings.setValue("useSymbols", useSymbols ? "true" : "false"); + settings.setValue("passwordLength", passwordLength); + settings.setValue("passwordChars", passwordChars); + settings.setValue("useTemplate", useTemplate); + settings.setValue("passTemplate", passTemplate); + settings.setValue("templateAllFields", templateAllFields); + settings.setValue("autoPull", autoPull ? "true" : "false"); + settings.setValue("autoPush", autoPush ? "true" : "false"); + + if (!profiles.isEmpty()) { + settings.beginGroup("profiles"); + settings.remove(""); + bool profileExists = false; + QHashIterator i(profiles); + while (i.hasNext()) { + i.next(); + // qDebug() << i.key() + "|" + i.value(); + if (i.key() == profile) + profileExists = true; + settings.setValue(i.key(), i.value()); + } + if (!profileExists) { + // just take the last one + profile = i.key(); } - freshStart = false; + settings.endGroup(); + } else { + settings.remove("profiles"); + } + updateProfileBox(); + ui->treeView->setRootIndex( + proxyModel.mapFromSource(model.setRootPath(passStore))); + + if (freshStart && + Util::checkConfig(passStore, passExecutable, gpgExecutable)) + config(); + updateEnv(); + if (!useGit || (gitExecutable.isEmpty() && passExecutable.isEmpty())) { + ui->pushButton->hide(); + ui->updateButton->hide(); + } else { + ui->pushButton->show(); + ui->updateButton->show(); + } + if (useTrayIcon && tray == NULL) + initTrayIcon(); + else if (!useTrayIcon && tray != NULL) + destroyTrayIcon(); } + freshStart = false; + } } /** * @brief MainWindow::on_updateButton_clicked */ -void MainWindow::on_updateButton_clicked() -{ - ui->statusBar->showMessage(tr("Updating password-store"), 2000); - currentAction = GIT; - if (usePass) - executePass("git pull"); - else - executeWrapper(gitExecutable, "pull"); +void MainWindow::on_updateButton_clicked() { + ui->statusBar->showMessage(tr("Updating password-store"), 2000); + currentAction = GIT; + if (usePass) + executePass("git pull"); + else + executeWrapper(gitExecutable, "pull"); } /** * @brief MainWindow::on_pushButton_clicked */ -void MainWindow::on_pushButton_clicked() -{ - ui->statusBar->showMessage(tr("Updating password-store"), 2000); - currentAction = GIT; - if (usePass) - executePass("git push"); - else - executeWrapper(gitExecutable, "push"); +void MainWindow::on_pushButton_clicked() { + ui->statusBar->showMessage(tr("Updating password-store"), 2000); + currentAction = GIT; + if (usePass) + executePass("git push"); + else + executeWrapper(gitExecutable, "push"); } -QString MainWindow::getDir(const QModelIndex &index, bool forPass) -{ - QString abspath = QDir(passStore).absolutePath() + '/'; - if (!index.isValid()) - return forPass ? "" : abspath; - QFileInfo info = model.fileInfo(proxyModel.mapToSource(index)); - QString filePath = (info.isFile() ? info.absolutePath() : info.absoluteFilePath()) + '/'; - if (forPass) { - filePath.replace(QRegExp("^" + passStore), ""); - filePath.replace(QRegExp("^" + abspath), ""); - } - return filePath; +QString MainWindow::getDir(const QModelIndex &index, bool forPass) { + QString abspath = QDir(passStore).absolutePath() + '/'; + if (!index.isValid()) + return forPass ? "" : abspath; + QFileInfo info = model.fileInfo(proxyModel.mapToSource(index)); + QString filePath = + (info.isFile() ? info.absolutePath() : info.absoluteFilePath()) + '/'; + if (forPass) { + filePath.replace(QRegExp("^" + passStore), ""); + filePath.replace(QRegExp("^" + abspath), ""); + } + return filePath; } -QString MainWindow::getFile(const QModelIndex &index, bool forPass) -{ - if (!index.isValid() || !model.fileInfo(proxyModel.mapToSource(index)).isFile()) - return QString(); - QString filePath = model.filePath(proxyModel.mapToSource(index)); - if (forPass) { - filePath.replace(QRegExp("\\.gpg$"), ""); - filePath.replace(QRegExp("^" + passStore), ""); - } - return filePath; +QString MainWindow::getFile(const QModelIndex &index, bool forPass) { + if (!index.isValid() || + !model.fileInfo(proxyModel.mapToSource(index)).isFile()) + return QString(); + QString filePath = model.filePath(proxyModel.mapToSource(index)); + if (forPass) { + filePath.replace(QRegExp("\\.gpg$"), ""); + filePath.replace(QRegExp("^" + passStore), ""); + } + return filePath; } /** * @brief MainWindow::on_treeView_clicked * @param index */ -void MainWindow::on_treeView_clicked(const QModelIndex &index) -{ - currentDir = getDir(ui->treeView->currentIndex(), false); - lastDecrypt = "Could not decrypt"; - setClippedPassword(""); - QString file = getFile(index, usePass); - if (!file.isEmpty()) { - currentAction = GPG; - if (usePass) - executePass("show \"" + file + '"'); - else - executeWrapper(gpgExecutable, - "-d --quiet --yes --no-encrypt-to --batch --use-agent \"" + file + '"'); - } else { - ui->editButton->setEnabled(false); - ui->deleteButton->setEnabled(true); - } +void MainWindow::on_treeView_clicked(const QModelIndex &index) { + currentDir = getDir(ui->treeView->currentIndex(), false); + lastDecrypt = "Could not decrypt"; + setClippedPassword(""); + QString file = getFile(index, usePass); + if (!file.isEmpty()) { + currentAction = GPG; + if (usePass) + executePass("show \"" + file + '"'); + else + executeWrapper(gpgExecutable, + "-d --quiet --yes --no-encrypt-to --batch --use-agent \"" + + file + '"'); + } else { + ui->editButton->setEnabled(false); + ui->deleteButton->setEnabled(true); + } } /** * @brief MainWindow::executePass * @param args */ -void MainWindow::executePass(QString args, QString input) -{ - executeWrapper(passExecutable, args, input); +void MainWindow::executePass(QString args, QString input) { + executeWrapper(passExecutable, args, input); } /** * @brief MainWindow::executePassGitInit */ -void MainWindow::executePassGitInit() -{ - qDebug() << "Pass git init called"; - if (usePass) - executePass("git init"); - else - executeWrapper("git", "init \"" + passStore + '"'); +void MainWindow::executePassGitInit() { + qDebug() << "Pass git init called"; + if (usePass) + executePass("git init"); + else + executeWrapper("git", "init \"" + passStore + '"'); } /** @@ -624,182 +615,180 @@ void MainWindow::executePassGitInit() * @param app * @param args */ -void MainWindow::executeWrapper(QString app, QString args, QString input) -{ - // qDebug() << app + " " + args; - // Happens a lot if e.g. git binary is not set. - // This will result in bogus "QProcess::FailedToStart" messages, - // also hiding legitimate errors from the gpg commands. - if (app.isEmpty()) { - qDebug() << "Trying to execute nothing.."; - return; - } - // Convert to absolute path, just in case - app = QDir(QCoreApplication::applicationDirPath()).absoluteFilePath(app); - if (wrapperRunning) { - execQueueItem item; - item.app = app; - item.args = args; - item.input = input; - - execQueue->enqueue(item); - qDebug() << item.app + "," + item.args + "," + item.input; - return; - } - wrapperRunning = true; - process->setWorkingDirectory(passStore); - process->setEnvironment(env); - clearTemplateWidgets(); - ui->textBrowser->clear(); - ui->textBrowser->setTextColor(Qt::black); - enableUiElements(false); - if (autoclearTimer != NULL) { - autoclearTimer->stop(); - delete autoclearTimer; - autoclearTimer = NULL; - } - process->start('"' + app + "\" " + args); - if (!input.isEmpty()) - process->write(input.toUtf8()); - process->closeWriteChannel(); +void MainWindow::executeWrapper(QString app, QString args, QString input) { + // qDebug() << app + " " + args; + // Happens a lot if e.g. git binary is not set. + // This will result in bogus "QProcess::FailedToStart" messages, + // also hiding legitimate errors from the gpg commands. + if (app.isEmpty()) { + qDebug() << "Trying to execute nothing.."; + return; + } + // Convert to absolute path, just in case + app = QDir(QCoreApplication::applicationDirPath()).absoluteFilePath(app); + if (wrapperRunning) { + execQueueItem item; + item.app = app; + item.args = args; + item.input = input; + + execQueue->enqueue(item); + qDebug() << item.app + "," + item.args + "," + item.input; + return; + } + wrapperRunning = true; + process->setWorkingDirectory(passStore); + process->setEnvironment(env); + clearTemplateWidgets(); + ui->textBrowser->clear(); + ui->textBrowser->setTextColor(Qt::black); + enableUiElements(false); + if (autoclearTimer != NULL) { + autoclearTimer->stop(); + delete autoclearTimer; + autoclearTimer = NULL; + } + process->start('"' + app + "\" " + args); + if (!input.isEmpty()) + process->write(input.toUtf8()); + process->closeWriteChannel(); } /** * @brief MainWindow::readyRead */ -void MainWindow::readyRead(bool finished = false) -{ - if (currentAction == PWGEN) - return; - QString output = ""; - QString error = process->readAllStandardError(); - if (currentAction != GPG_INTERNAL) { - output = process->readAllStandardOutput(); - if (finished && currentAction == GPG) { - lastDecrypt = output; - QStringList tokens = output.split("\n"); - - if (useClipboard != CLIPBOARD_NEVER && !output.isEmpty()) { - setClippedPassword(tokens[0]); - if (useClipboard == CLIPBOARD_ALWAYS) copyPasswordToClipboard(); - if (useAutoclearPanel) { - QTimer::singleShot(1000*autoclearPanelSeconds, \ - this, \ - SLOT(clearPanel())); - } - if (hidePassword && !useTemplate) { - tokens[0] = "***" + tr("Password hidden") + "***"; - output = tokens.join("\n"); - } - if (hideContent) - output = "***" + tr("Content hidden") + "***"; - } - - if (useTemplate) { - while (ui->formLayout->count() > 0) { - QLayoutItem *item = ui->formLayout->takeAt(0); - delete item->widget(); - delete item; - } - QLineEdit *pass = new QLineEdit(); - pass->setText(tokens[0]); - tokens.pop_front(); - if (hidePassword) - pass->setEchoMode(QLineEdit::Password); - pass->setReadOnly(true); - ui->formLayout->addRow(pass); - - for (int j = 0; j < tokens.length(); j++) { - QString token = tokens.at(j); - if (token.contains(':')) { - int colon = token.indexOf(':'); - QString field = token.left(colon); - if (templateAllFields || passTemplate.contains(field)) { - QString value = token.right(token.length()-colon-1); - if (!passTemplate.contains(field) && value.startsWith("//")) - continue; // colon is probably from a url - QLineEdit *line = new QLineEdit(); - line->setObjectName(field); - line->setText(value); - line->setReadOnly(true); - ui->formLayout->addRow(new QLabel(field), line); - tokens.removeAt(j); - j--; // tokens.length() also got shortened by the remove.. - } - } - } - if (ui->formLayout->count() == 0) - ui->verticalLayoutPassword->setSpacing(0); - else - ui->verticalLayoutPassword->setSpacing(6); - output = tokens.join("\n"); - } else { - clearTemplateWidgets(); - } - if (useAutoclearPanel) { - autoclearPass = output; - autoclearTimer = new QTimer(this); - autoclearTimer->setSingleShot(true); - autoclearTimer->setInterval(1000*autoclearPanelSeconds); - connect(autoclearTimer, SIGNAL(timeout()), this, SLOT(clearPanel())); - autoclearTimer->start(); - } +void MainWindow::readyRead(bool finished = false) { + if (currentAction == PWGEN) + return; + QString output = ""; + QString error = process->readAllStandardError(); + if (currentAction != GPG_INTERNAL) { + output = process->readAllStandardOutput(); + if (finished && currentAction == GPG) { + lastDecrypt = output; + QStringList tokens = output.split("\n"); + + if (useClipboard != CLIPBOARD_NEVER && !output.isEmpty()) { + setClippedPassword(tokens[0]); + if (useClipboard == CLIPBOARD_ALWAYS) + copyPasswordToClipboard(); + if (useAutoclearPanel) { + QTimer::singleShot(1000 * autoclearPanelSeconds, this, + SLOT(clearPanel())); } - output.replace(QRegExp("<"), "<"); - output.replace(QRegExp(">"), ">"); - } else { - // qDebug() << process->readAllStandardOutput(); - // qDebug() << process->readAllStandardError(); - if (finished && 0 != keygen) { - qDebug() << "Keygen Done"; - keygen->close(); - keygen = 0; - // TODO some sanity checking ? + if (hidePassword && !useTemplate) { + tokens[0] = "***" + tr("Password hidden") + "***"; + output = tokens.join("\n"); + } + if (hideContent) + output = "***" + tr("Content hidden") + "***"; + } + + if (useTemplate) { + while (ui->formLayout->count() > 0) { + QLayoutItem *item = ui->formLayout->takeAt(0); + delete item->widget(); + delete item; } + QLineEdit *pass = new QLineEdit(); + pass->setText(tokens[0]); + tokens.pop_front(); + if (hidePassword) + pass->setEchoMode(QLineEdit::Password); + pass->setReadOnly(true); + ui->formLayout->addRow(pass); + + for (int j = 0; j < tokens.length(); j++) { + QString token = tokens.at(j); + if (token.contains(':')) { + int colon = token.indexOf(':'); + QString field = token.left(colon); + if (templateAllFields || passTemplate.contains(field)) { + QString value = token.right(token.length() - colon - 1); + if (!passTemplate.contains(field) && value.startsWith("//")) + continue; // colon is probably from a url + QLineEdit *line = new QLineEdit(); + line->setObjectName(field); + line->setText(value); + line->setReadOnly(true); + ui->formLayout->addRow(new QLabel(field), line); + tokens.removeAt(j); + j--; // tokens.length() also got shortened by the remove.. + } + } + } + if (ui->formLayout->count() == 0) + ui->verticalLayoutPassword->setSpacing(0); + else + ui->verticalLayoutPassword->setSpacing(6); + output = tokens.join("\n"); + } else { + clearTemplateWidgets(); + } + if (useAutoclearPanel) { + autoclearPass = output; + autoclearTimer = new QTimer(this); + autoclearTimer->setSingleShot(true); + autoclearTimer->setInterval(1000 * autoclearPanelSeconds); + connect(autoclearTimer, SIGNAL(timeout()), this, SLOT(clearPanel())); + autoclearTimer->start(); + } } + output.replace(QRegExp("<"), "<"); + output.replace(QRegExp(">"), ">"); + } else { + // qDebug() << process->readAllStandardOutput(); + // qDebug() << process->readAllStandardError(); + if (finished && 0 != keygen) { + qDebug() << "Keygen Done"; + keygen->close(); + keygen = 0; + // TODO some sanity checking ? + } + } - if (!error.isEmpty()) { - if (currentAction == GIT) { - // https://github.com/IJHack/qtpass/issues/111 - output = "" + error + "
" + output; - } else { - output = "" + error + "
" + output; - } + if (!error.isEmpty()) { + if (currentAction == GIT) { + // https://github.com/IJHack/qtpass/issues/111 + output = "" + error + "
" + + output; + } else { + output = + "" + error + "
" + output; } + } - output.replace(QRegExp("((?:https?|ftp)://\\S+)"), "\\1"); - output.replace(QRegExp("\n"), "
"); - if (!ui->textBrowser->toPlainText().isEmpty()) - output = ui->textBrowser->toHtml() + output; - ui->textBrowser->setHtml(output); + output.replace(QRegExp("((?:https?|ftp)://\\S+)"), "\\1"); + output.replace(QRegExp("\n"), "
"); + if (!ui->textBrowser->toPlainText().isEmpty()) + output = ui->textBrowser->toHtml() + output; + ui->textBrowser->setHtml(output); } /** * @brief MainWindow::clearClipboard */ -void MainWindow::clearClipboard() -{ - QClipboard *clipboard = QApplication::clipboard(); - if (clipboard->text() == getClippedPassword()) { - clipboard->clear(); - ui->statusBar->showMessage(tr("Clipboard cleared"), 3000); - } else { - ui->statusBar->showMessage(tr("Clipboard not cleared"), 3000); - } +void MainWindow::clearClipboard() { + QClipboard *clipboard = QApplication::clipboard(); + if (clipboard->text() == getClippedPassword()) { + clipboard->clear(); + ui->statusBar->showMessage(tr("Clipboard cleared"), 3000); + } else { + ui->statusBar->showMessage(tr("Clipboard not cleared"), 3000); + } } /** * @brief MainWindow::clearPanel */ -void MainWindow::clearPanel() -{ - while (ui->formLayout->count() > 0) { - QLayoutItem *item = ui->formLayout->takeAt(0); - delete item->widget(); - delete item; - } - QString output = "***" + tr("Password and Content hidden") + "***"; - ui->textBrowser->setHtml(output); +void MainWindow::clearPanel() { + while (ui->formLayout->count() > 0) { + QLayoutItem *item = ui->formLayout->takeAt(0); + delete item->widget(); + delete item; + } + QString output = "***" + tr("Password and Content hidden") + "***"; + ui->textBrowser->setHtml(output); } /** @@ -807,18 +796,18 @@ void MainWindow::clearPanel() * @param exitCode * @param exitStatus */ -void MainWindow::processFinished(int exitCode, QProcess::ExitStatus exitStatus) -{ - wrapperRunning = false; - bool error = exitStatus != QProcess::NormalExit || exitCode > 0; - readyRead(true); - enableUiElements(true); - if (!error && currentAction == EDIT) - on_treeView_clicked(ui->treeView->currentIndex()); - if (!execQueue->isEmpty()) { - execQueueItem item = execQueue->dequeue(); - executeWrapper(item.app, item.args, item.input); - } +void MainWindow::processFinished(int exitCode, + QProcess::ExitStatus exitStatus) { + wrapperRunning = false; + bool error = exitStatus != QProcess::NormalExit || exitCode > 0; + readyRead(true); + enableUiElements(true); + if (!error && currentAction == EDIT) + on_treeView_clicked(ui->treeView->currentIndex()); + if (!execQueue->isEmpty()) { + execQueueItem item = execQueue->dequeue(); + executeWrapper(item.app, item.args, item.input); + } } /** QStringList tokens = output.split("\n"); @@ -826,131 +815,112 @@ void MainWindow::processFinished(int exitCode, QProcess::ExitStatus exitStatus) * @brief MainWindow::enableUiElements * @param state */ -void MainWindow::enableUiElements(bool state) -{ - ui->updateButton->setEnabled(state); - ui->treeView->setEnabled(state); - ui->lineEdit->setEnabled(state); - ui->addButton->setEnabled(state); - ui->usersButton->setEnabled(state); - ui->configButton->setEnabled(state); - // is a file selected? - state &= ui->treeView->currentIndex().isValid(); - ui->deleteButton->setEnabled(state); - ui->editButton->setEnabled(state); - ui->pushButton->setEnabled(state); +void MainWindow::enableUiElements(bool state) { + ui->updateButton->setEnabled(state); + ui->treeView->setEnabled(state); + ui->lineEdit->setEnabled(state); + ui->addButton->setEnabled(state); + ui->usersButton->setEnabled(state); + ui->configButton->setEnabled(state); + // is a file selected? + state &= ui->treeView->currentIndex().isValid(); + ui->deleteButton->setEnabled(state); + ui->editButton->setEnabled(state); + ui->pushButton->setEnabled(state); } /** * @brief MainWindow::processError * @param error */ -void MainWindow::processError(QProcess::ProcessError error) -{ - QString errorString; - switch (error) { - case QProcess::FailedToStart: - errorString = tr("QProcess::FailedToStart"); - break; - case QProcess::Crashed: - errorString = tr("QProcess::Crashed"); - break; - case QProcess::Timedout: - errorString = tr("QProcess::Timedout"); - break; - case QProcess::ReadError: - errorString = tr("QProcess::ReadError"); - break; - case QProcess::WriteError: - errorString = tr("QProcess::WriteError"); - break; - case QProcess::UnknownError: - errorString = tr("QProcess::UnknownError"); - break; - } - ui->textBrowser->setTextColor(Qt::red); - ui->textBrowser->setText(errorString); - if (process->state() == QProcess::NotRunning) - enableUiElements(true); +void MainWindow::processError(QProcess::ProcessError error) { + QString errorString; + switch (error) { + case QProcess::FailedToStart: + errorString = tr("QProcess::FailedToStart"); + break; + case QProcess::Crashed: + errorString = tr("QProcess::Crashed"); + break; + case QProcess::Timedout: + errorString = tr("QProcess::Timedout"); + break; + case QProcess::ReadError: + errorString = tr("QProcess::ReadError"); + break; + case QProcess::WriteError: + errorString = tr("QProcess::WriteError"); + break; + case QProcess::UnknownError: + errorString = tr("QProcess::UnknownError"); + break; + } + ui->textBrowser->setTextColor(Qt::red); + ui->textBrowser->setText(errorString); + if (process->state() == QProcess::NotRunning) + enableUiElements(true); } /** * @brief MainWindow::setPassExecutable * @param path */ -void MainWindow::setPassExecutable(QString path) -{ - passExecutable = path; -} +void MainWindow::setPassExecutable(QString path) { passExecutable = path; } /** * @brief MainWindow::setGitExecutable * @param path */ -void MainWindow::setGitExecutable(QString path) -{ - gitExecutable = path; -} +void MainWindow::setGitExecutable(QString path) { gitExecutable = path; } /** * @brief MainWindow::setGpgExecutable * @param path */ -void MainWindow::setGpgExecutable(QString path) -{ - gpgExecutable = path; -} +void MainWindow::setGpgExecutable(QString path) { gpgExecutable = path; } /** * @brief MainWindow::getGpgExecutable * @return */ -QString MainWindow::getGpgExecutable() -{ - return gpgExecutable; -} +QString MainWindow::getGpgExecutable() { return gpgExecutable; } /** * @brief MainWindow::on_configButton_clicked */ -void MainWindow::on_configButton_clicked() -{ - config(); -} +void MainWindow::on_configButton_clicked() { config(); } /** * @brief MainWindow::on_lineEdit_textChanged * @param arg1 */ -void MainWindow::on_lineEdit_textChanged(const QString &arg1) -{ - ui->treeView->expandAll(); - ui->statusBar->showMessage(tr("Looking for: %1").arg(arg1), 1000); - QString query = arg1; - query.replace(QRegExp(" "), ".*"); - QRegExp regExp(query, Qt::CaseInsensitive); - proxyModel.setFilterRegExp(regExp); - ui->treeView->setRootIndex(proxyModel.mapFromSource(model.setRootPath(passStore))); - selectFirstFile(); +void MainWindow::on_lineEdit_textChanged(const QString &arg1) { + ui->treeView->expandAll(); + ui->statusBar->showMessage(tr("Looking for: %1").arg(arg1), 1000); + QString query = arg1; + query.replace(QRegExp(" "), ".*"); + QRegExp regExp(query, Qt::CaseInsensitive); + proxyModel.setFilterRegExp(regExp); + ui->treeView->setRootIndex( + proxyModel.mapFromSource(model.setRootPath(passStore))); + selectFirstFile(); } /** * @brief MainWindow::on_lineEdit_returnPressed */ -void MainWindow::on_lineEdit_returnPressed() -{ - selectFirstFile(); - on_treeView_clicked(ui->treeView->currentIndex()); +void MainWindow::on_lineEdit_returnPressed() { + selectFirstFile(); + on_treeView_clicked(ui->treeView->currentIndex()); } /** * @brief MainWindow::selectFirstFile */ -void MainWindow::selectFirstFile() -{ - QModelIndex index = proxyModel.mapFromSource(model.setRootPath(passStore)); - index = firstFile(index); - ui->treeView->setCurrentIndex(index); +void MainWindow::selectFirstFile() { + QModelIndex index = proxyModel.mapFromSource(model.setRootPath(passStore)); + index = firstFile(index); + ui->treeView->setCurrentIndex(index); } /** @@ -958,58 +928,55 @@ void MainWindow::selectFirstFile() * @param parentIndex * @return QModelIndex */ -QModelIndex MainWindow::firstFile(QModelIndex parentIndex) -{ - QModelIndex index = parentIndex; - int numRows = proxyModel.rowCount(parentIndex); - for (int row = 0; row < numRows; ++row) { - index = proxyModel.index(row, 0, parentIndex); - if (model.fileInfo(proxyModel.mapToSource(index)).isFile()) - return index; - if (proxyModel.hasChildren(index)) - return firstFile(index); - } - return index; +QModelIndex MainWindow::firstFile(QModelIndex parentIndex) { + QModelIndex index = parentIndex; + int numRows = proxyModel.rowCount(parentIndex); + for (int row = 0; row < numRows; ++row) { + index = proxyModel.index(row, 0, parentIndex); + if (model.fileInfo(proxyModel.mapToSource(index)).isFile()) + return index; + if (proxyModel.hasChildren(index)) + return firstFile(index); + } + return index; } /** * @brief MainWindow::on_clearButton_clicked */ -void MainWindow::on_clearButton_clicked() -{ - ui->lineEdit->clear(); -} +void MainWindow::on_clearButton_clicked() { ui->lineEdit->clear(); } /** * @brief MainWindow::getRecipientList * @param for_file * @return */ -QStringList MainWindow::getRecipientList(QString for_file) -{ - QDir gpgIdPath(QFileInfo(for_file.startsWith( - passStore) ? for_file : passStore + for_file).absoluteDir()); - bool found = false; - while (gpgIdPath.exists() && gpgIdPath.absolutePath().startsWith(passStore)) - { - if (QFile(gpgIdPath.absoluteFilePath(".gpg-id")).exists()) { - found = true; - break; - } - if (!gpgIdPath.cdUp()) - break; +QStringList MainWindow::getRecipientList(QString for_file) { + QDir gpgIdPath(QFileInfo(for_file.startsWith(passStore) + ? for_file + : passStore + for_file) + .absoluteDir()); + bool found = false; + while (gpgIdPath.exists() && gpgIdPath.absolutePath().startsWith(passStore)) { + if (QFile(gpgIdPath.absoluteFilePath(".gpg-id")).exists()) { + found = true; + break; } - QFile gpgId(found ? gpgIdPath.absoluteFilePath(".gpg-id") : passStore + ".gpg-id"); - if (!gpgId.open(QIODevice::ReadOnly | QIODevice::Text)) - return QStringList(); - QStringList recipients; - while (!gpgId.atEnd()) { - QString recipient(gpgId.readLine()); - recipient = recipient.trimmed(); - if (!recipient.isEmpty()) - recipients += recipient; - } - return recipients; + if (!gpgIdPath.cdUp()) + break; + } + QFile gpgId(found ? gpgIdPath.absoluteFilePath(".gpg-id") + : passStore + ".gpg-id"); + if (!gpgId.open(QIODevice::ReadOnly | QIODevice::Text)) + return QStringList(); + QStringList recipients; + while (!gpgId.atEnd()) { + QString recipient(gpgId.readLine()); + recipient = recipient.trimmed(); + if (!recipient.isEmpty()) + recipients += recipient; + } + return recipients; } /** @@ -1019,15 +986,15 @@ QStringList MainWindow::getRecipientList(QString for_file) * @param count * @return */ -QString MainWindow::getRecipientString(QString for_file, QString separator, int *count) -{ - QString recipients_str; - QStringList recipients_list = getRecipientList(for_file); - if (count) - *count = recipients_list.size(); - foreach (const QString recipient, recipients_list) - recipients_str += separator + '"' + recipient + '"'; - return recipients_str; +QString MainWindow::getRecipientString(QString for_file, QString separator, + int *count) { + QString recipients_str; + QStringList recipients_list = getRecipientList(for_file); + if (count) + *count = recipients_list.size(); + foreach (const QString recipient, recipients_list) + recipients_str += separator + '"' + recipient + '"'; + return recipients_str; } /** @@ -1035,151 +1002,148 @@ QString MainWindow::getRecipientString(QString for_file, QString separator, int * @param file * @param overwrite */ -void MainWindow::setPassword(QString file, bool overwrite, bool isNew = false) -{ - if (!isNew && lastDecrypt.isEmpty()) { - // warn? - return; - } - PasswordDialog d(this); - d.setFile(file); - d.setTemplate(passTemplate); - d.useTemplate(useTemplate); - d.templateAll(templateAllFields); - d.setPassword(lastDecrypt); - if (!d.exec()) { - d.setPassword(NULL); - return; +void MainWindow::setPassword(QString file, bool overwrite, bool isNew = false) { + if (!isNew && lastDecrypt.isEmpty()) { + // warn? + return; + } + PasswordDialog d(this); + d.setFile(file); + d.setTemplate(passTemplate); + d.useTemplate(useTemplate); + d.templateAll(templateAllFields); + d.setPassword(lastDecrypt); + if (!d.exec()) { + d.setPassword(NULL); + return; + } + QString newValue = d.getPassword(); + if (newValue.isEmpty()) + return; + + if (newValue.right(1) != "\n") + newValue += "\n"; + + currentAction = EDIT; + if (usePass) { + QString force(overwrite ? " -f " : " "); + executePass("insert" + force + "-m \"" + file + '"', newValue); + } else { + QString recipients = getRecipientString(file, " -r "); + if (recipients.isEmpty()) { + QMessageBox::critical(this, tr("Can not edit"), + tr("Could not read encryption key to use, .gpg-id " + "file missing or invalid.")); + return; } - QString newValue = d.getPassword(); - if (newValue.isEmpty()) - return; - - if (newValue.right(1) != "\n") - newValue += "\n"; - - currentAction = EDIT; - if (usePass) { - QString force(overwrite ? " -f " : " "); - executePass("insert" + force + "-m \"" + file + '"', newValue); - } else { - QString recipients = getRecipientString(file, " -r "); - if (recipients.isEmpty()) { - QMessageBox::critical(this, tr("Can not edit"), - tr( - "Could not read encryption key to use, .gpg-id file missing or invalid.")); - return; - } - QString force(overwrite ? " --yes " : " "); - executeWrapper(gpgExecutable, - force + "--batch -eq --output \"" + file + "\" " + recipients + " -", - newValue); - if (!useWebDav && useGit) { - if (!overwrite) - executeWrapper(gitExecutable, "add \"" + file + '"'); - QString path = file; - path.replace(QRegExp("\\.gpg$"), ""); - path.replace(QRegExp("^" + passStore), ""); - executeWrapper(gitExecutable, - "commit \"" + file + "\" -m \"" + (overwrite ? "Edit" : "Add") + " for " + path - + " using QtPass.\""); - if (autoPush) - on_pushButton_clicked(); - } + QString force(overwrite ? " --yes " : " "); + executeWrapper(gpgExecutable, force + "--batch -eq --output \"" + file + + "\" " + recipients + " -", + newValue); + if (!useWebDav && useGit) { + if (!overwrite) + executeWrapper(gitExecutable, "add \"" + file + '"'); + QString path = file; + path.replace(QRegExp("\\.gpg$"), ""); + path.replace(QRegExp("^" + passStore), ""); + executeWrapper(gitExecutable, "commit \"" + file + "\" -m \"" + + (overwrite ? "Edit" : "Add") + " for " + + path + " using QtPass.\""); + if (autoPush) + on_pushButton_clicked(); } + } } /** * @brief MainWindow::on_addButton_clicked */ -void MainWindow::on_addButton_clicked() -{ - bool ok; - QString dir = getDir(ui->treeView->currentIndex(), usePass); - QString file = QInputDialog::getText(this, tr("New file"), - tr("New password file, will be placed in folder %1:").arg( - QDir::separator() - + getDir( - ui->treeView->currentIndex(), true)), QLineEdit::Normal, - "", &ok); - if (!ok || file.isEmpty()) - return; - file = dir + file; - if (!usePass) - file += ".gpg"; - lastDecrypt = ""; - setPassword(file, false, true); +void MainWindow::on_addButton_clicked() { + bool ok; + QString dir = getDir(ui->treeView->currentIndex(), usePass); + QString file = QInputDialog::getText( + this, tr("New file"), + tr("New password file, will be placed in folder %1:") + .arg(QDir::separator() + getDir(ui->treeView->currentIndex(), true)), + QLineEdit::Normal, "", &ok); + if (!ok || file.isEmpty()) + return; + file = dir + file; + if (!usePass) + file += ".gpg"; + lastDecrypt = ""; + setPassword(file, false, true); } /** * @brief MainWindow::on_deleteButton_clicked */ -void MainWindow::on_deleteButton_clicked() -{ - QFileInfo fileOrFolder = model.fileInfo(proxyModel.mapToSource(ui->treeView->currentIndex())); - QString file = ""; - - if (fileOrFolder.isFile()) { - file = getFile(ui->treeView->currentIndex(), usePass); - if (QMessageBox::question(this, tr("Delete password?"), - tr("Are you sure you want to delete %1?").arg(QDir::separator() - + getFile(ui-> - treeView-> - currentIndex(), - true)), - QMessageBox::Yes | QMessageBox::No) != QMessageBox::Yes) - return; - if (usePass) { - currentAction = DELETE; - executePass("rm -f \"" + file + '"'); - if (useGit && autoPush) - on_pushButton_clicked(); - } else { - if (useGit) { - executeWrapper(gitExecutable, "rm -f \"" + file + '"'); - executeWrapper(gitExecutable, - "commit \"" + file + "\" -m \" Remove for " - + getFile(ui->treeView->currentIndex(), true) + " using QtPass.\""); - if (autoPush) - on_pushButton_clicked(); - } else { - QFile(file).remove(); - } - } +void MainWindow::on_deleteButton_clicked() { + QFileInfo fileOrFolder = + model.fileInfo(proxyModel.mapToSource(ui->treeView->currentIndex())); + QString file = ""; + + if (fileOrFolder.isFile()) { + file = getFile(ui->treeView->currentIndex(), usePass); + if (QMessageBox::question( + this, tr("Delete password?"), + tr("Are you sure you want to delete %1?") + .arg(QDir::separator() + + getFile(ui->treeView->currentIndex(), true)), + QMessageBox::Yes | QMessageBox::No) != QMessageBox::Yes) + return; + if (usePass) { + currentAction = DELETE; + executePass("rm -f \"" + file + '"'); + if (useGit && autoPush) + on_pushButton_clicked(); } else { - file = getDir(ui->treeView->currentIndex(), usePass); - if (QMessageBox::question(this, tr("Delete folder?"), - tr("Are you sure you want to delete %1?").arg(QDir::separator() - + getDir(ui-> - treeView-> - currentIndex(), - true)), - QMessageBox::Yes | QMessageBox::No) != QMessageBox::Yes) - return; - if (usePass) { - currentAction = DELETE; - executePass("rm -r \"" + file + '"'); - if (useGit && autoPush) - on_pushButton_clicked(); - } else { - if (useGit) { - executeWrapper(gitExecutable, "rm -rf \"" + file + '"'); - executeWrapper(gitExecutable, - "commit \"" + file + "\" -m \" Remove for " - + getFile(ui->treeView->currentIndex(), true) + " using QtPass.\""); - if (autoPush) - on_pushButton_clicked(); - } else { + if (useGit) { + executeWrapper(gitExecutable, "rm -f \"" + file + '"'); + executeWrapper(gitExecutable, + "commit \"" + file + "\" -m \" Remove for " + + getFile(ui->treeView->currentIndex(), true) + + " using QtPass.\""); + if (autoPush) + on_pushButton_clicked(); + } else { + QFile(file).remove(); + } + } + } else { + file = getDir(ui->treeView->currentIndex(), usePass); + if (QMessageBox::question( + this, tr("Delete folder?"), + tr("Are you sure you want to delete %1?") + .arg(QDir::separator() + + getDir(ui->treeView->currentIndex(), true)), + QMessageBox::Yes | QMessageBox::No) != QMessageBox::Yes) + return; + if (usePass) { + currentAction = DELETE; + executePass("rm -r \"" + file + '"'); + if (useGit && autoPush) + on_pushButton_clicked(); + } else { + if (useGit) { + executeWrapper(gitExecutable, "rm -rf \"" + file + '"'); + executeWrapper(gitExecutable, + "commit \"" + file + "\" -m \" Remove for " + + getFile(ui->treeView->currentIndex(), true) + + " using QtPass.\""); + if (autoPush) + on_pushButton_clicked(); + } else { #if QT_VERSION >= QT_VERSION_CHECK(5, 0, 0) - QDir dir(file); - dir.removeRecursively(); + QDir dir(file); + dir.removeRecursively(); #else - removeDir(file); + removeDir(file); #endif - } - } + } } - lastDecrypt = ""; + } + lastDecrypt = ""; } /** @@ -1187,41 +1151,40 @@ void MainWindow::on_deleteButton_clicked() * @param dirName * @return */ -bool MainWindow::removeDir(const QString &dirName) -{ - bool result = true; - QDir dir(dirName); - - if (dir.exists(dirName)) { - Q_FOREACH(QFileInfo info, - dir.entryInfoList(QDir::NoDotAndDotDot | QDir::System | QDir::Hidden - | QDir::AllDirs - | QDir::Files, QDir::DirsFirst)) { - if (info.isDir()) - result = removeDir(info.absoluteFilePath()); - else - result = QFile::remove(info.absoluteFilePath()); - - if (!result) - return result; - } - result = dir.rmdir(dirName); +bool MainWindow::removeDir(const QString &dirName) { + bool result = true; + QDir dir(dirName); + + if (dir.exists(dirName)) { + Q_FOREACH (QFileInfo info, + dir.entryInfoList(QDir::NoDotAndDotDot | QDir::System | + QDir::Hidden | QDir::AllDirs | QDir::Files, + QDir::DirsFirst)) { + if (info.isDir()) + result = removeDir(info.absoluteFilePath()); + else + result = QFile::remove(info.absoluteFilePath()); + + if (!result) + return result; } - return result; + result = dir.rmdir(dirName); + } + return result; } /** * @brief MainWindow::on_editButton_clicked */ -void MainWindow::on_editButton_clicked() -{ - QString file = getFile(ui->treeView->currentIndex(), usePass); - if (file.isEmpty()) { - QMessageBox::critical(this, tr("Can not edit"), - tr("Selected password file does not exist, not able to edit")); - return; - } - setPassword(file, true); +void MainWindow::on_editButton_clicked() { + QString file = getFile(ui->treeView->currentIndex(), usePass); + if (file.isEmpty()) { + QMessageBox::critical( + this, tr("Can not edit"), + tr("Selected password file does not exist, not able to edit")); + return; + } + setPassword(file, true); } /** @@ -1230,138 +1193,141 @@ void MainWindow::on_editButton_clicked() * @param secret * @return */ -QList MainWindow::listKeys(QString keystring, bool secret) -{ - waitFor(5); - QList users; - currentAction = GPG_INTERNAL; - QString listopt = secret ? "--list-secret-keys " : "--list-keys "; - executeWrapper(gpgExecutable, "--no-tty --with-colons " + listopt + keystring); - process->waitForFinished(2000); - if (process->exitStatus() != QProcess::NormalExit) - return users; - QStringList keys = QString(process->readAllStandardOutput()).split(QRegExp( - "[\r\n]"), - QString::SkipEmptyParts); - UserInfo current_user; - foreach (QString key, keys) { - QStringList props = key.split(':'); - if (props.size() < 10) - continue; - if (props[0] == (secret ? "sec" : "pub")) { - if (!current_user.key_id.isEmpty()) - users.append(current_user); - current_user = UserInfo(); - current_user.key_id = props[4]; - current_user.name = props[9].toUtf8(); - current_user.validity = props[8][0].toLatin1(); - current_user.created.setTime_t(props[5].toInt()); - current_user.expiry.setTime_t(props[6].toInt()); - } else if (current_user.name.isEmpty() && props[0] == "uid") { - current_user.name = props[9]; - } - } - if (!current_user.key_id.isEmpty()) - users.append(current_user); +QList MainWindow::listKeys(QString keystring, bool secret) { + waitFor(5); + QList users; + currentAction = GPG_INTERNAL; + QString listopt = secret ? "--list-secret-keys " : "--list-keys "; + executeWrapper(gpgExecutable, + "--no-tty --with-colons " + listopt + keystring); + process->waitForFinished(2000); + if (process->exitStatus() != QProcess::NormalExit) return users; + QStringList keys = QString(process->readAllStandardOutput()) + .split(QRegExp("[\r\n]"), QString::SkipEmptyParts); + UserInfo current_user; + foreach (QString key, keys) { + QStringList props = key.split(':'); + if (props.size() < 10) + continue; + if (props[0] == (secret ? "sec" : "pub")) { + if (!current_user.key_id.isEmpty()) + users.append(current_user); + current_user = UserInfo(); + current_user.key_id = props[4]; + current_user.name = props[9].toUtf8(); + current_user.validity = props[8][0].toLatin1(); + current_user.created.setTime_t(props[5].toInt()); + current_user.expiry.setTime_t(props[6].toInt()); + } else if (current_user.name.isEmpty() && props[0] == "uid") { + current_user.name = props[9]; + } + } + if (!current_user.key_id.isEmpty()) + users.append(current_user); + return users; } -void MainWindow::userDialog(QString dir) -{ - if (!dir.isEmpty()) - currentDir = dir; - on_usersButton_clicked(); +void MainWindow::userDialog(QString dir) { + if (!dir.isEmpty()) + currentDir = dir; + on_usersButton_clicked(); } -void MainWindow::on_usersButton_clicked() -{ - QList users = listKeys(); - if (users.size() == 0) { - QMessageBox::critical(this, tr("Can not get key list"), - tr("Unable to get list of available gpg keys")); - return; - } - QList secret_keys = listKeys("", true); - foreach (const UserInfo &sec, secret_keys) { - for (QList::iterator it = users.begin(); it != users.end(); ++it) - if (sec.key_id == it->key_id) it->have_secret = true; - } - QList selected_users; - QString dir = currentDir.isEmpty() ? getDir(ui->treeView->currentIndex(), false) : currentDir; - int count = 0; - QString recipients = getRecipientString(dir.isEmpty() ? "" : dir, " ", &count); - if (!recipients.isEmpty()) - selected_users = listKeys(recipients); - foreach (const UserInfo &sel, selected_users) { - for (QList::iterator it = users.begin(); it != users.end(); ++it) - if (sel.key_id == it->key_id) it->enabled = true; - } - if (count > selected_users.size()) { - // Some keys seem missing from keyring, add them separately - QStringList recipients = getRecipientList(dir.isEmpty() ? "" : dir); - foreach (const QString recipient, recipients) { - if (listKeys(recipient).size() < 1) { - UserInfo i; - i.enabled = true; - i.key_id = recipient; - i.name = " ?? " + tr("Key not found in keyring"); - users.append(i); - } - } - } - UsersDialog d(this); - d.setUsers(&users); - if (!d.exec()) { - d.setUsers(NULL); - return; +void MainWindow::on_usersButton_clicked() { + QList users = listKeys(); + if (users.size() == 0) { + QMessageBox::critical(this, tr("Can not get key list"), + tr("Unable to get list of available gpg keys")); + return; + } + QList secret_keys = listKeys("", true); + foreach (const UserInfo &sec, secret_keys) { + for (QList::iterator it = users.begin(); it != users.end(); ++it) + if (sec.key_id == it->key_id) + it->have_secret = true; + } + QList selected_users; + QString dir = currentDir.isEmpty() + ? getDir(ui->treeView->currentIndex(), false) + : currentDir; + int count = 0; + QString recipients = + getRecipientString(dir.isEmpty() ? "" : dir, " ", &count); + if (!recipients.isEmpty()) + selected_users = listKeys(recipients); + foreach (const UserInfo &sel, selected_users) { + for (QList::iterator it = users.begin(); it != users.end(); ++it) + if (sel.key_id == it->key_id) + it->enabled = true; + } + if (count > selected_users.size()) { + // Some keys seem missing from keyring, add them separately + QStringList recipients = getRecipientList(dir.isEmpty() ? "" : dir); + foreach (const QString recipient, recipients) { + if (listKeys(recipient).size() < 1) { + UserInfo i; + i.enabled = true; + i.key_id = recipient; + i.name = " ?? " + tr("Key not found in keyring"); + users.append(i); + } } + } + UsersDialog d(this); + d.setUsers(&users); + if (!d.exec()) { d.setUsers(NULL); - QString gpgIdFile = dir + ".gpg-id"; - QFile gpgId(gpgIdFile); - bool addFile = false; - if (addGPGId) { - QFileInfo checkFile(gpgIdFile); - if (!checkFile.exists() || !checkFile.isFile()) - addFile = true; - } - if (!gpgId.open(QIODevice::WriteOnly | QIODevice::Text)) { - QMessageBox::critical(this, tr("Cannot update"), - tr("Failed to open .gpg-id for writing.")); - return; - } - bool secret_selected = false; - foreach (const UserInfo &user, users) { - if (user.enabled) { - gpgId.write((user.key_id + "\n").toUtf8()); - secret_selected |= user.have_secret; - } - } - gpgId.close(); - if (!secret_selected) { - QMessageBox::critical(this, tr("Check selected users!"), - tr("None of the selected keys have a secret key available.\n" - "You will not be able to decrypt any newly added passwords!")); - } - if (!useWebDav && useGit && !gitExecutable.isEmpty()) { - if (addFile) - executeWrapper(gitExecutable, "add \"" + gpgIdFile + '"'); - QString path = gpgIdFile; - path.replace(QRegExp("\\.gpg$"), ""); - executeWrapper(gitExecutable, - "commit \"" + gpgIdFile + "\" -m \"Added "+ path + " using QtPass.\""); - if (autoPush) - on_pushButton_clicked(); + return; + } + d.setUsers(NULL); + QString gpgIdFile = dir + ".gpg-id"; + QFile gpgId(gpgIdFile); + bool addFile = false; + if (addGPGId) { + QFileInfo checkFile(gpgIdFile); + if (!checkFile.exists() || !checkFile.isFile()) + addFile = true; + } + if (!gpgId.open(QIODevice::WriteOnly | QIODevice::Text)) { + QMessageBox::critical(this, tr("Cannot update"), + tr("Failed to open .gpg-id for writing.")); + return; + } + bool secret_selected = false; + foreach (const UserInfo &user, users) { + if (user.enabled) { + gpgId.write((user.key_id + "\n").toUtf8()); + secret_selected |= user.have_secret; } + } + gpgId.close(); + if (!secret_selected) { + QMessageBox::critical( + this, tr("Check selected users!"), + tr("None of the selected keys have a secret key available.\n" + "You will not be able to decrypt any newly added passwords!")); + } + if (!useWebDav && useGit && !gitExecutable.isEmpty()) { + if (addFile) + executeWrapper(gitExecutable, "add \"" + gpgIdFile + '"'); + QString path = gpgIdFile; + path.replace(QRegExp("\\.gpg$"), ""); + executeWrapper(gitExecutable, "commit \"" + gpgIdFile + "\" -m \"Added " + + path + " using QtPass.\""); + if (autoPush) + on_pushButton_clicked(); + } } /** * @brief MainWindow::setApp * @param app */ -void MainWindow::setApp(SingleApplication *app) -{ +void MainWindow::setApp(SingleApplication *app) { #if SINGLE_APP - connect(app, SIGNAL(messageAvailable(QString)), this, SLOT(messageAvailable(QString))); + connect(app, SIGNAL(messageAvailable(QString)), this, + SLOT(messageAvailable(QString))); #endif } @@ -1369,411 +1335,390 @@ void MainWindow::setApp(SingleApplication *app) * @brief MainWindow::messageAvailable * @param message */ -void MainWindow::messageAvailable(QString message) -{ - if (message.isEmpty()) { - focusInput(); - } else { - ui->treeView->expandAll(); - ui->lineEdit->setText(message); - on_lineEdit_returnPressed(); - } - show(); - raise(); +void MainWindow::messageAvailable(QString message) { + if (message.isEmpty()) { + focusInput(); + } else { + ui->treeView->expandAll(); + ui->lineEdit->setText(message); + on_lineEdit_returnPressed(); + } + show(); + raise(); } /** * @brief MainWindow::setText * @param message */ -void MainWindow::setText(QString text) -{ - ui->lineEdit->setText(text); -} +void MainWindow::setText(QString text) { ui->lineEdit->setText(text); } /** * @brief MainWindow::updateEnv */ -void MainWindow::updateEnv() -{ - QStringList store = env.filter("PASSWORD_STORE_DIR"); - // put PASSWORD_STORE_DIR in env - if (store.isEmpty()) { - // qDebug() << "Added PASSWORD_STORE_DIR"; - env.append("PASSWORD_STORE_DIR=" + passStore); - } else { - // qDebug() << "Update PASSWORD_STORE_DIR with " + passStore; - env.replaceInStrings(store.first(), "PASSWORD_STORE_DIR=" + passStore); - } +void MainWindow::updateEnv() { + QStringList store = env.filter("PASSWORD_STORE_DIR"); + // put PASSWORD_STORE_DIR in env + if (store.isEmpty()) { + // qDebug() << "Added PASSWORD_STORE_DIR"; + env.append("PASSWORD_STORE_DIR=" + passStore); + } else { + // qDebug() << "Update PASSWORD_STORE_DIR with " + passStore; + env.replaceInStrings(store.first(), "PASSWORD_STORE_DIR=" + passStore); + } } /** * @brief MainWindow::getSecretKeys * @return QStringList keys */ -QStringList MainWindow::getSecretKeys() -{ - QList keys = listKeys("", true); - QStringList names; +QStringList MainWindow::getSecretKeys() { + QList keys = listKeys("", true); + QStringList names; - if (keys.size() == 0) - return names; + if (keys.size() == 0) + return names; - foreach (const UserInfo &sec, keys) - names << sec.name; + foreach (const UserInfo &sec, keys) + names << sec.name; - return names; + return names; } /** * @brief Dialog::genKey * @param QString batch */ -void MainWindow::generateKeyPair(QString batch, QDialog *keygenWindow) -{ - keygen = keygenWindow; - ui->statusBar->showMessage(tr("Generating GPG key pair"), 60000); - currentAction = GPG_INTERNAL; - executeWrapper(gpgExecutable, "--gen-key --no-tty --batch", batch); +void MainWindow::generateKeyPair(QString batch, QDialog *keygenWindow) { + keygen = keygenWindow; + ui->statusBar->showMessage(tr("Generating GPG key pair"), 60000); + currentAction = GPG_INTERNAL; + executeWrapper(gpgExecutable, "--gen-key --no-tty --batch", batch); } /** * @brief MainWindow::updateProfileBox */ -void MainWindow::updateProfileBox() -{ - // qDebug() << profiles.size(); - if (profiles.isEmpty()) { - ui->profileBox->hide(); - } else { - ui->profileBox->show(); - if (profiles.size() < 2) - ui->profileBox->setEnabled(false); - else - ui->profileBox->setEnabled(true); - ui->profileBox->clear(); - QHashIterator i(profiles); - while (i.hasNext()) { - i.next(); - if (!i.key().isEmpty()) - ui->profileBox->addItem(i.key()); - } +void MainWindow::updateProfileBox() { + // qDebug() << profiles.size(); + if (profiles.isEmpty()) { + ui->profileBox->hide(); + } else { + ui->profileBox->show(); + if (profiles.size() < 2) + ui->profileBox->setEnabled(false); + else + ui->profileBox->setEnabled(true); + ui->profileBox->clear(); + QHashIterator i(profiles); + while (i.hasNext()) { + i.next(); + if (!i.key().isEmpty()) + ui->profileBox->addItem(i.key()); } - int index = ui->profileBox->findText(profile); - if (index != -1) // -1 for not found - ui->profileBox->setCurrentIndex(index); + } + int index = ui->profileBox->findText(profile); + if (index != -1) // -1 for not found + ui->profileBox->setCurrentIndex(index); } /** * @brief MainWindow::on_profileBox_currentIndexChanged * @param name */ -void MainWindow::on_profileBox_currentIndexChanged(QString name) -{ - if (startupPhase || name == profile) - return; - profile = name; - - passStore = profiles[name]; - ui->statusBar->showMessage(tr("Profile changed to %1").arg(name), 2000); - - QSettings &settings(getSettings()); - - settings.setValue("profile", profile); - settings.setValue("passStore", passStore); - - // qDebug() << env; - QStringList store = env.filter("PASSWORD_STORE_DIR"); - // put PASSWORD_STORE_DIR in env - if (store.isEmpty()) { - // qDebug() << "Added PASSWORD_STORE_DIR"; - env.append("PASSWORD_STORE_DIR=" + passStore); - } else { - // qDebug() << "Update PASSWORD_STORE_DIR"; - env.replaceInStrings(store.first(), "PASSWORD_STORE_DIR=" + passStore); - } - - ui->treeView->setRootIndex(proxyModel.mapFromSource(model.setRootPath(passStore))); +void MainWindow::on_profileBox_currentIndexChanged(QString name) { + if (startupPhase || name == profile) + return; + profile = name; + + passStore = profiles[name]; + ui->statusBar->showMessage(tr("Profile changed to %1").arg(name), 2000); + + QSettings &settings(getSettings()); + + settings.setValue("profile", profile); + settings.setValue("passStore", passStore); + + // qDebug() << env; + QStringList store = env.filter("PASSWORD_STORE_DIR"); + // put PASSWORD_STORE_DIR in env + if (store.isEmpty()) { + // qDebug() << "Added PASSWORD_STORE_DIR"; + env.append("PASSWORD_STORE_DIR=" + passStore); + } else { + // qDebug() << "Update PASSWORD_STORE_DIR"; + env.replaceInStrings(store.first(), "PASSWORD_STORE_DIR=" + passStore); + } + + ui->treeView->setRootIndex( + proxyModel.mapFromSource(model.setRootPath(passStore))); } /** * @brief MainWindow::initTrayIcon */ -void MainWindow::initTrayIcon() -{ - if (tray != NULL) { - qDebug() << "Creating tray icon again?"; - return; - } - if (QSystemTrayIcon::isSystemTrayAvailable() == true) { - // Setup tray icon - this->tray = new TrayIcon(this); - if (tray == NULL) - qDebug() << "Allocating tray icon failed."; - } else { - qDebug() << "No tray icon for this OS possibly also not show options?"; - } +void MainWindow::initTrayIcon() { + if (tray != NULL) { + qDebug() << "Creating tray icon again?"; + return; + } + if (QSystemTrayIcon::isSystemTrayAvailable() == true) { + // Setup tray icon + this->tray = new TrayIcon(this); + if (tray == NULL) + qDebug() << "Allocating tray icon failed."; + } else { + qDebug() << "No tray icon for this OS possibly also not show options?"; + } } /** * @brief MainWindow::destroyTrayIcon */ -void MainWindow::destroyTrayIcon() -{ - if (tray == NULL) { - qDebug() << "Destroy non existing tray icon?"; - return; - } - delete this->tray; - tray = NULL; +void MainWindow::destroyTrayIcon() { + if (tray == NULL) { + qDebug() << "Destroy non existing tray icon?"; + return; + } + delete this->tray; + tray = NULL; } /** * @brief MainWindow::closeEvent * @param event */ -void MainWindow::closeEvent(QCloseEvent *event) -{ - if (hideOnClose) { - this->hide(); - event->ignore(); - } else { - settings->beginGroup("mainwindow"); - settings->setValue("geometry", saveGeometry()); - settings->setValue("savestate", saveState()); - settings->setValue("maximized", isMaximized()); - if (!isMaximized()) { - settings->setValue("pos", pos()); - settings->setValue("size", size()); - } - settings->setValue("splitterLeft", ui->splitter->sizes()[0]); - settings->setValue("splitterRight", ui->splitter->sizes()[1]); - settings->endGroup(); - event->accept(); +void MainWindow::closeEvent(QCloseEvent *event) { + if (hideOnClose) { + this->hide(); + event->ignore(); + } else { + settings->beginGroup("mainwindow"); + settings->setValue("geometry", saveGeometry()); + settings->setValue("savestate", saveState()); + settings->setValue("maximized", isMaximized()); + if (!isMaximized()) { + settings->setValue("pos", pos()); + settings->setValue("size", size()); } + settings->setValue("splitterLeft", ui->splitter->sizes()[0]); + settings->setValue("splitterRight", ui->splitter->sizes()[1]); + settings->endGroup(); + event->accept(); + } } -void MainWindow::on_copyPasswordButton_clicked() -{ - copyPasswordToClipboard(); -} +void MainWindow::on_copyPasswordButton_clicked() { copyPasswordToClipboard(); } /** * @brief MainWindow::showContextMenu * @param pos */ -void MainWindow::showContextMenu(const QPoint &pos) -{ - QModelIndex index = ui->treeView->indexAt(pos); - bool selected = true; - if (!index.isValid()) { - ui->treeView->clearSelection(); - ui->deleteButton->setEnabled(false); - ui->editButton->setEnabled(false); - currentDir = ""; - selected = false; - } - - ui->treeView->setCurrentIndex(index); - - QPoint globalPos = ui->treeView->viewport()->mapToGlobal(pos); - - QFileInfo fileOrFolder = model.fileInfo(proxyModel.mapToSource(ui->treeView->currentIndex())); - - QMenu contextMenu; - if (!selected || fileOrFolder.isDir()) { - QAction *addFolder = contextMenu.addAction(tr("Add folder")); - QAction *addPassword = contextMenu.addAction(tr("Add password")); - QAction *users = contextMenu.addAction(tr("Users")); - connect(addFolder, SIGNAL(triggered()), this, SLOT(addFolder())); - connect(addPassword, SIGNAL(triggered()), this, SLOT(on_addButton_clicked())); - connect(users, SIGNAL(triggered()), this, SLOT(on_usersButton_clicked())); - } else if (fileOrFolder.isFile()) { - QAction *edit = contextMenu.addAction(tr("Edit")); - connect(edit, SIGNAL(triggered()), this, SLOT(editPassword())); - } - if (selected) { - // if (useClipboard != CLIPBOARD_NEVER) { - // contextMenu.addSeparator(); - // QAction* copyItem = contextMenu.addAction(tr("Copy Password")); - // if (getClippedPassword().length() == 0) copyItem->setEnabled(false); - // connect(copyItem, SIGNAL(triggered()), this, SLOT(copyPasswordToClipboard())); - // } - contextMenu.addSeparator(); - QAction *deleteItem = contextMenu.addAction(tr("Delete")); - connect(deleteItem, SIGNAL(triggered()), this, SLOT(on_deleteButton_clicked())); - } - - contextMenu.exec(globalPos); +void MainWindow::showContextMenu(const QPoint &pos) { + QModelIndex index = ui->treeView->indexAt(pos); + bool selected = true; + if (!index.isValid()) { + ui->treeView->clearSelection(); + ui->deleteButton->setEnabled(false); + ui->editButton->setEnabled(false); + currentDir = ""; + selected = false; + } + + ui->treeView->setCurrentIndex(index); + + QPoint globalPos = ui->treeView->viewport()->mapToGlobal(pos); + + QFileInfo fileOrFolder = + model.fileInfo(proxyModel.mapToSource(ui->treeView->currentIndex())); + + QMenu contextMenu; + if (!selected || fileOrFolder.isDir()) { + QAction *addFolder = contextMenu.addAction(tr("Add folder")); + QAction *addPassword = contextMenu.addAction(tr("Add password")); + QAction *users = contextMenu.addAction(tr("Users")); + connect(addFolder, SIGNAL(triggered()), this, SLOT(addFolder())); + connect(addPassword, SIGNAL(triggered()), this, + SLOT(on_addButton_clicked())); + connect(users, SIGNAL(triggered()), this, SLOT(on_usersButton_clicked())); + } else if (fileOrFolder.isFile()) { + QAction *edit = contextMenu.addAction(tr("Edit")); + connect(edit, SIGNAL(triggered()), this, SLOT(editPassword())); + } + if (selected) { + // if (useClipboard != CLIPBOARD_NEVER) { + // contextMenu.addSeparator(); + // QAction* copyItem = contextMenu.addAction(tr("Copy Password")); + // if (getClippedPassword().length() == 0) copyItem->setEnabled(false); + // connect(copyItem, SIGNAL(triggered()), this, + // SLOT(copyPasswordToClipboard())); + // } + contextMenu.addSeparator(); + QAction *deleteItem = contextMenu.addAction(tr("Delete")); + connect(deleteItem, SIGNAL(triggered()), this, + SLOT(on_deleteButton_clicked())); + } + + contextMenu.exec(globalPos); } /** * @brief MainWindow::showContextMenu * @param pos */ -void MainWindow::showBrowserContextMenu(const QPoint &pos) -{ - QMenu *contextMenu = ui->textBrowser->createStandardContextMenu(pos); - - if (useClipboard != CLIPBOARD_NEVER) { - contextMenu->addSeparator(); - QAction *copyItem = contextMenu->addAction(tr("Copy Password")); - if (getClippedPassword().length() == 0) copyItem->setEnabled(false); - connect(copyItem, \ - SIGNAL(triggered()), \ - this, \ - SLOT(copyPasswordToClipboard())); - } - QPoint globalPos = ui->textBrowser->viewport()->mapToGlobal(pos); - - contextMenu->exec(globalPos); +void MainWindow::showBrowserContextMenu(const QPoint &pos) { + QMenu *contextMenu = ui->textBrowser->createStandardContextMenu(pos); + + if (useClipboard != CLIPBOARD_NEVER) { + contextMenu->addSeparator(); + QAction *copyItem = contextMenu->addAction(tr("Copy Password")); + if (getClippedPassword().length() == 0) + copyItem->setEnabled(false); + connect(copyItem, SIGNAL(triggered()), this, + SLOT(copyPasswordToClipboard())); + } + QPoint globalPos = ui->textBrowser->viewport()->mapToGlobal(pos); + + contextMenu->exec(globalPos); } /** * @brief MainWindow::addFolder */ -void MainWindow::addFolder() -{ - bool ok; - QString dir = getDir(ui->treeView->currentIndex(), false); - QString newdir = QInputDialog::getText(this, tr("New file"), - tr("New folder, will be placed in folder %1:").arg(QDir:: - separator() - + - getDir( - ui->treeView->currentIndex(), true)), QLineEdit::Normal, - "", &ok); - if (!ok || newdir.isEmpty()) - return; - newdir.prepend(dir); - // qDebug() << newdir; - QDir().mkdir(newdir); - // TODO add to git? +void MainWindow::addFolder() { + bool ok; + QString dir = getDir(ui->treeView->currentIndex(), false); + QString newdir = QInputDialog::getText( + this, tr("New file"), + tr("New folder, will be placed in folder %1:") + .arg(QDir::separator() + getDir(ui->treeView->currentIndex(), true)), + QLineEdit::Normal, "", &ok); + if (!ok || newdir.isEmpty()) + return; + newdir.prepend(dir); + // qDebug() << newdir; + QDir().mkdir(newdir); + // TODO add to git? } /** * @brief MainWindow::editPassword */ -void MainWindow::editPassword() -{ - if (useGit && autoPull) - on_updateButton_clicked(); - waitFor(30); - // TODO move to editbutton stuff possibly? - currentDir = getDir(ui->treeView->currentIndex(), false); - lastDecrypt = "Could not decrypt"; - QString file = getFile(ui->treeView->currentIndex(), usePass); - if (!file.isEmpty()) { - currentAction = GPG; - if (usePass) - executePass('"' + file + '"'); - else - executeWrapper(gpgExecutable, - "-d --quiet --yes --no-encrypt-to --batch --use-agent \"" + file + '"'); - process->waitForFinished(30000); // long wait (passphrase stuff) - if (process->exitStatus() == QProcess::NormalExit) - on_editButton_clicked(); - } +void MainWindow::editPassword() { + if (useGit && autoPull) + on_updateButton_clicked(); + waitFor(30); + // TODO move to editbutton stuff possibly? + currentDir = getDir(ui->treeView->currentIndex(), false); + lastDecrypt = "Could not decrypt"; + QString file = getFile(ui->treeView->currentIndex(), usePass); + if (!file.isEmpty()) { + currentAction = GPG; + if (usePass) + executePass('"' + file + '"'); + else + executeWrapper(gpgExecutable, + "-d --quiet --yes --no-encrypt-to --batch --use-agent \"" + + file + '"'); + process->waitForFinished(30000); // long wait (passphrase stuff) + if (process->exitStatus() == QProcess::NormalExit) + on_editButton_clicked(); + } } /** * @brief MainWindow::generatePassword * @return */ -QString MainWindow::generatePassword() -{ - QString passwd; - if (usePwgen) { - waitFor(2); - QString args = (useSymbols ? "--symbols -1 " : "-1 ") + QString::number(passwordLength); - currentAction = PWGEN; - executeWrapper(pwgenExecutable, args); - process->waitForFinished(1000); - if (process->exitStatus() == QProcess::NormalExit) - passwd = QString(process->readAllStandardOutput()).remove(QRegExp("[\\n\\r]")); - else - qDebug() << "pwgen fail"; +QString MainWindow::generatePassword() { + QString passwd; + if (usePwgen) { + waitFor(2); + QString args = (useSymbols ? "--symbols -1 " : "-1 ") + + QString::number(passwordLength); + currentAction = PWGEN; + executeWrapper(pwgenExecutable, args); + process->waitForFinished(1000); + if (process->exitStatus() == QProcess::NormalExit) + passwd = + QString(process->readAllStandardOutput()).remove(QRegExp("[\\n\\r]")); + else + qDebug() << "pwgen fail"; + } else { + int length = passwordChars.length(); + if (length > 0) { + for (int i = 0; i < passwordLength; ++i) { + int index = qrand() % length; + QChar nextChar = passwordChars.at(index); + passwd.append(nextChar); + } } else { - int length = passwordChars.length(); - if (length > 0) { - for (int i = 0; i < passwordLength; ++i) { - int index = qrand() % length; - QChar nextChar = passwordChars.at(index); - passwd.append(nextChar); - } - } else { - QMessageBox::critical(this, tr("No characters chosen"), - tr( - "Can't generate password, there are no characters to choose from set in the configuration!")); - } + QMessageBox::critical( + this, tr("No characters chosen"), + tr("Can't generate password, there are no characters to choose from " + "set in the configuration!")); } - return passwd; + } + return passwd; } /** * @brief MainWindow::waitFor * @param seconds */ -void MainWindow::waitFor(int seconds) -{ - QDateTime current = QDateTime::currentDateTime(); - uint stop = current.toTime_t() + seconds; - while (!process->atEnd() || !execQueue->isEmpty()) { - current = QDateTime::currentDateTime(); - if (stop < current.toTime_t()) { - QMessageBox::critical(this, tr("Timed out"), - tr("Can't start process, previous one is still running!")); - return; - } - Util::qSleep(100); +void MainWindow::waitFor(int seconds) { + QDateTime current = QDateTime::currentDateTime(); + uint stop = current.toTime_t() + seconds; + while (!process->atEnd() || !execQueue->isEmpty()) { + current = QDateTime::currentDateTime(); + if (stop < current.toTime_t()) { + QMessageBox::critical( + this, tr("Timed out"), + tr("Can't start process, previous one is still running!")); + return; } + Util::qSleep(100); + } } /** * @brief MainWindow::clearTemplateWidgets */ -void MainWindow::clearTemplateWidgets() -{ - while (ui->formLayout->count() > 0) { - QLayoutItem *item = ui->formLayout->takeAt(0); - delete item->widget(); - delete item; - } - ui->verticalLayoutPassword->setSpacing(0); +void MainWindow::clearTemplateWidgets() { + while (ui->formLayout->count() > 0) { + QLayoutItem *item = ui->formLayout->takeAt(0); + delete item->widget(); + delete item; + } + ui->verticalLayoutPassword->setSpacing(0); } /* - * @brief Mainwindow::copyPasswordToClipboard - copy the clipped password (if not "") to the clipboard + * @brief Mainwindow::copyPasswordToClipboard - copy the clipped password (if + * not "") to the clipboard * @return */ -void MainWindow::copyPasswordToClipboard() -{ - if (clippedPass.length() > 0) { - QClipboard *clip = QApplication::clipboard(); - clip->setText(clippedPass); - ui->statusBar->showMessage(tr("Password copied to clipboard"), 3000); - if (useAutoclear) { - QTimer::singleShot(1000*autoclearSeconds, \ - this, \ - SLOT(clearClipboard())); - } +void MainWindow::copyPasswordToClipboard() { + if (clippedPass.length() > 0) { + QClipboard *clip = QApplication::clipboard(); + clip->setText(clippedPass); + ui->statusBar->showMessage(tr("Password copied to clipboard"), 3000); + if (useAutoclear) { + QTimer::singleShot(1000 * autoclearSeconds, this, SLOT(clearClipboard())); } + } } /** * @brief Mainwindow::setClippedPassword - set the stored clipped password * @return none */ -void MainWindow::setClippedPassword(const QString &pass) -{ - clippedPass = pass; - if (clippedPass.length() == 0) - ui->copyPasswordButton->setEnabled(false); - else - ui->copyPasswordButton->setEnabled(true); +void MainWindow::setClippedPassword(const QString &pass) { + clippedPass = pass; + if (clippedPass.length() == 0) + ui->copyPasswordButton->setEnabled(false); + else + ui->copyPasswordButton->setEnabled(true); } -const QString &MainWindow::getClippedPassword() -{ - return clippedPass; -} +const QString &MainWindow::getClippedPassword() { return clippedPass; } diff --git a/mainwindow.h b/mainwindow.h index 85fdfbdf2..0b90ac6c8 100644 --- a/mainwindow.h +++ b/mainwindow.h @@ -21,153 +21,151 @@ class MainWindow; } struct execQueueItem { - QString app; - QString args; - QString input; + QString app; + QString args; + QString input; }; struct UserInfo; -class MainWindow : public QMainWindow -{ - Q_OBJECT +class MainWindow : public QMainWindow { + Q_OBJECT - enum actionType { - GPG, GIT, EDIT, DELETE, GPG_INTERNAL, PWGEN - }; + enum actionType { GPG, GIT, EDIT, DELETE, GPG_INTERNAL, PWGEN }; public: - enum clipBoardType { - CLIPBOARD_NEVER = 0, - CLIPBOARD_ALWAYS = 1, - CLIPBOARD_ON_DEMAND = 2 - }; + enum clipBoardType { + CLIPBOARD_NEVER = 0, + CLIPBOARD_ALWAYS = 1, + CLIPBOARD_ON_DEMAND = 2 + }; - explicit MainWindow(QWidget *parent = 0); - ~MainWindow(); - void setPassExecutable(QString); - void setGitExecutable(QString); - void setGpgExecutable(QString); - QString getGpgExecutable(); - bool checkConfig(); - void setApp(SingleApplication *app); - void setText(QString); - QStringList getSecretKeys(); - void generateKeyPair(QString, QDialog *); - void userDialog(QString = ""); - QString generatePassword(); - void config(); - void executePassGitInit(); + explicit MainWindow(QWidget *parent = 0); + ~MainWindow(); + void setPassExecutable(QString); + void setGitExecutable(QString); + void setGpgExecutable(QString); + QString getGpgExecutable(); + bool checkConfig(); + void setApp(SingleApplication *app); + void setText(QString); + QStringList getSecretKeys(); + void generateKeyPair(QString, QDialog *); + void userDialog(QString = ""); + QString generatePassword(); + void config(); + void executePassGitInit(); protected: - void closeEvent(QCloseEvent *event); + void closeEvent(QCloseEvent *event); private slots: - void on_updateButton_clicked(); - void on_pushButton_clicked(); - void on_treeView_clicked(const QModelIndex &index); - void on_configButton_clicked(); - void readyRead(bool finished); - void processFinished(int, QProcess::ExitStatus); - void processError(QProcess::ProcessError); - void clearClipboard(); - void clearPanel(); - void on_lineEdit_textChanged(const QString &arg1); - void on_lineEdit_returnPressed(); - void on_clearButton_clicked(); - void on_addButton_clicked(); - void on_deleteButton_clicked(); - void on_editButton_clicked(); - void on_usersButton_clicked(); - void messageAvailable(QString message); - void on_profileBox_currentIndexChanged(QString); - void on_copyPasswordButton_clicked(); - void showContextMenu(const QPoint &pos); - void showBrowserContextMenu(const QPoint &pos); - void addFolder(); - void editPassword(); - void focusInput(); - void copyPasswordToClipboard(); + void on_updateButton_clicked(); + void on_pushButton_clicked(); + void on_treeView_clicked(const QModelIndex &index); + void on_configButton_clicked(); + void readyRead(bool finished); + void processFinished(int, QProcess::ExitStatus); + void processError(QProcess::ProcessError); + void clearClipboard(); + void clearPanel(); + void on_lineEdit_textChanged(const QString &arg1); + void on_lineEdit_returnPressed(); + void on_clearButton_clicked(); + void on_addButton_clicked(); + void on_deleteButton_clicked(); + void on_editButton_clicked(); + void on_usersButton_clicked(); + void messageAvailable(QString message); + void on_profileBox_currentIndexChanged(QString); + void on_copyPasswordButton_clicked(); + void showContextMenu(const QPoint &pos); + void showBrowserContextMenu(const QPoint &pos); + void addFolder(); + void editPassword(); + void focusInput(); + void copyPasswordToClipboard(); private: - QApplication *QtPass; - QScopedPointer settings; - QScopedPointer ui; - QFileSystemModel model; - StoreModel proxyModel; - QScopedPointer selectionModel; - QScopedPointer process; - bool usePass; - clipBoardType useClipboard; - bool useAutoclear; - bool useAutoclearPanel; - bool hidePassword; - bool hideContent; - bool addGPGId; - int autoclearSeconds; - int autoclearPanelSeconds; - QString passStore; - QString passExecutable; - QString gitExecutable; - QString gpgExecutable; - QString pwgenExecutable; - QString gpgHome; - bool useWebDav; - QString webDavUrl; - QString webDavUser; - QString webDavPassword; - QProcess fusedav; - QString clippedPass; - QString autoclearPass; - QTimer *autoclearTimer; - actionType currentAction; - QString lastDecrypt; - bool wrapperRunning; - QStringList env; - QQueue *execQueue; - bool freshStart; - QDialog *keygen; - QString currentDir; - QHash profiles; - QString profile; - bool startupPhase; - TrayIcon *tray; - bool useTrayIcon; - bool hideOnClose; - bool startMinimized; - bool useGit; - bool usePwgen; - bool useSymbols; - int passwordLength; - QString passwordChars; - bool useTemplate; - QString passTemplate; - bool templateAllFields; - bool autoPull; - bool autoPush; - void updateText(); - void executePass(QString, QString = QString()); - void executeWrapper(QString, QString, QString = QString()); - void enableUiElements(bool); - void selectFirstFile(); - QModelIndex firstFile(QModelIndex parentIndex); - QString getDir(const QModelIndex &, bool); - QString getFile(const QModelIndex &, bool); - void setPassword(QString, bool, bool); - QSettings &getSettings(); - QList listKeys(QString keystring = "", bool secret = false); - QStringList getRecipientList(QString for_file); - QString getRecipientString(QString for_file, QString separator = " ", int *count = NULL); - void mountWebDav(); - void updateEnv(); - void updateProfileBox(); - void initTrayIcon(); - void destroyTrayIcon(); - bool removeDir(const QString &dirName); - void waitFor(int); - void clearTemplateWidgets(); - void setClippedPassword(const QString &pass); - const QString &getClippedPassword(); + QApplication *QtPass; + QScopedPointer settings; + QScopedPointer ui; + QFileSystemModel model; + StoreModel proxyModel; + QScopedPointer selectionModel; + QScopedPointer process; + bool usePass; + clipBoardType useClipboard; + bool useAutoclear; + bool useAutoclearPanel; + bool hidePassword; + bool hideContent; + bool addGPGId; + int autoclearSeconds; + int autoclearPanelSeconds; + QString passStore; + QString passExecutable; + QString gitExecutable; + QString gpgExecutable; + QString pwgenExecutable; + QString gpgHome; + bool useWebDav; + QString webDavUrl; + QString webDavUser; + QString webDavPassword; + QProcess fusedav; + QString clippedPass; + QString autoclearPass; + QTimer *autoclearTimer; + actionType currentAction; + QString lastDecrypt; + bool wrapperRunning; + QStringList env; + QQueue *execQueue; + bool freshStart; + QDialog *keygen; + QString currentDir; + QHash profiles; + QString profile; + bool startupPhase; + TrayIcon *tray; + bool useTrayIcon; + bool hideOnClose; + bool startMinimized; + bool useGit; + bool usePwgen; + bool useSymbols; + int passwordLength; + QString passwordChars; + bool useTemplate; + QString passTemplate; + bool templateAllFields; + bool autoPull; + bool autoPush; + void updateText(); + void executePass(QString, QString = QString()); + void executeWrapper(QString, QString, QString = QString()); + void enableUiElements(bool); + void selectFirstFile(); + QModelIndex firstFile(QModelIndex parentIndex); + QString getDir(const QModelIndex &, bool); + QString getFile(const QModelIndex &, bool); + void setPassword(QString, bool, bool); + QSettings &getSettings(); + QList listKeys(QString keystring = "", bool secret = false); + QStringList getRecipientList(QString for_file); + QString getRecipientString(QString for_file, QString separator = " ", + int *count = NULL); + void mountWebDav(); + void updateEnv(); + void updateProfileBox(); + void initTrayIcon(); + void destroyTrayIcon(); + bool removeDir(const QString &dirName); + void waitFor(int); + void clearTemplateWidgets(); + void setClippedPassword(const QString &pass); + const QString &getClippedPassword(); }; #endif // MAINWINDOW_H diff --git a/passworddialog.cpp b/passworddialog.cpp index 6b939d3a3..fb081a3d2 100644 --- a/passworddialog.cpp +++ b/passworddialog.cpp @@ -4,125 +4,108 @@ #include #include -PasswordDialog::PasswordDialog(MainWindow *parent) : - QDialog(parent), - ui(new Ui::PasswordDialog) -{ - mainWindow = parent; - templating = false; - allFields = false; - ui->setupUi(this); +PasswordDialog::PasswordDialog(MainWindow *parent) + : QDialog(parent), ui(new Ui::PasswordDialog) { + mainWindow = parent; + templating = false; + allFields = false; + ui->setupUi(this); } -PasswordDialog::~PasswordDialog() -{ - delete ui; -} +PasswordDialog::~PasswordDialog() { delete ui; } -void PasswordDialog::on_checkBoxShow_stateChanged(int arg1) -{ - if (arg1) - ui->lineEditPassword->setEchoMode(QLineEdit::Normal); - else - ui->lineEditPassword->setEchoMode(QLineEdit::Password); +void PasswordDialog::on_checkBoxShow_stateChanged(int arg1) { + if (arg1) + ui->lineEditPassword->setEchoMode(QLineEdit::Normal); + else + ui->lineEditPassword->setEchoMode(QLineEdit::Password); } -void PasswordDialog::on_createPasswordButton_clicked() -{ - ui->widget->setEnabled(false); - ui->lineEditPassword->setText(mainWindow->generatePassword()); - ui->widget->setEnabled(true); +void PasswordDialog::on_createPasswordButton_clicked() { + ui->widget->setEnabled(false); + ui->lineEditPassword->setText(mainWindow->generatePassword()); + ui->widget->setEnabled(true); } -void PasswordDialog::setPassword(QString password) -{ - QStringList tokens = password.split("\n"); - ui->lineEditPassword->setText(tokens[0]); - tokens.pop_front(); - if (templating) { - QWidget *previous = ui->checkBoxShow; - for (int i = 0; i < ui->formLayout->rowCount(); i++) { - QLayoutItem *item = ui->formLayout->itemAt(i, QFormLayout::FieldRole); - if (item == NULL) - continue; - QWidget *widget = item->widget(); - for (int j = 0; j < tokens.length(); j++) { - QString token = tokens.at(j); - if (token.startsWith(widget->objectName()+':')) { - tokens.removeAt(j); - QString value = token.remove(0, widget->objectName().length()+1); - ((QLineEdit *)widget)->setText(value); - } - } - previous = widget; +void PasswordDialog::setPassword(QString password) { + QStringList tokens = password.split("\n"); + ui->lineEditPassword->setText(tokens[0]); + tokens.pop_front(); + if (templating) { + QWidget *previous = ui->checkBoxShow; + for (int i = 0; i < ui->formLayout->rowCount(); i++) { + QLayoutItem *item = ui->formLayout->itemAt(i, QFormLayout::FieldRole); + if (item == NULL) + continue; + QWidget *widget = item->widget(); + for (int j = 0; j < tokens.length(); j++) { + QString token = tokens.at(j); + if (token.startsWith(widget->objectName() + ':')) { + tokens.removeAt(j); + QString value = token.remove(0, widget->objectName().length() + 1); + ((QLineEdit *)widget)->setText(value); } - if (allFields) { - for (int j = 0; j < tokens.length(); j++) { - QString token = tokens.at(j); - if (token.contains(':')) { - int colon = token.indexOf(':'); - QString field = token.left(colon); - QString value = token.right(token.length()-colon-1); - if (!passTemplate.contains(field) && value.startsWith("//")) - continue; // colon is probably from a url - QLineEdit *line = new QLineEdit(); - line->setObjectName(field); - line->setText(value); - ui->formLayout->addRow(new QLabel(field), line); - setTabOrder(previous, line); - previous = line; - tokens.removeAt(j); - j--; // tokens.length() also got shortened by the remove.. - } - } + } + previous = widget; + } + if (allFields) { + for (int j = 0; j < tokens.length(); j++) { + QString token = tokens.at(j); + if (token.contains(':')) { + int colon = token.indexOf(':'); + QString field = token.left(colon); + QString value = token.right(token.length() - colon - 1); + if (!passTemplate.contains(field) && value.startsWith("//")) + continue; // colon is probably from a url + QLineEdit *line = new QLineEdit(); + line->setObjectName(field); + line->setText(value); + ui->formLayout->addRow(new QLabel(field), line); + setTabOrder(previous, line); + previous = line; + tokens.removeAt(j); + j--; // tokens.length() also got shortened by the remove.. } + } } - ui->plainTextEdit->insertPlainText(tokens.join("\n")); + } + ui->plainTextEdit->insertPlainText(tokens.join("\n")); } -QString PasswordDialog::getPassword() -{ - QString passFile = ui->lineEditPassword->text() + "\n"; - for (int i = 0; i < ui->formLayout->rowCount(); i++) { - QLayoutItem *item = ui->formLayout->itemAt(i, QFormLayout::FieldRole); - if (item == NULL) - continue; - QWidget *widget = item->widget(); - QString text = ((QLineEdit *)widget)->text(); - if (text.isEmpty()) - continue; - passFile += widget->objectName() + ":" + text + "\n"; - } - passFile += ui->plainTextEdit->toPlainText(); - return passFile; +QString PasswordDialog::getPassword() { + QString passFile = ui->lineEditPassword->text() + "\n"; + for (int i = 0; i < ui->formLayout->rowCount(); i++) { + QLayoutItem *item = ui->formLayout->itemAt(i, QFormLayout::FieldRole); + if (item == NULL) + continue; + QWidget *widget = item->widget(); + QString text = ((QLineEdit *)widget)->text(); + if (text.isEmpty()) + continue; + passFile += widget->objectName() + ":" + text + "\n"; + } + passFile += ui->plainTextEdit->toPlainText(); + return passFile; } -void PasswordDialog::setTemplate(QString rawFields) -{ - fields = rawFields.split('\n'); - QWidget *previous = ui->checkBoxShow; - foreach (QString field, fields) { - if (field.isEmpty()) - continue; - QLineEdit *line = new QLineEdit(); - line->setObjectName(field); - ui->formLayout->addRow(new QLabel(field), line); - setTabOrder(previous, line); - previous = line; - } +void PasswordDialog::setTemplate(QString rawFields) { + fields = rawFields.split('\n'); + QWidget *previous = ui->checkBoxShow; + foreach (QString field, fields) { + if (field.isEmpty()) + continue; + QLineEdit *line = new QLineEdit(); + line->setObjectName(field); + ui->formLayout->addRow(new QLabel(field), line); + setTabOrder(previous, line); + previous = line; + } } -void PasswordDialog::setFile(QString file) -{ - this->setWindowTitle(this->windowTitle()+" "+file); +void PasswordDialog::setFile(QString file) { + this->setWindowTitle(this->windowTitle() + " " + file); } -void PasswordDialog::templateAll(bool templateAll) -{ - allFields = templateAll; -} +void PasswordDialog::templateAll(bool templateAll) { allFields = templateAll; } -void PasswordDialog::useTemplate(bool useTemplate) -{ - templating = useTemplate; -} +void PasswordDialog::useTemplate(bool useTemplate) { templating = useTemplate; } diff --git a/passworddialog.h b/passworddialog.h index 2ab2e5f8e..7df25da17 100644 --- a/passworddialog.h +++ b/passworddialog.h @@ -8,31 +8,30 @@ namespace Ui { class PasswordDialog; } -class PasswordDialog : public QDialog -{ - Q_OBJECT +class PasswordDialog : public QDialog { + Q_OBJECT public: - explicit PasswordDialog(MainWindow *parent = 0); - ~PasswordDialog(); - void setPassword(QString); - QString getPassword(); - void setTemplate(QString); - void setFile(QString); - void useTemplate(bool); - void templateAll(bool); + explicit PasswordDialog(MainWindow *parent = 0); + ~PasswordDialog(); + void setPassword(QString); + QString getPassword(); + void setTemplate(QString); + void setFile(QString); + void useTemplate(bool); + void templateAll(bool); private slots: - void on_checkBoxShow_stateChanged(int arg1); - void on_createPasswordButton_clicked(); + void on_checkBoxShow_stateChanged(int arg1); + void on_createPasswordButton_clicked(); private: - Ui::PasswordDialog *ui; - MainWindow *mainWindow; - QString passTemplate; - QStringList fields; - bool templating; - bool allFields; + Ui::PasswordDialog *ui; + MainWindow *mainWindow; + QString passTemplate; + QStringList fields; + bool templating; + bool allFields; }; #endif // PASSWORDDIALOG_H diff --git a/progressindicator.cpp b/progressindicator.cpp index 164bb8aa3..d1bb5fa2b 100644 --- a/progressindicator.cpp +++ b/progressindicator.cpp @@ -2,115 +2,94 @@ #include -QProgressIndicator::QProgressIndicator(QWidget *parent) : - QWidget(parent), - m_angle(0), - m_timerId(-1), - m_delay(40), - m_displayedWhenStopped(false), - m_color(Qt::black) -{ - setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed); - setFocusPolicy(Qt::NoFocus); +QProgressIndicator::QProgressIndicator(QWidget *parent) + : QWidget(parent), m_angle(0), m_timerId(-1), m_delay(40), + m_displayedWhenStopped(false), m_color(Qt::black) { + setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed); + setFocusPolicy(Qt::NoFocus); } -bool QProgressIndicator::isAnimated() const -{ - return m_timerId != -1; -} +bool QProgressIndicator::isAnimated() const { return m_timerId != -1; } -void QProgressIndicator::setDisplayedWhenStopped(bool state) -{ - m_displayedWhenStopped = state; +void QProgressIndicator::setDisplayedWhenStopped(bool state) { + m_displayedWhenStopped = state; - update(); + update(); } -bool QProgressIndicator::isDisplayedWhenStopped() const -{ - return m_displayedWhenStopped; +bool QProgressIndicator::isDisplayedWhenStopped() const { + return m_displayedWhenStopped; } -void QProgressIndicator::startAnimation() -{ - m_angle = 0; +void QProgressIndicator::startAnimation() { + m_angle = 0; - if (m_timerId == -1) - m_timerId = startTimer(m_delay); + if (m_timerId == -1) + m_timerId = startTimer(m_delay); } -void QProgressIndicator::stopAnimation() -{ - if (m_timerId != -1) - killTimer(m_timerId); +void QProgressIndicator::stopAnimation() { + if (m_timerId != -1) + killTimer(m_timerId); - m_timerId = -1; + m_timerId = -1; - update(); + update(); } -void QProgressIndicator::setAnimationDelay(int delay) -{ - if (m_timerId != -1) - killTimer(m_timerId); +void QProgressIndicator::setAnimationDelay(int delay) { + if (m_timerId != -1) + killTimer(m_timerId); - m_delay = delay; + m_delay = delay; - if (m_timerId != -1) - m_timerId = startTimer(m_delay); + if (m_timerId != -1) + m_timerId = startTimer(m_delay); } -void QProgressIndicator::setColor(const QColor &color) -{ - m_color = color; +void QProgressIndicator::setColor(const QColor &color) { + m_color = color; - update(); + update(); } -QSize QProgressIndicator::sizeHint() const -{ - return QSize(20, 20); -} +QSize QProgressIndicator::sizeHint() const { return QSize(20, 20); } -int QProgressIndicator::heightForWidth(int w) const -{ - return w; -} +int QProgressIndicator::heightForWidth(int w) const { return w; } -void QProgressIndicator::timerEvent(QTimerEvent * /*event*/) -{ - m_angle = (m_angle+30)%360; +void QProgressIndicator::timerEvent(QTimerEvent * /*event*/) { + m_angle = (m_angle + 30) % 360; - update(); + update(); } -void QProgressIndicator::paintEvent(QPaintEvent * /*event*/) -{ - if (!m_displayedWhenStopped && !isAnimated()) - return; - - int width = qMin(this->width(), this->height()); - - QPainter p(this); - p.setRenderHint(QPainter::Antialiasing); - - int outerRadius = (width-1)*0.5; - int innerRadius = (width-1)*0.5*0.38; - - int capsuleHeight = outerRadius - innerRadius; - int capsuleWidth = (width > 32) ? capsuleHeight *.23 : capsuleHeight *.35; - int capsuleRadius = capsuleWidth/2; - - for (int i = 0; i < 12; i++) { - QColor color = m_color; - color.setAlphaF(1.0f - (i/12.0f)); - p.setPen(Qt::NoPen); - p.setBrush(color); - p.save(); - p.translate(rect().center()); - p.rotate(m_angle - i*30.0f); - p.drawRoundedRect(-capsuleWidth*0.5, -(innerRadius+capsuleHeight), capsuleWidth, - capsuleHeight, capsuleRadius, capsuleRadius); - p.restore(); - } +void QProgressIndicator::paintEvent(QPaintEvent * /*event*/) { + if (!m_displayedWhenStopped && !isAnimated()) + return; + + int width = qMin(this->width(), this->height()); + + QPainter p(this); + p.setRenderHint(QPainter::Antialiasing); + + int outerRadius = (width - 1) * 0.5; + int innerRadius = (width - 1) * 0.5 * 0.38; + + int capsuleHeight = outerRadius - innerRadius; + int capsuleWidth = (width > 32) ? capsuleHeight * .23 : capsuleHeight * .35; + int capsuleRadius = capsuleWidth / 2; + + for (int i = 0; i < 12; i++) { + QColor color = m_color; + color.setAlphaF(1.0f - (i / 12.0f)); + p.setPen(Qt::NoPen); + p.setBrush(color); + p.save(); + p.translate(rect().center()); + p.rotate(m_angle - i * 30.0f); + p.drawRoundedRect(-capsuleWidth * 0.5, -(innerRadius + capsuleHeight), + capsuleWidth, capsuleHeight, capsuleRadius, + capsuleRadius); + p.restore(); + } } diff --git a/progressindicator.h b/progressindicator.h index 46dfa37e5..59fb35377 100644 --- a/progressindicator.h +++ b/progressindicator.h @@ -6,88 +6,92 @@ /*! \class QProgressIndicator - \brief The QProgressIndicator class lets an application display a progress indicator to show that a lengthy task is under way. + \brief The QProgressIndicator class lets an application display a progress + indicator to show that a lengthy task is under way. - Progress indicators are indeterminate and do nothing more than spin to show that the application is busy. + Progress indicators are indeterminate and do nothing more than spin to show + that the application is busy. \sa QProgressBar */ -class QProgressIndicator : public QWidget -{ - Q_OBJECT - Q_PROPERTY(int delay READ animationDelay WRITE setAnimationDelay) - Q_PROPERTY(bool displayedWhenStopped READ isDisplayedWhenStopped WRITE setDisplayedWhenStopped) - Q_PROPERTY(QColor color READ color WRITE setColor) +class QProgressIndicator : public QWidget { + Q_OBJECT + Q_PROPERTY(int delay READ animationDelay WRITE setAnimationDelay) + Q_PROPERTY(bool displayedWhenStopped READ isDisplayedWhenStopped WRITE + setDisplayedWhenStopped) + Q_PROPERTY(QColor color READ color WRITE setColor) public: - QProgressIndicator(QWidget *parent = 0); + QProgressIndicator(QWidget *parent = 0); -/*! Returns the delay between animation steps. - \return The number of milliseconds between animation steps. By default, the animation delay is set to 40 milliseconds. - \sa setAnimationDelay - */ - int animationDelay() const - { - return m_delay; - } + /*! Returns the delay between animation steps. + \return The number of milliseconds between animation steps. By default, + the animation delay is set to 40 milliseconds. + \sa setAnimationDelay + */ + int animationDelay() const { return m_delay; } -/*! Returns a Boolean value indicating whether the component is currently animated. - \return Animation state. - \sa startAnimation stopAnimation - */ - bool isAnimated() const; + /*! Returns a Boolean value indicating whether the component is currently + animated. + \return Animation state. + \sa startAnimation stopAnimation + */ + bool isAnimated() const; -/*! Returns a Boolean value indicating whether the receiver shows itself even when it is not animating. - \return Return true if the progress indicator shows itself even when it is not animating. By default, it returns false. - \sa setDisplayedWhenStopped - */ - bool isDisplayedWhenStopped() const; + /*! Returns a Boolean value indicating whether the receiver shows itself even + when it is not animating. + \return Return true if the progress indicator shows itself even when it is + not animating. By default, it returns false. + \sa setDisplayedWhenStopped + */ + bool isDisplayedWhenStopped() const; -/*! Returns the color of the component. - \sa setColor - */ - const QColor &color() const - { - return m_color; - } + /*! Returns the color of the component. + \sa setColor + */ + const QColor &color() const { return m_color; } - virtual QSize sizeHint() const; - int heightForWidth(int w) const; + virtual QSize sizeHint() const; + int heightForWidth(int w) const; public slots: -/*! Starts the spin animation. - \sa stopAnimation isAnimated - */ - void startAnimation(); + /*! Starts the spin animation. + \sa stopAnimation isAnimated + */ + void startAnimation(); -/*! Stops the spin animation. - \sa startAnimation isAnimated - */ - void stopAnimation(); + /*! Stops the spin animation. + \sa startAnimation isAnimated + */ + void stopAnimation(); -/*! Sets the delay between animation steps. - Setting the \a delay to a value larger than 40 slows the animation, while setting the \a delay to a smaller value speeds it up. - \param delay The delay, in milliseconds. - \sa animationDelay - */ - void setAnimationDelay(int delay); + /*! Sets the delay between animation steps. + Setting the \a delay to a value larger than 40 slows the animation, while + setting the \a delay to a smaller value speeds it up. + \param delay The delay, in milliseconds. + \sa animationDelay + */ + void setAnimationDelay(int delay); -/*! Sets whether the component hides itself when it is not animating. - \param state The animation state. Set false to hide the progress indicator when it is not animating; otherwise true. - \sa isDisplayedWhenStopped - */ - void setDisplayedWhenStopped(bool state); + /*! Sets whether the component hides itself when it is not animating. + \param state The animation state. Set false to hide the progress indicator + when it is not animating; otherwise true. + \sa isDisplayedWhenStopped + */ + void setDisplayedWhenStopped(bool state); + + /*! Sets the color of the components to the given color. + \sa color + */ + void setColor(const QColor &color); -/*! Sets the color of the components to the given color. - \sa color - */ - void setColor(const QColor &color); protected: - virtual void timerEvent(QTimerEvent *event); - virtual void paintEvent(QPaintEvent *event); + virtual void timerEvent(QTimerEvent *event); + virtual void paintEvent(QPaintEvent *event); + private: - int m_angle; - int m_timerId; - int m_delay; - bool m_displayedWhenStopped; - QColor m_color; + int m_angle; + int m_timerId; + int m_delay; + bool m_displayedWhenStopped; + QColor m_color; }; #endif // QPROGRESSINDICATOR_H diff --git a/singleapplication.cpp b/singleapplication.cpp index 52394d59b..3eb44838a 100644 --- a/singleapplication.cpp +++ b/singleapplication.cpp @@ -9,24 +9,25 @@ * @param uniqueKey */ SingleApplication::SingleApplication(int &argc, char *argv[], - const QString uniqueKey) : QApplication(argc, argv), - _uniqueKey(uniqueKey) -{ - sharedMemory.setKey(_uniqueKey); - if (sharedMemory.attach()) { - _isRunning = true; - } else { - _isRunning = false; - // create shared memory. - if (!sharedMemory.create(1)) { - qDebug("Unable to create single instance."); - return; - } - // create local server and listen to incomming messages from other instances. - localServer.reset(new QLocalServer(this)); - connect(localServer.data(), SIGNAL(newConnection()), this, SLOT(receiveMessage())); - localServer->listen(_uniqueKey); + const QString uniqueKey) + : QApplication(argc, argv), _uniqueKey(uniqueKey) { + sharedMemory.setKey(_uniqueKey); + if (sharedMemory.attach()) { + _isRunning = true; + } else { + _isRunning = false; + // create shared memory. + if (!sharedMemory.create(1)) { + qDebug("Unable to create single instance."); + return; } + // create local server and listen to incomming messages from other + // instances. + localServer.reset(new QLocalServer(this)); + connect(localServer.data(), SIGNAL(newConnection()), this, + SLOT(receiveMessage())); + localServer->listen(_uniqueKey); + } } // public slots. @@ -34,17 +35,16 @@ SingleApplication::SingleApplication(int &argc, char *argv[], /** * @brief SingleApplication::receiveMessage */ -void SingleApplication::receiveMessage() -{ - QLocalSocket *localSocket = localServer->nextPendingConnection(); - if (!localSocket->waitForReadyRead(timeout)) { - qDebug() << localSocket->errorString().toLatin1(); - return; - } - QByteArray byteArray = localSocket->readAll(); - QString message = QString::fromUtf8(byteArray.constData()); - emit messageAvailable(message); - localSocket->disconnectFromServer(); +void SingleApplication::receiveMessage() { + QLocalSocket *localSocket = localServer->nextPendingConnection(); + if (!localSocket->waitForReadyRead(timeout)) { + qDebug() << localSocket->errorString().toLatin1(); + return; + } + QByteArray byteArray = localSocket->readAll(); + QString message = QString::fromUtf8(byteArray.constData()); + emit messageAvailable(message); + localSocket->disconnectFromServer(); } // public functions. @@ -52,31 +52,27 @@ void SingleApplication::receiveMessage() * @brief SingleApplication::isRunning * @return */ -bool SingleApplication::isRunning() -{ - return _isRunning; -} +bool SingleApplication::isRunning() { return _isRunning; } /** * @brief SingleApplication::sendMessage * @param message * @return */ -bool SingleApplication::sendMessage(const QString &message) -{ - if (!_isRunning) - return false; - QLocalSocket localSocket(this); - localSocket.connectToServer(_uniqueKey, QIODevice::WriteOnly); - if (!localSocket.waitForConnected(timeout)) { - qDebug() << localSocket.errorString().toLatin1(); - return false; - } - localSocket.write(message.toUtf8()); - if (!localSocket.waitForBytesWritten(timeout)) { - qDebug() << localSocket.errorString().toLatin1(); - return false; - } - localSocket.disconnectFromServer(); - return true; +bool SingleApplication::sendMessage(const QString &message) { + if (!_isRunning) + return false; + QLocalSocket localSocket(this); + localSocket.connectToServer(_uniqueKey, QIODevice::WriteOnly); + if (!localSocket.waitForConnected(timeout)) { + qDebug() << localSocket.errorString().toLatin1(); + return false; + } + localSocket.write(message.toUtf8()); + if (!localSocket.waitForBytesWritten(timeout)) { + qDebug() << localSocket.errorString().toLatin1(); + return false; + } + localSocket.disconnectFromServer(); + return true; } diff --git a/singleapplication.h b/singleapplication.h index 236fabc12..b5a4e937e 100644 --- a/singleapplication.h +++ b/singleapplication.h @@ -5,27 +5,26 @@ #include #include -class SingleApplication : public QApplication -{ - Q_OBJECT +class SingleApplication : public QApplication { + Q_OBJECT public: - SingleApplication(int &argc, char *argv[], const QString uniqueKey); + SingleApplication(int &argc, char *argv[], const QString uniqueKey); - bool isRunning(); - bool sendMessage(const QString &message); + bool isRunning(); + bool sendMessage(const QString &message); public slots: - void receiveMessage(); + void receiveMessage(); signals: - void messageAvailable(QString message); + void messageAvailable(QString message); private: - bool _isRunning; - QString _uniqueKey; - QSharedMemory sharedMemory; - QScopedPointer localServer; + bool _isRunning; + QString _uniqueKey; + QSharedMemory sharedMemory; + QScopedPointer localServer; - static const int timeout = 1000; + static const int timeout = 1000; }; #endif // SINGLE_APPLICATION_H diff --git a/storemodel.cpp b/storemodel.cpp index c61195a42..cc664541b 100644 --- a/storemodel.cpp +++ b/storemodel.cpp @@ -2,12 +2,10 @@ /** * @brief StoreModel::StoreModel - * SubClass of QSortFilterProxyModel via http://www.qtcentre.org/threads/46471-QTreeView-Filter + * SubClass of QSortFilterProxyModel via + * http://www.qtcentre.org/threads/46471-QTreeView-Filter */ -StoreModel::StoreModel() -{ - fs = NULL; -} +StoreModel::StoreModel() { fs = NULL; } /** * @brief StoreModel::filterAcceptsRow @@ -15,10 +13,10 @@ StoreModel::StoreModel() * @param sourceParent * @return */ -bool StoreModel::filterAcceptsRow(int sourceRow, const QModelIndex &sourceParent) const -{ - QModelIndex index = sourceModel()->index(sourceRow, 0, sourceParent); - return ShowThis(index); +bool StoreModel::filterAcceptsRow(int sourceRow, + const QModelIndex &sourceParent) const { + QModelIndex index = sourceModel()->index(sourceRow, 0, sourceParent); + return ShowThis(index); } /** @@ -26,29 +24,28 @@ bool StoreModel::filterAcceptsRow(int sourceRow, const QModelIndex &sourceParent * @param index * @return */ -bool StoreModel::ShowThis(const QModelIndex index) const -{ - bool retVal = false; - if (fs == NULL) - return retVal; - // Gives you the info for number of childs with a parent - if (sourceModel()->rowCount(index) > 0) { - for (int nChild = 0; nChild < sourceModel()->rowCount(index); nChild++) { - QModelIndex childIndex = sourceModel()->index(nChild, 0, index); - if (!childIndex.isValid()) - break; - retVal = ShowThis(childIndex); - if (retVal) - break; - } - } else { - QModelIndex useIndex = sourceModel()->index(index.row(), 0, index.parent()); - QString path = fs->filePath(useIndex); - path.replace(QRegExp("\\.gpg$"), ""); - path.replace(QRegExp("^" + store), ""); - retVal = path.contains(filterRegExp()); - } +bool StoreModel::ShowThis(const QModelIndex index) const { + bool retVal = false; + if (fs == NULL) return retVal; + // Gives you the info for number of childs with a parent + if (sourceModel()->rowCount(index) > 0) { + for (int nChild = 0; nChild < sourceModel()->rowCount(index); nChild++) { + QModelIndex childIndex = sourceModel()->index(nChild, 0, index); + if (!childIndex.isValid()) + break; + retVal = ShowThis(childIndex); + if (retVal) + break; + } + } else { + QModelIndex useIndex = sourceModel()->index(index.row(), 0, index.parent()); + QString path = fs->filePath(useIndex); + path.replace(QRegExp("\\.gpg$"), ""); + path.replace(QRegExp("^" + store), ""); + retVal = path.contains(filterRegExp()); + } + return retVal; } /** @@ -56,10 +53,10 @@ bool StoreModel::ShowThis(const QModelIndex index) const * @param sourceModel * @param passStore */ -void StoreModel::setModelAndStore(QFileSystemModel *sourceModel, QString passStore) -{ - fs = sourceModel; - store = passStore; +void StoreModel::setModelAndStore(QFileSystemModel *sourceModel, + QString passStore) { + fs = sourceModel; + store = passStore; } /** @@ -68,19 +65,18 @@ void StoreModel::setModelAndStore(QFileSystemModel *sourceModel, QString passSto * @param role * @return */ -QVariant StoreModel::data(const QModelIndex &index, int role) const -{ - if (!index.isValid()) - return QVariant(); +QVariant StoreModel::data(const QModelIndex &index, int role) const { + if (!index.isValid()) + return QVariant(); - QVariant initial_value; - initial_value = QSortFilterProxyModel::data(index, role); + QVariant initial_value; + initial_value = QSortFilterProxyModel::data(index, role); - if (role == Qt::DisplayRole) { - QString name = initial_value.toString(); - name.replace(QRegExp("\\.gpg$"), ""); - initial_value.setValue(name); - } + if (role == Qt::DisplayRole) { + QString name = initial_value.toString(); + name.replace(QRegExp("\\.gpg$"), ""); + initial_value.setValue(name); + } - return initial_value; + return initial_value; } diff --git a/storemodel.h b/storemodel.h index 0f7488ec3..438a3a976 100644 --- a/storemodel.h +++ b/storemodel.h @@ -5,20 +5,19 @@ #include #include -class StoreModel : public QSortFilterProxyModel -{ - Q_OBJECT +class StoreModel : public QSortFilterProxyModel { + Q_OBJECT private: - QFileSystemModel* fs; - QString store; + QFileSystemModel *fs; + QString store; public: - StoreModel(); + StoreModel(); - bool filterAcceptsRow(int, const QModelIndex &) const; - bool ShowThis(const QModelIndex) const; - void setModelAndStore(QFileSystemModel *sourceModel, QString passStore); - QVariant data(const QModelIndex &index, int role) const; + bool filterAcceptsRow(int, const QModelIndex &) const; + bool ShowThis(const QModelIndex) const; + void setModelAndStore(QFileSystemModel *sourceModel, QString passStore); + QVariant data(const QModelIndex &index, int role) const; }; #endif // STOREMODEL_H diff --git a/trayicon.cpp b/trayicon.cpp index 4c1246dcc..f8e28e31d 100644 --- a/trayicon.cpp +++ b/trayicon.cpp @@ -1,80 +1,73 @@ #include "trayicon.h" -TrayIcon::TrayIcon(QMainWindow *parent) -{ - parentwin = parent; +TrayIcon::TrayIcon(QMainWindow *parent) { + parentwin = parent; - createActions(); - createTrayIcon(); + createActions(); + createTrayIcon(); - sysTrayIcon->setIcon(QIcon(":/artwork/icon.png")); + sysTrayIcon->setIcon(QIcon(":/artwork/icon.png")); - sysTrayIcon->show(); + sysTrayIcon->show(); - QObject::connect(sysTrayIcon, SIGNAL(activated(QSystemTrayIcon::ActivationReason)), - this, SLOT(iconActivated(QSystemTrayIcon::ActivationReason))); + QObject::connect(sysTrayIcon, + SIGNAL(activated(QSystemTrayIcon::ActivationReason)), this, + SLOT(iconActivated(QSystemTrayIcon::ActivationReason))); } -void TrayIcon::setVisible(bool visible) -{ - if (visible == true) - parentwin->show(); - else - parentwin->hide(); +void TrayIcon::setVisible(bool visible) { + if (visible == true) + parentwin->show(); + else + parentwin->hide(); } -void TrayIcon::createActions() -{ -// minimizeAction = new QAction(tr("Mi&nimize"), this); -// connect(minimizeAction, SIGNAL(triggered()), this, SLOT(hide())); +void TrayIcon::createActions() { + // minimizeAction = new QAction(tr("Mi&nimize"), this); + // connect(minimizeAction, SIGNAL(triggered()), this, SLOT(hide())); -// maximizeAction = new QAction(tr("Ma&ximize"), this); -// connect(maximizeAction, SIGNAL(triggered()), this, SLOT(showMaximized())); + // maximizeAction = new QAction(tr("Ma&ximize"), this); + // connect(maximizeAction, SIGNAL(triggered()), this, SLOT(showMaximized())); -// restoreAction = new QAction(tr("&Restore"), this); -// connect(restoreAction, SIGNAL(triggered()), this, SLOT(showNormal())); + // restoreAction = new QAction(tr("&Restore"), this); + // connect(restoreAction, SIGNAL(triggered()), this, SLOT(showNormal())); - quitAction = new QAction(tr("&Quit"), this); - connect(quitAction, SIGNAL(triggered()), qApp, SLOT(quit())); + quitAction = new QAction(tr("&Quit"), this); + connect(quitAction, SIGNAL(triggered()), qApp, SLOT(quit())); } -void TrayIcon::createTrayIcon() -{ - trayIconMenu = new QMenu(this); -// trayIconMenu->addAction(minimizeAction); -// trayIconMenu->addAction(maximizeAction); -// trayIconMenu->addAction(restoreAction); -// trayIconMenu->addSeparator(); - trayIconMenu->addAction(quitAction); +void TrayIcon::createTrayIcon() { + trayIconMenu = new QMenu(this); + // trayIconMenu->addAction(minimizeAction); + // trayIconMenu->addAction(maximizeAction); + // trayIconMenu->addAction(restoreAction); + // trayIconMenu->addSeparator(); + trayIconMenu->addAction(quitAction); - sysTrayIcon = new QSystemTrayIcon(this); - sysTrayIcon->setContextMenu(trayIconMenu); + sysTrayIcon = new QSystemTrayIcon(this); + sysTrayIcon->setContextMenu(trayIconMenu); } -void TrayIcon::showHideParent() -{ - if (parentwin->isVisible() == true) - parentwin->hide(); - else - parentwin->show(); +void TrayIcon::showHideParent() { + if (parentwin->isVisible() == true) + parentwin->hide(); + else + parentwin->show(); } -void TrayIcon::iconActivated(QSystemTrayIcon::ActivationReason reason) -{ - switch (reason) { - case QSystemTrayIcon::Trigger: - case QSystemTrayIcon::DoubleClick: - showHideParent(); - break; - case QSystemTrayIcon::MiddleClick: - showMessage("test", "test msg", 1000); - break; - default: - ; - } +void TrayIcon::iconActivated(QSystemTrayIcon::ActivationReason reason) { + switch (reason) { + case QSystemTrayIcon::Trigger: + case QSystemTrayIcon::DoubleClick: + showHideParent(); + break; + case QSystemTrayIcon::MiddleClick: + showMessage("test", "test msg", 1000); + break; + default:; + } } -void TrayIcon::showMessage(QString title, QString msg, int time) -{ - sysTrayIcon->showMessage(title, msg, QSystemTrayIcon::Information, time); +void TrayIcon::showMessage(QString title, QString msg, int time) { + sysTrayIcon->showMessage(title, msg, QSystemTrayIcon::Information, time); } diff --git a/trayicon.h b/trayicon.h index 3dde72abe..916832c2c 100644 --- a/trayicon.h +++ b/trayicon.h @@ -8,32 +8,31 @@ #include #include -class TrayIcon : public QWidget -{ - Q_OBJECT +class TrayIcon : public QWidget { + Q_OBJECT public: - explicit TrayIcon(QMainWindow *parent); - void showMessage(QString title, QString msg, int time); - void setVisible(bool visible); + explicit TrayIcon(QMainWindow *parent); + void showMessage(QString title, QString msg, int time); + void setVisible(bool visible); signals: public slots: - void showHideParent(); - void iconActivated(QSystemTrayIcon::ActivationReason reason); + void showHideParent(); + void iconActivated(QSystemTrayIcon::ActivationReason reason); private: - void createActions(); - void createTrayIcon(); + void createActions(); + void createTrayIcon(); -// QAction *minimizeAction; -// QAction *maximizeAction; - QAction *settingsAction; - QAction *quitAction; + // QAction *minimizeAction; + // QAction *maximizeAction; + QAction *settingsAction; + QAction *quitAction; - QSystemTrayIcon *sysTrayIcon; - QMenu *trayIconMenu; - QMainWindow *parentwin; + QSystemTrayIcon *sysTrayIcon; + QMenu *trayIconMenu; + QMainWindow *parentwin; }; #endif // TRAYICON_H diff --git a/usersdialog.cpp b/usersdialog.cpp index 711833dfe..e6691e8e1 100644 --- a/usersdialog.cpp +++ b/usersdialog.cpp @@ -3,105 +3,94 @@ #include #include -UsersDialog::UsersDialog(QWidget *parent) : - QDialog(parent), - ui(new Ui::UsersDialog) -{ - ui->setupUi(this); - connect(ui->buttonBox, SIGNAL(accepted()), this, SLOT(accept())); - connect(ui->buttonBox, SIGNAL(rejected()), this, SLOT(reject())); - connect(ui->listWidget, SIGNAL(itemChanged(QListWidgetItem *)), this, - SLOT(itemChange(QListWidgetItem *))); - userList = NULL; +UsersDialog::UsersDialog(QWidget *parent) + : QDialog(parent), ui(new Ui::UsersDialog) { + ui->setupUi(this); + connect(ui->buttonBox, SIGNAL(accepted()), this, SLOT(accept())); + connect(ui->buttonBox, SIGNAL(rejected()), this, SLOT(reject())); + connect(ui->listWidget, SIGNAL(itemChanged(QListWidgetItem *)), this, + SLOT(itemChange(QListWidgetItem *))); + userList = NULL; } -UsersDialog::~UsersDialog() -{ - delete ui; -} +UsersDialog::~UsersDialog() { delete ui; } Q_DECLARE_METATYPE(UserInfo *) -void UsersDialog::itemChange(QListWidgetItem *item) -{ - if (!item) return; - UserInfo *info = item->data(Qt::UserRole).value(); - if (!info) return; - info->enabled = item->checkState() == Qt::Checked; +void UsersDialog::itemChange(QListWidgetItem *item) { + if (!item) + return; + UserInfo *info = item->data(Qt::UserRole).value(); + if (!info) + return; + info->enabled = item->checkState() == Qt::Checked; } -void UsersDialog::setUsers(QList *users) -{ - userList = users; - populateList(""); +void UsersDialog::setUsers(QList *users) { + userList = users; + populateList(""); } -void UsersDialog::populateList(const QString &filter) -{ - QRegExp nameFilter("*"+filter+"*"); - nameFilter.setPatternSyntax(QRegExp::Wildcard); - nameFilter.setCaseSensitivity(Qt::CaseInsensitive); - ui->listWidget->clear(); - if (userList) { - for (QList::iterator it = userList->begin(); it != userList->end(); ++it) { - UserInfo &user(*it); - if (filter.isEmpty() || nameFilter.exactMatch(user.name)) { - if (user.validity == '-' && !ui->checkBox->isChecked()) - continue; - if (user.expiry.toTime_t() > 0 - && user.expiry.daysTo(QDateTime::currentDateTime()) > 0 - && !ui->checkBox->isChecked()) - continue; - QString userText = user.name + "\n" + user.key_id; - if (user.created.toTime_t() > 0) { - userText += " " + tr("created") + " " + user.created.toString( - Qt::SystemLocaleShortDate); - } - if (user.expiry.toTime_t() > 0) - userText += " " + tr("expires") + " " + user.expiry.toString( - Qt::SystemLocaleShortDate); - QListWidgetItem *item = new QListWidgetItem(userText, ui->listWidget); - item->setCheckState(user.enabled ? Qt::Checked : Qt::Unchecked); - item->setData(Qt::UserRole, QVariant::fromValue(&user)); - if (user.have_secret) { - // item->setForeground(QColor(32, 74, 135)); - item->setForeground(Qt::blue); - QFont font; - font.setFamily(font.defaultFamily()); - font.setBold(true); - item->setFont(font); - } else if (user.validity == '-') { - item->setBackground(QColor(164, 0, 0)); - item->setForeground(Qt::white); - } else if (user.expiry.toTime_t() > 0 - && user.expiry.daysTo(QDateTime::currentDateTime()) > 0) { - item->setForeground(QColor(164, 0, 0)); - } - - ui->listWidget->addItem(item); - } +void UsersDialog::populateList(const QString &filter) { + QRegExp nameFilter("*" + filter + "*"); + nameFilter.setPatternSyntax(QRegExp::Wildcard); + nameFilter.setCaseSensitivity(Qt::CaseInsensitive); + ui->listWidget->clear(); + if (userList) { + for (QList::iterator it = userList->begin(); + it != userList->end(); ++it) { + UserInfo &user(*it); + if (filter.isEmpty() || nameFilter.exactMatch(user.name)) { + if (user.validity == '-' && !ui->checkBox->isChecked()) + continue; + if (user.expiry.toTime_t() > 0 && + user.expiry.daysTo(QDateTime::currentDateTime()) > 0 && + !ui->checkBox->isChecked()) + continue; + QString userText = user.name + "\n" + user.key_id; + if (user.created.toTime_t() > 0) { + userText += " " + tr("created") + " " + + user.created.toString(Qt::SystemLocaleShortDate); + } + if (user.expiry.toTime_t() > 0) + userText += " " + tr("expires") + " " + + user.expiry.toString(Qt::SystemLocaleShortDate); + QListWidgetItem *item = new QListWidgetItem(userText, ui->listWidget); + item->setCheckState(user.enabled ? Qt::Checked : Qt::Unchecked); + item->setData(Qt::UserRole, QVariant::fromValue(&user)); + if (user.have_secret) { + // item->setForeground(QColor(32, 74, 135)); + item->setForeground(Qt::blue); + QFont font; + font.setFamily(font.defaultFamily()); + font.setBold(true); + item->setFont(font); + } else if (user.validity == '-') { + item->setBackground(QColor(164, 0, 0)); + item->setForeground(Qt::white); + } else if (user.expiry.toTime_t() > 0 && + user.expiry.daysTo(QDateTime::currentDateTime()) > 0) { + item->setForeground(QColor(164, 0, 0)); } + + ui->listWidget->addItem(item); + } } + } } -void UsersDialog::on_clearButton_clicked() -{ - ui->lineEdit->clear(); - populateList(""); +void UsersDialog::on_clearButton_clicked() { + ui->lineEdit->clear(); + populateList(""); } -void UsersDialog::on_lineEdit_textChanged(const QString &filter) -{ - populateList(filter); +void UsersDialog::on_lineEdit_textChanged(const QString &filter) { + populateList(filter); } -void UsersDialog::closeEvent(QCloseEvent *event) -{ - // TODO save window size or somethign - event->accept(); +void UsersDialog::closeEvent(QCloseEvent *event) { + // TODO save window size or somethign + event->accept(); } -void UsersDialog::on_checkBox_clicked() -{ - populateList(ui->lineEdit->text()); -} +void UsersDialog::on_checkBox_clicked() { populateList(ui->lineEdit->text()); } diff --git a/usersdialog.h b/usersdialog.h index 326af5b6a..6b1c4f234 100644 --- a/usersdialog.h +++ b/usersdialog.h @@ -14,43 +14,38 @@ class UsersDialog; class QListWidgetItem; struct UserInfo { - UserInfo() : validity('-'), - have_secret(false), - enabled(false) - { - } - - QString name; - QString key_id; - char validity; - bool have_secret; - bool enabled; - QDateTime expiry; - QDateTime created; + UserInfo() : validity('-'), have_secret(false), enabled(false) {} + + QString name; + QString key_id; + char validity; + bool have_secret; + bool enabled; + QDateTime expiry; + QDateTime created; }; -class UsersDialog : public QDialog -{ - Q_OBJECT +class UsersDialog : public QDialog { + Q_OBJECT public: - explicit UsersDialog(QWidget *parent = 0); - ~UsersDialog(); - void setUsers(QList *); + explicit UsersDialog(QWidget *parent = 0); + ~UsersDialog(); + void setUsers(QList *); protected: - void closeEvent(QCloseEvent *event); + void closeEvent(QCloseEvent *event); private slots: - void itemChange(QListWidgetItem *); - void on_clearButton_clicked(); - void on_lineEdit_textChanged(const QString &filter); - void on_checkBox_clicked(); + void itemChange(QListWidgetItem *); + void on_clearButton_clicked(); + void on_lineEdit_textChanged(const QString &filter); + void on_checkBox_clicked(); private: - Ui::UsersDialog *ui; - QList *userList; - void populateList(const QString &filter); + Ui::UsersDialog *ui; + QList *userList; + void populateList(const QString &filter); }; #endif // USERSDIALOG_H diff --git a/util.cpp b/util.cpp index 498a08636..8fdfee98b 100644 --- a/util.cpp +++ b/util.cpp @@ -14,45 +14,43 @@ bool Util::_envInitialised; /** * @brief Util::initialiseEnvironment */ -void Util::initialiseEnvironment() -{ - if (!_envInitialised) { - _env = QProcessEnvironment::systemEnvironment(); +void Util::initialiseEnvironment() { + if (!_envInitialised) { + _env = QProcessEnvironment::systemEnvironment(); #ifdef __APPLE__ - // TODO checks here - QString path = _env.value("PATH"); + // TODO checks here + QString path = _env.value("PATH"); - if (!path.contains("/usr/local/MacGPG2/bin") - && QFile("/usr/local/MacGPG2/bin").exists()) - path += ":/usr/local/MacGPG2/bin"; - if (!path.contains("/usr/local/bin")) - path += ":/usr/local/bin"; - _env.insert("PATH", path); + if (!path.contains("/usr/local/MacGPG2/bin") && + QFile("/usr/local/MacGPG2/bin").exists()) + path += ":/usr/local/MacGPG2/bin"; + if (!path.contains("/usr/local/bin")) + path += ":/usr/local/bin"; + _env.insert("PATH", path); #endif - _envInitialised = true; - } + _envInitialised = true; + } } /** * @brief Util::findPasswordStore * @return */ -QString Util::findPasswordStore() -{ - QString path; - initialiseEnvironment(); - if (_env.contains("PASSWORD_STORE_DIR")) { - path = _env.value("PASSWORD_STORE_DIR"); - } else { +QString Util::findPasswordStore() { + QString path; + initialiseEnvironment(); + if (_env.contains("PASSWORD_STORE_DIR")) { + path = _env.value("PASSWORD_STORE_DIR"); + } else { #ifdef Q_OS_WIN - path = QDir::homePath() + QDir::separator() - + "password-store" + QDir::separator(); + path = QDir::homePath() + QDir::separator() + "password-store" + + QDir::separator(); #else - path = QDir::homePath() + QDir::separator() - + ".password-store" + QDir::separator(); + path = QDir::homePath() + QDir::separator() + ".password-store" + + QDir::separator(); #endif - } - return Util::normalizeFolderPath(path); + } + return Util::normalizeFolderPath(path); } /** @@ -60,51 +58,49 @@ QString Util::findPasswordStore() * @param path * @return */ -QString Util::normalizeFolderPath(QString path) -{ - if (!path.endsWith("/") && !path.endsWith(QDir::separator())) - path += QDir::separator(); - return path; +QString Util::normalizeFolderPath(QString path) { + if (!path.endsWith("/") && !path.endsWith(QDir::separator())) + path += QDir::separator(); + return path; } -QString Util::findBinaryInPath(QString binary) -{ - initialiseEnvironment(); +QString Util::findBinaryInPath(QString binary) { + initialiseEnvironment(); - QString ret = ""; + QString ret = ""; - binary.prepend(QDir::separator()); + binary.prepend(QDir::separator()); - if (_env.contains("PATH")) { - QString path = _env.value("PATH"); + if (_env.contains("PATH")) { + QString path = _env.value("PATH"); - QStringList entries; + QStringList entries; #ifndef Q_OS_WIN - entries = path.split(':'); - if (entries.length() < 2) { + entries = path.split(':'); + if (entries.length() < 2) { #endif - entries = path.split(';'); + entries = path.split(';'); #ifndef Q_OS_WIN } #endif - foreach (QString entry, entries) { - QScopedPointer qfi(new QFileInfo(entry.append(binary))); + foreach (QString entry, entries) { + QScopedPointer qfi(new QFileInfo(entry.append(binary))); #ifdef Q_OS_WIN - if (!qfi->exists()) - qfi.reset(new QFileInfo(entry.append(".exe"))); + if (!qfi->exists()) + qfi.reset(new QFileInfo(entry.append(".exe"))); #endif - qDebug() << entry; - if (!qfi->isExecutable()) - continue; + qDebug() << entry; + if (!qfi->isExecutable()) + continue; - ret = qfi->absoluteFilePath(); - break; - } + ret = qfi->absoluteFilePath(); + break; } + } - return ret; + return ret; } /** @@ -114,24 +110,21 @@ QString Util::findBinaryInPath(QString binary) * @param gpgExecutable * @return */ -bool Util::checkConfig(QString passStore, QString passExecutable, QString gpgExecutable) -{ - return !QFile(passStore + ".gpg-id").exists() - || (!QFile(passExecutable).exists() && !QFile(gpgExecutable).exists()); +bool Util::checkConfig(QString passStore, QString passExecutable, + QString gpgExecutable) { + return !QFile(passStore + ".gpg-id").exists() || + (!QFile(passExecutable).exists() && !QFile(gpgExecutable).exists()); } /** * @brief Util::qSleep * @param ms - */\ - void Util::qSleep(int ms) -{ + */ +void Util::qSleep(int ms) { #ifdef Q_OS_WIN - Sleep(uint(ms)); + Sleep(uint(ms)); #else - struct timespec ts = { - ms / 1000, (ms % 1000) * 1000 * 1000 - }; - nanosleep(&ts, NULL); + struct timespec ts = {ms / 1000, (ms % 1000) * 1000 * 1000}; + nanosleep(&ts, NULL); #endif } diff --git a/util.h b/util.h index 53e1af98f..6d8eeda09 100644 --- a/util.h +++ b/util.h @@ -4,19 +4,18 @@ #include #include -class Util -{ +class Util { public: - static QString findBinaryInPath(QString); - static QString findPasswordStore(); - static QString normalizeFolderPath(QString); - static bool checkConfig(QString, QString, QString); - static void qSleep(int); + static QString findBinaryInPath(QString); + static QString findPasswordStore(); + static QString normalizeFolderPath(QString); + static bool checkConfig(QString, QString, QString); + static void qSleep(int); private: - static void initialiseEnvironment(); - static QProcessEnvironment _env; - static bool _envInitialised; + static void initialiseEnvironment(); + static QProcessEnvironment _env; + static bool _envInitialised; }; #endif // UTIL_H From f0dbb325ac80d23c8e025885ef56117e9caabd81 Mon Sep 17 00:00:00 2001 From: Anne Jan Brouwer Date: Tue, 24 Nov 2015 00:20:22 +0100 Subject: [PATCH 07/13] aparently a single . is not valid yml --- .linthub.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.linthub.yml b/.linthub.yml index d170b14ea..900fabca4 100644 --- a/.linthub.yml +++ b/.linthub.yml @@ -5,7 +5,7 @@ build: analyzers: - cpplint: true include: ["*.cpp", "*.h", "*.hpp", "*.c"] - path: . + path: ./ filters: - -whitespace - +whitespace/braces From 19e48a93df1eccf10c4b87de6d46b6f234a18639 Mon Sep 17 00:00:00 2001 From: Anne Jan Brouwer Date: Tue, 24 Nov 2015 00:44:37 +0100 Subject: [PATCH 08/13] This should fix about half --- keygendialog.cpp | 14 +++++++------- keygendialog.h | 10 +++++----- main.cpp | 2 +- passworddialog.h | 12 ++++++------ progressindicator.h | 11 ++++++----- singleapplication.h | 11 ++++++----- trayicon.h | 11 ++++++----- usersdialog.h | 12 ++++++------ util.h | 13 +++++++------ 9 files changed, 50 insertions(+), 46 deletions(-) diff --git a/keygendialog.cpp b/keygendialog.cpp index 6d0cb2635..c44cd0874 100644 --- a/keygendialog.cpp +++ b/keygendialog.cpp @@ -1,8 +1,8 @@ #include "keygendialog.h" -#include "ui_keygendialog.h" -#include "progressindicator.h" #include #include +#include "ui_keygendialog.h" +#include "progressindicator.h" KeygenDialog::KeygenDialog(ConfigDialog *parent) : QDialog(parent), ui(new Ui::KeygenDialog) { @@ -56,7 +56,7 @@ void KeygenDialog::replace(QString key, QString value) { QStringList clear; QString expert = ui->plainTextEdit->toPlainText(); QStringList lines = expert.split(QRegExp("[\r\n]"), QString::SkipEmptyParts); - foreach (QString line, lines) { + foreach(QString line, lines) { line.replace(QRegExp(key + ":.*"), key + ": " + value); if (key == "Passphrase") line.replace("%no-protection", "Passphrase: " + value); @@ -73,7 +73,7 @@ void KeygenDialog::no_protection(bool enable) { QStringList clear; QString expert = ui->plainTextEdit->toPlainText(); QStringList lines = expert.split(QRegExp("[\r\n]"), QString::SkipEmptyParts); - foreach (QString line, lines) { + foreach(QString line, lines) { bool remove = false; if (!enable) { if (line.indexOf("%no-protection") == 0) @@ -93,7 +93,7 @@ void KeygenDialog::no_protection(bool enable) { * @param r */ void KeygenDialog::done(int r) { - if (QDialog::Accepted == r) { // ok was pressed + if (QDialog::Accepted == r) { // ok was pressed ui->widget->setEnabled(false); ui->buttonBox->setEnabled(false); ui->checkBox->setEnabled(false); @@ -116,13 +116,13 @@ void KeygenDialog::done(int r) { this->show(); dialog->genKey(ui->plainTextEdit->toPlainText(), this); - } else { // cancel, close or exc was pressed + } else { // cancel, close or exc was pressed QDialog::done(r); return; } } void KeygenDialog::closeEvent(QCloseEvent *event) { - // TODO save window size or somethign + // TODO(annejan) save window size or somethign event->accept(); } diff --git a/keygendialog.h b/keygendialog.h index 0baa4f18c..ab6c94f8a 100644 --- a/keygendialog.h +++ b/keygendialog.h @@ -12,21 +12,21 @@ class KeygenDialog; class KeygenDialog : public QDialog { Q_OBJECT -public: + public: explicit KeygenDialog(ConfigDialog *parent = 0); ~KeygenDialog(); -protected: + protected: void closeEvent(QCloseEvent *event); -private slots: + private slots: void on_passphrase1_textChanged(const QString &arg1); void on_passphrase2_textChanged(const QString &arg1); void on_checkBox_stateChanged(int arg1); void on_email_textChanged(const QString &arg1); void on_name_textChanged(const QString &arg1); -private: + private: Ui::KeygenDialog *ui; void replace(QString, QString); void done(int r); @@ -34,4 +34,4 @@ private slots: ConfigDialog *dialog; }; -#endif // KEYGENDIALOG_H +#endif // KEYGENDIALOG_H_ diff --git a/main.cpp b/main.cpp index 9c9c065b0..d65a9e373 100644 --- a/main.cpp +++ b/main.cpp @@ -1,6 +1,6 @@ -#include "mainwindow.h" #include #include +#include "mainwindow.h" int main(int argc, char *argv[]) { // check for stupid apple psid or whatever flag diff --git a/passworddialog.h b/passworddialog.h index 7df25da17..eeebdcebc 100644 --- a/passworddialog.h +++ b/passworddialog.h @@ -11,21 +11,21 @@ class PasswordDialog; class PasswordDialog : public QDialog { Q_OBJECT -public: + public: explicit PasswordDialog(MainWindow *parent = 0); ~PasswordDialog(); void setPassword(QString); QString getPassword(); void setTemplate(QString); void setFile(QString); - void useTemplate(bool); - void templateAll(bool); + void useTemplate(bool useTemplate); + void templateAll(bool templateAll); -private slots: + private slots: void on_checkBoxShow_stateChanged(int arg1); void on_createPasswordButton_clicked(); -private: + private: Ui::PasswordDialog *ui; MainWindow *mainWindow; QString passTemplate; @@ -34,4 +34,4 @@ private slots: bool allFields; }; -#endif // PASSWORDDIALOG_H +#endif // PASSWORDDIALOG_H_ diff --git a/progressindicator.h b/progressindicator.h index 59fb35377..7cfc4c7bd 100644 --- a/progressindicator.h +++ b/progressindicator.h @@ -19,7 +19,8 @@ class QProgressIndicator : public QWidget { Q_PROPERTY(bool displayedWhenStopped READ isDisplayedWhenStopped WRITE setDisplayedWhenStopped) Q_PROPERTY(QColor color READ color WRITE setColor) -public: + + public: QProgressIndicator(QWidget *parent = 0); /*! Returns the delay between animation steps. @@ -51,7 +52,7 @@ class QProgressIndicator : public QWidget { virtual QSize sizeHint() const; int heightForWidth(int w) const; -public slots: + public slots: /*! Starts the spin animation. \sa stopAnimation isAnimated */ @@ -82,11 +83,11 @@ public slots: */ void setColor(const QColor &color); -protected: + protected: virtual void timerEvent(QTimerEvent *event); virtual void paintEvent(QPaintEvent *event); -private: + private: int m_angle; int m_timerId; int m_delay; @@ -94,4 +95,4 @@ public slots: QColor m_color; }; -#endif // QPROGRESSINDICATOR_H +#endif // QPROGRESSINDICATOR_H_ diff --git a/singleapplication.h b/singleapplication.h index b5a4e937e..79f1c28a2 100644 --- a/singleapplication.h +++ b/singleapplication.h @@ -7,19 +7,19 @@ class SingleApplication : public QApplication { Q_OBJECT -public: + public: SingleApplication(int &argc, char *argv[], const QString uniqueKey); bool isRunning(); bool sendMessage(const QString &message); -public slots: + public slots: void receiveMessage(); -signals: + signals: void messageAvailable(QString message); -private: + private: bool _isRunning; QString _uniqueKey; QSharedMemory sharedMemory; @@ -27,4 +27,5 @@ public slots: static const int timeout = 1000; }; -#endif // SINGLE_APPLICATION_H + +#endif // SINGLE_APPLICATION_H_ diff --git a/trayicon.h b/trayicon.h index 916832c2c..ab2ed84e2 100644 --- a/trayicon.h +++ b/trayicon.h @@ -10,18 +10,19 @@ class TrayIcon : public QWidget { Q_OBJECT -public: + + public: explicit TrayIcon(QMainWindow *parent); void showMessage(QString title, QString msg, int time); void setVisible(bool visible); -signals: + signals: -public slots: + public slots: void showHideParent(); void iconActivated(QSystemTrayIcon::ActivationReason reason); -private: + private: void createActions(); void createTrayIcon(); @@ -35,4 +36,4 @@ public slots: QMainWindow *parentwin; }; -#endif // TRAYICON_H +#endif // TRAYICON_H_ diff --git a/usersdialog.h b/usersdialog.h index 6b1c4f234..2088265a6 100644 --- a/usersdialog.h +++ b/usersdialog.h @@ -28,24 +28,24 @@ struct UserInfo { class UsersDialog : public QDialog { Q_OBJECT -public: + public: explicit UsersDialog(QWidget *parent = 0); ~UsersDialog(); void setUsers(QList *); -protected: + protected: void closeEvent(QCloseEvent *event); -private slots: - void itemChange(QListWidgetItem *); + private slots: + void itemChange(QListWidgetItem *item); void on_clearButton_clicked(); void on_lineEdit_textChanged(const QString &filter); void on_checkBox_clicked(); -private: + private: Ui::UsersDialog *ui; QList *userList; void populateList(const QString &filter); }; -#endif // USERSDIALOG_H +#endif // USERSDIALOG_H_ diff --git a/util.h b/util.h index 6d8eeda09..f71787ac0 100644 --- a/util.h +++ b/util.h @@ -5,17 +5,18 @@ #include class Util { -public: - static QString findBinaryInPath(QString); + public: + static QString findBinaryInPath(QString binary); static QString findPasswordStore(); - static QString normalizeFolderPath(QString); - static bool checkConfig(QString, QString, QString); + static QString normalizeFolderPath(QString path); + static bool checkConfig(QString passStore, QString passExecutable, + QString gpgExecutable); static void qSleep(int); -private: + private: static void initialiseEnvironment(); static QProcessEnvironment _env; static bool _envInitialised; }; -#endif // UTIL_H +#endif // UTIL_H_ From c34054da00a7151c7d35cabdd3228b1a982d4bee Mon Sep 17 00:00:00 2001 From: Anne Jan Brouwer Date: Tue, 24 Nov 2015 00:55:22 +0100 Subject: [PATCH 09/13] More linting and tiny optimisations (++i vs i++) --- configdialog.cpp | 12 ++++++------ mainwindow.h | 14 +++++++------- passworddialog.cpp | 10 +++++----- progressindicator.h | 1 + singleapplication.h | 7 +++---- storemodel.h | 6 +++--- util.h | 2 +- 7 files changed, 26 insertions(+), 26 deletions(-) diff --git a/configdialog.cpp b/configdialog.cpp index bc6a3f125..3a170dcc2 100644 --- a/configdialog.cpp +++ b/configdialog.cpp @@ -203,7 +203,7 @@ void ConfigDialog::on_toolButtonPass_clicked() { */ void ConfigDialog::on_toolButtonStore_clicked() { QString store = selectFolder(); - if (!store.isEmpty()) // TODO call check + if (!store.isEmpty()) // TODO(annejan) call check ui->storePath->setText(store); } @@ -451,7 +451,7 @@ void ConfigDialog::on_addButton_clicked() { * @brief ConfigDialog::on_deleteButton_clicked */ void ConfigDialog::on_deleteButton_clicked() { - QSet selectedRows; // we use a set to prevent doubles + QSet selectedRows; // we use a set to prevent doubles QList itemList = ui->profileTable->selectedItems(); if (itemList.count() == 0) { QMessageBox::warning(this, tr("No profile selected"), @@ -459,13 +459,13 @@ void ConfigDialog::on_deleteButton_clicked() { return; } QTableWidgetItem *item; - foreach (item, itemList) + foreach(item, itemList) selectedRows.insert(item->row()); // get a list, and sort it big to small QList rows = selectedRows.toList(); qSort(rows.begin(), rows.end()); // now actually do the removing: - foreach (int row, rows) + foreach(int row, rows) ui->profileTable->removeRow(row); if (ui->profileTable->rowCount() < 1) ui->deleteButton->setEnabled(false); @@ -505,7 +505,7 @@ void ConfigDialog::wizard() { QString passStore = ui->storePath->text(); if (!QFile(passStore).exists()) { - // TODO pass version? + // TODO(annejan) pass version? if (QMessageBox::question( this, tr("Create password-store?"), tr("Would you like to create a password-store at %1?") @@ -604,7 +604,7 @@ void ConfigDialog::on_checkBoxUseTrayIcon_clicked() { * @param event */ void ConfigDialog::closeEvent(QCloseEvent *event) { - // TODO save window size or something? + // TODO(annejan) save window size or something? event->accept(); } diff --git a/mainwindow.h b/mainwindow.h index 0b90ac6c8..6b978a63d 100644 --- a/mainwindow.h +++ b/mainwindow.h @@ -33,7 +33,7 @@ class MainWindow : public QMainWindow { enum actionType { GPG, GIT, EDIT, DELETE, GPG_INTERNAL, PWGEN }; -public: + public: enum clipBoardType { CLIPBOARD_NEVER = 0, CLIPBOARD_ALWAYS = 1, @@ -56,10 +56,10 @@ class MainWindow : public QMainWindow { void config(); void executePassGitInit(); -protected: + protected: void closeEvent(QCloseEvent *event); -private slots: + private slots: void on_updateButton_clicked(); void on_pushButton_clicked(); void on_treeView_clicked(const QModelIndex &index); @@ -86,7 +86,7 @@ private slots: void focusInput(); void copyPasswordToClipboard(); -private: + private: QApplication *QtPass; QScopedPointer settings; QScopedPointer ui; @@ -145,7 +145,7 @@ private slots: void updateText(); void executePass(QString, QString = QString()); void executeWrapper(QString, QString, QString = QString()); - void enableUiElements(bool); + void enableUiElements(bool state); void selectFirstFile(); QModelIndex firstFile(QModelIndex parentIndex); QString getDir(const QModelIndex &, bool); @@ -162,10 +162,10 @@ private slots: void initTrayIcon(); void destroyTrayIcon(); bool removeDir(const QString &dirName); - void waitFor(int); + void waitFor(int seconds); void clearTemplateWidgets(); void setClippedPassword(const QString &pass); const QString &getClippedPassword(); }; -#endif // MAINWINDOW_H +#endif // MAINWINDOW_H_ diff --git a/passworddialog.cpp b/passworddialog.cpp index fb081a3d2..19fed022c 100644 --- a/passworddialog.cpp +++ b/passworddialog.cpp @@ -1,8 +1,8 @@ #include "passworddialog.h" -#include "ui_passworddialog.h" #include #include #include +#include "ui_passworddialog.h" PasswordDialog::PasswordDialog(MainWindow *parent) : QDialog(parent), ui(new Ui::PasswordDialog) { @@ -49,14 +49,14 @@ void PasswordDialog::setPassword(QString password) { previous = widget; } if (allFields) { - for (int j = 0; j < tokens.length(); j++) { + for (int j = 0; j < tokens.length(); ++j) { QString token = tokens.at(j); if (token.contains(':')) { int colon = token.indexOf(':'); QString field = token.left(colon); QString value = token.right(token.length() - colon - 1); if (!passTemplate.contains(field) && value.startsWith("//")) - continue; // colon is probably from a url + continue; // colon is probably from a url QLineEdit *line = new QLineEdit(); line->setObjectName(field); line->setText(value); @@ -64,7 +64,7 @@ void PasswordDialog::setPassword(QString password) { setTabOrder(previous, line); previous = line; tokens.removeAt(j); - j--; // tokens.length() also got shortened by the remove.. + --j; // tokens.length() also got shortened by the remove.. } } } @@ -91,7 +91,7 @@ QString PasswordDialog::getPassword() { void PasswordDialog::setTemplate(QString rawFields) { fields = rawFields.split('\n'); QWidget *previous = ui->checkBoxShow; - foreach (QString field, fields) { + foreach(QString field, fields) { if (field.isEmpty()) continue; QLineEdit *line = new QLineEdit(); diff --git a/progressindicator.h b/progressindicator.h index 7cfc4c7bd..1af289c11 100644 --- a/progressindicator.h +++ b/progressindicator.h @@ -52,6 +52,7 @@ class QProgressIndicator : public QWidget { virtual QSize sizeHint() const; int heightForWidth(int w) const; + public slots: /*! Starts the spin animation. \sa stopAnimation isAnimated diff --git a/singleapplication.h b/singleapplication.h index 79f1c28a2..6f9802c34 100644 --- a/singleapplication.h +++ b/singleapplication.h @@ -1,5 +1,5 @@ -#ifndef SINGLE_APPLICATION_H -#define SINGLE_APPLICATION_H +#ifndef SINGLEAPPLICATION_H +#define SINGLEAPPLICATION_H #include #include @@ -9,7 +9,6 @@ class SingleApplication : public QApplication { Q_OBJECT public: SingleApplication(int &argc, char *argv[], const QString uniqueKey); - bool isRunning(); bool sendMessage(const QString &message); @@ -28,4 +27,4 @@ class SingleApplication : public QApplication { static const int timeout = 1000; }; -#endif // SINGLE_APPLICATION_H_ +#endif // SINGLEAPPLICATION_H_ diff --git a/storemodel.h b/storemodel.h index 438a3a976..7b3bc0a3c 100644 --- a/storemodel.h +++ b/storemodel.h @@ -7,11 +7,11 @@ class StoreModel : public QSortFilterProxyModel { Q_OBJECT -private: + private: QFileSystemModel *fs; QString store; -public: + public: StoreModel(); bool filterAcceptsRow(int, const QModelIndex &) const; @@ -20,4 +20,4 @@ class StoreModel : public QSortFilterProxyModel { QVariant data(const QModelIndex &index, int role) const; }; -#endif // STOREMODEL_H +#endif // STOREMODEL_H_ diff --git a/util.h b/util.h index f71787ac0..488800c2e 100644 --- a/util.h +++ b/util.h @@ -11,7 +11,7 @@ class Util { static QString normalizeFolderPath(QString path); static bool checkConfig(QString passStore, QString passExecutable, QString gpgExecutable); - static void qSleep(int); + static void qSleep(int ms); private: static void initialiseEnvironment(); From 703840e9273af99698c909257efd4e93d3d72a15 Mon Sep 17 00:00:00 2001 From: Anne Jan Brouwer Date: Tue, 24 Nov 2015 01:19:28 +0100 Subject: [PATCH 10/13] Even more linting and one more tiny opti --- configdialog.h | 54 +++++++++---------- keygendialog.cpp | 2 +- keygendialog.h | 6 +-- mainwindow.cpp | 48 ++++++++--------- mainwindow.h | 4 +- passworddialog.h | 4 +- ...essindicator.cpp => qprogressindicator.cpp | 3 +- progressindicator.h => qprogressindicator.h | 4 +- qtpass.pro | 8 +-- singleapplication.h | 4 +- storemodel.h | 4 +- trayicon.h | 4 +- usersdialog.cpp | 4 +- usersdialog.h | 6 +-- util.cpp | 4 +- util.h | 4 +- 16 files changed, 81 insertions(+), 82 deletions(-) rename progressindicator.cpp => qprogressindicator.cpp (98%) rename progressindicator.h => qprogressindicator.h (97%) diff --git a/configdialog.h b/configdialog.h index e6b38ba43..f24b6949e 100644 --- a/configdialog.h +++ b/configdialog.h @@ -1,11 +1,11 @@ -#ifndef DIALOG_H -#define DIALOG_H +#ifndef CONFIGDIALOG_H_ +#define CONFIGDIALOG_H_ #include #include -#include "mainwindow.h" #include #include +#include "mainwindow.h" namespace Ui { struct UserInfo; @@ -16,7 +16,7 @@ class ConfigDialog; class ConfigDialog : public QDialog { Q_OBJECT -public: + public: explicit ConfigDialog(MainWindow *parent); ~ConfigDialog(); void setPassPath(QString); @@ -24,15 +24,15 @@ class ConfigDialog : public QDialog { void setGpgPath(QString); void setStorePath(QString); void setProfiles(QHash, QString); - void usePass(bool); + void usePass(bool usePass); void useClipboard(MainWindow::clipBoardType); - void useAutoclear(bool); - void setAutoclear(int); - void useAutoclearPanel(bool); - void setAutoclearPanel(int); - void hidePassword(bool); - void hideContent(bool); - void addGPGId(bool); + void useAutoclear(bool useAutoclear); + void setAutoclear(int seconds); + void useAutoclearPanel(bool useAutoclearPanel); + void setAutoclearPanel(int seconds); + void hidePassword(bool hidePassword); + void hideContent(bool hideContent); + void addGPGId(bool addGPGId); QString getPassPath(); QString getGitPath(); QString getGpgPath(); @@ -52,36 +52,36 @@ class ConfigDialog : public QDialog { bool useTrayIcon(); bool hideOnClose(); bool startMinimized(); - void useTrayIcon(bool); - void hideOnClose(bool); - void startMinimized(bool); - void useGit(bool); + void useTrayIcon(bool useTrayIdon); + void hideOnClose(bool hideOnClose); + void startMinimized(bool startMinimized); + void useGit(bool useGit); bool useGit(); QString getPwgenPath(); void setPwgenPath(QString); - void usePwgen(bool); - void useSymbols(bool); - void setPasswordLength(int); + void usePwgen(bool usePwgen); + void useSymbols(bool useSymbols); + void setPasswordLength(int pwLen); void setPasswordChars(QString); bool usePwgen(); bool useSymbols(); int getPasswordLength(); QString getPasswordChars(); bool useTemplate(); - void useTemplate(bool); + void useTemplate(bool useTemplate); QString getTemplate(); void setTemplate(QString); - void templateAllFields(bool); + void templateAllFields(bool templateAllFields); bool templateAllFields(); bool autoPull(); - void autoPull(bool); + void autoPull(bool autoPull); bool autoPush(); - void autoPush(bool); + void autoPush(bool autoPush); -protected: + protected: void closeEvent(QCloseEvent *event); -private slots: + private slots: void on_radioButtonNative_clicked(); void on_radioButtonPass_clicked(); void on_toolButtonGit_clicked(); @@ -99,7 +99,7 @@ private slots: void on_checkBoxUsePwgen_clicked(); void on_checkBoxUseTemplate_clicked(); -private: + private: QScopedPointer ui; void setGroupBoxState(); QString selectExecutable(); @@ -110,4 +110,4 @@ private slots: MainWindow *mainWindow; }; -#endif // DIALOG_H +#endif // CONFIGDIALOG_H_ diff --git a/keygendialog.cpp b/keygendialog.cpp index c44cd0874..4fe2ad3f7 100644 --- a/keygendialog.cpp +++ b/keygendialog.cpp @@ -2,7 +2,7 @@ #include #include #include "ui_keygendialog.h" -#include "progressindicator.h" +#include "qprogressindicator.h" KeygenDialog::KeygenDialog(ConfigDialog *parent) : QDialog(parent), ui(new Ui::KeygenDialog) { diff --git a/keygendialog.h b/keygendialog.h index ab6c94f8a..4beb148e5 100644 --- a/keygendialog.h +++ b/keygendialog.h @@ -1,5 +1,5 @@ -#ifndef KEYGENDIALOG_H -#define KEYGENDIALOG_H +#ifndef KEYGENDIALOG_H_ +#define KEYGENDIALOG_H_ #include #include @@ -19,7 +19,7 @@ class KeygenDialog : public QDialog { protected: void closeEvent(QCloseEvent *event); - private slots: +private slots: void on_passphrase1_textChanged(const QString &arg1); void on_passphrase2_textChanged(const QString &arg1); void on_checkBox_stateChanged(int arg1); diff --git a/mainwindow.cpp b/mainwindow.cpp index fac1a4c2a..d9fd01e51 100644 --- a/mainwindow.cpp +++ b/mainwindow.cpp @@ -1,10 +1,4 @@ #include "mainwindow.h" -#include "ui_mainwindow.h" -#include "configdialog.h" -#include "usersdialog.h" -#include "keygendialog.h" -#include "passworddialog.h" -#include "util.h" #include #include #include @@ -21,6 +15,12 @@ #include #undef DELETE #endif +#include "ui_mainwindow.h" +#include "configdialog.h" +#include "usersdialog.h" +#include "keygendialog.h" +#include "passworddialog.h" +#include "util.h" /** * @brief MainWindow::MainWindow @@ -223,7 +223,7 @@ bool MainWindow::checkConfig() { profile = settings.value("profile").toString(); settings.beginGroup("profiles"); QStringList keys = settings.childKeys(); - foreach (QString key, keys) + foreach(QString key, keys) profiles[key] = settings.value(key).toString(); settings.endGroup(); @@ -295,7 +295,7 @@ bool MainWindow::checkConfig() { freshStart = false; - // TODO: this needs to be before we try to access the store, + // TODO(annejan): this needs to be before we try to access the store, // but it would be better to do it after the Window is shown, // as the long delay it can cause is irritating otherwise. if (useWebDav) @@ -400,7 +400,7 @@ void MainWindow::config() { d->autoPull(autoPull); d->autoPush(autoPush); if (startupPhase) - d->wizard(); // does shit + d->wizard(); // does shit if (d->exec()) { if (d->result() == QDialog::Accepted) { passExecutable = d->getPassPath(); @@ -698,7 +698,7 @@ void MainWindow::readyRead(bool finished = false) { pass->setReadOnly(true); ui->formLayout->addRow(pass); - for (int j = 0; j < tokens.length(); j++) { + for (int j = 0; j < tokens.length(); ++j) { QString token = tokens.at(j); if (token.contains(':')) { int colon = token.indexOf(':'); @@ -706,14 +706,14 @@ void MainWindow::readyRead(bool finished = false) { if (templateAllFields || passTemplate.contains(field)) { QString value = token.right(token.length() - colon - 1); if (!passTemplate.contains(field) && value.startsWith("//")) - continue; // colon is probably from a url + continue; // colon is probably from a url QLineEdit *line = new QLineEdit(); line->setObjectName(field); line->setText(value); line->setReadOnly(true); ui->formLayout->addRow(new QLabel(field), line); tokens.removeAt(j); - j--; // tokens.length() also got shortened by the remove.. + --j; // tokens.length() also got shortened by the remove.. } } } @@ -743,7 +743,7 @@ void MainWindow::readyRead(bool finished = false) { qDebug() << "Keygen Done"; keygen->close(); keygen = 0; - // TODO some sanity checking ? + // TODO(annejan) some sanity checking ? } } @@ -992,7 +992,7 @@ QString MainWindow::getRecipientString(QString for_file, QString separator, QStringList recipients_list = getRecipientList(for_file); if (count) *count = recipients_list.size(); - foreach (const QString recipient, recipients_list) + foreach(const QString recipient, recipients_list) recipients_str += separator + '"' + recipient + '"'; return recipients_str; } @@ -1156,7 +1156,7 @@ bool MainWindow::removeDir(const QString &dirName) { QDir dir(dirName); if (dir.exists(dirName)) { - Q_FOREACH (QFileInfo info, + Q_FOREACH(QFileInfo info, dir.entryInfoList(QDir::NoDotAndDotDot | QDir::System | QDir::Hidden | QDir::AllDirs | QDir::Files, QDir::DirsFirst)) { @@ -1206,7 +1206,7 @@ QList MainWindow::listKeys(QString keystring, bool secret) { QStringList keys = QString(process->readAllStandardOutput()) .split(QRegExp("[\r\n]"), QString::SkipEmptyParts); UserInfo current_user; - foreach (QString key, keys) { + foreach(QString key, keys) { QStringList props = key.split(':'); if (props.size() < 10) continue; @@ -1242,7 +1242,7 @@ void MainWindow::on_usersButton_clicked() { return; } QList secret_keys = listKeys("", true); - foreach (const UserInfo &sec, secret_keys) { + foreach(const UserInfo &sec, secret_keys) { for (QList::iterator it = users.begin(); it != users.end(); ++it) if (sec.key_id == it->key_id) it->have_secret = true; @@ -1256,7 +1256,7 @@ void MainWindow::on_usersButton_clicked() { getRecipientString(dir.isEmpty() ? "" : dir, " ", &count); if (!recipients.isEmpty()) selected_users = listKeys(recipients); - foreach (const UserInfo &sel, selected_users) { + foreach(const UserInfo &sel, selected_users) { for (QList::iterator it = users.begin(); it != users.end(); ++it) if (sel.key_id == it->key_id) it->enabled = true; @@ -1264,7 +1264,7 @@ void MainWindow::on_usersButton_clicked() { if (count > selected_users.size()) { // Some keys seem missing from keyring, add them separately QStringList recipients = getRecipientList(dir.isEmpty() ? "" : dir); - foreach (const QString recipient, recipients) { + foreach(const QString recipient, recipients) { if (listKeys(recipient).size() < 1) { UserInfo i; i.enabled = true; @@ -1295,7 +1295,7 @@ void MainWindow::on_usersButton_clicked() { return; } bool secret_selected = false; - foreach (const UserInfo &user, users) { + foreach(const UserInfo &user, users) { if (user.enabled) { gpgId.write((user.key_id + "\n").toUtf8()); secret_selected |= user.have_secret; @@ -1379,7 +1379,7 @@ QStringList MainWindow::getSecretKeys() { if (keys.size() == 0) return names; - foreach (const UserInfo &sec, keys) + foreach(const UserInfo &sec, keys) names << sec.name; return names; @@ -1418,7 +1418,7 @@ void MainWindow::updateProfileBox() { } } int index = ui->profileBox->findText(profile); - if (index != -1) // -1 for not found + if (index != -1) // -1 for not found ui->profileBox->setCurrentIndex(index); } @@ -1598,7 +1598,7 @@ void MainWindow::addFolder() { newdir.prepend(dir); // qDebug() << newdir; QDir().mkdir(newdir); - // TODO add to git? + // TODO(annejan) add to git? } /** @@ -1608,7 +1608,7 @@ void MainWindow::editPassword() { if (useGit && autoPull) on_updateButton_clicked(); waitFor(30); - // TODO move to editbutton stuff possibly? + // TODO(annejan) move to editbutton stuff possibly? currentDir = getDir(ui->treeView->currentIndex(), false); lastDecrypt = "Could not decrypt"; QString file = getFile(ui->treeView->currentIndex(), usePass); diff --git a/mainwindow.h b/mainwindow.h index 6b978a63d..8afb9ff9b 100644 --- a/mainwindow.h +++ b/mainwindow.h @@ -1,5 +1,5 @@ -#ifndef MAINWINDOW_H -#define MAINWINDOW_H +#ifndef MAINWINDOW_H_ +#define MAINWINDOW_H_ #include #include diff --git a/passworddialog.h b/passworddialog.h index eeebdcebc..3267cf401 100644 --- a/passworddialog.h +++ b/passworddialog.h @@ -1,5 +1,5 @@ -#ifndef PASSWORDDIALOG_H -#define PASSWORDDIALOG_H +#ifndef PASSWORDDIALOG_H_ +#define PASSWORDDIALOG_H_ #include #include "mainwindow.h" diff --git a/progressindicator.cpp b/qprogressindicator.cpp similarity index 98% rename from progressindicator.cpp rename to qprogressindicator.cpp index d1bb5fa2b..a626a7807 100644 --- a/progressindicator.cpp +++ b/qprogressindicator.cpp @@ -1,5 +1,4 @@ -#include "progressindicator.h" - +#include "qprogressindicator.h" #include QProgressIndicator::QProgressIndicator(QWidget *parent) diff --git a/progressindicator.h b/qprogressindicator.h similarity index 97% rename from progressindicator.h rename to qprogressindicator.h index 1af289c11..5856b8620 100644 --- a/progressindicator.h +++ b/qprogressindicator.h @@ -1,5 +1,5 @@ -#ifndef QPROGRESSINDICATOR_H -#define QPROGRESSINDICATOR_H +#ifndef QPROGRESSINDICATOR_H_ +#define QPROGRESSINDICATOR_H_ #include #include diff --git a/qtpass.pro b/qtpass.pro index fbf2c5477..152815ed9 100644 --- a/qtpass.pro +++ b/qtpass.pro @@ -27,9 +27,9 @@ SOURCES += main.cpp\ util.cpp \ usersdialog.cpp \ keygendialog.cpp \ - progressindicator.cpp \ trayicon.cpp \ - passworddialog.cpp + passworddialog.cpp \ + qprogressindicator.cpp HEADERS += mainwindow.h \ configdialog.h \ @@ -37,9 +37,9 @@ HEADERS += mainwindow.h \ util.h \ usersdialog.h \ keygendialog.h \ - progressindicator.h \ trayicon.h \ - passworddialog.h + passworddialog.h \ + qprogressindicator.h FORMS += mainwindow.ui \ configdialog.ui \ diff --git a/singleapplication.h b/singleapplication.h index 6f9802c34..ad642446a 100644 --- a/singleapplication.h +++ b/singleapplication.h @@ -1,5 +1,5 @@ -#ifndef SINGLEAPPLICATION_H -#define SINGLEAPPLICATION_H +#ifndef SINGLEAPPLICATION_H_ +#define SINGLEAPPLICATION_H_ #include #include diff --git a/storemodel.h b/storemodel.h index 7b3bc0a3c..c489c0e83 100644 --- a/storemodel.h +++ b/storemodel.h @@ -1,5 +1,5 @@ -#ifndef STOREMODEL_H -#define STOREMODEL_H +#ifndef STOREMODEL_H_ +#define STOREMODEL_H_ #include #include diff --git a/trayicon.h b/trayicon.h index ab2ed84e2..4eaacf0e6 100644 --- a/trayicon.h +++ b/trayicon.h @@ -1,5 +1,5 @@ -#ifndef TRAYICON_H -#define TRAYICON_H +#ifndef TRAYICON_H_ +#define TRAYICON_H_ #include #include diff --git a/usersdialog.cpp b/usersdialog.cpp index e6691e8e1..424524ec0 100644 --- a/usersdialog.cpp +++ b/usersdialog.cpp @@ -1,7 +1,7 @@ #include "usersdialog.h" -#include "ui_usersdialog.h" #include #include +#include "ui_usersdialog.h" UsersDialog::UsersDialog(QWidget *parent) : QDialog(parent), ui(new Ui::UsersDialog) { @@ -89,7 +89,7 @@ void UsersDialog::on_lineEdit_textChanged(const QString &filter) { } void UsersDialog::closeEvent(QCloseEvent *event) { - // TODO save window size or somethign + // TODO(annejan) save window size or somethign event->accept(); } diff --git a/usersdialog.h b/usersdialog.h index 2088265a6..a88d38bd8 100644 --- a/usersdialog.h +++ b/usersdialog.h @@ -1,5 +1,5 @@ -#ifndef USERSDIALOG_H -#define USERSDIALOG_H +#ifndef USERSDIALOG_H_ +#define USERSDIALOG_H_ #include #include @@ -36,7 +36,7 @@ class UsersDialog : public QDialog { protected: void closeEvent(QCloseEvent *event); - private slots: +private slots: void itemChange(QListWidgetItem *item); void on_clearButton_clicked(); void on_lineEdit_textChanged(const QString &filter); diff --git a/util.cpp b/util.cpp index 8fdfee98b..bc9b6cef9 100644 --- a/util.cpp +++ b/util.cpp @@ -18,7 +18,7 @@ void Util::initialiseEnvironment() { if (!_envInitialised) { _env = QProcessEnvironment::systemEnvironment(); #ifdef __APPLE__ - // TODO checks here + // TODO(annejan) checks here QString path = _env.value("PATH"); if (!path.contains("/usr/local/MacGPG2/bin") && @@ -84,7 +84,7 @@ QString Util::findBinaryInPath(QString binary) { } #endif - foreach (QString entry, entries) { + foreach(QString entry, entries) { QScopedPointer qfi(new QFileInfo(entry.append(binary))); #ifdef Q_OS_WIN if (!qfi->exists()) diff --git a/util.h b/util.h index 488800c2e..e3ec61bc6 100644 --- a/util.h +++ b/util.h @@ -1,5 +1,5 @@ -#ifndef UTIL_H -#define UTIL_H +#ifndef UTIL_H_ +#define UTIL_H_ #include #include From ade70fbf696244146ddb483d0fbda9b6a74a3f79 Mon Sep 17 00:00:00 2001 From: Anne Jan Brouwer Date: Tue, 24 Nov 2015 01:21:52 +0100 Subject: [PATCH 11/13] I'm done for now :) --- mainwindow.cpp | 2 +- usersdialog.h | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/mainwindow.cpp b/mainwindow.cpp index d9fd01e51..2955501f2 100644 --- a/mainwindow.cpp +++ b/mainwindow.cpp @@ -1620,7 +1620,7 @@ void MainWindow::editPassword() { executeWrapper(gpgExecutable, "-d --quiet --yes --no-encrypt-to --batch --use-agent \"" + file + '"'); - process->waitForFinished(30000); // long wait (passphrase stuff) + process->waitForFinished(30000); // long wait (passphrase stuff) if (process->exitStatus() == QProcess::NormalExit) on_editButton_clicked(); } diff --git a/usersdialog.h b/usersdialog.h index a88d38bd8..23eb9c7e4 100644 --- a/usersdialog.h +++ b/usersdialog.h @@ -36,7 +36,7 @@ class UsersDialog : public QDialog { protected: void closeEvent(QCloseEvent *event); -private slots: + private slots: void itemChange(QListWidgetItem *item); void on_clearButton_clicked(); void on_lineEdit_textChanged(const QString &filter); From 2f288e60c245a2a3430bab21b04c72b11114abfe Mon Sep 17 00:00:00 2001 From: Anne Jan Brouwer Date: Tue, 24 Nov 2015 01:40:13 +0100 Subject: [PATCH 12/13] Done with flint++ too :smile: --- configdialog.cpp | 4 ++-- passworddialog.cpp | 6 +++--- qprogressindicator.cpp | 2 +- singleapplication.cpp | 3 +-- storemodel.cpp | 2 +- util.cpp | 2 +- 6 files changed, 9 insertions(+), 10 deletions(-) diff --git a/configdialog.cpp b/configdialog.cpp index 3a170dcc2..4d6b3d4c0 100644 --- a/configdialog.cpp +++ b/configdialog.cpp @@ -411,7 +411,7 @@ void ConfigDialog::setProfiles(QHash profiles, if (i.key() == profile) ui->profileTable->selectRow(n); } - n++; + ++n; } } @@ -422,7 +422,7 @@ void ConfigDialog::setProfiles(QHash profiles, QHash ConfigDialog::getProfiles() { QHash profiles; // Check? - for (int i = 0; i < ui->profileTable->rowCount(); i++) { + for (int i = 0; i < ui->profileTable->rowCount(); ++i) { QTableWidgetItem *pathItem = ui->profileTable->item(i, 1); if (0 != pathItem) { QTableWidgetItem *item = ui->profileTable->item(i, 0); diff --git a/passworddialog.cpp b/passworddialog.cpp index 19fed022c..d3067fe33 100644 --- a/passworddialog.cpp +++ b/passworddialog.cpp @@ -33,12 +33,12 @@ void PasswordDialog::setPassword(QString password) { tokens.pop_front(); if (templating) { QWidget *previous = ui->checkBoxShow; - for (int i = 0; i < ui->formLayout->rowCount(); i++) { + for (int i = 0; i < ui->formLayout->rowCount(); ++i) { QLayoutItem *item = ui->formLayout->itemAt(i, QFormLayout::FieldRole); if (item == NULL) continue; QWidget *widget = item->widget(); - for (int j = 0; j < tokens.length(); j++) { + for (int j = 0; j < tokens.length(); ++j) { QString token = tokens.at(j); if (token.startsWith(widget->objectName() + ':')) { tokens.removeAt(j); @@ -74,7 +74,7 @@ void PasswordDialog::setPassword(QString password) { QString PasswordDialog::getPassword() { QString passFile = ui->lineEditPassword->text() + "\n"; - for (int i = 0; i < ui->formLayout->rowCount(); i++) { + for (int i = 0; i < ui->formLayout->rowCount(); ++i) { QLayoutItem *item = ui->formLayout->itemAt(i, QFormLayout::FieldRole); if (item == NULL) continue; diff --git a/qprogressindicator.cpp b/qprogressindicator.cpp index a626a7807..f00b084cd 100644 --- a/qprogressindicator.cpp +++ b/qprogressindicator.cpp @@ -78,7 +78,7 @@ void QProgressIndicator::paintEvent(QPaintEvent * /*event*/) { int capsuleWidth = (width > 32) ? capsuleHeight * .23 : capsuleHeight * .35; int capsuleRadius = capsuleWidth / 2; - for (int i = 0; i < 12; i++) { + for (int i = 0; i < 12; ++i) { QColor color = m_color; color.setAlphaF(1.0f - (i / 12.0f)); p.setPen(Qt::NoPen); diff --git a/singleapplication.cpp b/singleapplication.cpp index 3eb44838a..d72a61694 100644 --- a/singleapplication.cpp +++ b/singleapplication.cpp @@ -1,6 +1,5 @@ -#include - #include "singleapplication.h" +#include /** * @brief SingleApplication::SingleApplication diff --git a/storemodel.cpp b/storemodel.cpp index cc664541b..ada0540eb 100644 --- a/storemodel.cpp +++ b/storemodel.cpp @@ -30,7 +30,7 @@ bool StoreModel::ShowThis(const QModelIndex index) const { return retVal; // Gives you the info for number of childs with a parent if (sourceModel()->rowCount(index) > 0) { - for (int nChild = 0; nChild < sourceModel()->rowCount(index); nChild++) { + for (int nChild = 0; nChild < sourceModel()->rowCount(index); ++nChild) { QModelIndex childIndex = sourceModel()->index(nChild, 0, index); if (!childIndex.isValid()) break; diff --git a/util.cpp b/util.cpp index bc9b6cef9..ef4abf8bd 100644 --- a/util.cpp +++ b/util.cpp @@ -1,9 +1,9 @@ +#include "util.h" #include #include #include #include #include -#include "util.h" #ifdef Q_OS_WIN #include #endif From 640f398b27760c628046cef59141af7fe1703af0 Mon Sep 17 00:00:00 2001 From: Anne Jan Brouwer Date: Tue, 24 Nov 2015 11:12:03 +0100 Subject: [PATCH 13/13] More linting (reinterpret_cast and empty {} etc) --- keygendialog.h | 2 +- passworddialog.cpp | 4 ++-- qprogressindicator.h | 2 +- trayicon.cpp | 2 +- 4 files changed, 5 insertions(+), 5 deletions(-) diff --git a/keygendialog.h b/keygendialog.h index 4beb148e5..19d996cef 100644 --- a/keygendialog.h +++ b/keygendialog.h @@ -19,7 +19,7 @@ class KeygenDialog : public QDialog { protected: void closeEvent(QCloseEvent *event); -private slots: + private slots: void on_passphrase1_textChanged(const QString &arg1); void on_passphrase2_textChanged(const QString &arg1); void on_checkBox_stateChanged(int arg1); diff --git a/passworddialog.cpp b/passworddialog.cpp index d3067fe33..688bcefb1 100644 --- a/passworddialog.cpp +++ b/passworddialog.cpp @@ -43,7 +43,7 @@ void PasswordDialog::setPassword(QString password) { if (token.startsWith(widget->objectName() + ':')) { tokens.removeAt(j); QString value = token.remove(0, widget->objectName().length() + 1); - ((QLineEdit *)widget)->setText(value); + reinterpret_cast(widget)->setText(value); } } previous = widget; @@ -79,7 +79,7 @@ QString PasswordDialog::getPassword() { if (item == NULL) continue; QWidget *widget = item->widget(); - QString text = ((QLineEdit *)widget)->text(); + QString text = reinterpret_cast(widget)->text(); if (text.isEmpty()) continue; passFile += widget->objectName() + ":" + text + "\n"; diff --git a/qprogressindicator.h b/qprogressindicator.h index 5856b8620..980ebd7de 100644 --- a/qprogressindicator.h +++ b/qprogressindicator.h @@ -21,7 +21,7 @@ class QProgressIndicator : public QWidget { Q_PROPERTY(QColor color READ color WRITE setColor) public: - QProgressIndicator(QWidget *parent = 0); + explicit QProgressIndicator(QWidget *parent = 0); /*! Returns the delay between animation steps. \return The number of milliseconds between animation steps. By default, diff --git a/trayicon.cpp b/trayicon.cpp index f8e28e31d..f7cf76563 100644 --- a/trayicon.cpp +++ b/trayicon.cpp @@ -64,7 +64,7 @@ void TrayIcon::iconActivated(QSystemTrayIcon::ActivationReason reason) { case QSystemTrayIcon::MiddleClick: showMessage("test", "test msg", 1000); break; - default:; + default:{}; } }