diff --git a/.linthub.yml b/.linthub.yml new file mode 100644 index 000000000..900fabca4 --- /dev/null +++ b/.linthub.yml @@ -0,0 +1,13 @@ +platform: linux | osx +build: +- qmake +- make +analyzers: + - cpplint: true + include: ["*.cpp", "*.h", "*.hpp", "*.c"] + path: ./ + filters: + - -whitespace + - +whitespace/braces + style: google + - markdownlint: true 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/) diff --git a/configdialog.cpp b/configdialog.cpp index 690449088..4d6b3d4c0 100644 --- a/configdialog.cpp +++ b/configdialog.cpp @@ -13,153 +13,128 @@ * @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); - } + 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(); + 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); - } + if (ui->radioButtonPass->isChecked()) { + ui->groupBoxNative->setEnabled(false); + ui->groupBoxPass->setEnabled(true); + } else { + ui->groupBoxNative->setEnabled(true); + ui->groupBoxPass->setEnabled(false); + } } /** @@ -167,13 +142,13 @@ void ConfigDialog::setGroupBoxState() { * @return */ QString ConfigDialog::selectExecutable() { - QFileDialog dialog(this); - dialog.setFileMode(QFileDialog::ExistingFile); - dialog.setOption(QFileDialog::ReadOnly); - if (dialog.exec()) { - return dialog.selectedFiles().first(); - } - else return ""; + QFileDialog dialog(this); + dialog.setFileMode(QFileDialog::ExistingFile); + dialog.setOption(QFileDialog::ReadOnly); + if (dialog.exec()) + return dialog.selectedFiles().first(); + else + return ""; } /** @@ -181,264 +156,234 @@ QString ConfigDialog::selectExecutable() { * @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 ""; + 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(annejan) 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); } /** @@ -446,162 +391,160 @@ 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) +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); - } + // 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), +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(annejan) 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); + 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 still does not exist :/"; - // appears not to be store - // init yes / no ? - 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 still does not exist :/"; + // appears not to be store + // init yes / no ? + mainWindow->userDialog(passStore); + } + } } /** @@ -609,7 +552,7 @@ void ConfigDialog::wizard() * @return */ bool ConfigDialog::useTrayIcon() { - return ui->checkBoxUseTrayIcon->isChecked(); + return ui->checkBoxUseTrayIcon->isChecked(); } /** @@ -617,7 +560,8 @@ bool ConfigDialog::useTrayIcon() { * @return */ bool ConfigDialog::hideOnClose() { - return ui->checkBoxHideOnClose->isEnabled() && ui->checkBoxHideOnClose->isChecked(); + return ui->checkBoxHideOnClose->isEnabled() && + ui->checkBoxHideOnClose->isChecked(); } /** @@ -625,13 +569,13 @@ bool ConfigDialog::hideOnClose() { * @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); - } + ui->checkBoxUseTrayIcon->setChecked(useSystray); + ui->checkBoxHideOnClose->setEnabled(useSystray); + ui->checkBoxStartMinimized->setEnabled(useSystray); + if (!useSystray) { + ui->checkBoxHideOnClose->setChecked(false); + ui->checkBoxStartMinimized->setChecked(false); + } } /** @@ -639,20 +583,20 @@ void ConfigDialog::useTrayIcon(bool useSystray) { * @param hideOnClose */ void ConfigDialog::hideOnClose(bool hideOnClose) { - ui->checkBoxHideOnClose->setChecked(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); - } + if (ui->checkBoxUseTrayIcon->isChecked()) { + ui->checkBoxHideOnClose->setEnabled(true); + ui->checkBoxStartMinimized->setEnabled(true); + } else { + ui->checkBoxStartMinimized->setEnabled(false); + ui->checkBoxHideOnClose->setEnabled(false); + } } /** @@ -660,84 +604,74 @@ void ConfigDialog::on_checkBoxUseTrayIcon_clicked() { * @param event */ void ConfigDialog::closeEvent(QCloseEvent *event) { - // TODO save window size or something? - event->accept(); + // TODO(annejan) 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()); } /** @@ -745,11 +679,10 @@ void ConfigDialog::on_checkBoxUsePwgen_clicked() * @param usePwgen */ void ConfigDialog::usePwgen(bool usePwgen) { - if (ui->pwgenPath->text().isEmpty()) { - usePwgen = false; - } - ui->checkBoxUsePwgen->setChecked(usePwgen); - on_checkBoxUsePwgen_clicked(); + if (ui->pwgenPath->text().isEmpty()) + usePwgen = false; + ui->checkBoxUsePwgen->setChecked(usePwgen); + on_checkBoxUsePwgen_clicked(); } /** @@ -757,7 +690,7 @@ void ConfigDialog::usePwgen(bool usePwgen) { * @param useSymbols */ void ConfigDialog::useSymbols(bool useSymbols) { - ui->checkBoxUseSymbols->setChecked(useSymbols); + ui->checkBoxUseSymbols->setChecked(useSymbols); } /** @@ -765,35 +698,31 @@ void ConfigDialog::useSymbols(bool useSymbols) { * @param pwLen */ void ConfigDialog::setPasswordLength(int pwLen) { - ui->spinBoxPasswordLength->setValue(pwLen); + ui->spinBoxPasswordLength->setValue(pwLen); } void ConfigDialog::setPasswordChars(QString pwChars) { - ui->lineEditPasswordChars->setText(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(); + return ui->spinBoxPasswordLength->value(); } /** @@ -801,7 +730,7 @@ int ConfigDialog::getPasswordLength() { * @return */ QString ConfigDialog::getPasswordChars() { - return ui->lineEditPasswordChars->text(); + return ui->lineEditPasswordChars->text(); } /** @@ -809,7 +738,7 @@ QString ConfigDialog::getPasswordChars() { * @return */ bool ConfigDialog::startMinimized() { - return ui->checkBoxStartMinimized->isChecked(); + return ui->checkBoxStartMinimized->isChecked(); } /** @@ -817,15 +746,16 @@ bool ConfigDialog::startMinimized() { * @param startMinimized */ void ConfigDialog::startMinimized(bool startMinimized) { - ui->checkBoxStartMinimized->setChecked(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()); + ui->plainTextEditTemplate->setEnabled(ui->checkBoxUseTemplate->isChecked()); + ui->checkBoxTemplateAllFields->setEnabled( + ui->checkBoxUseTemplate->isChecked()); } /** @@ -833,8 +763,8 @@ void ConfigDialog::on_checkBoxUseTemplate_clicked() { * @param useTemplate */ void ConfigDialog::useTemplate(bool useTemplate) { - ui->checkBoxUseTemplate->setChecked(useTemplate); - on_checkBoxUseTemplate_clicked(); + ui->checkBoxUseTemplate->setChecked(useTemplate); + on_checkBoxUseTemplate_clicked(); } /** @@ -842,7 +772,7 @@ void ConfigDialog::useTemplate(bool useTemplate) { * @return */ bool ConfigDialog::useTemplate() { - return ui->checkBoxUseTemplate->isChecked(); + return ui->checkBoxUseTemplate->isChecked(); } /** @@ -850,7 +780,7 @@ bool ConfigDialog::useTemplate() { * @param passTemplate */ void ConfigDialog::setTemplate(QString passTemplate) { - ui->plainTextEditTemplate->setPlainText(passTemplate); + ui->plainTextEditTemplate->setPlainText(passTemplate); } /** @@ -858,7 +788,7 @@ void ConfigDialog::setTemplate(QString passTemplate) { * @return */ QString ConfigDialog::getTemplate() { - return ui->plainTextEditTemplate->toPlainText(); + return ui->plainTextEditTemplate->toPlainText(); } /** @@ -866,7 +796,7 @@ QString ConfigDialog::getTemplate() { * @param autoPull */ void ConfigDialog::autoPull(bool autoPull) { - ui->checkBoxAutoPull->setChecked(autoPull); + ui->checkBoxAutoPull->setChecked(autoPull); } /** @@ -874,31 +804,27 @@ void ConfigDialog::autoPull(bool autoPull) { * @param autoPush */ void ConfigDialog::autoPush(bool autoPush) { - ui->checkBoxAutoPush->setChecked(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(); + return ui->checkBoxTemplateAllFields->isChecked(); } /** @@ -906,5 +832,5 @@ bool ConfigDialog::templateAllFields() { * @param templateAll */ void ConfigDialog::templateAllFields(bool templateAll) { - ui->checkBoxTemplateAllFields->setChecked(templateAll); + ui->checkBoxTemplateAllFields->setChecked(templateAll); } diff --git a/configdialog.h b/configdialog.h index d18cd0ab5..f24b6949e 100644 --- a/configdialog.h +++ b/configdialog.h @@ -1,115 +1,113 @@ -#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; 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); + 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 usePass); + void useClipboard(MainWindow::clipBoardType); + 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(); + 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 useTrayIdon); + void hideOnClose(bool hideOnClose); + void startMinimized(bool startMinimized); + void useGit(bool useGit); + bool useGit(); + QString getPwgenPath(); + void setPwgenPath(QString); + 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 useTemplate); + QString getTemplate(); + void setTemplate(QString); + void templateAllFields(bool templateAllFields); + bool templateAllFields(); + bool autoPull(); + void autoPull(bool autoPull); + bool autoPush(); + void autoPush(bool autoPush); -protected: - void closeEvent(QCloseEvent *event); + protected: + 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(); + 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(); -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; + 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; }; -#endif // DIALOG_H +#endif // CONFIGDIALOG_H_ diff --git a/keygendialog.cpp b/keygendialog.cpp index 64d31a610..4fe2ad3f7 100644 --- a/keygendialog.cpp +++ b/keygendialog.cpp @@ -1,61 +1,50 @@ #include "keygendialog.h" -#include "ui_keygendialog.h" -#include "progressindicator.h" #include #include +#include "ui_keygendialog.h" +#include "qprogressindicator.h" -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); } /** @@ -63,85 +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(); + // TODO(annejan) save window size or somethign + event->accept(); } diff --git a/keygendialog.h b/keygendialog.h index 01f4a39a2..19d996cef 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 @@ -9,31 +9,29 @@ namespace Ui { class KeygenDialog; } -class KeygenDialog : public QDialog -{ - Q_OBJECT - -public: - explicit KeygenDialog(ConfigDialog *parent = 0); - ~KeygenDialog(); - -protected: - 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); - -private: - Ui::KeygenDialog *ui; - void replace(QString, QString); - void done(int r); - void no_protection(bool enable); - ConfigDialog *dialog; - +class KeygenDialog : public QDialog { + Q_OBJECT + + public: + explicit KeygenDialog(ConfigDialog *parent = 0); + ~KeygenDialog(); + + protected: + 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); + + private: + Ui::KeygenDialog *ui; + void replace(QString, QString); + void done(int r); + void no_protection(bool enable); + ConfigDialog *dialog; }; -#endif // KEYGENDIALOG_H +#endif // KEYGENDIALOG_H_ diff --git a/main.cpp b/main.cpp index c645fd100..d65a9e373 100644 --- a/main.cpp +++ b/main.cpp @@ -1,53 +1,52 @@ -#include "mainwindow.h" #include #include +#include "mainwindow.h" -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 aac760416..2955501f2 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 @@ -15,131 +9,141 @@ #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 #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 * @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(); + 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")); - } + 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() { #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(); - } - } - 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); - } + 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(); + } + } + 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 } @@ -147,464 +151,444 @@ void MainWindow::mountWebDav() { * @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); - } - 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(); - } + 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(); - - 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(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) + 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(); - } + 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); + } } /** @@ -612,19 +596,18 @@ void MainWindow::on_treeView_clicked(const QModelIndex &index) * @param args */ void MainWindow::executePass(QString args, QString input) { - executeWrapper(passExecutable, args, 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 + '"'); - } + qDebug() << "Pass git init called"; + if (usePass) + executePass("git init"); + else + executeWrapper("git", "init \"" + passStore + '"'); } /** @@ -633,186 +616,179 @@ void MainWindow::executePassGitInit() { * @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(); + // 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(); - } + 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 (!error.isEmpty()) { - if (currentAction == GIT) { - // https://github.com/IJHack/qtpass/issues/111 - output = "" + error + "
" + output; - } else { - output = "" + error + "
" + output; + 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(annejan) some sanity checking ? + } + } + + 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); } /** @@ -820,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"); @@ -840,125 +816,111 @@ void MainWindow::processFinished(int exitCode, QProcess::ExitStatus exitStatus) * @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); + 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); } /** @@ -967,60 +929,54 @@ void MainWindow::selectFirstFile() * @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 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; - } - } - 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; +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; + } + 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; } /** @@ -1030,19 +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; } /** @@ -1050,143 +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; - } - 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(); - } - } - } +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 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 = ""; } /** @@ -1194,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); - } - return result; +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); + } + 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); } /** @@ -1237,151 +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 } @@ -1389,318 +1335,295 @@ 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()); - } - } - } - int index = ui->profileBox->findText(profile); - if ( index != -1 ) { // -1 for not found - ui->profileBox->setCurrentIndex(index); - } +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); } /** * @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, \ +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); + } + QPoint globalPos = ui->textBrowser->viewport()->mapToGlobal(pos); - contextMenu->exec(globalPos); + 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(annejan) 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(annejan) 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(); + } } /** @@ -1708,99 +1631,94 @@ void MainWindow::editPassword() * @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 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; 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!")); - 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 587d2a749..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 @@ -21,149 +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 }; + public: + 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); + protected: + 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(); + 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(); -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(); + 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 state); + 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 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 e8199d8a8..688bcefb1 100644 --- a/passworddialog.cpp +++ b/passworddialog.cpp @@ -1,130 +1,111 @@ #include "passworddialog.h" -#include "ui_passworddialog.h" #include #include #include +#include "ui_passworddialog.h" -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); + reinterpret_cast(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 = reinterpret_cast(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; - } + 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); + 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..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" @@ -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); + public: + explicit PasswordDialog(MainWindow *parent = 0); + ~PasswordDialog(); + void setPassword(QString); + QString getPassword(); + void setTemplate(QString); + void setFile(QString); + void useTemplate(bool useTemplate); + void templateAll(bool templateAll); -private slots: - void on_checkBoxShow_stateChanged(int arg1); - void on_createPasswordButton_clicked(); + private slots: + void on_checkBoxShow_stateChanged(int arg1); + void on_createPasswordButton_clicked(); -private: - Ui::PasswordDialog *ui; - MainWindow *mainWindow; - QString passTemplate; - QStringList fields; - bool templating; - bool allFields; + private: + Ui::PasswordDialog *ui; + MainWindow *mainWindow; + QString passTemplate; + QStringList fields; + bool templating; + bool allFields; }; -#endif // PASSWORDDIALOG_H +#endif // PASSWORDDIALOG_H_ diff --git a/progressindicator.cpp b/progressindicator.cpp deleted file mode 100644 index b3835f662..000000000 --- a/progressindicator.cpp +++ /dev/null @@ -1,116 +0,0 @@ -#include "progressindicator.h" - -#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); -} - -bool QProgressIndicator::isAnimated () const -{ - return (m_timerId != -1); -} - -void QProgressIndicator::setDisplayedWhenStopped(bool state) -{ - m_displayedWhenStopped = state; - - update(); -} - -bool QProgressIndicator::isDisplayedWhenStopped() const -{ - return m_displayedWhenStopped; -} - -void QProgressIndicator::startAnimation() -{ - m_angle = 0; - - if (m_timerId == -1) - m_timerId = startTimer(m_delay); -} - -void QProgressIndicator::stopAnimation() -{ - if (m_timerId != -1) - killTimer(m_timerId); - - m_timerId = -1; - - update(); -} - -void QProgressIndicator::setAnimationDelay(int delay) -{ - if (m_timerId != -1) - killTimer(m_timerId); - - m_delay = delay; - - if (m_timerId != -1) - m_timerId = startTimer(m_delay); -} - -void QProgressIndicator::setColor(const QColor & color) -{ - m_color = color; - - update(); -} - -QSize QProgressIndicator::sizeHint() const -{ - return QSize(20,20); -} - -int QProgressIndicator::heightForWidth(int w) const -{ - return w; -} - -void QProgressIndicator::timerEvent(QTimerEvent * /*event*/) -{ - m_angle = (m_angle+30)%360; - - 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(); - } -} diff --git a/progressindicator.h b/progressindicator.h deleted file mode 100644 index 65d80f768..000000000 --- a/progressindicator.h +++ /dev/null @@ -1,87 +0,0 @@ -#ifndef QPROGRESSINDICATOR_H -#define QPROGRESSINDICATOR_H - -#include -#include - -/*! - \class QProgressIndicator - \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 - 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); - - /*! 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 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; } - - virtual QSize sizeHint() const; - int heightForWidth(int w) const; -public slots: - /*! Starts the spin animation. - \sa stopAnimation isAnimated - */ - void startAnimation(); - - /*! 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 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); -protected: - 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; -}; - -#endif // QPROGRESSINDICATOR_H diff --git a/qprogressindicator.cpp b/qprogressindicator.cpp new file mode 100644 index 000000000..f00b084cd --- /dev/null +++ b/qprogressindicator.cpp @@ -0,0 +1,94 @@ +#include "qprogressindicator.h" +#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); +} + +bool QProgressIndicator::isAnimated() const { return m_timerId != -1; } + +void QProgressIndicator::setDisplayedWhenStopped(bool state) { + m_displayedWhenStopped = state; + + update(); +} + +bool QProgressIndicator::isDisplayedWhenStopped() const { + return m_displayedWhenStopped; +} + +void QProgressIndicator::startAnimation() { + m_angle = 0; + + if (m_timerId == -1) + m_timerId = startTimer(m_delay); +} + +void QProgressIndicator::stopAnimation() { + if (m_timerId != -1) + killTimer(m_timerId); + + m_timerId = -1; + + update(); +} + +void QProgressIndicator::setAnimationDelay(int delay) { + if (m_timerId != -1) + killTimer(m_timerId); + + m_delay = delay; + + if (m_timerId != -1) + m_timerId = startTimer(m_delay); +} + +void QProgressIndicator::setColor(const QColor &color) { + m_color = color; + + update(); +} + +QSize QProgressIndicator::sizeHint() const { return QSize(20, 20); } + +int QProgressIndicator::heightForWidth(int w) const { return w; } + +void QProgressIndicator::timerEvent(QTimerEvent * /*event*/) { + m_angle = (m_angle + 30) % 360; + + 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(); + } +} diff --git a/qprogressindicator.h b/qprogressindicator.h new file mode 100644 index 000000000..980ebd7de --- /dev/null +++ b/qprogressindicator.h @@ -0,0 +1,99 @@ +#ifndef QPROGRESSINDICATOR_H_ +#define QPROGRESSINDICATOR_H_ + +#include +#include + +/*! + \class QProgressIndicator + \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 + 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: + explicit 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 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 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 + */ + void startAnimation(); + + /*! 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 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); + + protected: + 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; +}; + +#endif // QPROGRESSINDICATOR_H_ 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..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 \ @@ -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/singleapplication.cpp b/singleapplication.cpp index 8573a8cce..d72a61694 100644 --- a/singleapplication.cpp +++ b/singleapplication.cpp @@ -1,6 +1,5 @@ -#include - #include "singleapplication.h" +#include /** * @brief SingleApplication::SingleApplication @@ -8,25 +7,26 @@ * @param argv * @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); - } +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); + } } // public slots. @@ -34,18 +34,16 @@ SingleApplication::SingleApplication(int &argc, char *argv[], const QString uniq /** * @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. @@ -53,33 +51,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 966dc95c5..ad642446a 100644 --- a/singleapplication.h +++ b/singleapplication.h @@ -1,31 +1,30 @@ -#ifndef SINGLE_APPLICATION_H -#define SINGLE_APPLICATION_H +#ifndef SINGLEAPPLICATION_H_ +#define SINGLEAPPLICATION_H_ #include #include #include -class SingleApplication : public QApplication -{ - Q_OBJECT -public: - SingleApplication(int &argc, char *argv[], const QString uniqueKey); +class SingleApplication : public QApplication { + Q_OBJECT + public: + 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(); -public slots: - void receiveMessage(); + signals: + void messageAvailable(QString message); -signals: - void messageAvailable(QString message); + private: + bool _isRunning; + QString _uniqueKey; + QSharedMemory sharedMemory; + QScopedPointer localServer; -private: - bool _isRunning; - QString _uniqueKey; - QSharedMemory sharedMemory; - QScopedPointer localServer; - - static const int timeout = 1000; + static const int timeout = 1000; }; -#endif // SINGLE_APPLICATION_H + +#endif // SINGLEAPPLICATION_H_ diff --git a/storemodel.cpp b/storemodel.cpp index 3738236f7..ada0540eb 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 @@ -16,10 +14,9 @@ StoreModel::StoreModel() * @return */ bool StoreModel::filterAcceptsRow(int sourceRow, - const QModelIndex &sourceParent) const -{ - QModelIndex index = sourceModel()->index(sourceRow, 0, sourceParent); - return ShowThis(index); + const QModelIndex &sourceParent) const { + QModelIndex index = sourceModel()->index(sourceRow, 0, sourceParent); + return ShowThis(index); } /** @@ -27,38 +24,28 @@ bool StoreModel::filterAcceptsRow(int sourceRow, * @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; } /** @@ -66,9 +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; } /** @@ -77,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..c489c0e83 100644 --- a/storemodel.h +++ b/storemodel.h @@ -1,24 +1,23 @@ -#ifndef STOREMODEL_H -#define STOREMODEL_H +#ifndef STOREMODEL_H_ +#define STOREMODEL_H_ #include #include #include -class StoreModel : public QSortFilterProxyModel -{ - Q_OBJECT -private: - QFileSystemModel* fs; - QString store; +class StoreModel : public QSortFilterProxyModel { + Q_OBJECT + private: + QFileSystemModel *fs; + QString store; -public: - StoreModel(); + public: + 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 +#endif // STOREMODEL_H_ diff --git a/trayicon.cpp b/trayicon.cpp index 8dace210c..f7cf76563 100644 --- a/trayicon.cpp +++ b/trayicon.cpp @@ -1,7 +1,6 @@ #include "trayicon.h" -trayIcon::trayIcon(QMainWindow *parent) -{ +TrayIcon::TrayIcon(QMainWindow *parent) { parentwin = parent; createActions(); @@ -11,74 +10,64 @@ trayIcon::trayIcon(QMainWindow *parent) 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) { +void TrayIcon::setVisible(bool visible) { + if (visible == true) parentwin->show(); - } else { + 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())); } - -void trayIcon::createTrayIcon() -{ +void TrayIcon::createTrayIcon() { trayIconMenu = new QMenu(this); -// trayIconMenu->addAction(minimizeAction); -// trayIconMenu->addAction(maximizeAction); -// trayIconMenu->addAction(restoreAction); -// trayIconMenu->addSeparator(); + // 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) { +void TrayIcon::showHideParent() { + if (parentwin->isVisible() == true) parentwin->hide(); - } else { + 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 b8ea411d3..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 @@ -8,32 +8,32 @@ #include #include -class trayIcon : public QWidget -{ - Q_OBJECT -public: - explicit trayIcon(QMainWindow *parent); - void showMessage(QString title, QString msg, int time); - void setVisible(bool visible); +class TrayIcon : public QWidget { + Q_OBJECT -signals: + public: + explicit TrayIcon(QMainWindow *parent); + void showMessage(QString title, QString msg, int time); + void setVisible(bool visible); -public slots: - void showHideParent(); - void iconActivated(QSystemTrayIcon::ActivationReason reason); + signals: -private: - void createActions(); - void createTrayIcon(); + public slots: + void showHideParent(); + void iconActivated(QSystemTrayIcon::ActivationReason reason); -// QAction *minimizeAction; -// QAction *maximizeAction; - QAction *settingsAction; - QAction *quitAction; + private: + void createActions(); + void createTrayIcon(); - QSystemTrayIcon *sysTrayIcon; - QMenu *trayIconMenu; - QMainWindow *parentwin; + // QAction *minimizeAction; + // QAction *maximizeAction; + QAction *settingsAction; + QAction *quitAction; + + QSystemTrayIcon *sysTrayIcon; + QMenu *trayIconMenu; + QMainWindow *parentwin; }; -#endif // TRAYICON_H +#endif // TRAYICON_H_ diff --git a/usersdialog.cpp b/usersdialog.cpp index ffc4d9962..424524ec0 100644 --- a/usersdialog.cpp +++ b/usersdialog.cpp @@ -1,103 +1,96 @@ #include "usersdialog.h" -#include "ui_usersdialog.h" #include #include +#include "ui_usersdialog.h" -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(); + // TODO(annejan) 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 5f3793be6..23eb9c7e4 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 @@ -14,38 +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 *); + public: + explicit UsersDialog(QWidget *parent = 0); + ~UsersDialog(); + void setUsers(QList *); -protected: - void closeEvent(QCloseEvent *event); + protected: + void closeEvent(QCloseEvent *event); -private slots: - void itemChange(QListWidgetItem *); - void on_clearButton_clicked(); - void on_lineEdit_textChanged(const QString &filter); - void on_checkBox_clicked(); + private slots: + void itemChange(QListWidgetItem *item); + 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); + private: + Ui::UsersDialog *ui; + QList *userList; + void populateList(const QString &filter); }; -#endif // USERSDIALOG_H +#endif // USERSDIALOG_H_ diff --git a/util.cpp b/util.cpp index 218c61a62..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 @@ -14,44 +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"); - - 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); + // TODO(annejan) 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); #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,52 +59,48 @@ QString Util::findPasswordStore() * @return */ QString Util::normalizeFolderPath(QString path) { - if (!path.endsWith("/") && !path.endsWith(QDir::separator())) { - path += QDir::separator(); - } - return 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; } /** @@ -115,22 +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..e3ec61bc6 100644 --- a/util.h +++ b/util.h @@ -1,22 +1,22 @@ -#ifndef UTIL_H -#define UTIL_H +#ifndef UTIL_H_ +#define UTIL_H_ #include #include -class Util -{ -public: - static QString findBinaryInPath(QString); - static QString findPasswordStore(); - static QString normalizeFolderPath(QString); - static bool checkConfig(QString, QString, QString); - static void qSleep(int); +class Util { + public: + static QString findBinaryInPath(QString binary); + static QString findPasswordStore(); + static QString normalizeFolderPath(QString path); + static bool checkConfig(QString passStore, QString passExecutable, + QString gpgExecutable); + static void qSleep(int ms); -private: - static void initialiseEnvironment(); - static QProcessEnvironment _env; - static bool _envInitialised; + private: + static void initialiseEnvironment(); + static QProcessEnvironment _env; + static bool _envInitialised; }; -#endif // UTIL_H +#endif // UTIL_H_